BitTorrent is a protocol for distributing files. It identifies content by URL and is designed to integrate seamlessly with the web. Its advantage over plain HTTP is that when multiple downloads of the same file happen concurrently, the downloaders upload to each other, making it possible For The File Source To Support Very Large Numbers of Downloaders with Only A Modest Increase In Its Load.
A BitTorrent File Distribution Consists of these Entities:
An ORDINARY Web Server A Static 'MetaInfo' File A Bittorrent Tracker An 'Original' Downloader The End User Web Browsers The End User Downloaders
There is Ideally Many End Uses for a Single File.
To Start Serving, A Host Goes THROUGH The FOLLOWING STEPS:
Start running a tracker (or, more likely, have one running already). Start running an ordinary web server, such as apache, or have one already. Associate the extension .torrent with mimetype application / x-bittorrent on their web server (or have done so already). Generate a metainfo (.torrent) file using the complete file to be served and the URL of the tracker. Put the metainfo file on the web server. Link to the metainfo (.torrent) file from some other web Page. Start a Downloader Which Already Has The Complete File (The 'Origin').
To Start Downloading, A User Does The Following:
Install BitTorrent (or have done so already). Surf the web. Click on a link to a .torrent file. Select where to save the file locally, or select a partial download to resume. Wait for download to complete. Tell downloader to exit (IT Keeps Uploading Until this Happens).
The Connectivity Is as Follows:
The web site is serving up static files as normal, but kicking off the BitTorrent helper app on the clients. The tracker is receiving information from all downloaders and giving them random lists of peers. This is done over HTTP or HTTPS. Downloaders are periodically checking in with the tracker to keep it informed of their progress, and are uploading to and downloading from each other via direct connections. These connections use the BitTorrent peer protocol, which operates over TCP. The origin is uploading but not downloading at all, since it has the entire file. The origin is necessary to get the entire file into the network. Often for popular downloads the origin can be taken down after a while since several downloads may have completed and been left running indefinitely.Metainfo file and tracker responses are both Sent In A Simple, Effectient, And Extensible Format Called Bencoding (PRONOUNCED 'BEE ENCODING'). BENCODED Messages Are Nested Dictionaries and Lists (As in Python), WHIC H CAN Contain Strings and Integers. EXTENSIBILITY IS Supported by ignoring unExpected Dictionary Keys, SO Additional Optional Ons Can Be Added Later.
Bencoding is Done as Follows:
Strings are length-prefixed base ten followed by a colon and the string For example 4:. Spam corresponds to 'spam' Integers are represented by an 'i' followed by the number in base 10 followed by an 'e' For example.. i3e corresponds to 3 and i3e corresponds to -3. Integers have no size limitation. i0e is invalid. All encodings with a leading zero, such as i03e, are invalid, other than i0e, which of course corresponds to 0. Lists are encoded as an 'l' followed by their elements (also bencoded) followed by an 'e' For example l4:. spam4: eggse corresponds to [ 'spam', 'eggs'] Dictionaries are encoded as a 'd'. followed by a list of alternating keys and their corresponding values followed by an 'e' For example, d3:. cow3: moo4: spam4: eggse corresponds to { 'cow': 'moo', 'spam': 'eggs'} and d4: spaml1: a1: bee corresponds to { 'spam': [ 'a', 'b']}. Keys must be strings and appear in sorted order (sorted as raw strings, not alphanumerics) .Metainfo files are bencoded dictionaries with The Following Key S:
Announce
The Url of the Tracker.
Info
This Maps to a Dictionary, with keys described Below.
The name key maps to a string which is the sugester name to save the file (or directory) as. It is purely advisory.
piece length maps to the number of bytes in each piece the file is split into. For the purposes of transfer, files are split into fixed-size pieces which are all the same length except for possibly the last one which may be truncated. Piece length IS Almost Always a Power of TWO, MOST Commonly 218 = 256 k (Bittorrent Prior To Version 3.2 Uses 220 = 1 m as default).
pieces maps to a string whose length is a multiple of 20. It is to be subdivided into strings of length 20, each of which is the SHA1 hash of the piece at the corresponding index.There is also a key length or a key files, But not Both or neither. If Length Is Present The Download Represents a Single File, OtherWise IT Repesents A Set of Files Which Go In A Directory Structure.
In The Single File Case, Length Maps to The Length of The File in bytes.
For the purposes of the other keys, the multi-file case is treated as only having a single file by concatenating the files in the order they appear in the files list. The files list is the value files maps to, and is a list of Dictionaries Containing The Following Keys:
Length
The Length of the file, in bytes.
Path
A List of strings Corresponding to Subdirectory Names, The Last of Which Is The Actual File Name (a zero length list is an error case).
In The Single File Case, The Name Key Is The Name of A File, In The Muliple File Case, It's The Name of a Directory.
Tracker queries are two way. The tracker receives information via HTTP GET parameters and returns a bencoded message. Note that although the current tracker implementation has its own web server, the tracker could run very nicely as, for example, an apache module.
Tracker Get Requests Have The Following Keys:
INFO_HASH
................ .י.................................................
Peer_id
A String of Length 20 Which this Downloader Uses As ITS ID. Each Downloader Genereates ITS OWN ID AT Random At The Start of a New Download. This value will also almost ceert have to be escaped.ip
An OPTIONAL Parameter Giving The IP (or DNS Name) Which this peer is at. Generally Used for the Origin if it's on the same machine as the tracker.
port
The Port Number this Peer Is Listening on. Common Behavior Is for a Downloader To try to listen on port 6881 and if That port is taken try 6882, the 6883, etc. And give up after 6889.
Uploaded
The Total Amount Uploaded So Far, Encoded In Base Ten ASCII.
Downloaded
The Total Amount Downloaded So Far, Encode In Base Ten ASCII.
Left
The number of bytes this peer still has to download, encoded in base ten ascii. Note that this can not be computed from downloaded and the file length since it might be a resume, and there's a chance that some of the downloaded data failed an Integrity Check and Had to Be Re-Downloaded.
Event
This is an optional key which maps to started, completed, or stopped (or empty, which is the same as not being present). If not present, this is one of the announcements done at regular intervals. An announcement using started is sent when a download first begins, and one using completed is sent when the download is complete. No completed is sent if the file was complete when started. downloaders send an announcement using 'stopped' when they cease downloading.
Tracker responses are bencoded dictionaries If a tracker response has a key failure reason, then that maps to a human readable string which explains why the query failed, and no other keys are required Otherwise, it must have two keys:.. Interval, which maps to the number of seconds the downloader should wait between regular rerequests, and peers. peers maps to a list of dictionaries corresponding to peers, each of which contains the keys peer id, ip, and port, which map to the peer's self-selected ID , IP address or dns name as a string, and port number, respectively. Note that downloaders may rerequest on nonscheduled times if an event happens or they need more peers.If you want to make any extensions to metainfo files or tracker queries, please coordinate WITH BRAM Cohen to make Sure That All Extensions Are Done Compatibly.
BitTorrent's Peer Protocol Operates over TCP. It Performs EfficIntly without setting annousting.
Peer Connections Are Symmetrical. Messages Sent In Both Directions Look The Same, And Data Can Flow IN Either Direction.
The peer protocol refers to pieces of the file by index as described in the metainfo file, starting at zero. When a peer finishes downloading a piece and checks that the hash matches, it announces that it has that piece to all of its peers.
Connections contain two bits of state on either end: choked or not, and interested or not Choking is a notification that no data will be sent until unchoking happens The reasoning and common techniques behind choking are explained later in this document...
. Data transfer takes place whenever one side is interested and the other side is not choking Interest state must be kept up to date at all times - whenever a downloader does not have something they currently would ask a peer for in unchoked, they must express lack of interest, despite being choked. Implementing this properly is tricky, but makes it possible for downloaders to know which peers will start downloading immediately if unchoked.Connections start out choked and not interested.
When data is being transferred, downloaders should keep several piece requests queued up at once in order to get good TCP performance (this is called 'pipelining'.) On the other side, requests which can not be written out to the TCP buffer immediately SHOULD BE Queued Up in Memory Rather Than Kept In Aplication-Level Network Buffer
The peer wire protocol consists of a handshake followed by a never-ending stream of length-prefixed messages. The handshake starts with character ninteen (decimal) followed by the string 'BitTorrent protocol'. The leading character is a length prefix, put there in ..................
All Later Integers Sent In The Protocol Are Encoded As FourTes Big-endian.
After the fixed headers come eight reserved bytes, which are all zero in all current implementations. If you wish to extend the protocol using these bytes, please coordinate with Bram Cohen to make sure all extensions are done compatibly.
Next comes the 20 byte sha1 hash of the bencoded form of the info value from the metainfo file. (This is the same value which is announced as info_hash to the tracker, only here it's raw instead of quoted here). If both sides don ' t send the same value, they sever the connection. The one possible exception is if a downloader wants to do multiple downloads over a single port, they may wait for incoming connections to give a download hash first, and respond with the same one if it's in their list.After the download hash comes the 20-byte peer id which is reported in tracker requests and contained in peer lists in tracker responses. If the receiving side's peer id does not match the one the initiating side expects, it severs the CONNECTION.
That's it for handshaking, next comes an alternating stream of length prefixes and messages. Messages of length zero are keepalives, and ignored. Keepalives are generally sent once every two minutes, but note that timeouts can be done much more quickly when data is expected.
All Non-Keepalive Messages Start with a single. The Possible Values Are:
0 - choke 1 - UNCHOKE 2 - INTERESTED 3 - Not Interested 4 - Have 5 - Bitfield 6 - Request 7 - Piece 8 - Cancel
'choke', 'unchoke', 'INTERESTED', AND 'NOT INTERESTED' HAVE No Payload.
'Bitfield' is only ever sent as the first message. Its payload is a bitfield with each index that downloader has sent set to one and the rest set to zero. Downloaders which do not have anything yet may skip the 'bitfield' message. The first byte of the bitfield corresponds to indices 0 -. 7 from high bit to low bit, respectively The next one 8-15, etc. Spare bits at the end are set to zero.The 'have' message's payload is a single number .
'Request' messages contain an index, begin, and length. The last two are byte offsets. Length is generally a power of two unless it gets truncated by the end of the file. All current implementations use 215, and close connections which request an Amount Greater Than 217.
'Cancel' messages have the same payload as request messages. They are generally only sent towards the end of a download, during what's called 'endgame mode'. When a download is almost complete, there's a tendency for the last few pieces to all be downloaded off a single hosed modem line, taking a very long time. to make sure the last few pieces come in quickly, once requests for all pieces a given downloader does not have yet are currently pending, it sends requests for everything to everyone it's Downloading from. To Keep this from Becoming Horribly INEFFICIENT, IT Sends Cancels To Everyone else Every Time a Piece Arrives.
'Piece' messages contain an index, begin, and piece. Note that they are correlated with request messages implicitly. It's possible for an unexpected piece to arrive if choke and unchoke messages are sent in quick succession and / or transfer is going very slowly. ............. ..
Choking is done for several reasons. TCP congestion control behaves very poorly when sending over many connections at once. Also, choking lets each peer use a tit-for-tat-ish algorithm to ensure that they get a consistent download rate.
The choking algorithm described below is the currently deployed one. It is very important that all new algorithms work well both in a network consisting entirely of themselves and in a network consisting mostly of this one.
There are several criteria a good choking algorithm should meet. It should cap the number of simultaneous uploads for good TCP performance. It should avoid choking and unchoking quickly, known as 'fibrillation'. It should reciprocate to peers who let it download. Finally, IT SHOULD TRY OUSED CONNECTIONS ONCE IN A While To Find Out Iw Might Be Better Than THE CURRENTLY Used Ones, known as Optimistic UNCHOKING.
The currently deployed choking algorithm avoids fibrillation by only changing who's choked once every ten seconds. It does reciprocation and number of uploads capping by unchoking the four peers which it has the best download rates from and are interested. Peers which have a better upload rate but are not interested get unchoked and if they become interested the worst uploader gets choked. If a downloader has a complete file, it uses its upload rate rather than its download rate to decide who to unchoke.For optimistic unchoking, at any one time there is a single peer which is unchoked regardless of it's upload rate (if interested, it counts as one of the four allowed downloaders.) Which peer is optimistically unchoked rotates every 30 seconds. to give them a decent chance of getting a complete piece to upload New Connections Are Three Times As LIKELY to Start As The Current Optimistic UNCHOKE AS Anywhere Else In The Rotation.