summaryrefslogblamecommitdiffstats
path: root/src/dht.c
blob: b4b3cbf29775619123f6259b200827dd00725324 (plain) (tree)
1
2
3
4
5
6
7
8
9
10









                       

                   










                                            

                                                                                     







                      
             
                             
                                 



                                                                                  










                                               
                 








                                            



                




















                                                                                          



                        
                                                                                          

                             










                                                 


















                                              





                                                                  
                                                                                                                

























                                                                                                

                                                                             

                                                                                                 



                                                                                                                                  






























                                                                                                  



                         
                                            
                                                                                    
                                                                                    

                                                              
                                                            
                                                                                                  
                                                                              






                                                                                                                                                                             
                                                                                                                                 
  
 
   










                                                                                                   
                                                               





                                                                                             

                                                                                                                                                                                                                                      

   
                                                    

                                              

                                   

                                                


                                                                                                                            















                                                                                   



                                                                 
                                                   


                                                                   






                                                                              

                 







                                                                                                                                                            













                                                                                                                                                                                                               











                                               



                











                                                                                                                        
























                                                                                        


   



                                                                                                         
                                                                                                                     


                                                             
                                                                    
                           
                            
                                      







                                                                                                                                                
                                                                                                                    



                                                             
                                                                     



































































                                                                                                                                                                                              
                                                                   











                                                                                                                                                                                                                                                                                                                   
                                                                                











                                                  
























































                                                                                                      



                                                                                                                                                                                         
                                                                                       





                                                              
                                                                                                 
                                       

                                                        




                                                 




























                                                                                                                                  
         


   
                                         


                                                                                                                                                                                                                                                                            

                                                                                                                                                                                           
                                      
                                       

   
                                                                      
                                 




                                                                                       
                                      


   
                                          

                              

                                                  
                                                                                                                                                                                                                       

   
                                                                                                                         

                                                    





                                            
















                                                         





                                                                      































                                                                                                                

                                                                          






























                                                                                


   

































                                                                                                                                                                                                                                           
                                                                                                                                                                                                                                                                                                                                                                                                                                   
  

             
                                      
                                                       
                                                                          

   
                                                                                                     
                                            
                                                     
                                     

                                    
                                  

                                

   
































                                                                                                       

                                       
                                                                                                                                                                                                                               
  
                                                                             




                                                                                                                                                                                                  
















                                                          


   
                                                                                                                                                                                                                                     





                                                                                                                                                                   














                                          


   
                                                                                                                                                                                    
  



                                                                                                                                                                                                      

   

                                                                              

                       
                                                               
                                     

                                    






                                                              





                                     


   







                                                                                                                                                                
                                                                                          































                                                                                                             































                                                                                                        


                                                                             






                                                                                 


                                                 

                                                                                      
                                                                     

                                                                                                     




                                                                                 
                                                                                                  






                                                                                 









                                                                                                          
                                                                                 












                                                                                                                        
                                                                 





                                                                                                      

                                                                                    




                                                                                                  
                                                                                 











                                                                                                                        


















                                                                                                                                                                                                                                          
                                                                           
                                                                 
                                              






















                                                                                                                                                  







                                                                                                                                       

                                                                 
                                              




                                                                   
                                                                                       


                                              
                                                                                                             
                         



                                                                                                                              










                                                                                                                                     


                                                                                                             








                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
                         


































                                                                                                                                                                                                                                                                                                 
         

                                                    


   



                                                              

                                                                                 
  
                                                                                              

   
















                                                   

                                                               


                                                                      





                                                                                                                                                      










                                                                                                
                           

                                                                     



                                             
 
#include <time.h>
#include <sys/random.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <limits.h>
#include <search.h>
#define ECB 1
#define AES128 1
#include <aes.c>
#include <bencoding.c>

time_t seconds () {
	struct timespec tp;
	clock_gettime(CLOCK_MONOTONIC, &tp);
	return tp.tv_sec;
}

int family (const char * addr) {
	return memcmp("\0\0\0\0\0\0\0\0\0\0\xFF\xFF", addr, 12) ? AF_INET6 : AF_INET;
}

#define K 8

/**
 * node representation
 */

struct node {
	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 */
	time_t last_sent; /**< time when I sent the last packet to it */
	struct node * next;
};

/**
 * creates a new node
 */

struct node * node_init () {
	struct node * n = calloc(1, sizeof *n);
	if (!n)
		return NULL;
	n->last_received = seconds();
	return n;
}

/**
 * frees a node
 *
 * @param n	[in]	the node to be freed
 */

