Coverage Report

Created: 2024-01-26 01:52

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