in ,

Building a BitTorrent client from the ground up in Go, Hacker News

[1]

         

tl ; dr:What is the complete path between visiting thepiratebay and sublimating an mp3 file from thin air? In this post, we’ll implement enough of the BitTorrent protocol to download Debian. Look at theSource codeor skip to thelast bit.               [byteIndex] BitTorrent is a protocol for downloading and distributing files across the Internet. In contrast with the traditional client / server relationship, in which downloaders connect to a central server (for example: watching a movie on Netflix, or loading the web page you’re reading now), participants in the BitTorrent network, called peers

download pieces of files fromeach other – this is what makes it a [

1] peer-to-peer

protocol. We’ll investigate how this works, and build our own client that can find peers and exchange data between them.

The protocol evolved organically over the past 20 years, and various people and organizations added extensions for features like encryption, private torrents, and new ways of finding peers. We’ll be implementing theoriginal spec from 2020 to keep this a weekend-sized project.

I’ll be using a (Debian ISOfile as my guinea pig because it’s big, but not huge, at 686 MB. As a popular Linux distribution, there will be lots of fast and cooperative peers for us to connect to. And we’ll avoid the legal and ethical issues related to downloading pirated content.

Here’s a problem: we want to download a file with BitTorrent, but it’s a peer-to-peer protocol and we have no idea where to find peers to download it from. This is a lot like moving to a new city and trying to make friends — maybe we’ll hit up a local pub or a meetup group! Centralized locations like these are the big idea behind

trackers, which are central servers that introduce peers to each other. They’re just web servers running over HTTP* Some trackers use a [0] ************************** (UDP) binary protocol to save bandwidth, and you can find Debian’s at http: //bttracker.debian.org: /

**********************************

Of course, these central servers are liable to get raided by the feds if they facilitate peers exchanging illegal content. You may remember reading about trackers like TorrentSpy, Popcorn Time, and KickassTorrents getting seized and shut down. New methods cut out the middleman by making even

peer discoveryA distributed process. We won’t be implementing them, but if you’re interested, some terms you can research are

DHT (********************, [

1] PEX, and

magnet links

.

Parsing a .torrent file (*****************************************

A .torrent file describes the contents of a torrentable file and information for connecting to a tracker. It’s all we need in order to kickstart the process of downloading a torrent. Debian’s .torrent file looks like this: (************************************** d8: announce (***********************************************************************************************************************************************************************: http: //bttracker.debian.org: / announce7 : comment (***********************************************************************************************************************************************************************: “Debian CD from cdimage.debian.org” (**********************************************************************************************************************************************************************************: creation datei e9: httpseedsl [

1pstrlen820:] ********************************************************************************************************************************: https: //cdimage.debian.org/cdimage/release/ (************************************************************************************************************************************************************************************. 2.0 // srv / cdbuilder.debian.org / dst / deb-cd / weekly-builds / amd 64 / iso-cd / debian – 2.0 -amd – netinst.iso 188: https: //cdimage.debian.org/cdimage/archive/ (2.0) srv / cdbuilder.debian.org / dst / deb-cd / weekly-builds / amd 74 / iso-cd / debian – (***************************************************************************************************************************************************************************************, 2.0-amd -netinst.isoe4: infod6: lengthi (e4: name**************************************************************************************************************************************** (debian-) **************************************************************************************************************************************************************************************, 2.0-amd 64 – netinst.iso (********************************************************************************************************************************************************************************: piece lengthi (e6: pieces) : PS ^ (binary blob of the hashes of each piece) ee

That mess is encoded in a format called (Bencode) ************************ (pronounced) ***************************** (bee-encode) ), and we'll need to decode it.

Bencode can encode roughly the same types of structures as JSON — strings, integers, lists, and dictionaries. Bencoded data is not as human-readable / writable as JSON, but it can efficiently handle binary data and it’s really simple to parse from a stream. Strings come with a length prefix, and look like

4: spam
. Integers go between

startand

end

markers, so (7) would encode to [0:4] ****************************** (i7e) ******************************************. Lists and dictionaries work in a similar way: (l4: spami7ee) represents

['spam', 7]
, whiled4: spami7ee  means  {spam: 7} (********************************************.

In a prettier format, our .torrent file looks like this: [

1]    (****************************************** (d) ************************************    8 [1:] ****************************: ***************************** (announce)      [1pstrlen820:] : http://bttracker.debian.org: / announce   7 [1:] ****************************: ******************************** (comment)      [1pstrlen820:] : “Debian CD from cdimage.debian.org”   [1pstrlen820:] ************************************************************************************************************************************************************************:creation date     i (************************************ (************************************diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationshipse   4 [1:] ****************************: ****************************** (info)      d [1:] ****************************        6 [1:] ****************************: ****************************** (length)          i (************************************ (************************************ (e)        4 [1:] ****************************: ****************************** (name)          [1pstrlen820:]debian – (****************************************************************************************************************************************************************************************************************. 2.0-amd – netinst.iso        [1pstrlen820:] ************************************************************************************************************************************************************************: piece length         i (************************************ (************************************ (e)        6 [1:] ****************************: ****************************** (pieces)          [1pstrlen820:]: ()) binary blob of the hashes of each piece)     e [1:] **************************** e [1:] **************************** (**********************************************

In this file, we can spot the URL of the tracker, the creation date (as a Unix timestamp), the name and size of the file, and a big binary blob containing the SHA-1 hashes of each

piece (*************************, which are equally-sized parts of the file we want to download. The exact size of a piece varies between torrents, but they are usually somewhere between 350 KB and 1MB. This means that a large file might be made up of

thousands of pieces. We’ll download these pieces from our peers, check them against the hashes from our torrent file, assemble them together, and boom, we’ve got a file!

******************************************diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships

This mechanism allows us to verify the integrity of each piece as we go. It makes BitTorrent resistant to accidental corruption or intentional

torrent poisoning. Unless an attacker is capable of breaking SHA-1 with a preimage attack, we will get exactly the content we asked for.

It would be really fun to write a bencode parser, but parsing isn’t our focus today. But I found Fredrik Lundh’s(line parser) to be especially illuminating. For this project, I usedgithub.com/jackpal/bencode-go(*************************: (*************************** [

1]   [1] (************************************************ (import(**************************************     “github.com/jackpal/bencode-go”(**************************************type (************************************ (bencodeInfo) (struct [1:] ************************ ({**************************************      Pieces (********************************** (string) bencode: pieces ”     PieceLength [1:] **************************** (int) bencode: piece length ”    Length (********************************** (int) bencode: length ”    Name (********************************** (string) bencode: name ”} (**************************************type (************************************ (bencodeTorrent) (struct [1:] ************************ ({**************************************     Announce [1:] **************************** (string) bencode: announce “    Info (************************************ (bencodeInfo) bencode: info ”} (**************************************// Open parses a torrent file [1:] **************************func (Open) ************************************* (diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships (r) ************************************* (io) ************************************ (**************************************************************** (Reader) ************************************diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships)[1:] **************************** [‘spam’, 7] bencodeTorrent

,(error) ************************************){{************************************)     bto (************************************:=bencodeTorrent) ************************************* {}      err [1:] **************************** (************************************:=bencode) *************************************

****************Unmarshal***********************************

************ (r) (****************************, **************************************diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships&

bto)      if (********************************** (err)!=(************************************ (nil) ************************************{        return (********************************** (nil), [1:] ************************ (err) **************************************     }     return&diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationshipsbto [1:] ,

Notably, I split (pieces) ****************************************** (previously a string) into a slice of hashes (each [20] byte [

4] so that I can easily access individual hashes later. I also computed the SHA-1 hash of the entire bencodedinfo

dict (the one which contains the name, size, and piece hashes). We know this as the

infohashand it uniquely identifies files when we talk to trackers and peers. More on this later.

************************************************ [

4] [1]   [1] (************************************************ (type(TorrentFile) ************************************* (struct) {{****************************************     Announce [1:] **************************** (string)      [1pstrlen820:] ************************ (InfoHash) ************************************[20]byte [1:] ****************************     [1pstrlen820:] ************************ (PieceHashes) ************************************[] [20]byte (**************************************      PieceLength [1:] **************************** (int)     Length (********************************** (int)     Name (********************************** (string)} (**************************************func (********************************** ()diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationshipsbto [1:] ************************ [‘spam’, 7] ************************************

bencodeTorrent) (************************************ (toTorrentFile)() (******************************** ()

* (****************************, ************************************ (TorrentFile) ************************************,*********************************** (error)) [1:] ************************ ({**************************************     … [1:] **************************}(************************************************ (***********************************************   

************************************************ view in context [

4] ****************************************** Retrieving peers from the tracker

Now that we have information about the file and its tracker, let’s talk to the tracker to

announce

our presence as a peer and to retrieve a list of other peers. We just need to make a GET request to theannounce

URL supplied in the .torrent file, with a few query parameters:

[1]   [1] (************************************************ (func) ********************************************************************** (********************************** (t) (********************************** (TorrentFile) ************************************

)buildTrackerURL((peerID) **************************************

************** [2] byte (**********************************,

port [

1:] ************************** (uint)(************************************ ()diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationshipsstring, [2] error) {     base [1:] ****************************,err [1:] ************************:=url(***********************************. **********************************

************ (Parse) (( (******************************** (t) ************************************

. (Announce) ************************************)     if (********************************** (err)!=(************************************ (nil) ************************************{        return (********************************** () “************************************), (*********************************** (err)     }      params (************************************:=url (**********************************

****************Values ​​*********************************** {************************************         “info_hash” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({string (********************************** ()(t) ************************************ [1:] **************************InfoHash********************************** [:])},         “peer_id” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({string (********************************** ()(peerID) ************************************ [1:] ************************** [offset4:offset6]},          “port” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({(strconv) **************************************

itoa) ************************************ [

1:] ************************** ([byteIndex] ****************int(************************************ (Port))},         “uploaded” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({“0”diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships},        “downloaded” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({“0”diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships},        “compact” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({(1)diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships},         “left” (**********************************:diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships[]************************************** (string) ************************************ ({(strconv) **************************************

itoa) ************************************ [

1:] ************************** ([byteIndex] ****************tdiagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships(************************************. ********************************** (Length)),     }      base [1:] ****************************(RawQuery) ************************************ [1:] ************************==********************************

params************************************. ********************************** (Encode)()    return (********************************** (base)[1:] ************************ (String) ************************************

(),(nil) *************************************} (********************************************  

************************************************** view in context

******************************************

The important ones:[

1] info_hash

: Identifies thefile

we’re trying to download. It’s the infohash we calculated earlier from the bencoded (info) dict. The tracker will use this to figure out which peers to show us.

    peer_id (**************************: A byte name to identify (ourselves) to trackers and peers. We’ll just generate 25 random bytes for this. Real BitTorrent clients have IDs like- TR - k8hj0wgej6chwhich identify the client software and version — in this case, TR (stands for Transmission client 2.) *********************************************************************************************************************************************************. ****************************************************** [

1pstrlen820:] ******************************************************** () ******************************** (Parsing the tracker response)

We get back a bencoded response:

[1]    (****************************************** (d) ************************************    8 [1:] ****************************: ****************************** (interval)      i (************************************ (************************************* e   5 [1:] ****************************: ***************************** (peers)      [1pstrlen820:] ****************************************************************************************************************************** (**************************************:(another long binary blob)e [1:] **************************** (******************************************** (**********************************************

************************************** (Interval) tells us how often we’re supposed to connect to the tracker again to refresh our list of peers. A value of means we should reconnect every (minutes) 1195 seconds).

************************************** (Peers) ******************************************** is another long binary blob containing the IP addresses of each peer. It’s made out of

groups of six bytes. The first four bytes in each group represent the peer’s IP address — each byte represents a number in the IP. The last two bytes represent the port, as a big-endian (uint) ****************************************************************************************************************************************************************************** [

1:] **********************************.Big-endian

, or

network order, means that we can interpret a group of bytes as an integer by just squishing them together left to right. For example, the bytes (0x1A (0xE1) ******************************************** make (0x1AE1) , or (in decimal.) *Interpreting the same bytes. in

little-endian

order would make 0xE A=

******************************************************** [1:] **********************[1]   [1] (************************************************// Peer encodes connection information for a peer [1:] ************************** (************************* (typePeer ************************************** (struct) {****************************************     IP [1:] **************************** (net)[1:] ********************** (IP) **************************************      Port [1:] **************************** (uint) ******************************************************************************************************************************************************************************} (**************************************// Unmarshal parses peer IP addresses and ports from a buffer [1:] **************************func

(Unmarshal) ************************************* (diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships (peersBin) ************************************* [] [byteIndex] ****************byte) (************************************ ([](Peer. [1:] **************************,(error) *************************************{{**************************************     const (********************************** (peerSize)=[1:] ************************ (6) ************************************

// 4 for IP, 2 for port [

1:] **************************numPeers(**********************************:=(************************************ (len)( (********************************** (peersBin) ************************************** [2])/ peerSize     if (********************************** (len) ( [1:] ************************ (peersBin) ***********************************

)(%) ************************************ (peerSize)!=(******************************** (0) ************************************

{         err [1:] **************************** (************************************:=(fmt) *************************************

**************** (Errorf) ************************************ (************************************

“Received malformed peers”)        return (********************************** (nil), [1:] ************************ (err) **************************************     }     peers (************************************:=make (************************************ ([] [4] ********************** (Peer) (****************************, ************************************** (numPeers))     for (********************************** (i):=(*********************************** (0) ************************************; (i) ************************************

************ (;

i( ) **********************************diagram showing the difference between client/server (all clients connecting to one server) and peer-to-peer (peers connecting to each other) relationships{         offset [1:] **************************** (************************************:=(i) *************************************

****************peerSize        peers (************************************ [i] ****************************

1:] **************************** peersBin [1][offset:offset4])        peers (************************************ [i] ****************************

1:] ************************ (

**************

peersBin************************************ [offset4:offset6]))        return (********************************** (peers), [1:] ********************** (nil) **************************************} (********************************************  

******************************************************** (view in context

******************************************

Now that we have a list of peers, it’s time to connect with them and start downloading pieces! We can break down the process into a few steps. For each peer, we want to:

(******************************************************** Start a TCP connection with the peer. This is like starting a phone call.

  • What do you think?

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    GIPHY App Key not set. Please check settings

    Isaiah Thomas 'Embarrassing Ejection Tests Limits of Wizards' Patience, Crypto Coins News

    Isaiah Thomas 'Embarrassing Ejection Tests Limits of Wizards' Patience, Crypto Coins News

    Locks, Mutexes, and Semaphores: Types of Synchronization Objects, Hacker News