forked from irungentoo/toxcore
-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathDHT.c
3004 lines (2382 loc) · 92.6 KB
/
DHT.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright © 2016-2018 The TokTok team.
* Copyright © 2013 Tox project.
*/
/**
* An implementation of the DHT as seen in docs/updates/DHT.md
*/
#include "DHT.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "LAN_discovery.h"
#include "ccompat.h"
#include "logger.h"
#include "mono_time.h"
#include "network.h"
#include "ping.h"
#include "shared_key_cache.h"
#include "state.h"
#include "util.h"
/** The timeout after which a node is discarded completely. */
#define KILL_NODE_TIMEOUT (BAD_NODE_TIMEOUT + PING_INTERVAL)
/** Ping interval in seconds for each random sending of a get nodes request. */
#define GET_NODE_INTERVAL 20
#define MAX_PUNCHING_PORTS 48
/** Interval in seconds between punching attempts*/
#define PUNCH_INTERVAL 3
/** Time in seconds after which punching parameters will be reset */
#define PUNCH_RESET_TIME 40
#define MAX_NORMAL_PUNCHING_TRIES 5
#define NAT_PING_REQUEST 0
#define NAT_PING_RESPONSE 1
/** Number of get node requests to send to quickly find close nodes. */
#define MAX_BOOTSTRAP_TIMES 5
// TODO(sudden6): find out why we need multiple callbacks and if we really need 32
#define DHT_FRIEND_MAX_LOCKS 32
/* Settings for the shared key cache */
#define MAX_KEYS_PER_SLOT 4
#define KEYS_TIMEOUT 600
typedef struct DHT_Friend_Callback {
dht_ip_cb *ip_callback;
void *data;
int32_t number;
} DHT_Friend_Callback;
struct DHT_Friend {
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE];
Client_data client_list[MAX_FRIEND_CLIENTS];
/* Time at which the last get_nodes request was sent. */
uint64_t lastgetnode;
/* number of times get_node packets were sent. */
uint32_t bootstrap_times;
/* Symmetric NAT hole punching stuff. */
NAT nat;
/* Each set bit represents one installed callback */
uint32_t lock_flags;
DHT_Friend_Callback callbacks[DHT_FRIEND_MAX_LOCKS];
Node_format to_bootstrap[MAX_SENT_NODES];
unsigned int num_to_bootstrap;
};
static const DHT_Friend empty_dht_friend = {{0}};
const Node_format empty_node_format = {{0}};
static_assert(sizeof (empty_dht_friend.lock_flags) * 8 == DHT_FRIEND_MAX_LOCKS, "Bitfield size and number of locks don't match");
typedef struct Cryptopacket_Handler {
cryptopacket_handler_cb *function;
void *object;
} Cryptopacket_Handler;
struct DHT {
const Logger *log;
const Network *ns;
Mono_Time *mono_time;
const Memory *mem;
const Random *rng;
Networking_Core *net;
bool hole_punching_enabled;
bool lan_discovery_enabled;
Client_data close_clientlist[LCLIENT_LIST];
uint64_t close_lastgetnodes;
uint32_t close_bootstrap_times;
/* DHT keypair */
uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
DHT_Friend *friends_list;
uint16_t num_friends;
Node_format *loaded_nodes_list;
uint32_t loaded_num_nodes;
unsigned int loaded_nodes_index;
Shared_Key_Cache *shared_keys_recv;
Shared_Key_Cache *shared_keys_sent;
struct Ping *ping;
Ping_Array *dht_ping_array;
uint64_t cur_time;
Cryptopacket_Handler cryptopackethandlers[256];
Node_format to_bootstrap[MAX_CLOSE_TO_BOOTSTRAP_NODES];
unsigned int num_to_bootstrap;
dht_get_nodes_response_cb *get_nodes_response;
};
const uint8_t *dht_friend_public_key(const DHT_Friend *dht_friend)
{
return dht_friend->public_key;
}
const Client_data *dht_friend_client(const DHT_Friend *dht_friend, size_t index)
{
return &dht_friend->client_list[index];
}
const uint8_t *dht_get_self_public_key(const DHT *dht)
{
return dht->self_public_key;
}
const uint8_t *dht_get_self_secret_key(const DHT *dht)
{
return dht->self_secret_key;
}
void dht_set_self_public_key(DHT *dht, const uint8_t *key)
{
memcpy(dht->self_public_key, key, CRYPTO_PUBLIC_KEY_SIZE);
}
void dht_set_self_secret_key(DHT *dht, const uint8_t *key)
{
memcpy(dht->self_secret_key, key, CRYPTO_SECRET_KEY_SIZE);
}
Networking_Core *dht_get_net(const DHT *dht)
{
return dht->net;
}
struct Ping *dht_get_ping(const DHT *dht)
{
return dht->ping;
}
const Client_data *dht_get_close_clientlist(const DHT *dht)
{
return dht->close_clientlist;
}
const Client_data *dht_get_close_client(const DHT *dht, uint32_t client_num)
{
assert(client_num < sizeof(dht->close_clientlist) / sizeof(dht->close_clientlist[0]));
return &dht->close_clientlist[client_num];
}
uint16_t dht_get_num_friends(const DHT *dht)
{
return dht->num_friends;
}
DHT_Friend *dht_get_friend(DHT *dht, uint32_t friend_num)
{
assert(friend_num < dht->num_friends);
return &dht->friends_list[friend_num];
}
const uint8_t *dht_get_friend_public_key(const DHT *dht, uint32_t friend_num)
{
assert(friend_num < dht->num_friends);
return dht->friends_list[friend_num].public_key;
}
non_null()
static bool assoc_timeout(uint64_t cur_time, const IPPTsPng *assoc)
{
return (assoc->timestamp + BAD_NODE_TIMEOUT) <= cur_time;
}
/** @brief Converts an IPv4-in-IPv6 to IPv4 and returns the new IP_Port.
*
* If the ip_port is already IPv4 this function returns a copy of the original ip_port.
*/
non_null()
static IP_Port ip_port_normalize(const IP_Port *ip_port)
{
IP_Port res = *ip_port;
if (net_family_is_ipv6(res.ip.family) && ipv6_ipv4_in_v6(&res.ip.ip.v6)) {
res.ip.family = net_family_ipv4();
res.ip.ip.v4.uint32 = res.ip.ip.v6.uint32[3];
}
return res;
}
int id_closest(const uint8_t *pk, const uint8_t *pk1, const uint8_t *pk2)
{
for (size_t i = 0; i < CRYPTO_PUBLIC_KEY_SIZE; ++i) {
const uint8_t distance1 = pk[i] ^ pk1[i];
const uint8_t distance2 = pk[i] ^ pk2[i];
if (distance1 < distance2) {
return 1;
}
if (distance1 > distance2) {
return 2;
}
}
return 0;
}
/** Return index of first unequal bit number between public keys pk1 and pk2. */
unsigned int bit_by_bit_cmp(const uint8_t *pk1, const uint8_t *pk2)
{
unsigned int i = 0;
unsigned int j = 0;
for (i = 0; i < CRYPTO_PUBLIC_KEY_SIZE; ++i) {
if (pk1[i] == pk2[i]) {
continue;
}
for (j = 0; j < 8; ++j) {
const uint8_t mask = 1 << (7 - j);
if ((pk1[i] & mask) != (pk2[i] & mask)) {
break;
}
}
break;
}
return i * 8 + j;
}
/**
* Copy shared_key to encrypt/decrypt DHT packet from public_key into shared_key
* for packets that we receive.
*/
const uint8_t *dht_get_shared_key_recv(DHT *dht, const uint8_t *public_key)
{
return shared_key_cache_lookup(dht->shared_keys_recv, public_key);
}
/**
* Copy shared_key to encrypt/decrypt DHT packet from public_key into shared_key
* for packets that we send.
*/
const uint8_t *dht_get_shared_key_sent(DHT *dht, const uint8_t *public_key)
{
return shared_key_cache_lookup(dht->shared_keys_sent, public_key);
}
#define CRYPTO_SIZE (1 + CRYPTO_PUBLIC_KEY_SIZE * 2 + CRYPTO_NONCE_SIZE)
int create_request(const Random *rng, const uint8_t *send_public_key, const uint8_t *send_secret_key,
uint8_t *packet, const uint8_t *recv_public_key,
const uint8_t *data, uint32_t data_length, uint8_t request_id)
{
if (send_public_key == nullptr || packet == nullptr || recv_public_key == nullptr || data == nullptr) {
return -1;
}
if (MAX_CRYPTO_REQUEST_SIZE < data_length + CRYPTO_SIZE + 1 + CRYPTO_MAC_SIZE) {
return -1;
}
uint8_t *const nonce = packet + 1 + CRYPTO_PUBLIC_KEY_SIZE * 2;
random_nonce(rng, nonce);
uint8_t temp[MAX_CRYPTO_REQUEST_SIZE] = {0};
temp[0] = request_id;
memcpy(temp + 1, data, data_length);
const int len = encrypt_data(recv_public_key, send_secret_key, nonce, temp, data_length + 1,
packet + CRYPTO_SIZE);
if (len == -1) {
crypto_memzero(temp, MAX_CRYPTO_REQUEST_SIZE);
return -1;
}
packet[0] = NET_PACKET_CRYPTO;
memcpy(packet + 1, recv_public_key, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, send_public_key, CRYPTO_PUBLIC_KEY_SIZE);
crypto_memzero(temp, MAX_CRYPTO_REQUEST_SIZE);
return len + CRYPTO_SIZE;
}
int handle_request(const uint8_t *self_public_key, const uint8_t *self_secret_key, uint8_t *public_key, uint8_t *data,
uint8_t *request_id, const uint8_t *packet, uint16_t packet_length)
{
if (self_public_key == nullptr || public_key == nullptr || data == nullptr || request_id == nullptr
|| packet == nullptr) {
return -1;
}
if (packet_length <= CRYPTO_SIZE + CRYPTO_MAC_SIZE || packet_length > MAX_CRYPTO_REQUEST_SIZE) {
return -1;
}
if (!pk_equal(packet + 1, self_public_key)) {
return -1;
}
memcpy(public_key, packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, CRYPTO_PUBLIC_KEY_SIZE);
const uint8_t *const nonce = packet + 1 + CRYPTO_PUBLIC_KEY_SIZE * 2;
uint8_t temp[MAX_CRYPTO_REQUEST_SIZE];
int32_t len1 = decrypt_data(public_key, self_secret_key, nonce,
packet + CRYPTO_SIZE, packet_length - CRYPTO_SIZE, temp);
if (len1 == -1 || len1 == 0) {
crypto_memzero(temp, MAX_CRYPTO_REQUEST_SIZE);
return -1;
}
assert(len1 == packet_length - CRYPTO_SIZE - CRYPTO_MAC_SIZE);
// Because coverity can't figure out this equation:
assert(len1 <= MAX_CRYPTO_REQUEST_SIZE - CRYPTO_SIZE - CRYPTO_MAC_SIZE);
request_id[0] = temp[0];
--len1;
memcpy(data, temp + 1, len1);
crypto_memzero(temp, MAX_CRYPTO_REQUEST_SIZE);
return len1;
}
int packed_node_size(Family ip_family)
{
if (net_family_is_ipv4(ip_family) || net_family_is_tcp_ipv4(ip_family)) {
return PACKED_NODE_SIZE_IP4;
}
if (net_family_is_ipv6(ip_family) || net_family_is_tcp_ipv6(ip_family)) {
return PACKED_NODE_SIZE_IP6;
}
return -1;
}
int pack_ip_port(const Logger *logger, uint8_t *data, uint16_t length, const IP_Port *ip_port)
{
if (data == nullptr) {
return -1;
}
bool is_ipv4 = 0;
uint8_t family = 0;
if (net_family_is_ipv4(ip_port->ip.family)) {
// TODO(irungentoo): use functions to convert endianness
is_ipv4 = true;
family = TOX_AF_INET;
} else if (net_family_is_tcp_ipv4(ip_port->ip.family)) {
is_ipv4 = true;
family = TOX_TCP_INET;
} else if (net_family_is_ipv6(ip_port->ip.family)) {
is_ipv4 = false;
family = TOX_AF_INET6;
} else if (net_family_is_tcp_ipv6(ip_port->ip.family)) {
is_ipv4 = false;
family = TOX_TCP_INET6;
} else {
Ip_Ntoa ip_str;
// TODO(iphydf): Find out why we're trying to pack invalid IPs, stop
// doing that, and turn this into an error.
LOGGER_TRACE(logger, "cannot pack invalid IP: %s", net_ip_ntoa(&ip_port->ip, &ip_str));
return -1;
}
if (is_ipv4) {
const uint32_t size = 1 + SIZE_IP4 + sizeof(uint16_t);
if (size > length) {
return -1;
}
data[0] = family;
memcpy(data + 1, &ip_port->ip.ip.v4, SIZE_IP4);
memcpy(data + 1 + SIZE_IP4, &ip_port->port, sizeof(uint16_t));
return size;
} else {
const uint32_t size = 1 + SIZE_IP6 + sizeof(uint16_t);
if (size > length) {
return -1;
}
data[0] = family;
memcpy(data + 1, &ip_port->ip.ip.v6, SIZE_IP6);
memcpy(data + 1 + SIZE_IP6, &ip_port->port, sizeof(uint16_t));
return size;
}
}
int dht_create_packet(const Memory *mem, const Random *rng,
const uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE],
const uint8_t *shared_key, const uint8_t type,
const uint8_t *plain, size_t plain_length,
uint8_t *packet, size_t length)
{
uint8_t *encrypted = (uint8_t *)mem_balloc(mem, plain_length + CRYPTO_MAC_SIZE);
uint8_t nonce[CRYPTO_NONCE_SIZE];
if (encrypted == nullptr) {
return -1;
}
random_nonce(rng, nonce);
const int encrypted_length = encrypt_data_symmetric(shared_key, nonce, plain, plain_length, encrypted);
if (encrypted_length == -1) {
mem_delete(mem, encrypted);
return -1;
}
if (length < 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + encrypted_length) {
mem_delete(mem, encrypted);
return -1;
}
packet[0] = type;
memcpy(packet + 1, public_key, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, nonce, CRYPTO_NONCE_SIZE);
memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE, encrypted, encrypted_length);
mem_delete(mem, encrypted);
return 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + encrypted_length;
}
int unpack_ip_port(IP_Port *ip_port, const uint8_t *data, uint16_t length, bool tcp_enabled)
{
if (data == nullptr) {
return -1;
}
bool is_ipv4 = 0;
Family host_family;
if (data[0] == TOX_AF_INET) {
is_ipv4 = true;
host_family = net_family_ipv4();
} else if (data[0] == TOX_TCP_INET) {
if (!tcp_enabled) {
return -1;
}
is_ipv4 = true;
host_family = net_family_tcp_ipv4();
} else if (data[0] == TOX_AF_INET6) {
is_ipv4 = false;
host_family = net_family_ipv6();
} else if (data[0] == TOX_TCP_INET6) {
if (!tcp_enabled) {
return -1;
}
is_ipv4 = false;
host_family = net_family_tcp_ipv6();
} else {
return -1;
}
*ip_port = empty_ip_port;
if (is_ipv4) {
const uint32_t size = 1 + SIZE_IP4 + sizeof(uint16_t);
if (size > length) {
return -1;
}
ip_port->ip.family = host_family;
memcpy(&ip_port->ip.ip.v4, data + 1, SIZE_IP4);
memcpy(&ip_port->port, data + 1 + SIZE_IP4, sizeof(uint16_t));
return size;
} else {
const uint32_t size = 1 + SIZE_IP6 + sizeof(uint16_t);
if (size > length) {
return -1;
}
ip_port->ip.family = host_family;
memcpy(&ip_port->ip.ip.v6, data + 1, SIZE_IP6);
memcpy(&ip_port->port, data + 1 + SIZE_IP6, sizeof(uint16_t));
return size;
}
}
int pack_nodes(const Logger *logger, uint8_t *data, uint16_t length, const Node_format *nodes, uint16_t number)
{
uint32_t packed_length = 0;
for (uint32_t i = 0; i < number && packed_length < length; ++i) {
const int ipp_size = pack_ip_port(logger, data + packed_length, length - packed_length, &nodes[i].ip_port);
if (ipp_size == -1) {
return -1;
}
packed_length += ipp_size;
if (packed_length + CRYPTO_PUBLIC_KEY_SIZE > length) {
return -1;
}
memcpy(data + packed_length, nodes[i].public_key, CRYPTO_PUBLIC_KEY_SIZE);
packed_length += CRYPTO_PUBLIC_KEY_SIZE;
#ifndef NDEBUG
const uint32_t increment = ipp_size + CRYPTO_PUBLIC_KEY_SIZE;
#endif
assert(increment == PACKED_NODE_SIZE_IP4 || increment == PACKED_NODE_SIZE_IP6);
}
return packed_length;
}
int unpack_nodes(Node_format *nodes, uint16_t max_num_nodes, uint16_t *processed_data_len, const uint8_t *data,
uint16_t length, bool tcp_enabled)
{
uint32_t num = 0;
uint32_t len_processed = 0;
while (num < max_num_nodes && len_processed < length) {
const int ipp_size = unpack_ip_port(&nodes[num].ip_port, data + len_processed, length - len_processed, tcp_enabled);
if (ipp_size == -1) {
return -1;
}
len_processed += ipp_size;
if (len_processed + CRYPTO_PUBLIC_KEY_SIZE > length) {
return -1;
}
memcpy(nodes[num].public_key, data + len_processed, CRYPTO_PUBLIC_KEY_SIZE);
len_processed += CRYPTO_PUBLIC_KEY_SIZE;
++num;
#ifndef NDEBUG
const uint32_t increment = ipp_size + CRYPTO_PUBLIC_KEY_SIZE;
#endif
assert(increment == PACKED_NODE_SIZE_IP4 || increment == PACKED_NODE_SIZE_IP6);
}
if (processed_data_len != nullptr) {
*processed_data_len = len_processed;
}
return num;
}
/** @brief Find index in an array with public_key equal to pk.
*
* @return index or UINT32_MAX if not found.
*/
non_null(3) nullable(1)
static uint32_t index_of_client_pk(const Client_data *array, uint32_t size, const uint8_t *pk)
{
assert(size == 0 || array != nullptr);
for (uint32_t i = 0; i < size; ++i) {
if (pk_equal(array[i].public_key, pk)) {
return i;
}
}
return UINT32_MAX;
}
non_null(3) nullable(1)
static uint32_t index_of_friend_pk(const DHT_Friend *array, uint32_t size, const uint8_t *pk)
{
assert(size == 0 || array != nullptr);
for (uint32_t i = 0; i < size; ++i) {
if (pk_equal(array[i].public_key, pk)) {
return i;
}
}
return UINT32_MAX;
}
non_null(3) nullable(1)
static uint32_t index_of_node_pk(const Node_format *array, uint32_t size, const uint8_t *pk)
{
assert(size == 0 || array != nullptr);
for (uint32_t i = 0; i < size; ++i) {
if (pk_equal(array[i].public_key, pk)) {
return i;
}
}
return UINT32_MAX;
}
/** @brief Find index of Client_data with ip_port equal to param ip_port.
*
* @return index or UINT32_MAX if not found.
*/
non_null(3) nullable(1)
static uint32_t index_of_client_ip_port(const Client_data *array, uint32_t size, const IP_Port *ip_port)
{
assert(size == 0 || array != nullptr);
for (uint32_t i = 0; i < size; ++i) {
if ((net_family_is_ipv4(ip_port->ip.family) && ipport_equal(&array[i].assoc4.ip_port, ip_port)) ||
(net_family_is_ipv6(ip_port->ip.family) && ipport_equal(&array[i].assoc6.ip_port, ip_port))) {
return i;
}
}
return UINT32_MAX;
}
/** Update ip_port of client if it's needed. */
non_null()
static void update_client(const Logger *log, const Mono_Time *mono_time, int index, Client_data *client,
const IP_Port *ip_port)
{
IPPTsPng *assoc = NULL;
int ip_version = 0;
if (net_family_is_ipv4(ip_port->ip.family)) {
assoc = &client->assoc4;
ip_version = 4;
} else if (net_family_is_ipv6(ip_port->ip.family)) {
assoc = &client->assoc6;
ip_version = 6;
} else {
return;
}
if (!ipport_equal(&assoc->ip_port, ip_port)) {
Ip_Ntoa ip_str_from;
Ip_Ntoa ip_str_to;
LOGGER_TRACE(log, "coipil[%u]: switching ipv%d from %s:%u to %s:%u",
index, ip_version,
net_ip_ntoa(&assoc->ip_port.ip, &ip_str_from),
net_ntohs(assoc->ip_port.port),
net_ip_ntoa(&ip_port->ip, &ip_str_to),
net_ntohs(ip_port->port));
}
if (!ip_is_lan(&assoc->ip_port.ip) && ip_is_lan(&ip_port->ip)) {
return;
}
assoc->ip_port = *ip_port;
assoc->timestamp = mono_time_get(mono_time);
}
/** @brief Check if client with public_key is already in list of length length.
*
* If it is then set its corresponding timestamp to current time.
* If the id is already in the list with a different ip_port, update it.
* TODO(irungentoo): Maybe optimize this.
*/
non_null()
static bool client_or_ip_port_in_list(const Logger *log, const Mono_Time *mono_time, Client_data *list, uint16_t length,
const uint8_t *public_key, const IP_Port *ip_port)
{
const uint64_t temp_time = mono_time_get(mono_time);
uint32_t index = index_of_client_pk(list, length, public_key);
/* if public_key is in list, find it and maybe overwrite ip_port */
if (index != UINT32_MAX) {
update_client(log, mono_time, index, &list[index], ip_port);
return true;
}
/* public_key not in list yet: see if we can find an identical ip_port, in
* that case we kill the old public_key by overwriting it with the new one
* TODO(irungentoo): maybe we SHOULDN'T do that if that public_key is in a friend_list
* and the one who is the actual friend's public_key/address set?
* MAYBE: check the other address, if valid, don't nuke? */
index = index_of_client_ip_port(list, length, ip_port);
if (index == UINT32_MAX) {
return false;
}
IPPTsPng *assoc = NULL;
int ip_version = 0;
if (net_family_is_ipv4(ip_port->ip.family)) {
assoc = &list[index].assoc4;
ip_version = 4;
} else {
assoc = &list[index].assoc6;
ip_version = 6;
}
/* Initialize client timestamp. */
assoc->timestamp = temp_time;
memcpy(list[index].public_key, public_key, CRYPTO_PUBLIC_KEY_SIZE);
LOGGER_DEBUG(log, "coipil[%u]: switching public_key (ipv%d)", index, ip_version);
/* kill the other address, if it was set */
const IPPTsPng empty_ipptspng = {{{{0}}}};
*assoc = empty_ipptspng;
return true;
}
bool add_to_list(Node_format *nodes_list, uint32_t length, const uint8_t *pk, const IP_Port *ip_port,
const uint8_t *cmp_pk)
{
for (uint32_t i = 0; i < length; ++i) {
if (id_closest(cmp_pk, nodes_list[i].public_key, pk) == 2) {
uint8_t pk_bak[CRYPTO_PUBLIC_KEY_SIZE];
memcpy(pk_bak, nodes_list[i].public_key, CRYPTO_PUBLIC_KEY_SIZE);
const IP_Port ip_port_bak = nodes_list[i].ip_port;
memcpy(nodes_list[i].public_key, pk, CRYPTO_PUBLIC_KEY_SIZE);
nodes_list[i].ip_port = *ip_port;
if (i != length - 1) {
add_to_list(nodes_list, length, pk_bak, &ip_port_bak, cmp_pk);
}
return true;
}
}
return false;
}
/**
* helper for `get_close_nodes()`. argument list is a monster :D
*/
non_null()
static void get_close_nodes_inner(uint64_t cur_time, const uint8_t *public_key, Node_format *nodes_list,
Family sa_family, const Client_data *client_list, uint32_t client_list_length,
uint32_t *num_nodes_ptr, bool is_lan,
bool want_announce)
{
if (!net_family_is_ipv4(sa_family) && !net_family_is_ipv6(sa_family) && !net_family_is_unspec(sa_family)) {
return;
}
uint32_t num_nodes = *num_nodes_ptr;
for (uint32_t i = 0; i < client_list_length; ++i) {
const Client_data *const client = &client_list[i];
/* node already in list? */
if (index_of_node_pk(nodes_list, MAX_SENT_NODES, client->public_key) != UINT32_MAX) {
continue;
}
const IPPTsPng *ipptp = NULL;
if (net_family_is_ipv4(sa_family) || client->assoc4.timestamp >= client->assoc6.timestamp) {
ipptp = &client->assoc4;
} else {
ipptp = &client->assoc6;
}
/* node not in a good condition? */
if (assoc_timeout(cur_time, ipptp)) {
continue;
}
/* don't send LAN ips to non LAN peers */
if (ip_is_lan(&ipptp->ip_port.ip) && !is_lan) {
continue;
}
#ifdef CHECK_ANNOUNCE_NODE
if (want_announce && !client->announce_node) {
continue;
}
#endif
if (num_nodes < MAX_SENT_NODES) {
memcpy(nodes_list[num_nodes].public_key, client->public_key, CRYPTO_PUBLIC_KEY_SIZE);
nodes_list[num_nodes].ip_port = ipptp->ip_port;
++num_nodes;
} else {
// TODO(zugz): this could be made significantly more efficient by
// using a version of add_to_list which works with a sorted list.
add_to_list(nodes_list, MAX_SENT_NODES, client->public_key, &ipptp->ip_port, public_key);
}
}
*num_nodes_ptr = num_nodes;
}
/**
* Find MAX_SENT_NODES nodes closest to the public_key for the send nodes request:
* put them in the nodes_list and return how many were found.
*
* want_announce: return only nodes which implement the dht announcements protocol.
*/
non_null()
static int get_somewhat_close_nodes(const DHT *dht, const uint8_t *public_key, Node_format *nodes_list,
Family sa_family, bool is_lan, bool want_announce)
{
uint32_t num_nodes = 0;
get_close_nodes_inner(dht->cur_time, public_key, nodes_list, sa_family,
dht->close_clientlist, LCLIENT_LIST, &num_nodes, is_lan, want_announce);
for (uint32_t i = 0; i < dht->num_friends; ++i) {
get_close_nodes_inner(dht->cur_time, public_key, nodes_list, sa_family,
dht->friends_list[i].client_list, MAX_FRIEND_CLIENTS,
&num_nodes, is_lan, want_announce);
}
return num_nodes;
}
int get_close_nodes(const DHT *dht, const uint8_t *public_key, Node_format *nodes_list, Family sa_family,
bool is_lan, bool want_announce)
{
memset(nodes_list, 0, MAX_SENT_NODES * sizeof(Node_format));
return get_somewhat_close_nodes(dht, public_key, nodes_list, sa_family,
is_lan, want_announce);
}
typedef struct DHT_Cmp_Data {
uint64_t cur_time;
const uint8_t *base_public_key;
Client_data entry;
} DHT_Cmp_Data;
non_null()
static int dht_cmp_entry(const void *a, const void *b)
{
const DHT_Cmp_Data *cmp1 = (const DHT_Cmp_Data *)a;
const DHT_Cmp_Data *cmp2 = (const DHT_Cmp_Data *)b;
const Client_data entry1 = cmp1->entry;
const Client_data entry2 = cmp2->entry;
const uint8_t *cmp_public_key = cmp1->base_public_key;
const bool t1 = assoc_timeout(cmp1->cur_time, &entry1.assoc4) && assoc_timeout(cmp1->cur_time, &entry1.assoc6);
const bool t2 = assoc_timeout(cmp2->cur_time, &entry2.assoc4) && assoc_timeout(cmp2->cur_time, &entry2.assoc6);
if (t1 && t2) {
return 0;
}
if (t1) {
return -1;
}
if (t2) {
return 1;
}
const int closest = id_closest(cmp_public_key, entry1.public_key, entry2.public_key);
if (closest == 1) {
return 1;
}
if (closest == 2) {
return -1;
}
return 0;
}
#ifdef CHECK_ANNOUNCE_NODE
non_null()
static void set_announce_node_in_list(Client_data *list, uint32_t list_len, const uint8_t *public_key)
{
const uint32_t index = index_of_client_pk(list, list_len, public_key);
if (index != UINT32_MAX) {
list[index].announce_node = true;
}
}
void set_announce_node(DHT *dht, const uint8_t *public_key)
{
unsigned int index = bit_by_bit_cmp(public_key, dht->self_public_key);
if (index >= LCLIENT_LENGTH) {
index = LCLIENT_LENGTH - 1;
}
set_announce_node_in_list(dht->close_clientlist + index * LCLIENT_NODES, LCLIENT_NODES, public_key);
for (int32_t i = 0; i < dht->num_friends; ++i) {
set_announce_node_in_list(dht->friends_list[i].client_list, MAX_FRIEND_CLIENTS, public_key);
}
}
/** @brief Send data search request, searching for a random key. */
non_null()
static bool send_announce_ping(DHT *dht, const uint8_t *public_key, const IP_Port *ip_port)
{
uint8_t plain[CRYPTO_PUBLIC_KEY_SIZE + sizeof(uint64_t)];
uint8_t unused_secret_key[CRYPTO_SECRET_KEY_SIZE];
crypto_new_keypair(dht->rng, plain, unused_secret_key);
const uint64_t ping_id = ping_array_add(dht->dht_ping_array,
dht->mono_time,
dht->rng,
public_key, CRYPTO_PUBLIC_KEY_SIZE);
memcpy(plain + CRYPTO_PUBLIC_KEY_SIZE, &ping_id, sizeof(ping_id));
const uint8_t *shared_key = dht_get_shared_key_sent(dht, public_key);
uint8_t request[1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + sizeof(plain) + CRYPTO_MAC_SIZE];
if (dht_create_packet(dht->mem, dht->rng,
dht->self_public_key, shared_key, NET_PACKET_DATA_SEARCH_REQUEST,
plain, sizeof(plain), request, sizeof(request)) != sizeof(request)) {
return false;
}
return sendpacket(dht->net, ip_port, request, sizeof(request)) == sizeof(request);
}
/** @brief If the response is valid, set the sender as an announce node. */
non_null(1, 2, 3) nullable(5)
static int handle_data_search_response(void *object, const IP_Port *source,
const uint8_t *packet, uint16_t length,
void *userdata)
{
DHT *dht = (DHT *) object;
const int32_t plain_len = (int32_t)length - (1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + CRYPTO_MAC_SIZE);
if (plain_len < (int32_t)(CRYPTO_PUBLIC_KEY_SIZE + sizeof(uint64_t))) {
return 1;
}
VLA(uint8_t, plain, plain_len);
const uint8_t *public_key = packet + 1;
const uint8_t *shared_key = dht_get_shared_key_recv(dht, public_key);
if (decrypt_data_symmetric(shared_key,
packet + 1 + CRYPTO_PUBLIC_KEY_SIZE,
packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE,
plain_len + CRYPTO_MAC_SIZE,
plain) != plain_len) {
return 1;
}
uint64_t ping_id = 0;
memcpy(&ping_id, plain + (plain_len - sizeof(uint64_t)), sizeof(ping_id));
uint8_t ping_data[CRYPTO_PUBLIC_KEY_SIZE];
if (ping_array_check(dht->dht_ping_array,
dht->mono_time, ping_data,
sizeof(ping_data), ping_id) != sizeof(ping_data)) {
return 1;
}
if (!pk_equal(ping_data, public_key)) {
return 1;
}
set_announce_node(dht, public_key);
return 0;
}
#endif
/** @brief Is it ok to store node with public_key in client.
*
* return false if node can't be stored.
* return true if it can.
*/
non_null()