Coverage Report

Created: 2026-10-24 08:16

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