unet-cli: strip initial newline in usage message
[project/unetd.git] / dht.c
1 /*
2 Copyright (c) 2009-2011 by Juliusz Chroboczek
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in
12 all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE.
21 */
22
23 /* Please, please, please.
24
25 You are welcome to integrate this code in your favourite Bittorrent
26 client. Please remember, however, that it is meant to be usable by
27 others, including myself. This means no C++, no relicensing, and no
28 gratuitious changes to the coding style. And please send back any
29 improvements to the author. */
30
31 /* For memmem. */
32 #define _GNU_SOURCE
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <stdarg.h>
39
40 #if !defined(_WIN32) || defined(__MINGW32__)
41 #include <sys/time.h>
42 #endif
43
44 #ifndef _WIN32
45 #include <unistd.h>
46 #include <fcntl.h>
47
48 #include <arpa/inet.h>
49 #include <sys/types.h>
50 #include <sys/socket.h>
51 #include <netinet/in.h>
52 #else
53 #ifndef _WIN32_WINNT
54 #define _WIN32_WINNT 0x0501 /* Windows XP */
55 #endif
56 #ifndef WINVER
57 #define WINVER _WIN32_WINNT
58 #endif
59 #include <ws2tcpip.h>
60 #include <windows.h>
61 #endif
62
63 #include "dht.h"
64
65 #ifndef HAVE_MEMMEM
66 #ifdef __GLIBC__
67 #define HAVE_MEMMEM
68 #endif
69 #endif
70
71 #ifndef MSG_CONFIRM
72 #define MSG_CONFIRM 0
73 #endif
74
75 #if !defined(_WIN32) || defined(__MINGW32__)
76 #define dht_gettimeofday(_ts, _tz) gettimeofday((_ts), (_tz))
77 #else
78 extern int dht_gettimeofday(struct timeval *tv, struct timezone *tz);
79 #endif
80
81 #ifdef _WIN32
82
83 #undef EAFNOSUPPORT
84 #define EAFNOSUPPORT WSAEAFNOSUPPORT
85
86 static int
87 random(void)
88 {
89 return rand();
90 }
91
92 /* Windows Vista and later already provide the implementation. */
93 #if _WIN32_WINNT < 0x0600
94 extern const char *inet_ntop(int, const void *, char *, socklen_t);
95 #endif
96
97 #ifdef _MSC_VER
98 /* There is no snprintf in MSVCRT. */
99 #define snprintf _snprintf
100 #endif
101
102 #endif
103
104 /* We set sin_family to 0 to mark unused slots. */
105 #if AF_INET == 0 || AF_INET6 == 0
106 #error You lose
107 #endif
108
109 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
110 /* nothing */
111 #elif defined(__GNUC__)
112 #define inline __inline
113 #if (__GNUC__ >= 3)
114 #define restrict __restrict
115 #else
116 #define restrict /**/
117 #endif
118 #else
119 #define inline /**/
120 #define restrict /**/
121 #endif
122
123 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
124 #define MIN(x, y) ((x) <= (y) ? (x) : (y))
125
126 struct node {
127 unsigned char id[20];
128 struct sockaddr_storage ss;
129 int sslen;
130 time_t time; /* time of last message received */
131 time_t reply_time; /* time of last correct reply received */
132 time_t pinged_time; /* time of last request */
133 int pinged; /* how many requests we sent since last reply */
134 struct node *next;
135 };
136
137 struct bucket {
138 int af;
139 unsigned char first[20];
140 int count; /* number of nodes */
141 int max_count; /* max number of nodes for this bucket */
142 time_t time; /* time of last reply in this bucket */
143 struct node *nodes;
144 struct sockaddr_storage cached; /* the address of a likely candidate */
145 int cachedlen;
146 struct bucket *next;
147 };
148
149 struct search_node {
150 unsigned char id[20];
151 struct sockaddr_storage ss;
152 int sslen;
153 time_t request_time; /* the time of the last unanswered request */
154 time_t reply_time; /* the time of the last reply */
155 int pinged;
156 unsigned char token[40];
157 int token_len;
158 int replied; /* whether we have received a reply */
159 int acked; /* whether they acked our announcement */
160 };
161
162 /* When performing a search, we search for up to SEARCH_NODES closest nodes
163 to the destination, and use the additional ones to backtrack if any of
164 the target 8 turn out to be dead. */
165 #define SEARCH_NODES 14
166
167 struct search {
168 unsigned short tid;
169 int af;
170 time_t step_time; /* the time of the last search_step */
171 unsigned char id[20];
172 unsigned short port; /* 0 for pure searches */
173 int done;
174 struct search_node nodes[SEARCH_NODES];
175 int numnodes;
176 struct search *next;
177 };
178
179 struct peer {
180 time_t time;
181 unsigned char ip[16];
182 unsigned short len;
183 unsigned short port;
184 };
185
186 /* The maximum number of peers we store for a given hash. */
187 #ifndef DHT_MAX_PEERS
188 #define DHT_MAX_PEERS 2048
189 #endif
190
191 /* The maximum number of hashes we're willing to track. */
192 #ifndef DHT_MAX_HASHES
193 #define DHT_MAX_HASHES 16384
194 #endif
195
196 /* The maximum number of searches we keep data about. */
197 #ifndef DHT_MAX_SEARCHES
198 #define DHT_MAX_SEARCHES 1024
199 #endif
200
201 /* The time after which we consider a search to be expirable. */
202 #ifndef DHT_SEARCH_EXPIRE_TIME
203 #define DHT_SEARCH_EXPIRE_TIME (62 * 60)
204 #endif
205
206 /* The maximum number of in-flight queries per search. */
207 #ifndef DHT_INFLIGHT_QUERIES
208 #define DHT_INFLIGHT_QUERIES 4
209 #endif
210
211 /* The retransmit timeout when performing searches. */
212 #ifndef DHT_SEARCH_RETRANSMIT
213 #define DHT_SEARCH_RETRANSMIT 10
214 #endif
215
216 struct storage {
217 unsigned char id[20];
218 int numpeers, maxpeers;
219 struct peer *peers;
220 struct storage *next;
221 };
222
223 static struct storage * find_storage(const unsigned char *id);
224 static void flush_search_node(struct search_node *n, struct search *sr);
225
226 static int send_ping(const struct sockaddr *sa, int salen,
227 const unsigned char *tid, int tid_len);
228 static int send_pong(const struct sockaddr *sa, int salen,
229 const unsigned char *tid, int tid_len);
230 static int send_find_node(const struct sockaddr *sa, int salen,
231 const unsigned char *tid, int tid_len,
232 const unsigned char *target, int want, int confirm);
233 static int send_nodes_peers(const struct sockaddr *sa, int salen,
234 const unsigned char *tid, int tid_len,
235 const unsigned char *nodes, int nodes_len,
236 const unsigned char *nodes6, int nodes6_len,
237 int af, struct storage *st,
238 const unsigned char *token, int token_len);
239 static int send_closest_nodes(const struct sockaddr *sa, int salen,
240 const unsigned char *tid, int tid_len,
241 const unsigned char *id, int want,
242 int af, struct storage *st,
243 const unsigned char *token, int token_len);
244 static int send_get_peers(const struct sockaddr *sa, int salen,
245 unsigned char *tid, int tid_len,
246 unsigned char *infohash, int want, int confirm);
247 static int send_announce_peer(const struct sockaddr *sa, int salen,
248 unsigned char *tid, int tid_len,
249 unsigned char *infohas, unsigned short port,
250 unsigned char *token, int token_len, int confirm);
251 static int send_peer_announced(const struct sockaddr *sa, int salen,
252 unsigned char *tid, int tid_len);
253 static int send_error(const struct sockaddr *sa, int salen,
254 unsigned char *tid, int tid_len,
255 int code, const char *message);
256
257 static void
258 add_search_node(const unsigned char *id, const struct sockaddr *sa, int salen);
259
260 #define ERROR 0
261 #define REPLY 1
262 #define PING 2
263 #define FIND_NODE 3
264 #define GET_PEERS 4
265 #define ANNOUNCE_PEER 5
266
267 #define WANT4 1
268 #define WANT6 2
269
270 #define PARSE_TID_LEN 16
271 #define PARSE_TOKEN_LEN 128
272 #define PARSE_NODES_LEN (26 * 16)
273 #define PARSE_NODES6_LEN (38 * 16)
274 #define PARSE_VALUES_LEN 2048
275 #define PARSE_VALUES6_LEN 2048
276
277 struct parsed_message {
278 unsigned char tid[PARSE_TID_LEN];
279 unsigned short tid_len;
280 unsigned char id[20];
281 unsigned char info_hash[20];
282 unsigned char target[20];
283 unsigned short port;
284 unsigned short implied_port;
285 unsigned char token[PARSE_TOKEN_LEN];
286 unsigned short token_len;
287 unsigned char nodes[PARSE_NODES_LEN];
288 unsigned short nodes_len;
289 unsigned char nodes6[PARSE_NODES6_LEN];
290 unsigned short nodes6_len;
291 unsigned char values[PARSE_VALUES_LEN];
292 unsigned short values_len;
293 unsigned char values6[PARSE_VALUES6_LEN];
294 unsigned short values6_len;
295 unsigned short want;
296 };
297
298 static int parse_message(const unsigned char *buf, int buflen,
299 struct parsed_message *m);
300
301 static const unsigned char zeroes[20] = {0};
302 static const unsigned char v4prefix[16] = {
303 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0
304 };
305
306 static int dht_socket = -1;
307 static int dht_socket6 = -1;
308
309 static time_t search_time;
310 static time_t confirm_nodes_time;
311 static time_t rotate_secrets_time;
312
313 static unsigned char myid[20];
314 static int have_v = 0;
315 static unsigned char my_v[9];
316 static unsigned char secret[8];
317 static unsigned char oldsecret[8];
318
319 static struct bucket *buckets = NULL;
320 static struct bucket *buckets6 = NULL;
321 static struct storage *storage;
322 static int numstorage;
323
324 static struct search *searches = NULL;
325 static int numsearches;
326 static unsigned short search_id;
327
328 /* The maximum number of nodes that we snub. There is probably little
329 reason to increase this value. */
330 #ifndef DHT_MAX_BLACKLISTED
331 #define DHT_MAX_BLACKLISTED 10
332 #endif
333 static struct sockaddr_storage blacklist[DHT_MAX_BLACKLISTED];
334 int next_blacklisted;
335
336 static struct timeval now;
337 static time_t mybucket_grow_time, mybucket6_grow_time;
338 static time_t expire_stuff_time;
339
340 #define MAX_TOKEN_BUCKET_TOKENS 400
341 static time_t token_bucket_time;
342 static int token_bucket_tokens;
343
344 FILE *dht_debug = NULL;
345
346 #ifdef __GNUC__
347 __attribute__ ((format (printf, 1, 2)))
348 #endif
349 static void
350 debugf(const char *format, ...)
351 {
352 va_list args;
353 va_start(args, format);
354 if(dht_debug)
355 vfprintf(dht_debug, format, args);
356 va_end(args);
357 if(dht_debug)
358 fflush(dht_debug);
359 }
360
361 static void
362 debug_printable(const unsigned char *buf, int buflen)
363 {
364 int i;
365 if(dht_debug) {
366 for(i = 0; i < buflen; i++)
367 putc(buf[i] >= 32 && buf[i] <= 126 ? buf[i] : '.', dht_debug);
368 }
369 }
370
371 static void
372 print_hex(FILE *f, const unsigned char *buf, int buflen)
373 {
374 int i;
375 for(i = 0; i < buflen; i++)
376 fprintf(f, "%02x", buf[i]);
377 }
378
379 static int
380 is_martian(const struct sockaddr *sa)
381 {
382 switch(sa->sa_family) {
383 case AF_INET: {
384 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
385 const unsigned char *address = (const unsigned char*)&sin->sin_addr;
386 return sin->sin_port == 0 ||
387 (address[0] == 0) ||
388 (address[0] == 127) ||
389 ((address[0] & 0xE0) == 0xE0);
390 }
391 case AF_INET6: {
392 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
393 const unsigned char *address = (const unsigned char*)&sin6->sin6_addr;
394 return sin6->sin6_port == 0 ||
395 (address[0] == 0xFF) ||
396 (address[0] == 0xFE && (address[1] & 0xC0) == 0x80) ||
397 (memcmp(address, zeroes, 15) == 0 &&
398 (address[15] == 0 || address[15] == 1)) ||
399 (memcmp(address, v4prefix, 12) == 0);
400 }
401
402 default:
403 return 0;
404 }
405 }
406
407 /* Forget about the ``XOR-metric''. An id is just a path from the
408 root of the tree, so bits are numbered from the start. */
409
410 static int
411 id_cmp(const unsigned char *restrict id1, const unsigned char *restrict id2)
412 {
413 /* Memcmp is guaranteed to perform an unsigned comparison. */
414 return memcmp(id1, id2, 20);
415 }
416
417 /* Find the lowest 1 bit in an id. */
418 static int
419 lowbit(const unsigned char *id)
420 {
421 int i, j;
422 for(i = 19; i >= 0; i--)
423 if(id[i] != 0)
424 break;
425
426 if(i < 0)
427 return -1;
428
429 for(j = 7; j >= 0; j--)
430 if((id[i] & (0x80 >> j)) != 0)
431 break;
432
433 return 8 * i + j;
434 }
435
436 /* Find how many bits two ids have in common. */
437 static int
438 common_bits(const unsigned char *id1, const unsigned char *id2)
439 {
440 int i, j;
441 unsigned char xor;
442 for(i = 0; i < 20; i++) {
443 if(id1[i] != id2[i])
444 break;
445 }
446
447 if(i == 20)
448 return 160;
449
450 xor = id1[i] ^ id2[i];
451
452 j = 0;
453 while((xor & 0x80) == 0) {
454 xor <<= 1;
455 j++;
456 }
457
458 return 8 * i + j;
459 }
460
461 /* Determine whether id1 or id2 is closer to ref */
462 static int
463 xorcmp(const unsigned char *id1, const unsigned char *id2,
464 const unsigned char *ref)
465 {
466 int i;
467 for(i = 0; i < 20; i++) {
468 unsigned char xor1, xor2;
469 if(id1[i] == id2[i])
470 continue;
471 xor1 = id1[i] ^ ref[i];
472 xor2 = id2[i] ^ ref[i];
473 if(xor1 < xor2)
474 return -1;
475 else
476 return 1;
477 }
478 return 0;
479 }
480
481 /* We keep buckets in a sorted linked list. A bucket b ranges from
482 b->first inclusive up to b->next->first exclusive. */
483 static int
484 in_bucket(const unsigned char *id, struct bucket *b)
485 {
486 return id_cmp(b->first, id) <= 0 &&
487 (b->next == NULL || id_cmp(id, b->next->first) < 0);
488 }
489
490 static struct bucket *
491 find_bucket(unsigned const char *id, int af)
492 {
493 struct bucket *b = af == AF_INET ? buckets : buckets6;
494
495 if(b == NULL)
496 return NULL;
497
498 while(1) {
499 if(b->next == NULL)
500 return b;
501 if(id_cmp(id, b->next->first) < 0)
502 return b;
503 b = b->next;
504 }
505 }
506
507 static struct bucket *
508 previous_bucket(struct bucket *b)
509 {
510 struct bucket *p = b->af == AF_INET ? buckets : buckets6;
511
512 if(b == p)
513 return NULL;
514
515 while(1) {
516 if(p->next == NULL)
517 return NULL;
518 if(p->next == b)
519 return p;
520 p = p->next;
521 }
522 }
523
524 /* Every bucket contains an unordered list of nodes. */
525 static struct node *
526 find_node(const unsigned char *id, int af)
527 {
528 struct bucket *b = find_bucket(id, af);
529 struct node *n;
530
531 if(b == NULL)
532 return NULL;
533
534 n = b->nodes;
535 while(n) {
536 if(id_cmp(n->id, id) == 0)
537 return n;
538 n = n->next;
539 }
540 return NULL;
541 }
542
543 /* Return a random node in a bucket. */
544 static struct node *
545 random_node(struct bucket *b)
546 {
547 struct node *n;
548 int nn;
549
550 if(b->count == 0)
551 return NULL;
552
553 nn = random() % b->count;
554 n = b->nodes;
555 while(nn > 0 && n) {
556 n = n->next;
557 nn--;
558 }
559 return n;
560 }
561
562 /* Return the middle id of a bucket. */
563 static int
564 bucket_middle(struct bucket *b, unsigned char *id_return)
565 {
566 int bit1 = lowbit(b->first);
567 int bit2 = b->next ? lowbit(b->next->first) : -1;
568 int bit = MAX(bit1, bit2) + 1;
569
570 if(bit >= 160)
571 return -1;
572
573 memcpy(id_return, b->first, 20);
574 id_return[bit / 8] |= (0x80 >> (bit % 8));
575 return 1;
576 }
577
578 /* Return a random id within a bucket. */
579 static int
580 bucket_random(struct bucket *b, unsigned char *id_return)
581 {
582 int bit1 = lowbit(b->first);
583 int bit2 = b->next ? lowbit(b->next->first) : -1;
584 int bit = MAX(bit1, bit2) + 1;
585 int i;
586
587 if(bit >= 160) {
588 memcpy(id_return, b->first, 20);
589 return 1;
590 }
591
592 memcpy(id_return, b->first, bit / 8);
593 id_return[bit / 8] = b->first[bit / 8] & (0xFF00 >> (bit % 8));
594 id_return[bit / 8] |= random() & 0xFF >> (bit % 8);
595 for(i = bit / 8 + 1; i < 20; i++)
596 id_return[i] = random() & 0xFF;
597 return 1;
598 }
599
600 /* This is our definition of a known-good node. */
601 static int
602 node_good(struct node *node)
603 {
604 return
605 node->pinged <= 2 &&
606 node->reply_time >= now.tv_sec - 7200 &&
607 node->time >= now.tv_sec - 900;
608 }
609
610 /* Our transaction-ids are 4-bytes long, with the first two bytes identi-
611 fying the kind of request, and the remaining two a sequence number in
612 host order. */
613
614 static void
615 make_tid(unsigned char *tid_return, const char *prefix, unsigned short seqno)
616 {
617 tid_return[0] = prefix[0] & 0xFF;
618 tid_return[1] = prefix[1] & 0xFF;
619 memcpy(tid_return + 2, &seqno, 2);
620 }
621
622 static int
623 tid_match(const unsigned char *tid, const char *prefix,
624 unsigned short *seqno_return)
625 {
626 if(tid[0] == (prefix[0] & 0xFF) && tid[1] == (prefix[1] & 0xFF)) {
627 if(seqno_return)
628 memcpy(seqno_return, tid + 2, 2);
629 return 1;
630 } else
631 return 0;
632 }
633
634 /* Every bucket caches the address of a likely node. Ping it. */
635 static int
636 send_cached_ping(struct bucket *b)
637 {
638 unsigned char tid[4];
639 int rc;
640 /* We set family to 0 when there's no cached node. */
641 if(b->cached.ss_family == 0)
642 return 0;
643
644 debugf("Sending ping to cached node.\n");
645 make_tid(tid, "pn", 0);
646 rc = send_ping((struct sockaddr*)&b->cached, b->cachedlen, tid, 4);
647 b->cached.ss_family = 0;
648 b->cachedlen = 0;
649 return rc;
650 }
651
652 /* Called whenever we send a request to a node, increases the ping count
653 and, if that reaches 3, sends a ping to a new candidate. */
654 static void
655 pinged(struct node *n, struct bucket *b)
656 {
657 n->pinged++;
658 n->pinged_time = now.tv_sec;
659 if(n->pinged >= 3)
660 send_cached_ping(b ? b : find_bucket(n->id, n->ss.ss_family));
661 }
662
663 /* The internal blacklist is an LRU cache of nodes that have sent
664 incorrect messages. */
665 static void
666 blacklist_node(const unsigned char *id, const struct sockaddr *sa, int salen)
667 {
668 int i;
669
670 debugf("Blacklisting broken node.\n");
671
672 if(id) {
673 struct node *n;
674 struct search *sr;
675 /* Make the node easy to discard. */
676 n = find_node(id, sa->sa_family);
677 if(n) {
678 n->pinged = 3;
679 pinged(n, NULL);
680 }
681 /* Discard it from any searches in progress. */
682 sr = searches;
683 while(sr) {
684 for(i = 0; i < sr->numnodes; i++)
685 if(id_cmp(sr->nodes[i].id, id) == 0)
686 flush_search_node(&sr->nodes[i], sr);
687 sr = sr->next;
688 }
689 }
690 /* And make sure we don't hear from it again. */
691 memcpy(&blacklist[next_blacklisted], sa, salen);
692 next_blacklisted = (next_blacklisted + 1) % DHT_MAX_BLACKLISTED;
693 }
694
695 static int
696 node_blacklisted(const struct sockaddr *sa, int salen)
697 {
698 int i;
699
700 if((unsigned)salen > sizeof(struct sockaddr_storage))
701 abort();
702
703 if(dht_blacklisted(sa, salen))
704 return 1;
705
706 for(i = 0; i < DHT_MAX_BLACKLISTED; i++) {
707 if(memcmp(&blacklist[i], sa, salen) == 0)
708 return 1;
709 }
710
711 return 0;
712 }
713
714 static struct node *
715 append_nodes(struct node *n1, struct node *n2)
716 {
717 struct node *n;
718
719 if(n1 == NULL)
720 return n2;
721
722 if(n2 == NULL)
723 return n1;
724
725 n = n1;
726 while(n->next != NULL)
727 n = n->next;
728
729 n->next = n2;
730 return n1;
731 }
732
733 /* Insert a new node into a bucket, don't check for duplicates.
734 Returns 1 if the node was inserted, 0 if a bucket must be split. */
735 static int
736 insert_node(struct node *node, struct bucket **split_return)
737 {
738 struct bucket *b = find_bucket(node->id, node->ss.ss_family);
739
740 if(b == NULL)
741 return -1;
742
743 if(b->count >= b->max_count) {
744 *split_return = b;
745 return 0;
746 }
747 node->next = b->nodes;
748 b->nodes = node;
749 b->count++;
750 return 1;
751 }
752
753 /* Splits a bucket, and returns the list of nodes that must be reinserted
754 into the routing table. */
755 static int
756 split_bucket_helper(struct bucket *b, struct node **nodes_return)
757 {
758 struct bucket *new;
759 int rc;
760 unsigned char new_id[20];
761
762 if(!in_bucket(myid, b)) {
763 debugf("Attempted to split wrong bucket.\n");
764 return -1;
765 }
766
767 rc = bucket_middle(b, new_id);
768 if(rc < 0)
769 return -1;
770
771 new = calloc(1, sizeof(struct bucket));
772 if(new == NULL)
773 return -1;
774
775 send_cached_ping(b);
776
777 new->af = b->af;
778 memcpy(new->first, new_id, 20);
779 new->time = b->time;
780
781 *nodes_return = b->nodes;
782 b->nodes = NULL;
783 b->count = 0;
784 new->next = b->next;
785 b->next = new;
786
787 if(in_bucket(myid, b)) {
788 new->max_count = b->max_count;
789 b->max_count = MAX(b->max_count / 2, 8);
790 } else {
791 new->max_count = MAX(b->max_count / 2, 8);
792 }
793
794 return 1;
795 }
796
797 static int
798 split_bucket(struct bucket *b)
799 {
800 int rc;
801 struct node *nodes = NULL;
802 struct node *n = NULL;
803
804 debugf("Splitting.\n");
805 rc = split_bucket_helper(b, &nodes);
806 if(rc < 0) {
807 debugf("Couldn't split bucket");
808 return -1;
809 }
810
811 while(n != NULL || nodes != NULL) {
812 struct bucket *split = NULL;
813 if(n == NULL) {
814 n = nodes;
815 nodes = nodes->next;
816 n->next = NULL;
817 }
818 rc = insert_node(n, &split);
819 if(rc < 0) {
820 debugf("Couldn't insert node.\n");
821 free(n);
822 n = NULL;
823 } else if(rc > 0) {
824 n = NULL;
825 } else if(!in_bucket(myid, split)) {
826 free(n);
827 n = NULL;
828 } else {
829 struct node *insert = NULL;
830 debugf("Splitting (recursive).\n");
831 rc = split_bucket_helper(split, &insert);
832 if(rc < 0) {
833 debugf("Couldn't split bucket.\n");
834 free(n);
835 n = NULL;
836 } else {
837 nodes = append_nodes(nodes, insert);
838 }
839 }
840 }
841 return 1;
842 }
843
844 /* We just learnt about a node, not necessarily a new one. Confirm is 1 if
845 the node sent a message, 2 if it sent us a reply. */
846 static struct node *
847 new_node(const unsigned char *id, const struct sockaddr *sa, int salen,
848 int confirm)
849 {
850 struct bucket *b;
851 struct node *n;
852 int mybucket;
853
854 again:
855
856 b = find_bucket(id, sa->sa_family);
857 if(b == NULL)
858 return NULL;
859
860 if(id_cmp(id, myid) == 0)
861 return NULL;
862
863 if(is_martian(sa) || node_blacklisted(sa, salen))
864 return NULL;
865
866 mybucket = in_bucket(myid, b);
867
868 if(confirm == 2)
869 b->time = now.tv_sec;
870
871 n = b->nodes;
872 while(n) {
873 if(id_cmp(n->id, id) == 0) {
874 if(confirm || n->time < now.tv_sec - 15 * 60) {
875 /* Known node. Update stuff. */
876 memcpy((struct sockaddr*)&n->ss, sa, salen);
877 if(confirm)
878 n->time = now.tv_sec;
879 if(confirm >= 2) {
880 n->reply_time = now.tv_sec;
881 n->pinged = 0;
882 n->pinged_time = 0;
883 }
884 }
885 if(confirm == 2)
886 add_search_node(id, sa, salen);
887 return n;
888 }
889 n = n->next;
890 }
891
892 /* New node. */
893
894 if(mybucket) {
895 if(sa->sa_family == AF_INET)
896 mybucket_grow_time = now.tv_sec;
897 else
898 mybucket6_grow_time = now.tv_sec;
899 }
900
901 /* First, try to get rid of a known-bad node. */
902 n = b->nodes;
903 while(n) {
904 if(n->pinged >= 3 && n->pinged_time < now.tv_sec - 15) {
905 memcpy(n->id, id, 20);
906 memcpy((struct sockaddr*)&n->ss, sa, salen);
907 n->time = confirm ? now.tv_sec : 0;
908 n->reply_time = confirm >= 2 ? now.tv_sec : 0;
909 n->pinged_time = 0;
910 n->pinged = 0;
911 if(confirm == 2)
912 add_search_node(id, sa, salen);
913 return n;
914 }
915 n = n->next;
916 }
917
918 if(b->count >= b->max_count) {
919 /* Bucket full. Ping a dubious node */
920 int dubious = 0;
921 n = b->nodes;
922 while(n) {
923 /* Pick the first dubious node that we haven't pinged in the
924 last 15 seconds. This gives nodes the time to reply, but
925 tends to concentrate on the same nodes, so that we get rid
926 of bad nodes fast. */
927 if(!node_good(n)) {
928 dubious = 1;
929 if(n->pinged_time < now.tv_sec - 15) {
930 unsigned char tid[4];
931 debugf("Sending ping to dubious node.\n");
932 make_tid(tid, "pn", 0);
933 send_ping((struct sockaddr*)&n->ss, n->sslen,
934 tid, 4);
935 n->pinged++;
936 n->pinged_time = now.tv_sec;
937 break;
938 }
939 }
940 n = n->next;
941 }
942
943 if(mybucket && !dubious) {
944 int rc;
945 rc = split_bucket(b);
946 if(rc > 0)
947 goto again;
948 return NULL;
949 }
950
951 /* No space for this node. Cache it away for later. */
952 if(confirm || b->cached.ss_family == 0) {
953 memcpy(&b->cached, sa, salen);
954 b->cachedlen = salen;
955 }
956
957 if(confirm == 2)
958 add_search_node(id, sa, salen);
959 return NULL;
960 }
961
962 /* Create a new node. */
963 n = calloc(1, sizeof(struct node));
964 if(n == NULL)
965 return NULL;
966 memcpy(n->id, id, 20);
967 memcpy(&n->ss, sa, salen);
968 n->sslen = salen;
969 n->time = confirm ? now.tv_sec : 0;
970 n->reply_time = confirm >= 2 ? now.tv_sec : 0;
971 n->next = b->nodes;
972 b->nodes = n;
973 b->count++;
974 if(confirm == 2)
975 add_search_node(id, sa, salen);
976 return n;
977 }
978
979 /* Called periodically to purge known-bad nodes. Note that we're very
980 conservative here: broken nodes in the table don't do much harm, we'll
981 recover as soon as we find better ones. */
982 static int
983 expire_buckets(struct bucket *b)
984 {
985 while(b) {
986 struct node *n, *p;
987 int changed = 0;
988
989 while(b->nodes && b->nodes->pinged >= 4) {
990 n = b->nodes;
991 b->nodes = n->next;
992 b->count--;
993 changed = 1;
994 free(n);
995 }
996
997 p = b->nodes;
998 while(p) {
999 while(p->next && p->next->pinged >= 4) {
1000 n = p->next;
1001 p->next = n->next;
1002 b->count--;
1003 changed = 1;
1004 free(n);
1005 }
1006 p = p->next;
1007 }
1008
1009 if(changed)
1010 send_cached_ping(b);
1011
1012 b = b->next;
1013 }
1014 expire_stuff_time = now.tv_sec + 120 + random() % 240;
1015 return 1;
1016 }
1017
1018 /* While a search is in progress, we don't necessarily keep the nodes being
1019 walked in the main bucket table. A search in progress is identified by
1020 a unique transaction id, a short (and hence small enough to fit in the
1021 transaction id of the protocol packets). */
1022
1023 static struct search *
1024 find_search(unsigned short tid, int af)
1025 {
1026 struct search *sr = searches;
1027 while(sr) {
1028 if(sr->tid == tid && sr->af == af)
1029 return sr;
1030 sr = sr->next;
1031 }
1032 return NULL;
1033 }
1034
1035 /* A search contains a list of nodes, sorted by decreasing distance to the
1036 target. We just got a new candidate, insert it at the right spot or
1037 discard it. */
1038
1039 static struct search_node*
1040 insert_search_node(const unsigned char *id,
1041 const struct sockaddr *sa, int salen,
1042 struct search *sr, int replied,
1043 unsigned char *token, int token_len)
1044 {
1045 struct search_node *n;
1046 int i, j;
1047
1048 if(sa->sa_family != sr->af) {
1049 debugf("Attempted to insert node in the wrong family.\n");
1050 return NULL;
1051 }
1052
1053 for(i = 0; i < sr->numnodes; i++) {
1054 if(id_cmp(id, sr->nodes[i].id) == 0) {
1055 n = &sr->nodes[i];
1056 goto found;
1057 }
1058 if(xorcmp(id, sr->nodes[i].id, sr->id) < 0)
1059 break;
1060 }
1061
1062 if(i == SEARCH_NODES)
1063 return NULL;
1064
1065 if(sr->numnodes < SEARCH_NODES)
1066 sr->numnodes++;
1067
1068 for(j = sr->numnodes - 1; j > i; j--) {
1069 sr->nodes[j] = sr->nodes[j - 1];
1070 }
1071
1072 n = &sr->nodes[i];
1073
1074 memset(n, 0, sizeof(struct search_node));
1075 memcpy(n->id, id, 20);
1076
1077 found:
1078 memcpy(&n->ss, sa, salen);
1079 n->sslen = salen;
1080
1081 if(replied) {
1082 n->replied = 1;
1083 n->reply_time = now.tv_sec;
1084 n->request_time = 0;
1085 n->pinged = 0;
1086 }
1087 if(token) {
1088 if(token_len >= 40) {
1089 debugf("Eek! Overlong token.\n");
1090 } else {
1091 memcpy(n->token, token, token_len);
1092 n->token_len = token_len;
1093 }
1094 }
1095
1096 return n;
1097 }
1098
1099 static void
1100 flush_search_node(struct search_node *n, struct search *sr)
1101 {
1102 int i = n - sr->nodes, j;
1103 for(j = i; j < sr->numnodes - 1; j++)
1104 sr->nodes[j] = sr->nodes[j + 1];
1105 sr->numnodes--;
1106 }
1107
1108 static void
1109 expire_searches(dht_callback_t *callback, void *closure)
1110 {
1111 struct search *sr = searches, *previous = NULL;
1112
1113 while(sr) {
1114 struct search *next = sr->next;
1115 if(sr->step_time < now.tv_sec - DHT_SEARCH_EXPIRE_TIME) {
1116 if(previous)
1117 previous->next = next;
1118 else
1119 searches = next;
1120 numsearches--;
1121 if (!sr->done) {
1122 if(callback)
1123 (*callback)(closure,
1124 sr->af == AF_INET ?
1125 DHT_EVENT_SEARCH_DONE : DHT_EVENT_SEARCH_DONE6,
1126 sr->id, NULL, 0);
1127 }
1128 free(sr);
1129 } else {
1130 previous = sr;
1131 }
1132 sr = next;
1133 }
1134 }
1135
1136 /* This must always return 0 or 1, never -1, not even on failure (see below). */
1137 static int
1138 search_send_get_peers(struct search *sr, struct search_node *n)
1139 {
1140 struct node *node;
1141 unsigned char tid[4];
1142
1143 if(n == NULL) {
1144 int i;
1145 for(i = 0; i < sr->numnodes; i++) {
1146 if(sr->nodes[i].pinged < 3 && !sr->nodes[i].replied &&
1147 sr->nodes[i].request_time < now.tv_sec - DHT_SEARCH_RETRANSMIT)
1148 n = &sr->nodes[i];
1149 }
1150 }
1151
1152 if(!n || n->pinged >= 3 || n->replied ||
1153 n->request_time >= now.tv_sec - DHT_SEARCH_RETRANSMIT)
1154 return 0;
1155
1156 debugf("Sending get_peers.\n");
1157 make_tid(tid, "gp", sr->tid);
1158 send_get_peers((struct sockaddr*)&n->ss, n->sslen, tid, 4, sr->id, -1,
1159 n->reply_time >= now.tv_sec - DHT_SEARCH_RETRANSMIT);
1160 n->pinged++;
1161 n->request_time = now.tv_sec;
1162 /* If the node happens to be in our main routing table, mark it
1163 as pinged. */
1164 node = find_node(n->id, n->ss.ss_family);
1165 if(node) pinged(node, NULL);
1166 return 1;
1167 }
1168
1169 /* Insert a new node into any incomplete search. */
1170 static void
1171 add_search_node(const unsigned char *id, const struct sockaddr *sa, int salen)
1172 {
1173 struct search *sr;
1174 for(sr = searches; sr; sr = sr->next) {
1175 if(sr->af == sa->sa_family && sr->numnodes < SEARCH_NODES) {
1176 struct search_node *n =
1177 insert_search_node(id, sa, salen, sr, 0, NULL, 0);
1178 if(n)
1179 search_send_get_peers(sr, n);
1180 }
1181 }
1182 }
1183
1184 /* When a search is in progress, we periodically call search_step to send
1185 further requests. */
1186 static void
1187 search_step(struct search *sr, dht_callback_t *callback, void *closure)
1188 {
1189 int i, j;
1190 int all_done = 1;
1191
1192 /* Check if the first 8 live nodes have replied. */
1193 j = 0;
1194 for(i = 0; i < sr->numnodes && j < 8; i++) {
1195 struct search_node *n = &sr->nodes[i];
1196 if(n->pinged >= 3)
1197 continue;
1198 if(!n->replied) {
1199 all_done = 0;
1200 break;
1201 }
1202 j++;
1203 }
1204
1205 if(all_done) {
1206 if(sr->port == 0) {
1207 goto done;
1208 } else {
1209 int all_acked = 1;
1210 j = 0;
1211 for(i = 0; i < sr->numnodes && j < 8; i++) {
1212 struct search_node *n = &sr->nodes[i];
1213 struct node *node;
1214 unsigned char tid[4];
1215 if(n->pinged >= 3)
1216 continue;
1217 /* A proposed extension to the protocol consists in
1218 omitting the token when storage tables are full. While
1219 I don't think this makes a lot of sense -- just sending
1220 a positive reply is just as good --, let's deal with it. */
1221 if(n->token_len == 0)
1222 n->acked = 1;
1223 if(!n->acked) {
1224 all_acked = 0;
1225 debugf("Sending announce_peer.\n");
1226 make_tid(tid, "ap", sr->tid);
1227 send_announce_peer((struct sockaddr*)&n->ss,
1228 sizeof(struct sockaddr_storage),
1229 tid, 4, sr->id, sr->port,
1230 n->token, n->token_len,
1231 n->reply_time >= now.tv_sec - 15);
1232 n->pinged++;
1233 n->request_time = now.tv_sec;
1234 node = find_node(n->id, n->ss.ss_family);
1235 if(node) pinged(node, NULL);
1236 }
1237 j++;
1238 }
1239 if(all_acked)
1240 goto done;
1241 }
1242 sr->step_time = now.tv_sec;
1243 return;
1244 }
1245
1246 if(sr->step_time + DHT_SEARCH_RETRANSMIT >= now.tv_sec)
1247 return;
1248
1249 j = 0;
1250 for(i = 0; i < sr->numnodes; i++) {
1251 j += search_send_get_peers(sr, &sr->nodes[i]);
1252 if(j >= DHT_INFLIGHT_QUERIES)
1253 break;
1254 }
1255 sr->step_time = now.tv_sec;
1256 return;
1257
1258 done:
1259 sr->done = 1;
1260 if(callback)
1261 (*callback)(closure,
1262 sr->af == AF_INET ?
1263 DHT_EVENT_SEARCH_DONE : DHT_EVENT_SEARCH_DONE6,
1264 sr->id, NULL, 0);
1265 sr->step_time = now.tv_sec;
1266 }
1267
1268 static struct search *
1269 new_search(void)
1270 {
1271 struct search *sr, *oldest = NULL;
1272
1273 /* Find the oldest done search */
1274 sr = searches;
1275 while(sr) {
1276 if(sr->done &&
1277 (oldest == NULL || oldest->step_time > sr->step_time))
1278 oldest = sr;
1279 sr = sr->next;
1280 }
1281
1282 /* The oldest slot is expired. */
1283 if(oldest && oldest->step_time < now.tv_sec - DHT_SEARCH_EXPIRE_TIME)
1284 return oldest;
1285
1286 /* Allocate a new slot. */
1287 if(numsearches < DHT_MAX_SEARCHES) {
1288 sr = calloc(1, sizeof(struct search));
1289 if(sr != NULL) {
1290 sr->next = searches;
1291 searches = sr;
1292 numsearches++;
1293 return sr;
1294 }
1295 }
1296
1297 /* Return oldest slot if it's done. */
1298 if(oldest && oldest->done)
1299 return oldest;
1300
1301 /* No available slots found, return NULL. */
1302 return NULL;
1303 }
1304
1305 /* Insert the contents of a bucket into a search structure. */
1306 static void
1307 insert_search_bucket(struct bucket *b, struct search *sr)
1308 {
1309 struct node *n;
1310 n = b->nodes;
1311 while(n) {
1312 insert_search_node(n->id, (struct sockaddr*)&n->ss, n->sslen,
1313 sr, 0, NULL, 0);
1314 n = n->next;
1315 }
1316 }
1317
1318 /* Start a search. If port is non-zero, perform an announce when the
1319 search is complete. */
1320 int
1321 dht_search(const unsigned char *id, int port, int af,
1322 dht_callback_t *callback, void *closure)
1323 {
1324 struct search *sr;
1325 struct storage *st;
1326 struct bucket *b = find_bucket(id, af);
1327
1328 if(b == NULL) {
1329 errno = EAFNOSUPPORT;
1330 return -1;
1331 }
1332
1333 /* Try to answer this search locally. In a fully grown DHT this
1334 is very unlikely, but people are running modified versions of
1335 this code in private DHTs with very few nodes. What's wrong
1336 with flooding? */
1337 if(callback) {
1338 st = find_storage(id);
1339 if(st) {
1340 unsigned short swapped;
1341 unsigned char buf[18];
1342 int i;
1343
1344 debugf("Found local data (%d peers).\n", st->numpeers);
1345
1346 for(i = 0; i < st->numpeers; i++) {
1347 swapped = htons(st->peers[i].port);
1348 if(st->peers[i].len == 4) {
1349 memcpy(buf, st->peers[i].ip, 4);
1350 memcpy(buf + 4, &swapped, 2);
1351 (*callback)(closure, DHT_EVENT_VALUES, id,
1352 (void*)buf, 6);
1353 } else if(st->peers[i].len == 16) {
1354 memcpy(buf, st->peers[i].ip, 16);
1355 memcpy(buf + 16, &swapped, 2);
1356 (*callback)(closure, DHT_EVENT_VALUES6, id,
1357 (void*)buf, 18);
1358 }
1359 }
1360 }
1361 }
1362
1363 sr = searches;
1364 while(sr) {
1365 if(sr->af == af && id_cmp(sr->id, id) == 0)
1366 break;
1367 sr = sr->next;
1368 }
1369
1370 int sr_duplicate = sr && !sr->done;
1371
1372 if(sr) {
1373 /* We're reusing data from an old search. Reusing the same tid
1374 means that we can merge replies for both searches. */
1375 int i;
1376 sr->done = 0;
1377 again:
1378 for(i = 0; i < sr->numnodes; i++) {
1379 struct search_node *n;
1380 n = &sr->nodes[i];
1381 /* Discard any doubtful nodes. */
1382 if(n->pinged >= 3 || n->reply_time < now.tv_sec - 7200) {
1383 flush_search_node(n, sr);
1384 goto again;
1385 }
1386 n->pinged = 0;
1387 n->token_len = 0;
1388 n->replied = 0;
1389 n->acked = 0;
1390 }
1391 } else {
1392 sr = new_search();
1393 if(sr == NULL) {
1394 errno = ENOSPC;
1395 return -1;
1396 }
1397 sr->af = af;
1398 sr->tid = search_id++;
1399 sr->step_time = 0;
1400 memcpy(sr->id, id, 20);
1401 sr->done = 0;
1402 sr->numnodes = 0;
1403 }
1404
1405 sr->port = port;
1406
1407 insert_search_bucket(b, sr);
1408
1409 if(sr->numnodes < SEARCH_NODES) {
1410 struct bucket *p = previous_bucket(b);
1411 if(b->next)
1412 insert_search_bucket(b->next, sr);
1413 if(p)
1414 insert_search_bucket(p, sr);
1415 }
1416 if(sr->numnodes < SEARCH_NODES)
1417 insert_search_bucket(find_bucket(myid, af), sr);
1418
1419 search_step(sr, callback, closure);
1420 search_time = now.tv_sec;
1421 if(sr_duplicate) {
1422 return 0;
1423 } else {
1424 return 1;
1425 }
1426 }
1427
1428 /* A struct storage stores all the stored peer addresses for a given info
1429 hash. */
1430
1431 static struct storage *
1432 find_storage(const unsigned char *id)
1433 {
1434 struct storage *st = storage;
1435
1436 while(st) {
1437 if(id_cmp(id, st->id) == 0)
1438 break;
1439 st = st->next;
1440 }
1441 return st;
1442 }
1443
1444 static int
1445 storage_store(const unsigned char *id,
1446 const struct sockaddr *sa, unsigned short port)
1447 {
1448 int i, len;
1449 struct storage *st;
1450 unsigned char *ip;
1451
1452 if(sa->sa_family == AF_INET) {
1453 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1454 ip = (unsigned char*)&sin->sin_addr;
1455 len = 4;
1456 } else if(sa->sa_family == AF_INET6) {
1457 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1458 ip = (unsigned char*)&sin6->sin6_addr;
1459 len = 16;
1460 } else {
1461 return -1;
1462 }
1463
1464 st = find_storage(id);
1465
1466 if(st == NULL) {
1467 if(numstorage >= DHT_MAX_HASHES)
1468 return -1;
1469 st = calloc(1, sizeof(struct storage));
1470 if(st == NULL) return -1;
1471 memcpy(st->id, id, 20);
1472 st->next = storage;
1473 storage = st;
1474 numstorage++;
1475 }
1476
1477 for(i = 0; i < st->numpeers; i++) {
1478 if(st->peers[i].port == port && st->peers[i].len == len &&
1479 memcmp(st->peers[i].ip, ip, len) == 0)
1480 break;
1481 }
1482
1483 if(i < st->numpeers) {
1484 /* Already there, only need to refresh */
1485 st->peers[i].time = now.tv_sec;
1486 return 0;
1487 } else {
1488 struct peer *p;
1489 if(i >= st->maxpeers) {
1490 /* Need to expand the array. */
1491 struct peer *new_peers;
1492 int n;
1493 if(st->maxpeers >= DHT_MAX_PEERS)
1494 return 0;
1495 n = st->maxpeers == 0 ? 2 : 2 * st->maxpeers;
1496 n = MIN(n, DHT_MAX_PEERS);
1497 new_peers = realloc(st->peers, n * sizeof(struct peer));
1498 if(new_peers == NULL)
1499 return -1;
1500 st->peers = new_peers;
1501 st->maxpeers = n;
1502 }
1503 p = &st->peers[st->numpeers++];
1504 p->time = now.tv_sec;
1505 p->len = len;
1506 memcpy(p->ip, ip, len);
1507 p->port = port;
1508 return 1;
1509 }
1510 }
1511
1512 static int
1513 expire_storage(void)
1514 {
1515 struct storage *st = storage, *previous = NULL;
1516 while(st) {
1517 int i = 0;
1518 while(i < st->numpeers) {
1519 if(st->peers[i].time < now.tv_sec - 32 * 60) {
1520 if(i != st->numpeers - 1)
1521 st->peers[i] = st->peers[st->numpeers - 1];
1522 st->numpeers--;
1523 } else {
1524 i++;
1525 }
1526 }
1527
1528 if(st->numpeers == 0) {
1529 free(st->peers);
1530 if(previous)
1531 previous->next = st->next;
1532 else
1533 storage = st->next;
1534 free(st);
1535 if(previous)
1536 st = previous->next;
1537 else
1538 st = storage;
1539 numstorage--;
1540 if(numstorage < 0) {
1541 debugf("Eek... numstorage became negative.\n");
1542 numstorage = 0;
1543 }
1544 } else {
1545 previous = st;
1546 st = st->next;
1547 }
1548 }
1549 return 1;
1550 }
1551
1552 static int
1553 rotate_secrets(void)
1554 {
1555 int rc;
1556
1557 rotate_secrets_time = now.tv_sec + 900 + random() % 1800;
1558
1559 memcpy(oldsecret, secret, sizeof(secret));
1560 rc = dht_random_bytes(secret, sizeof(secret));
1561
1562 if(rc < 0)
1563 return -1;
1564
1565 return 1;
1566 }
1567
1568 #ifndef TOKEN_SIZE
1569 #define TOKEN_SIZE 8
1570 #endif
1571
1572 static void
1573 make_token(const struct sockaddr *sa, int old, unsigned char *token_return)
1574 {
1575 void *ip;
1576 int iplen;
1577 unsigned short port;
1578
1579 if(sa->sa_family == AF_INET) {
1580 struct sockaddr_in *sin = (struct sockaddr_in*)sa;
1581 ip = &sin->sin_addr;
1582 iplen = 4;
1583 port = htons(sin->sin_port);
1584 } else if(sa->sa_family == AF_INET6) {
1585 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
1586 ip = &sin6->sin6_addr;
1587 iplen = 16;
1588 port = htons(sin6->sin6_port);
1589 } else {
1590 abort();
1591 }
1592
1593 dht_hash(token_return, TOKEN_SIZE,
1594 old ? oldsecret : secret, sizeof(secret),
1595 ip, iplen, (unsigned char*)&port, 2);
1596 }
1597 static int
1598 token_match(const unsigned char *token, int token_len,
1599 const struct sockaddr *sa)
1600 {
1601 unsigned char t[TOKEN_SIZE];
1602 if(token_len != TOKEN_SIZE)
1603 return 0;
1604 make_token(sa, 0, t);
1605 if(memcmp(t, token, TOKEN_SIZE) == 0)
1606 return 1;
1607 make_token(sa, 1, t);
1608 if(memcmp(t, token, TOKEN_SIZE) == 0)
1609 return 1;
1610 return 0;
1611 }
1612
1613 int
1614 dht_nodes(int af, int *good_return, int *dubious_return, int *cached_return,
1615 int *incoming_return)
1616 {
1617 int good = 0, dubious = 0, cached = 0, incoming = 0;
1618 struct bucket *b = af == AF_INET ? buckets : buckets6;
1619
1620 while(b) {
1621 struct node *n = b->nodes;
1622 while(n) {
1623 if(node_good(n)) {
1624 good++;
1625 if(n->time > n->reply_time)
1626 incoming++;
1627 } else {
1628 dubious++;
1629 }
1630 n = n->next;
1631 }
1632 if(b->cached.ss_family > 0)
1633 cached++;
1634 b = b->next;
1635 }
1636 if(good_return)
1637 *good_return = good;
1638 if(dubious_return)
1639 *dubious_return = dubious;
1640 if(cached_return)
1641 *cached_return = cached;
1642 if(incoming_return)
1643 *incoming_return = incoming;
1644 return good + dubious;
1645 }
1646
1647 static void
1648 dump_bucket(FILE *f, struct bucket *b)
1649 {
1650 struct node *n = b->nodes;
1651 fprintf(f, "Bucket ");
1652 print_hex(f, b->first, 20);
1653 fprintf(f, " count %d/%d age %d%s%s:\n",
1654 b->count, b->max_count, (int)(now.tv_sec - b->time),
1655 in_bucket(myid, b) ? " (mine)" : "",
1656 b->cached.ss_family ? " (cached)" : "");
1657 while(n) {
1658 char buf[512];
1659 unsigned short port;
1660 fprintf(f, " Node ");
1661 print_hex(f, n->id, 20);
1662 if(n->ss.ss_family == AF_INET) {
1663 struct sockaddr_in *sin = (struct sockaddr_in*)&n->ss;
1664 inet_ntop(AF_INET, &sin->sin_addr, buf, 512);
1665 port = ntohs(sin->sin_port);
1666 } else if(n->ss.ss_family == AF_INET6) {
1667 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&n->ss;
1668 inet_ntop(AF_INET6, &sin6->sin6_addr, buf, 512);
1669 port = ntohs(sin6->sin6_port);
1670 } else {
1671 snprintf(buf, 512, "unknown(%d)", n->ss.ss_family);
1672 port = 0;
1673 }
1674
1675 if(n->ss.ss_family == AF_INET6)
1676 fprintf(f, " [%s]:%d ", buf, port);
1677 else
1678 fprintf(f, " %s:%d ", buf, port);
1679 if(n->time != n->reply_time)
1680 fprintf(f, "age %ld, %ld",
1681 (long)(now.tv_sec - n->time),
1682 (long)(now.tv_sec - n->reply_time));
1683 else
1684 fprintf(f, "age %ld", (long)(now.tv_sec - n->time));
1685 if(n->pinged)
1686 fprintf(f, " (%d)", n->pinged);
1687 if(node_good(n))
1688 fprintf(f, " (good)");
1689 fprintf(f, "\n");
1690 n = n->next;
1691 }
1692
1693 }
1694
1695 void
1696 dht_dump_tables(FILE *f)
1697 {
1698 int i;
1699 struct bucket *b;
1700 struct storage *st = storage;
1701 struct search *sr = searches;
1702
1703 fprintf(f, "My id ");
1704 print_hex(f, myid, 20);
1705 fprintf(f, "\n");
1706
1707 b = buckets;
1708 while(b) {
1709 dump_bucket(f, b);
1710 b = b->next;
1711 }
1712
1713 fprintf(f, "\n");
1714
1715 b = buckets6;
1716 while(b) {
1717 dump_bucket(f, b);
1718 b = b->next;
1719 }
1720
1721 while(sr) {
1722 fprintf(f, "\nSearch%s id ", sr->af == AF_INET6 ? " (IPv6)" : "");
1723 print_hex(f, sr->id, 20);
1724 fprintf(f, " age %d%s\n", (int)(now.tv_sec - sr->step_time),
1725 sr->done ? " (done)" : "");
1726 for(i = 0; i < sr->numnodes; i++) {
1727 struct search_node *n = &sr->nodes[i];
1728 fprintf(f, "Node %d id ", i);
1729 print_hex(f, n->id, 20);
1730 fprintf(f, " bits %d age ", common_bits(sr->id, n->id));
1731 if(n->request_time)
1732 fprintf(f, "%d, ", (int)(now.tv_sec - n->request_time));
1733 fprintf(f, "%d", (int)(now.tv_sec - n->reply_time));
1734 if(n->pinged)
1735 fprintf(f, " (%d)", n->pinged);
1736 fprintf(f, "%s%s.\n",
1737 find_node(n->id, sr->af) ? " (known)" : "",
1738 n->replied ? " (replied)" : "");
1739 }
1740 sr = sr->next;
1741 }
1742
1743 while(st) {
1744 fprintf(f, "\nStorage ");
1745 print_hex(f, st->id, 20);
1746 fprintf(f, " %d/%d nodes:", st->numpeers, st->maxpeers);
1747 for(i = 0; i < st->numpeers; i++) {
1748 char buf[100];
1749 if(st->peers[i].len == 4) {
1750 inet_ntop(AF_INET, st->peers[i].ip, buf, 100);
1751 } else if(st->peers[i].len == 16) {
1752 buf[0] = '[';
1753 inet_ntop(AF_INET6, st->peers[i].ip, buf + 1, 98);
1754 strcat(buf, "]");
1755 } else {
1756 strcpy(buf, "???");
1757 }
1758 fprintf(f, " %s:%u (%ld)",
1759 buf, st->peers[i].port,
1760 (long)(now.tv_sec - st->peers[i].time));
1761 }
1762 st = st->next;
1763 }
1764
1765 fprintf(f, "\n\n");
1766 fflush(f);
1767 }
1768
1769 int
1770 dht_init(int s, int s6, const unsigned char *id, const unsigned char *v)
1771 {
1772 int rc;
1773
1774 if(dht_socket >= 0 || dht_socket6 >= 0 || buckets || buckets6) {
1775 errno = EBUSY;
1776 return -1;
1777 }
1778
1779 searches = NULL;
1780 numsearches = 0;
1781
1782 storage = NULL;
1783 numstorage = 0;
1784
1785 if(s >= 0) {
1786 buckets = calloc(1, sizeof(struct bucket));
1787 if(buckets == NULL)
1788 return -1;
1789 buckets->max_count = 128;
1790 buckets->af = AF_INET;
1791 }
1792
1793 if(s6 >= 0) {
1794 buckets6 = calloc(1, sizeof(struct bucket));
1795 if(buckets6 == NULL)
1796 return -1;
1797 buckets6->max_count = 128;
1798 buckets6->af = AF_INET6;
1799 }
1800
1801 memcpy(myid, id, 20);
1802 if(v) {
1803 memcpy(my_v, "1:v4:", 5);
1804 memcpy(my_v + 5, v, 4);
1805 have_v = 1;
1806 } else {
1807 have_v = 0;
1808 }
1809
1810 dht_gettimeofday(&now, NULL);
1811
1812 mybucket_grow_time = now.tv_sec;
1813 mybucket6_grow_time = now.tv_sec;
1814 confirm_nodes_time = now.tv_sec + random() % 3;
1815
1816 search_id = random() & 0xFFFF;
1817 search_time = 0;
1818
1819 next_blacklisted = 0;
1820
1821 token_bucket_time = now.tv_sec;
1822 token_bucket_tokens = MAX_TOKEN_BUCKET_TOKENS;
1823
1824 memset(secret, 0, sizeof(secret));
1825 rc = rotate_secrets();
1826 if(rc < 0)
1827 goto fail;
1828
1829 dht_socket = s;
1830 dht_socket6 = s6;
1831
1832 expire_buckets(buckets);
1833 expire_buckets(buckets6);
1834
1835 return 1;
1836
1837 fail:
1838 free(buckets);
1839 buckets = NULL;
1840 free(buckets6);
1841 buckets6 = NULL;
1842 return -1;
1843 }
1844
1845 int
1846 dht_uninit()
1847 {
1848 if(dht_socket < 0 && dht_socket6 < 0) {
1849 errno = EINVAL;
1850 return -1;
1851 }
1852
1853 dht_socket = -1;
1854 dht_socket6 = -1;
1855
1856 while(buckets) {
1857 struct bucket *b = buckets;
1858 buckets = b->next;
1859 while(b->nodes) {
1860 struct node *n = b->nodes;
1861 b->nodes = n->next;
1862 free(n);
1863 }
1864 free(b);
1865 }
1866
1867 while(buckets6) {
1868 struct bucket *b = buckets6;
1869 buckets6 = b->next;
1870 while(b->nodes) {
1871 struct node *n = b->nodes;
1872 b->nodes = n->next;
1873 free(n);
1874 }
1875 free(b);
1876 }
1877
1878 while(storage) {
1879 struct storage *st = storage;
1880 storage = storage->next;
1881 free(st->peers);
1882 free(st);
1883 }
1884
1885 while(searches) {
1886 struct search *sr = searches;
1887 searches = searches->next;
1888 free(sr);
1889 }
1890
1891 return 1;
1892 }
1893
1894 /* Rate control for requests we receive. */
1895
1896 static int
1897 token_bucket(void)
1898 {
1899 if(token_bucket_tokens == 0) {
1900 token_bucket_tokens = MIN(MAX_TOKEN_BUCKET_TOKENS,
1901 100 * (now.tv_sec - token_bucket_time));
1902 token_bucket_time = now.tv_sec;
1903 }
1904
1905 if(token_bucket_tokens == 0)
1906 return 0;
1907
1908 token_bucket_tokens--;
1909 return 1;
1910 }
1911
1912 static int
1913 neighbourhood_maintenance(int af)
1914 {
1915 unsigned char id[20];
1916 struct bucket *b = find_bucket(myid, af);
1917 struct bucket *q;
1918 struct node *n;
1919
1920 if(b == NULL)
1921 return 0;
1922
1923 memcpy(id, myid, 20);
1924 id[19] = random() & 0xFF;
1925 q = b;
1926 if(q->next && (q->count == 0 || (random() & 7) == 0))
1927 q = b->next;
1928 if(q->count == 0 || (random() & 7) == 0) {
1929 struct bucket *r;
1930 r = previous_bucket(b);
1931 if(r && r->count > 0)
1932 q = r;
1933 }
1934
1935 if(q) {
1936 /* Since our node-id is the same in both DHTs, it's probably
1937 profitable to query both families. */
1938 int want = dht_socket >= 0 && dht_socket6 >= 0 ? (WANT4 | WANT6) : -1;
1939 n = random_node(q);
1940 if(n) {
1941 unsigned char tid[4];
1942 debugf("Sending find_node for%s neighborhood maintenance.\n",
1943 af == AF_INET6 ? " IPv6" : "");
1944 make_tid(tid, "fn", 0);
1945 send_find_node((struct sockaddr*)&n->ss, n->sslen,
1946 tid, 4, id, want,
1947 n->reply_time >= now.tv_sec - 15);
1948 pinged(n, q);
1949 }
1950 return 1;
1951 }
1952 return 0;
1953 }
1954
1955 static int
1956 bucket_maintenance(int af)
1957 {
1958 struct bucket *b;
1959
1960 b = af == AF_INET ? buckets : buckets6;
1961
1962 while(b) {
1963 /* 10 minutes for an 8-node bucket */
1964 int to = MAX(600 / (b->max_count / 8), 30);
1965 struct bucket *q;
1966 if(b->time < now.tv_sec - to) {
1967 /* This bucket hasn't seen any positive confirmation for a long
1968 time. Pick a random id in this bucket's range, and send
1969 a request to a random node. */
1970 unsigned char id[20];
1971 struct node *n;
1972 int rc;
1973
1974 rc = bucket_random(b, id);
1975 if(rc < 0)
1976 memcpy(id, b->first, 20);
1977
1978 q = b;
1979 /* If the bucket is empty, we try to fill it from a neighbour.
1980 We also sometimes do it gratuitiously to recover from
1981 buckets full of broken nodes. */
1982 if(q->next && (q->count == 0 || (random() & 7) == 0))
1983 q = b->next;
1984 if(q->count == 0 || (random() & 7) == 0) {
1985 struct bucket *r;
1986 r = previous_bucket(b);
1987 if(r && r->count > 0)
1988 q = r;
1989 }
1990
1991 if(q) {
1992 n = random_node(q);
1993 if(n) {
1994 unsigned char tid[4];
1995 int want = -1;
1996
1997 if(dht_socket >= 0 && dht_socket6 >= 0) {
1998 struct bucket *otherbucket;
1999 otherbucket =
2000 find_bucket(id, af == AF_INET ? AF_INET6 : AF_INET);
2001 if(otherbucket &&
2002 otherbucket->count < otherbucket->max_count)
2003 /* The corresponding bucket in the other family
2004 is not full -- querying both is useful. */
2005 want = WANT4 | WANT6;
2006 else if(random() % 37 == 0)
2007 /* Most of the time, this just adds overhead.
2008 However, it might help stitch back one of
2009 the DHTs after a network collapse, so query
2010 both, but only very occasionally. */
2011 want = WANT4 | WANT6;
2012 }
2013
2014 debugf("Sending find_node for%s bucket maintenance.\n",
2015 af == AF_INET6 ? " IPv6" : "");
2016 make_tid(tid, "fn", 0);
2017 send_find_node((struct sockaddr*)&n->ss, n->sslen,
2018 tid, 4, id, want,
2019 n->reply_time >= now.tv_sec - 15);
2020 pinged(n, q);
2021 /* In order to avoid sending queries back-to-back,
2022 give up for now and reschedule us soon. */
2023 return 1;
2024 }
2025 }
2026 }
2027 b = b->next;
2028 }
2029 return 0;
2030 }
2031
2032 int
2033 dht_periodic(const void *buf, size_t buflen,
2034 const struct sockaddr *from, int fromlen,
2035 time_t *tosleep,
2036 dht_callback_t *callback, void *closure)
2037 {
2038 dht_gettimeofday(&now, NULL);
2039
2040 if(buflen > 0) {
2041 int message;
2042 struct parsed_message m;
2043 unsigned short ttid;
2044
2045 if(is_martian(from))
2046 goto dontread;
2047
2048 if(node_blacklisted(from, fromlen)) {
2049 debugf("Received packet from blacklisted node.\n");
2050 goto dontread;
2051 }
2052
2053 if(((char*)buf)[buflen] != '\0') {
2054 debugf("Unterminated message.\n");
2055 errno = EINVAL;
2056 return -1;
2057 }
2058
2059 memset(&m, 0, sizeof(m));
2060 message = parse_message(buf, buflen, &m);
2061
2062 if(message < 0 || message == ERROR || id_cmp(m.id, zeroes) == 0) {
2063 debugf("Unparseable message: ");
2064 debug_printable(buf, buflen);
2065 debugf("\n");
2066 goto dontread;
2067 }
2068
2069 if(id_cmp(m.id, myid) == 0) {
2070 debugf("Received message from self.\n");
2071 goto dontread;
2072 }
2073
2074 if(message > REPLY) {
2075 /* Rate limit requests. */
2076 if(!token_bucket()) {
2077 debugf("Dropping request due to rate limiting.\n");
2078 goto dontread;
2079 }
2080 }
2081
2082 switch(message) {
2083 case REPLY:
2084 if(m.tid_len != 4) {
2085 debugf("Broken node truncates transaction ids: ");
2086 debug_printable(buf, buflen);
2087 debugf("\n");
2088 /* This is really annoying, as it means that we will
2089 time-out all our searches that go through this node.
2090 Kill it. */
2091 blacklist_node(m.id, from, fromlen);
2092 goto dontread;
2093 }
2094 if(tid_match(m.tid, "pn", NULL)) {
2095 debugf("Pong!\n");
2096 new_node(m.id, from, fromlen, 2);
2097 } else if(tid_match(m.tid, "fn", NULL) ||
2098 tid_match(m.tid, "gp", NULL)) {
2099 int gp = 0;
2100 struct search *sr = NULL;
2101 if(tid_match(m.tid, "gp", &ttid)) {
2102 gp = 1;
2103 sr = find_search(ttid, from->sa_family);
2104 }
2105 debugf("Nodes found (%d+%d)%s!\n",
2106 m.nodes_len/26, m.nodes6_len/38,
2107 gp ? " for get_peers" : "");
2108 if(m.nodes_len % 26 != 0 || m.nodes6_len % 38 != 0) {
2109 debugf("Unexpected length for node info!\n");
2110 blacklist_node(m.id, from, fromlen);
2111 } else if(gp && sr == NULL) {
2112 debugf("Unknown search!\n");
2113 new_node(m.id, from, fromlen, 1);
2114 } else {
2115 int i;
2116 new_node(m.id, from, fromlen, 2);
2117 for(i = 0; i < m.nodes_len / 26; i++) {
2118 unsigned char *ni = m.nodes + i * 26;
2119 struct sockaddr_in sin;
2120 if(id_cmp(ni, myid) == 0)
2121 continue;
2122 memset(&sin, 0, sizeof(sin));
2123 sin.sin_family = AF_INET;
2124 memcpy(&sin.sin_addr, ni + 20, 4);
2125 memcpy(&sin.sin_port, ni + 24, 2);
2126 new_node(ni, (struct sockaddr*)&sin, sizeof(sin), 0);
2127 if(sr && sr->af == AF_INET) {
2128 insert_search_node(ni,
2129 (struct sockaddr*)&sin,
2130 sizeof(sin),
2131 sr, 0, NULL, 0);
2132 }
2133 }
2134 for(i = 0; i < m.nodes6_len / 38; i++) {
2135 unsigned char *ni = m.nodes6 + i * 38;
2136 struct sockaddr_in6 sin6;
2137 if(id_cmp(ni, myid) == 0)
2138 continue;
2139 memset(&sin6, 0, sizeof(sin6));
2140 sin6.sin6_family = AF_INET6;
2141 memcpy(&sin6.sin6_addr, ni + 20, 16);
2142 memcpy(&sin6.sin6_port, ni + 36, 2);
2143 new_node(ni, (struct sockaddr*)&sin6, sizeof(sin6), 0);
2144 if(sr && sr->af == AF_INET6) {
2145 insert_search_node(ni,
2146 (struct sockaddr*)&sin6,
2147 sizeof(sin6),
2148 sr, 0, NULL, 0);
2149 }
2150 }
2151 if(sr)
2152 /* Since we received a reply, the number of
2153 requests in flight has decreased. Let's push
2154 another request. */
2155 search_send_get_peers(sr, NULL);
2156 }
2157 if(sr) {
2158 insert_search_node(m.id, from, fromlen, sr,
2159 1, m.token, m.token_len);
2160 if(m.values_len > 0 || m.values6_len > 0) {
2161 debugf("Got values (%d+%d)!\n",
2162 m.values_len / 6, m.values6_len / 18);
2163 if(callback) {
2164 if(m.values_len > 0)
2165 (*callback)(closure, DHT_EVENT_VALUES, sr->id,
2166 (void*)m.values, m.values_len);
2167
2168 if(m.values6_len > 0)
2169 (*callback)(closure, DHT_EVENT_VALUES6, sr->id,
2170 (void*)m.values6, m.values6_len);
2171 }
2172 }
2173 }
2174 } else if(tid_match(m.tid, "ap", &ttid)) {
2175 struct search *sr;
2176 debugf("Got reply to announce_peer.\n");
2177 sr = find_search(ttid, from->sa_family);
2178 if(!sr) {
2179 debugf("Unknown search!\n");
2180 new_node(m.id, from, fromlen, 1);
2181 } else {
2182 int i;
2183 new_node(m.id, from, fromlen, 2);
2184 for(i = 0; i < sr->numnodes; i++)
2185 if(id_cmp(sr->nodes[i].id, m.id) == 0) {
2186 sr->nodes[i].request_time = 0;
2187 sr->nodes[i].reply_time = now.tv_sec;
2188 sr->nodes[i].acked = 1;
2189 sr->nodes[i].pinged = 0;
2190 break;
2191 }
2192 /* See comment for gp above. */
2193 search_send_get_peers(sr, NULL);
2194 }
2195 } else {
2196 debugf("Unexpected reply: ");
2197 debug_printable(buf, buflen);
2198 debugf("\n");
2199 }
2200 break;
2201 case PING:
2202 debugf("Ping (%d)!\n", m.tid_len);
2203 new_node(m.id, from, fromlen, 1);
2204 debugf("Sending pong.\n");
2205 send_pong(from, fromlen, m.tid, m.tid_len);
2206 break;
2207 case FIND_NODE:
2208 debugf("Find node!\n");
2209 new_node(m.id, from, fromlen, 1);
2210 debugf("Sending closest nodes (%d).\n", m.want);
2211 send_closest_nodes(from, fromlen,
2212 m.tid, m.tid_len, m.target, m.want,
2213 0, NULL, NULL, 0);
2214 break;
2215 case GET_PEERS:
2216 debugf("Get_peers!\n");
2217 new_node(m.id, from, fromlen, 1);
2218 if(id_cmp(m.info_hash, zeroes) == 0) {
2219 debugf("Eek! Got get_peers with no info_hash.\n");
2220 send_error(from, fromlen, m.tid, m.tid_len,
2221 203, "Get_peers with no info_hash");
2222 break;
2223 } else {
2224 struct storage *st = find_storage(m.info_hash);
2225 unsigned char token[TOKEN_SIZE];
2226 make_token(from, 0, token);
2227 if(st && st->numpeers > 0) {
2228 debugf("Sending found%s peers.\n",
2229 from->sa_family == AF_INET6 ? " IPv6" : "");
2230 send_closest_nodes(from, fromlen,
2231 m.tid, m.tid_len,
2232 m.info_hash, m.want,
2233 from->sa_family, st,
2234 token, TOKEN_SIZE);
2235 } else {
2236 debugf("Sending nodes for get_peers.\n");
2237 send_closest_nodes(from, fromlen,
2238 m.tid, m.tid_len, m.info_hash, m.want,
2239 0, NULL, token, TOKEN_SIZE);
2240 }
2241 }
2242 break;
2243 case ANNOUNCE_PEER:
2244 debugf("Announce peer!\n");
2245 new_node(m.id, from, fromlen, 1);
2246 if(id_cmp(m.info_hash, zeroes) == 0) {
2247 debugf("Announce_peer with no info_hash.\n");
2248 send_error(from, fromlen, m.tid, m.tid_len,
2249 203, "Announce_peer with no info_hash");
2250 break;
2251 }
2252 if(!token_match(m.token, m.token_len, from)) {
2253 debugf("Incorrect token for announce_peer.\n");
2254 send_error(from, fromlen, m.tid, m.tid_len,
2255 203, "Announce_peer with wrong token");
2256 break;
2257 }
2258 if(m.implied_port != 0) {
2259 /* Do this even if port > 0. That's what the spec says. */
2260 switch(from->sa_family) {
2261 case AF_INET:
2262 m.port = htons(((struct sockaddr_in*)from)->sin_port);
2263 break;
2264 case AF_INET6:
2265 m.port = htons(((struct sockaddr_in6*)from)->sin6_port);
2266 break;
2267 }
2268 }
2269 if(m.port == 0) {
2270 debugf("Announce_peer with forbidden port %d.\n", m.port);
2271 send_error(from, fromlen, m.tid, m.tid_len,
2272 203, "Announce_peer with forbidden port number");
2273 break;
2274 }
2275 storage_store(m.info_hash, from, m.port);
2276 /* Note that if storage_store failed, we lie to the requestor.
2277 This is to prevent them from backtracking, and hence
2278 polluting the DHT. */
2279 debugf("Sending peer announced.\n");
2280 send_peer_announced(from, fromlen, m.tid, m.tid_len);
2281 }
2282 }
2283
2284 dontread:
2285 if(now.tv_sec >= rotate_secrets_time)
2286 rotate_secrets();
2287
2288 if(now.tv_sec >= expire_stuff_time) {
2289 expire_buckets(buckets);
2290 expire_buckets(buckets6);
2291 expire_storage();
2292 expire_searches(callback, closure);
2293 }
2294
2295 if(search_time > 0 && now.tv_sec >= search_time) {
2296 struct search *sr;
2297 sr = searches;
2298 while(sr) {
2299 if(!sr->done &&
2300 sr->step_time + DHT_SEARCH_RETRANSMIT / 2 + 1 <= now.tv_sec) {
2301 search_step(sr, callback, closure);
2302 }
2303 sr = sr->next;
2304 }
2305
2306 search_time = 0;
2307
2308 sr = searches;
2309 while(sr) {
2310 if(!sr->done) {
2311 time_t tm = sr->step_time +
2312 DHT_SEARCH_RETRANSMIT + random() % DHT_SEARCH_RETRANSMIT;
2313 if(search_time == 0 || search_time > tm)
2314 search_time = tm;
2315 }
2316 sr = sr->next;
2317 }
2318 }
2319
2320 if(now.tv_sec >= confirm_nodes_time) {
2321 int soon = 0;
2322
2323 soon |= bucket_maintenance(AF_INET);
2324 soon |= bucket_maintenance(AF_INET6);
2325
2326 if(!soon) {
2327 if(mybucket_grow_time >= now.tv_sec - 150)
2328 soon |= neighbourhood_maintenance(AF_INET);
2329 if(mybucket6_grow_time >= now.tv_sec - 150)
2330 soon |= neighbourhood_maintenance(AF_INET6);
2331 }
2332
2333 /* Given the timeouts in bucket_maintenance, with a 22-bucket
2334 table, worst case is a ping every 18 seconds (22 buckets plus
2335 11 buckets overhead for the larger buckets). Keep the "soon"
2336 case within 15 seconds, which gives some margin for neighbourhood
2337 maintenance. */
2338
2339 if(soon)
2340 confirm_nodes_time = now.tv_sec + 5 + random() % 10;
2341 else
2342 confirm_nodes_time = now.tv_sec + 60 + random() % 120;
2343 }
2344
2345 if(confirm_nodes_time > now.tv_sec)
2346 *tosleep = confirm_nodes_time - now.tv_sec;
2347 else
2348 *tosleep = 0;
2349
2350 if(search_time > 0) {
2351 if(search_time <= now.tv_sec)
2352 *tosleep = 0;
2353 else if(*tosleep > search_time - now.tv_sec)
2354 *tosleep = search_time - now.tv_sec;
2355 }
2356
2357 return 1;
2358 }
2359
2360 int
2361 dht_get_nodes(struct sockaddr_in *sin, int *num,
2362 struct sockaddr_in6 *sin6, int *num6)
2363 {
2364 int i, j;
2365 struct bucket *b;
2366 struct node *n;
2367
2368 i = 0;
2369
2370 /* For restoring to work without discarding too many nodes, the list
2371 must start with the contents of our bucket. */
2372 b = find_bucket(myid, AF_INET);
2373 if(b == NULL)
2374 goto no_ipv4;
2375
2376 n = b->nodes;
2377 while(n && i < *num) {
2378 if(node_good(n)) {
2379 sin[i] = *(struct sockaddr_in*)&n->ss;
2380 i++;
2381 }
2382 n = n->next;
2383 }
2384
2385 b = buckets;
2386 while(b && i < *num) {
2387 if(!in_bucket(myid, b)) {
2388 n = b->nodes;
2389 while(n && i < *num) {
2390 if(node_good(n)) {
2391 sin[i] = *(struct sockaddr_in*)&n->ss;
2392 i++;
2393 }
2394 n = n->next;
2395 }
2396 }
2397 b = b->next;
2398 }
2399
2400 no_ipv4:
2401
2402 j = 0;
2403
2404 b = find_bucket(myid, AF_INET6);
2405 if(b == NULL)
2406 goto no_ipv6;
2407
2408 n = b->nodes;
2409 while(n && j < *num6) {
2410 if(node_good(n)) {
2411 sin6[j] = *(struct sockaddr_in6*)&n->ss;
2412 j++;
2413 }
2414 n = n->next;
2415 }
2416
2417 b = buckets6;
2418 while(b && j < *num6) {
2419 if(!in_bucket(myid, b)) {
2420 n = b->nodes;
2421 while(n && j < *num6) {
2422 if(node_good(n)) {
2423 sin6[j] = *(struct sockaddr_in6*)&n->ss;
2424 j++;
2425 }
2426 n = n->next;
2427 }
2428 }
2429 b = b->next;
2430 }
2431
2432 no_ipv6:
2433
2434 *num = i;
2435 *num6 = j;
2436 return i + j;
2437 }
2438
2439 int
2440 dht_insert_node(const unsigned char *id, struct sockaddr *sa, int salen)
2441 {
2442 struct node *n;
2443
2444 if(sa->sa_family != AF_INET && sa->sa_family != AF_INET6) {
2445 errno = EAFNOSUPPORT;
2446 return -1;
2447 }
2448
2449 n = new_node(id, sa, salen, 0);
2450 return !!n;
2451 }
2452
2453 int
2454 dht_ping_node(const struct sockaddr *sa, int salen)
2455 {
2456 unsigned char tid[4];
2457
2458 debugf("Sending ping.\n");
2459 make_tid(tid, "pn", 0);
2460 return send_ping(sa, salen, tid, 4);
2461 }
2462
2463 /* We could use a proper bencoding printer and parser, but the format of
2464 DHT messages is fairly stylised, so this seemed simpler. */
2465
2466 #define CHECK(offset, delta, size) \
2467 if(delta < 0 || offset + delta > size) goto fail
2468
2469 #define INC(offset, delta, size) \
2470 CHECK(offset, delta, size); \
2471 offset += delta
2472
2473 #define COPY(buf, offset, src, delta, size) \
2474 CHECK(offset, delta, size); \
2475 memcpy(buf + offset, src, delta); \
2476 offset += delta;
2477
2478 #define ADD_V(buf, offset, size) \
2479 if(have_v) { \
2480 COPY(buf, offset, my_v, sizeof(my_v), size); \
2481 }
2482
2483 static int
2484 dht_send(const void *buf, size_t len, int flags,
2485 const struct sockaddr *sa, int salen)
2486 {
2487 int s;
2488
2489 if(salen == 0)
2490 abort();
2491
2492 if(node_blacklisted(sa, salen)) {
2493 debugf("Attempting to send to blacklisted node.\n");
2494 errno = EPERM;
2495 return -1;
2496 }
2497
2498 if(sa->sa_family == AF_INET)
2499 s = dht_socket;
2500 else if(sa->sa_family == AF_INET6)
2501 s = dht_socket6;
2502 else
2503 s = -1;
2504
2505 if(s < 0) {
2506 errno = EAFNOSUPPORT;
2507 return -1;
2508 }
2509
2510 return dht_sendto(s, buf, len, flags, sa, salen);
2511 }
2512
2513 int
2514 send_ping(const struct sockaddr *sa, int salen,
2515 const unsigned char *tid, int tid_len)
2516 {
2517 char buf[512];
2518 int i = 0, rc;
2519 rc = snprintf(buf + i, 512 - i, "d1:ad2:id20:"); INC(i, rc, 512);
2520 COPY(buf, i, myid, 20, 512);
2521 rc = snprintf(buf + i, 512 - i, "e1:q4:ping1:t%d:", tid_len);
2522 INC(i, rc, 512);
2523 COPY(buf, i, tid, tid_len, 512);
2524 ADD_V(buf, i, 512);
2525 rc = snprintf(buf + i, 512 - i, "1:y1:qe"); INC(i, rc, 512);
2526 return dht_send(buf, i, 0, sa, salen);
2527
2528 fail:
2529 errno = ENOSPC;
2530 return -1;
2531 }
2532
2533 int
2534 send_pong(const struct sockaddr *sa, int salen,
2535 const unsigned char *tid, int tid_len)
2536 {
2537 char buf[512];
2538 int i = 0, rc;
2539 rc = snprintf(buf + i, 512 - i, "d1:rd2:id20:"); INC(i, rc, 512);
2540 COPY(buf, i, myid, 20, 512);
2541 rc = snprintf(buf + i, 512 - i, "e1:t%d:", tid_len); INC(i, rc, 512);
2542 COPY(buf, i, tid, tid_len, 512);
2543 ADD_V(buf, i, 512);
2544 rc = snprintf(buf + i, 512 - i, "1:y1:re"); INC(i, rc, 512);
2545 return dht_send(buf, i, 0, sa, salen);
2546
2547 fail:
2548 errno = ENOSPC;
2549 return -1;
2550 }
2551
2552 int
2553 send_find_node(const struct sockaddr *sa, int salen,
2554 const unsigned char *tid, int tid_len,
2555 const unsigned char *target, int want, int confirm)
2556 {
2557 char buf[512];
2558 int i = 0, rc;
2559 rc = snprintf(buf + i, 512 - i, "d1:ad2:id20:"); INC(i, rc, 512);
2560 COPY(buf, i, myid, 20, 512);
2561 rc = snprintf(buf + i, 512 - i, "6:target20:"); INC(i, rc, 512);
2562 COPY(buf, i, target, 20, 512);
2563 if(want > 0) {
2564 rc = snprintf(buf + i, 512 - i, "4:wantl%s%se",
2565 (want & WANT4) ? "2:n4" : "",
2566 (want & WANT6) ? "2:n6" : "");
2567 INC(i, rc, 512);
2568 }
2569 rc = snprintf(buf + i, 512 - i, "e1:q9:find_node1:t%d:", tid_len);
2570 INC(i, rc, 512);
2571 COPY(buf, i, tid, tid_len, 512);
2572 ADD_V(buf, i, 512);
2573 rc = snprintf(buf + i, 512 - i, "1:y1:qe"); INC(i, rc, 512);
2574 return dht_send(buf, i, confirm ? MSG_CONFIRM : 0, sa, salen);
2575
2576 fail:
2577 errno = ENOSPC;
2578 return -1;
2579 }
2580
2581 int
2582 send_nodes_peers(const struct sockaddr *sa, int salen,
2583 const unsigned char *tid, int tid_len,
2584 const unsigned char *nodes, int nodes_len,
2585 const unsigned char *nodes6, int nodes6_len,
2586 int af, struct storage *st,
2587 const unsigned char *token, int token_len)
2588 {
2589 char buf[2048];
2590 int i = 0, rc, j0, j, k, len;
2591
2592 rc = snprintf(buf + i, 2048 - i, "d1:rd2:id20:"); INC(i, rc, 2048);
2593 COPY(buf, i, myid, 20, 2048);
2594 if(nodes_len > 0) {
2595 rc = snprintf(buf + i, 2048 - i, "5:nodes%d:", nodes_len);
2596 INC(i, rc, 2048);
2597 COPY(buf, i, nodes, nodes_len, 2048);
2598 }
2599 if(nodes6_len > 0) {
2600 rc = snprintf(buf + i, 2048 - i, "6:nodes6%d:", nodes6_len);
2601 INC(i, rc, 2048);
2602 COPY(buf, i, nodes6, nodes6_len, 2048);
2603 }
2604 if(token_len > 0) {
2605 rc = snprintf(buf + i, 2048 - i, "5:token%d:", token_len);
2606 INC(i, rc, 2048);
2607 COPY(buf, i, token, token_len, 2048);
2608 }
2609
2610 if(st && st->numpeers > 0) {
2611 /* We treat the storage as a circular list, and serve a randomly
2612 chosen slice. In order to make sure we fit within 1024 octets,
2613 we limit ourselves to 50 peers. */
2614
2615 len = af == AF_INET ? 4 : 16;
2616 j0 = random() % st->numpeers;
2617 j = j0;
2618 k = 0;
2619
2620 rc = snprintf(buf + i, 2048 - i, "6:valuesl"); INC(i, rc, 2048);
2621 do {
2622 if(st->peers[j].len == len) {
2623 unsigned short swapped;
2624 swapped = htons(st->peers[j].port);
2625 rc = snprintf(buf + i, 2048 - i, "%d:", len + 2);
2626 INC(i, rc, 2048);
2627 COPY(buf, i, st->peers[j].ip, len, 2048);
2628 COPY(buf, i, &swapped, 2, 2048);
2629 k++;
2630 }
2631 j = (j + 1) % st->numpeers;
2632 } while(j != j0 && k < 50);
2633 rc = snprintf(buf + i, 2048 - i, "e"); INC(i, rc, 2048);
2634 }
2635
2636 rc = snprintf(buf + i, 2048 - i, "e1:t%d:", tid_len); INC(i, rc, 2048);
2637 COPY(buf, i, tid, tid_len, 2048);
2638 ADD_V(buf, i, 2048);
2639 rc = snprintf(buf + i, 2048 - i, "1:y1:re"); INC(i, rc, 2048);
2640
2641 return dht_send(buf, i, 0, sa, salen);
2642
2643 fail:
2644 errno = ENOSPC;
2645 return -1;
2646 }
2647
2648 static int
2649 insert_closest_node(unsigned char *nodes, int numnodes,
2650 const unsigned char *id, struct node *n)
2651 {
2652 int i, size;
2653
2654 if(n->ss.ss_family == AF_INET)
2655 size = 26;
2656 else if(n->ss.ss_family == AF_INET6)
2657 size = 38;
2658 else
2659 abort();
2660
2661 for(i = 0; i< numnodes; i++) {
2662 if(id_cmp(n->id, nodes + size * i) == 0)
2663 return numnodes;
2664 if(xorcmp(n->id, nodes + size * i, id) < 0)
2665 break;
2666 }
2667
2668 if(i == 8)
2669 return numnodes;
2670
2671 if(numnodes < 8)
2672 numnodes++;
2673
2674 if(i < numnodes - 1)
2675 memmove(nodes + size * (i + 1), nodes + size * i,
2676 size * (numnodes - i - 1));
2677
2678 if(n->ss.ss_family == AF_INET) {
2679 struct sockaddr_in *sin = (struct sockaddr_in*)&n->ss;
2680 memcpy(nodes + size * i, n->id, 20);
2681 memcpy(nodes + size * i + 20, &sin->sin_addr, 4);
2682 memcpy(nodes + size * i + 24, &sin->sin_port, 2);
2683 } else if(n->ss.ss_family == AF_INET6) {
2684 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&n->ss;
2685 memcpy(nodes + size * i, n->id, 20);
2686 memcpy(nodes + size * i + 20, &sin6->sin6_addr, 16);
2687 memcpy(nodes + size * i + 36, &sin6->sin6_port, 2);
2688 } else {
2689 abort();
2690 }
2691
2692 return numnodes;
2693 }
2694
2695 static int
2696 buffer_closest_nodes(unsigned char *nodes, int numnodes,
2697 const unsigned char *id, struct bucket *b)
2698 {
2699 struct node *n = b->nodes;
2700 while(n) {
2701 if(node_good(n))
2702 numnodes = insert_closest_node(nodes, numnodes, id, n);
2703 n = n->next;
2704 }
2705 return numnodes;
2706 }
2707
2708 int
2709 send_closest_nodes(const struct sockaddr *sa, int salen,
2710 const unsigned char *tid, int tid_len,
2711 const unsigned char *id, int want,
2712 int af, struct storage *st,
2713 const unsigned char *token, int token_len)
2714 {
2715 unsigned char nodes[8 * 26];
2716 unsigned char nodes6[8 * 38];
2717 int numnodes = 0, numnodes6 = 0;
2718 struct bucket *b;
2719
2720 if(want <= 0)
2721 want = sa->sa_family == AF_INET ? WANT4 : WANT6;
2722
2723 if((want & WANT4)) {
2724 b = find_bucket(id, AF_INET);
2725 if(b) {
2726 numnodes = buffer_closest_nodes(nodes, numnodes, id, b);
2727 if(b->next)
2728 numnodes = buffer_closest_nodes(nodes, numnodes, id, b->next);
2729 b = previous_bucket(b);
2730 if(b)
2731 numnodes = buffer_closest_nodes(nodes, numnodes, id, b);
2732 }
2733 }
2734
2735 if((want & WANT6)) {
2736 b = find_bucket(id, AF_INET6);
2737 if(b) {
2738 numnodes6 = buffer_closest_nodes(nodes6, numnodes6, id, b);
2739 if(b->next)
2740 numnodes6 =
2741 buffer_closest_nodes(nodes6, numnodes6, id, b->next);
2742 b = previous_bucket(b);
2743 if(b)
2744 numnodes6 = buffer_closest_nodes(nodes6, numnodes6, id, b);
2745 }
2746 }
2747 debugf(" (%d+%d nodes.)\n", numnodes, numnodes6);
2748
2749 return send_nodes_peers(sa, salen, tid, tid_len,
2750 nodes, numnodes * 26,
2751 nodes6, numnodes6 * 38,
2752 af, st, token, token_len);
2753 }
2754
2755 int
2756 send_get_peers(const struct sockaddr *sa, int salen,
2757 unsigned char *tid, int tid_len, unsigned char *infohash,
2758 int want, int confirm)
2759 {
2760 char buf[512];
2761 int i = 0, rc;
2762
2763 rc = snprintf(buf + i, 512 - i, "d1:ad2:id20:"); INC(i, rc, 512);
2764 COPY(buf, i, myid, 20, 512);
2765 rc = snprintf(buf + i, 512 - i, "9:info_hash20:"); INC(i, rc, 512);
2766 COPY(buf, i, infohash, 20, 512);
2767 if(want > 0) {
2768 rc = snprintf(buf + i, 512 - i, "4:wantl%s%se",
2769 (want & WANT4) ? "2:n4" : "",
2770 (want & WANT6) ? "2:n6" : "");
2771 INC(i, rc, 512);
2772 }
2773 rc = snprintf(buf + i, 512 - i, "e1:q9:get_peers1:t%d:", tid_len);
2774 INC(i, rc, 512);
2775 COPY(buf, i, tid, tid_len, 512);
2776 ADD_V(buf, i, 512);
2777 rc = snprintf(buf + i, 512 - i, "1:y1:qe"); INC(i, rc, 512);
2778 return dht_send(buf, i, confirm ? MSG_CONFIRM : 0, sa, salen);
2779
2780 fail:
2781 errno = ENOSPC;
2782 return -1;
2783 }
2784
2785 int
2786 send_announce_peer(const struct sockaddr *sa, int salen,
2787 unsigned char *tid, int tid_len,
2788 unsigned char *infohash, unsigned short port,
2789 unsigned char *token, int token_len, int confirm)
2790 {
2791 char buf[512];
2792 int i = 0, rc;
2793
2794 rc = snprintf(buf + i, 512 - i, "d1:ad2:id20:"); INC(i, rc, 512);
2795 COPY(buf, i, myid, 20, 512);
2796 rc = snprintf(buf + i, 512 - i, "12:implied_porti1e9:info_hash20:"); INC(i, rc, 512);
2797 COPY(buf, i, infohash, 20, 512);
2798 rc = snprintf(buf + i, 512 - i, "4:porti%ue5:token%d:", (unsigned)port,
2799 token_len);
2800 INC(i, rc, 512);
2801 COPY(buf, i, token, token_len, 512);
2802 rc = snprintf(buf + i, 512 - i, "e1:q13:announce_peer1:t%d:", tid_len);
2803 INC(i, rc, 512);
2804 COPY(buf, i, tid, tid_len, 512);
2805 ADD_V(buf, i, 512);
2806 rc = snprintf(buf + i, 512 - i, "1:y1:qe"); INC(i, rc, 512);
2807
2808 return dht_send(buf, i, confirm ? 0 : MSG_CONFIRM, sa, salen);
2809
2810 fail:
2811 errno = ENOSPC;
2812 return -1;
2813 }
2814
2815 static int
2816 send_peer_announced(const struct sockaddr *sa, int salen,
2817 unsigned char *tid, int tid_len)
2818 {
2819 char buf[512];
2820 int i = 0, rc;
2821
2822 rc = snprintf(buf + i, 512 - i, "d1:rd2:id20:"); INC(i, rc, 512);
2823 COPY(buf, i, myid, 20, 512);
2824 rc = snprintf(buf + i, 512 - i, "e1:t%d:", tid_len);
2825 INC(i, rc, 512);
2826 COPY(buf, i, tid, tid_len, 512);
2827 ADD_V(buf, i, 512);
2828 rc = snprintf(buf + i, 512 - i, "1:y1:re"); INC(i, rc, 512);
2829 return dht_send(buf, i, 0, sa, salen);
2830
2831 fail:
2832 errno = ENOSPC;
2833 return -1;
2834 }
2835
2836 static int
2837 send_error(const struct sockaddr *sa, int salen,
2838 unsigned char *tid, int tid_len,
2839 int code, const char *message)
2840 {
2841 char buf[512];
2842 int i = 0, rc, message_len;
2843
2844 message_len = strlen(message);
2845 rc = snprintf(buf + i, 512 - i, "d1:eli%de%d:", code, message_len);
2846 INC(i, rc, 512);
2847 COPY(buf, i, message, message_len, 512);
2848 rc = snprintf(buf + i, 512 - i, "e1:t%d:", tid_len); INC(i, rc, 512);
2849 COPY(buf, i, tid, tid_len, 512);
2850 ADD_V(buf, i, 512);
2851 rc = snprintf(buf + i, 512 - i, "1:y1:ee"); INC(i, rc, 512);
2852 return dht_send(buf, i, 0, sa, salen);
2853
2854 fail:
2855 errno = ENOSPC;
2856 return -1;
2857 }
2858
2859 #undef CHECK
2860 #undef INC
2861 #undef COPY
2862 #undef ADD_V
2863
2864 #ifdef HAVE_MEMMEM
2865
2866 static void *
2867 dht_memmem(const void *haystack, size_t haystacklen,
2868 const void *needle, size_t needlelen)
2869 {
2870 return memmem(haystack, haystacklen, needle, needlelen);
2871 }
2872
2873 #else
2874
2875 static void *
2876 dht_memmem(const void *haystack, size_t haystacklen,
2877 const void *needle, size_t needlelen)
2878 {
2879 const char *h = haystack;
2880 const char *n = needle;
2881 size_t i;
2882
2883 /* size_t is unsigned */
2884 if(needlelen > haystacklen)
2885 return NULL;
2886
2887 for(i = 0; i <= haystacklen - needlelen; i++) {
2888 if(memcmp(h + i, n, needlelen) == 0)
2889 return (void*)(h + i);
2890 }
2891 return NULL;
2892 }
2893
2894 #endif
2895
2896 static int
2897 parse_message(const unsigned char *buf, int buflen,
2898 struct parsed_message *m)
2899 {
2900 const unsigned char *p;
2901
2902 /* This code will happily crash if the buffer is not NUL-terminated. */
2903 if(buf[buflen] != '\0') {
2904 debugf("Eek! parse_message with unterminated buffer.\n");
2905 return -1;
2906 }
2907
2908
2909 #define CHECK(ptr, len) \
2910 if(((unsigned char*)ptr) + (len) > (buf) + (buflen)) goto overflow;
2911
2912 p = dht_memmem(buf, buflen, "1:t", 3);
2913 if(p) {
2914 long l;
2915 char *q;
2916 l = strtol((char*)p + 3, &q, 10);
2917 if(q && *q == ':' && l > 0 && l < PARSE_TID_LEN) {
2918 CHECK(q + 1, l);
2919 memcpy(m->tid, q + 1, l);
2920 m->tid_len = l;
2921 }
2922 }
2923
2924 p = dht_memmem(buf, buflen, "2:id20:", 7);
2925 if(p) {
2926 CHECK(p + 7, 20);
2927 memcpy(m->id, p + 7, 20);
2928 }
2929
2930 p = dht_memmem(buf, buflen, "9:info_hash20:", 14);
2931 if(p) {
2932 CHECK(p + 14, 20);
2933 memcpy(m->info_hash, p + 14, 20);
2934 }
2935
2936 p = dht_memmem(buf, buflen, "4:porti", 7);
2937 if(p) {
2938 long l;
2939 char *q;
2940 l = strtol((char*)p + 7, &q, 10);
2941 if(q && *q == 'e' && l > 0 && l < 0x10000)
2942 m->port = l;
2943 }
2944
2945 p = dht_memmem(buf, buflen, "12:implied_porti", 16);
2946 if(p) {
2947 long l;
2948 char *q;
2949 l = strtol((char*)p + 16, &q, 10);
2950 if(q && *q == 'e' && l > 0 && l < 0x10000)
2951 m->implied_port = l;
2952 }
2953
2954 p = dht_memmem(buf, buflen, "6:target20:", 11);
2955 if(p) {
2956 CHECK(p + 11, 20);
2957 memcpy(m->target, p + 11, 20);
2958 }
2959
2960 p = dht_memmem(buf, buflen, "5:token", 7);
2961 if(p) {
2962 long l;
2963 char *q;
2964 l = strtol((char*)p + 7, &q, 10);
2965 if(q && *q == ':' && l > 0 && l < PARSE_TOKEN_LEN) {
2966 CHECK(q + 1, l);
2967 memcpy(m->token, q + 1, l);
2968 m->token_len = l;
2969 }
2970 }
2971
2972 p = dht_memmem(buf, buflen, "5:nodes", 7);
2973 if(p) {
2974 long l;
2975 char *q;
2976 l = strtol((char*)p + 7, &q, 10);
2977 if(q && *q == ':' && l > 0 && l <= PARSE_NODES_LEN) {
2978 CHECK(q + 1, l);
2979 memcpy(m->nodes, q + 1, l);
2980 m->nodes_len = l;
2981 }
2982 }
2983
2984 p = dht_memmem(buf, buflen, "6:nodes6", 8);
2985 if(p) {
2986 long l;
2987 char *q;
2988 l = strtol((char*)p + 8, &q, 10);
2989 if(q && *q == ':' && l > 0 && l <= PARSE_NODES6_LEN) {
2990 CHECK(q + 1, l);
2991 memcpy(m->nodes6, q + 1, l);
2992 m->nodes6_len = l;
2993 }
2994 }
2995
2996 p = dht_memmem(buf, buflen, "6:valuesl", 9);
2997 if(p) {
2998 int i = p - buf + 9;
2999 int j = 0, j6 = 0;
3000 while(1) {
3001 long l;
3002 char *q;
3003 l = strtol((char*)buf + i, &q, 10);
3004 if(q && *q == ':' && l > 0) {
3005 CHECK(q + 1, l);
3006 i = q + 1 + l - (char*)buf;
3007 if(l == 6) {
3008 if(j + l > PARSE_VALUES_LEN)
3009 continue;
3010 memcpy((char*)m->values + j, q + 1, l);
3011 j += l;
3012 } else if(l == 18) {
3013 if(j6 + l > PARSE_VALUES6_LEN)
3014 continue;
3015 memcpy((char*)m->values6 + j6, q + 1, l);
3016 j6 += l;
3017 } else {
3018 debugf("Received weird value -- %d bytes.\n", (int)l);
3019 }
3020 } else {
3021 break;
3022 }
3023 }
3024 if(i >= buflen || buf[i] != 'e')
3025 debugf("eek... unexpected end for values.\n");
3026 m->values_len = j;
3027 m->values6_len = j6;
3028 }
3029
3030 p = dht_memmem(buf, buflen, "4:wantl", 7);
3031 if(p) {
3032 int i = p - buf + 7;
3033 m->want = 0;
3034 while(buf[i] > '0' && buf[i] <= '9' && buf[i + 1] == ':' &&
3035 i + 2 + buf[i] - '0' < buflen) {
3036 CHECK(buf + i + 2, buf[i] - '0');
3037 if(buf[i] == '2' && memcmp(buf + i + 2, "n4", 2) == 0)
3038 m->want |= WANT4;
3039 else if(buf[i] == '2' && memcmp(buf + i + 2, "n6", 2) == 0)
3040 m->want |= WANT6;
3041 else
3042 debugf("eek... unexpected want flag (%c)\n", buf[i]);
3043 i += 2 + buf[i] - '0';
3044 }
3045 if(i >= buflen || buf[i] != 'e')
3046 debugf("eek... unexpected end for want.\n");
3047 }
3048
3049 #undef CHECK
3050
3051 if(dht_memmem(buf, buflen, "1:y1:r", 6))
3052 return REPLY;
3053 if(dht_memmem(buf, buflen, "1:y1:e", 6))
3054 return ERROR;
3055 if(!dht_memmem(buf, buflen, "1:y1:q", 6))
3056 return -1;
3057 if(dht_memmem(buf, buflen, "1:q4:ping", 9))
3058 return PING;
3059 if(dht_memmem(buf, buflen, "1:q9:find_node", 14))
3060 return FIND_NODE;
3061 if(dht_memmem(buf, buflen, "1:q9:get_peers", 14))
3062 return GET_PEERS;
3063 if(dht_memmem(buf, buflen, "1:q13:announce_peer", 19))
3064 return ANNOUNCE_PEER;
3065 return -1;
3066
3067 overflow:
3068 debugf("Truncated message.\n");
3069 return -1;
3070 }