BitTorrent protocol specification

Source: Internet
Author: User
Tags sha1 sha1 hash

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 are ideally else end users for a single file.

To start serving, a host goes through the following steps:

  1. Start running a tracker (or, more likely, have one running already ).
  2. Start running an ordinary web server, such as Apache, or have one already.
  3. Associate the extension.torrentWith mimetypeapplication/x-bittorrentOn their Web Server (or have done so already ).
  4. Generate a metainfo (. torrent) file using the complete file to be served and the URL of the tracker.
  5. Put the metainfo file on the Web server.
  6. Link to the metainfo (. torrent) file from some other web page.
  7. Start a downloader which already has the complete file (the 'origin ').

To start downloading, a user does the following:

  1. Install BitTorrent (or have done so already ).
  2. Surf the web.
  3. Click on a link to a. torrent file.
  4. Select where to save the file locally, or select a partial download to resume.
  5. Wait for download to complete.
  6. 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 processing ing 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, efficient, and extensible format called bencoding (pronounced 'bee encoding '). bencoded messages are nested dictionaries and lists (as in Python), which can contain strings and integers. extensibility
Is supported by ignoring unexpected dictionary keys, so additional optional ones 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:spamCorresponds to 'spam '.
  • Integers are represented by an 'I 'followed by the number in base 10 followed by an 'e'. For example
    i3eCorresponds to 3 andi-3eCorresponds to-3. integers have no size limitation.
    i-0eIs invalid. All encodings with a leading zero, suchi03e, Are invalid, other
    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:eggseCorresponds 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:eggseCorresponds to {'cow': 'moo', 'spam': 'eggs '} and
    d4:spaml1:a1:beeCorresponds 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 keys:

announce

The URL of the tracker.

info

This maps to a dictionary, with keys described below.

ThenameKey Maps to a string which is the suggested name to save the file (or directory) as. It is purely advisory.

piece lengthMaps to the number of bytes in each piece the file is split. for the purposes of transfer, files are split into fixed-size pieces which are all the same length limit t 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 ).

piecesMaps 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 keylengthOr a keyfiles, But not both or neither. If
lengthIs present then the download represents a single file, otherwise it represents a set of files which go in a directory structure.

In the single file case,lengthMaps 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
filesMaps 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,nameKey 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 has es information via http get parameters and returns a bencoded message. note that although the current tracker implementation has its own web server, the tracker cocould run very nicely as, for example, an Apache
Module.

Tracker GET requests have the following keys:

info_hash

The 20 byte sha1 hash of the bencoded form ofinfoValue from the metainfo file. Note that this is a substring of the metainfo file. This value will almost certainly have to be escaped.

peer_id

A string of length 20 which This downloader uses as its ID. Each downloader generates its own ID at random at the start of a new download. This value will also almost certainly 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, then 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, encoded in base ten ASCII.

left

The number of bytes this peer still has to download, encoded in base ten ASCII. note that this can't 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 mapsstarted,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
startedIs sent when a download first begins, and one usingcompletedIs sent when the download is complete. No
completedIs 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 shoshould wait between regular reRequests, and
peers.peersMaps to a list of dictionaries corresponding to peers, each of which contains the keys
peer id,ip, Andport, 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 efficiently without setting any socket options.

Peer connections are supported rical. 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 doesn' t have something they currently wocould 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 shoshould 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't be written out to the TCP buffer immediately shoshould
Be queued up in memory rather than kept in an application-level network buffer, so they can all be thrown out when a choke happens.

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 the hope that other new protocols may do the same and thus be trivially distinguishable from each other.

All later integers sent in the Protocol are encoded as four bytes 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 ofinfoValue 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
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 processing side's peer id doesn't 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 byte which gives their type. 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 don't 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, the index which that downloader just completed and checked the hash.

'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 doesn't 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.

Downloaders generally download pieces in random order, which does a reasonably good job of keeping them from having a strict subset or superset of the pieces of any of their peers.

Choking is done for several reasons. TCP congestion control behaves very poorly when sending over many ons 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 showould meet. it shoshould cap the number of simultaneous uploads for good TCP performance. it shoshould avoid choking and unchoking quickly, known as 'fig '. it shoshould reciprocate to peers who let it
Download. Finally, it shocould try out unused connections once in a while to find out if they might be better than the currently used ones, known as optimistic unchoking.

The currently deployed choking algorithm avoids maid 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 aren't 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.