summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAnton Luka Šijanec <anton@sijanec.eu>2022-11-27 23:07:08 +0100
committerAnton Luka Šijanec <anton@sijanec.eu>2022-11-27 23:07:08 +0100
commit5c7fa69c8bd538b806ae6c3bed16d452f10ee486 (patch)
tree76ce3a4a9c3aa3e84e7034dd81142ad20ba02338
parentbencoding (diff)
downloadtravnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.tar
travnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.tar.gz
travnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.tar.bz2
travnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.tar.lz
travnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.tar.xz
travnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.tar.zst
travnik-5c7fa69c8bd538b806ae6c3bed16d452f10ee486.zip
-rw-r--r--.gitignore1
-rw-r--r--src/bencoding.c357
-rw-r--r--src/dht.c458
-rw-r--r--utils/bencoding.c48
4 files changed, 747 insertions, 117 deletions
diff --git a/.gitignore b/.gitignore
index d08bd07..3cd4f18 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,4 @@ a.out
core
.gdb_history
tiny-AES-c/
+travnik.patch
diff --git a/src/bencoding.c b/src/bencoding.c
index 801c5b6..2063bdc 100644
--- a/src/bencoding.c
+++ b/src/bencoding.c
@@ -60,9 +60,9 @@ int bcompare (struct bencoding * a, struct bencoding * b) {
return -1;
if (a && !b)
return 1;
- if (a->type & (num | string | list | dict) < b->type (num | string | list | dict))
+ if ((a->type & (num | string | list | dict)) < (b->type & (num | string | list | dict)))
return -1;
- if (a->type & (num | string | list | dict) > b->type (num | string | list | dict))
+ if ((a->type & (num | string | list | dict)) > (b->type & (num | string | list | dict)))
return 1;
int ret = bcompare(a->key, b->key);
if (ret)
@@ -83,9 +83,9 @@ int bcompare (struct bencoding * a, struct bencoding * b) {
return -1;
if (a->child && !b->child)
return 1;
- a = a->child;
- b = b->child;
- if (a->value & (list | dict)) {
+ if (a->type & (list | dict)) {
+ a = a->child;
+ b = b->child;
while (1) {
if (!a && !b)
return 0;
@@ -96,68 +96,49 @@ int bcompare (struct bencoding * a, struct bencoding * b) {
b = b->next;
}
}
+ return 0;
}
/**
- * insert into bencoding dict or list. if key already exists, it's prepended to the already existing key, unless opts has replace set.
- *
- * the memory pointed to by elem is considered ownership and responsibility of the dict now, so it shouldn't be freed by the caller. it can still be modified, however.
- *
- * if elem or benc is NULL, function does nothing.
+ * returns a bencoding element that represents a string. the resulting element is allocated on heap and must be bencoding_free()d.
*
- * default (without replace), new element will be inserted into the dict, but before the old element, with the aim that finders, such as bpath(), would return the new element instead of the old.
- * replace option frees the old element and inserts this one instead if the key already exists in the dict. this is not the default, because it frees objects that may be used elsewhere.
+ * the string ownership is transfered, so for static strings, do strdup() before pass
*
- * @param benc [in] the structure to which elem will be inserted into
- * @param elem [in] the element that will be inserted into the structure
+ * @param str [in] the string to be converted to a bencoding element
*/
-void binsert (struct bencoding * benc, struct bencoding * elem) {
- if (!benc || !elem)
+struct bencoding * bstr (char * str) {
+ if (!str)
return NULL;
- elem->parent = benc;
- if (!benc->child) {
- elem->next = NULL;
- elem->prev = NULL;
- elem->parent = benc;
- benc->child = elem;
- return;
- }
- benc = benc->child;
- while (benc->next && bcompare(elem->key, benc->next->key) < 0)
- benc = benc->next;
- struct bencoding * oldnext = benc->next;
- benc->next = elem;
- elem->prev = benc;
- elem->next = oldnext;
- if (oldnext)
- oldnext->prev = elem;
+ struct bencoding * b = calloc(1, sizeof *b);
+ if (!b)
+ return NULL;
+ b->type = string;
+ b->valuelen = strlen(str);
+ b->value = str;
+ return b;
}
/**
- * returns a bencoding element that represents a string
+ * returns a bencoding element that represents a string. the string ownership is not transfered and the element is allocated on the stack, so no cleanup is required. ideal for bval(), DO NOT USE ON binsert() and similar.
*
- * the string ownership is not transfered, the string is strdup()ed
+ * implemented as a macro that edits the current function's stack.
*
* @param str [in] the string to be converted to a bencoding element
*/
-struct bencoding * bstr (const char * str) {
- struct bencoding * b = calloc(1, sizeof *b);
- if (!b)
- return NULL;
+#define bstrs(x) bstrs_set(alloca(sizeof(struct bencoding)), x)
+
+struct bencoding * bstrs_set (struct bencoding * b, char * s) {
+ memset(b, '\0', sizeof *b);
+ b->value = s;
+ b->valuelen = strlen(s);
b->type = string;
- b->valuelen = strlen(str);
- b->value = strdup(str);
- if (!b->value) {
- free(b);
- return NULL;
- }
return b;
}
/**
- * returns a bencoding element that represents a number
+ * returns a bencoding element that represents a number. the resulting element is allocated on heap and must be bencoding_free()d.
*
* @param num [in] the number to be converted to a bencoding number
*/
@@ -167,14 +148,33 @@ struct bencoding * bnum (long int num) {
if (!b)
return NULL;
b->type = num;
- char buf[512];
+ /* char buf[512];
sprintf(buf, "%ld", num);
b->value = strdup(buf);
- if (!b->valueint) {
+ if (!b->intvalue) {
free(b);
return NULL;
- }
- b->valueint = num;
+ } */ // we could do this, but I don't think it's necessary.
+ b->valuelen = 0;
+ b->intvalue = num;
+ return b;
+}
+
+/**
+ * returns a bencoding element that represents a number. the element is allocated on the stack, so no cleanup is required. ideal for bval(), DO NOT USE ON binsert() and similar.
+ *
+ * implemented as a macro that edits the current function's stack.
+ *
+ * @param num [in] the number to be converted to a bencoding number
+ */
+
+#define bnums(x) bnums_set(alloca(sizeof(struct bencoding)), x)
+
+struct bencoding * bnums_set (struct bencoding * b, long int num) {
+ memset(b, '\0', sizeof *b);
+ b->type = num;
+ b->valuelen = 0;
+ b->intvalue = num;
return b;
}
@@ -266,40 +266,32 @@ char * b2json_charrepr (char * dest, unsigned char a) {
*/
int b2json_length (struct bencoding * b) {
+ int add = 0;
if (!b)
return 4;
+ if (b->key)
+ add += 1 + b2json_length(b->key);
if (b->type & string) {
int size = 2;
for (size_t i = 0; i < b->valuelen; i++)
size += b2json_charsize(b->value[i]);
- return size;
+ return size+add;
}
if (b->type & num) {
char buf[512];
sprintf(buf, "%ld", b->intvalue);
- return strlen(buf);
+ return strlen(buf)+add;
}
- if (b->type & list) {
+ if (b->type & (list | dict)) {
if (!b->child)
- return 2;
+ return 2+add;
struct bencoding * t = b->child;
int size = 2 + b2json_length(t);
while (t->next) {
t = t->next;
size += b2json_length(t) + 1;
}
- return size;
- }
- if (b->type & dict) {
- if (!b->child)
- return 2;
- struct bencoding * t = b->child;
- int size = 3 + b2json_length(t) + b2json_length(t->key);
- while (t->next) {
- t = t->next;
- size += 1 + b2json_length(t) + 1 + b2json_length(t->key);
- }
- return size;
+ return size+add;
}
return 5;
}
@@ -321,6 +313,10 @@ char * b2json (char * dest, struct bencoding * b) {
strncpy(dest, "null", 4);
return dest+4;
}
+ if (b->key) {
+ dest = b2json(dest, b->key);
+ *dest++ = ':';
+ }
if (b->type & string) {
*dest++ = '"';
for (size_t i = 0; i < b->valuelen; i++)
@@ -334,40 +330,20 @@ char * b2json (char * dest, struct bencoding * b) {
strncpy(dest, buf, strlen(buf));
return dest+strlen(buf);
}
- if (b->type & list) {
+ if (b->type & (list | dict)) {
if (!b->child) {
- strncpy(dest, "[]", 2);
+ strncpy(dest, b->type & list ? "[]" : "{}", 2);
return dest+2;
}
+ *dest++ = b->type & list ? '[' : '{';
struct bencoding * t = b->child;
- *dest++ = '[';
dest = b2json(dest, t);
while (t->next) {
t = t->next;
*dest++ = ',';
dest = b2json(dest, t);
}
- *dest++ = ']';
- return dest;
- }
- if (b->type & dict) {
- if (!b->child) {
- strncpy(dest, "{}", 2);
- return dest+2;
- }
- *dest++ = '{';
- struct bencoding * t = b->child;
- dest = b2json(dest, t->key);
- *dest++ = ':';
- dest = b2json(dest, t);
- while (t->next) {
- t = t->next;
- *dest++ = ',';
- dest = b2json(dest, t->key);
- *dest++ = ':';
- dest = b2json(dest, t);
- }
- *dest++ = '}';
+ *dest++ = b->type & list ? ']' : '}';
return dest;
}
strncpy(dest, "false", 4);
@@ -376,6 +352,83 @@ char * b2json (char * dest, struct bencoding * b) {
}
/**
+ * print bstructure to a FILE *. used for debugging. in JSON
+ *
+ * @param benc [in] the structure to be printed
+ * @param benc [in] the FILE * to which to print to
+ */
+
+void bprint (FILE * out, struct bencoding * benc) {
+ char o[1+b2json_length(benc)];
+ b2json(o, benc);
+ o[b2json_length(benc)] = '\0';
+ fprintf(out, "%s\n", o);
+}
+
+/**
+ * insert into bencoding dict or list. if key already exists, it's prepended to the already existing key, unless opts has replace set.
+ *
+ * the memory pointed to by elem is considered ownership and responsibility of the dict now, so it shouldn't be freed by the caller. it can still be modified, however.
+ *
+ * if elem or benc is NULL, function does nothing.
+ *
+ * default (without replace), new element will be inserted into the dict, but before the old element, with the aim that finders, such as bpath(), would return the new element instead of the old.
+ * replace option frees the old element and inserts this one instead if the key already exists in the dict. this is not the default, because it frees objects that may be used elsewhere.
+ *
+ * for lists, binsert adds the new element to the start of the list
+ *
+ * @param benc [in] the structure to which elem will be inserted into
+ * @param elem [in] the element that will be inserted into the structure
+ */
+
+void binsert (struct bencoding * benc, struct bencoding * elem) {
+ if (!benc || !elem)
+ return;
+ elem->parent = benc;
+ struct bencoding ** place = &benc->child;
+ while (1) {
+ if (!*place) {
+ *place = elem;
+ elem->next = NULL;
+ elem->prev = NULL;
+ return;
+ }
+ if (bcompare((*place)->key, elem->key) >= 0) {
+ elem->prev = (*place)->prev;
+ elem->next = *place;
+ (*place)->prev = elem;
+ if (((benc->type & replace) || (elem->type & replace)) && !bcompare((*place)->key, elem->key)) {
+ elem->next = (*place)->next;
+ if ((*place)->next)
+ (*place)->next->prev = elem;
+ free_bencoding(*place);
+ }
+ *place = elem;
+ return;
+ }
+ place = &(*place)->next;
+ }
+}
+
+/**
+ * detaches an element from a bencoding list or dict, does not free it.
+ *
+ * @param elem [in] the element to be detached but not freed
+ */
+
+void bdetach (struct bencoding * elem) {
+ if (!elem)
+ return;
+ if (elem->prev)
+ elem->prev->next = elem->next;
+ if (elem->next)
+ elem->next->prev = elem->prev;
+ elem->next = NULL;
+ elem->prev = NULL;
+ // elem->parent = NULL; // we could also do that, no issue with me 20221123
+}
+
+/**
* bdecodes a bencoded structure from a string into a bencoding structure that must be free_bencodinged by the caller.
*
* nonstandard things: this parser allows for dict keys to be of any type, valuekey
@@ -551,26 +604,132 @@ struct bencoding * bpath (struct bencoding * benc, const char * key) {
/**
* find a value in a list. returns NULL if not found.
*
+ * to easily check if a number or string is present in a list or dict as a value:
+ *
+ * if (bval(benc, bnums(123)) || bval(benc, bstrs("some string")));
+ *
* @param benc [in] the bencoding list or dict to look in
- * @param str [in] the value
+ * @param val [in] the value
*/
-struct bencoding * bval (struct bencoding * benc, const char * val) {
+struct bencoding * bval (struct bencoding * benc, struct bencoding * val) {
if (!benc)
return NULL;
if (!benc->child)
return NULL;
benc = benc->child;
while (benc) {
- if (benc->type & num) {
- char buf[412];
- sprintf(buf, "%ld", benc->intvalue);
- if (!strcmp(buf, val))
- return benc;
- }
- if (benc->type & string && strlen(val) == benc->valuelen && !strncmp(benc->value, val, benc->valuelen))
+ if (!bcompare(benc, val))
return benc;
benc = benc->next;
}
return NULL;
}
+
+/**
+ * returns the size required to store a bencoded object, without the terminating NULL byte.
+ *
+ * @param b [in] the bencoding object
+ */
+
+int bencode_length (struct bencoding * b) {
+ if (!b)
+ return 0;
+ char buf[512];
+ if (b->type & num) {
+ sprintf(buf, "%ld", b->intvalue);
+ return strlen(buf)+bencode_length(b->key)+2;
+ }
+ if (b->type & string) {
+ sprintf(buf, "%ld", b->valuelen);
+ return strlen(buf)+1+b->valuelen+bencode_length(b->key);
+ }
+ if (b->type & (list | dict)) {
+ struct bencoding * t = b->child;
+ int size = 2;
+ while (t) {
+ size += bencode_length(t);
+ t = t->next;
+ }
+ return size+bencode_length(b->key);
+ }
+ return 0;
+}
+
+/**
+ * encode a bencoding object with bencoding and store it into memory pointed to by dest with at least bencode_length(b) space.
+ *
+ * does not write a terminating NULL byte.
+ *
+ * @param dest [in] the destination to which to write to
+ * @param b [in] the bencoding object
+ * @return the pointer to the byte after the last written byte
+ */
+
+char * bencode (char * dest, struct bencoding * b) {
+ if (!b)
+ return dest;
+ char buf[512];
+ if (b->key)
+ dest = bencode(dest, b->key);
+ if (b->type & num) {
+ sprintf(buf, "i%ld", b->intvalue);
+ strncpy(dest, buf, strlen(buf));
+ dest += strlen(buf);
+ *dest++ = 'e';
+ }
+ if (b->type & string) {
+ sprintf(buf, "%ld:", b->valuelen);
+ strncpy(dest, buf, strlen(buf));
+ dest += strlen(buf);
+ memcpy(dest, b->value, b->valuelen);
+ dest += b->valuelen;
+ }
+ if (b->type & (list | dict)) {
+ if (b->type & list)
+ *dest++ = 'l';
+ else
+ *dest++ = 'd';
+ struct bencoding * t = b->child;
+ while (t) {
+ dest = bencode(dest, t);
+ t = t->next;
+ }
+ *dest++ = 'e';
+ }
+ return dest;
+}
+
+/**
+ * clones a bencoding object including all of it's children
+ *
+ * @param b [in] the source object
+ * @return the new object, allocated on heap
+ */
+
+struct bencoding * bclone (struct bencoding * b) {
+ if (!b)
+ return NULL;
+ struct bencoding * c = calloc(1, sizeof(*c));
+ if (b->key) {
+ c->key = bclone(b->key);
+ c->key->parent = c;
+ }
+ if (b->child) {
+ c->child = bclone(b->child);
+ c->child->parent = c;
+ }
+ if (b->next) {
+ c->next = bclone(b->child);
+ c->next->parent = c;
+ }
+ c->valuelen = b->valuelen;
+ if (b->value) {
+ c->value = malloc(c->valuelen+1);
+ memcpy(c->value, b->value, c->valuelen+1);
+ }
+ c->intvalue = b->intvalue;
+ c->type = b->type;
+ c->index = b->index;
+ return c;
+}
diff --git a/src/dht.c b/src/dht.c
index a8538b5..4009fb4 100644
--- a/src/dht.c
+++ b/src/dht.c
@@ -1,18 +1,450 @@
-struct dht {
- char id[20];
- int socket;
- char secret[16]; /**< for calculating opaque write token, random */
-};
+#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>
+#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 (struct in6_addr addr) {
+ return memcmp("\0\0\0\0\0\0\0\0\0\0\xFF\xFF", addr.s6_addr, 12) ? AF_INET6 : AF_INET;
+}
+
+#define K 8
+
+/**
+ * node representation
+ */
+
struct node {
char id[20];
- int lost;
- int sent;
- int answers;
- int malformed;
- int received;
- time_t last;
- struct sockaddr addr;
+ 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;
+ struct dht * dht; /**< a reference to the library handle */
+}
+
+/**
+ * frees a node
+ *
+ * @param n [in] the node to be freed
+ */
+
+void node_free (struct node * n) {
+ free(n->addr);
+ free(n);
+}
+
+/**
+ * bucket representation
+ */
+
+struct bucket {
+ char id[20]; /**< bucket spans from id inclusive to next->id exclusive */
+ struct node * nodes;
+ struct bucket * next;
+ struct dht * dht; /**< a reference to the library handle */
+ int count; /**< number of nodes in this bucket */
+}
+
+/**
+ * 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);
+}
+
+/**
+ * handle for the library
+ */
+
+struct dht {
+ 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 */
+ FILE * log; /**< FILE to log to, defaults to stderr */
+ struct bucket * buckets;
+ struct bucket * buckets6: /**< IPv6 routing table */
};
-void token (char * dest, struct sockaddr addr) {š
+/**
+ * creates a handle. you can override id and 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
+ */
+
+struct dht * dht_init (void) {
+ struct dht * d = calloc(1, sizeof *d);
+ d->log = stderr;
+ d->buckets = calloc(1, sizeof(struct bucket));
+ d->buckets->dht = d;
+ 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;
+ 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.
+ * TODO: sends all my knowledge as a burst of UDP packets to nodes in my bucket.
+ */
+
+#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);
+ }
+ free(d);
+}
+
+/**
+ * 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] the node's IP address, from which get_peers was received
+ * @param l [in] the length of socket address struct a
+ */
+
+void token (const struct dht * d, char * t, struct sockaddr_in6 * a) {
+ struct AES_ctx aes;
+ memcpy(t, a->sin6_addr, 16);
+ AES_init_ctx(&aes, dht->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] the node's IP address, from which announce was received
+ * @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) {
+ 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 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 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;
+}
+
+/**
+ * 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 window 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 char * id, const struct sockaddr_in6 * addr) {
+
+}
+
+/**
+ * sends a find_node query to a "raw node", a tuple if id and ip
+ *
+ * @param d [in] handle
+ * @param id [in] id of remote node to which we are sending the query
+ * @param a [in] address of the remote node
+ * @param query [in] 20 byte id we are querying
+ */
+
+void find_node (const struct dht * d, const char * id, const struct sockaddr_in6 * a, const char * query) {
+
+}
+
+/**
+ * when we are sure about association nodeid<->ipaddress and 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.
+ *
+ * @param d [in] library handle
+ * @param id [in] 20 byte node id
+ * @param a [in] pointer to sockaddr of the node
+ */
+
+void potential_node (const struct dht * d, const char * id, const struct sockaddr_in6 * a) {
+ struct bucket * bucket = d->buckets;
+ if (family(a->sin6_addr) == AF_INET6)
+ bucket = b->buckets6;
+ find(rid->value, &bucket, NULL);
+ if (bucket->count <= K || in_bucket(d->id, bucket)) {
+ char random[20];
+ if (getrandom(random, 20, GRND_NONBLOCK) == -1)
+ return;
+ find_node(d, id, a, random);
+ }
+}
+
+/**
+ * does work; syncs with the network, handles incoming queries
+ *
+ * call this:
+ * - whenever socket can be read from (via poll/epoll/select/...)
+ * - every 14 minutes so that nodes with no activity are pinged
+ */
+
+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 {
+ struct bdecoding * b = bdecode(packet, ret, 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, addrlen))
+ 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;
+ switch (qtype[0]) {
+ case 'P': // ping
+ case 'p':
+ struct bencoding * rid = bpath(bpath(b, "a"), "id");
+ if (rid && rid->type & string && rid->valuelen == 20) {
+ potential_node(d, rid->value, &addr, addrlen);
+ }
+ 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 *d);
+ id->type = dict;
+ id->key = bstr(strdup("id"));
+ id->valuelen = 20;
+ id->value = malloc(20);
+ memcpy(id->value, d->id, 20);
+ struct bencoding * r = calloc(1, sizeof *d);
+ 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 *r);
+ response->type = dict;
+ binsert(response, y);
+ binsert(response, r);
+ binsert(response, bclone(bpath(b, "t")));
+ sendb(d, response, &addr, addrlen);
+ free_bencoding(response);
+ break;
+ default: // see NOTE01
+ int len = b2json_length(b);
+ char json[len+1];
+ b2json(json, b);
+ json[len] = '\0';
+ L(dht->log, "%s sent an unknown query type: %s");
+ break;
+ }
+ break;
+ case 'R':
+ case 'r':
+ break;
+ 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);
+ }
}
diff --git a/utils/bencoding.c b/utils/bencoding.c
index 1e90737..ec5909d 100644
--- a/utils/bencoding.c
+++ b/utils/bencoding.c
@@ -8,7 +8,7 @@
#define S0(x) (x ? x : "")
int main (int argc, char ** argv) {
if (argc < 1+1)
- error_at_line(1, 0, __FILE__, __LINE__, "%s encode < json || %s decode < bencoding || %s path path/to/obj < bencoding || %s foreach < bencoding || %s val value < bencoding (should output null or value as JSON string if found in array)", S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]));
+ error_at_line(1, 0, __FILE__, __LINE__, "%s encode < json || %s decode < bencoding || %s path path/to/obj < bencoding || %s foreach < bencoding || %s val value < bencoding (should output null or value as JSON string if found in array) || %s insert bencoding [replace] < bencoding || %s compare bencoding < bencoding || %s encode < bencoding", S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]), S0(argv[0]));
if (argv[1][0] == 'p' && argc != 1+2)
error_at_line(1, 0, __FILE__, __LINE__, "set path!");
int size = 2048;
@@ -21,8 +21,6 @@ int main (int argc, char ** argv) {
if ((size - len) < 1024)
in = realloc(in, size *= 2);
}
- if (argv[1][0] == 'e')
- error_at_line(3, 0, __FILE__, __LINE__, "N/I");
struct bencoding * bencoding = bdecode(in, size, 0);
if (argv[1][0] == 'd') {
len = b2json_length(bencoding);
@@ -45,9 +43,9 @@ int main (int argc, char ** argv) {
fprintf(stderr, "len: %d\n", len);
}
if (argv[1][0] == 'v') {
- len = b2json_length(bval(bencoding, argv[2]));
+ len = b2json_length(bval(bencoding, bstrs(argv[2])));
char out[len+1];
- char * end = b2json(out, bval(bencoding, argv[2]));
+ char * end = b2json(out, bval(bencoding, bstrs(argv[2])));
*end = '\0';
puts(out);
if (end - out != len)
@@ -72,6 +70,46 @@ int main (int argc, char ** argv) {
printf("value(%d): %s\n", len, out2);
}
}
+ if (argv[1][0] == 'i') {
+ if (argc < 1+2)
+ error_at_line(5, 0, __FILE__, __LINE__, "missing element argument");
+ struct bencoding * elem = bdecode(argv[2], -2, argv[3] ? replace : 0);
+ if (!elem)
+ error_at_line(4, 0, __FILE__, __LINE__, "bdecode of element returned NULL");
+ binsert(bencoding, elem->child);
+ elem->child = NULL;
+ free_bencoding(elem);
+ len = b2json_length(bencoding);
+ char out[len+1];
+ char * end = b2json(out, bencoding);
+ *end = '\0';
+ puts(out);
+ if (end - out != len)
+ error_at_line(4, 0, __FILE__, __LINE__, "b2json wrote %ld instead of %d bytes.", end-out, len);
+ fprintf(stderr, "len: %d\n", len);
+ }
+ if (argv[1][0] == 'c') {
+ struct bencoding * elem = bdecode(argv[2], -2, 0);
+ switch (bcompare(bencoding, elem)) {
+ case -1:
+ fprintf(stdout, "stdin is less than argv\n");
+ break;
+ case 0:
+ fprintf(stdout, "stdin is same as argv\n");
+ break;
+ case 1:
+ fprintf(stdout, "stdin is greater than argv\n");
+ break;
+ }
+ free_bencoding(elem);
+ }
+ if (argv[1][0] == 'e') {
+ int len = bencode_length(bencoding);
+ char bencoded[len+1];
+ bencoded[len] = '\0';
+ bencode(bencoded, bencoding);
+ puts(bencoded);
+ }
free_bencoding(bencoding);
free(in);
return 0;