diff options
Diffstat (limited to 'src/dht.c')
-rw-r--r-- | src/dht.c | 388 |
1 files changed, 335 insertions, 53 deletions
@@ -32,7 +32,7 @@ int family (const char * addr) { */ struct node { - char id[20]; + unsigned char id[20]; struct sockaddr_in6 addr; int unanswered; /**< number of packets I've sent since last_received */ time_t last_received; /**< time when I received the last packet from it */ @@ -49,7 +49,6 @@ struct node * node_init () { if (!n) return NULL; n->last_received = seconds(); - n->last_sent = seconds(); return n; } @@ -64,11 +63,32 @@ void node_free (struct node * n) { } /** + * returns which 20 byte bytestring is closer with XOR metric to target 20 byte bytestring + * + * at most 20 bytes are read from each pointer + *{ + * @param a [in] 20 byte to consider + * @param b [in] 20 byte string to consider + * @param t [in] target + * @return 0 if a is closer or 1 if b is closer, -1 if both are the same + */ + +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]) + return 0; + if (a[i] ^ t[i] > b[i] ^ t[i]) + return 1; + } + return -1; +} + +/** * bucket representation */ struct bucket { - char id[20]; /**< bucket spans from id inclusive to next->id exclusive */ + unsigned char id[20]; /**< bucket spans from id inclusive to next->id exclusive */ struct node * nodes; struct bucket * next; }; @@ -107,6 +127,7 @@ 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 */ }; /** @@ -133,12 +154,14 @@ enum torrent { */ struct torrent { - enum torrent type; - char hash[20]; /**< infohash */ + enum torrent 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 DHT nodes to this hash */ - char pieces[]; /**< when checking a torrent, this is filled. every piece is one bit. TODO */ + 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,17 +197,35 @@ int torrent_compare (const void * a, const void * b) { */ struct dht { - char id[20]; /**< own id */ + unsigned char id[20]; /**< own id */ int socket; /**< v4&v6 UDP socket that is bound on UDP and sends to nodes */ - char secret[16]; /**< for calculating opaque write token, random */ + unsigned char secret[16]; /**< for calculating opaque write token, random */ FILE * log; /**< FILE to log to, defaults to stderr */ struct bucket * buckets; struct bucket * buckets6; /**< IPv6 routing table */ - struct torrent ** torrents; /**< binary tree of torrents for which we want to know peers */ + struct torrent * torrents; /**< linked list of torrents for which we want to know peers */ 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_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 */ }; /** + * a dummy function that does nothing that is set as the default for possible_torrent in struct dht + * + * @param d [in] the dht library handler + * @param h [in] the infohash of the found torrent + */ + +void possible_torrent (struct dht *, const unsigned char * h) { + return; +} + +/** * creates a handle. you can override log in the result struct. * * this function does not log, as log fd is not known yet @@ -201,6 +242,8 @@ struct dht * dht_init (const struct bencoding * c) { d->log = stderr; d->dl = -1; d->buckets = bucket_init(); + d->buckets6 = bucket_init(); + d->possible_torrent = &possible_torrent; errno = 0; if (!d) return NULL; @@ -256,6 +299,18 @@ void dht_free (struct dht * d) { bucket = bucket->next; bucket_free(old); } + struct bucket * bucket6 = d->buckets6; + while (bucket6) { + struct bucket * old = bucket6; + bucket6 = bucket6->next; + bucket_free(old); + } + struct torrent * torrent = d->torrents; + while (torrent) { + struct torrent * old = torrent; + torrent = torrent->next; + torrent_free(old); + } free(d); } @@ -304,13 +359,13 @@ struct bencoding * persistent (const struct dht * d) { * * @param d [in] used to obtain the secret key * @param t [out] the destination to which to write the 16 bytes - * @param a [in] the node's IP address, from which get_peers was received + * @param a [in] 16 bytes of the node's IP address, from which get_peers was received - addr.sin6_addr.s6_addr * @param l [in] the length of socket address struct a */ -void token (const struct dht * d, char * t, struct sockaddr_in6 * a) { +void token (const struct dht * d, unsigned * t, const char * addr) { struct AES_ctx aes; - memcpy(t, a->sin6_addr, 16); + memcpy(t, addr, 16); AES_init_ctx(&aes, dht->secret); AES_ECB_encrypt(&aes, t); } @@ -320,12 +375,12 @@ void token (const struct dht * d, char * t, struct sockaddr_in6 * a) { * * @param d [in] used to obtain the secret key * @param t [in] the address from which to obtain the 16 byte token - * @param a [in] the node's IP address, from which announce was received + * @param a [in] 16 bytes of the node's IP address, from which announce was received - addr.sin6_addr.s6_addr * @param l [in] the length of socket address struct a * @return 1 if the token is valid for this node, 0 otherwise */ -int valid (const struct dht * d, const char * t, struct sockaddr_in6 * a) { +int valid (const struct dht * d, const char * t, const char * addr) { char try[16]; memcpy(try, t, 16); token(d, try, a, l); @@ -394,7 +449,7 @@ void send_error (const struct dht * d, const struct bencoding * b, struct sockad * @return 1 if belongs to a bucket, 0 otherwise */ -int in_bucket (const char * id, const struct bucket * b) { +int in_bucket (const unsigned char * id, const struct bucket * b) { return memcmp(id, b->id, 20) >= 0 && (!b->next || memcmp(id, b->next->id, 20) < 0); } @@ -407,7 +462,7 @@ int in_bucket (const char * id, const struct bucket * b) { * @return the pointer to the node or NULL if not found */ -struct node * find (const char * id, struct bucket ** b, struct ** n) { +struct node * find (const unsigned char * id, struct bucket ** b, struct ** n) { while (!in_bucket(id, *b)) *b = (*b)->next; struct node * node = (*b)->nodes; @@ -420,6 +475,63 @@ struct node * find (const char * id, struct bucket ** b, struct ** n) { } /** + * find the middle point of a bucket/or two 20 byte bytestrings + * + * @param r [out] midpoint + * @param a [in] lower boundary + * @param b [in] upper boundary. if NULL, 0xffffffffffffffffffffffffffffffffffffffff is assumed + */ + +void midpoint (unsigned char * r, const unsigned char * a, const unsigned char * b) { + unsigned char up[20]; + for (int i = 0; i < 20; i++) + up[i] = 0xFF; + if (b) + memcpy(up, b, 20); + unsigned carry = 0; + for (int i = 19; i >= 0; i--) { + if (carry + (unsigned) up[i] < (unsigned) a[i]) { + r[i] = (unsigned) up[i] + 255 - (unsigned) a[i]; + carry = 1; + } else { + r[i] = (unsigned) up[i] - (unsigned) a[i]; + carry = 0; + if (r[i] & 1 && i != 19) + r[i+1] |= 1 << 7; + r[i] >>= 1; + } + } + 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; + carry = 1; + } else { + t[i] = t[i] + a[i]; + carry = 0; + } + } +} + +/** + * splits a bucket + * + * @param b [in] the bucket to split + */ + +void split (struct bucket * b) { + struct bucket * new = bucket_init(); + 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; + 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. @@ -431,15 +543,43 @@ struct node * find (const char * id, struct bucket ** b, struct ** n) { * @param addr [in] address from which the id was received */ -void replied (const struct dht * d, const char * id, const struct sockaddr_in6 * addr) { +void replied (const struct dht * d, const unsigned char * id, const struct sockaddr_in6 * addr) { struct bucket * b = d->buckets; 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 } - } /** @@ -454,7 +594,7 @@ void replied (const struct dht * d, const char * id, const struct sockaddr_in6 * */ void ping_node (const struct dht * d, const struct sockaddr_in6 * a) { - char target[20]; + 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 @@ -471,7 +611,7 @@ void ping_node (const struct dht * d, const struct sockaddr_in6 * a) { * @param query [in] 20 byte id we are querying */ -void find_node (const struct dht * d, const struct sockaddr_in6 * a, const char * query) { +void find_node (const struct dht * d, const struct sockaddr_in6 * a, const unsigned char * query) { struct bencoding * b = calloc(1, sizeof *b); b->type = dict; struct bencoding * t = bstr(strdup("t@_a.si")); @@ -533,8 +673,8 @@ int node_count (const struct node * n) { * TODO: test util */ -unsigned int distance (const char * a, const char * b) { - char xor[20]; +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++) { xor[i] ^= b[i]; @@ -610,7 +750,7 @@ 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 char * id) { +void potential_node (const 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 = b->buckets6; @@ -621,44 +761,115 @@ void potential_node (const struct dht * d, const struct sockaddr_in6 * a, const } /** + * find a torrent based on hash + * + * @param d [in] the library handle + * @param h [in] a 20 byte infohash + * @return pointer to torrent or NULL + */ + +struct torrent * find_torrent (struct dht * d, const unsigned char * h) { + const struct torrent * t = d->torrents; + while (t) { + if (!memcmp(t->hash, h, 20)) + return t; + t = t->next; + } + return NULL; +} + +/** + * what to do when there are too many torrents and their peers stored, used in add_peer and add_torrent + * + * removes last added torrent that wasn't manually added + * + * @param d [in] libhandle + */ + +void oom (struct dht * d) { + struct torrent * drop = d->last_torrent; + while (drop && drop->type) + drop = drop->prev; + remove_torrent(drop); +} + +/** * adds a torrent to a list of torrents * - * if the torrent already exists in the database flags of this one will be anded with the flags of the old one, meaning this function can be used to set keep, announce, info and dl flags. see @return for important details. + * if the torrent already exists in the database flags of this one will be anded with the flags of the old one, meaning this function can be used to set peers, announce, info and dl flags. see @return for important details. * - * @param d [in] dht library handler + * @param d [in] dht library handler, for counting torrents in storage * @param t [in] torrent object, whose memory ownership is transfered to the library and must be heap allocated * @return the new pointer to the torrent. if the torrent is already in the storage, the passed torrent will be freed, so the return value must be checked if you intend to use the torrent weiter */ struct torrent * add_torrent (struct dht * d, struct torrent * t) { - return *(struct torrent **) tsearch(t, &d->torrents, torrent_compare); + struct torrent * found = find_torrent(d, t->hash); + if (found) { + found->type |= t->type; + torrent_free(t); + return found; + } + if (d->torrents) + d->torrents->prev = t; + else + d->last_torrent = t; + t->prev = NULL; + t->next = d->torrents; + d->torrents = t; + d->torrents++; + if (d->torrents >= d->torrents_max) + oom(d); + return t; } /** - * deletes a torrent from storage. if you downloaded a torrent and set keep/announce flags, do not remove_torrent once you're done with it, but instead just clear keep/announce bits. this will remove the torrent when necessary. + * 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) { - tdelete(t, &d->dht->torrents, torrent_compare); - free(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); } /** - * find a torrent based on hash + * 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. * - * @param d [in] the library handle - * @param h [in] a 20 byte infohash + * @param d [in] library handle, for counting peers + * @param t [in] torrent + * @param p [in] peer to add + * @param this peer in storage. could be different if old one was freed, so discard value that you passed in and replace it with this value. memory ownership is NOT transfered from storage to caller */ -struct torrent * find_torrent (struct dht * d, const char * h) { - struct torrent t; - memcpy(t.hash, h, 20); - const struct torrent ** t = tfind(&t, &d->torrents, torrent_compare); - if (t) - return *t; +struct peer * add_peer (struct dht * d, struct torrent * t, struct peer * p) { + struct peer * peer = torrent->peers; + while (peer) + if (!memcmp(&peer->addr, &addr, sizeof addr)) { + free(p); + return peer; + } + peer->next = torrent->peers; + torrent->peers = peer; + d->peers++; + if (d->peers >= d->peers_max) + oom(d); + return peer; } /** @@ -670,7 +881,7 @@ struct torrent * find_torrent (struct dht * d, const char * h) { * @return bencoding object whose memory ownership and free responsibility is transfered to the caller */ -struct bencoding * nodes (const struct dht * d, const char * id, sa_family_t f) { +struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_family_t f) { struct bencoding * nodes = calloc(1, sizeof *nodes); nodes->type = list; nodes->key = bstr(strdup(f == AF_INET ? "nodes" : "nodes6")); @@ -738,16 +949,16 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { struct bencoding * rid = bpath(b, "a/id"); if (rid && rid->type & string && rid->valuelen == 20) potential_node(d, &addr, rid->value); + 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); + } switch (qtype[0]) { case 'P': // ping case 'p': - 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); - } struct bencoding * id = calloc(1, sizeof *id); id->type = string; id->key = bstr(strdup("id")); @@ -776,7 +987,7 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { struct bencoding * y = bstr(strdup("r")); y->key = bstr(strdup("y")); binsert(response, y); - binsert(response, bclone(bpath(b, "r"))); + binsert(response, bclone(bpath(b, "t"))); struct bencoding * r = calloc(1, sizeof *r); r->type = dict; struct bencoding * id = calloc(1, sizeof *id); @@ -796,12 +1007,14 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { struct bencoding * hash = bpath(b, "a/info_hash"); if (!hash || !(hash->type & string) || target->valuelen != 20) break; // see NOTE01 + else + d->possible_torrent(d, hash->value); struct bencoding * response = calloc(1, sizeof *response); response->type = dict; struct benncoding * y = bstr(strdup("r")); y->key = bstr(strdup("y")); binsert(response, y); - binsert(response, bclone(bpath(b, "r"))); + binsert(response, bclone(bpath(b, "t"))); struct bencoding * r = calloc(1, sizeof *r); r->type = dict; struct bencoding * id = calloc(1, sizeof *id); @@ -814,9 +1027,60 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { 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)); - // TODO: token, peers + struct torrent * torrent = find_torrent(d, hash->value); + 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 + 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); + 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; + } + binsert(r, values); + struct bencoding * tok = calloc(1, sizeof *tok); + tok->type = string; + tok->key = bstr(strdup("token")); + token(d, (tok->value = malloc((tok->valuelen = 16))), addr.sin6_addr.s6_addr); + binsert(r, tok); sendb(d, response, &addr, addrlen); break; + case 'A': // announce + case 'a': + struct bencoding * tok = bpath(b, "a/token"); + 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"); + if (!hash || !(hash->type & string) || hash->valuelen != 20) + break; // see NOTE01 + struct bencoding * response = calloc(1, sizeof *response); + response->type = dict; + binsert(response, bclone(bpath(b, "t"))); + struct bencoding * r = calloc(1, sizeof *r); + r->type = dict; + r->key = bstr(strdup("r")); + struct bencoding * 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->key = bstr(strdup("y")); + binsert(response, y); + sendb(response); // first we send confirmation, then we store + struct torrent * torrent = calloc(1, sizeof *torrent); + memcpy(torrent->hash, hash->value, 20); + torrent = add_torrent(d, torrent); + struct 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) + peer->addr.sin6_port = htons(bpath(b, "a/port")->intvalue); + add_peer(d, torrent, peer); + break; default: // see NOTE01 int len = b2json_length(b); char json[len+1]; @@ -828,6 +1092,7 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { break; case 'R': case 'r': + // TODO break; case 'E': case 'e': @@ -874,12 +1139,29 @@ void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) { * * namely, it sends UDP packets: * - announcing all torrents with announce - * - searching deeper DHT storage nodes for torrents with keep and announce - * - get_peers on torrents with keep + * - searching deeper DHT storage nodes for torrents with peers and announce + * - get_peers on torrents with peers * - * this can be a lot of packets, so please keep number of torrents with keep and announce low + * 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; + while (t) { + if (t->type & announce) { + // TODO + } + if (t->type & (peers | announce)) { + // TODO + } + if (t->type & peers) { + // TODO + } + t = t->next; + } + return; +} + /** * does work; syncs with the network, handles incoming queries. * |