Coverage Report

Created: 2025-10-08 19:34

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