From b2e5f8a07a7d45a50ce3c0af0ecf6ec894b5b7c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anton=20Luka=20=C5=A0ijanec?= Date: Tue, 6 Dec 2022 21:37:13 +0100 Subject: =?UTF-8?q?grem=20se=20u=C4=8Dit=20sloven=C5=A1=C4=8Dino.=20src/dh?= =?UTF-8?q?t.c=20se=20prevede=20brez=20napak.=20nepreverjeno=20delovanje.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/bencoding.c | 20 +- src/dht.c | 936 ++++++++++++++++++++++++++++++++++++-------------------- src/main.c | 10 +- 3 files changed, 620 insertions(+), 346 deletions(-) (limited to 'src') diff --git a/src/bencoding.c b/src/bencoding.c index 11acee9..8a044e2 100644 --- a/src/bencoding.c +++ b/src/bencoding.c @@ -579,7 +579,7 @@ struct bencoding * bdecode (const char * s, int len, enum benc opts) { * @param key [in] the path */ -struct bencoding * bpath (struct bencoding * benc, const char * key) { +struct bencoding * bpath (const struct bencoding * benc, const char * key) { if (!benc) return NULL; if (!benc->child) @@ -596,17 +596,23 @@ struct bencoding * bpath (struct bencoding * benc, const char * key) { char buf[512]; sprintf(buf, "%ld", benc->key->intvalue); if (len == strlen(buf) && !strncmp(buf, key, len)) { - if (!c) + if (!c) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers" return benc; - else +#pragma GCC diagnostic pop + } else return bpath(benc, key+len); } } if (benc->key && benc->key->type & string) { if (len == benc->key->valuelen && !strncmp(key, benc->key->value, len)) { - if (!c) + if (!c) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdiscarded-qualifiers" return benc; - else +#pragma GCC diagnostic pop + } else return bpath(benc, key+len); } } @@ -618,11 +624,11 @@ struct bencoding * bpath (struct bencoding * benc, const char * key) { /** * macro that loops following code body across a list or values of dict * - * @param elem [out] name of element that will be used for value while looping * @param list [in] list/dict of values + * @param elem [out] name of element that will be used for value while looping */ -#define bforeach(elem, list) \ +#define bforeach(list, elem) \ for (struct bencoding * elem = list ? list->child : NULL; elem; elem = elem->next) /** diff --git a/src/dht.c b/src/dht.c index 852d2d0..05403e4 100644 --- a/src/dht.c +++ b/src/dht.c @@ -15,13 +15,13 @@ #include #include -time_t seconds () { +time_t seconds (void) { struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return tp.tv_sec; } -int family (const char * addr) { +int family (const unsigned char * addr) { return memcmp("\0\0\0\0\0\0\0\0\0\0\xFF\xFF", addr, 12) ? AF_INET6 : AF_INET; } @@ -44,7 +44,7 @@ struct node { * creates a new node */ -struct node * node_init () { +struct node * node_init (void) { struct node * n = calloc(1, sizeof *n); if (!n) return NULL; @@ -76,9 +76,9 @@ void node_free (struct node * n) { int closer (const unsigned char * a, const unsigned char * b, const unsigned char * t) { for (int i = 0; i < 20; i++) { - if (a[i] ^ t[i] < b[i] ^ t[i]) + if ((a[i] ^ t[i]) < (b[i] ^ t[i])) return 0; - if (a[i] ^ t[i] > b[i] ^ t[i]) + if ((a[i] ^ t[i]) > (b[i] ^ t[i])) return 1; } return -1; @@ -98,7 +98,7 @@ struct bucket { * creates a new bucket */ -struct bucket * bucket_init () { +struct bucket * bucket_init (void) { struct bucket * b = calloc(1, sizeof *b); if (!b) return NULL; @@ -128,7 +128,6 @@ void bucket_free (struct bucket * b) { struct peer { struct sockaddr_in6 addr; /**< peer ip address and port */ struct peer * next; - unsigned char pieces[]; /**< which pieces of the torrent does this peer have, 1 bit is one piece TODO */ }; /** @@ -143,7 +142,7 @@ void peer_free (struct peer * p) { * reason why a torrent is in our database. 0 just means it is stored as a result of an announce */ -enum torrent { +enum interested { announce = 1 << 0, /**< will announce myself on every work() call with no packet */ peers = 1 << 1, /**< will get peers on every work() call with no packet */ info = 1 << 2, /**< download metadata into `dht->dl`/$hash.info */ @@ -155,12 +154,11 @@ enum torrent { */ struct torrent { - enum torrent type; /**< is truthy only for manually added torrents */ + enum interested type; /**< is truthy only for manually added torrents */ unsigned char hash[20]; /**< infohash */ struct peer * peers; time_t last; /**< last operation on this torrent, so that inactive torrents are purged */ struct node * nodes; /**< closest K DHT nodes to this hash, used only for announce, peers, info and dl torrents */ - unsigned char pieces[]; /**< when checking a torrent, this is filled. every piece is one bit. TODO */ struct torrent * next; struct torrent * prev; /**< prev is here so that we can easily pop the oldest torrent. dht->last_torrent is useful here */ }; @@ -174,7 +172,7 @@ void torrent_free (struct torrent * t) { while (n) { struct node * old = n; n = n->next; - node_free(n); + node_free(old); } struct peer * p = t->peers; while (p) { @@ -208,12 +206,17 @@ struct dht { int dl; /**< dirfd storage directory for download and info torrents */ void (* possible_torrent)(struct dht *, const unsigned char *); /**< a user callback function that is called whenever we come across a torrent hash from a network */ void * userdata; /**< unused, but left for the library user to set so he can refer back to his structures from callback code, such as dht->possible_torrent(d, h) */ - unsigned torrents; /**< number of torrents. this number can rise indefinitely, so it can, and should be capped by the caller, depending on how much memory he has */ - unsigned peers; /**< number of peers. same notice regarding memory applies here as for torrents */ + unsigned torrents_num; /**< number of torrents. this number can rise indefinitely, so it can, and should be capped by the caller, depending on available memory */ + unsigned peers_num; /**< number of peers. same notice regarding memory applies here as for torrents */ unsigned torrents_max; /**< max number of torrents that we are allowed to store */ unsigned peers_max; /**< max number of peers that we are allowed to store */ struct torrent * last_torrent; /**< to quickly go to the end of the doubly linked list of torrents is helpful when reaching torrents_max and needing to pop oldest */ unsigned peers_per_torrent_max; /**< max number of peers to store per torrent - applies to ->type and !->type torrents */ + unsigned time; /**< statistics: time of initialization, for amount of seconds since initialization, check seconds() */ + unsigned rxp; /**< statistics: total number of received packets */ + unsigned txp; /**< statistics: total number of sent packets */ + unsigned rxb; /**< statistics: total number of bytes in received UDP bodies */ + unsigned txb; /**< statistics: total number of bytes in transmitted UDP bodies */ }; /** @@ -223,10 +226,125 @@ struct dht { * @param h [in] the infohash of the found torrent */ -void possible_torrent (struct dht *, const unsigned char * h) { +void possible_torrent (struct dht * d __attribute__((unused)), const unsigned char * h __attribute__((unused))) { return; } +/** + * macro for printing logs + * + * @param o [in] FILE * to which to write to + * @param f [in] printf style format string + * @param ... [in] variable arguments to go with f + */ + +#define L(o, f, ...) do {char t[512]; time_t n = time(NULL); strftime(t, 512, "%c", localtime(&n)); fprintf(o, "[%s] %s()%s:%d: " f "\n", t, __func__, __FILE__, __LINE__ __VA_OPT__(,) __VA_ARGS__);} while (0) + +/** + * sends a bencoding object to the remote node. does not free the input bencoding. inserts a v key to the input bencoding. + * + * @param d [in] the dht library handle + * @param b [in] the bencoding to send serialized, m. ownership NOT transfered + * @param a [in] destination address + */ + +void sendb (struct dht * d, struct bencoding * b, const struct sockaddr_in6 * a) { + char remote[INET6_ADDRSTRLEN + 7]; + if (!inet_ntop(a->sin6_family, a, remote, sizeof *a)) + snprintf(remote, sizeof remote, "(inet_ntop: %s)", strerror(errno)); + sprintf(remote+strlen(remote), ":%d", ntohs(((struct sockaddr_in6 *) a)->sin6_port)); + struct bencoding * v = bstr(strdup("TK00")); + v->key = bstr(strdup("v")); + binsert(b, v); + int len = b2json_length(b); + char json[len+1]; + b2json(json, b); + json[len] = '\0'; + L(d->log, "sending to %s: %s", remote, json); + len = bencode_length(b); + char text[len]; + bencode(text, b); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wincompatible-pointer-types" + if (sendto(d->socket, text, len, MSG_DONTWAIT | MSG_NOSIGNAL, a, sizeof *a) == -1) + L(d->log, "sendto(%s): %s", remote, strerror(errno)); + else { + d->txp++; + d->txb += len; + } +#pragma GCC diagnostic pop +} + +/** + * sends a find_node query to a "raw node" + * + * @param d [in] handle + * @param a [in] address of the remote node + * @param query [in] 20 byte id we are querying + */ + +void find_node (struct dht * d, const struct sockaddr_in6 * addr, const unsigned char * query) { + struct bencoding * b = calloc(1, sizeof *b); + b->type = dict; + struct bencoding * t = calloc(1, sizeof *t); + memcpy((t->value = malloc(20)), query, (t->valuelen = 20)); + t->key = bstr(strdup("t")); + t->type = string; + binsert(b, t); + struct bencoding * y = bstr(strdup("q")); + t->key = bstr(strdup("y")); + t->type = string; + binsert(b, y); + struct bencoding * q = bstr(strdup("find_node")); + q->key = bstr(strdup("q")); + q->type = string; + binsert(b, q); + struct bencoding * a = calloc(1, sizeof *a); + a->type = dict; + struct bencoding * id = calloc(1, sizeof *id); + id->type = string; + id->valuelen = 20; + id->key = bstr(strdup("key")); + memcpy((id->value = malloc(20)), d->id, 20); + binsert(a, id); + struct bencoding * want = calloc(1, sizeof *want); // BEP-0032 + want->key = bstr(strdup("want")); + want->type = list; + binsert(want, bstr(strdup("n4"))); + binsert(want, bstr(strdup("n6"))); + binsert(a, want); + struct bencoding * target = calloc(1, sizeof *target); + target->key = bstr(strdup("target")); + target->type = string; + target->valuelen = 20; + memcpy((target->value = malloc(20)), query, 20); + binsert(a, target); + binsert(b, a); + sendb(d, b, addr); + free_bencoding(b); +} + +/** + * ping a raw node by sending a find_node + * + * instead of sending a ping query, we send a find_node query. this gets us useful information of peers around our ID instead of just a blank ping reply. infolgedessen we don't have to actively search for our neighbour nodes, since we'll get them through pings anyways + * + * DEV THOUGHT: instead of sending a find_node for an ID close to ours, we could send a find_node for a random ID far from us. though those buckets will probably quickly be filled by torrent searches. + * + * @param d [in] library handle + * @param a [in] address of node + */ + +void ping_node (struct dht * d, const struct sockaddr_in6 * a) { + unsigned char target[20]; + memcpy(target, d->id, 20); + if (target[19] & 1) // flip the last bit, so the other node doesn't just return + target[19] &= 0xFE; // our ID but K ids around it + else + target[19] |= 1; + find_node(d, a, target); +} + /** * creates a handle. you can override log in the result struct. * @@ -241,13 +359,14 @@ void possible_torrent (struct dht *, const unsigned char * h) { struct dht * dht_init (const struct bencoding * c) { struct dht * d = calloc(1, sizeof *d); + d->time = seconds(); d->log = stderr; d->dl = -1; d->buckets = bucket_init(); d->buckets6 = bucket_init(); d->possible_torrent = &possible_torrent; d->torrents_max = UINT_MAX; // this is hardcore - so many torrents makes LL traversal too slow - d->peers_max UINT_MAX; // there's no way there even are this many peers on the entire network at a time xDDDDDDDDDDD + d->peers_max = UINT_MAX; // there's no way there even are this many peers on the entire network at a time xDDDDDDDDDDD d->peers_per_torrent_max = UINT_MAX; errno = 0; if (!d) @@ -260,20 +379,31 @@ struct dht * dht_init (const struct bencoding * c) { if (d->socket == -1) goto e; struct sockaddr_in6 a = { - sin6_family = AF_INET6, - sin6_addr = in6addr_any + .sin6_family = AF_INET6, + .sin6_addr = in6addr_any }; + const struct bencoding * port = NULL; + if (c && (port = bpath(c, "port")) && port->type & num) + a.sin6_port = htons(port->intvalue); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wincompatible-pointer-types" if (bind(d->socket, &a, sizeof a) == -1) - goto e; + if (errno == EADDRINUSE) { + a.sin6_port = 0; + if (bind(d->socket, &a, sizeof a) == -1) +#pragma GCC diagnostic pop + goto e; + } if (c) { const struct bencoding * id = bpath(c, "id"); - if (id & id->type & string && id->valuelen == 20) + if (id && id->type & string && id->valuelen == 20) memcpy(d->id, id->value, 20); bforeach (bpath(c, "nodes"), str) { struct sockaddr_in6 addr; char remote[INET6_ADDRSTRLEN + 7]; strncpy(remote, str->value, str->valuelen); - char * port = strchr(remote, ':'); + char * port = strchr(remote, '/'); + port[0] = '\0'; if (port) { if (inet_pton(AF_INET6, remote, &addr) == 1) { addr.sin6_port = htons(atoi(++port)); @@ -292,8 +422,6 @@ struct dht * dht_init (const struct bencoding * c) { * frees a handle. does nothing if handle is NULL. does not fclose log. closes socket. please set socket to -1 before calling if you don't want to close it. */ -#define L(o, f, ...) do {char t[512]; time_t n = time(NULL); strftime(t, 512, "%c", localtime(&n)); fprintf(o, "[%s] %s()%s:%d: " f "\n", t, __func__, __FILE__, __LINE__ __VA_OPT__(,) __VA_ARGS__)} while (0) - void dht_free (struct dht * d) { if (d->socket != -1) if (close(d->socket) == -1) @@ -337,11 +465,21 @@ struct bencoding * persistent (const struct dht * d) { b->type = dict; struct bencoding * id = calloc(1, sizeof *id); id->type = string; - id->value = malloc(20); - id->valuelen = 20; - memcpy(id->value, d->id); + memcpy((id->value = malloc(20)), d->id, (id->valuelen = 20)); id->key = bstr(strdup("id")); binsert(b, id); + struct sockaddr_in6 bound; + socklen_t size = sizeof bound; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wincompatible-pointer-types" + if (getsockname(d->socket, &bound, &size) == -1) + L(d->log, "getsockname: %s", strerror(errno)); + else { + struct bencoding * port = bnum(ntohs(bound.sin6_port)); + b->key = bstr(strdup("port")); + binsert(b, port); + } +#pragma GCC diagnostic pop struct bencoding * nodes = calloc(1, sizeof *nodes); nodes->type = list; struct bucket * bucket = d->buckets; @@ -349,8 +487,10 @@ struct bencoding * persistent (const struct dht * d) { struct node * node = bucket->nodes; while (node) { char remote[INET6_ADDRSTRLEN + 7]; - if (inet_ntop(AF_INET6, &node->addr, remote, sizeof node->addr)) + if (inet_ntop(AF_INET6, &node->addr, remote, sizeof node->addr)) { + sprintf(remote+strlen(remote), "/%u", ntohs(node->addr.sin6_port)); binsert(nodes, bstr(strdup(remote))); + } node = node->next; } bucket = bucket->next; @@ -368,7 +508,7 @@ struct bencoding * persistent (const struct dht * d) { * @param l [in] the length of socket address struct a */ -void token (const struct dht * d, unsigned * t, const char * addr) { +void token (const struct dht * d, unsigned char * t, const unsigned char * addr) { struct AES_ctx aes; memcpy(t, addr, 16); AES_init_ctx(&aes, d->secret); @@ -385,41 +525,13 @@ void token (const struct dht * d, unsigned * t, const char * addr) { * @return 1 if the token is valid for this node, 0 otherwise */ -int valid (const struct dht * d, const char * t, const char * addr) { - char try[16]; +int valid (const struct dht * d, const unsigned char * t, const unsigned char * addr) { + unsigned char try[16]; memcpy(try, t, 16); - token(d, try, a, l); + token(d, try, addr); return !memcmp(try, t, 16); } -/** - * sends a bencoding object to the remote node. does not free the input bencoding. inserts a v key to the input bencoding. - * - * @param d [in] the dht library handle - * @param b [in] the bencoding to send serialized, m. ownership NOT transfered - * @param a [in] destination address - */ - -void sendb (const struct dht * d, struct bencoding * b, struct sockaddr_in6 * a) { - char remote[INET6_ADDRSTRLEN + 7]; - if (!inet_ntop(a->sa_family, a, remote, sizeof *a)) - snprintf(remote, sizeof remote, "(inet_ntop: %s)", strerror(errno)); - sprintf(remote+strlen(remote), ":%d", ntohs(((struct sockaddr_in6 *) a)->sin6_port)); - struct bencoding * v = bstr(strdup("TK00")); - v->key = bstr(strdup("v")); - binsert(b, v); - int len = b2json_length(b); - char json[len+1]; - b2json(json, a); - json[len] = '\0'; - L(d->log, "sending to %s: %s", remote, json); - len = bencode_length(b); - char text[len]; - bencode(text, b); - if (sendto(dht->socket, text, len, MSG_DONTWAIT | MSG_NOSIGNAL, a, sizeof *a) == -1) - L(d->log, "sendto(%s): %s", remote, strerror(errno)); -} - /** * sends an error rpc packet to a node. make sure that this is always similar size to the received packet, otherwise we could get amplification attacks. * @@ -430,14 +542,14 @@ void sendb (const struct dht * d, struct bencoding * b, struct sockaddr_in6 * a) * @param text [in] error text. memory ownership is transfered and string is freed, so make sure it's allocated on heap and no longer used by the caller - for static strings use strdup() */ -void send_error (const struct dht * d, const struct bencoding * b, struct sockaddr_in6 * a, int errnum, char * text) { +void send_error (struct dht * d, const struct bencoding * b, struct sockaddr_in6 * a, int errnum, char * text) { struct bencoding * e = calloc(1, sizeof *e); e->type = list; e->key = bstr(strdup("e")); binsert(e, bstr(text)); binsert(e, bnum(errnum)); struct bencoding * y = bstr(strdup("e")); - b->key = bstr(strdup("y")); + y->key = bstr(strdup("y")); struct bencoding * response = calloc(1, sizeof *response); binsert(response, y); binsert(response, e); @@ -467,16 +579,17 @@ int in_bucket (const unsigned char * id, const struct bucket * b) { * @return the pointer to the node or NULL if not found */ -struct node * find (const unsigned char * id, struct bucket ** b, struct ** n) { +struct node * find (const unsigned char * id, struct bucket ** b, struct node ** n) { while (!in_bucket(id, *b)) *b = (*b)->next; struct node * node = (*b)->nodes; - struct prev = NULL; - while (node && memcmp(node->id, id) < 0) { + struct node * prev = NULL; + while (node && memcmp(node->id, id, 20) < 0) { prev = node; node = node->next; } *n = prev; + return node; } /** @@ -508,11 +621,11 @@ void midpoint (unsigned char * r, const unsigned char * a, const unsigned char * } carry = 0; for (int i = 19; i >= 0; i--) { - if (carry + (unsigned) t[i] + (unsigned) a[i] > 255) { - t[i] = t[i] + a[i] - 255; + if (carry + (unsigned) r[i] + (unsigned) a[i] > 255) { + r[i] = r[i] + a[i] - 255; carry = 1; } else { - t[i] = t[i] + a[i]; + r[i] = r[i] + a[i]; carry = 0; } } @@ -526,142 +639,16 @@ void midpoint (unsigned char * r, const unsigned char * a, const unsigned char * void split (struct bucket * b) { struct bucket * new = bucket_init(); - midpoint(new->id, b->id, b->next ? b->next-id : NULL); + midpoint(new->id, b->id, b->next ? b->next->id : NULL); new->next = b->next; struct node ** n = &b->nodes; - while (*node && !in_bucket((*node)->id, new)) - node = &(*node)->next; - new->nodes = *node; - *node = NULL; + while (*n && !in_bucket((*n)->id, new)) + n = &(*n)->next; + new->nodes = *n; + *n = NULL; b->next = new; } -/** - * informs the library of a successfully received response packet from a node, knowing it's id and ip:port. do not call if the node queried us, if that's the case, use potential_node(). - * - * if the node is new, it's added in a bucket. - * - * if the node is found in a bucket, it's last received time and unanswered are updated - * - * @param d [in] handle - * @param id [in] node id that was received - * @param addr [in] address from which the id was received - */ - -void replied (const struct dht * d, const unsigned char * id, const struct sockaddr_in6 * addr) { - struct bucket * b = d->buckets; - if (family(addr->sin6_addr.s6_addr) == AF_INET6) - b = d->buckets6; - struct node * n; - struct node * found = find(id, &b, &n); - if (found) { - found->last_received = seconds(); - found->unanswered = 0; - return; - } - if (bucket_good(d, b)) - return; - struct node * node = node_init(); - memcpy(&node->addr, addr, sizeof *addr); - memcpy(node->id, id, 20); - if (!n) { - b->nodes = node; - return; - } - if (node_count(b->nodes) < K) { - struct node * index = b->nodes; - while (index->next && memcmp(node->id, index->next->id, 20) > 1) - index = index->next; - node->next = index->next; - index->next = node; - return; - } - if (in_bucket(d->id, b)) { - struct node * n = b->nodes; - while (n->next) - if (distance(n->id, n->next->id) != 1) // at least one gap, if not, then we have the innermost bucket full - goto ok; - return; - ok: - node_free(node); - split_bucket(b); - replied(d, id, addr); // find bucket again - } -} - -/** - * ping a raw node by sending a get_peers - * - * instead of sending a ping query, we send a find_node query. this gets us useful information of peers around our ID instead of just a blank ping reply. infolgedessen we don't have to actively search for our neighbour nodes, since we'll get them through pings anyways - * - * instead of sending a find_node for an ID close to ours, we could send a find_node for a random ID far from us. though those buckets will probably quickly be filled by torrent searches. - * - * @param d [in] library handle - * @param a [in] address of node - */ - -void ping_node (const struct dht * d, const struct sockaddr_in6 * a) { - unsigned char target[20]; - memcpy(target, d->id, 20); - if (target[19] & 1) // flip the last bit, so the other node doesn't just return - target[19] &= 0xFE; // our ID but K ids around it - else - target[19] |= 1; - find_node(d, a, target, NULL); -} - -/** - * sends a find_node query to a "raw node" - * - * @param d [in] handle - * @param a [in] address of the remote node - * @param query [in] 20 byte id we are querying - * @param t [in] token bencoding element (t key in dict). if NULL, a static token will be sent. ->key must be set. memory ownership is transfered away from the caller and the object is freed by this function. - */ - -void find_node (const struct dht * d, const struct sockaddr_in6 * a, const unsigned char * query, struct bencoding * t) { - struct bencoding * b = calloc(1, sizeof *b); - b->type = dict; - if (!t) { - t = bstr(strdup("t@_a.si")); - t->key = bstr(strdup("t")); - t->value[2] = '4'; - t->type = string; - } - binsert(b, t); - struct bencoding * y = bstr(strdup("q")); - t->key = bstr(strdup("y")); - t->type = string; - binsert(b, y); - struct bencoding * q = bstr(strdup("find_node")); - q->key = bstr(strdup("q")); - q->type = string; - binsert(b, q); - struct bencoding * a = calloc(1, sizeof *a); - a->type = dict; - struct bencoding * id = calloc(1, sizeof *id); - id->type = string; - id->valuelen = 20; - id->key = bstr(strdup("key")); - memcpy((id->value = malloc(20)), d->id, 20); - binsert(a, id); - struct bencoding * want = calloc(1, sizeof *want); // BEP-0032 - want->key = bstr(strdup("want")); - want->type = list; - binsert(want, bstr(strdup("n4"))); - binsert(want, bstr(strdup("n6"))); - binsert(a, want); - struct bencoding * target = calloc(1, sizeof *target); - target->key = bstr(strdup("target")); - target->type = string; - target->valuelen = 20; - memcpy((id->value = malloc(20)), query, 20); - binsert(a, id); - binsert(b, a); - sendb(d, b, a); - free_bencoding(b); -} - /** * returns a count of nodes in a linked list * @@ -685,15 +672,16 @@ int node_count (const struct node * n) { unsigned int distance (const unsigned char * a, const unsigned char * b) { unsigned char xor[20]; - memcpy(xor, a); - for (int i = 0; i < 20; i++) { + memcpy(xor, a, 20); + for (long unsigned int i = 0; i < 20; i++) { xor[i] ^= b[i]; - if (i < 20-sizeof unsigned && xor[i]) + if (i < 20 - sizeof (unsigned int) && xor[i]) return UINT_MAX; } unsigned r = 0; - for (int i = 0; i < sizeof unsigned; i++) - r |= xor[i] << (sizeof unsigned - 1 - i) * 8; + for (long unsigned int i = 0; i < sizeof (unsigned); i++) + r |= xor[i] << (sizeof (unsigned) - 1 - i) * 8; + return r; } enum node_grade { @@ -710,8 +698,8 @@ enum node_grade { */ enum node_grade node_grade (const struct node * n) { - if (node->last_received + 15*60 < seconds()) { - if (node->last_sent + 14*60 < seconds() && node->unanswered > 1) + if (n->last_received + 15*60 < seconds()) { + if (n->last_sent + 14*60 < seconds() && n->unanswered > 1) return bad; return questionable; } @@ -749,6 +737,60 @@ int bucket_good (const struct dht * d, const struct bucket * b) { return 0; n = n->next; } + return 1; + } +} + +/** + * informs the library of a successfully received response packet from a node, knowing it's id and ip:port. do not call if the node queried us, if that's the case, use potential_node(). + * + * if the node is new, it's added in a bucket. + * + * if the node is found in a bucket, it's last received time and unanswered are updated + * + * @param d [in] handle + * @param id [in] node id that was received + * @param addr [in] address from which the id was received + */ + +void replied (const struct dht * d, const unsigned char * id, const struct sockaddr_in6 * addr) { + struct bucket * b = d->buckets; + if (family(addr->sin6_addr.s6_addr) == AF_INET6) + b = d->buckets6; + struct node * n; + struct node * found = find(id, &b, &n); + if (found) { + found->last_received = seconds(); + found->unanswered = 0; + return; + } + if (bucket_good(d, b)) + return; + struct node * node = node_init(); + memcpy(&node->addr, addr, sizeof *addr); + memcpy(node->id, id, 20); + if (!n) { + b->nodes = node; + return; + } + if (node_count(b->nodes) < K) { + struct node * index = b->nodes; + while (index->next && memcmp(node->id, index->next->id, 20) > 1) + index = index->next; + node->next = index->next; + index->next = node; + return; + } + if (in_bucket(d->id, b)) { + struct node * n = b->nodes; + while (n->next) + if (distance(n->id, n->next->id) != 1) // at least one gap, if not, then we have the innermost bucket full + goto ok; + return; + ok: + node_free(node); + split(b); + replied(d, id, addr); // find bucket again } } @@ -762,13 +804,13 @@ int bucket_good (const struct dht * d, const struct bucket * b) { * @param id [in] id of the node, 20 bytes is read from this address */ -void potential_node (const struct dht * d, const struct sockaddr_in6 * a, const unsigned char * id) { +void potential_node (struct dht * d, const struct sockaddr_in6 * a, const unsigned char * id) { struct bucket * bucket = d->buckets; if (family(a->sin6_addr.s6_addr) == AF_INET6) bucket = d->buckets6; if (find(id, &bucket, NULL)) return; - if (!bucket_good(bucket)); + if (!bucket_good(d, bucket)) ping_node(d, a); } @@ -781,7 +823,7 @@ void potential_node (const struct dht * d, const struct sockaddr_in6 * a, const */ struct torrent * find_torrent (struct dht * d, const unsigned char * h) { - const struct torrent * t = d->torrents; + struct torrent * t = d->torrents; while (t) { if (!memcmp(t->hash, h, 20)) return t; @@ -790,6 +832,31 @@ struct torrent * find_torrent (struct dht * d, const unsigned char * h) { return NULL; } +/** + * deletes a torrent from storage. if you downloaded a torrent and set peers/announce flags, do not remove_torrent once you're done with it, but instead just clear peers/announce bits. this will remove the torrent when necessary. + * + * @param d [in] the library handle + * @param t [in] the pointer to the torrent to be deleted. do not craft torrent yourself, it must be stored in dht and that specific instance must be passed + */ + +void remove_torrent (struct dht * d, struct torrent * t) { + if (!t) + return; + if (!t->next) + d->last_torrent = t->prev; + if (t->prev) + t->prev->next = t->next; + if (t->next) + t->next->prev = t->prev; + struct peer * p = t->peers; + while (p) { + d->peers_num--; + p = p->next; + } + d->torrents_num--; + torrent_free(t); +} + /** * what to do when there are too many torrents and their peers stored, used in add_peer and add_torrent * @@ -802,7 +869,7 @@ void oom (struct dht * d) { struct torrent * drop = d->last_torrent; while (drop && drop->type) drop = drop->prev; - remove_torrent(drop); + remove_torrent(d, drop); } /** @@ -829,37 +896,12 @@ struct torrent * add_torrent (struct dht * d, struct torrent * t) { t->prev = NULL; t->next = d->torrents; d->torrents = t; - d->torrents++; - if (d->torrents >= d->torrents_max) + d->torrents_num++; + if (d->torrents_num >= d->torrents_max) oom(d); return t; } -/** - * deletes a torrent from storage. if you downloaded a torrent and set peers/announce flags, do not remove_torrent once you're done with it, but instead just clear peers/announce bits. this will remove the torrent when necessary. - * - * @param d [in] the library handle - * @param t [in] the pointer to the torrent to be deleted. do not craft torrent yourself, it must be stored in dht and that specific instance must be passed - */ - -void remove_torrent (struct dht * d, struct torrent * t) { - if (!t) - return; - if (!t->next) - d->last_torrent = t->prev; - if (t->prev) - t->prev->next = t->next; - if (t->next) - t->next->prev = t->prev; - struct peer * p = t->peers; - while (p) { - d->peers--; - p = p->next; - } - d->torrents--; - torrent_free(t); -} - /** * adds a peer to a torrent, memory ownership is transfered, so make sure it's allocated on heap. if this peer already exists, the input peer is freed and the old peer is returned. * @@ -870,28 +912,82 @@ void remove_torrent (struct dht * d, struct torrent * t) { */ struct peer * add_peer (struct dht * d, struct torrent * t, struct peer * p) { - struct peer * peer = torrent->peers; + struct peer * peer = t->peers; unsigned i = 0; while (peer) { - if (!memcmp(&peer->addr, &addr, sizeof addr)) { + if (!memcmp(&peer->addr, &p->addr, sizeof p->addr)) { peer_free(p); return peer; } if (peer->next && !peer->next->next) if (++i >= d->peers_per_torrent_max) { - d->peers--; - free_peer(peer->next); + d->peers_num--; + peer_free(peer->next); peer->next = NULL; } } - peer->next = torrent->peers; - torrent->peers = peer; - d->peers++; - if (d->peers >= d->peers_max) + peer->next = t->peers; + t->peers = peer; + d->peers_num++; + if (d->peers_num >= d->peers_max) oom(d); return peer; } +/** + * parses a compact node description in either ipv4 or ipv6 from nodes or nodes6 and invoke actions. call this for every string in nodes and nodes6 array in incoming response packets. + * + * if the newly found node is useful for filling the K closest nodes ll of the torrent, it will be added in the LL. it may also replace an existing node if the existing node is bad or furthest away from torrent hash and this one is closer. upon insertion, the node is queried for find_node. + * + * @param d [in] libh + * @param value [in] compact node info buffer pointer + * @param len [in] length of buffer, can be either 20+4+2 for ipv4 or 20+16+2 for ipv6 + * @param t + */ + +void compact (struct dht * d, const char * value, int len, struct torrent * t) { + if (len != 4+2+20 || len != 16+2+20) { + L(d->log, "received packet contained an invalid compact node"); + return; + } + struct node * node = node_init(); + memcpy(node->addr.sin6_addr.s6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\xFF\xFF\xFF\xFF", 12); + node->addr.sin6_port = *((uint16_t *) (value + len-2)); + memcpy(node->addr.sin6_addr.s6_addr+(len == 4+2+20 ? 8 : 0), value + 20, len == 4+2+20 ? 4 : 16); + memcpy(node->id, value, 20); + potential_node(d, &node->addr, node->id); // NOTE02 at the beginning, a lot of packets will be sent, since every reply of potential_node will generate K replies. naively this would generate an exponentially increasing number of packets, in increasing powers of 8 (8**n). to prevent an absolute resource hog, this is only done when node would be useful and would contribute to the routing table + if (t) { + int i = 0; + struct node ** replaceable = NULL; + struct node ** farthest = &t->nodes; + struct node ** index = &t->nodes; + while (*index) { + i++; + if (node_grade(*index) == bad) + replaceable = index; + if (!closer((*index)->id, (*farthest)->id, t->hash)) + farthest = index; + index = &(*index)->next; + } + if (i <= K) { + node->next = t->nodes; + t->nodes = node->next; + } else if (replaceable) { + node->next = (*replaceable)->next; + node_free(*replaceable); + *replaceable = node; + find_node(d, &node->addr, t->hash); + } else if (!closer(node->id, (*farthest)->id, t->hash)) { + node->next = (*farthest)->next; + node_free(*farthest); + *farthest = node; + find_node(d, &node->addr, t->hash); + } else + node_free(node); + } else + node_free(node); +} + /** * returns a dict containing nodes or nodes6 bencoding list (with a key) with compact nodes in the bucket. if exact node is found, only that one is in the list. * @@ -905,8 +1001,7 @@ struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_fam struct bencoding * nodes = calloc(1, sizeof *nodes); nodes->type = list; nodes->key = bstr(strdup(f == AF_INET ? "nodes" : "nodes6")); - binsert(r, nodes); - struct bucket * bucket = f == AF_INET ? d->buckets : d->bucket6; + struct bucket * bucket = f == AF_INET ? d->buckets : d->buckets6; struct node * found = find(id, &bucket, NULL); #define ADDRLEN(f) (f == AF_INET ? 4 : 16) if (found) { @@ -915,7 +1010,7 @@ struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_fam compact->value = malloc((compact->valuelen = 20+ADDRLEN(f)+2)); memcpy(compact->value, found->id, 20); memcpy(compact->value+20, found->addr.sin6_addr.s6_addr+(16-ADDRLEN(f)), ADDRLEN(f)); - memcpy(compact->value+20+ADDRLEN(f), found->addr.sin6_port, 2); + memcpy(compact->value+20+ADDRLEN(f), &found->addr.sin6_port, 2); binsert(nodes, compact); } else { struct node * node = bucket->nodes; @@ -925,7 +1020,7 @@ struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_fam compact->value = malloc((compact->valuelen = 20+ADDRLEN(f)+2)); memcpy(compact->value, found->id, 20); memcpy(compact->value+20, found->addr.sin6_addr.s6_addr+(16-ADDRLEN(f)), ADDRLEN(f)); - memcpy(compact->value+20+ADDRLEN(f), found->addr.sin6_port, 2); + memcpy(compact->value+20+ADDRLEN(f), &found->addr.sin6_port, 2); binsert(nodes, compact); node = node->next; } @@ -933,6 +1028,71 @@ struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_fam return nodes; } +/** + * sends an announce_peer query to a raw node + * + * @param d [in] lh + * @param a [in] node addr + * @param t [in] bencoding object from r/token to be inserted into a/token when sending. memory ownership and responsibility is transfered and this object is freed after call to this function, so use something along the lines of bclone(bpath(b, "r/token")) as argument to call + * @param h [in] torrent hash to announce from which 20 bytes are read + */ + +void announce_peer (struct dht * d, const struct sockaddr_in6 * addr, struct bencoding * t, const unsigned char * h) { + struct bencoding * b = calloc(1, sizeof *b); + b->type = dict; + struct bencoding * t_elem = bstr(strdup("a@4_.si")); + t_elem->key = bstr(strdup("t")); + t_elem->value[3] = 'a'; + binsert(b, t_elem); + struct bencoding * y = bstr(strdup("q")); + t->key = bstr(strdup("y")); + t->type = string; + binsert(b, y); + struct bencoding * q = bstr(strdup("announce_peer")); + q->key = bstr(strdup("q")); + q->type = string; + binsert(b, q); + struct bencoding * a = calloc(1, sizeof *a); + a->type = dict; + struct bencoding * id = calloc(1, sizeof *id); + id->type = string; + id->valuelen = 20; + id->key = bstr(strdup("key")); + memcpy((id->value = malloc(20)), d->id, 20); + binsert(a, id); + struct bencoding * want = calloc(1, sizeof *want); // BEP-0032 + want->key = bstr(strdup("want")); + want->type = list; + binsert(want, bstr(strdup("n4"))); + binsert(want, bstr(strdup("n6"))); + binsert(a, want); + struct bencoding * info_hash = calloc(1, sizeof *info_hash); + info_hash->key = bstr(strdup("info_hash")); + info_hash->type = string; + info_hash->valuelen = 20; + memcpy((info_hash->value = malloc(20)), h, 20); + binsert(a, info_hash); + struct bencoding * implied_port = bnum(1); + implied_port->key = bstr(strdup("implied_port")); + binsert(b, implied_port); + binsert(b, t); + struct sockaddr_in6 bound; + socklen_t size = sizeof bound; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wincompatible-pointer-types" + if (getsockname(d->socket, &bound, &size) == -1) + L(d->log, "getsockname: %s", strerror(errno)); + else { + struct bencoding * port = bnum(ntohs(bound.sin6_port)); + b->key = bstr(strdup("port")); + binsert(b, port); + } +#pragma GCC diagnostic pop + binsert(b, a); + sendb(d, b, addr); + free_bencoding(b); +} + /** * handles an incoming packet * @@ -943,11 +1103,11 @@ struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_fam */ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { - struct bdecoding * b = bdecode(pkt, len, replace); - struct bdecoding * v = bpath(b, "v"); + struct bencoding * b = bdecode(pkt, len, replace); + struct bencoding * v = bpath(b, "v"); char * node_ver = ""; char remote[INET_ADDRSTRLEN + INET6_ADDRSTRLEN + 7 + (v && v->type & string) ? v->valuelen : 0]; - if (!inet_ntop(addr.sa_family, &addr, remote, sizeof addr)) + if (!inet_ntop(addr.sin6_family, &addr, remote, sizeof addr)) { snprintf(remote, sizeof remote, "(inet_ntop: %s)", strerror(errno)); sprintf(remote+strlen(remote), ":%d", ntohs(addr.sin6_port)); } @@ -955,30 +1115,36 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { node_ver = v->value; sprintf(remote+strlen(remote), "-%s", node_ver); } - struct bdecoding * y = bpath(b, "y"); + struct bencoding * y = bpath(b, "y"); char * msg_type = ""; if (y && y->type & string) msg_type = y->value; switch (msg_type[0]) { case 'Q': case 'q': + ; struct bencoding * q = bpath(b, "q"); char * qtype = ""; if (q && q->type & string) qtype = q->value; struct bencoding * rid = bpath(b, "a/id"); - if (rid && rid->type & string && rid->valuelen == 20) + if (rid && rid->type & string && rid->valuelen == 20) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" potential_node(d, &addr, rid->value); +#pragma GCC diagnostic pop + } else { // see NOTE01 int len = b2json_length(b); char j[len+1]; b2json(j, b); j[len] = '\0'; - L("%s did not send a valid id in %s", remote, j); + L(d->log, "%s did not send a valid id in %s", remote, j); } switch (qtype[0]) { case 'P': // ping case 'p': + ; struct bencoding * id = calloc(1, sizeof *id); id->type = string; id->key = bstr(strdup("id")); @@ -988,75 +1154,100 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { r->key = bstr(strdup("r")); binsert(r, id); struct bencoding * y = bstr(strdup("r")); - y->key = bstr(strdup("y")); + y->key = bstr(strdup("y")); struct bencoding * response = calloc(1, sizeof *response); response->type = dict; binsert(response, y); binsert(response, r); binsert(response, bclone(bpath(b, "t"))); - sendb(d, response, &addr, addrlen); + sendb(d, response, &addr); free_bencoding(response); break; case 'F': // find_node case 'f': + ; struct bencoding * target = bpath(b, "a/target"); if (!target || !(target->type & string) || target->valuelen != 20) break; // see NOTE01 - struct bencoding * response = calloc(1, sizeof *response); + response = calloc(1, sizeof *response); response->type = dict; - struct bencoding * y = bstr(strdup("r")); + y = bstr(strdup("r")); y->key = bstr(strdup("y")); binsert(response, y); binsert(response, bclone(bpath(b, "t"))); - struct bencoding * r = calloc(1, sizeof *r); + r = calloc(1, sizeof *r); r->type = dict; - struct bencoding * id = calloc(1, sizeof *id); + id = calloc(1, sizeof *id); id->type = string; id->key = bstr(strdup("id")); memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20); binsert(r, id); binsert(response, r); - if (family(addr.sin6_addr.s6_addr) == AF_INET || bval(bpath("a/want"), "v4")) + if (family(addr.sin6_addr.s6_addr) == AF_INET || bval(bpath(b, "a/want"), bstrs("v4"))) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" binsert(response, nodes(d, target->value, AF_INET)); - if (family(addr.sin6_addr.s6_addr) == AF_INET6 || bval(bpath("a/want"), "v6")) { +#pragma GCC diagnostic pop + } + if (family(addr.sin6_addr.s6_addr) == AF_INET6 || bval(bpath(b, "a/want"), bstrs("v6"))) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" binsert(response, nodes(d, target->value, AF_INET6)); - sendb(d, response, &addr, addrlen); +#pragma GCC diagnostic pop + } + sendb(d, response, &addr); free_bencoding(response); break; case 'G': // get_peers case 'g': + ; struct bencoding * hash = bpath(b, "a/info_hash"); - if (!hash || !(hash->type & string) || target->valuelen != 20) + if (!hash || !(hash->type & string) || hash->valuelen != 20) break; // see NOTE01 - else + else { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" d->possible_torrent(d, hash->value); - struct bencoding * response = calloc(1, sizeof *response); +#pragma GCC diagnostic pop + } + response = calloc(1, sizeof *response); response->type = dict; - struct benncoding * y = bstr(strdup("r")); + y = bstr(strdup("r")); y->key = bstr(strdup("y")); binsert(response, y); binsert(response, bclone(bpath(b, "t"))); - struct bencoding * r = calloc(1, sizeof *r); + r = calloc(1, sizeof *r); r->type = dict; - struct bencoding * id = calloc(1, sizeof *id); + id = calloc(1, sizeof *id); id->type = string; id->key = bstr(strdup("id")); memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20); binsert(r, id); binsert(response, r); - if (family(addr.sin6_addr.s6_addr) == AF_INET || bval(bpath("a/want"), "v4")) - binsert(response, nodes(d, target->value, AF_INET)); - if (family(addr.sin6_addr.s6_addr) == AF_INET6 || bval(bpath("a/want"), "v6")) { - binsert(response, nodes(d, target->value, AF_INET6)); + if (family(addr.sin6_addr.s6_addr) == AF_INET || bval(bpath(b, "a/want"), bstrs("v4"))) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" + binsert(response, nodes(d, hash->value, AF_INET)); +#pragma GCC diagnostic pop + } + if (family(addr.sin6_addr.s6_addr) == AF_INET6 || bval(bpath(b, "a/want"), bstrs("v6"))) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" + binsert(response, nodes(d, hash->value, AF_INET6)); +#pragma GCC diagnostic pop + } +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" struct torrent * torrent = find_torrent(d, hash->value); +#pragma GCC diagnostic pop struct peer * peer = torrent->peers; struct bencoding * values = calloc(1, sizeof *values); values->type = list; - while (peer && i) { // TODO implement peer preference: prefer sending peers that responded to us + while (peer) { // TODO implement peer preference: prefer sending peers that responded to us if (family(peer->addr.sin6_addr.s6_addr) == family(addr.sin6_addr.s6_addr)) { // possible struct bencoding * value = calloc(1, sizeof *value); - memcpy((value->value = (value->valuelen = malloc(ADDRLEN(family(peer->addr.sin6_addr.s6_addr))+2))), peer->addr.sin6_addr.s6_addr, ADDRLEN(family(peer->addr.sin6_addr.s6_addr))); - memcpy(value->value+ADDRLEN(family(peer->addr.sin6_addr.s6_addr)), peer->addr.sin6_port, 2); + memcpy((value->value = malloc((value->valuelen = ADDRLEN(family(peer->addr.sin6_addr.s6_addr))+2))), peer->addr.sin6_addr.s6_addr, ADDRLEN(family(peer->addr.sin6_addr.s6_addr))); + memcpy(value->value+ADDRLEN(family(peer->addr.sin6_addr.s6_addr)), &peer->addr.sin6_port, 2); binsert(values, value); // possible stack overflow if there are a lot of peers, see limit in bdecode() wrapper } // TODO add a random IP address for plausible deniability peer = peer->next; @@ -1065,96 +1256,101 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { struct bencoding * tok = calloc(1, sizeof *tok); tok->type = string; tok->key = bstr(strdup("token")); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" token(d, (tok->value = malloc((tok->valuelen = 16))), addr.sin6_addr.s6_addr); +#pragma GCC diagnostic pop binsert(r, tok); - sendb(d, response, &addr, addrlen); + sendb(d, response, &addr); free_bencoding(response); break; case 'A': // announce case 'a': - struct bencoding * tok = bpath(b, "a/token"); + ; + tok = bpath(b, "a/token"); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" if (!tok || !(tok->type & string) || tok->valuelen != 16 || !valid(d, tok->value, addr.sin6_addr.s6_addr)) break; // see NOTE01 - struct bencoding * hash = bpath(b, "a/info_hash"); +#pragma GCC diagnostic pop + hash = bpath(b, "a/info_hash"); if (!hash || !(hash->type & string) || hash->valuelen != 20) break; // see NOTE01 - struct bencoding * response = calloc(1, sizeof *response); + response = calloc(1, sizeof *response); response->type = dict; binsert(response, bclone(bpath(b, "t"))); - struct bencoding * r = calloc(1, sizeof *r); + r = calloc(1, sizeof *r); r->type = dict; r->key = bstr(strdup("r")); - struct bencoding * id = calloc(1, sizeof *id); + id = calloc(1, sizeof *id); id->key = bstr(strdup("id")); id->type = string; memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20); binsert(r, id); binsert(response, r); - struct bencoding * y = bstr(strdup("r")); + y = bstr(strdup("r")); y->key = bstr(strdup("y")); binsert(response, y); - struct torrent * torrent = calloc(1, sizeof *torrent); + torrent = calloc(1, sizeof *torrent); memcpy(torrent->hash, hash->value, 20); torrent = add_torrent(d, torrent); - struct peer * peer = calloc(1, sizeof *peer); + peer = calloc(1, sizeof *peer); memcpy(&peer->addr, &addr, sizeof addr); - if (bpath(b, "a/port") && !bpath(b, "a/implied_port") || !bpath(b, "a/implied_port")->intvalue) + if (bpath(b, "a/port") && (!bpath(b, "a/implied_port") || !bpath(b, "a/implied_port")->intvalue)) peer->addr.sin6_port = htons(bpath(b, "a/port")->intvalue); add_peer(d, torrent, peer); - sendb(response); + sendb(d, response, &addr); free_bencoding(response); break; default: // see NOTE01 + ; int len = b2json_length(b); char json[len+1]; b2json(json, b); json[len] = '\0'; - L(d->log, "%s sent an unknown query type: %s"); + L(d->log, "%s sent an unknown query type: %s", remote, json); break; } break; case 'R': // we only ever query and expect responses to get_peers and find_node, so it's egal - case 'r': - struct bencoding * rid = bpath(b, "r/id"); - if (rid && rid->type & string && rid->valuelen == 20) - replied(d, rid->value, &addr); // since here I'm only really interested about nodes and values + case 'r': + ; + rid = bpath(b, "r/id"); + if (rid && rid->type & string && rid->valuelen == 20) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" + replied(d, rid->value, &addr); // since here I'm only really interested about nodes and values or +#pragma GCC diagnostic pop + } struct bencoding * t = bpath(b, "t"); struct torrent * torrent = NULL; - if ((t && t->type & string && t->valuelen == 20) && (torrent = find_torrent(d, t->value)) && torrent->type) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-sign" + if ((t && t->type & string && t->valuelen == 20) && memcmp(d->id, t->value, 20) && (torrent = find_torrent(d, t->value)) && torrent->type) { +#pragma GCC diagnostic pop bforeach (bpath(b, "r/values"), p) { if (!(p->type & string) || (p->valuelen != 6 && p->valuelen != 18)) break; struct peer * peer = calloc(1, sizeof *peer); - memcpy(peer->addr.sin6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\xFF\xFF\xFF\xFF", 12); + memcpy(peer->addr.sin6_addr.s6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\xFF\xFF\xFF\xFF", 12); peer->addr.sin6_port = *((uint16_t *) (p->value + p->valuelen-2)); - memcpy(peer->addr.sin6_addr+(p->valuelen == 6 ? 8 : 0), p->value, p->valuelen == 6 ? 4 : 16); + memcpy(peer->addr.sin6_addr.s6_addr+(p->valuelen == 6 ? 8 : 0), p->value, p->valuelen == 6 ? 4 : 16); add_peer(d, torrent, peer); } - bforeach (bpath(b, "r/nodes" /* haha subreddit */), n) { - if (!(n->type & string) || (n->valuelen != 4+2+20 && n->valuelen != 16+2+20)) - break; - struct node * node = node_init(); - memcpy(node->addr.sin6_addr, "\0\0\0\0\0\0\0\0\0\0\0\0\xFF\xFF\xFF\xFF", 12); - node->addr.sin6_port = *((uint16_t *) (n->value + n->valuelen-2)); - memcpy(node->addr.sin6_addr+(n->valuelen == 4+2+20 ? 8 : 0), n->value + 20, n->valuelen == 4+2+20 ? 4 : 16); - memcpy(node->id, n->value, 20); - potential_node(d, &node->addr, id); // NOTE02 this is quite important and means that at the beginning, a lot of packets will be sent, since every reply of potential_node will generate K replies. naively this would generate an exponentially increasing number of packets, in increasing powers of 8 (8**n). to prevent an absolute resource hog, this is only done when node would be useful and would contribute to the routing table - if (torrent) { // TODO add node into list of nodes, replacing dead nodes. if there are no dead nodes, replace the node that's farthest away if this node is closer. - int i = 0; - struct node ** replaceable = NULL; - struct node ** index = &torrent->nodes; - while (*index) { - if (node_grade(*index) != good) { - * - } - *index = &(*index)->next; - } - } else - node_free(node); + bforeach (bpath(b, "r/nodes" /* haha subreddit */), n) + if (n->type & string) + compact(d, n->value, n->valuelen, torrent); + bforeach(bpath(b, "r/nodes6"), n) + if (n->type & string) + compact(d, n->value, n->valuelen, torrent); + if (torrent->type & announce) + announce_peer(d, &addr, bclone(bpath(b, "r/token")), torrent->hash); } + break; case 'E': case 'e': - struct bdecoding * e = bpath(b, "e"); + ; + struct bencoding * e = bpath(b, "e"); char * errtype = "Unspecified Error"; if (e && e->child) switch (e->child->intvalue) { @@ -1180,15 +1376,90 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { L(d->log, "%s sent %s%s%s", remote, errtype, msg ? ": " : "", msg ? msg : ""); break; default: // NOTE01 sending an error is unfortunately bad in this case, since clever hackers can force two servers speaking entirely different UDP based protcols into sending error messages to each other, telling one another that they don't understand each other's messages. + ; int len = b2json_length(b); char json[len+1]; b2json(json, b); json[len] = '\0'; - L(dht->log, "%s sent an unknown type: %s"); + L(d->log, "%s sent an unknown type: %s", remote, json); // send_error(d, b, &addr, addrlen, 203, "unknown type"); break; } - struct bdecoding * trans_id = bpath(b, "t"); + free_bencoding(b); +} + +/** + * do periodic housekeeping on the routing table LL, making sure no nodes are bad. removes bad nodes and does not ping questionable nodes. see NOTE03 + * + * @param b [in] first bucket in LL - basically either d->buckets or d->buckets6 + */ + +void refresh (struct bucket * b) { + struct node ** n = &b->nodes; + while (*n) { + switch (node_grade(*n)) { + case bad: + ; + struct node * old = *n; + *n = (*n)->next; + node_free(old); + break; + case questionable: + // ping_node(d, *n); // NOTE03 about not pinging questionable nodes: this ensures a constant regeneration of the routing table. this is just an idea, if the client frequently gets in a situation without any nodes in the routing table, remove the comment before ping_node call. + break; + case good: + break; + } + n = &(*n)->next; + } +} + +/** + * sends a get_peers query to a raw node + * + * @param d [in] handle + * @param a [in] address + * @param q [in] 20 byte hash we query for + */ + +void get_peers (struct dht * d, const struct sockaddr_in6 * addr, const unsigned char * q) { + struct bencoding * b = calloc(1, sizeof *b); + b->type = dict; + struct bencoding * t = calloc(1, sizeof *t); + memcpy((t->value = malloc(20)), q, (t->valuelen = 20)); + t->key = bstr(strdup("t")); + t->type = string; + binsert(b, t); + struct bencoding * y = bstr(strdup("q")); + t->key = bstr(strdup("y")); + t->type = string; + binsert(b, y); + struct bencoding * q_elem = bstr(strdup("get_peers")); + q_elem->key = bstr(strdup("q")); + q_elem->type = string; + binsert(b, q_elem); + struct bencoding * a = calloc(1, sizeof *a); + a->type = dict; + struct bencoding * id = calloc(1, sizeof *id); + id->type = string; + id->valuelen = 20; + id->key = bstr(strdup("key")); + memcpy((id->value = malloc(20)), d->id, 20); + binsert(a, id); + struct bencoding * want = calloc(1, sizeof *want); // BEP-0032 + want->key = bstr(strdup("want")); + want->type = list; + binsert(want, bstr(strdup("n4"))); + binsert(want, bstr(strdup("n6"))); + binsert(a, want); + struct bencoding * info_hash = calloc(1, sizeof *info_hash); + info_hash->key = bstr(strdup("info_hash")); + info_hash->type = string; + info_hash->valuelen = 20; + memcpy((info_hash->value = malloc(20)), q, 20); + binsert(a, info_hash); + binsert(b, a); + sendb(d, b, addr); free_bencoding(b); } @@ -1196,24 +1467,23 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { * does periodic work for the library, called every 13 minutes * * namely, it sends UDP packets: - * - announcing all torrents with announce * - searching deeper DHT storage nodes for torrents with peers and announce - * - get_peers on torrents with peers + * - get_peers on torrents with peers or announce. when a response is received for a torrent with announce, an announce will be sent as well * * this can be a lot of packets, so please keep number of torrents with peers and announce low */ void periodic (struct dht * d) { - struct torrent * t; + refresh(d->buckets); + refresh(d->buckets6); + struct torrent * t = d->torrents; while (t) { - if (t->type & announce) { - // TODO - } if (t->type & (peers | announce)) { - // TODO - } - if (t->type & peers) { - // TODO + struct node * n = t->nodes; + while (n) { + get_peers(d, &n->addr, t->hash); + n = n->next; + } } t = t->next; } @@ -1237,8 +1507,11 @@ void work (struct dht * d) { char packet[65536]; struct sockaddr_in6 addr; socklen_t addrlen = sizeof addr; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wincompatible-pointer-types" int ret = recvfrom(d->socket, packet, 65536, MSG_DONTWAIT | MSG_TRUNC, &addr, &addrlen); - if (addrlen != sizeof add) +#pragma GCC diagnostic pop + if (addrlen != sizeof addr) L(d->log, "addrlen changed, not parsing packet"); else if (ret > 65536) L(d->log, "recvfrom()d larger packet than 65536, not parsing packet"); @@ -1247,6 +1520,9 @@ void work (struct dht * d) { L(d->log, "recvfrom(): %s", strerror(errno)); else periodic(d); - } else + } else { + d->rxp++; + d->rxb += ret; handle(d, packet, ret, addr); + } } diff --git a/src/main.c b/src/main.c index 74a9d1d..e8debe6 100644 --- a/src/main.c +++ b/src/main.c @@ -1,13 +1,5 @@ -/* system libraries */ #include #include #include - -/* my code */ -#include -#include - -int main (int argc, char ** argv) { - char * val free_char_after = malloc(16); - return argv ? argc : 69; +int main (void) { } -- cgit v1.2.3