tlibeech.c - libeech - bittorrent library
 (HTM) git clone git://z3bra.org/libeech.git
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) README
 (DIR) LICENSE
       ---
       tlibeech.c (26359B)
       ---
            1 /* See LICENSE file for copyright and license details. */
            2 #include <errno.h>
            3 #include <fcntl.h>
            4 #include <limits.h>
            5 #include <netdb.h>
            6 #include <poll.h>
            7 #include <stdint.h>
            8 #include <stdio.h>
            9 #include <stdlib.h>
           10 #include <string.h>
           11 #include <time.h>
           12 #include <unistd.h>
           13 
           14 #include <sys/types.h>
           15 #include <sys/stat.h>
           16 #include <sys/mman.h>
           17 #include <sys/socket.h>
           18 #include <netinet/in.h>
           19 
           20 #include "be.h"
           21 #include "sha1.h"
           22 #include "util.h"
           23 #include "libeech.h"
           24 
           25 /* Cast a 4 byte array as a 32 bit integer */
           26 #define U32(s) (((uint32_t *)(s))[0])
           27 
           28 /* Associate message types with their numerical value */
           29 enum {
           30         CHOKE = 0,
           31         UNCHOKE,
           32         INTERESTED,
           33         UNINTERESTED,
           34         HAVE,
           35         BITFIELD,
           36         REQUEST,
           37         PIECE,
           38         CANCEL,
           39         HANDSHAKE
           40 };
           41 
           42 struct peerfds {
           43         struct peer **p;
           44         struct pollfd *fds;
           45 };
           46 
           47 /* helpers to deal with bitfields */
           48 static int bit(char *, long);
           49 static char *setbit(char *, long);
           50 static char *clrbit(char *, long);
           51 
           52 /* helpers to retrieve attributes from metadata */
           53 static char * peerid();
           54 static long torrentsize(struct torrent *);
           55 static long torrentfiles(struct torrent *);
           56 static int chktorrent(struct be *);
           57 
           58 /* manage a list of peers */
           59 static struct peer * addpeer(struct peer *, struct peer *, char *, int);
           60 static struct peer * getpeer(struct peer *, char *, int);
           61 static struct peer * delpeer(struct peer *, struct peer *);
           62 static int peercnt(struct peer *);
           63 
           64 /* verify handshake validity */
           65 static int hsck(struct torrent *, char *, long);
           66 
           67 /* helpers to deal with pieces/blocks */
           68 static long readpiece(struct torrent *, struct piece *, long);
           69 static long writepiece(struct torrent *, struct piece *);
           70 static int chkpiece(struct torrent *, struct piece *, long);
           71 
           72 /* handle peer wire protocol (PWP) messages */
           73 static ssize_t pwprecv(struct peer *);
           74 static ssize_t pwpsend(struct peer *, char *, size_t);
           75 
           76 /* send different PWP messages */
           77 static ssize_t send_handshake(struct torrent *, struct peer *);
           78 static ssize_t send_state(struct peer *, int);
           79 static ssize_t send_have(struct peer *, long);
           80 static ssize_t send_bitfield(struct torrent *, struct peer *);
           81 static ssize_t send_request(struct torrent *, struct peer *);
           82 static ssize_t send_piece(struct torrent *, struct peer *, size_t, size_t, size_t);
           83 static ssize_t send_cancel(struct torrent *, struct peer *);
           84 
           85 /* callbacks for received PWP messages */
           86 static int cb_handshake(struct torrent *, struct peer *);
           87 static int cb_state(struct peer *, int);
           88 static int cb_have(struct peer *, size_t, char *);
           89 static int cb_bitfield(struct peer *, size_t, char *);
           90 static int cb_request(struct torrent *, struct peer *, size_t, char *);
           91 static int cb_piece(struct torrent *, struct peer *, size_t, char *);
           92 
           93 /* various wrappers around PWP messages */
           94 static int catchup(struct torrent *, struct peer *);
           95 static int cancelrq(struct torrent *, struct peer *);
           96 
           97 /* handle all received PWP messages */
           98 static int callbacks(struct torrent *, struct peer *, int, size_t, char *);
           99 
          100 /* functions to run when a peer can receive or has sent bytes over the wire */
          101 static int pwptx(struct torrent *, struct peer *);
          102 static int pwprx(struct torrent *, struct peer *);
          103 
          104 /* p2p network management */
          105 static int p2p_connect(char *, int);
          106 static int p2p_poll(struct torrent *, int);
          107 
          108 
          109 /* check wether a specific bit is set or not in a byte */
          110 int
          111 bit(char *bits, long off)
          112 {
          113         return !!(bits[off / 8] & (1 << (7 - off%8)));
          114 }
          115 
          116 /* set a bit in a byte to one */
          117 char *
          118 setbit(char *bits, long off)
          119 {
          120         bits[off / 8] |= (1 << (7 - off%8));
          121         return bits;
          122 }
          123 
          124 /* set a bit in a byte to zero */
          125 char *
          126 clrbit(char *bits, long off)
          127 {
          128         bits[off / sizeof(*bits)] &= ~(1 << (7 - off%8));
          129         return bits;
          130 }
          131 
          132 /* generate a random peer ID */
          133 char *
          134 peerid()
          135 {
          136         int n;
          137         char hex[40], hash[20];
          138         static char id[21] = "-GT0000-XXXXXXXXXXXX";
          139 
          140         srand(time(NULL)); /* good-enough seed */
          141         n = rand();
          142         snprintf(hex, 40, "%08x%08x\n", n, ~n);
          143         sha1(hex, 16, hash);
          144         memcpy(id + 8, tohex(hash, hex, 12), 12);
          145 
          146         return id;
          147 }
          148 
          149 /* Calculate full torrent size */
          150 long
          151 torrentsize(struct torrent *t)
          152 {
          153         int i;
          154         long l, sz = 0;
          155         struct be file;
          156 
          157         if (!bekv(&t->info, "files", 5, &file)) {
          158                 for (i = 0; !belistnext(&file) && !belistover(&file); i++) {
          159                         l = bekint(&file, "length", 6);
          160                         if (l < 0)
          161                                 return -1;
          162                         sz += l;
          163                 }
          164         } else {
          165                 sz = bekint(&t->info, "length", 6);
          166                 if (sz < 0)
          167                         return -1;
          168         }
          169 
          170         return sz;
          171 }
          172 
          173 /*
          174  * Read file(s) from torrent file, and store their path/size in a struct
          175  *
          176  * TODO: Remove this function entirely, and create helpers to fetch
          177  * these info directly from the torrent file.
          178  * torrent->files would thus be a `struct be` pointing to either "file"
          179  * or "files" attribute in the torrent, removing one more malloc()
          180  * in the library.
          181  */
          182 long
          183 torrentfiles(struct torrent *t)
          184 {
          185         int i;
          186         long n = 0;
          187         char basedir[PATH_MAX], *sp;
          188         struct be file, tmp;
          189 
          190         bekstr(&t->info, "name", 4, &tmp);
          191         memset(basedir, 0, PATH_MAX);
          192         memcpy(basedir, tmp.off, tmp.end - tmp.off);
          193 
          194         /* multi-file torrent */
          195         if (!bekv(&t->info, "files", 5, &file)) {
          196                 t->files = NULL;
          197                 belist(&file, (unsigned long *)&n);
          198                 t->files = malloc(sizeof(*t->files) * n);
          199                 if (!t->files)
          200                         return -1;
          201 
          202                 for (i = 0; !belistnext(&file) && !belistover(&file); i++) {
          203                         /* save file length */
          204                         t->files[i].sz = bekint(&file, "length", 6);
          205 
          206                         /* save file path */
          207                         sp = t->files[i].path;
          208                         memcpy(t->files[i].path, basedir, PATH_MAX);
          209                         bekv(&file, "path", 4, &tmp);
          210                         bepath(&tmp, &sp, PATH_MAX);
          211                 }
          212                 n = i;
          213         /* single-file torrent */
          214         } else {
          215                 n = 1;
          216                 t->files = malloc(sizeof(*t->files));
          217                 t->files[0].sz = bekint(&t->info, "length", 6);
          218                 memcpy(t->files[0].path, basedir, PATH_MAX);
          219         }
          220 
          221         return n;
          222 }
          223 
          224 /* Verify that all mandatory keys of a torrent are present */
          225 int
          226 chktorrent(struct be *b)
          227 {
          228         struct be i;
          229         struct be f;
          230 
          231         if (bekv(b, "announce", 8, NULL) < 0) {
          232                 printf("Missing key: %s\n", "announce");
          233                 return -1;
          234         }
          235         if (bekv(b, "info", 4, &i) < 0) {
          236                 printf("Missing key: info\n");
          237                 return -1;
          238         }
          239         if (bekv(&i, "name", 4, NULL) < 0) {
          240                 printf("Missing key: name\n");
          241                 return -1;
          242         }
          243         if (bekv(&i, "pieces", 6, NULL) < 0) {
          244                 printf("Missing key: pieces\n");
          245                 return -1;
          246         }
          247         if (bekv(&i, "piece length", 12, NULL) < 0) {
          248                 printf("piece Missing key: length\n");
          249                 return -1;
          250         }
          251 
          252         if (!bekv(&i, "files", 5, &f)) {
          253                 while(!belistnext(&f) && !belistover(&f)) {
          254                         if (bekv(&f, "path", 4, NULL) < 0) {
          255                                 printf("piece Missing files/path\n");
          256                                 return -1;
          257                         }
          258                         if (bekv(&f, "length", 6, NULL) < 0) {
          259                                 printf("piece Missing files/length\n");
          260                                 return -1;
          261                         }
          262                 }
          263         } else {
          264                 if (bekv(&i, "length", 6, NULL) < 0) {
          265                         printf("Missing key: length\n");
          266                         return -1;
          267                 }
          268         }
          269 
          270         return 0;
          271 }
          272 
          273 /* read a piece from a metafile (named after the SHA1 infohash) */
          274 long
          275 readpiece(struct torrent *t, struct piece *p, long n)
          276 {
          277         char hex[41];
          278         size_t off;
          279         FILE *f = NULL;
          280 
          281         /* last piece might be truncated, so recalculate it*/
          282         p->sz = (n == t->npiece - 1) ? t->sz % t->psz : t->psz;
          283 
          284         /* Calculate file offset for this piece */
          285         off = t->psz * n;
          286 
          287         f = fopen(tohex(t->ih, hex, 20), "r");
          288         if (!f)
          289                 return -1;
          290 
          291         fseek(f, off, SEEK_SET);
          292         fread(p->blks, 1, p->sz, f);
          293         fclose(f);
          294 
          295         return p->sz;
          296 }
          297 
          298 /* write a piece to a metafile (named after the SHA1 infohash) */
          299 long
          300 writepiece(struct torrent *t, struct piece *p)
          301 {
          302         int fd;
          303         char *addr, hex[41];
          304         size_t off;
          305         struct stat sb;
          306 
          307         off = p->n * t->psz;
          308 
          309         tohex(t->ih, hex, 20);
          310         if ((fd = open(hex, O_RDWR|O_CREAT, 0644)) < 0) {
          311                 perror(hex);
          312                 return -1;
          313         }
          314 
          315         if (!stat(hex, &sb) && (size_t)sb.st_size < off + p->sz)
          316                 ftruncate(fd, off + p->sz);
          317 
          318         addr = mmap(0, off + p->sz, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
          319         if (addr == MAP_FAILED) {
          320                 perror("mmap");
          321                 close(fd);
          322                 return -1;
          323         }
          324 
          325         memcpy(addr + off, p->blks, p->sz);
          326         munmap(addr, off + p->sz);
          327         close(fd);
          328 
          329         return 0;
          330 }
          331 
          332 /* Verify that a piece matches its SHA1 hash */
          333 int
          334 chkpiece(struct torrent *t, struct piece *p, long n)
          335 {
          336         char hash[20];
          337         sha1(p->blks, p->sz, hash);
          338 
          339         return memcmp(t->ph + n*20, hash, 20);
          340 }
          341 
          342 /* Initialize a peer and add it to the peer list */
          343 struct peer *
          344 addpeer(struct peer *pl, struct peer *p, char *host, int port)
          345 {
          346         p->fd = -1;
          347         p->state = 0;
          348         p->next = pl;
          349         p->port = port;
          350         p->rxbufsz = 0;
          351         p->piece.n = -1;
          352         memcpy(p->host, host, HOST_NAME_MAX);
          353         memset(p->bf, 0, PCENUM / 8 + !!(PCENUM % 8));
          354         memset(p->rxbuf, 0, MSGSIZ);
          355 
          356         return p;
          357 }
          358 
          359 /* Find a peer by its host + port */
          360 struct peer *
          361 getpeer(struct peer *pl, char *host, int port)
          362 {
          363         struct peer *p;
          364 
          365         for (p = pl; p; p = p->next) {
          366                 if (p->port == port && !strncmp(p->host, host, HOST_NAME_MAX))
          367                         return p;
          368         }
          369         return NULL;
          370 }
          371 
          372 /*
          373  * Remove a peer from the struct
          374  *
          375  * TODO: Do not free() the peer to delete, and return a pointer to
          376  * it instead.
          377  * Memory tracking of those peers is on the caller responsibility.
          378  */
          379 struct peer *
          380 delpeer(struct peer *pl, struct peer *p)
          381 {
          382         struct peer *tmp;
          383 
          384         if (p == pl) {
          385                 pl = pl->next;
          386         } else {
          387                 for (tmp = pl; tmp->next == p; tmp = tmp->next);
          388                 tmp->next = p->next;
          389         }
          390 
          391         free(p);
          392         return pl;
          393 }
          394 
          395 /* Count the number of peers currently added to this torrent */
          396 int
          397 peercnt(struct peer *pl)
          398 {
          399         return (pl ? 1 + peercnt(pl->next) : 0);
          400 }
          401 
          402 
          403 /*
          404  * PWP (Peer Wire Protocol) message management
          405  *
          406  * Standard PWP messages: [LENGTH][TYPE][PAYLOAD]
          407  * >  A PWP message has the following structure:
          408  * >
          409  * > -----------------------------------------
          410  * > | Message Length | Message ID | Payload |
          411  * > -----------------------------------------
          412  *
          413  * Message Length: 4 bytes bigendian; size is (ID + payload)
          414  * Message ID is a single byte
          415  * Payload is variable and is length - 1
          416  */
          417 
          418 /*
          419  * Wrapper to the recv() syscall to bufferize input. The received message
          420  * content and size is stored in the peer's buffer.
          421  * Until the read bytes count matches the expected message length,
          422  * we keep reading from socket on each call.
          423  *
          424  * The function returns the numbers of bytes missing in the message,
          425  * or -1 in case of errors.
          426  * When it returns 0, it means the message is fully read and can be
          427  * parsed.
          428  *
          429  * Expected message length depends on the context. Until the peer's
          430  * handshake is received, expected length will be the one of a full
          431  * handshake: fixed to 68 bytes in BTP/1.0.
          432  *
          433  * After handshake is received (status available in the peer's struct),
          434  * we peek 4 bytes from the PWP message, to retrieve its length.
          435  * Once we have it, we read this amount of bytes + 4 (the initial size)
          436  * from the socket.  Reading bytes is done in a buffer tied to the peer,
          437  * so that if we cannot read the whole message yet, the remaining parts
          438  * will be read on the next iteration.
          439  */
          440 ssize_t
          441 pwprecv(struct peer *p)
          442 {
          443         ssize_t l, r;
          444 
          445         /* defaults to handshake length */
          446         l = 68;
          447 
          448         /*
          449          * handshake is received, treat incoming bytes as a standard
          450          * PWP message
          451          */
          452         if (p->state & HANDSHAKERCVD) {
          453                 /* peek at first 4 bytes and compute full message length */
          454                 if (!p->rxbufsz && (r = recv(p->fd, p->rxbuf, 4, MSG_PEEK)) < 4)
          455                         return -1;
          456 
          457                 l = ntohl(U32(p->rxbuf)) + 4;
          458         }
          459 
          460         if (l > MSGSIZ || l < 5)
          461                 return -1;
          462 
          463         while ((r = recv(p->fd, p->rxbuf + p->rxbufsz, l - p->rxbufsz, 0)) > 0)
          464                 p->rxbufsz += r;
          465 
          466         if (r < 0 && errno != EAGAIN)
          467                 return -1;
          468 
          469         return l - p->rxbufsz;
          470 }
          471 
          472 /*
          473  * Wrapper to the send() syscall. It will loop to send the full message,
          474  * until everything is sent, or an error occurs.
          475  */
          476 ssize_t
          477 pwpsend(struct peer *p, char *m, size_t sz)
          478 {
          479         size_t s = 0;
          480         ssize_t r = 0;
          481 
          482         while (s < sz) {
          483                 r = send(p->fd, m + s, sz - s, MSG_NOSIGNAL);
          484                 if (r < 0 && errno != EAGAIN)
          485                         return -1;
          486                 if (r > 0)
          487                         s += r;
          488         }
          489 
          490         return s;
          491 }
          492 
          493 
          494 /* Verify that a handshake is valid according to a torrent */
          495 int
          496 hsck(struct torrent *t, char *hs, long l)
          497 {
          498         if (l != 68)
          499                 return -1;
          500         if (hs[0] != 19)
          501                 return -1;
          502         if (memcmp(hs+1, "BitTorrent protocol", 19))
          503                 return -1;
          504         if (memcmp(hs+28, t->ih, 20))
          505                 return -1;
          506         if (!memcmp(hs+48, t->id, 20))
          507                 return -1;
          508 
          509         return 0;
          510 }
          511 
          512 /*
          513  * Create and send a handshake message. From the Bittorrent spec:
          514  *
          515  * > A handshake is a string of bytes with the following structure:
          516  * >
          517  * > ----------------------------------------------------------------
          518  * > | Name Length | Protocol Name | Reserved | Info Hash | Peer ID |
          519  * > ----------------------------------------------------------------
          520  *
          521  * Name length: size of the "Protocol Name" attribute
          522  * Protocol name: "Bittorrent protocol", as of BitTorrent Protocol revision 1.33 (BTP/1.0)
          523  * Reserved: Used to list supported extensions to the protocol
          524  * Info hash: SHA1 hash of the full "info" key from the torrent
          525  * Peer ID: Our own ID, used for identification (or not at all)
          526  */
          527 ssize_t
          528 send_handshake(struct torrent *t, struct peer *p)
          529 {
          530         char m[68];
          531 
          532         m[0] = 19;
          533         memcpy(m + 1, "BitTorrent protocol", 19);
          534         memset(m + 20, 0, 8);
          535         memcpy(m + 28, t->ih, 20);
          536         memcpy(m + 48, t->id, 20);
          537 
          538         return pwpsend(p, m, 68);
          539 }
          540 
          541 /*
          542  * Send a change of status PWP message.
          543  * These messages have no payload and can be sent the same way.
          544  *
          545  *         0: CHOKE
          546  *         1: UNCHOKE
          547  *         2: INTERESTED
          548  *         3: UNINTERESTED
          549  *
          550  */
          551 ssize_t
          552 send_state(struct peer *p, int t)
          553 {
          554         char m[MSGSIZ];
          555 
          556         memset(m, 0, 5);
          557 
          558         /* Message length */
          559         m[3] = 1;
          560 
          561         /* Message type */
          562         m[4] = t;
          563 
          564         return pwpsend(p, m, 5);
          565 }
          566 
          567 /* Send a HAVE PWP message */
          568 ssize_t
          569 send_have(struct peer *p, long n)
          570 {
          571         char m[MSGSIZ];
          572 
          573         memset(m, 0, 5);
          574 
          575         /* Message length */
          576         U32(m) = htonl(5);
          577 
          578         /* Message type */
          579         m[4] = HAVE;
          580 
          581         /* Piece number */
          582         U32(m+5) = htonl(n);
          583 
          584         return pwpsend(p, m, 9);
          585 }
          586 
          587 /*
          588  * Send a BITFIELD message with our full bitfield (no cheating with HAVE
          589  * messages here)
          590  */
          591 ssize_t
          592 send_bitfield(struct torrent *t, struct peer *p)
          593 {
          594         char m[MSGSIZ];
          595         ssize_t l;
          596 
          597         l = t->npiece / 8 + !!(t->npiece % 8);
          598 
          599         memset(m, 0, l + 5);
          600 
          601         /* Message length */
          602         U32(m) = htonl(l + 1);
          603 
          604         /* Message type */
          605         m[4] = BITFIELD;
          606 
          607         /* Bitfield */
          608         memcpy(m+5, t->bf, l);
          609         memcpy(p->view, t->bf, l);
          610 
          611         return pwpsend(p, m, l + 5);
          612 }
          613 
          614 /*
          615  * Send a REQUEST PWP message for all blocks in a piece.
          616  *
          617  * We request only once piece at a time to a peer. The piece currently
          618  * being requested is saved in the peer struct. A piece number of -1
          619  * means that the peer is not requesting any piece.
          620  * A piece number of t->npiece means that no piece can be requested to
          621  * the peer (no new piece available).
          622  *
          623  * The function will send a REQUEST messages for all the blocks in the
          624  * piece, then return.
          625  *
          626  * TODO: Implement a function to select a piece from different algorithms
          627  */
          628 ssize_t
          629 send_request(struct torrent *t, struct peer *p)
          630 {
          631         char m[MSGSIZ];
          632         ssize_t i, bl, bo;
          633 
          634         /* Find a missing piece we can get from the peer */
          635         if (p->piece.n < 0) {
          636                 for (i = 0; i < t->npiece && (bit(t->bf, i) || !bit(p->bf, i)); i++);
          637                 memset(p->piece.bl, 0, sizeof(p->piece.bl));
          638                 memset(p->piece.rq, 0, sizeof(p->piece.rq));
          639 
          640                 if (i == t->npiece)
          641                         return -1;
          642 
          643                 p->piece.n = i;
          644                 p->piece.sz = (i == t->npiece - 1) ? t->sz % t->psz : t->psz;
          645         }
          646 
          647         /* Find a block that hasn't been requested yet */
          648         for (i = 0; i < BLKNUM && bit(p->piece.rq, i); i++);
          649 
          650         bo = i * BLKSIZ;
          651         bl = BLKSIZ;
          652         if (bo + BLKSIZ > p->piece.sz)
          653                 bl = p->piece.sz - bo;
          654 
          655         /* All blocks requested */
          656         if (bo >= p->piece.sz)
          657                 return -1;
          658 
          659 
          660         memset(m, 0, MSGSIZ);
          661 
          662         /* Message length */
          663         U32(m) = htonl(13);
          664 
          665         /* Message type */
          666         m[4] = REQUEST;
          667 
          668         /* Piece index */
          669         U32(m+5) = htonl(p->piece.n);
          670 
          671         /* Block offset */
          672         U32(m+9) = htonl(bo);
          673 
          674         /* Block length */
          675         U32(m+13) = htonl(bl);
          676 
          677         pwpsend(p, m, 17);
          678 
          679         setbit(p->piece.rq, i);
          680 
          681         return 0;
          682 }
          683 
          684 ssize_t
          685 send_piece(struct torrent *t, struct peer *p, size_t i, size_t bl, size_t bo)
          686 {
          687         char m[MSGSIZ];
          688         struct piece piece;
          689 
          690         if (readpiece(t, &piece, i) < 0)
          691                 return -1;
          692 
          693         if (bo + bl > (size_t)piece.sz)
          694                 return -1;
          695 
          696         memset(m, 0, MSGSIZ);
          697 
          698         /* Message length */
          699         U32(m) = htonl(bl + 9);
          700 
          701         /* Message type */
          702         m[4] = PIECE;
          703 
          704         /* Piece index */
          705         U32(m+5) = htonl(i);
          706 
          707         /* Block offset */
          708         U32(m+9) = htonl(bo);
          709 
          710         /* Block length */
          711         U32(m+13) = htonl(bl);
          712 
          713         pwpsend(p, m, bl + 9);
          714 
          715         return 0;
          716 }
          717 
          718 ssize_t
          719 send_cancel(struct torrent *t, struct peer *p)
          720 {
          721         char m[MSGSIZ];
          722         ssize_t i, bl, bo;
          723 
          724         /* We're not requesting anything from peer */
          725         if (p->piece.n < 0)
          726                 return 0;
          727 
          728         /* Find a block that hasn't been requested yet */
          729         for (i = 0; i < BLKNUM && bit(p->piece.rq, i); i++) {
          730 
          731                 /* We currently don't have the requested block */
          732                 if (!bit(p->piece.bl, i))
          733                         continue;
          734 
          735                 bo = i * BLKSIZ;
          736                 bl = BLKSIZ;
          737                 if (bo + BLKSIZ > p->piece.sz)
          738                         bl = p->piece.sz - bo;
          739 
          740                 /* All blocks requested */
          741                 if (bo >= p->piece.sz)
          742                         return -1;
          743 
          744                 memset(m, 0, MSGSIZ);
          745 
          746                 /* Message length */
          747                 U32(m) = htonl(13);
          748 
          749                 /* Message type */
          750                 m[4] = CANCEL;
          751 
          752                 /* Piece index */
          753                 U32(m+5) = htonl(p->piece.n);
          754 
          755                 /* Block offset */
          756                 U32(m+9) = htonl(bo);
          757 
          758                 /* Block length */
          759                 U32(m+13) = htonl(bl);
          760 
          761                 pwpsend(p, m, 17);
          762         }
          763 
          764         return 0;
          765 }
          766 
          767 /* Receive and treat a change of status from the peer */
          768 int
          769 cb_state(struct peer *p, int type)
          770 {
          771         switch (type) {
          772         case CHOKE:
          773                 p->state |= AMCHOKING;
          774                 break;
          775         case UNCHOKE:
          776                 p->state &= ~AMCHOKING;
          777                 break;
          778         case INTERESTED:
          779                 p->state |= ISINTERESTED;
          780                 break;
          781         case UNINTERESTED:
          782                 p->state &= ~ISINTERESTED;
          783                 break;
          784         }
          785         return 0;
          786 }
          787 
          788 /* Receive and treat a HAVE message from the peer */
          789 int
          790 cb_have(struct peer *p, size_t sz, char *pl)
          791 {
          792         if (sz != 4)
          793                 return -1;
          794 
          795         setbit(p->bf, ntohl(U32(pl)));
          796         return 0;
          797 }
          798 
          799 /* Receive and save the BITFIELD sent by a peer */
          800 int
          801 cb_bitfield(struct peer *p, size_t sz, char *pl)
          802 {
          803         memcpy(p->bf, pl, sz);
          804         return 0;
          805 }
          806 
          807 /* Receive a block REQUEST from a peer */
          808 int
          809 cb_request(struct torrent *t, struct peer *p, size_t sz, char *pl)
          810 {
          811         ssize_t i, bo, bl;
          812 
          813         /* only reply to requests if peer is interested and not choked */
          814         if (p->state & ISCHOKING)
          815                 return -1;
          816 
          817         if (!(p->state & ISINTERESTED))
          818                 return -1;
          819 
          820         i  = ntohl(U32(pl));
          821         bo = ntohl(U32(pl+4));
          822         bl = ntohl(U32(pl+8));
          823 
          824         /* exit if we don't have the piece */
          825         if (!bit(t->bf, i))
          826                 return -1;
          827 
          828         return send_piece(t, p, i, bo, bl);
          829 }
          830 
          831 /*
          832  * Receive a PIECE block from a peer
          833  *
          834  * After receiving a block, we'll verify if the piece matches its SHA1 hash.
          835  * If it does, we write the piece to a metafile named after the hexadecimal
          836  * version of the info hash.
          837  *
          838  * TODO: Keep track of received blocks, so we can discard a piece if we
          839  * receive all blocks, but the hash doesn't match what we expect.
          840  */
          841 int
          842 cb_piece(struct torrent *t, struct peer *p, size_t sz, char *pl)
          843 {
          844         int i;
          845         size_t idx, off;
          846         char *blk, bl[BLKNUM / 8 + !!(BLKNUM % 8)];
          847 
          848         idx = ntohl(U32(pl));
          849         off = ntohl(U32(pl+4));
          850         blk = pl + 8;
          851 
          852         /* calculate a full piece block bitfield, for comparison */
          853         memset(bl, 0, BLKNUM / 8 + !!(BLKNUM % 8));
          854         for (i = 0; i < (p->piece.sz / BLKSIZ + !!(p->piece.sz % BLKSIZ)); i++)
          855                 setbit(bl, i);
          856 
          857         memcpy(p->piece.blks + off, blk, sz - 8);
          858         setbit(p->piece.bl, off / BLKSIZ);
          859 
          860         /* Check piece hash and write it on disk when all blocks are received */
          861         if (!memcmp(p->piece.bl, bl, BLKNUM / 8 + !!(BLKNUM % 8))) {
          862                 if (!chkpiece(t, &p->piece, idx) && !writepiece(t, &(p->piece)))
          863                         setbit(t->bf, p->piece.n);
          864 
          865                 /* Reset piece number, no matter what */
          866                 p->piece.n = -1;
          867         }
          868 
          869         /* Save amount of bytes downloaded */
          870         t->sz += sz - 8;
          871 
          872         return 0;
          873 }
          874 
          875 int
          876 cb_handshake(struct torrent *t, struct peer *p)
          877 {
          878         if (hsck(t, p->rxbuf, p->rxbufsz) < 0) {
          879                 delpeer(t->peers, p);
          880                 return -1;
          881         }
          882 
          883         p->state |= HANDSHAKERCVD;
          884         return 0;
          885 }
          886 
          887 /*
          888  * Get a peer to catch up new pieces we had received
          889  */
          890 int
          891 catchup(struct torrent *t, struct peer *p)
          892 {
          893         long i;
          894 
          895         for (i = 0; i < t->npiece; i++) {
          896                 if (bit(t->bf, i) && !bit(p->view, i)) {
          897                         send_have(p, i);
          898                         setbit(p->view, i);
          899                 }
          900         }
          901         return 0;
          902 }
          903 
          904 /*
          905  * Sent CANCEL messages for all pieces still requested that we have
          906  */
          907 int
          908 cancelrq(struct torrent *t, struct peer *p)
          909 {
          910         if (p->piece.n >= 0 && bit(t->bf, p->piece.n))
          911                 send_cancel(t, p);
          912 
          913         return 0;
          914 }
          915 
          916 /*
          917  * PWP message received callback
          918  * This function will run the appropriate function based on the message type
          919  */
          920 int
          921 callbacks(struct torrent *t, struct peer *p, int type, size_t sz, char *pl)
          922 {
          923         switch (type) {
          924                 case CHOKE:
          925                 case UNCHOKE:
          926                 case INTERESTED:
          927                 case UNINTERESTED:
          928                         cb_state(p, type);
          929                         break;
          930                 case HAVE:
          931                         cb_have(p, sz, pl);
          932                         break;
          933                 case BITFIELD:
          934                         cb_bitfield(p, sz, pl);
          935                         break;
          936                 case REQUEST:
          937                         cb_request(t, p, sz, pl);
          938                         break;
          939                 case PIECE:
          940                         cb_piece(t, p, sz, pl);
          941                         break;
          942                 case CANCEL:
          943                         /* not handled */
          944                         break;
          945                 case HANDSHAKE:
          946                         cb_handshake(t, p);
          947                         break;
          948         }
          949         return 0;
          950 }
          951 
          952 /* Logic to send messages when peer is ready */
          953 int
          954 pwptx(struct torrent *t, struct peer *p)
          955 {
          956         /* send handshake */
          957         if (!(p->state & HANDSHAKESENT)) {
          958                 send_handshake(t, p);
          959                 send_bitfield(t, p);
          960                 p->state |= HANDSHAKESENT;
          961         }
          962 
          963         if (!(p->state & CONNECTED))
          964                 return 0;
          965 
          966         if (p->state & LEECHING) {
          967                 if (!(p->state & AMINTERESTED)) {
          968                         send_state(p, INTERESTED);
          969                         p->state |= AMINTERESTED;
          970                 }
          971 
          972                 if (!(p->state & AMCHOKING))
          973                         send_request(t, p);
          974 
          975                 if (memcmp(p->piece.rq, p->piece.bl, PCENUM / 8 + !!(PCENUM % 8)))
          976                         cancelrq(t, p);
          977         }
          978 
          979         if (p->state & SEEDING) {
          980                 /* send missing pieces as HAVE messages */
          981                 if (memcmp(t->bf, p->view, PCENUM / 8 + !!(PCENUM % 8)))
          982                         catchup(t, p);
          983 
          984                 /* unchoke all interested peers when seeding */
          985                 if (!(p->state & ISINTERESTED) && p->state & ISCHOKING) {
          986                         send_state(p, UNCHOKE);
          987                         p->state &= ~(ISCHOKING);
          988                 }
          989         }
          990 
          991         return 0;
          992 }
          993 
          994 /* Logic to receive messages when peer sent data */
          995 int
          996 pwprx(struct torrent *t, struct peer *p)
          997 {
          998         int type;
          999 
         1000         /* receive message from peer */
         1001         if (!pwprecv(p)) {
         1002                 /* assume first message to be a handshake */
         1003                 type  = (p->state & HANDSHAKERCVD) ? p->rxbuf[4] : HANDSHAKE;
         1004 
         1005                 /* run appropriate callback given message type */
         1006                 callbacks(t, p, type, p->rxbufsz - 5, p->rxbuf+5);
         1007                 memset(p->rxbuf, 0, MSGSIZ);
         1008                 p->rxbufsz = 0;
         1009                 return 0;
         1010         }
         1011 
         1012         return -1;
         1013 }
         1014 
         1015 /* Initiate connection with a peer */
         1016 int
         1017 p2p_connect(char *host, int port)
         1018 {
         1019         int fd = -1;
         1020         int flags = 0;
         1021         struct hostent *he;
         1022         struct sockaddr_in in;
         1023 
         1024         if (!(he = gethostbyname(host)))
         1025                 return -1;
         1026 
         1027         memset(&in, 0, sizeof(in));
         1028         memcpy(&in.sin_addr, he->h_addr_list[0], he->h_length);
         1029         in.sin_family = AF_INET;
         1030         in.sin_port   = htons(port);
         1031 
         1032         fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
         1033         if (fd < 0)
         1034                 return -1;
         1035 
         1036         flags = fcntl(fd, F_GETFL, 0);
         1037         fcntl(fd, F_SETFL, flags|O_NONBLOCK);
         1038 
         1039         if (connect(fd, (struct sockaddr *)&in, sizeof(in)) < 0 && errno != EINPROGRESS) {
         1040                 close(fd);
         1041                 return -1;
         1042         }
         1043 
         1044         return fd;
         1045 }
         1046 
         1047 /* Poll() all peers for read/write readiness on each iteration */
         1048 int
         1049 p2p_poll(struct torrent *t, int timeout)
         1050 {
         1051         int r, npeer = 0;
         1052         nfds_t i, nfds;
         1053         struct peer *p;
         1054         struct peerfds pfds;
         1055 
         1056         nfds = npeer = peercnt(t->peers);
         1057         if (nfds < 1)
         1058                 return -1;
         1059 
         1060         pfds.p   = malloc(nfds * sizeof(*pfds.p));
         1061         pfds.fds = malloc(nfds * sizeof(*pfds.fds));
         1062 
         1063         for (i = 0, p = t->peers; p; p = p->next) {
         1064                 if (p->fd > 0) {
         1065                         pfds.p[i] = p;
         1066                         pfds.fds[i].fd = p->fd;
         1067                         pfds.fds[i].events = POLLIN|POLLOUT|POLLERR;
         1068                         i++;
         1069                 }
         1070         }
         1071         nfds = i;
         1072 
         1073         /* poll all peers for TCP events */
         1074         if ((r = poll(pfds.fds, nfds, timeout)) < 1)
         1075                 return r;
         1076 
         1077         for (i = 0; i < nfds; i++) {
         1078                 if (pfds.fds[i].revents & POLLOUT)
         1079                         pwptx(t, pfds.p[i]);
         1080 
         1081                 if (pfds.fds[i].revents & POLLIN)
         1082                         pwprx(t, pfds.p[i]);
         1083 
         1084                 /* peer is now ready to exchange data */
         1085                 if (pfds.p[i]->state == (HANDSHAKESENT|HANDSHAKERCVD))
         1086                         pfds.p[i]->state |= (CONNECTED|LEECHING|AMCHOKING);
         1087         }
         1088 
         1089         free(pfds.p);
         1090         free(pfds.fds);
         1091 
         1092         return npeer;
         1093 }
         1094 
         1095 
         1096 /*
         1097  * Library function call
         1098  */
         1099 
         1100 /*
         1101  * Load a torrent in a torrent struct
         1102  *
         1103  * RETURN VALUE: returns 0 if the torrent is loaded, -1 otherwise
         1104  */
         1105 int
         1106 glch_loadtorrent(struct torrent *t, char *b, size_t s)
         1107 {
         1108         long i;
         1109         struct be v;
         1110         struct piece piece;
         1111 
         1112         if (beinit(&t->be, b, s) < 0)
         1113                 return -1;
         1114 
         1115         if (chktorrent(&t->be) < 0)
         1116                 return -1;
         1117 
         1118         /* Calculate 'info' key checksum */
         1119         bekv(&t->be, "info", 4, &t->info);
         1120         sha1(t->info.start, t->info.end - t->info.start, t->ih);
         1121 
         1122         /* save tracker URL */
         1123         bekstr(&t->be, "announce", 8, &v);
         1124         memcpy(t->tr, v.off, v.end - v.off);
         1125 
         1126         /* Generate randomized peer ID */
         1127         memcpy(t->id, peerid(), 20);
         1128         t->id[20] = 0;
         1129 
         1130         t->ul = 0;
         1131         t->dl = 0;
         1132         t->sz = torrentsize(t);
         1133         t->nfile = torrentfiles(t);
         1134         t->peers = NULL;
         1135 
         1136         /* pieces related values */
         1137         t->psz = bekint(&t->info, "piece length", 12);
         1138         t->npiece = t->sz / t->psz + !!(t->sz % t->psz);
         1139         bekstr(&t->info, "pieces", 6, &v);
         1140         memcpy(t->ph, v.off, v.end - v.off);
         1141         memset(t->bf, 0, PCENUM / 8);
         1142 
         1143         for (i = 0; i < t->npiece; i++) {
         1144                 if (readpiece(t, &piece, i) > 0 && !chkpiece(t, &piece, i))
         1145                         setbit(t->bf, i);
         1146         }
         1147 
         1148         return 1;
         1149 }
         1150 
         1151 /*
         1152  * Connect to a remote peer
         1153  *
         1154  * RETURN VALUE: returns 0 if connection is established, -1 otherwise
         1155  */
         1156 int
         1157 glch_addpeer(struct torrent *t, struct peer *p, char *host, int port)
         1158 {
         1159         /* ignore request if peer already exists */
         1160         if (getpeer(t->peers, host, port))
         1161                 return 0;
         1162 
         1163         addpeer(t->peers, p, host, port);
         1164         p->fd = p2p_connect(p->host, p->port);
         1165         if (!p || p->fd < 0) {
         1166                 free(p);
         1167                 return -1;
         1168         }
         1169 
         1170         t->peers = p;
         1171 
         1172         return 0;
         1173 }
         1174 
         1175 /*
         1176  * bind on a local port to listen for incoming connections
         1177  * 
         1178  * RETURN VALUE: the socket fd on successful bind, -1 otherwise
         1179  */
         1180 int
         1181 glch_bind(char *host, int port)
         1182 {
         1183         int fd;
         1184         struct in_addr *h;
         1185         struct sockaddr_in s;
         1186 
         1187         if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
         1188                 return -1;
         1189 
         1190         h = getinetaddr(host);
         1191 
         1192         memset(&s, 0, sizeof(s));
         1193         s.sin_family = AF_INET;
         1194         s.sin_addr.s_addr = h->s_addr;
         1195         s.sin_port = htons(port);
         1196 
         1197         if (bind(fd, (struct sockaddr *)&s, sizeof(s)) < 0)
         1198                 return -1;
         1199 
         1200         if (listen(fd, 10) < 0)
         1201                 return -1;
         1202 
         1203         return fd;
         1204 }
         1205 
         1206 /*
         1207  * Perform one network iteration with all the peers, or timeout if
         1208  * no one replies
         1209  */
         1210 int
         1211 glch_leech(struct torrent *t, int timeout)
         1212 {
         1213         return p2p_poll(t, timeout);
         1214 }
         1215 
         1216 /* Return the number of currently downloaded pieces */
         1217 long
         1218 glch_piececount(struct torrent *t)
         1219 {
         1220         long i, n;
         1221         for (i = n = 0; i < t->npiece; i++)
         1222                 n += bit(t->bf, i);
         1223 
         1224         return n;
         1225 }