void node_free (struct node * n) {
	free(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 {
	unsigned char id[20]; /**< bucket spans from id inclusive to next->id exclusive */
	struct node * nodes;
	struct bucket * next;
};

/**
 * creates a new bucket
 */

struct bucket * bucket_init () {
	struct bucket * b = calloc(1, sizeof *b);
	if (!b)
		return NULL;
	return b;
}

/**
 * frees a bucket
 *
 * @param b	[in]	the bucket to be freed
 */

void bucket_free (struct bucket * b) {
	struct node * node = b->nodes;
	while (node) {
		struct node * old = node;
		node = node->next;
		node_free(old);
	}
	free(b);
}

/**
 * peer of a torrent
 */

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 */
};

/**
 * free a torrent peer
 */

void peer_free (struct peer * p) {
	free(p);
}

/**
 * reason why a torrent is in our database. 0 just means it is stored as a result of an announce
 */

enum torrent {
	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 */
	dl = 1 << 3 /**< download torrent content into `dht->dl`/$hash.blob TODO */
};

/**
 * torrent we are interested in
 */

struct torrent {
	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 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 */
};

/**
 * free a torrent object and it's nodes and peers
 */

void torrent_free (struct torrent * t) {
	struct node * n = t->nodes;
	while (n) {
		struct node * old = n;
		n = n->next;
		node_free(n);
	}
	struct peer * p = t->peers;
	while (p) {
		struct peer * old = p;
		p = p->next;
		peer_free(old);
	}
	free(t);
}

/**
 * compares two torrent objects based on their hash
 */

int torrent_compare (const void * a, const void * b) {
	return memcmp(((const struct torrent *) a)->hash, ((const struct torrent *) b)->hash, 20);
}

/**
 * handle for the library
 */

struct dht {
	unsigned char id[20]; /**< own id */
	int socket; /**< v4&v6 UDP socket that is bound on UDP and sends to nodes */
	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; /**< 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 */
	unsigned peers_per_torrent_max; /**< max number of peers to store per torrent - applies to ->type and !->type torrents */
};

/**
 * 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
 *
 * socket must be close()d before being overriden, if the caller wants to use custom binding.
 *
 * binds UDP to all ifaces
 *
 * @param c	[in]	bencoding object containing the persistent config file, generated from a previous run with persistent(). memory ownership is NOT transfered, it's the caller's responsibility to free the object. can be NULL.
 */

struct dht * dht_init (const struct bencoding * c) {
	struct dht * d = calloc(1, sizeof *d);
	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_per_torrent_max = UINT_MAX;
	errno = 0;
	if (!d)
		return NULL;
	if (getrandom(d->id, 20, GRND_NONBLOCK) == -1)
		goto e;
	if (getrandom(d->secret, 16, GRND_NONBLOCK) == -1)
		goto e;
	d->socket = socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
	if (d->socket == -1)
		goto e;
	struct sockaddr_in6 a = {
		sin6_family = AF_INET6,
		sin6_addr = in6addr_any
	};
	if (bind(d->socket, &a, sizeof a) == -1)
		goto e;
	if (c) {
		const struct bencoding * id = bpath(c, "id");
		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, ':');
			if (port) {
				if (inet_pton(AF_INET6, remote, &addr) == 1) {
					addr.sin6_port = htons(atoi(++port));
					ping_node(d, &addr);
				}
			}
		}
	}
	return d;
	e:
	free(d);
	return NULL;
}

/**
 * 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)
			L(d->log, "close(d->socket) == -1");
	struct bucket * bucket = d->buckets;
	while (bucket) {
		struct bucket * old = bucket;
		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);
}

/**
 * generate a bencoding struct containing the persistent storage config
 *
 * this config contains:
 * 	- nodes from the routing table that can be used to bootstrap into the dht net
 * 	- this node's id
 *
 * please make sure that you do not start two nodes from the same config
 *
 * @param d	[in]	library handle
 * @return bencoding object, whose memory ownership is transfered to the caller, which must call bencoding_free() on it.
 */

struct bencoding * persistent (const struct dht * d) {
	struct bencoding * b = calloc(1, sizeof *b);
	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);
	id->key = bstr(strdup("id"));
	binsert(b, id);
	struct bencoding * nodes = calloc(1, sizeof *nodes);
	nodes->type = list;
	struct bucket * bucket = d->buckets;
	while (bucket) {
		struct node * node = bucket->nodes;
		while (node) {
			char remote[INET6_ADDRSTRLEN + 7];
			if (inet_ntop(AF_INET6, &node->addr, remote, sizeof node->addr))
				binsert(nodes, bstr(strdup(remote)));
			node = node->next;
		}
		bucket = bucket->next;
	}
	binsert(b, nodes);
	return b;
}

