1 /* SPDX-License-Identifier: GPL-3.0-or-later
2  * Copyright © 2016-2018 The TokTok team.
3  * Copyright © 2013 Tox project.
4  */
5 
6 /*
7  * Functions for the core network crypto.
8  *
9  * NOTE: This code has to be perfect. We don't mess around with encryption.
10  */
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14 
15 #include "net_crypto.h"
16 
17 #include <math.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 #include "mono_time.h"
22 #include "util.h"
23 
24 typedef struct Packet_Data {
25     uint64_t sent_time;
26     uint16_t length;
27     uint8_t data[MAX_CRYPTO_DATA_SIZE];
28 } Packet_Data;
29 
30 typedef struct Packets_Array {
31     Packet_Data *buffer[CRYPTO_PACKET_BUFFER_SIZE];
32     uint32_t  buffer_start;
33     uint32_t  buffer_end; /* packet numbers in array: `{buffer_start, buffer_end)` */
34 } Packets_Array;
35 
36 typedef enum Crypto_Conn_State {
37     CRYPTO_CONN_FREE = 0,            /* the connection slot is free. This value is 0 so it is valid after
38                                       * `crypto_memzero(...)` of the parent struct
39                                       */
40     CRYPTO_CONN_NO_CONNECTION,       /* the connection is allocated, but not yet used */
41     CRYPTO_CONN_COOKIE_REQUESTING,   /* we are sending cookie request packets */
42     CRYPTO_CONN_HANDSHAKE_SENT,      /* we are sending handshake packets */
43     CRYPTO_CONN_NOT_CONFIRMED,       /* we are sending handshake packets.
44                                       * we have received one from the other, but no data */
45     CRYPTO_CONN_ESTABLISHED,         /* the connection is established */
46 } Crypto_Conn_State;
47 
48 typedef struct Crypto_Connection {
49     uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* The real public key of the peer. */
50     uint8_t recv_nonce[CRYPTO_NONCE_SIZE]; /* Nonce of received packets. */
51     uint8_t sent_nonce[CRYPTO_NONCE_SIZE]; /* Nonce of sent packets. */
52     uint8_t sessionpublic_key[CRYPTO_PUBLIC_KEY_SIZE]; /* Our public key for this session. */
53     uint8_t sessionsecret_key[CRYPTO_SECRET_KEY_SIZE]; /* Our private key for this session. */
54     uint8_t peersessionpublic_key[CRYPTO_PUBLIC_KEY_SIZE]; /* The public key of the peer. */
55     uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE]; /* The precomputed shared key from encrypt_precompute. */
56     Crypto_Conn_State status; /* See Crypto_Conn_State documentation */
57     uint64_t cookie_request_number; /* number used in the cookie request packets for this connection */
58     uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* The dht public key of the peer */
59 
60     uint8_t *temp_packet; /* Where the cookie request/handshake packet is stored while it is being sent. */
61     uint16_t temp_packet_length;
62     uint64_t temp_packet_sent_time; /* The time at which the last temp_packet was sent in ms. */
63     uint32_t temp_packet_num_sent;
64 
65     IP_Port ip_portv4; /* The ip and port to contact this guy directly.*/
66     IP_Port ip_portv6;
67     uint64_t direct_lastrecv_timev4; /* The Time at which we last received a direct packet in ms. */
68     uint64_t direct_lastrecv_timev6;
69 
70     uint64_t last_tcp_sent; /* Time the last TCP packet was sent. */
71 
72     Packets_Array send_array;
73     Packets_Array recv_array;
74 
75     connection_status_cb *connection_status_callback;
76     void *connection_status_callback_object;
77     int connection_status_callback_id;
78 
79     connection_data_cb *connection_data_callback;
80     void *connection_data_callback_object;
81     int connection_data_callback_id;
82 
83     connection_lossy_data_cb *connection_lossy_data_callback;
84     void *connection_lossy_data_callback_object;
85     int connection_lossy_data_callback_id;
86 
87     uint64_t last_request_packet_sent;
88     uint64_t direct_send_attempt_time;
89 
90     uint32_t packet_counter;
91     double packet_recv_rate;
92     uint64_t packet_counter_set;
93 
94     double packet_send_rate;
95     uint32_t packets_left;
96     uint64_t last_packets_left_set;
97     double last_packets_left_rem;
98 
99     double packet_send_rate_requested;
100     uint32_t packets_left_requested;
101     uint64_t last_packets_left_requested_set;
102     double last_packets_left_requested_rem;
103 
104     uint32_t last_sendqueue_size[CONGESTION_QUEUE_ARRAY_SIZE];
105     uint32_t last_sendqueue_counter;
106     long signed int last_num_packets_sent[CONGESTION_LAST_SENT_ARRAY_SIZE];
107     long signed int last_num_packets_resent[CONGESTION_LAST_SENT_ARRAY_SIZE];
108     uint32_t packets_sent;
109     uint32_t packets_resent;
110     uint64_t last_congestion_event;
111     uint64_t rtt_time;
112 
113     /* TCP_connection connection_number */
114     unsigned int connection_number_tcp;
115 
116     uint8_t maximum_speed_reached;
117 
118     /* Must be a pointer, because the struct is moved in memory */
119     pthread_mutex_t *mutex;
120 
121     dht_pk_cb *dht_pk_callback;
122     void *dht_pk_callback_object;
123     uint32_t dht_pk_callback_number;
124 } Crypto_Connection;
125 
126 struct Net_Crypto {
127     const Logger *log;
128     Mono_Time *mono_time;
129 
130     DHT *dht;
131     TCP_Connections *tcp_c;
132 
133     Crypto_Connection *crypto_connections;
134     pthread_mutex_t tcp_mutex;
135 
136     pthread_mutex_t connections_mutex;
137     unsigned int connection_use_counter;
138 
139     uint32_t crypto_connections_length; /* Length of connections array. */
140 
141     /* Our public and secret keys. */
142     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
143     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
144 
145     /* The secret key used for cookies */
146     uint8_t secret_symmetric_key[CRYPTO_SYMMETRIC_KEY_SIZE];
147 
148     new_connection_cb *new_connection_callback;
149     void *new_connection_callback_object;
150 
151     /* The current optimal sleep time */
152     uint32_t current_sleep_time;
153 
154     BS_List ip_port_list;
155 };
156 
nc_get_self_public_key(const Net_Crypto * c)157 const uint8_t *nc_get_self_public_key(const Net_Crypto *c)
158 {
159     return c->self_public_key;
160 }
161 
nc_get_self_secret_key(const Net_Crypto * c)162 const uint8_t *nc_get_self_secret_key(const Net_Crypto *c)
163 {
164     return c->self_secret_key;
165 }
166 
nc_get_tcp_c(const Net_Crypto * c)167 TCP_Connections *nc_get_tcp_c(const Net_Crypto *c)
168 {
169     return c->tcp_c;
170 }
171 
nc_get_dht(const Net_Crypto * c)172 DHT *nc_get_dht(const Net_Crypto *c)
173 {
174     return c->dht;
175 }
176 
crypt_connection_id_is_valid(const Net_Crypto * c,int crypt_connection_id)177 static bool crypt_connection_id_is_valid(const Net_Crypto *c, int crypt_connection_id)
178 {
179     if ((uint32_t)crypt_connection_id >= c->crypto_connections_length) {
180         return false;
181     }
182 
183     if (c->crypto_connections == nullptr) {
184         return false;
185     }
186 
187     const Crypto_Conn_State status = c->crypto_connections[crypt_connection_id].status;
188 
189     if (status == CRYPTO_CONN_NO_CONNECTION || status == CRYPTO_CONN_FREE) {
190         return false;
191     }
192 
193     return true;
194 }
195 
196 /* cookie timeout in seconds */
197 #define COOKIE_TIMEOUT 15
198 #define COOKIE_DATA_LENGTH (uint16_t)(CRYPTO_PUBLIC_KEY_SIZE * 2)
199 #define COOKIE_CONTENTS_LENGTH (uint16_t)(sizeof(uint64_t) + COOKIE_DATA_LENGTH)
200 #define COOKIE_LENGTH (uint16_t)(CRYPTO_NONCE_SIZE + COOKIE_CONTENTS_LENGTH + CRYPTO_MAC_SIZE)
201 
202 #define COOKIE_REQUEST_PLAIN_LENGTH (uint16_t)(COOKIE_DATA_LENGTH + sizeof(uint64_t))
203 #define COOKIE_REQUEST_LENGTH (uint16_t)(1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + COOKIE_REQUEST_PLAIN_LENGTH + CRYPTO_MAC_SIZE)
204 #define COOKIE_RESPONSE_LENGTH (uint16_t)(1 + CRYPTO_NONCE_SIZE + COOKIE_LENGTH + sizeof(uint64_t) + CRYPTO_MAC_SIZE)
205 
206 /* Create a cookie request packet and put it in packet.
207  * dht_public_key is the dht public key of the other
208  *
209  * packet must be of size COOKIE_REQUEST_LENGTH or bigger.
210  *
211  * return -1 on failure.
212  * return COOKIE_REQUEST_LENGTH on success.
213  */
create_cookie_request(const Net_Crypto * c,uint8_t * packet,uint8_t * dht_public_key,uint64_t number,uint8_t * shared_key)214 static int create_cookie_request(const Net_Crypto *c, uint8_t *packet, uint8_t *dht_public_key, uint64_t number,
215                                  uint8_t *shared_key)
216 {
217     uint8_t plain[COOKIE_REQUEST_PLAIN_LENGTH];
218     uint8_t padding[CRYPTO_PUBLIC_KEY_SIZE] = {0};
219 
220     memcpy(plain, c->self_public_key, CRYPTO_PUBLIC_KEY_SIZE);
221     memcpy(plain + CRYPTO_PUBLIC_KEY_SIZE, padding, CRYPTO_PUBLIC_KEY_SIZE);
222     memcpy(plain + (CRYPTO_PUBLIC_KEY_SIZE * 2), &number, sizeof(uint64_t));
223 
224     dht_get_shared_key_sent(c->dht, shared_key, dht_public_key);
225     uint8_t nonce[CRYPTO_NONCE_SIZE];
226     random_nonce(nonce);
227     packet[0] = NET_PACKET_COOKIE_REQUEST;
228     memcpy(packet + 1, dht_get_self_public_key(c->dht), CRYPTO_PUBLIC_KEY_SIZE);
229     memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, nonce, CRYPTO_NONCE_SIZE);
230     int len = encrypt_data_symmetric(shared_key, nonce, plain, sizeof(plain),
231                                      packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE);
232 
233     if (len != COOKIE_REQUEST_PLAIN_LENGTH + CRYPTO_MAC_SIZE) {
234         return -1;
235     }
236 
237     return (1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + len);
238 }
239 
240 /* Create cookie of length COOKIE_LENGTH from bytes of length COOKIE_DATA_LENGTH using encryption_key
241  *
242  * return -1 on failure.
243  * return 0 on success.
244  */
create_cookie(const Logger * log,const Mono_Time * mono_time,uint8_t * cookie,const uint8_t * bytes,const uint8_t * encryption_key)245 static int create_cookie(const Logger *log, const Mono_Time *mono_time, uint8_t *cookie, const uint8_t *bytes,
246                          const uint8_t *encryption_key)
247 {
248     uint8_t contents[COOKIE_CONTENTS_LENGTH];
249     const uint64_t temp_time = mono_time_get(mono_time);
250     memcpy(contents, &temp_time, sizeof(temp_time));
251     memcpy(contents + sizeof(temp_time), bytes, COOKIE_DATA_LENGTH);
252     random_nonce(cookie);
253     int len = encrypt_data_symmetric(encryption_key, cookie, contents, sizeof(contents), cookie + CRYPTO_NONCE_SIZE);
254 
255     if (len != COOKIE_LENGTH - CRYPTO_NONCE_SIZE) {
256         return -1;
257     }
258 
259     return 0;
260 }
261 
262 /* Open cookie of length COOKIE_LENGTH to bytes of length COOKIE_DATA_LENGTH using encryption_key
263  *
264  * return -1 on failure.
265  * return 0 on success.
266  */
open_cookie(const Logger * log,const Mono_Time * mono_time,uint8_t * bytes,const uint8_t * cookie,const uint8_t * encryption_key)267 static int open_cookie(const Logger *log, const Mono_Time *mono_time, uint8_t *bytes, const uint8_t *cookie,
268                        const uint8_t *encryption_key)
269 {
270     uint8_t contents[COOKIE_CONTENTS_LENGTH];
271     const int len = decrypt_data_symmetric(encryption_key, cookie, cookie + CRYPTO_NONCE_SIZE,
272                                            COOKIE_LENGTH - CRYPTO_NONCE_SIZE, contents);
273 
274     if (len != sizeof(contents)) {
275         return -1;
276     }
277 
278     uint64_t cookie_time;
279     memcpy(&cookie_time, contents, sizeof(cookie_time));
280     const uint64_t temp_time = mono_time_get(mono_time);
281 
282     if (cookie_time + COOKIE_TIMEOUT < temp_time || temp_time < cookie_time) {
283         return -1;
284     }
285 
286     memcpy(bytes, contents + sizeof(cookie_time), COOKIE_DATA_LENGTH);
287     return 0;
288 }
289 
290 
291 /* Create a cookie response packet and put it in packet.
292  * request_plain must be COOKIE_REQUEST_PLAIN_LENGTH bytes.
293  * packet must be of size COOKIE_RESPONSE_LENGTH or bigger.
294  *
295  * return -1 on failure.
296  * return COOKIE_RESPONSE_LENGTH on success.
297  */
create_cookie_response(const Net_Crypto * c,uint8_t * packet,const uint8_t * request_plain,const uint8_t * shared_key,const uint8_t * dht_public_key)298 static int create_cookie_response(const Net_Crypto *c, uint8_t *packet, const uint8_t *request_plain,
299                                   const uint8_t *shared_key, const uint8_t *dht_public_key)
300 {
301     uint8_t cookie_plain[COOKIE_DATA_LENGTH];
302     memcpy(cookie_plain, request_plain, CRYPTO_PUBLIC_KEY_SIZE);
303     memcpy(cookie_plain + CRYPTO_PUBLIC_KEY_SIZE, dht_public_key, CRYPTO_PUBLIC_KEY_SIZE);
304     uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
305 
306     if (create_cookie(c->log, c->mono_time, plain, cookie_plain, c->secret_symmetric_key) != 0) {
307         return -1;
308     }
309 
310     memcpy(plain + COOKIE_LENGTH, request_plain + COOKIE_DATA_LENGTH, sizeof(uint64_t));
311     packet[0] = NET_PACKET_COOKIE_RESPONSE;
312     random_nonce(packet + 1);
313     int len = encrypt_data_symmetric(shared_key, packet + 1, plain, sizeof(plain), packet + 1 + CRYPTO_NONCE_SIZE);
314 
315     if (len != COOKIE_RESPONSE_LENGTH - (1 + CRYPTO_NONCE_SIZE)) {
316         return -1;
317     }
318 
319     return COOKIE_RESPONSE_LENGTH;
320 }
321 
322 /* Handle the cookie request packet of length length.
323  * Put what was in the request in request_plain (must be of size COOKIE_REQUEST_PLAIN_LENGTH)
324  * Put the key used to decrypt the request into shared_key (of size CRYPTO_SHARED_KEY_SIZE) for use in the response.
325  *
326  * return -1 on failure.
327  * return 0 on success.
328  */
handle_cookie_request(const Net_Crypto * c,uint8_t * request_plain,uint8_t * shared_key,uint8_t * dht_public_key,const uint8_t * packet,uint16_t length)329 static int handle_cookie_request(const Net_Crypto *c, uint8_t *request_plain, uint8_t *shared_key,
330                                  uint8_t *dht_public_key, const uint8_t *packet, uint16_t length)
331 {
332     if (length != COOKIE_REQUEST_LENGTH) {
333         return -1;
334     }
335 
336     memcpy(dht_public_key, packet + 1, CRYPTO_PUBLIC_KEY_SIZE);
337     dht_get_shared_key_sent(c->dht, shared_key, dht_public_key);
338     int len = decrypt_data_symmetric(shared_key, packet + 1 + CRYPTO_PUBLIC_KEY_SIZE,
339                                      packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE, COOKIE_REQUEST_PLAIN_LENGTH + CRYPTO_MAC_SIZE,
340                                      request_plain);
341 
342     if (len != COOKIE_REQUEST_PLAIN_LENGTH) {
343         return -1;
344     }
345 
346     return 0;
347 }
348 
349 /* Handle the cookie request packet (for raw UDP)
350  */
udp_handle_cookie_request(void * object,IP_Port source,const uint8_t * packet,uint16_t length,void * userdata)351 static int udp_handle_cookie_request(void *object, IP_Port source, const uint8_t *packet, uint16_t length,
352                                      void *userdata)
353 {
354     Net_Crypto *c = (Net_Crypto *)object;
355     uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
356     uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
357     uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE];
358 
359     if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) {
360         return 1;
361     }
362 
363     uint8_t data[COOKIE_RESPONSE_LENGTH];
364 
365     if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
366         return 1;
367     }
368 
369     if ((uint32_t)sendpacket(dht_get_net(c->dht), source, data, sizeof(data)) != sizeof(data)) {
370         return 1;
371     }
372 
373     return 0;
374 }
375 
376 /* Handle the cookie request packet (for TCP)
377  */
tcp_handle_cookie_request(Net_Crypto * c,int connections_number,const uint8_t * packet,uint16_t length)378 static int tcp_handle_cookie_request(Net_Crypto *c, int connections_number, const uint8_t *packet, uint16_t length)
379 {
380     uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
381     uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
382     uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE];
383 
384     if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) {
385         return -1;
386     }
387 
388     uint8_t data[COOKIE_RESPONSE_LENGTH];
389 
390     if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
391         return -1;
392     }
393 
394     int ret = send_packet_tcp_connection(c->tcp_c, connections_number, data, sizeof(data));
395     return ret;
396 }
397 
398 /* Handle the cookie request packet (for TCP oob packets)
399  */
tcp_oob_handle_cookie_request(const Net_Crypto * c,unsigned int tcp_connections_number,const uint8_t * dht_public_key,const uint8_t * packet,uint16_t length)400 static int tcp_oob_handle_cookie_request(const Net_Crypto *c, unsigned int tcp_connections_number,
401         const uint8_t *dht_public_key, const uint8_t *packet, uint16_t length)
402 {
403     uint8_t request_plain[COOKIE_REQUEST_PLAIN_LENGTH];
404     uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
405     uint8_t dht_public_key_temp[CRYPTO_PUBLIC_KEY_SIZE];
406 
407     if (handle_cookie_request(c, request_plain, shared_key, dht_public_key_temp, packet, length) != 0) {
408         return -1;
409     }
410 
411     if (public_key_cmp(dht_public_key, dht_public_key_temp) != 0) {
412         return -1;
413     }
414 
415     uint8_t data[COOKIE_RESPONSE_LENGTH];
416 
417     if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
418         return -1;
419     }
420 
421     int ret = tcp_send_oob_packet(c->tcp_c, tcp_connections_number, dht_public_key, data, sizeof(data));
422     return ret;
423 }
424 
425 /* Handle a cookie response packet of length encrypted with shared_key.
426  * put the cookie in the response in cookie
427  *
428  * cookie must be of length COOKIE_LENGTH.
429  *
430  * return -1 on failure.
431  * return COOKIE_LENGTH on success.
432  */
handle_cookie_response(const Logger * log,uint8_t * cookie,uint64_t * number,const uint8_t * packet,uint16_t length,const uint8_t * shared_key)433 static int handle_cookie_response(const Logger *log, uint8_t *cookie, uint64_t *number,
434                                   const uint8_t *packet, uint16_t length,
435                                   const uint8_t *shared_key)
436 {
437     if (length != COOKIE_RESPONSE_LENGTH) {
438         return -1;
439     }
440 
441     uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
442     const int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + CRYPTO_NONCE_SIZE,
443                                            length - (1 + CRYPTO_NONCE_SIZE), plain);
444 
445     if (len != sizeof(plain)) {
446         return -1;
447     }
448 
449     memcpy(cookie, plain, COOKIE_LENGTH);
450     memcpy(number, plain + COOKIE_LENGTH, sizeof(uint64_t));
451     return COOKIE_LENGTH;
452 }
453 
454 #define HANDSHAKE_PACKET_LENGTH (1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE + COOKIE_LENGTH + CRYPTO_MAC_SIZE)
455 
456 /* Create a handshake packet and put it in packet.
457  * cookie must be COOKIE_LENGTH bytes.
458  * packet must be of size HANDSHAKE_PACKET_LENGTH or bigger.
459  *
460  * return -1 on failure.
461  * return HANDSHAKE_PACKET_LENGTH on success.
462  */
create_crypto_handshake(const Net_Crypto * c,uint8_t * packet,const uint8_t * cookie,const uint8_t * nonce,const uint8_t * session_pk,const uint8_t * peer_real_pk,const uint8_t * peer_dht_pubkey)463 static int create_crypto_handshake(const Net_Crypto *c, uint8_t *packet, const uint8_t *cookie, const uint8_t *nonce,
464                                    const uint8_t *session_pk, const uint8_t *peer_real_pk, const uint8_t *peer_dht_pubkey)
465 {
466     uint8_t plain[CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE + COOKIE_LENGTH];
467     memcpy(plain, nonce, CRYPTO_NONCE_SIZE);
468     memcpy(plain + CRYPTO_NONCE_SIZE, session_pk, CRYPTO_PUBLIC_KEY_SIZE);
469     crypto_sha512(plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE, cookie, COOKIE_LENGTH);
470     uint8_t cookie_plain[COOKIE_DATA_LENGTH];
471     memcpy(cookie_plain, peer_real_pk, CRYPTO_PUBLIC_KEY_SIZE);
472     memcpy(cookie_plain + CRYPTO_PUBLIC_KEY_SIZE, peer_dht_pubkey, CRYPTO_PUBLIC_KEY_SIZE);
473 
474     if (create_cookie(c->log, c->mono_time, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE,
475                       cookie_plain, c->secret_symmetric_key) != 0) {
476         return -1;
477     }
478 
479     random_nonce(packet + 1 + COOKIE_LENGTH);
480     int len = encrypt_data(peer_real_pk, c->self_secret_key, packet + 1 + COOKIE_LENGTH, plain, sizeof(plain),
481                            packet + 1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE);
482 
483     if (len != HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE)) {
484         return -1;
485     }
486 
487     packet[0] = NET_PACKET_CRYPTO_HS;
488     memcpy(packet + 1, cookie, COOKIE_LENGTH);
489 
490     return HANDSHAKE_PACKET_LENGTH;
491 }
492 
493 /* Handle a crypto handshake packet of length.
494  * put the nonce contained in the packet in nonce,
495  * the session public key in session_pk
496  * the real public key of the peer in peer_real_pk
497  * the dht public key of the peer in dht_public_key and
498  * the cookie inside the encrypted part of the packet in cookie.
499  *
500  * if expected_real_pk isn't NULL it denotes the real public key
501  * the packet should be from.
502  *
503  * nonce must be at least CRYPTO_NONCE_SIZE
504  * session_pk must be at least CRYPTO_PUBLIC_KEY_SIZE
505  * peer_real_pk must be at least CRYPTO_PUBLIC_KEY_SIZE
506  * cookie must be at least COOKIE_LENGTH
507  *
508  * return -1 on failure.
509  * return 0 on success.
510  */
handle_crypto_handshake(const Net_Crypto * c,uint8_t * nonce,uint8_t * session_pk,uint8_t * peer_real_pk,uint8_t * dht_public_key,uint8_t * cookie,const uint8_t * packet,uint16_t length,const uint8_t * expected_real_pk)511 static int handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t *session_pk, uint8_t *peer_real_pk,
512                                    uint8_t *dht_public_key, uint8_t *cookie, const uint8_t *packet, uint16_t length, const uint8_t *expected_real_pk)
513 {
514     if (length != HANDSHAKE_PACKET_LENGTH) {
515         return -1;
516     }
517 
518     uint8_t cookie_plain[COOKIE_DATA_LENGTH];
519 
520     if (open_cookie(c->log, c->mono_time, cookie_plain, packet + 1, c->secret_symmetric_key) != 0) {
521         return -1;
522     }
523 
524     if (expected_real_pk) {
525         if (public_key_cmp(cookie_plain, expected_real_pk) != 0) {
526             return -1;
527         }
528     }
529 
530     uint8_t cookie_hash[CRYPTO_SHA512_SIZE];
531     crypto_sha512(cookie_hash, packet + 1, COOKIE_LENGTH);
532 
533     uint8_t plain[CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE + COOKIE_LENGTH];
534     int len = decrypt_data(cookie_plain, c->self_secret_key, packet + 1 + COOKIE_LENGTH,
535                            packet + 1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE,
536                            HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + CRYPTO_NONCE_SIZE), plain);
537 
538     if (len != sizeof(plain)) {
539         return -1;
540     }
541 
542     if (crypto_memcmp(cookie_hash, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE,
543                       CRYPTO_SHA512_SIZE) != 0) {
544         return -1;
545     }
546 
547     memcpy(nonce, plain, CRYPTO_NONCE_SIZE);
548     memcpy(session_pk, plain + CRYPTO_NONCE_SIZE, CRYPTO_PUBLIC_KEY_SIZE);
549     memcpy(cookie, plain + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SHA512_SIZE, COOKIE_LENGTH);
550     memcpy(peer_real_pk, cookie_plain, CRYPTO_PUBLIC_KEY_SIZE);
551     memcpy(dht_public_key, cookie_plain + CRYPTO_PUBLIC_KEY_SIZE, CRYPTO_PUBLIC_KEY_SIZE);
552     return 0;
553 }
554 
555 
get_crypto_connection(const Net_Crypto * c,int crypt_connection_id)556 static Crypto_Connection *get_crypto_connection(const Net_Crypto *c, int crypt_connection_id)
557 {
558     if (!crypt_connection_id_is_valid(c, crypt_connection_id)) {
559         return nullptr;
560     }
561 
562     return &c->crypto_connections[crypt_connection_id];
563 }
564 
565 
566 /* Associate an ip_port to a connection.
567  *
568  * return -1 on failure.
569  * return 0 on success.
570  */
add_ip_port_connection(Net_Crypto * c,int crypt_connection_id,IP_Port ip_port)571 static int add_ip_port_connection(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port)
572 {
573     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
574 
575     if (conn == nullptr) {
576         return -1;
577     }
578 
579     if (net_family_is_ipv4(ip_port.ip.family)) {
580         if (!ipport_equal(&ip_port, &conn->ip_portv4) && !ip_is_lan(conn->ip_portv4.ip)) {
581             if (!bs_list_add(&c->ip_port_list, (uint8_t *)&ip_port, crypt_connection_id)) {
582                 return -1;
583             }
584 
585             bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv4, crypt_connection_id);
586             conn->ip_portv4 = ip_port;
587             return 0;
588         }
589     } else if (net_family_is_ipv6(ip_port.ip.family)) {
590         if (!ipport_equal(&ip_port, &conn->ip_portv6)) {
591             if (!bs_list_add(&c->ip_port_list, (uint8_t *)&ip_port, crypt_connection_id)) {
592                 return -1;
593             }
594 
595             bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv6, crypt_connection_id);
596             conn->ip_portv6 = ip_port;
597             return 0;
598         }
599     }
600 
601     return -1;
602 }
603 
604 /* Return the IP_Port that should be used to send packets to the other peer.
605  *
606  * return IP_Port with family 0 on failure.
607  * return IP_Port on success.
608  */
return_ip_port_connection(Net_Crypto * c,int crypt_connection_id)609 static IP_Port return_ip_port_connection(Net_Crypto *c, int crypt_connection_id)
610 {
611     const IP_Port empty = {{{0}}};
612 
613     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
614 
615     if (conn == nullptr) {
616         return empty;
617     }
618 
619     const uint64_t current_time = mono_time_get(c->mono_time);
620     bool v6 = 0;
621     bool v4 = 0;
622 
623     if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev4) > current_time) {
624         v4 = 1;
625     }
626 
627     if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev6) > current_time) {
628         v6 = 1;
629     }
630 
631     /* Prefer IP_Ports which haven't timed out to those which have.
632      * To break ties, prefer ipv4 lan, then ipv6, then non-lan ipv4.
633      */
634     if (v4 && ip_is_lan(conn->ip_portv4.ip)) {
635         return conn->ip_portv4;
636     }
637 
638     if (v6 && net_family_is_ipv6(conn->ip_portv6.ip.family)) {
639         return conn->ip_portv6;
640     }
641 
642     if (v4 && net_family_is_ipv4(conn->ip_portv4.ip.family)) {
643         return conn->ip_portv4;
644     }
645 
646     if (ip_is_lan(conn->ip_portv4.ip)) {
647         return conn->ip_portv4;
648     }
649 
650     if (net_family_is_ipv6(conn->ip_portv6.ip.family)) {
651         return conn->ip_portv6;
652     }
653 
654     if (net_family_is_ipv4(conn->ip_portv4.ip.family)) {
655         return conn->ip_portv4;
656     }
657 
658     return empty;
659 }
660 
661 /* Sends a packet to the peer using the fastest route.
662  *
663  * return -1 on failure.
664  * return 0 on success.
665  */
send_packet_to(Net_Crypto * c,int crypt_connection_id,const uint8_t * data,uint16_t length)666 static int send_packet_to(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length)
667 {
668 // TODO(irungentoo): TCP, etc...
669     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
670 
671     if (conn == nullptr) {
672         return -1;
673     }
674 
675     int direct_send_attempt = 0;
676 
677     pthread_mutex_lock(conn->mutex);
678     IP_Port ip_port = return_ip_port_connection(c, crypt_connection_id);
679 
680     // TODO(irungentoo): on bad networks, direct connections might not last indefinitely.
681     if (!net_family_is_unspec(ip_port.ip.family)) {
682         bool direct_connected = 0;
683 
684         // FIXME(sudden6): handle return value
685         crypto_connection_status(c, crypt_connection_id, &direct_connected, nullptr);
686 
687         if (direct_connected) {
688             if ((uint32_t)sendpacket(dht_get_net(c->dht), ip_port, data, length) == length) {
689                 pthread_mutex_unlock(conn->mutex);
690                 return 0;
691             }
692 
693             pthread_mutex_unlock(conn->mutex);
694             return -1;
695         }
696 
697         // TODO(irungentoo): a better way of sending packets directly to confirm the others ip.
698         const uint64_t current_time = mono_time_get(c->mono_time);
699 
700         if ((((UDP_DIRECT_TIMEOUT / 2) + conn->direct_send_attempt_time) < current_time && length < 96)
701                 || data[0] == NET_PACKET_COOKIE_REQUEST || data[0] == NET_PACKET_CRYPTO_HS) {
702             if ((uint32_t)sendpacket(dht_get_net(c->dht), ip_port, data, length) == length) {
703                 direct_send_attempt = 1;
704                 conn->direct_send_attempt_time = mono_time_get(c->mono_time);
705             }
706         }
707     }
708 
709     pthread_mutex_unlock(conn->mutex);
710     pthread_mutex_lock(&c->tcp_mutex);
711     int ret = send_packet_tcp_connection(c->tcp_c, conn->connection_number_tcp, data, length);
712     pthread_mutex_unlock(&c->tcp_mutex);
713 
714     pthread_mutex_lock(conn->mutex);
715 
716     if (ret == 0) {
717         conn->last_tcp_sent = current_time_monotonic(c->mono_time);
718     }
719 
720     pthread_mutex_unlock(conn->mutex);
721 
722     if (ret == 0 || direct_send_attempt) {
723         return 0;
724     }
725 
726     return -1;
727 }
728 
729 /** START: Array Related functions */
730 
731 
732 /* Return number of packets in array
733  * Note that holes are counted too.
734  */
num_packets_array(const Packets_Array * array)735 static uint32_t num_packets_array(const Packets_Array *array)
736 {
737     return array->buffer_end - array->buffer_start;
738 }
739 
740 /* Add data with packet number to array.
741  *
742  * return -1 on failure.
743  * return 0 on success.
744  */
add_data_to_buffer(const Logger * log,Packets_Array * array,uint32_t number,const Packet_Data * data)745 static int add_data_to_buffer(const Logger *log, Packets_Array *array, uint32_t number, const Packet_Data *data)
746 {
747     if (number - array->buffer_start >= CRYPTO_PACKET_BUFFER_SIZE) {
748         return -1;
749     }
750 
751     uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
752 
753     if (array->buffer[num]) {
754         return -1;
755     }
756 
757     Packet_Data *new_d = (Packet_Data *)malloc(sizeof(Packet_Data));
758 
759     if (new_d == nullptr) {
760         return -1;
761     }
762 
763     memcpy(new_d, data, sizeof(Packet_Data));
764     array->buffer[num] = new_d;
765 
766     if (number - array->buffer_start >= num_packets_array(array)) {
767         array->buffer_end = number + 1;
768     }
769 
770     return 0;
771 }
772 
773 /* Get pointer of data with packet number.
774  *
775  * return -1 on failure.
776  * return 0 if data at number is empty.
777  * return 1 if data pointer was put in data.
778  */
get_data_pointer(const Logger * log,const Packets_Array * array,Packet_Data ** data,uint32_t number)779 static int get_data_pointer(const Logger *log, const Packets_Array *array, Packet_Data **data, uint32_t number)
780 {
781     const uint32_t num_spots = num_packets_array(array);
782 
783     if (array->buffer_end - number > num_spots || number - array->buffer_start >= num_spots) {
784         return -1;
785     }
786 
787     uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
788 
789     if (!array->buffer[num]) {
790         return 0;
791     }
792 
793     *data = array->buffer[num];
794     return 1;
795 }
796 
797 /* Add data to end of array.
798  *
799  * return -1 on failure.
800  * return packet number on success.
801  */
add_data_end_of_buffer(const Logger * log,Packets_Array * array,const Packet_Data * data)802 static int64_t add_data_end_of_buffer(const Logger *log, Packets_Array *array, const Packet_Data *data)
803 {
804     const uint32_t num_spots = num_packets_array(array);
805 
806     if (num_spots >= CRYPTO_PACKET_BUFFER_SIZE) {
807         return -1;
808     }
809 
810     Packet_Data *new_d = (Packet_Data *)malloc(sizeof(Packet_Data));
811 
812     if (new_d == nullptr) {
813         return -1;
814     }
815 
816     memcpy(new_d, data, sizeof(Packet_Data));
817     uint32_t id = array->buffer_end;
818     array->buffer[id % CRYPTO_PACKET_BUFFER_SIZE] = new_d;
819     ++array->buffer_end;
820     return id;
821 }
822 
823 /* Read data from beginning of array.
824  *
825  * return -1 on failure.
826  * return packet number on success.
827  */
read_data_beg_buffer(const Logger * log,Packets_Array * array,Packet_Data * data)828 static int64_t read_data_beg_buffer(const Logger *log, Packets_Array *array, Packet_Data *data)
829 {
830     if (array->buffer_end == array->buffer_start) {
831         return -1;
832     }
833 
834     const uint32_t num = array->buffer_start % CRYPTO_PACKET_BUFFER_SIZE;
835 
836     if (!array->buffer[num]) {
837         return -1;
838     }
839 
840     memcpy(data, array->buffer[num], sizeof(Packet_Data));
841     uint32_t id = array->buffer_start;
842     ++array->buffer_start;
843     free(array->buffer[num]);
844     array->buffer[num] = nullptr;
845     return id;
846 }
847 
848 /* Delete all packets in array before number (but not number)
849  *
850  * return -1 on failure.
851  * return 0 on success
852  */
clear_buffer_until(const Logger * log,Packets_Array * array,uint32_t number)853 static int clear_buffer_until(const Logger *log, Packets_Array *array, uint32_t number)
854 {
855     const uint32_t num_spots = num_packets_array(array);
856 
857     if (array->buffer_end - number >= num_spots || number - array->buffer_start > num_spots) {
858         return -1;
859     }
860 
861     uint32_t i;
862 
863     for (i = array->buffer_start; i != number; ++i) {
864         uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
865 
866         if (array->buffer[num]) {
867             free(array->buffer[num]);
868             array->buffer[num] = nullptr;
869         }
870     }
871 
872     array->buffer_start = i;
873     return 0;
874 }
875 
clear_buffer(Packets_Array * array)876 static int clear_buffer(Packets_Array *array)
877 {
878     uint32_t i;
879 
880     for (i = array->buffer_start; i != array->buffer_end; ++i) {
881         uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
882 
883         if (array->buffer[num]) {
884             free(array->buffer[num]);
885             array->buffer[num] = nullptr;
886         }
887     }
888 
889     array->buffer_start = i;
890     return 0;
891 }
892 
893 /* Set array buffer end to number.
894  *
895  * return -1 on failure.
896  * return 0 on success.
897  */
set_buffer_end(const Logger * log,Packets_Array * array,uint32_t number)898 static int set_buffer_end(const Logger *log, Packets_Array *array, uint32_t number)
899 {
900     if (number - array->buffer_start > CRYPTO_PACKET_BUFFER_SIZE) {
901         return -1;
902     }
903 
904     if (number - array->buffer_end > CRYPTO_PACKET_BUFFER_SIZE) {
905         return -1;
906     }
907 
908     array->buffer_end = number;
909     return 0;
910 }
911 
912 /* Create a packet request packet from recv_array and send_buffer_end into
913  * data of length.
914  *
915  * return -1 on failure.
916  * return length of packet on success.
917  */
generate_request_packet(const Logger * log,uint8_t * data,uint16_t length,const Packets_Array * recv_array)918 static int generate_request_packet(const Logger *log, uint8_t *data, uint16_t length, const Packets_Array *recv_array)
919 {
920     if (length == 0) {
921         return -1;
922     }
923 
924     data[0] = PACKET_ID_REQUEST;
925 
926     uint16_t cur_len = 1;
927 
928     if (recv_array->buffer_start == recv_array->buffer_end) {
929         return cur_len;
930     }
931 
932     if (length <= cur_len) {
933         return cur_len;
934     }
935 
936     uint32_t n = 1;
937 
938     for (uint32_t i = recv_array->buffer_start; i != recv_array->buffer_end; ++i) {
939         uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
940 
941         if (!recv_array->buffer[num]) {
942             data[cur_len] = n;
943             n = 0;
944             ++cur_len;
945 
946             if (length <= cur_len) {
947                 return cur_len;
948             }
949         } else if (n == 255) {
950             data[cur_len] = 0;
951             n = 0;
952             ++cur_len;
953 
954             if (length <= cur_len) {
955                 return cur_len;
956             }
957         }
958 
959         ++n;
960     }
961 
962     return cur_len;
963 }
964 
965 /* Handle a request data packet.
966  * Remove all the packets the other received from the array.
967  *
968  * return -1 on failure.
969  * return number of requested packets on success.
970  */
handle_request_packet(Mono_Time * mono_time,const Logger * log,Packets_Array * send_array,const uint8_t * data,uint16_t length,uint64_t * latest_send_time,uint64_t rtt_time)971 static int handle_request_packet(Mono_Time *mono_time, const Logger *log, Packets_Array *send_array,
972                                  const uint8_t *data, uint16_t length, uint64_t *latest_send_time, uint64_t rtt_time)
973 {
974     if (length == 0) {
975         return -1;
976     }
977 
978     if (data[0] != PACKET_ID_REQUEST) {
979         return -1;
980     }
981 
982     if (length == 1) {
983         return 0;
984     }
985 
986     ++data;
987     --length;
988 
989     uint32_t n = 1;
990     uint32_t requested = 0;
991 
992     const uint64_t temp_time = current_time_monotonic(mono_time);
993     uint64_t l_sent_time = -1;
994 
995     for (uint32_t i = send_array->buffer_start; i != send_array->buffer_end; ++i) {
996         if (length == 0) {
997             break;
998         }
999 
1000         uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
1001 
1002         if (n == data[0]) {
1003             if (send_array->buffer[num]) {
1004                 uint64_t sent_time = send_array->buffer[num]->sent_time;
1005 
1006                 if ((sent_time + rtt_time) < temp_time) {
1007                     send_array->buffer[num]->sent_time = 0;
1008                 }
1009             }
1010 
1011             ++data;
1012             --length;
1013             n = 0;
1014             ++requested;
1015         } else {
1016             if (send_array->buffer[num]) {
1017                 uint64_t sent_time = send_array->buffer[num]->sent_time;
1018 
1019                 if (l_sent_time < sent_time) {
1020                     l_sent_time = sent_time;
1021                 }
1022 
1023                 free(send_array->buffer[num]);
1024                 send_array->buffer[num] = nullptr;
1025             }
1026         }
1027 
1028         if (n == 255) {
1029             n = 1;
1030 
1031             if (data[0] != 0) {
1032                 return -1;
1033             }
1034 
1035             ++data;
1036             --length;
1037         } else {
1038             ++n;
1039         }
1040     }
1041 
1042     if (*latest_send_time < l_sent_time) {
1043         *latest_send_time = l_sent_time;
1044     }
1045 
1046     return requested;
1047 }
1048 
1049 /** END: Array Related functions */
1050 
1051 #define MAX_DATA_DATA_PACKET_SIZE (MAX_CRYPTO_PACKET_SIZE - (1 + sizeof(uint16_t) + CRYPTO_MAC_SIZE))
1052 
1053 /* Creates and sends a data packet to the peer using the fastest route.
1054  *
1055  * return -1 on failure.
1056  * return 0 on success.
1057  */
send_data_packet(Net_Crypto * c,int crypt_connection_id,const uint8_t * data,uint16_t length)1058 static int send_data_packet(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length)
1059 {
1060     const uint16_t max_length = MAX_CRYPTO_PACKET_SIZE - (1 + sizeof(uint16_t) + CRYPTO_MAC_SIZE);
1061 
1062     if (length == 0 || length > max_length) {
1063         return -1;
1064     }
1065 
1066     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1067 
1068     if (conn == nullptr) {
1069         return -1;
1070     }
1071 
1072     pthread_mutex_lock(conn->mutex);
1073     VLA(uint8_t, packet, 1 + sizeof(uint16_t) + length + CRYPTO_MAC_SIZE);
1074     packet[0] = NET_PACKET_CRYPTO_DATA;
1075     memcpy(packet + 1, conn->sent_nonce + (CRYPTO_NONCE_SIZE - sizeof(uint16_t)), sizeof(uint16_t));
1076     const int len = encrypt_data_symmetric(conn->shared_key, conn->sent_nonce, data, length, packet + 1 + sizeof(uint16_t));
1077 
1078     if (len + 1 + sizeof(uint16_t) != SIZEOF_VLA(packet)) {
1079         pthread_mutex_unlock(conn->mutex);
1080         return -1;
1081     }
1082 
1083     increment_nonce(conn->sent_nonce);
1084     pthread_mutex_unlock(conn->mutex);
1085 
1086     return send_packet_to(c, crypt_connection_id, packet, SIZEOF_VLA(packet));
1087 }
1088 
1089 /* Creates and sends a data packet with buffer_start and num to the peer using the fastest route.
1090  *
1091  * return -1 on failure.
1092  * return 0 on success.
1093  */
send_data_packet_helper(Net_Crypto * c,int crypt_connection_id,uint32_t buffer_start,uint32_t num,const uint8_t * data,uint16_t length)1094 static int send_data_packet_helper(Net_Crypto *c, int crypt_connection_id, uint32_t buffer_start, uint32_t num,
1095                                    const uint8_t *data, uint16_t length)
1096 {
1097     if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
1098         return -1;
1099     }
1100 
1101     num = net_htonl(num);
1102     buffer_start = net_htonl(buffer_start);
1103     uint16_t padding_length = (MAX_CRYPTO_DATA_SIZE - length) % CRYPTO_MAX_PADDING;
1104     VLA(uint8_t, packet, sizeof(uint32_t) + sizeof(uint32_t) + padding_length + length);
1105     memcpy(packet, &buffer_start, sizeof(uint32_t));
1106     memcpy(packet + sizeof(uint32_t), &num, sizeof(uint32_t));
1107     memset(packet + (sizeof(uint32_t) * 2), PACKET_ID_PADDING, padding_length);
1108     memcpy(packet + (sizeof(uint32_t) * 2) + padding_length, data, length);
1109 
1110     return send_data_packet(c, crypt_connection_id, packet, SIZEOF_VLA(packet));
1111 }
1112 
reset_max_speed_reached(Net_Crypto * c,int crypt_connection_id)1113 static int reset_max_speed_reached(Net_Crypto *c, int crypt_connection_id)
1114 {
1115     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1116 
1117     if (conn == nullptr) {
1118         return -1;
1119     }
1120 
1121     /* If last packet send failed, try to send packet again.
1122      * If sending it fails we won't be able to send the new packet. */
1123     if (conn->maximum_speed_reached) {
1124         Packet_Data *dt = nullptr;
1125         const uint32_t packet_num = conn->send_array.buffer_end - 1;
1126         const int ret = get_data_pointer(c->log, &conn->send_array, &dt, packet_num);
1127 
1128         if (ret == 1 && dt->sent_time == 0) {
1129             if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num,
1130                                         dt->data, dt->length) != 0) {
1131                 return -1;
1132             }
1133 
1134             dt->sent_time = current_time_monotonic(c->mono_time);
1135         }
1136 
1137         conn->maximum_speed_reached = 0;
1138     }
1139 
1140     return 0;
1141 }
1142 
1143 /*  return -1 if data could not be put in packet queue.
1144  *  return positive packet number if data was put into the queue.
1145  */
send_lossless_packet(Net_Crypto * c,int crypt_connection_id,const uint8_t * data,uint16_t length,uint8_t congestion_control)1146 static int64_t send_lossless_packet(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length,
1147                                     uint8_t congestion_control)
1148 {
1149     if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
1150         return -1;
1151     }
1152 
1153     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1154 
1155     if (conn == nullptr) {
1156         return -1;
1157     }
1158 
1159     /* If last packet send failed, try to send packet again.
1160      * If sending it fails we won't be able to send the new packet. */
1161     reset_max_speed_reached(c, crypt_connection_id);
1162 
1163     if (conn->maximum_speed_reached && congestion_control) {
1164         return -1;
1165     }
1166 
1167     Packet_Data dt;
1168     dt.sent_time = 0;
1169     dt.length = length;
1170     memcpy(dt.data, data, length);
1171     pthread_mutex_lock(conn->mutex);
1172     int64_t packet_num = add_data_end_of_buffer(c->log, &conn->send_array, &dt);
1173     pthread_mutex_unlock(conn->mutex);
1174 
1175     if (packet_num == -1) {
1176         return -1;
1177     }
1178 
1179     if (!congestion_control && conn->maximum_speed_reached) {
1180         return packet_num;
1181     }
1182 
1183     if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num, data, length) == 0) {
1184         Packet_Data *dt1 = nullptr;
1185 
1186         if (get_data_pointer(c->log, &conn->send_array, &dt1, packet_num) == 1) {
1187             dt1->sent_time = current_time_monotonic(c->mono_time);
1188         }
1189     } else {
1190         conn->maximum_speed_reached = 1;
1191         LOGGER_DEBUG(c->log, "send_data_packet failed");
1192     }
1193 
1194     return packet_num;
1195 }
1196 
1197 /* Get the lowest 2 bytes from the nonce and convert
1198  * them to host byte format before returning them.
1199  */
get_nonce_uint16(const uint8_t * nonce)1200 static uint16_t get_nonce_uint16(const uint8_t *nonce)
1201 {
1202     uint16_t num;
1203     memcpy(&num, nonce + (CRYPTO_NONCE_SIZE - sizeof(uint16_t)), sizeof(uint16_t));
1204     return net_ntohs(num);
1205 }
1206 
1207 #define DATA_NUM_THRESHOLD 21845
1208 
1209 /* Handle a data packet.
1210  * Decrypt packet of length and put it into data.
1211  * data must be at least MAX_DATA_DATA_PACKET_SIZE big.
1212  *
1213  * return -1 on failure.
1214  * return length of data on success.
1215  */
handle_data_packet(const Net_Crypto * c,int crypt_connection_id,uint8_t * data,const uint8_t * packet,uint16_t length)1216 static int handle_data_packet(const Net_Crypto *c, int crypt_connection_id, uint8_t *data, const uint8_t *packet,
1217                               uint16_t length)
1218 {
1219     const uint16_t crypto_packet_overhead = 1 + sizeof(uint16_t) + CRYPTO_MAC_SIZE;
1220 
1221     if (length <= crypto_packet_overhead || length > MAX_CRYPTO_PACKET_SIZE) {
1222         return -1;
1223     }
1224 
1225     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1226 
1227     if (conn == nullptr) {
1228         return -1;
1229     }
1230 
1231     uint8_t nonce[CRYPTO_NONCE_SIZE];
1232     memcpy(nonce, conn->recv_nonce, CRYPTO_NONCE_SIZE);
1233     uint16_t num_cur_nonce = get_nonce_uint16(nonce);
1234     uint16_t num;
1235     net_unpack_u16(packet + 1, &num);
1236     uint16_t diff = num - num_cur_nonce;
1237     increment_nonce_number(nonce, diff);
1238     int len = decrypt_data_symmetric(conn->shared_key, nonce, packet + 1 + sizeof(uint16_t),
1239                                      length - (1 + sizeof(uint16_t)), data);
1240 
1241     if ((unsigned int)len != length - crypto_packet_overhead) {
1242         return -1;
1243     }
1244 
1245     if (diff > DATA_NUM_THRESHOLD * 2) {
1246         increment_nonce_number(conn->recv_nonce, DATA_NUM_THRESHOLD);
1247     }
1248 
1249     return len;
1250 }
1251 
1252 /* Send a request packet.
1253  *
1254  * return -1 on failure.
1255  * return 0 on success.
1256  */
send_request_packet(Net_Crypto * c,int crypt_connection_id)1257 static int send_request_packet(Net_Crypto *c, int crypt_connection_id)
1258 {
1259     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1260 
1261     if (conn == nullptr) {
1262         return -1;
1263     }
1264 
1265     uint8_t data[MAX_CRYPTO_DATA_SIZE];
1266     int len = generate_request_packet(c->log, data, sizeof(data), &conn->recv_array);
1267 
1268     if (len == -1) {
1269         return -1;
1270     }
1271 
1272     return send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, conn->send_array.buffer_end, data,
1273                                    len);
1274 }
1275 
1276 /* Send up to max num previously requested data packets.
1277  *
1278  * return -1 on failure.
1279  * return number of packets sent on success.
1280  */
send_requested_packets(Net_Crypto * c,int crypt_connection_id,uint32_t max_num)1281 static int send_requested_packets(Net_Crypto *c, int crypt_connection_id, uint32_t max_num)
1282 {
1283     if (max_num == 0) {
1284         return -1;
1285     }
1286 
1287     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1288 
1289     if (conn == nullptr) {
1290         return -1;
1291     }
1292 
1293     const uint64_t temp_time = current_time_monotonic(c->mono_time);
1294     const uint32_t array_size = num_packets_array(&conn->send_array);
1295     uint32_t num_sent = 0;
1296 
1297     for (uint32_t i = 0; i < array_size; ++i) {
1298         Packet_Data *dt;
1299         const uint32_t packet_num = i + conn->send_array.buffer_start;
1300         const int ret = get_data_pointer(c->log, &conn->send_array, &dt, packet_num);
1301 
1302         if (ret == -1) {
1303             return -1;
1304         }
1305 
1306         if (ret == 0) {
1307             continue;
1308         }
1309 
1310         if (dt->sent_time) {
1311             continue;
1312         }
1313 
1314         if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num, dt->data,
1315                                     dt->length) == 0) {
1316             dt->sent_time = temp_time;
1317             ++num_sent;
1318         }
1319 
1320         if (num_sent >= max_num) {
1321             break;
1322         }
1323     }
1324 
1325     return num_sent;
1326 }
1327 
1328 
1329 /* Add a new temp packet to send repeatedly.
1330  *
1331  * return -1 on failure.
1332  * return 0 on success.
1333  */
new_temp_packet(const Net_Crypto * c,int crypt_connection_id,const uint8_t * packet,uint16_t length)1334 static int new_temp_packet(const Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length)
1335 {
1336     if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
1337         return -1;
1338     }
1339 
1340     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1341 
1342     if (conn == nullptr) {
1343         return -1;
1344     }
1345 
1346     uint8_t *temp_packet = (uint8_t *)malloc(length);
1347 
1348     if (temp_packet == nullptr) {
1349         return -1;
1350     }
1351 
1352     if (conn->temp_packet) {
1353         free(conn->temp_packet);
1354     }
1355 
1356     memcpy(temp_packet, packet, length);
1357     conn->temp_packet = temp_packet;
1358     conn->temp_packet_length = length;
1359     conn->temp_packet_sent_time = 0;
1360     conn->temp_packet_num_sent = 0;
1361     return 0;
1362 }
1363 
1364 /* Clear the temp packet.
1365  *
1366  * return -1 on failure.
1367  * return 0 on success.
1368  */
clear_temp_packet(const Net_Crypto * c,int crypt_connection_id)1369 static int clear_temp_packet(const Net_Crypto *c, int crypt_connection_id)
1370 {
1371     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1372 
1373     if (conn == nullptr) {
1374         return -1;
1375     }
1376 
1377     if (conn->temp_packet) {
1378         free(conn->temp_packet);
1379     }
1380 
1381     conn->temp_packet = nullptr;
1382     conn->temp_packet_length = 0;
1383     conn->temp_packet_sent_time = 0;
1384     conn->temp_packet_num_sent = 0;
1385     return 0;
1386 }
1387 
1388 
1389 /* Send the temp packet.
1390  *
1391  * return -1 on failure.
1392  * return 0 on success.
1393  */
send_temp_packet(Net_Crypto * c,int crypt_connection_id)1394 static int send_temp_packet(Net_Crypto *c, int crypt_connection_id)
1395 {
1396     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1397 
1398     if (conn == nullptr) {
1399         return -1;
1400     }
1401 
1402     if (!conn->temp_packet) {
1403         return -1;
1404     }
1405 
1406     if (send_packet_to(c, crypt_connection_id, conn->temp_packet, conn->temp_packet_length) != 0) {
1407         return -1;
1408     }
1409 
1410     conn->temp_packet_sent_time = current_time_monotonic(c->mono_time);
1411     ++conn->temp_packet_num_sent;
1412     return 0;
1413 }
1414 
1415 /* Create a handshake packet and set it as a temp packet.
1416  * cookie must be COOKIE_LENGTH.
1417  *
1418  * return -1 on failure.
1419  * return 0 on success.
1420  */
create_send_handshake(Net_Crypto * c,int crypt_connection_id,const uint8_t * cookie,const uint8_t * dht_public_key)1421 static int create_send_handshake(Net_Crypto *c, int crypt_connection_id, const uint8_t *cookie,
1422                                  const uint8_t *dht_public_key)
1423 {
1424     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1425 
1426     if (conn == nullptr) {
1427         return -1;
1428     }
1429 
1430     uint8_t handshake_packet[HANDSHAKE_PACKET_LENGTH];
1431 
1432     if (create_crypto_handshake(c, handshake_packet, cookie, conn->sent_nonce, conn->sessionpublic_key,
1433                                 conn->public_key, dht_public_key) != sizeof(handshake_packet)) {
1434         return -1;
1435     }
1436 
1437     if (new_temp_packet(c, crypt_connection_id, handshake_packet, sizeof(handshake_packet)) != 0) {
1438         return -1;
1439     }
1440 
1441     send_temp_packet(c, crypt_connection_id);
1442     return 0;
1443 }
1444 
1445 /* Send a kill packet.
1446  *
1447  * return -1 on failure.
1448  * return 0 on success.
1449  */
send_kill_packet(Net_Crypto * c,int crypt_connection_id)1450 static int send_kill_packet(Net_Crypto *c, int crypt_connection_id)
1451 {
1452     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1453 
1454     if (conn == nullptr) {
1455         return -1;
1456     }
1457 
1458     uint8_t kill_packet = PACKET_ID_KILL;
1459     return send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, conn->send_array.buffer_end,
1460                                    &kill_packet, sizeof(kill_packet));
1461 }
1462 
connection_kill(Net_Crypto * c,int crypt_connection_id,void * userdata)1463 static void connection_kill(Net_Crypto *c, int crypt_connection_id, void *userdata)
1464 {
1465     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1466 
1467     if (conn == nullptr) {
1468         return;
1469     }
1470 
1471     if (conn->connection_status_callback) {
1472         conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 0,
1473                                          userdata);
1474     }
1475 
1476     while (1) { /* TODO(irungentoo): is this really the best way to do this? */
1477         pthread_mutex_lock(&c->connections_mutex);
1478 
1479         if (!c->connection_use_counter) {
1480             break;
1481         }
1482 
1483         pthread_mutex_unlock(&c->connections_mutex);
1484     }
1485 
1486     crypto_kill(c, crypt_connection_id);
1487     pthread_mutex_unlock(&c->connections_mutex);
1488 }
1489 
1490 /* Handle a received data packet.
1491  *
1492  * return -1 on failure.
1493  * return 0 on success.
1494  */
handle_data_packet_core(Net_Crypto * c,int crypt_connection_id,const uint8_t * packet,uint16_t length,bool udp,void * userdata)1495 static int handle_data_packet_core(Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length,
1496                                    bool udp, void *userdata)
1497 {
1498     if (length > MAX_CRYPTO_PACKET_SIZE || length <= CRYPTO_DATA_PACKET_MIN_SIZE) {
1499         return -1;
1500     }
1501 
1502     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1503 
1504     if (conn == nullptr) {
1505         return -1;
1506     }
1507 
1508     uint8_t data[MAX_DATA_DATA_PACKET_SIZE];
1509     int len = handle_data_packet(c, crypt_connection_id, data, packet, length);
1510 
1511     if (len <= (int)(sizeof(uint32_t) * 2)) {
1512         return -1;
1513     }
1514 
1515     uint32_t buffer_start;
1516     uint32_t num;
1517     memcpy(&buffer_start, data, sizeof(uint32_t));
1518     memcpy(&num, data + sizeof(uint32_t), sizeof(uint32_t));
1519     buffer_start = net_ntohl(buffer_start);
1520     num = net_ntohl(num);
1521 
1522     uint64_t rtt_calc_time = 0;
1523 
1524     if (buffer_start != conn->send_array.buffer_start) {
1525         Packet_Data *packet_time;
1526 
1527         if (get_data_pointer(c->log, &conn->send_array, &packet_time, conn->send_array.buffer_start) == 1) {
1528             rtt_calc_time = packet_time->sent_time;
1529         }
1530 
1531         if (clear_buffer_until(c->log, &conn->send_array, buffer_start) != 0) {
1532             return -1;
1533         }
1534     }
1535 
1536     uint8_t *real_data = data + (sizeof(uint32_t) * 2);
1537     uint16_t real_length = len - (sizeof(uint32_t) * 2);
1538 
1539     while (real_data[0] == PACKET_ID_PADDING) { /* Remove Padding */
1540         ++real_data;
1541         --real_length;
1542 
1543         if (real_length == 0) {
1544             return -1;
1545         }
1546     }
1547 
1548     if (real_data[0] == PACKET_ID_KILL) {
1549         connection_kill(c, crypt_connection_id, userdata);
1550         return 0;
1551     }
1552 
1553     if (conn->status == CRYPTO_CONN_NOT_CONFIRMED) {
1554         clear_temp_packet(c, crypt_connection_id);
1555         conn->status = CRYPTO_CONN_ESTABLISHED;
1556 
1557         if (conn->connection_status_callback) {
1558             conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 1,
1559                                              userdata);
1560         }
1561     }
1562 
1563     if (real_data[0] == PACKET_ID_REQUEST) {
1564         uint64_t rtt_time;
1565 
1566         if (udp) {
1567             rtt_time = conn->rtt_time;
1568         } else {
1569             rtt_time = DEFAULT_TCP_PING_CONNECTION;
1570         }
1571 
1572         int requested = handle_request_packet(c->mono_time, c->log, &conn->send_array, real_data, real_length, &rtt_calc_time,
1573                                               rtt_time);
1574 
1575         if (requested == -1) {
1576             return -1;
1577         }
1578 
1579         set_buffer_end(c->log, &conn->recv_array, num);
1580     } else if (real_data[0] >= PACKET_ID_RANGE_LOSSLESS_START && real_data[0] <= PACKET_ID_RANGE_LOSSLESS_END) {
1581         Packet_Data dt = {0};
1582         dt.length = real_length;
1583         memcpy(dt.data, real_data, real_length);
1584 
1585         if (add_data_to_buffer(c->log, &conn->recv_array, num, &dt) != 0) {
1586             return -1;
1587         }
1588 
1589         while (1) {
1590             pthread_mutex_lock(conn->mutex);
1591             int ret = read_data_beg_buffer(c->log, &conn->recv_array, &dt);
1592             pthread_mutex_unlock(conn->mutex);
1593 
1594             if (ret == -1) {
1595                 break;
1596             }
1597 
1598             if (conn->connection_data_callback) {
1599                 conn->connection_data_callback(conn->connection_data_callback_object, conn->connection_data_callback_id, dt.data,
1600                                                dt.length, userdata);
1601             }
1602 
1603             /* conn might get killed in callback. */
1604             conn = get_crypto_connection(c, crypt_connection_id);
1605 
1606             if (conn == nullptr) {
1607                 return -1;
1608             }
1609         }
1610 
1611         /* Packet counter. */
1612         ++conn->packet_counter;
1613     } else if (real_data[0] >= PACKET_ID_RANGE_LOSSY_START && real_data[0] <= PACKET_ID_RANGE_LOSSY_END) {
1614 
1615         set_buffer_end(c->log, &conn->recv_array, num);
1616 
1617         if (conn->connection_lossy_data_callback) {
1618             conn->connection_lossy_data_callback(conn->connection_lossy_data_callback_object,
1619                                                  conn->connection_lossy_data_callback_id, real_data, real_length, userdata);
1620         }
1621     } else {
1622         return -1;
1623     }
1624 
1625     if (rtt_calc_time != 0) {
1626         uint64_t rtt_time = current_time_monotonic(c->mono_time) - rtt_calc_time;
1627 
1628         if (rtt_time < conn->rtt_time) {
1629             conn->rtt_time = rtt_time;
1630         }
1631     }
1632 
1633     return 0;
1634 }
1635 
1636 /* Handle a packet that was received for the connection.
1637  *
1638  * return -1 on failure.
1639  * return 0 on success.
1640  */
handle_packet_connection(Net_Crypto * c,int crypt_connection_id,const uint8_t * packet,uint16_t length,bool udp,void * userdata)1641 static int handle_packet_connection(Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length,
1642                                     bool udp, void *userdata)
1643 {
1644     if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
1645         return -1;
1646     }
1647 
1648     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1649 
1650     if (conn == nullptr) {
1651         return -1;
1652     }
1653 
1654     switch (packet[0]) {
1655         case NET_PACKET_COOKIE_RESPONSE: {
1656             if (conn->status != CRYPTO_CONN_COOKIE_REQUESTING) {
1657                 return -1;
1658             }
1659 
1660             uint8_t cookie[COOKIE_LENGTH];
1661             uint64_t number;
1662 
1663             if (handle_cookie_response(c->log, cookie, &number, packet, length, conn->shared_key) != sizeof(cookie)) {
1664                 return -1;
1665             }
1666 
1667             if (number != conn->cookie_request_number) {
1668                 return -1;
1669             }
1670 
1671             if (create_send_handshake(c, crypt_connection_id, cookie, conn->dht_public_key) != 0) {
1672                 return -1;
1673             }
1674 
1675             conn->status = CRYPTO_CONN_HANDSHAKE_SENT;
1676             return 0;
1677         }
1678 
1679         case NET_PACKET_CRYPTO_HS: {
1680             if (conn->status != CRYPTO_CONN_COOKIE_REQUESTING
1681                     && conn->status != CRYPTO_CONN_HANDSHAKE_SENT
1682                     && conn->status != CRYPTO_CONN_NOT_CONFIRMED) {
1683                 return -1;
1684             }
1685 
1686             uint8_t peer_real_pk[CRYPTO_PUBLIC_KEY_SIZE];
1687             uint8_t dht_public_key[CRYPTO_PUBLIC_KEY_SIZE];
1688             uint8_t cookie[COOKIE_LENGTH];
1689 
1690             if (handle_crypto_handshake(c, conn->recv_nonce, conn->peersessionpublic_key, peer_real_pk, dht_public_key, cookie,
1691                                         packet, length, conn->public_key) != 0) {
1692                 return -1;
1693             }
1694 
1695             if (public_key_cmp(dht_public_key, conn->dht_public_key) == 0) {
1696                 encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
1697 
1698                 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING) {
1699                     if (create_send_handshake(c, crypt_connection_id, cookie, dht_public_key) != 0) {
1700                         return -1;
1701                     }
1702                 }
1703 
1704                 conn->status = CRYPTO_CONN_NOT_CONFIRMED;
1705             } else {
1706                 if (conn->dht_pk_callback) {
1707                     conn->dht_pk_callback(conn->dht_pk_callback_object, conn->dht_pk_callback_number, dht_public_key, userdata);
1708                 }
1709             }
1710 
1711             return 0;
1712         }
1713 
1714         case NET_PACKET_CRYPTO_DATA: {
1715             if (conn->status != CRYPTO_CONN_NOT_CONFIRMED && conn->status != CRYPTO_CONN_ESTABLISHED) {
1716                 return -1;
1717             }
1718 
1719             return handle_data_packet_core(c, crypt_connection_id, packet, length, udp, userdata);
1720         }
1721 
1722         default: {
1723             return -1;
1724         }
1725     }
1726 }
1727 
1728 /* Set the size of the friend list to numfriends.
1729  *
1730  *  return -1 if realloc fails.
1731  *  return 0 if it succeeds.
1732  */
realloc_cryptoconnection(Net_Crypto * c,uint32_t num)1733 static int realloc_cryptoconnection(Net_Crypto *c, uint32_t num)
1734 {
1735     if (num == 0) {
1736         free(c->crypto_connections);
1737         c->crypto_connections = nullptr;
1738         return 0;
1739     }
1740 
1741     Crypto_Connection *newcrypto_connections = (Crypto_Connection *)realloc(c->crypto_connections,
1742             num * sizeof(Crypto_Connection));
1743 
1744     if (newcrypto_connections == nullptr) {
1745         return -1;
1746     }
1747 
1748     c->crypto_connections = newcrypto_connections;
1749     return 0;
1750 }
1751 
1752 
1753 /* Create a new empty crypto connection.
1754  *
1755  * return -1 on failure.
1756  * return connection id on success.
1757  */
create_crypto_connection(Net_Crypto * c)1758 static int create_crypto_connection(Net_Crypto *c)
1759 {
1760     while (1) { /* TODO(irungentoo): is this really the best way to do this? */
1761         pthread_mutex_lock(&c->connections_mutex);
1762 
1763         if (!c->connection_use_counter) {
1764             break;
1765         }
1766 
1767         pthread_mutex_unlock(&c->connections_mutex);
1768     }
1769 
1770     int id = -1;
1771 
1772     for (uint32_t i = 0; i < c->crypto_connections_length; ++i) {
1773         if (c->crypto_connections[i].status == CRYPTO_CONN_FREE) {
1774             id = i;
1775             break;
1776         }
1777     }
1778 
1779     if (id == -1) {
1780         if (realloc_cryptoconnection(c, c->crypto_connections_length + 1) == 0) {
1781             id = c->crypto_connections_length;
1782             ++c->crypto_connections_length;
1783             memset(&c->crypto_connections[id], 0, sizeof(Crypto_Connection));
1784         }
1785     }
1786 
1787     if (id != -1) {
1788         // Memsetting float/double to 0 is non-portable, so we explicitly set them to 0
1789         c->crypto_connections[id].packet_recv_rate = 0;
1790         c->crypto_connections[id].packet_send_rate = 0;
1791         c->crypto_connections[id].last_packets_left_rem = 0;
1792         c->crypto_connections[id].packet_send_rate_requested = 0;
1793         c->crypto_connections[id].last_packets_left_requested_rem = 0;
1794         c->crypto_connections[id].mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
1795 
1796         if (c->crypto_connections[id].mutex == nullptr) {
1797             pthread_mutex_unlock(&c->connections_mutex);
1798             return -1;
1799         }
1800 
1801         if (pthread_mutex_init(c->crypto_connections[id].mutex, nullptr) != 0) {
1802             free(c->crypto_connections[id].mutex);
1803             pthread_mutex_unlock(&c->connections_mutex);
1804             return -1;
1805         }
1806 
1807         c->crypto_connections[id].status = CRYPTO_CONN_NO_CONNECTION;
1808     }
1809 
1810     pthread_mutex_unlock(&c->connections_mutex);
1811     return id;
1812 }
1813 
1814 /* Wipe a crypto connection.
1815  *
1816  * return -1 on failure.
1817  * return 0 on success.
1818  */
wipe_crypto_connection(Net_Crypto * c,int crypt_connection_id)1819 static int wipe_crypto_connection(Net_Crypto *c, int crypt_connection_id)
1820 {
1821     if ((uint32_t)crypt_connection_id >= c->crypto_connections_length) {
1822         return -1;
1823     }
1824 
1825     if (c->crypto_connections == nullptr) {
1826         return -1;
1827     }
1828 
1829     const Crypto_Conn_State status = c->crypto_connections[crypt_connection_id].status;
1830 
1831     if (status == CRYPTO_CONN_FREE) {
1832         return -1;
1833     }
1834 
1835     uint32_t i;
1836 
1837     pthread_mutex_destroy(c->crypto_connections[crypt_connection_id].mutex);
1838     free(c->crypto_connections[crypt_connection_id].mutex);
1839     crypto_memzero(&c->crypto_connections[crypt_connection_id], sizeof(Crypto_Connection));
1840 
1841     /* check if we can resize the connections array */
1842     for (i = c->crypto_connections_length; i != 0; --i) {
1843         if (c->crypto_connections[i - 1].status != CRYPTO_CONN_FREE) {
1844             break;
1845         }
1846     }
1847 
1848     if (c->crypto_connections_length != i) {
1849         c->crypto_connections_length = i;
1850         realloc_cryptoconnection(c, c->crypto_connections_length);
1851     }
1852 
1853     return 0;
1854 }
1855 
1856 /* Get crypto connection id from public key of peer.
1857  *
1858  *  return -1 if there are no connections like we are looking for.
1859  *  return id if it found it.
1860  */
getcryptconnection_id(const Net_Crypto * c,const uint8_t * public_key)1861 static int getcryptconnection_id(const Net_Crypto *c, const uint8_t *public_key)
1862 {
1863     for (uint32_t i = 0; i < c->crypto_connections_length; ++i) {
1864         if (!crypt_connection_id_is_valid(c, i)) {
1865             continue;
1866         }
1867 
1868         if (public_key_cmp(public_key, c->crypto_connections[i].public_key) == 0) {
1869             return i;
1870         }
1871     }
1872 
1873     return -1;
1874 }
1875 
1876 /* Add a source to the crypto connection.
1877  * This is to be used only when we have received a packet from that source.
1878  *
1879  *  return -1 on failure.
1880  *  return positive number on success.
1881  *  0 if source was a direct UDP connection.
1882  */
crypto_connection_add_source(Net_Crypto * c,int crypt_connection_id,IP_Port source)1883 static int crypto_connection_add_source(Net_Crypto *c, int crypt_connection_id, IP_Port source)
1884 {
1885     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1886 
1887     if (conn == nullptr) {
1888         return -1;
1889     }
1890 
1891     if (net_family_is_ipv4(source.ip.family) || net_family_is_ipv6(source.ip.family)) {
1892         if (add_ip_port_connection(c, crypt_connection_id, source) != 0) {
1893             return -1;
1894         }
1895 
1896         if (net_family_is_ipv4(source.ip.family)) {
1897             conn->direct_lastrecv_timev4 = mono_time_get(c->mono_time);
1898         } else {
1899             conn->direct_lastrecv_timev6 = mono_time_get(c->mono_time);
1900         }
1901 
1902         return 0;
1903     }
1904 
1905     if (net_family_is_tcp_family(source.ip.family)) {
1906         if (add_tcp_number_relay_connection(c->tcp_c, conn->connection_number_tcp, source.ip.ip.v6.uint32[0]) == 0) {
1907             return 1;
1908         }
1909     }
1910 
1911     return -1;
1912 }
1913 
1914 
1915 /* Set function to be called when someone requests a new connection to us.
1916  *
1917  * The set function should return -1 on failure and 0 on success.
1918  *
1919  * n_c is only valid for the duration of the function call.
1920  */
new_connection_handler(Net_Crypto * c,new_connection_cb * new_connection_callback,void * object)1921 void new_connection_handler(Net_Crypto *c, new_connection_cb *new_connection_callback, void *object)
1922 {
1923     c->new_connection_callback = new_connection_callback;
1924     c->new_connection_callback_object = object;
1925 }
1926 
1927 /* Handle a handshake packet by someone who wants to initiate a new connection with us.
1928  * This calls the callback set by new_connection_handler() if the handshake is ok.
1929  *
1930  * return -1 on failure.
1931  * return 0 on success.
1932  */
handle_new_connection_handshake(Net_Crypto * c,IP_Port source,const uint8_t * data,uint16_t length,void * userdata)1933 static int handle_new_connection_handshake(Net_Crypto *c, IP_Port source, const uint8_t *data, uint16_t length,
1934         void *userdata)
1935 {
1936     New_Connection n_c;
1937     n_c.cookie = (uint8_t *)malloc(COOKIE_LENGTH);
1938 
1939     if (n_c.cookie == nullptr) {
1940         return -1;
1941     }
1942 
1943     n_c.source = source;
1944     n_c.cookie_length = COOKIE_LENGTH;
1945 
1946     if (handle_crypto_handshake(c, n_c.recv_nonce, n_c.peersessionpublic_key, n_c.public_key, n_c.dht_public_key,
1947                                 n_c.cookie, data, length, nullptr) != 0) {
1948         free(n_c.cookie);
1949         return -1;
1950     }
1951 
1952     const int crypt_connection_id = getcryptconnection_id(c, n_c.public_key);
1953 
1954     if (crypt_connection_id != -1) {
1955         Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1956 
1957         if (conn == nullptr) {
1958             return -1;
1959         }
1960 
1961         if (public_key_cmp(n_c.dht_public_key, conn->dht_public_key) != 0) {
1962             connection_kill(c, crypt_connection_id, userdata);
1963         } else {
1964             if (conn->status != CRYPTO_CONN_COOKIE_REQUESTING && conn->status != CRYPTO_CONN_HANDSHAKE_SENT) {
1965                 free(n_c.cookie);
1966                 return -1;
1967             }
1968 
1969             memcpy(conn->recv_nonce, n_c.recv_nonce, CRYPTO_NONCE_SIZE);
1970             memcpy(conn->peersessionpublic_key, n_c.peersessionpublic_key, CRYPTO_PUBLIC_KEY_SIZE);
1971             encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
1972 
1973             crypto_connection_add_source(c, crypt_connection_id, source);
1974 
1975             if (create_send_handshake(c, crypt_connection_id, n_c.cookie, n_c.dht_public_key) != 0) {
1976                 free(n_c.cookie);
1977                 return -1;
1978             }
1979 
1980             conn->status = CRYPTO_CONN_NOT_CONFIRMED;
1981             free(n_c.cookie);
1982             return 0;
1983         }
1984     }
1985 
1986     int ret = c->new_connection_callback(c->new_connection_callback_object, &n_c);
1987     free(n_c.cookie);
1988     return ret;
1989 }
1990 
1991 /* Accept a crypto connection.
1992  *
1993  * return -1 on failure.
1994  * return connection id on success.
1995  */
accept_crypto_connection(Net_Crypto * c,New_Connection * n_c)1996 int accept_crypto_connection(Net_Crypto *c, New_Connection *n_c)
1997 {
1998     if (getcryptconnection_id(c, n_c->public_key) != -1) {
1999         return -1;
2000     }
2001 
2002     const int crypt_connection_id = create_crypto_connection(c);
2003 
2004     if (crypt_connection_id == -1) {
2005         LOGGER_ERROR(c->log, "Could not create new crypto connection");
2006         return -1;
2007     }
2008 
2009     Crypto_Connection *conn = &c->crypto_connections[crypt_connection_id];
2010 
2011     if (n_c->cookie_length != COOKIE_LENGTH) {
2012         wipe_crypto_connection(c, crypt_connection_id);
2013         return -1;
2014     }
2015 
2016     pthread_mutex_lock(&c->tcp_mutex);
2017     const int connection_number_tcp = new_tcp_connection_to(c->tcp_c, n_c->dht_public_key, crypt_connection_id);
2018     pthread_mutex_unlock(&c->tcp_mutex);
2019 
2020     if (connection_number_tcp == -1) {
2021         wipe_crypto_connection(c, crypt_connection_id);
2022         return -1;
2023     }
2024 
2025     conn->connection_number_tcp = connection_number_tcp;
2026     memcpy(conn->public_key, n_c->public_key, CRYPTO_PUBLIC_KEY_SIZE);
2027     memcpy(conn->recv_nonce, n_c->recv_nonce, CRYPTO_NONCE_SIZE);
2028     memcpy(conn->peersessionpublic_key, n_c->peersessionpublic_key, CRYPTO_PUBLIC_KEY_SIZE);
2029     random_nonce(conn->sent_nonce);
2030     crypto_new_keypair(conn->sessionpublic_key, conn->sessionsecret_key);
2031     encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
2032     conn->status = CRYPTO_CONN_NOT_CONFIRMED;
2033 
2034     if (create_send_handshake(c, crypt_connection_id, n_c->cookie, n_c->dht_public_key) != 0) {
2035         pthread_mutex_lock(&c->tcp_mutex);
2036         kill_tcp_connection_to(c->tcp_c, conn->connection_number_tcp);
2037         pthread_mutex_unlock(&c->tcp_mutex);
2038         wipe_crypto_connection(c, crypt_connection_id);
2039         return -1;
2040     }
2041 
2042     memcpy(conn->dht_public_key, n_c->dht_public_key, CRYPTO_PUBLIC_KEY_SIZE);
2043     conn->packet_send_rate = CRYPTO_PACKET_MIN_RATE;
2044     conn->packet_send_rate_requested = CRYPTO_PACKET_MIN_RATE;
2045     conn->packets_left = CRYPTO_MIN_QUEUE_LENGTH;
2046     conn->rtt_time = DEFAULT_PING_CONNECTION;
2047     crypto_connection_add_source(c, crypt_connection_id, n_c->source);
2048     return crypt_connection_id;
2049 }
2050 
2051 /* Create a crypto connection.
2052  * If one to that real public key already exists, return it.
2053  *
2054  * return -1 on failure.
2055  * return connection id on success.
2056  */
new_crypto_connection(Net_Crypto * c,const uint8_t * real_public_key,const uint8_t * dht_public_key)2057 int new_crypto_connection(Net_Crypto *c, const uint8_t *real_public_key, const uint8_t *dht_public_key)
2058 {
2059     int crypt_connection_id = getcryptconnection_id(c, real_public_key);
2060 
2061     if (crypt_connection_id != -1) {
2062         return crypt_connection_id;
2063     }
2064 
2065     crypt_connection_id = create_crypto_connection(c);
2066 
2067     if (crypt_connection_id == -1) {
2068         return -1;
2069     }
2070 
2071     Crypto_Connection *conn = &c->crypto_connections[crypt_connection_id];
2072 
2073     pthread_mutex_lock(&c->tcp_mutex);
2074     const int connection_number_tcp = new_tcp_connection_to(c->tcp_c, dht_public_key, crypt_connection_id);
2075     pthread_mutex_unlock(&c->tcp_mutex);
2076 
2077     if (connection_number_tcp == -1) {
2078         wipe_crypto_connection(c, crypt_connection_id);
2079         return -1;
2080     }
2081 
2082     conn->connection_number_tcp = connection_number_tcp;
2083     memcpy(conn->public_key, real_public_key, CRYPTO_PUBLIC_KEY_SIZE);
2084     random_nonce(conn->sent_nonce);
2085     crypto_new_keypair(conn->sessionpublic_key, conn->sessionsecret_key);
2086     conn->status = CRYPTO_CONN_COOKIE_REQUESTING;
2087     conn->packet_send_rate = CRYPTO_PACKET_MIN_RATE;
2088     conn->packet_send_rate_requested = CRYPTO_PACKET_MIN_RATE;
2089     conn->packets_left = CRYPTO_MIN_QUEUE_LENGTH;
2090     conn->rtt_time = DEFAULT_PING_CONNECTION;
2091     memcpy(conn->dht_public_key, dht_public_key, CRYPTO_PUBLIC_KEY_SIZE);
2092 
2093     conn->cookie_request_number = random_u64();
2094     uint8_t cookie_request[COOKIE_REQUEST_LENGTH];
2095 
2096     if (create_cookie_request(c, cookie_request, conn->dht_public_key, conn->cookie_request_number,
2097                               conn->shared_key) != sizeof(cookie_request)
2098             || new_temp_packet(c, crypt_connection_id, cookie_request, sizeof(cookie_request)) != 0) {
2099         pthread_mutex_lock(&c->tcp_mutex);
2100         kill_tcp_connection_to(c->tcp_c, conn->connection_number_tcp);
2101         pthread_mutex_unlock(&c->tcp_mutex);
2102         wipe_crypto_connection(c, crypt_connection_id);
2103         return -1;
2104     }
2105 
2106     return crypt_connection_id;
2107 }
2108 
2109 /* Set the direct ip of the crypto connection.
2110  *
2111  * Connected is 0 if we are not sure we are connected to that person, 1 if we are sure.
2112  *
2113  * return -1 on failure.
2114  * return 0 on success.
2115  */
set_direct_ip_port(Net_Crypto * c,int crypt_connection_id,IP_Port ip_port,bool connected)2116 int set_direct_ip_port(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port, bool connected)
2117 {
2118     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2119 
2120     if (conn == nullptr) {
2121         return -1;
2122     }
2123 
2124     if (add_ip_port_connection(c, crypt_connection_id, ip_port) != 0) {
2125         return -1;
2126     }
2127 
2128     const uint64_t direct_lastrecv_time = connected ? mono_time_get(c->mono_time) : 0;
2129 
2130     if (net_family_is_ipv4(ip_port.ip.family)) {
2131         conn->direct_lastrecv_timev4 = direct_lastrecv_time;
2132     } else {
2133         conn->direct_lastrecv_timev6 = direct_lastrecv_time;
2134     }
2135 
2136     return 0;
2137 }
2138 
2139 
tcp_data_callback(void * object,int crypt_connection_id,const uint8_t * data,uint16_t length,void * userdata)2140 static int tcp_data_callback(void *object, int crypt_connection_id, const uint8_t *data, uint16_t length,
2141                              void *userdata)
2142 {
2143     Net_Crypto *c = (Net_Crypto *)object;
2144 
2145     if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
2146         return -1;
2147     }
2148 
2149     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2150 
2151     if (conn == nullptr) {
2152         return -1;
2153     }
2154 
2155     if (data[0] == NET_PACKET_COOKIE_REQUEST) {
2156         return tcp_handle_cookie_request(c, conn->connection_number_tcp, data, length);
2157     }
2158 
2159     // This unlocks the mutex that at this point is locked by do_tcp before
2160     // calling do_tcp_connections.
2161     pthread_mutex_unlock(&c->tcp_mutex);
2162     int ret = handle_packet_connection(c, crypt_connection_id, data, length, 0, userdata);
2163     pthread_mutex_lock(&c->tcp_mutex);
2164 
2165     if (ret != 0) {
2166         return -1;
2167     }
2168 
2169     // TODO(irungentoo): detect and kill bad TCP connections.
2170     return 0;
2171 }
2172 
tcp_oob_callback(void * object,const uint8_t * public_key,unsigned int tcp_connections_number,const uint8_t * data,uint16_t length,void * userdata)2173 static int tcp_oob_callback(void *object, const uint8_t *public_key, unsigned int tcp_connections_number,
2174                             const uint8_t *data, uint16_t length, void *userdata)
2175 {
2176     Net_Crypto *c = (Net_Crypto *)object;
2177 
2178     if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
2179         return -1;
2180     }
2181 
2182     if (data[0] == NET_PACKET_COOKIE_REQUEST) {
2183         return tcp_oob_handle_cookie_request(c, tcp_connections_number, public_key, data, length);
2184     }
2185 
2186     if (data[0] == NET_PACKET_CRYPTO_HS) {
2187         IP_Port source;
2188         source.port = 0;
2189         source.ip.family = net_family_tcp_family;
2190         source.ip.ip.v6.uint32[0] = tcp_connections_number;
2191 
2192         if (handle_new_connection_handshake(c, source, data, length, userdata) != 0) {
2193             return -1;
2194         }
2195 
2196         return 0;
2197     }
2198 
2199     return -1;
2200 }
2201 
2202 /* Add a tcp relay, associating it to a crypt_connection_id.
2203  *
2204  * return 0 if it was added.
2205  * return -1 if it wasn't.
2206  */
add_tcp_relay_peer(Net_Crypto * c,int crypt_connection_id,IP_Port ip_port,const uint8_t * public_key)2207 int add_tcp_relay_peer(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port, const uint8_t *public_key)
2208 {
2209     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2210 
2211     if (conn == nullptr) {
2212         return -1;
2213     }
2214 
2215     pthread_mutex_lock(&c->tcp_mutex);
2216     int ret = add_tcp_relay_connection(c->tcp_c, conn->connection_number_tcp, ip_port, public_key);
2217     pthread_mutex_unlock(&c->tcp_mutex);
2218     return ret;
2219 }
2220 
2221 /* Add a tcp relay to the array.
2222  *
2223  * return 0 if it was added.
2224  * return -1 if it wasn't.
2225  */
add_tcp_relay(Net_Crypto * c,IP_Port ip_port,const uint8_t * public_key)2226 int add_tcp_relay(Net_Crypto *c, IP_Port ip_port, const uint8_t *public_key)
2227 {
2228     pthread_mutex_lock(&c->tcp_mutex);
2229     int ret = add_tcp_relay_global(c->tcp_c, ip_port, public_key);
2230     pthread_mutex_unlock(&c->tcp_mutex);
2231     return ret;
2232 }
2233 
2234 /* Return a random TCP connection number for use in send_tcp_onion_request.
2235  *
2236  * TODO(irungentoo): This number is just the index of an array that the elements can
2237  * change without warning.
2238  *
2239  * return TCP connection number on success.
2240  * return -1 on failure.
2241  */
get_random_tcp_con_number(Net_Crypto * c)2242 int get_random_tcp_con_number(Net_Crypto *c)
2243 {
2244     pthread_mutex_lock(&c->tcp_mutex);
2245     int ret = get_random_tcp_onion_conn_number(c->tcp_c);
2246     pthread_mutex_unlock(&c->tcp_mutex);
2247 
2248     return ret;
2249 }
2250 
2251 /* Send an onion packet via the TCP relay corresponding to tcp_connections_number.
2252  *
2253  * return 0 on success.
2254  * return -1 on failure.
2255  */
send_tcp_onion_request(Net_Crypto * c,unsigned int tcp_connections_number,const uint8_t * data,uint16_t length)2256 int send_tcp_onion_request(Net_Crypto *c, unsigned int tcp_connections_number, const uint8_t *data, uint16_t length)
2257 {
2258     pthread_mutex_lock(&c->tcp_mutex);
2259     int ret = tcp_send_onion_request(c->tcp_c, tcp_connections_number, data, length);
2260     pthread_mutex_unlock(&c->tcp_mutex);
2261 
2262     return ret;
2263 }
2264 
2265 /* Copy a maximum of num TCP relays we are connected to to tcp_relays.
2266  * NOTE that the family of the copied ip ports will be set to TCP_INET or TCP_INET6.
2267  *
2268  * return number of relays copied to tcp_relays on success.
2269  * return 0 on failure.
2270  */
copy_connected_tcp_relays(Net_Crypto * c,Node_format * tcp_relays,uint16_t num)2271 unsigned int copy_connected_tcp_relays(Net_Crypto *c, Node_format *tcp_relays, uint16_t num)
2272 {
2273     if (num == 0) {
2274         return 0;
2275     }
2276 
2277     pthread_mutex_lock(&c->tcp_mutex);
2278     unsigned int ret = tcp_copy_connected_relays(c->tcp_c, tcp_relays, num);
2279     pthread_mutex_unlock(&c->tcp_mutex);
2280 
2281     return ret;
2282 }
2283 
do_tcp(Net_Crypto * c,void * userdata)2284 static void do_tcp(Net_Crypto *c, void *userdata)
2285 {
2286     pthread_mutex_lock(&c->tcp_mutex);
2287     do_tcp_connections(c->log, c->tcp_c, userdata);
2288     pthread_mutex_unlock(&c->tcp_mutex);
2289 
2290     for (uint32_t i = 0; i < c->crypto_connections_length; ++i) {
2291         Crypto_Connection *conn = get_crypto_connection(c, i);
2292 
2293         if (conn == nullptr) {
2294             continue;
2295         }
2296 
2297         if (conn->status != CRYPTO_CONN_ESTABLISHED) {
2298             continue;
2299         }
2300 
2301         bool direct_connected = false;
2302 
2303         if (!crypto_connection_status(c, i, &direct_connected, nullptr)) {
2304             continue;
2305         }
2306 
2307         pthread_mutex_lock(&c->tcp_mutex);
2308         set_tcp_connection_to_status(c->tcp_c, conn->connection_number_tcp, !direct_connected);
2309         pthread_mutex_unlock(&c->tcp_mutex);
2310     }
2311 }
2312 
2313 /* Set function to be called when connection with crypt_connection_id goes connects/disconnects.
2314  *
2315  * The set function should return -1 on failure and 0 on success.
2316  * Note that if this function is set, the connection will clear itself on disconnect.
2317  * Object and id will be passed to this function untouched.
2318  * status is 1 if the connection is going online, 0 if it is going offline.
2319  *
2320  * return -1 on failure.
2321  * return 0 on success.
2322  */
connection_status_handler(const Net_Crypto * c,int crypt_connection_id,connection_status_cb * connection_status_callback,void * object,int id)2323 int connection_status_handler(const Net_Crypto *c, int crypt_connection_id,
2324                               connection_status_cb *connection_status_callback, void *object, int id)
2325 {
2326     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2327 
2328     if (conn == nullptr) {
2329         return -1;
2330     }
2331 
2332     conn->connection_status_callback = connection_status_callback;
2333     conn->connection_status_callback_object = object;
2334     conn->connection_status_callback_id = id;
2335     return 0;
2336 }
2337 
2338 /* Set function to be called when connection with crypt_connection_id receives a data packet of length.
2339  *
2340  * The set function should return -1 on failure and 0 on success.
2341  * Object and id will be passed to this function untouched.
2342  *
2343  * return -1 on failure.
2344  * return 0 on success.
2345  */
connection_data_handler(const Net_Crypto * c,int crypt_connection_id,connection_data_cb * connection_data_callback,void * object,int id)2346 int connection_data_handler(const Net_Crypto *c, int crypt_connection_id,
2347                             connection_data_cb *connection_data_callback, void *object, int id)
2348 {
2349     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2350 
2351     if (conn == nullptr) {
2352         return -1;
2353     }
2354 
2355     conn->connection_data_callback = connection_data_callback;
2356     conn->connection_data_callback_object = object;
2357     conn->connection_data_callback_id = id;
2358     return 0;
2359 }
2360 
2361 /* Set function to be called when connection with crypt_connection_id receives a lossy data packet of length.
2362  *
2363  * The set function should return -1 on failure and 0 on success.
2364  * Object and id will be passed to this function untouched.
2365  *
2366  * return -1 on failure.
2367  * return 0 on success.
2368  */
connection_lossy_data_handler(Net_Crypto * c,int crypt_connection_id,connection_lossy_data_cb * connection_lossy_data_callback,void * object,int id)2369 int connection_lossy_data_handler(Net_Crypto *c, int crypt_connection_id,
2370                                   connection_lossy_data_cb *connection_lossy_data_callback,
2371                                   void *object, int id)
2372 {
2373     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2374 
2375     if (conn == nullptr) {
2376         return -1;
2377     }
2378 
2379     conn->connection_lossy_data_callback = connection_lossy_data_callback;
2380     conn->connection_lossy_data_callback_object = object;
2381     conn->connection_lossy_data_callback_id = id;
2382     return 0;
2383 }
2384 
2385 
2386 /* Set the function for this friend that will be callbacked with object and number if
2387  * the friend sends us a different dht public key than we have associated to him.
2388  *
2389  * If this function is called, the connection should be recreated with the new public key.
2390  *
2391  * object and number will be passed as argument to this function.
2392  *
2393  * return -1 on failure.
2394  * return 0 on success.
2395  */
nc_dht_pk_callback(Net_Crypto * c,int crypt_connection_id,dht_pk_cb * function,void * object,uint32_t number)2396 int nc_dht_pk_callback(Net_Crypto *c, int crypt_connection_id, dht_pk_cb *function, void *object, uint32_t number)
2397 {
2398     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2399 
2400     if (conn == nullptr) {
2401         return -1;
2402     }
2403 
2404     conn->dht_pk_callback = function;
2405     conn->dht_pk_callback_object = object;
2406     conn->dht_pk_callback_number = number;
2407     return 0;
2408 }
2409 
2410 /* Get the crypto connection id from the ip_port.
2411  *
2412  * return -1 on failure.
2413  * return connection id on success.
2414  */
crypto_id_ip_port(const Net_Crypto * c,IP_Port ip_port)2415 static int crypto_id_ip_port(const Net_Crypto *c, IP_Port ip_port)
2416 {
2417     return bs_list_find(&c->ip_port_list, (uint8_t *)&ip_port);
2418 }
2419 
2420 #define CRYPTO_MIN_PACKET_SIZE (1 + sizeof(uint16_t) + CRYPTO_MAC_SIZE)
2421 
2422 /* Handle raw UDP packets coming directly from the socket.
2423  *
2424  * Handles:
2425  * Cookie response packets.
2426  * Crypto handshake packets.
2427  * Crypto data packets.
2428  *
2429  */
udp_handle_packet(void * object,IP_Port source,const uint8_t * packet,uint16_t length,void * userdata)2430 static int udp_handle_packet(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata)
2431 {
2432     Net_Crypto *c = (Net_Crypto *)object;
2433 
2434     if (length <= CRYPTO_MIN_PACKET_SIZE || length > MAX_CRYPTO_PACKET_SIZE) {
2435         return 1;
2436     }
2437 
2438     const int crypt_connection_id = crypto_id_ip_port(c, source);
2439 
2440     if (crypt_connection_id == -1) {
2441         if (packet[0] != NET_PACKET_CRYPTO_HS) {
2442             return 1;
2443         }
2444 
2445         if (handle_new_connection_handshake(c, source, packet, length, userdata) != 0) {
2446             return 1;
2447         }
2448 
2449         return 0;
2450     }
2451 
2452     if (handle_packet_connection(c, crypt_connection_id, packet, length, 1, userdata) != 0) {
2453         return 1;
2454     }
2455 
2456     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2457 
2458     if (conn == nullptr) {
2459         return -1;
2460     }
2461 
2462     pthread_mutex_lock(conn->mutex);
2463 
2464     if (net_family_is_ipv4(source.ip.family)) {
2465         conn->direct_lastrecv_timev4 = mono_time_get(c->mono_time);
2466     } else {
2467         conn->direct_lastrecv_timev6 = mono_time_get(c->mono_time);
2468     }
2469 
2470     pthread_mutex_unlock(conn->mutex);
2471     return 0;
2472 }
2473 
2474 /* The dT for the average packet receiving rate calculations.
2475  * Also used as the */
2476 #define PACKET_COUNTER_AVERAGE_INTERVAL 50
2477 
2478 /* Ratio of recv queue size / recv packet rate (in seconds) times
2479  * the number of ms between request packets to send at that ratio
2480  */
2481 #define REQUEST_PACKETS_COMPARE_CONSTANT (0.125 * 100.0)
2482 
2483 /* Timeout for increasing speed after congestion event (in ms). */
2484 #define CONGESTION_EVENT_TIMEOUT 1000
2485 
2486 /* If the send queue is SEND_QUEUE_RATIO times larger than the
2487  * calculated link speed the packet send speed will be reduced
2488  * by a value depending on this number.
2489  */
2490 #define SEND_QUEUE_RATIO 2.0
2491 
send_crypto_packets(Net_Crypto * c)2492 static void send_crypto_packets(Net_Crypto *c)
2493 {
2494     const uint64_t temp_time = current_time_monotonic(c->mono_time);
2495     double total_send_rate = 0;
2496     uint32_t peak_request_packet_interval = -1;
2497 
2498     for (uint32_t i = 0; i < c->crypto_connections_length; ++i) {
2499         Crypto_Connection *conn = get_crypto_connection(c, i);
2500 
2501         if (conn == nullptr) {
2502             continue;
2503         }
2504 
2505         if ((CRYPTO_SEND_PACKET_INTERVAL + conn->temp_packet_sent_time) < temp_time) {
2506             send_temp_packet(c, i);
2507         }
2508 
2509         if ((conn->status == CRYPTO_CONN_NOT_CONFIRMED || conn->status == CRYPTO_CONN_ESTABLISHED)
2510                 && (CRYPTO_SEND_PACKET_INTERVAL + conn->last_request_packet_sent) < temp_time) {
2511             if (send_request_packet(c, i) == 0) {
2512                 conn->last_request_packet_sent = temp_time;
2513             }
2514         }
2515 
2516         if (conn->status == CRYPTO_CONN_ESTABLISHED) {
2517             if (conn->packet_recv_rate > CRYPTO_PACKET_MIN_RATE) {
2518                 double request_packet_interval = (REQUEST_PACKETS_COMPARE_CONSTANT / ((num_packets_array(
2519                                                       &conn->recv_array) + 1.0) / (conn->packet_recv_rate + 1.0)));
2520 
2521                 double request_packet_interval2 = ((CRYPTO_PACKET_MIN_RATE / conn->packet_recv_rate) *
2522                                                    (double)CRYPTO_SEND_PACKET_INTERVAL) + (double)PACKET_COUNTER_AVERAGE_INTERVAL;
2523 
2524                 if (request_packet_interval2 < request_packet_interval) {
2525                     request_packet_interval = request_packet_interval2;
2526                 }
2527 
2528                 if (request_packet_interval < PACKET_COUNTER_AVERAGE_INTERVAL) {
2529                     request_packet_interval = PACKET_COUNTER_AVERAGE_INTERVAL;
2530                 }
2531 
2532                 if (request_packet_interval > CRYPTO_SEND_PACKET_INTERVAL) {
2533                     request_packet_interval = CRYPTO_SEND_PACKET_INTERVAL;
2534                 }
2535 
2536                 if (temp_time - conn->last_request_packet_sent > (uint64_t)request_packet_interval) {
2537                     if (send_request_packet(c, i) == 0) {
2538                         conn->last_request_packet_sent = temp_time;
2539                     }
2540                 }
2541 
2542                 if (request_packet_interval < peak_request_packet_interval) {
2543                     peak_request_packet_interval = request_packet_interval;
2544                 }
2545             }
2546 
2547             if ((PACKET_COUNTER_AVERAGE_INTERVAL + conn->packet_counter_set) < temp_time) {
2548                 const double dt = temp_time - conn->packet_counter_set;
2549 
2550                 conn->packet_recv_rate = (double)conn->packet_counter / (dt / 1000.0);
2551                 conn->packet_counter = 0;
2552                 conn->packet_counter_set = temp_time;
2553 
2554                 uint32_t packets_sent = conn->packets_sent;
2555                 conn->packets_sent = 0;
2556 
2557                 uint32_t packets_resent = conn->packets_resent;
2558                 conn->packets_resent = 0;
2559 
2560                 /* conjestion control
2561                  *  calculate a new value of conn->packet_send_rate based on some data
2562                  */
2563 
2564                 unsigned int pos = conn->last_sendqueue_counter % CONGESTION_QUEUE_ARRAY_SIZE;
2565                 conn->last_sendqueue_size[pos] = num_packets_array(&conn->send_array);
2566 
2567                 long signed int sum = 0;
2568                 sum = (long signed int)conn->last_sendqueue_size[pos] -
2569                       (long signed int)conn->last_sendqueue_size[(pos + 1) % CONGESTION_QUEUE_ARRAY_SIZE];
2570 
2571                 unsigned int n_p_pos = conn->last_sendqueue_counter % CONGESTION_LAST_SENT_ARRAY_SIZE;
2572                 conn->last_num_packets_sent[n_p_pos] = packets_sent;
2573                 conn->last_num_packets_resent[n_p_pos] = packets_resent;
2574 
2575                 conn->last_sendqueue_counter = (conn->last_sendqueue_counter + 1) %
2576                                                (CONGESTION_QUEUE_ARRAY_SIZE * CONGESTION_LAST_SENT_ARRAY_SIZE);
2577 
2578                 bool direct_connected = 0;
2579                 /* return value can be ignored since the `if` above ensures the connection is established */
2580                 crypto_connection_status(c, i, &direct_connected, nullptr);
2581 
2582                 /* When switching from TCP to UDP, don't change the packet send rate for CONGESTION_EVENT_TIMEOUT ms. */
2583                 if (!(direct_connected && conn->last_tcp_sent + CONGESTION_EVENT_TIMEOUT > temp_time)) {
2584                     long signed int total_sent = 0;
2585                     long signed int total_resent = 0;
2586 
2587                     // TODO(irungentoo): use real delay
2588                     unsigned int delay = (unsigned int)((conn->rtt_time / PACKET_COUNTER_AVERAGE_INTERVAL) + 0.5);
2589                     unsigned int packets_set_rem_array = (CONGESTION_LAST_SENT_ARRAY_SIZE - CONGESTION_QUEUE_ARRAY_SIZE);
2590 
2591                     if (delay > packets_set_rem_array) {
2592                         delay = packets_set_rem_array;
2593                     }
2594 
2595                     for (unsigned j = 0; j < CONGESTION_QUEUE_ARRAY_SIZE; ++j) {
2596                         unsigned int ind = (j + (packets_set_rem_array  - delay) + n_p_pos) % CONGESTION_LAST_SENT_ARRAY_SIZE;
2597                         total_sent += conn->last_num_packets_sent[ind];
2598                         total_resent += conn->last_num_packets_resent[ind];
2599                     }
2600 
2601                     if (sum > 0) {
2602                         total_sent -= sum;
2603                     } else {
2604                         if (total_resent > -sum) {
2605                             total_resent = -sum;
2606                         }
2607                     }
2608 
2609                     /* if queue is too big only allow resending packets. */
2610                     uint32_t npackets = num_packets_array(&conn->send_array);
2611                     double min_speed = 1000.0 * (((double)(total_sent)) / ((double)(CONGESTION_QUEUE_ARRAY_SIZE) *
2612                                                  PACKET_COUNTER_AVERAGE_INTERVAL));
2613 
2614                     double min_speed_request = 1000.0 * (((double)(total_sent + total_resent)) / ((double)(
2615                             CONGESTION_QUEUE_ARRAY_SIZE) * PACKET_COUNTER_AVERAGE_INTERVAL));
2616 
2617                     if (min_speed < CRYPTO_PACKET_MIN_RATE) {
2618                         min_speed = CRYPTO_PACKET_MIN_RATE;
2619                     }
2620 
2621                     double send_array_ratio = (((double)npackets) / min_speed);
2622 
2623                     // TODO(irungentoo): Improve formula?
2624                     if (send_array_ratio > SEND_QUEUE_RATIO && CRYPTO_MIN_QUEUE_LENGTH < npackets) {
2625                         conn->packet_send_rate = min_speed * (1.0 / (send_array_ratio / SEND_QUEUE_RATIO));
2626                     } else if (conn->last_congestion_event + CONGESTION_EVENT_TIMEOUT < temp_time) {
2627                         conn->packet_send_rate = min_speed * 1.2;
2628                     } else {
2629                         conn->packet_send_rate = min_speed * 0.9;
2630                     }
2631 
2632                     conn->packet_send_rate_requested = min_speed_request * 1.2;
2633 
2634                     if (conn->packet_send_rate < CRYPTO_PACKET_MIN_RATE) {
2635                         conn->packet_send_rate = CRYPTO_PACKET_MIN_RATE;
2636                     }
2637 
2638                     if (conn->packet_send_rate_requested < conn->packet_send_rate) {
2639                         conn->packet_send_rate_requested = conn->packet_send_rate;
2640                     }
2641                 }
2642             }
2643 
2644             if (conn->last_packets_left_set == 0 || conn->last_packets_left_requested_set == 0) {
2645                 conn->last_packets_left_requested_set = temp_time;
2646                 conn->last_packets_left_set = temp_time;
2647                 conn->packets_left_requested = CRYPTO_MIN_QUEUE_LENGTH;
2648                 conn->packets_left = CRYPTO_MIN_QUEUE_LENGTH;
2649             } else {
2650                 if (((uint64_t)((1000.0 / conn->packet_send_rate) + 0.5) + conn->last_packets_left_set) <= temp_time) {
2651                     double n_packets = conn->packet_send_rate * (((double)(temp_time - conn->last_packets_left_set)) / 1000.0);
2652                     n_packets += conn->last_packets_left_rem;
2653 
2654                     uint32_t num_packets = n_packets;
2655                     double rem = n_packets - (double)num_packets;
2656 
2657                     if (conn->packets_left > num_packets * 4 + CRYPTO_MIN_QUEUE_LENGTH) {
2658                         conn->packets_left = num_packets * 4 + CRYPTO_MIN_QUEUE_LENGTH;
2659                     } else {
2660                         conn->packets_left += num_packets;
2661                     }
2662 
2663                     conn->last_packets_left_set = temp_time;
2664                     conn->last_packets_left_rem = rem;
2665                 }
2666 
2667                 if (((uint64_t)((1000.0 / conn->packet_send_rate_requested) + 0.5) + conn->last_packets_left_requested_set) <=
2668                         temp_time) {
2669                     double n_packets = conn->packet_send_rate_requested * (((double)(temp_time - conn->last_packets_left_requested_set)) /
2670                                        1000.0);
2671                     n_packets += conn->last_packets_left_requested_rem;
2672 
2673                     uint32_t num_packets = n_packets;
2674                     double rem = n_packets - (double)num_packets;
2675                     conn->packets_left_requested = num_packets;
2676 
2677                     conn->last_packets_left_requested_set = temp_time;
2678                     conn->last_packets_left_requested_rem = rem;
2679                 }
2680 
2681                 if (conn->packets_left > conn->packets_left_requested) {
2682                     conn->packets_left_requested = conn->packets_left;
2683                 }
2684             }
2685 
2686             int ret = send_requested_packets(c, i, conn->packets_left_requested);
2687 
2688             if (ret != -1) {
2689                 conn->packets_left_requested -= ret;
2690                 conn->packets_resent += ret;
2691 
2692                 if ((unsigned int)ret < conn->packets_left) {
2693                     conn->packets_left -= ret;
2694                 } else {
2695                     conn->last_congestion_event = temp_time;
2696                     conn->packets_left = 0;
2697                 }
2698             }
2699 
2700             if (conn->packet_send_rate > CRYPTO_PACKET_MIN_RATE * 1.5) {
2701                 total_send_rate += conn->packet_send_rate;
2702             }
2703         }
2704     }
2705 
2706     c->current_sleep_time = -1;
2707     uint32_t sleep_time = peak_request_packet_interval;
2708 
2709     if (c->current_sleep_time > sleep_time) {
2710         c->current_sleep_time = sleep_time;
2711     }
2712 
2713     if (total_send_rate > CRYPTO_PACKET_MIN_RATE) {
2714         sleep_time = (1000.0 / total_send_rate);
2715 
2716         if (c->current_sleep_time > sleep_time) {
2717             c->current_sleep_time = sleep_time + 1;
2718         }
2719     }
2720 
2721     sleep_time = CRYPTO_SEND_PACKET_INTERVAL;
2722 
2723     if (c->current_sleep_time > sleep_time) {
2724         c->current_sleep_time = sleep_time;
2725     }
2726 }
2727 
2728 /* Return 1 if max speed was reached for this connection (no more data can be physically through the pipe).
2729  * Return 0 if it wasn't reached.
2730  */
max_speed_reached(Net_Crypto * c,int crypt_connection_id)2731 bool max_speed_reached(Net_Crypto *c, int crypt_connection_id)
2732 {
2733     return reset_max_speed_reached(c, crypt_connection_id) != 0;
2734 }
2735 
2736 /* returns the number of packet slots left in the sendbuffer.
2737  * return 0 if failure.
2738  */
crypto_num_free_sendqueue_slots(const Net_Crypto * c,int crypt_connection_id)2739 uint32_t crypto_num_free_sendqueue_slots(const Net_Crypto *c, int crypt_connection_id)
2740 {
2741     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2742 
2743     if (conn == nullptr) {
2744         return 0;
2745     }
2746 
2747     uint32_t max_packets = CRYPTO_PACKET_BUFFER_SIZE - num_packets_array(&conn->send_array);
2748 
2749     if (conn->packets_left < max_packets) {
2750         return conn->packets_left;
2751     }
2752 
2753     return max_packets;
2754 }
2755 
2756 /* Sends a lossless cryptopacket.
2757  *
2758  * return -1 if data could not be put in packet queue.
2759  * return positive packet number if data was put into the queue.
2760  *
2761  * The first byte of data must in the PACKET_ID_RANGE_LOSSLESS.
2762  *
2763  * congestion_control: should congestion control apply to this packet?
2764  */
write_cryptpacket(Net_Crypto * c,int crypt_connection_id,const uint8_t * data,uint16_t length,uint8_t congestion_control)2765 int64_t write_cryptpacket(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length,
2766                           uint8_t congestion_control)
2767 {
2768     if (length == 0) {
2769         return -1;
2770     }
2771 
2772     if (data[0] < PACKET_ID_RANGE_LOSSLESS_START || data[0] > PACKET_ID_RANGE_LOSSLESS_END) {
2773         return -1;
2774     }
2775 
2776     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2777 
2778     if (conn == nullptr) {
2779         return -1;
2780     }
2781 
2782     if (conn->status != CRYPTO_CONN_ESTABLISHED) {
2783         return -1;
2784     }
2785 
2786     if (congestion_control && conn->packets_left == 0) {
2787         return -1;
2788     }
2789 
2790     int64_t ret = send_lossless_packet(c, crypt_connection_id, data, length, congestion_control);
2791 
2792     if (ret == -1) {
2793         return -1;
2794     }
2795 
2796     if (congestion_control) {
2797         --conn->packets_left;
2798         --conn->packets_left_requested;
2799         ++conn->packets_sent;
2800     }
2801 
2802     return ret;
2803 }
2804 
2805 /* Check if packet_number was received by the other side.
2806  *
2807  * packet_number must be a valid packet number of a packet sent on this connection.
2808  *
2809  * return -1 on failure.
2810  * return 0 on success.
2811  *
2812  * Note: The condition `buffer_end - buffer_start < packet_number - buffer_start` is
2813  * a trick which handles situations `buffer_end >= buffer_start` and
2814  * `buffer_end < buffer_start` (when buffer_end overflowed) both correctly.
2815  *
2816  * It CANNOT be simplified to `packet_number < buffer_start`, as it will fail
2817  * when `buffer_end < buffer_start`.
2818  */
cryptpacket_received(Net_Crypto * c,int crypt_connection_id,uint32_t packet_number)2819 int cryptpacket_received(Net_Crypto *c, int crypt_connection_id, uint32_t packet_number)
2820 {
2821     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2822 
2823     if (conn == nullptr) {
2824         return -1;
2825     }
2826 
2827     uint32_t num = num_packets_array(&conn->send_array);
2828     uint32_t num1 = packet_number - conn->send_array.buffer_start;
2829 
2830     if (num >= num1) {
2831         return -1;
2832     }
2833 
2834     return 0;
2835 }
2836 
2837 /* Sends a lossy cryptopacket.
2838  *
2839  * return -1 on failure.
2840  * return 0 on success.
2841  *
2842  * The first byte of data must in the PACKET_ID_RANGE_LOSSY.
2843  */
send_lossy_cryptpacket(Net_Crypto * c,int crypt_connection_id,const uint8_t * data,uint16_t length)2844 int send_lossy_cryptpacket(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length)
2845 {
2846     if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
2847         return -1;
2848     }
2849 
2850     if (data[0] < PACKET_ID_RANGE_LOSSY_START || data[0] > PACKET_ID_RANGE_LOSSY_END) {
2851         return -1;
2852     }
2853 
2854     pthread_mutex_lock(&c->connections_mutex);
2855     ++c->connection_use_counter;
2856     pthread_mutex_unlock(&c->connections_mutex);
2857 
2858     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2859 
2860     int ret = -1;
2861 
2862     if (conn) {
2863         pthread_mutex_lock(conn->mutex);
2864         uint32_t buffer_start = conn->recv_array.buffer_start;
2865         uint32_t buffer_end = conn->send_array.buffer_end;
2866         pthread_mutex_unlock(conn->mutex);
2867         ret = send_data_packet_helper(c, crypt_connection_id, buffer_start, buffer_end, data, length);
2868     }
2869 
2870     pthread_mutex_lock(&c->connections_mutex);
2871     --c->connection_use_counter;
2872     pthread_mutex_unlock(&c->connections_mutex);
2873 
2874     return ret;
2875 }
2876 
2877 /* Kill a crypto connection.
2878  *
2879  * return -1 on failure.
2880  * return 0 on success.
2881  */
crypto_kill(Net_Crypto * c,int crypt_connection_id)2882 int crypto_kill(Net_Crypto *c, int crypt_connection_id)
2883 {
2884     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2885 
2886     int ret = -1;
2887 
2888     if (conn) {
2889         if (conn->status == CRYPTO_CONN_ESTABLISHED) {
2890             send_kill_packet(c, crypt_connection_id);
2891         }
2892 
2893         pthread_mutex_lock(&c->tcp_mutex);
2894         kill_tcp_connection_to(c->tcp_c, conn->connection_number_tcp);
2895         pthread_mutex_unlock(&c->tcp_mutex);
2896 
2897         bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv4, crypt_connection_id);
2898         bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv6, crypt_connection_id);
2899         clear_temp_packet(c, crypt_connection_id);
2900         clear_buffer(&conn->send_array);
2901         clear_buffer(&conn->recv_array);
2902         ret = wipe_crypto_connection(c, crypt_connection_id);
2903     }
2904 
2905     return ret;
2906 }
2907 
crypto_connection_status(const Net_Crypto * c,int crypt_connection_id,bool * direct_connected,unsigned int * online_tcp_relays)2908 bool crypto_connection_status(const Net_Crypto *c, int crypt_connection_id, bool *direct_connected,
2909                               unsigned int *online_tcp_relays)
2910 {
2911     Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2912 
2913     if (conn == nullptr) {
2914         return false;
2915     }
2916 
2917     if (direct_connected) {
2918         *direct_connected = 0;
2919 
2920         const uint64_t current_time = mono_time_get(c->mono_time);
2921 
2922         if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev4) > current_time) {
2923             *direct_connected = 1;
2924         } else if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev6) > current_time) {
2925             *direct_connected = 1;
2926         }
2927     }
2928 
2929     if (online_tcp_relays) {
2930         *online_tcp_relays = tcp_connection_to_online_tcp_relays(c->tcp_c, conn->connection_number_tcp);
2931     }
2932 
2933     return true;
2934 }
2935 
new_keys(Net_Crypto * c)2936 void new_keys(Net_Crypto *c)
2937 {
2938     crypto_new_keypair(c->self_public_key, c->self_secret_key);
2939 }
2940 
2941 /* Save the public and private keys to the keys array.
2942  * Length must be CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_SECRET_KEY_SIZE.
2943  *
2944  * TODO(irungentoo): Save only secret key.
2945  */
save_keys(const Net_Crypto * c,uint8_t * keys)2946 void save_keys(const Net_Crypto *c, uint8_t *keys)
2947 {
2948     memcpy(keys, c->self_public_key, CRYPTO_PUBLIC_KEY_SIZE);
2949     memcpy(keys + CRYPTO_PUBLIC_KEY_SIZE, c->self_secret_key, CRYPTO_SECRET_KEY_SIZE);
2950 }
2951 
2952 /* Load the secret key.
2953  * Length must be CRYPTO_SECRET_KEY_SIZE.
2954  */
load_secret_key(Net_Crypto * c,const uint8_t * sk)2955 void load_secret_key(Net_Crypto *c, const uint8_t *sk)
2956 {
2957     memcpy(c->self_secret_key, sk, CRYPTO_SECRET_KEY_SIZE);
2958     crypto_derive_public_key(c->self_public_key, c->self_secret_key);
2959 }
2960 
2961 /* Run this to (re)initialize net_crypto.
2962  * Sets all the global connection variables to their default values.
2963  */
new_net_crypto(const Logger * log,Mono_Time * mono_time,DHT * dht,TCP_Proxy_Info * proxy_info)2964 Net_Crypto *new_net_crypto(const Logger *log, Mono_Time *mono_time, DHT *dht, TCP_Proxy_Info *proxy_info)
2965 {
2966     if (dht == nullptr) {
2967         return nullptr;
2968     }
2969 
2970     Net_Crypto *temp = (Net_Crypto *)calloc(1, sizeof(Net_Crypto));
2971 
2972     if (temp == nullptr) {
2973         return nullptr;
2974     }
2975 
2976     temp->log = log;
2977     temp->mono_time = mono_time;
2978 
2979     temp->tcp_c = new_tcp_connections(mono_time, dht_get_self_secret_key(dht), proxy_info);
2980 
2981     if (temp->tcp_c == nullptr) {
2982         free(temp);
2983         return nullptr;
2984     }
2985 
2986     set_packet_tcp_connection_callback(temp->tcp_c, &tcp_data_callback, temp);
2987     set_oob_packet_tcp_connection_callback(temp->tcp_c, &tcp_oob_callback, temp);
2988 
2989     if (create_recursive_mutex(&temp->tcp_mutex) != 0 ||
2990             pthread_mutex_init(&temp->connections_mutex, nullptr) != 0) {
2991         kill_tcp_connections(temp->tcp_c);
2992         free(temp);
2993         return nullptr;
2994     }
2995 
2996     temp->dht = dht;
2997 
2998     new_keys(temp);
2999     new_symmetric_key(temp->secret_symmetric_key);
3000 
3001     temp->current_sleep_time = CRYPTO_SEND_PACKET_INTERVAL;
3002 
3003     networking_registerhandler(dht_get_net(dht), NET_PACKET_COOKIE_REQUEST, &udp_handle_cookie_request, temp);
3004     networking_registerhandler(dht_get_net(dht), NET_PACKET_COOKIE_RESPONSE, &udp_handle_packet, temp);
3005     networking_registerhandler(dht_get_net(dht), NET_PACKET_CRYPTO_HS, &udp_handle_packet, temp);
3006     networking_registerhandler(dht_get_net(dht), NET_PACKET_CRYPTO_DATA, &udp_handle_packet, temp);
3007 
3008     bs_list_init(&temp->ip_port_list, sizeof(IP_Port), 8);
3009 
3010     return temp;
3011 }
3012 
kill_timedout(Net_Crypto * c,void * userdata)3013 static void kill_timedout(Net_Crypto *c, void *userdata)
3014 {
3015     for (uint32_t i = 0; i < c->crypto_connections_length; ++i) {
3016         Crypto_Connection *conn = get_crypto_connection(c, i);
3017 
3018         if (conn == nullptr) {
3019             continue;
3020         }
3021 
3022         if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING || conn->status == CRYPTO_CONN_HANDSHAKE_SENT
3023                 || conn->status == CRYPTO_CONN_NOT_CONFIRMED) {
3024             if (conn->temp_packet_num_sent < MAX_NUM_SENDPACKET_TRIES) {
3025                 continue;
3026             }
3027 
3028             connection_kill(c, i, userdata);
3029         }
3030 
3031 #if 0
3032 
3033         if (conn->status == CRYPTO_CONN_ESTABLISHED) {
3034             // TODO(irungentoo): add a timeout here?
3035             do_timeout_here();
3036         }
3037 
3038 #endif
3039     }
3040 }
3041 
3042 /* return the optimal interval in ms for running do_net_crypto.
3043  */
crypto_run_interval(const Net_Crypto * c)3044 uint32_t crypto_run_interval(const Net_Crypto *c)
3045 {
3046     return c->current_sleep_time;
3047 }
3048 
3049 /* Main loop. */
do_net_crypto(Net_Crypto * c,void * userdata)3050 void do_net_crypto(Net_Crypto *c, void *userdata)
3051 {
3052     kill_timedout(c, userdata);
3053     do_tcp(c, userdata);
3054     send_crypto_packets(c);
3055 }
3056 
kill_net_crypto(Net_Crypto * c)3057 void kill_net_crypto(Net_Crypto *c)
3058 {
3059     uint32_t i;
3060 
3061     for (i = 0; i < c->crypto_connections_length; ++i) {
3062         crypto_kill(c, i);
3063     }
3064 
3065     pthread_mutex_destroy(&c->tcp_mutex);
3066     pthread_mutex_destroy(&c->connections_mutex);
3067 
3068     kill_tcp_connections(c->tcp_c);
3069     bs_list_free(&c->ip_port_list);
3070     networking_registerhandler(dht_get_net(c->dht), NET_PACKET_COOKIE_REQUEST, nullptr, nullptr);
3071     networking_registerhandler(dht_get_net(c->dht), NET_PACKET_COOKIE_RESPONSE, nullptr, nullptr);
3072     networking_registerhandler(dht_get_net(c->dht), NET_PACKET_CRYPTO_HS, nullptr, nullptr);
3073     networking_registerhandler(dht_get_net(c->dht), NET_PACKET_CRYPTO_DATA, nullptr, nullptr);
3074     crypto_memzero(c, sizeof(Net_Crypto));
3075     free(c);
3076 }
3077