torrentd

simple torrent daemon
git clone git@git.2f30.org/torrentd.git
Log | Files | Refs | LICENSE

torrentd.c (22344B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <sys/types.h>
      3 #include <sys/stat.h>
      4 #include <sys/socket.h>
      5 
      6 #include <netdb.h>
      7 #include <arpa/inet.h>
      8 #include <netinet/in.h>
      9 
     10 #include <ctype.h>
     11 #include <err.h>
     12 #include <fcntl.h>
     13 #include <setjmp.h>
     14 #include <stdarg.h>
     15 #include <stdint.h>
     16 #include <stdio.h>
     17 #include <stdlib.h>
     18 #include <string.h>
     19 #include <unistd.h>
     20 
     21 #include <curl/curl.h>
     22 
     23 #include "queue.h"
     24 #include "sha1.h"
     25 
     26 #define PORT 49155
     27 
     28 enum {
     29 	EVSTARTED,
     30 	EVCOMPLETED,
     31 	EVSTOPPED
     32 };
     33 
     34 struct buf {
     35 	char *p;
     36 	size_t n;
     37 };
     38 
     39 struct ben {
     40 	int type;
     41 	struct ben *k;
     42 	struct ben *v;
     43 	char *start, *end;
     44 	char *s;
     45 	long long i;
     46 	long long len;
     47 	struct ben *next;
     48 };
     49 
     50 struct file {
     51 	size_t len;
     52 	char *path;
     53 };
     54 
     55 struct announce {
     56 	char **urls;
     57 	size_t len;
     58 };
     59 
     60 struct peer {
     61 	char hostname[16]; /* ipv4 only */
     62 	char port[6];
     63 	int amchoking;
     64 	int aminterested;
     65 	int peerchoking;
     66 	int peerinterested;
     67 };
     68 
     69 struct torrent {
     70 	char *buf;
     71 	size_t buflen;
     72 	struct ben *ben;
     73 	struct ben *info;
     74 	struct ben *pieces;
     75 	struct announce *announcers;
     76 	size_t nannouncers;
     77 	char *filename;
     78 	struct file *files;
     79 	size_t nfiles;
     80 	size_t totallen;
     81 	uint8_t infohash[20];
     82 	long long piecelen;
     83 	long long npieces;
     84 	uint32_t *piecebm;
     85 	struct peer *peers;
     86 	size_t npeers;
     87 	size_t uploaded;
     88 	size_t downloaded;
     89 	TAILQ_ENTRY(torrent) entry;
     90 };
     91 TAILQ_HEAD(torrenthead, torrent) torrenthead;
     92 
     93 /* util functions */
     94 void *emalloc(size_t);
     95 void *ecalloc(size_t, size_t);
     96 uint32_t *newbit(int);
     97 void setbit(uint32_t *, int);
     98 void clrbit(uint32_t *, int);
     99 int tstbit(uint32_t *, int);
    100 uint8_t hex2int(int);
    101 uint8_t int2hex(int);
    102 uint8_t *hex2bin(const char *, uint8_t *, size_t);
    103 char *bin2hex(const uint8_t *, char *, size_t);
    104 void sha1sum(uint8_t *, unsigned long, uint8_t *);
    105 int readfile(char *, char **, size_t *);
    106 ssize_t writen(int, const void *, size_t);
    107 ssize_t readn(int, void *, size_t);
    108 #undef strlcpy
    109 size_t strlcpy(char *, const char *, size_t);
    110 #undef strlcat
    111 size_t strlcat(char *, const char *, size_t);
    112 void initbuf(struct buf *);
    113 void freebuf(struct buf *);
    114 size_t fillbuf(struct buf *, void *, size_t);
    115 int unpack(uint8_t *, size_t, char *, ...);
    116 int pack(uint8_t *, size_t, char *, ...);
    117 int dial(char *, char *);
    118 
    119 /* ben parsing functions */
    120 char *parse(char *, char *, struct ben **);
    121 char *bdecode(char *, char *, struct ben **);
    122 char *bstr2str(struct ben *);
    123 int bstrcmp(struct ben *, struct ben *);
    124 struct ben *dlook(struct ben *, struct ben *);
    125 struct ben *dlookstr(struct ben *, char *);
    126 void bfree(struct ben *);
    127 void bprint(struct ben *, int);
    128 
    129 /* torrent file handling */
    130 void dumptorrent(struct torrent *);
    131 struct torrent *loadtorrent(char *);
    132 void unloadtorrent(struct torrent *);
    133 int piecehash(struct torrent *, long long, uint8_t *);
    134 char *peerid(void);
    135 
    136 /* tracker related functionality */
    137 int trackerget(struct torrent *, int);
    138 
    139 /* peer handling */
    140 int parsepeers(struct torrent *, struct buf *);
    141 
    142 jmp_buf savesp;
    143 
    144 void *
    145 emalloc(size_t size)
    146 {
    147 	void *p;
    148 
    149 	p = malloc(size);
    150 	if (!p)
    151 		err(1, "malloc");
    152 	return p;
    153 }
    154 
    155 void *
    156 ecalloc(size_t n, size_t size)
    157 {
    158 	void *p;
    159 
    160 	p = calloc(n, size);
    161 	if (!p)
    162 		err(1, "calloc");
    163 	return p;
    164 }
    165 
    166 uint32_t *
    167 newbit(int n)
    168 {
    169 	return ecalloc((n + 31) / 32, 4);
    170 }
    171 
    172 void
    173 setbit(uint32_t *b, int n)
    174 {
    175 	b[n / 32] |= (1 << n);
    176 }
    177 
    178 void
    179 clrbit(uint32_t *b, int n)
    180 {
    181 	b[n / 32] &= ~(1 << n);
    182 }
    183 
    184 int
    185 tstbit(uint32_t *b, int n)
    186 {
    187 	return (b[n / 32] & (1 << n % 32)) != 0;
    188 }
    189 
    190 uint8_t
    191 hex2int(int c)
    192 {
    193 	c = toupper(c);
    194 	if (c >= '0' && c <= '9')
    195 		return c - '0';
    196 	if (c >= 'A' && c <= 'F')
    197 		return c - 'A' + 10;
    198 	errx(1, "%c is not hex", c);
    199 	return -1; /* NOTREACHED */
    200 }
    201 
    202 uint8_t
    203 int2hex(int c)
    204 {
    205 	const char *hex = "0123456789ABCDEF";
    206 	return hex[c & 0xf];
    207 }
    208 
    209 uint8_t *
    210 hex2bin(const char *h, uint8_t *b, size_t n)
    211 {
    212 	size_t i;
    213 
    214 	for (i = 0; i < n; i++)
    215 		b[i] = hex2int(h[i * 2]) << 4 | hex2int(h[i * 2 + 1]);
    216 	return b;
    217 }
    218 
    219 char *
    220 bin2hex(const uint8_t *b, char *h, size_t n)
    221 {
    222 	size_t i;
    223 
    224 	for (i = 0; i < n; i++) {
    225 		h[i * 2] = int2hex(b[i] >> 4);
    226 		h[i * 2 + 1] = int2hex(b[i]);
    227 	}
    228 	h[i * 2] = '\0';
    229 	return h;
    230 }
    231 
    232 void
    233 sha1sum(uint8_t *b, unsigned long n, uint8_t *md)
    234 {
    235 	struct sha1 ctx;
    236 
    237 	sha1_init(&ctx);
    238 	sha1_update(&ctx, b, n);
    239 	sha1_sum(&ctx, md);
    240 }
    241 
    242 int
    243 readfile(char *file, char **b, size_t *n)
    244 {
    245 	struct stat sb;
    246 	int fd;
    247 
    248 	if ((fd = open(file, O_RDONLY)) < 0)
    249 		return -1;
    250 	if (fstat(fd, &sb) < 0) {
    251 		close(fd);
    252 		return -1;
    253 	}
    254 	*b = emalloc(*n = sb.st_size);
    255 	if (read(fd, *b, *n) != (ssize_t)*n) {
    256 		free(*b);
    257 		close(fd);
    258 		return -1;
    259 	}
    260 	close(fd);
    261 	return 0;
    262 }
    263 
    264 ssize_t
    265 writen(int fd, const void *buf, size_t count)
    266 {
    267 	const char *p = buf;
    268 	ssize_t n;
    269 	size_t total = 0;
    270 
    271 	while (count > 0) {
    272 		n = write(fd, p + total, count);
    273 		if (n < 0)
    274 			err(1, "write");
    275 		else if (n == 0)
    276 			break;
    277 		total += n;
    278 		count -= n;
    279 	}
    280 	return total;
    281 }
    282 
    283 ssize_t
    284 readn(int fd, void *buf, size_t count)
    285 {
    286 	char *p = buf;
    287 	ssize_t n;
    288 	size_t total = 0;
    289 
    290 	while (count > 0) {
    291 		n = read(fd, p + total, count);
    292 		if (n < 0)
    293 			err(1, "read");
    294 		else if (n == 0)
    295 			break;
    296 		total += n;
    297 		count -= n;
    298 	}
    299 	return total;
    300 }
    301 
    302 size_t
    303 strlcpy(char *dst, const char *src, size_t dsize)
    304 {
    305 	const char *osrc = src;
    306 	size_t nleft = dsize;
    307 
    308 	/* Copy as many bytes as will fit. */
    309 	if (nleft != 0) {
    310 		while (--nleft != 0) {
    311 			if ((*dst++ = *src++) == '\0')
    312 				break;
    313 		}
    314 	}
    315 
    316 	/* Not enough room in dst, add NUL and traverse rest of src. */
    317 	if (nleft == 0) {
    318 		if (dsize != 0)
    319 			*dst = '\0';		/* NUL-terminate dst */
    320 		while (*src++)
    321 			;
    322 	}
    323 
    324 	return(src - osrc - 1);	/* count does not include NUL */
    325 }
    326 
    327 size_t
    328 strlcat(char *dst, const char *src, size_t dsize)
    329 {
    330 	const char *odst = dst;
    331 	const char *osrc = src;
    332 	size_t n = dsize;
    333 	size_t dlen;
    334 
    335 	/* Find the end of dst and adjust bytes left but don't go past end. */
    336 	while (n-- != 0 && *dst != '\0')
    337 		dst++;
    338 	dlen = dst - odst;
    339 	n = dsize - dlen;
    340 
    341 	if (n-- == 0)
    342 		return(dlen + strlen(src));
    343 	while (*src != '\0') {
    344 		if (n != 0) {
    345 			*dst++ = *src;
    346 			n--;
    347 		}
    348 		src++;
    349 	}
    350 	*dst = '\0';
    351 
    352 	return(dlen + (src - osrc));	/* count does not include NUL */
    353 }
    354 
    355 void
    356 initbuf(struct buf *b)
    357 {
    358 	memset(b, 0, sizeof(*b));
    359 }
    360 
    361 void
    362 freebuf(struct buf *b)
    363 {
    364 	free(b->p);
    365 	b->p = NULL;
    366 }
    367 
    368 size_t
    369 fillbuf(struct buf *b, void *ptr, size_t n)
    370 {
    371 	if (!(b->p = realloc(b->p, b->n + n)))
    372 		err(1, "realloc");
    373 	memcpy(b->p + b->n, ptr, n);
    374 	b->n += n;
    375 	return b->n;
    376 }
    377 
    378 int
    379 unpack(uint8_t *s, size_t n, char *fmt, ...)
    380 {
    381 	va_list arg;
    382 	uint8_t *b, *e;
    383 
    384 	b = s;
    385 	e = b + n;
    386 	va_start(arg, fmt);
    387 	for (; *fmt; fmt++) {
    388 		switch (*fmt) {
    389 		case '_':
    390 			s++;
    391 			break;
    392 		case 'b':
    393 			if (s + 1 > e)
    394 				goto err;
    395 			*va_arg(arg, int *) = *s++;
    396 			break;
    397 		case 'w':
    398 			if (s + 2 > e)
    399 				goto err;
    400 			*va_arg(arg, int *) = s[0] << 8 | s[1];
    401 			s += 2;
    402 			break;
    403 		case 'l':
    404 			if (s + 4 > e)
    405 				goto err;
    406 			*va_arg(arg, int *) = s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
    407 			s += 4;
    408 			break;
    409 		case 'v':
    410 			if (s + 4 > e)
    411 				goto err;
    412 			*va_arg(arg, long long *) =
    413 				(long long)s[0] << 56 |
    414 				(long long)s[1] << 48 |
    415 				(long long)s[2] << 40 |
    416 				(long long)s[3] << 32 |
    417 				(long long)s[4] << 24 |
    418 				(long long)s[5] << 16 |
    419 				(long long)s[6] << 8 |
    420 				(long long)s[7];
    421 			s += 8;
    422 			break;
    423 		}
    424 	}
    425 	va_end(arg);
    426 	return s - b;
    427 err:
    428 	va_end(arg);
    429 	return -1;
    430 }
    431 
    432 int
    433 pack(uint8_t *s, size_t n, char *fmt, ...)
    434 {
    435 	va_list arg;
    436 	uint8_t *b, *e;
    437 	long long v;
    438 	int i;
    439 
    440 	b = s;
    441 	e = b + n;
    442 	va_start(arg, fmt);
    443 	for (; *fmt; fmt++) {
    444 		switch (*fmt) {
    445 		case '_':
    446 			i = 0;
    447 			if (0) {
    448 		case 'b':
    449 			i = va_arg(arg, int);
    450 			}
    451 			if (s + 1 > e)
    452 				goto err;
    453 			*s++ = i & 0xff;
    454 			break;
    455 		case 'w':
    456 			i = va_arg(arg, int);
    457 			if (s + 2 > e)
    458 				goto err;
    459 			*s++ = (i >> 8) & 0xff;
    460 			*s++ = i & 0xff;
    461 			break;
    462 		case 'l':
    463 			i = va_arg(arg, int);
    464 			if (s + 4 > e)
    465 				goto err;
    466 			*s++ = (i >> 24) & 0xff;
    467 			*s++ = (i >> 16) & 0xff;
    468 			*s++ = (i >> 8) & 0xff;
    469 			*s++ = i & 0xff;
    470 			break;
    471 		case 'v':
    472 			v = va_arg(arg, long long);
    473 			if (s + 8 > e)
    474 				goto err;
    475 			*s++ = (v >> 56) & 0xff;
    476 			*s++ = (v >> 48) & 0xff;
    477 			*s++ = (v >> 40) & 0xff;
    478 			*s++ = (v >> 32) & 0xff;
    479 			*s++ = (v >> 24) & 0xff;
    480 			*s++ = (v >> 16) & 0xff;
    481 			*s++ = (v >> 8) & 0xff;
    482 			*s++ = v & 0xff;
    483 			break;
    484 		case '*':
    485 			i = va_arg(arg, int);
    486 			if (s + i > e)
    487 				goto err;
    488 			memmove(s, va_arg(arg, void *), i);
    489 			s += i;
    490 			break;
    491 		}
    492 	}
    493 	va_end(arg);
    494 	return s - b;
    495 err:
    496 	va_end(arg);
    497 	return -1;
    498 }
    499 
    500 int
    501 dial(char *host, char *port)
    502 {
    503 	struct addrinfo hints, *res, *r;
    504 	int s;
    505 
    506 	memset(&hints, 0, sizeof(hints));
    507 	hints.ai_family = AF_INET;
    508 	hints.ai_socktype = SOCK_STREAM;
    509 	if (getaddrinfo(host, port, &hints, &res)) {
    510 		warnx("can't resolve %s", host);
    511 		return -1;
    512 	}
    513 	for (r = res; r; r = r->ai_next) {
    514 		s = socket(r->ai_family, r->ai_socktype, 0);
    515 		if (s < 0)
    516 			continue;
    517 		if (!connect(s, r->ai_addr, r->ai_addrlen))
    518 			break;
    519 		close(s);
    520 	}
    521 	freeaddrinfo(res);
    522 	if (!r) {
    523 		warnx("cannot connect to %s on port %s", host, port);
    524 		return -1;
    525 	}
    526 	return s;
    527 }
    528 
    529 void
    530 error(char *msg)
    531 {
    532 	fprintf(stderr, "%s\n", msg);
    533 	longjmp(savesp, 1);
    534 }
    535 
    536 char *
    537 parsestr(char *s, char *e, struct ben **b)
    538 {
    539 	char *p;
    540 	long long len = 0;
    541 
    542 	for (p = s; p != e && isdigit((unsigned char)*p); p++)
    543 		len = len * 10 + *p - '0';
    544 	if (p == e)
    545 		error("bad string");
    546 	if (*p++ != ':')
    547 		error("expected ':' in string");
    548 	if (p + len > e)
    549 		error("bad string");
    550 	p += len;
    551 	*b = emalloc(sizeof(**b));
    552 	(*b)->type = 's';
    553 	(*b)->s = &p[-len];
    554 	(*b)->start = s;
    555 	(*b)->end = p;
    556 	(*b)->len = len;
    557 	return p;
    558 }
    559 
    560 char *
    561 parseint(char *s, char *e, struct ben **b)
    562 {
    563 	char *p = s;
    564 	long long v;
    565 	int isneg = 0, iszero = 0;
    566 
    567 	if (*p != 'i')
    568 		error("expected integer");
    569 	if (++p == e)
    570 		error("bad integer");
    571 
    572 	if (*p == '-')
    573 		isneg = 1;
    574 	else if (*p == '0')
    575 		iszero = 1;
    576 	else
    577 		p--;
    578 
    579 	v = 0;
    580 	while (1) {
    581 		if (++p == e)
    582 			error("bad integer");
    583 		if (*p == 'e' || iszero) {
    584 			if (*p != 'e')
    585 				error("0 not followed by e");
    586 			break;
    587 		}
    588 		if (isneg && *p == '0')
    589 			error("i-0 is invalid");
    590 		if (!isdigit((unsigned char)*p))
    591 			error("unexpected char in integer");
    592 		v = v * 10 + *p - '0';
    593 	}
    594 	if (*p++ != 'e')
    595 		error("expected terminator");
    596 
    597 	*b = emalloc(sizeof(**b));
    598 	(*b)->type = 'i';
    599 	(*b)->start = s;
    600 	(*b)->end = p;
    601 	(*b)->i = isneg ? -v : v;
    602 	return p;
    603 }
    604 
    605 char *
    606 parsedl(char *s, char *e, struct ben **b)
    607 {
    608 	char *p = s;
    609 	struct ben head;
    610 	struct ben *bp = &head;
    611 	int type = *p;
    612 	long long len = 0;
    613 
    614 	memset(&head, 0, sizeof(head));
    615 	if (*p != 'd' && *p != 'l')
    616 		error("expected dictionary or list");
    617 	p++;
    618 	while (1) {
    619 		if (p == e)
    620 			error("bad dictionary or list");
    621 		if (*p == 'e')
    622 			break;
    623 		len++;
    624 		bp->next = emalloc(sizeof(*bp));
    625 		bp = bp->next;
    626 		bp->type = type;
    627 		bp->k = NULL;
    628 		if (type == 'd')
    629 			p = parsestr(p, e, &bp->k);
    630 		p = parse(p, e, &bp->v);
    631 		bp->next = NULL;
    632 	}
    633 	if (*p++ != 'e')
    634 		error("expected terminator");
    635 
    636 	*b = head.next;
    637 	if (!head.next) {
    638 		*b = malloc(sizeof(**b));
    639 		(*b)->type = type;
    640 		(*b)->k = NULL;
    641 		(*b)->v = NULL;
    642 		(*b)->next = NULL;
    643 	}
    644 	(*b)->len = len;
    645 	(*b)->start = s;
    646 	(*b)->end = p;
    647 	return p;
    648 }
    649 
    650 char *
    651 parse(char *s, char *e, struct ben **b)
    652 {
    653 	if (s == e)
    654 		return s;
    655 	switch (*s) {
    656 	case 'i':
    657 		return parseint(s, e, b);
    658 		break;
    659 	case 'l':
    660 	case 'd':
    661 		return parsedl(s, e, b);
    662 		break;
    663 	default:
    664 		if (!isdigit((unsigned char)*s))
    665 			error("unknown type");
    666 		return parsestr(s, e, b);
    667 	}
    668 }
    669 
    670 char *
    671 bdecode(char *s, char *e, struct ben **b)
    672 {
    673 	*b = NULL;
    674 	if (!setjmp(savesp))
    675 		return parse(s, e, b);
    676 	bfree(*b);
    677 	*b = NULL;
    678 	return NULL;
    679 }
    680 
    681 char *
    682 bstr2str(struct ben *b)
    683 {
    684 	char *s;
    685 
    686 	s = emalloc(b->len + 1);
    687 	memcpy(s, b->s, b->len);
    688 	s[b->len] = '\0';
    689 	return s;
    690 }
    691 
    692 int
    693 bstrcmp(struct ben *a, struct ben *b)
    694 {
    695 	long long i;
    696 
    697 	if (a->type != 's' || b->type != 's')
    698 		return 1;
    699 	if (a->len != b->len)
    700 		return 1;
    701 	for (i = 0; i < a->len; i++)
    702 		if (a->s[i] != b->s[i])
    703 			return 1;
    704 	return 0;
    705 }
    706 
    707 struct ben *
    708 dlook(struct ben *d, struct ben *k)
    709 {
    710 	struct ben *b;
    711 
    712 	if (d->type != 'd' || k->type != 's')
    713 		return NULL;
    714 	for (b = d; b; b = b->next)
    715 		if (!bstrcmp(b->k, k))
    716 			return b->v;
    717 	return NULL;
    718 }
    719 
    720 struct ben *
    721 dlookstr(struct ben *d, char *s)
    722 {
    723 	struct ben k;
    724 
    725 	k.type = 's';
    726 	k.s = s;
    727 	k.len = strlen(s);
    728 	return dlook(d, &k);
    729 }
    730 
    731 void
    732 bfree(struct ben *b)
    733 {
    734 	struct ben *bp, *btmp;
    735 
    736 	if (!b)
    737 		return;
    738 	switch (b->type) {
    739 	case 's':
    740 		free(b);
    741 		break;
    742 	case 'i':
    743 		free(b);
    744 		break;
    745 	case 'l':
    746 	case 'd':
    747 		bp = b;
    748 		while (bp) {
    749 			btmp = bp->next;
    750 			bfree(bp->k);
    751 			bfree(bp->v);
    752 			free(bp);
    753 			bp = btmp;
    754 		}
    755 		break;
    756 	}
    757 }
    758 
    759 void
    760 printstr(struct ben *b)
    761 {
    762 	int64_t i;
    763 
    764 	for (i = 0; i < b->len; i++)
    765 		putchar(b->s[i]);
    766 }
    767 
    768 void
    769 printindent(int indent)
    770 {
    771 	while (indent--)
    772 		putchar(' ');
    773 }
    774 
    775 void
    776 bprint(struct ben *b, int indent)
    777 {
    778 	struct ben *bl;
    779 	struct ben *bd;
    780 
    781 	if (!b)
    782 		return;
    783 	switch (b->type) {
    784 	case 's':
    785 		printindent(indent);
    786 		printstr(b);
    787 		putchar('\n');
    788 		break;
    789 	case 'i':
    790 		printindent(indent);
    791 		printf("%lld\n", (long long)b->i);
    792 		break;
    793 	case 'l':
    794 		printindent(indent);
    795 		printf("[\n");
    796 		for (bl = b; bl; bl = bl->next)
    797 			bprint(bl->v, indent + 1);
    798 		printindent(indent);
    799 		printf("]\n");
    800 		break;
    801 	case 'd':
    802 		printindent(indent);
    803 		printf("{\n");
    804 		for (bd = b; bd; bd = bd->next) {
    805 			if (bd->k) {
    806 				printindent(indent + 1);
    807 				printstr(bd->k);
    808 				printf(" :\n");
    809 				bprint(bd->v, indent + 2);
    810 			}
    811 		}
    812 		printindent(indent);
    813 		printf("}\n");
    814 		break;
    815 	}
    816 }
    817 
    818 void
    819 calcinfohash(struct torrent *t)
    820 {
    821 	sha1sum((uint8_t *)t->info->start,
    822 	        t->info->end - t->info->start, t->infohash);
    823 }
    824 
    825 void
    826 dumptorrent(struct torrent *t)
    827 {
    828 	uint8_t md[20];
    829 	char hex[41];
    830 	long long i;
    831 	size_t n, m;
    832 
    833 	printf("announcers:\n");
    834 	for (n = 0; n < t->nannouncers; n++) {
    835 		printf("%zu: announcer\n", n);
    836 		for (m = 0; m < t->announcers[n].len; m++)
    837 			printf("\t%zu: %s\n", m,
    838 			       t->announcers[n].urls[m]);
    839 	}
    840 
    841 	if (t->filename[0])
    842 		printf("directory: %s\n", t->filename);
    843 	if (t->nfiles)
    844 		printf("files (%zu):\n", t->nfiles);
    845 	for (n = 0; n < t->nfiles; n++) {
    846 		printf("\tpath: %s, length: %zu\n",
    847 		       t->files[n].path, t->files[n].len);
    848 	}
    849 
    850 	bin2hex(t->infohash, hex, 20);
    851 	printf("infohash: %s\n", hex);
    852 	printf("piecelen: %lld\n", t->piecelen);
    853 	printf("npieces: %lld\n", t->npieces);
    854 
    855 	for (i = 0; i < t->npieces; i++) {
    856 		piecehash(t, i, md);
    857 		bin2hex(md, hex, 20);
    858 		printf("piece[%lld] hash: %s\n", i, hex);
    859 	}
    860 }
    861 
    862 struct torrent *
    863 loadtorrent(char *f)
    864 {
    865 	struct torrent *t;
    866 	struct ben *files, *file;
    867 	struct ben *length, *path, *tmp, *a;
    868 	size_t i, j, pathlen;
    869 	char *p;
    870 
    871 	t = ecalloc(1, sizeof(*t));
    872 	TAILQ_INSERT_TAIL(&torrenthead, t, entry);
    873 	if (readfile(f, &t->buf, &t->buflen) < 0) {
    874 		warnx("failed to read %s", f);
    875 		goto fail;
    876 	}
    877 	if (!bdecode(t->buf, t->buf + t->buflen, &t->ben)) {
    878 		warnx("failed to decode %s", f);
    879 		goto fail;
    880 	}
    881 
    882 	t->info = dlookstr(t->ben, "info");
    883 	if (!t->info) {
    884 		warnx("no info dictionary in %s", f);
    885 		goto fail;
    886 	}
    887 
    888 	t->pieces = dlookstr(t->info, "pieces");
    889 	if (!t->pieces) {
    890 		warnx("no pieces field in %s", f);
    891 		goto fail;
    892 	}
    893 	if (t->pieces->len % 20) {
    894 		warnx("incorrect pieces length in %s", f);
    895 		goto fail;
    896 	}
    897 
    898 	if ((tmp = dlookstr(t->ben, "announce-list")) && tmp->len) {
    899 		if (tmp->type != 'l') {
    900 			warnx("announce-list must be of type list");
    901 			goto fail;
    902 		}
    903 		t->announcers = ecalloc(tmp->len, sizeof(struct announce));
    904 
    905 		for (i = 0; tmp; tmp = tmp->next, i++, t->nannouncers++) {
    906 			if (tmp->v->type != 'l') {
    907 				warnx("announce-list item must be of type list");
    908 				goto fail;
    909 			}
    910 			if (!tmp->v->len)
    911 				continue;
    912 			t->announcers[i].urls = ecalloc(tmp->v->len, sizeof(char *));
    913 			for (a = tmp->v, j = 0; a; a = a->next, j++, t->announcers[i].len++) {
    914 				if (a->v->type != 's') {
    915 					warnx("announce item must be of type string");
    916 					goto fail;
    917 				}
    918 				t->announcers[i].urls[j] = bstr2str(a->v);
    919 			}
    920 		}
    921 	} else if ((tmp = dlookstr(t->ben, "announce"))) {
    922 		t->announcers = ecalloc(tmp->len, sizeof(struct announce));
    923 		t->nannouncers = 1;
    924 		t->announcers[0].len = 1;
    925 		t->announcers[0].urls = ecalloc(1, sizeof(char *));
    926 		t->announcers[0].urls[0] = bstr2str(tmp);
    927 	} else {
    928 		warnx("no announce field in %s", f);
    929 		goto fail;
    930 	}
    931 
    932 	if (!dlookstr(t->info, "piece length")) {
    933 		warnx("no piece length field in %s", f);
    934 		goto fail;
    935 	}
    936 	t->piecelen = dlookstr(t->info, "piece length")->i;
    937 	if (t->piecelen <= 0) {
    938 		warnx("piecelen is <= 0 in %s", f);
    939 		goto fail;
    940 	}
    941 
    942 	if (!dlookstr(t->info, "name")) {
    943 		warnx("no filename field in %s", f);
    944 		goto fail;
    945 	}
    946 	t->filename = bstr2str(dlookstr(t->info, "name"));
    947 
    948 	/* multi-file mode or single file? */
    949 	if ((files = dlookstr(t->info, "files"))) {
    950 		if (files->type != 'l') {
    951 			warnx("files must be of type list");
    952 			goto fail;
    953 		}
    954 		t->files = ecalloc(files->len, sizeof(struct file));
    955 
    956 		for (file = files; file; file = file->next, t->nfiles++) {
    957 			if (!(length = dlookstr(file->v, "length"))) {
    958 				warnx("no length field in %s", f);
    959 				goto fail;
    960 			}
    961 			if (length->type != 'i') {
    962 				warnx("length must be of type integer");
    963 				goto fail;
    964 			}
    965 			if (length->i < 0) {
    966 				warnx("length is < 0 in %s", f);
    967 				goto fail;
    968 			}
    969 			t->totallen += length->i;
    970 			t->files[t->nfiles].len = length->i;
    971 
    972 			if (!(path = dlookstr(file->v, "path")))
    973 				break;
    974 			if (path->type != 'l')
    975 				warnx("path must be of type list");
    976 
    977 			/* check path list and count path buffer size */
    978 			for (tmp = path, pathlen = 0; tmp; tmp = tmp->next) {
    979 				if (tmp->v->type != 's') {
    980 					warnx("path item must be of type string");
    981 					goto fail;
    982 				}
    983 				pathlen += tmp->v->len + 1;
    984 			}
    985 			t->files[t->nfiles].path = ecalloc(1, pathlen);
    986 			for (tmp = path; tmp; tmp = tmp->next) {
    987 				p = bstr2str(tmp->v);
    988 				strlcat(t->files[t->nfiles].path, p, pathlen);
    989 				free(p);
    990 				if (tmp != path && tmp->next)
    991 					strlcat(t->files[t->nfiles].path, "/", pathlen);
    992 			}
    993 		}
    994 	} else {
    995 		if (!(length = dlookstr(t->info, "length"))) {
    996 			warnx("no length field in %s", f);
    997 			goto fail;
    998 		}
    999 		if (length->type != 'i') {
   1000 			warnx("length must be of type integer");
   1001 			goto fail;
   1002 		}
   1003 		if (length->i < 0) {
   1004 			warnx("length is < 0 in %s", f);
   1005 			goto fail;
   1006 		}
   1007 		t->nfiles = 1;
   1008 		t->files = ecalloc(1, sizeof(struct file));
   1009 		t->files[0].len = length->i;
   1010 		t->files[0].path = t->filename;
   1011 		t->filename = strdup("");
   1012 		t->totallen = length->i;
   1013 	}
   1014 
   1015 	t->npieces = (t->totallen + t->piecelen - 1) / t->piecelen;
   1016 	t->piecebm = newbit(t->npieces);
   1017 
   1018 	calcinfohash(t);
   1019 
   1020 	return t;
   1021 fail:
   1022 	unloadtorrent(t);
   1023 	return NULL;
   1024 }
   1025 
   1026 void
   1027 unloadtorrent(struct torrent *t)
   1028 {
   1029 	size_t i, j;
   1030 
   1031 	if (!t)
   1032 		return;
   1033 
   1034 	TAILQ_REMOVE(&torrenthead, t, entry);
   1035 	i = t->nannouncers;
   1036 	while (i--) {
   1037 		j = t->announcers[i].len;
   1038 		while (j--)
   1039 			free(t->announcers[i].urls[j]);
   1040 		free(t->announcers[i].urls);
   1041 	}
   1042 	free(t->announcers);
   1043 
   1044 	for (i = 0; i < t->nfiles; i++)
   1045 		free(t->files[i].path);
   1046 	free(t->files);
   1047 
   1048 	bfree(t->ben);
   1049 	free(t->buf);
   1050 	free(t->piecebm);
   1051 	free(t);
   1052 }
   1053 
   1054 int
   1055 piecehash(struct torrent *t, long long n, uint8_t *md)
   1056 {
   1057 	if (n < 0 || n >= t->npieces)
   1058 		return -1;
   1059 	memcpy(md, t->pieces->start + n * 20, 20);
   1060 	return 0;
   1061 }
   1062 
   1063 char *
   1064 peerid(void)
   1065 {
   1066 	static char id[] = "-TD4242-000000000000";
   1067 	return id;
   1068 }
   1069 
   1070 size_t
   1071 writefn(void *ptr, size_t size, size_t nmemb, struct buf *b)
   1072 {
   1073 	return fillbuf(b, ptr, size * nmemb);
   1074 }
   1075 
   1076 int
   1077 trackerget(struct torrent *t, int event)
   1078 {
   1079 	CURL *curl;
   1080 	CURLcode res;
   1081 	struct buf reply;
   1082 	char buf[8192], *infohash, *id, *ev;
   1083 	int r;
   1084 
   1085 	switch (event) {
   1086 	case EVSTARTED:
   1087 		ev = "started";
   1088 		break;
   1089 	case EVCOMPLETED:
   1090 		ev = "completed";
   1091 		break;
   1092 	case EVSTOPPED:
   1093 		ev = "stopped";
   1094 		break;
   1095 	default:
   1096 		return -1;
   1097 	}
   1098 
   1099 	if (!(curl = curl_easy_init()))
   1100 		return -1;
   1101 
   1102 	if (!(infohash = curl_easy_escape(curl, (char *)t->infohash, 20))) {
   1103 		r = -1;
   1104 		goto err0;
   1105 	}
   1106 
   1107 	if (!(id = curl_easy_escape(curl, peerid(), 20))) {
   1108 		r = -1;
   1109 		goto err1;
   1110 	}
   1111 
   1112 	r = snprintf(buf, sizeof(buf),
   1113 	             "%s?info_hash=%s&peer_id=%s&port=%d&uploaded=%zu&"
   1114 	             "downloaded=%zu&left=%zu&compact=1&event=%s",
   1115 	             t->announcers[0].urls[0], infohash, id, PORT,
   1116 	             t->uploaded, t->downloaded, t->totallen - t->downloaded,
   1117 	             ev);
   1118 	if (r < 0 || (size_t)r >= sizeof(buf)) {
   1119 		r = -1;
   1120 		goto err2;
   1121 	}
   1122 
   1123 	initbuf(&reply);
   1124 	curl_easy_setopt(curl, CURLOPT_URL, buf);
   1125 	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefn);
   1126 	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &reply);
   1127 	if ((res = curl_easy_perform(curl)) != CURLE_OK) {
   1128 		r = - 1;
   1129 		goto err3;
   1130 	}
   1131 
   1132 	if (parsepeers(t, &reply) < 0) {
   1133 		r = - 1;
   1134 		goto err3;
   1135 	}
   1136 
   1137 	r = 0;
   1138 err3:
   1139 	freebuf(&reply);
   1140 err2:
   1141 	curl_free(id);
   1142 err1:
   1143 	curl_free(infohash);
   1144 err0:
   1145 	curl_easy_cleanup(curl);
   1146 	return r;
   1147 }
   1148 
   1149 int
   1150 parsepeers(struct torrent *t, struct buf *b)
   1151 {
   1152 	struct sockaddr_in sa;
   1153 	struct ben *reply, *peers;
   1154 	struct peer *peer;
   1155 	char *p, *errstr;
   1156 
   1157 	if (!bdecode(b->p, b->p + b->n, &reply))
   1158 		return -1;
   1159 
   1160 	if (dlookstr(reply, "failure reason")) {
   1161 		errstr = bstr2str(dlookstr(reply, "failure reason"));
   1162 		warnx("tracker failure: %s", errstr);
   1163 		bfree(reply);
   1164 		free(errstr);
   1165 		return -1;
   1166 	}
   1167 
   1168 	if (!(peers = dlookstr(reply, "peers"))) {
   1169 		warnx("no peers field in tracker reply");
   1170 		bfree(reply);
   1171 		return -1;
   1172 	}
   1173 
   1174 	if (peers->len % 6) {
   1175 		warnx("peers length needs to be a multiple of 6 bytes");
   1176 		bfree(reply);
   1177 		return -1;
   1178 	}
   1179 
   1180 	if (peers->type == 's') {
   1181 		for (p = peers->s; p < &peers->s[peers->len]; p += 6) {
   1182 			t->peers = realloc(t->peers,
   1183 			                   (t->npeers + 1) * sizeof(*t->peers));
   1184 			if (!t->peers)
   1185 				err(1, "realloc");
   1186 			peer = &t->peers[t->npeers];
   1187 			memset(peer, 0, sizeof(*peer));
   1188 			memcpy(&sa.sin_addr, p, 4);
   1189 			inet_ntop(AF_INET, &sa.sin_addr, peer->hostname,
   1190 			          sizeof(peer->hostname));
   1191 			snprintf(peer->port, sizeof(peer->port), "%d",
   1192 			         (int)ntohs(*(short *)&p[4]));
   1193 			peer->amchoking = 1;
   1194 			peer->peerchoking = 1;
   1195 			printf("%s:%s\n", peer->hostname, peer->port);
   1196 			t->npeers++;
   1197 		}
   1198 	} else if (peers->type == 'd') {
   1199 		warnx("not implemented");
   1200 		bfree(reply);
   1201 		return -1;
   1202 	} else {
   1203 		warnx("unexpected peers type: %d", peers->type);
   1204 		bfree(reply);
   1205 		return -1;
   1206 	}
   1207 
   1208 	free(reply);
   1209 	return 0;
   1210 }
   1211 
   1212 void
   1213 usage(char *argv0)
   1214 {
   1215 	fprintf(stderr, "usage: %s torrent\n", argv0);
   1216 	exit(1);
   1217 }
   1218 
   1219 int
   1220 main(int argc, char *argv[])
   1221 {
   1222 	struct torrent *t;
   1223 
   1224 	if (argc != 2)
   1225 		usage(argv[0]);
   1226 	TAILQ_INIT(&torrenthead);
   1227 	if (!(t = loadtorrent(argv[1])))
   1228 		exit(1);
   1229 	dumptorrent(t);
   1230 	trackerget(t, EVSTARTED);
   1231 	unloadtorrent(t);
   1232 	exit(0);
   1233 }