/**
 * generates a 16 byte token for allowing a node to store it's IP addres in our node. verify with valid()
 *
 * @param d	[in]	used to obtain the secret key
 * @param t	[out]	the destination to which to write the 16 bytes
 * @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, unsigned * t, const char * addr) {
	struct AES_ctx aes;
	memcpy(t, addr, 16);
	AES_init_ctx(&aes, d->secret);
	AES_ECB_encrypt(&aes, t);
}

/**
 * verifies a 16 byte token, if it was really generated with token(), to prevent unsolicited adding of IPs to storage with src ip addr spoofing.
 *
 * @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]	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, const char * addr) {
	char try[16];
	memcpy(try, t, 16);
	token(d, try, a, l);
	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.
 *
 * @param d	[in]	the dht library handle, for logging and for socket fd
 * @param b	[in]	the incoming packet that caused the error, to get key t
 * @param a	[in]	address of the incoming packet to which an error is sent
 * @param num	[in]	error number, as specified by BEP-0005
 * @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) {
	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"));
	struct bencoding * response = calloc(1, sizeof *response);
	binsert(response, y);
	binsert(response, e);
	binsert(response, bpath(b, "t"));
	sendb(d, response, a);
	free_bencoding(response);
}

/**
 * decides if a node id belongs to a bucket or not. this does not actually check the bucket for it's contents, just the ranges.
 *
 * @param id	[in]	the node id
 * @param b	[in]	the bucket
 * @return 1 if belongs to a bucket, 0 otherwise
 */

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);
}

/**
 * searches for a stored node based on id
 *
 * @param id	[in]	the node id
 * @param b		pointer to a variable containing a pointer to the first bucket in ll. after the call the value at this pointer is overwritten to the bucket that should contain this node. since it's overwritten, do NOT just pass &dht->buckets. do struct bucket * b = dht->buckets and pass &b instead.
 * @param n	[out]	the node directly before the searched for node. NULL is written if this node would be placed at the start of the bucket. NULL may be passed without consequences.
 * @return the pointer to the node or NULL if not found
 */

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;
	struct prev = NULL;
	while (node && memcmp(node->id, id) < 0) {
		prev = node;
		node = node->next;
	}
	*n = prev;
}

/**
 * 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.
 *
 * 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
 *
 * @param n	[in]	first node in ll
 */

int node_count (const struct node * n) {
	int c = 0;
	while (n) {
		c++;
		n = n->next;
	}
	return c;
}

/**
 * returns the distance between two ids. if it cannot be represented with an unsigned int, UINT_MAX is returned.
 *
 * TODO: test util
 */

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];
		if (i < 20-sizeof unsigned && xor[i])
			return UINT_MAX;
	}
	unsigned r = 0;
	for (int i = 0; i < sizeof unsigned; i++)
		r |= xor[i] << (sizeof unsigned - 1 - i) * 8;
}

enum node_grade {
	good,
	bad,
	questionable
};

/**
 * determines if node is considered good, bad or questionable
 *
 * @param n	[in]	node
 * @return 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)
			return bad;
		return questionable;
	}
	return good;
}

/**
 * returns 1 if bucket is perfect, meaning it is fresh, has K nodes, and all nodes are good. bucket that contains id is almost never perfect, as it can usually be split into smaller buckets, that's why param d is required to get own id
 *
 * if d is NULL, it's not checked whether we fall into the bucket and whether it could be split
 *
 * @param d	[in]	library handle to get own id
 * @param b	[in]	the bucket
 */

int bucket_good (const struct dht * d, const struct bucket * b) {
	if (d) {
		if (!bucket_good(NULL, b))
			return 0;
		if (in_bucket(d->id, b)) {
			struct node * n = b->nodes;
			while (n->next) {
				if (distance(n->id, n->next->id) != 1)
					return 0;
			}
			return 1;
		}
		return 1;
	} else {
		if (node_count(b->nodes) < K)
			return 0;
		struct node * n = b->nodes;
		if (n) {
			if (node_grade(n) != good)
				return 0;
			n = n->next;
		}
	}
}

/**
 * when we are sure that a node exists on a specific ip:port and we know it's port, but we are unsure if the node is already in the routing table, we call this function, which makes a query to this node if it's a candidate for filling the routing table. this doesn't yet add it to the routing table, because we are unsure if it's a good node / can respond to queries. replied() is called if a node replied to our query.
 *
 * see NOTE02
 *
 * @param d	[in]	library handle
 * @param a	[in]	pointer to sockaddr of the node
 * @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) {
	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));
		ping_node(d, a);
}

/**
 * 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 peers, announce, info and dl flags. see @return for important details.
 *
 * @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) {
	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 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.
 *
 * @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 peer * add_peer (struct dht * d, struct torrent * t, struct peer * p) {
	struct peer * peer = torrent->peers;
	unsigned i = 0;
	while (peer) {
		if (!memcmp(&peer->addr, &addr, sizeof 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);
				peer->next = NULL;
			}
	}
	peer->next = torrent->peers;
	torrent->peers = peer;
	d->peers++;
	if (d->peers >= d->peers_max)
		oom(d);
	return peer;
}

/**
 * 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.
 *
 * @param d	[in]	library handle
 * @param id	[in]	target node id, 20 bytes is read from this location
 * @param f	[in]	address family, AF_INET or AF_INET6
 * @return bencoding object whose memory ownership and free responsibility is transfered to the caller
 */

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"));
	binsert(r, nodes);
	struct bucket * bucket = f == AF_INET ? d->buckets : d->bucket6;
	struct node * found = find(id, &bucket, NULL);
