6 typedef struct Dict Dict;
7 typedef struct Piece Piece;
8 typedef struct File File;
9 typedef struct Stats Stats;
13 char typ; // i, d, s, l
52 char *deftrack = "http://exodus.desync.com/announce";
53 char *mntweb = "/mnt/web";
80 bparse(char *s, char *e, Dict **dp)
102 s = bparse(s, e, dp);
106 d = *dp = mallocz(sizeof(*d), 1);
110 s = bparse(s, e, &d->val);
121 if((s = memchr(x, 'e', e - x)) == nil)
127 if((x = memchr(s, ':', e - s)) == nil)
130 if((n = atoi(s)) < 0)
133 if((s > e) || (s < x)){
139 d = mallocz(sizeof(*d) + n+1, 1);
141 memmove(d->str, x, d->len = n);
150 if(d && (d->typ == 's' || d->typ == 'i'))
156 dlook(Dict *d, char *s)
158 for(; d && d->typ == 'd'; d = d->next)
159 if(d->len && strcmp(d->str, s) == 0)
165 readall(int fd, char **p)
171 while(*p = realloc(*p, n+1024)){
172 if((r = read(fd, *p+n, 1024)) <= 0)
180 rwpiece(int wr, int index, uchar *data, int len, int poff)
186 if(len <= 0 || poff >= pieces[index].len)
188 if(len+poff > pieces[index].len)
189 len = pieces[index].len - poff;
190 off = (vlong)index * blocksize;
192 for(f = files; f; f = f->next)
193 if((f->off+f->len) > off)
196 n = ((off + len) > f->len) ? f->len - off : len;
197 if((n = (wr ? pwrite(f->fd, data, n, off) : pread(f->fd, data, n, off))) <= 0)
199 if((m = rwpiece(wr, index, data + n, len - n, poff + n)) < 0)
207 uchar *p, m, hash[20];
211 if(havemap[x>>3] & m)
213 p = malloc(blocksize);
215 if(rwpiece(0, x, p, n, 0) != n){
219 sha1(p, n, hash, nil);
221 if(memcmp(hash, pieces[x].hash, 20))
224 if((havemap[x>>3] & m) == 0){
227 stats.left -= pieces[x].len;
234 pickpiece(uchar *map)
241 for(i = 0; i<nhavemap; i++){
244 for(x = i<<3, m = 0x80; m; m >>= 1, x++){
245 if((~map[i] | havemap[i]) & m)
255 unpack(uchar *s, int n, char *fmt, ...)
269 if(s+1 > e) goto Err;
270 *va_arg(arg, int*) = *s++;
273 if(s+4 > e) goto Err;
274 *va_arg(arg, int*) = s[0]<<24 | s[1]<<16 | s[2]<<8 | s[3];
287 pack(uchar *s, int n, char *fmt, ...)
302 i = va_arg(arg, int);
304 if(s+1 > e) goto Err;
308 i = va_arg(arg, int);
309 if(s+4 > e) goto Err;
310 *s++ = (i>>24) & 0xFF;
311 *s++ = (i>>16) & 0xFF;
312 *s++ = (i>>8) & 0xFF;
316 i = va_arg(arg, int);
317 if(s+i > e) goto Err;
318 memmove(s, va_arg(arg, uchar*), i);
333 peer(int fd, int incoming, char *addr)
335 uchar buf[64+MAXIO], *map, *told, *p, m;
336 int mechoking, hechoking;
341 if(debug) fprint(2, "peer %s: %s connected\n", addr, incoming ? "incoming" : "outgoing");
344 if((incoming && i) || (!incoming && !i)){
345 if(debug) fprint(2, "peer %s: -> handshake\n", addr);
346 n = pack(buf, sizeof(buf), "*________**",
347 20, "\x13BitTorrent protocol",
348 sizeof(infohash), infohash,
349 sizeof(peerid), peerid);
350 if(write(fd, buf, n) != n)
353 if((incoming && !i) || (!incoming && i)){
354 n = 20 + 8 + sizeof(infohash);
355 if((n = readn(fd, buf, n)) != n)
357 if(memcmp(buf, "\x13BitTorrent protocol", 20))
359 if(memcmp(infohash, buf + 20 + 8, sizeof(infohash)))
361 if(debug) fprint(2, "peer %s: <- handshake\n", addr);
364 if(readn(fd, buf, sizeof(peerid)) != sizeof(peerid))
366 if(memcmp(peerid, buf, sizeof(peerid)) == 0)
368 if(debug) fprint(2, "peer %s: peerid %.*s\n", addr, sizeof(peerid), (char*)buf);
375 map = mallocz(nhavemap, 1);
376 told = malloc(nhavemap);
378 if(debug) fprint(2, "peer %s: -> bitfield %d\n", addr, nhavemap);
379 memmove(told, havemap, nhavemap);
380 n = pack(buf, sizeof(buf), "lb*", nhavemap+1, 0x05, nhavemap, told);
381 if(write(fd, buf, n) != n)
385 for(i=0; i<nhavemap; i++){
386 if(told[i] != havemap[i]){
387 for(x = i<<3, m = 0x80; m; m >>= 1, x++){
388 if((~havemap[i] | told[i] | map[i]) & m)
391 if(debug) fprint(2, "peer %s: -> have %d\n", addr, x);
392 n = pack(buf, sizeof(buf), "lbl", 1+4, 0x04, x);
393 if(write(fd, buf, n) != n)
397 if(!mewant && (map[i] & ~havemap[i])){
399 if(debug) fprint(2, "peer %s: -> interested\n", addr);
400 n = pack(buf, sizeof(buf), "lb", 1, 0x02);
401 if(write(fd, buf, n) != n)
405 if(!hechoking && mewant){
407 if(x >= 0 && pieces[x].brk < pieces[x].len)
409 else x = pickpiece(map);
412 l = pieces[x].len - o;
415 if(debug) fprint(2, "peer %s: -> request %d %d %d\n", addr, x, o, l);
416 n = pack(buf, sizeof(buf), "lblll", 1+4+4+4, 0x06, x, o, l);
417 if(write(fd, buf, n) != n)
422 if(mechoking && hewant){
424 if(debug) fprint(2, "peer %s: -> unchoke\n", addr);
425 n = pack(buf, sizeof(buf), "lb", 1, 0x01);
426 if(write(fd, buf, n) != n)
430 if(readn(fd, buf, 4) != 4)
432 unpack(buf, 4, "l", &n);
433 if(n < 0 || n > sizeof(buf))
437 if(readn(fd, buf, n) != n)
446 if(debug) fprint(2, "peer %s: <- choke\n", addr);
448 case 0x01: // Unchoke
450 if(debug) fprint(2, "peer %s: <- unchoke\n", addr);
452 case 0x02: // Interested
454 if(debug) fprint(2, "peer %s: <- interested\n", addr);
456 case 0x03: // Notinterested
458 if(debug) fprint(2, "peer %s: <- notinterested\n", addr);
460 case 0x04: // Have <piceindex>
461 if(unpack(p, n, "l", &x) < 0)
463 if(debug) fprint(2, "peer %s: <- have %d\n", addr, x);
464 if(x < 0 || x >= npieces)
466 map[x>>3] |= 0x80>>(x&7);
468 case 0x05: // Bitfield
469 if(debug) fprint(2, "peer %s: <- bitfield %d\n", addr, n);
474 case 0x06: // Request <index> <begin> <length>
475 if(unpack(p, n, "lll", &x, &o, &l) < 0)
477 if(debug) fprint(2, "peer %s: <- request %d %d %d\n", addr, x, o, l);
478 if(x < 0 || x >= npieces)
480 if(!hewant || mechoking || (~havemap[x>>3]&(0x80>>(x&7))))
482 if(debug) fprint(2, "peer %s: -> piece %d %d\n", addr, x, o);
486 if((l = rwpiece(0, x, buf + n, l, o)) <= 0)
488 n = pack(buf, sizeof(buf), "lbll", 1+4+4+l, 0x07, x, o);
490 if(write(fd, buf, n) != n)
496 case 0x07: // Piece <index> <begin> <block>
497 if(unpack(p, n, "ll", &x, &o) != 8)
504 if(debug) fprint(2, "peer %s: <- piece %d %d %d\n", addr, x, o, n);
505 if(x < 0 || x >= npieces)
507 if((pieces[x].brk != o) || (havemap[x>>3]&(0x80>>(x&7))))
509 if(rwpiece(1, x, p, n, o) == n){
510 if((pieces[x].brk = o+n) == pieces[x].len){
516 case 0x08: // Cancel <index> <begin> <length>
517 if(unpack(p, n, "lll", &x, &o, &l) < 0)
519 if(debug) fprint(2, "peer %s: <- cancel %d %d %d\n", addr, x, o, l);
521 case 0x09: // Port <port>
522 if(unpack(p, n, "l", &x) < 0)
524 if(debug) fprint(2, "peer %s: <- port %d\n", addr, x);
538 char addr[64], adir[40], ldir[40];
543 for(port=6881; port<6890; port++){
544 snprint(addr, sizeof(addr), "tcp!*!%d", port);
545 if((afd = announce(addr, adir)) >= 0)
549 fprint(2, "announce: %r");
552 if(rfork(RFFDG|RFPROC|RFMEM))
555 if((lfd = listen(adir, ldir)) < 0){
556 fprint(2, "listen: %r");
559 if(rfork(RFFDG|RFPROC|RFMEM)){
563 if((dfd = accept(lfd, ldir)) < 0){
564 fprint(2, "accept: %r");
567 ni = getnetconninfo(ldir, dfd);
568 peer(dfd, 1, ni ? ni->raddr : "???");
569 if(ni) freenetconninfo(ni);
576 client(char *ip, char *port)
579 static QLock peerslk;
584 if(ip == nil || port == nil)
587 d = mallocz(sizeof(*d) + 64, 1);
588 snprint(addr = d->str, 64, "tcp!%s!%s", ip, port);
590 if(dlook(peers, addr)){
595 d->len = strlen(addr);
602 if(debug) fprint(2, "client %s\n", addr);
604 if(rfork(RFFDG|RFPROC|RFMEM))
606 for(try = 0; try < 10; try++){
607 if((fd = dial(addr, nil, nil, nil)) >= 0){
608 if(!peer(fd, 0, addr))
612 sleep((1000<<try)+nrand(5000));
618 hopen(char *url, ...)
620 int conn, ctlfd, fd, n;
624 snprint(buf, sizeof buf, "%s/clone", mntweb);
625 if((ctlfd = open(buf, ORDWR)) < 0)
627 if((n = read(ctlfd, buf, sizeof buf-1)) <= 0){
635 n = 4+vsnprint(buf+4, sizeof(buf)-4, url, arg);
637 if(write(ctlfd, buf, n) != n){
642 snprint(buf, sizeof buf, "%s/%d/body", mntweb, conn);
643 if((fd = open(buf, OREAD)) < 0)
652 static Dict *trackers;
653 static QLock trackerslk;
663 if(dlook(trackers, url)){
664 qunlock(&trackerslk);
668 d = mallocz(sizeof(*d) + n+1, 1);
676 qunlock(&trackerslk);
678 if(debug) fprint(2, "tracker %s\n", url);
680 if(rfork(RFPROC|RFMEM))
683 event = "&event=started";
685 vlong up, down, left;
694 if((fd = hopen("%s?info_hash=%.*H&peer_id=%.*H&port=%d&"
695 "uploaded=%lld&downloaded=%lld&left=%lld&compact=1&no_peer_id=1%s",
696 url, sizeof(infohash), infohash, sizeof(peerid), peerid, port,
697 up, down, left, event)) >= 0){
703 } else if(debug) fprint(2, "tracker %s: %r\n", url);
704 if(l = dlook(d, "peers")){
710 for(; b+6 <= e; b += 6){
711 char ip[16], port[6];
713 snprint(ip, sizeof(ip), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
714 snprint(port, sizeof(port), "%d", b[4]<<8 | b[5]);
717 } else for(; l && l->typ == 'l'; l = l->next)
718 client(dstr(dlook(l->val, "ip")), dstr(dlook(l->val, "port")));
721 if(p = dstr(dlook(d, "interval")))
723 if(n < 10 | n > 60*60)
726 sleep(n * 1000 + nrand(5000));
734 s = va_arg(f->args, uchar*);
735 if(f->flags & FmtPrec)
738 e = s + strlen((char*)s);
740 if(fmtprint(f, *s && ((*s >= '0' && *s <= '9') ||
741 (*s >= 'a' && *s <= 'z') ||
742 (*s >= 'A' && *s <= 'Z') ||
743 strchr(".-_~", *s)) ? "%c" : "%%%.2x", *s) < 0)
749 mktorrent(int fd, char *url)
755 if((d = dirfstat(fd)) == nil)
757 if(d->qid.type == QTDIR){
759 werrstr("file is a directory");
764 werrstr("empty file");
768 for(blocksize = 256*1024;;blocksize<<=1){
769 npieces = (d->length + blocksize-1) / blocksize;
770 if(npieces <= 8*1024 || blocksize >= 2*1024*1024)
774 print("8:announce%ld:%s", strlen(url), url);
777 print("4:name%ld:%s", strlen(d->name), d->name);
778 print("6:lengthi%llde", d->length);
779 print("12:piece lengthi%de", blocksize);
780 print("6:pieces%d:", npieces*sizeof(h));
782 b = malloc(blocksize);
783 while((n = readn(fd, b, blocksize)) > 0){
785 if(write(1, h, sizeof(h)) != sizeof(h)){
793 werrstr("read failed: %r");
807 if(access(s, AEXIST) == 0)
809 for(p=strchr(s+1, '/'); p; p=strchr(p+1, '/')){
811 if(access(s, AEXIST)){
812 if((f = create(s, OREAD, DMDIR | 0777)) < 0){
834 s += chartorune(&r, s);
837 if((n + runelen(r)) >= l){
841 n += runetochar(d + n, &r);
848 killnote(void *, char *)
850 postnote(PNGROUP, killgroup, "kill");
857 fprint(2, "usage: %s [ -vsdpc ] [ -m mtpt ] [ -t url ] [ file ]\n", argv0);
862 main(int argc, char *argv[])
864 int sflag, pflag, vflag, cflag, fd, i, n;
865 Dict *info, *torrent, *d;
866 char *p, *s, *e, *url;
870 fmtinstall('H', Hfmt);
872 sflag = pflag = vflag = cflag = 0;
875 mntweb = EARGF(usage());
878 url = EARGF(usage());
901 if((fd = open(*argv, OREAD)) < 0)
902 sysfatal("open: %r");
906 if(mktorrent(fd, url) < 0)
910 if((n = readall(fd, &p)) <= 0)
911 sysfatal("read torrent: %r");
912 bparse(p, p+n, &torrent);
913 if((d = info = dlook(torrent, "info")) == nil)
914 sysfatal("no meta info in torrent");
915 for(s = e = d->start; d && d->typ == 'd'; d = d->next)
917 sha1((uchar*)s, e - s, (uchar*)infohash, nil);
921 if(d = dlook(info, "files")){
922 for(; d && d->typ == 'l'; d = d->next){
925 if((s = dstr(dlook(d->val, "length"))) == nil)
927 f = mallocz(sizeof(*f), 1);
929 f->name = dstr(dlook(info, "name"));
930 for(di = dlook(d->val, "path"); di && di->typ == 'l'; di = di->next)
931 if(s = dstr(di->val))
932 f->name = f->name ? smprint("%s/%s", f->name, s) : s;
936 } else if(s = dstr(dlook(info, "length"))){
937 f = mallocz(sizeof(*f), 1);
939 f->name = dstr(dlook(info, "name"));
943 for(f = files; f; f = f->next){
944 if(f->name == nil || f->len <= 0)
945 sysfatal("bogus file entry in meta info");
946 f->name = fixnamedup(f->name);
947 if(vflag) fprint(pflag ? 2 : 1, "%s\n", f->name);
948 if((f->fd = open(f->name, ORDWR)) < 0){
949 if(mkdirs(f->name) < 0)
950 sysfatal("mkdirs: %r");
951 if((f->fd = create(f->name, ORDWR, 0666)) < 0)
952 sysfatal("create: %r");
958 sysfatal("no files in torrent");
960 if((s = dstr(dlook(info, "piece length"))) == nil)
961 sysfatal("missing piece length in meta info");
962 if((blocksize = atoi(s)) <= 0)
963 sysfatal("bogus piece length in meta info");
964 d = dlook(info, "pieces");
965 if(d == nil || d->typ != 's' || d->len <= 0 || d->len % 20)
966 sysfatal("bad or no pices in meta info");
967 npieces = d->len / 20;
968 pieces = mallocz(sizeof(Piece) * npieces, 1);
969 nhavemap = (npieces+7) / 8;
970 havemap = mallocz(nhavemap, 1);
971 for(i = 0; i<npieces; i++){
972 pieces[i].hash = (uchar*)d->str + i*20;
976 pieces[i].len = blocksize;
977 len -= pieces[i].len;
978 stats.left += pieces[i].len;
981 sysfatal("pieces do not match file length");
983 for(i = 0; i<npieces; i++)
987 atnotify(killnote, 1);
988 switch(i = rfork(RFPROC|RFMEM|RFNOTEG)){
990 sysfatal("fork: %r");
992 memmove(peerid, "-NF9001-", 8);
993 for(i=8; i<sizeof(peerid); i++)
994 peerid[i] = nrand(10)+'0';
997 tracker(dstr(dlook(torrent, "announce")));
998 for(d = dlook(torrent, "announce-list"); d && d->typ == 'l'; d = d->next)
999 if(d->val && d->val->typ == 'l')
1000 tracker(dstr(d->val->val));
1001 while(waitpid() != -1)
1006 while((nhavepieces < npieces) || sflag){
1008 print("%d %d\n", nhavepieces, npieces);
1012 postnote(PNGROUP, killgroup, "kill");