#define ADDRLEN(f) (f == AF_INET ? 4 : 16)
	if (found) {
		struct bencoding * compact = calloc(1, sizeof *compact);
		compact->type = string;
		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);
		binsert(nodes, compact);
	} else {
		struct node * node = bucket->nodes;
		while (node) {
			struct bencoding * compact = calloc(1, sizeof *compact);
			compact->type = string;
			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);
			binsert(nodes, compact);
			node = node->next;
		}
	}
	return nodes;
}

/**
 * handles an incoming packet
 *
 * @param d	[in]	library handle
 * @param pkt	[in]	incoming UDP packet content
 * @param len	[in]	length of the packet
 * @param addr	[in]	IP address and port of sender
 */

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");
	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))
		snprintf(remote, sizeof remote,  "(inet_ntop: %s)", strerror(errno));
		sprintf(remote+strlen(remote), ":%d", ntohs(addr.sin6_port));
	}
	if (v && v->type & string) {
		node_ver = v->value;
		sprintf(remote+strlen(remote), "-%s", node_ver);
	}
	struct bdecoding * 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)
				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':
					struct bencoding * id = calloc(1, sizeof *id);
					id->type = string;
					id->key = bstr(strdup("id"));
					memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20);
					struct bencoding * r = calloc(1, sizeof *r);
					r->type = dict;
					r->key = bstr(strdup("r"));
					binsert(r, id);
					struct bencoding * y = bstr(strdup("r"));
					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);
					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->type = dict;
					struct bencoding * 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->type = dict;
					struct bencoding * 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));
					sendb(d, response, &addr, addrlen);
					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)
						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, "t")));
					struct bencoding * r = calloc(1, sizeof *r);
					r->type = dict;
					struct bencoding * 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));
					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);
					free_bencoding(response);
					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);
					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);
					sendb(response);
					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");
					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
			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)
				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);
					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);
					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)
				else
					node_free(node);
			}
		case 'E':
		case 'e':
			struct bdecoding * e = bpath(b, "e");
			char * errtype = "Unspecified Error";
			if (e && e->child)
				switch (e->child->intvalue) {
					case 201:
						errtype = "Generic Error";
						break;
					case 202:
						errtype = "Server Error";
						break;
					case 203:
						errtype = "Protocol Error, such as a malformed packet, invalid arguments, or bad token";
						break;
					case 204:
						errtype = "Method Unknown";
						break;
					default:
						errtype = "Unknown Error";
						break;
				}
			char * msg = NULL;
			if (e && e->child && e->child->next && e->child->next->type & string)
				msg = e->child->next->value;
			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");
			// send_error(d, b, &addr, addrlen, 203, "unknown type");
			break;
	}
	struct bdecoding * trans_id = bpath(b, "t");
	free_bencoding(b);
}

/**
 * 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
 *
 * 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.
 *
 * call this:
 * 	- whenever socket can be read from (via poll/epoll/select/...)
 * 	- every 13 minutes, even if it was called for incoming packets in this time period
 * 		+ stale buckets are refreshed
 *		+ peers are refetched for joined torrents and announcements are sent
 *		+ calling it more often is discouraged, since every periodic call sends out UDP packets for PEX and DHT searches/announces of torrents
 *
 * @param d	[in]	dht library handle
 */

void work (struct dht * d) {
	char packet[65536];
	struct sockaddr_in6 addr;
	socklen_t addrlen = sizeof addr;
	int ret = recvfrom(d->socket, packet, 65536, MSG_DONTWAIT | MSG_TRUNC, &addr, &addrlen);
	if (addrlen != sizeof add)
		L(d->log, "addrlen changed, not parsing packet");
	else if (ret > 65536)
		L(d->log, "recvfrom()d larger packet than 65536, not parsing packet");
	else if (ret < 0) {
		if (ret != EAGAIN)
			L(d->log, "recvfrom(): %s", strerror(errno));
		else
			periodic(d);
	} else
		handle(d, packet, ret, addr);
}