Coverage Report

Created: 2024-01-26 01:52

/work/toxcore/TCP_client.c
Line
Count
Source (jump to first uncovered line)
1
/* SPDX-License-Identifier: GPL-3.0-or-later
2
 * Copyright © 2016-2018 The TokTok team.
3
 * Copyright © 2014 Tox project.
4
 */
5
6
/**
7
 * Implementation of the TCP relay client part of Tox.
8
 */
9
#include "TCP_client.h"
10
11
#include <assert.h>
12
#include <stdio.h>
13
#include <string.h>
14
15
#include "DHT.h"
16
#include "TCP_common.h"
17
#include "ccompat.h"
18
#include "crypto_core.h"
19
#include "forwarding.h"
20
#include "logger.h"
21
#include "mem.h"
22
#include "mono_time.h"
23
#include "network.h"
24
#include "util.h"
25
26
typedef struct TCP_Client_Conn {
27
    // TODO(iphydf): Add an enum for this.
28
    uint8_t status; /* 0 if not used, 1 if other is offline, 2 if other is online. */
29
    uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE];
30
    uint32_t number;
31
} TCP_Client_Conn;
32
33
struct TCP_Client_Connection {
34
    TCP_Connection con;
35
    TCP_Client_Status status;
36
    uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* our public key */
37
    uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]; /* public key of the server */
38
    IP_Port ip_port; /* The ip and port of the server */
39
    TCP_Proxy_Info proxy_info;
40
    uint8_t recv_nonce[CRYPTO_NONCE_SIZE]; /* Nonce of received packets. */
41
    uint16_t next_packet_length;
42
43
    uint8_t temp_secret_key[CRYPTO_SECRET_KEY_SIZE];
44
45
    uint64_t kill_at;
46
47
    uint64_t last_pinged;
48
    uint64_t ping_id;
49
50
    uint64_t ping_response_id;
51
    uint64_t ping_request_id;
52
53
    TCP_Client_Conn connections[NUM_CLIENT_CONNECTIONS];
54
    tcp_routing_response_cb *response_callback;
55
    void *response_callback_object;
56
    tcp_routing_status_cb *status_callback;
57
    void *status_callback_object;
58
    tcp_routing_data_cb *data_callback;
59
    void *data_callback_object;
60
    tcp_oob_data_cb *oob_data_callback;
61
    void *oob_data_callback_object;
62
63
    tcp_onion_response_cb *onion_callback;
64
    void *onion_callback_object;
65
66
    forwarded_response_cb *forwarded_response_callback;
67
    void *forwarded_response_callback_object;
68
69
    /* Can be used by user. */
70
    void *custom_object;
71
    uint32_t custom_uint;
72
};
73
74
const uint8_t *tcp_con_public_key(const TCP_Client_Connection *con)
75
688
{
76
688
    return con->public_key;
77
688
}
78
79
IP_Port tcp_con_ip_port(const TCP_Client_Connection *con)
80
585
{
81
585
    return con->ip_port;
82
585
}
83
84
TCP_Client_Status tcp_con_status(const TCP_Client_Connection *con)
85
19.9k
{
86
19.9k
    return con->status;
87
19.9k
}
88
void *tcp_con_custom_object(const TCP_Client_Connection *con)
89
1.31k
{
90
1.31k
    return con->custom_object;
91
1.31k
}
92
uint32_t tcp_con_custom_uint(const TCP_Client_Connection *con)
93
1.31k
{
94
1.31k
    return con->custom_uint;
95
1.31k
}
96
void tcp_con_set_custom_object(TCP_Client_Connection *con, void *object)
97
200
{
98
200
    con->custom_object = object;
99
200
}
100
void tcp_con_set_custom_uint(TCP_Client_Connection *con, uint32_t value)
101
200
{
102
200
    con->custom_uint = value;
103
200
}
104
105
/**
106
 * @retval true on success
107
 * @retval false on failure
108
 */
109
non_null()
110
static bool connect_sock_to(const Logger *logger, const Memory *mem, Socket sock, const IP_Port *ip_port, const TCP_Proxy_Info *proxy_info)
111
437
{
112
437
    if (proxy_info->proxy_type != TCP_PROXY_NONE) {
113
191
        return net_connect(mem, logger, sock, &proxy_info->ip_port);
114
246
    } else {
115
246
        return net_connect(mem, logger, sock, ip_port);
116
246
    }
117
437
}
118
119
/**
120
 * @retval 1 on success.
121
 * @retval 0 on failure.
122
 */
123
non_null()
124
static int proxy_http_generate_connection_request(TCP_Client_Connection *tcp_conn)
125
148
{
126
148
    const char one[] = "CONNECT ";
127
148
    const char two[] = " HTTP/1.1\nHost: ";
128
148
    const char three[] = "\r\n\r\n";
129
130
148
    char ip[TOX_INET6_ADDRSTRLEN];
131
132
148
    if (!ip_parse_addr(&tcp_conn->ip_port.ip, ip, sizeof(ip))) {
133
0
        return 0;
134
0
    }
135
136
148
    const uint16_t port = net_ntohs(tcp_conn->ip_port.port);
137
148
    const int written = snprintf((char *)tcp_conn->con.last_packet, MAX_PACKET_SIZE, "%s%s:%hu%s%s:%hu%s", one, ip, port,
138
148
                                 two, ip, port, three);
139
140
148
    if (written < 0 || MAX_PACKET_SIZE < written) {
141
0
        return 0;
142
0
    }
143
144
148
    tcp_conn->con.last_packet_length = written;
145
148
    tcp_conn->con.last_packet_sent = 0;
146
148
    return 1;
147
148
}
148
149
/**
150
 * @retval 1 on success.
151
 * @retval 0 if no data received.
152
 * @retval -1 on failure (connection refused).
153
 */
154
non_null()
155
static int proxy_http_read_connection_response(const Logger *logger, const TCP_Client_Connection *tcp_conn)
156
268
{
157
268
    const char success[] = "200";
158
268
    uint8_t data[16]; // draining works the best if the length is a power of 2
159
160
268
    const TCP_Connection *con0 = &tcp_conn->con;
161
268
    const int ret = read_tcp_packet(logger, con0->mem, con0->ns, con0->sock, data, sizeof(data) - 1, &con0->ip_port);
162
163
268
    if (ret == -1) {
164
151
        return 0;
165
151
    }
166
167
117
    data[sizeof(data) - 1] = 0;
168
169
117
    if (strstr((const char *)data, success) != nullptr) {
170
        // drain all data
171
111
        uint16_t data_left = net_socket_data_recv_buffer(tcp_conn->con.ns, tcp_conn->con.sock);
172
173
266
        while (data_left > 0) {
174
239
            uint8_t temp_data[16];
175
239
            const uint16_t temp_data_size = min_u16(data_left, sizeof(temp_data));
176
239
            const TCP_Connection *con = &tcp_conn->con;
177
178
239
            if (read_tcp_packet(logger, con->mem, con->ns, con->sock, temp_data, temp_data_size,
179
239
                                &con->ip_port) == -1) {
180
84
                LOGGER_ERROR(logger, "failed to drain TCP data (but ignoring failure)");
181
84
                return 1;
182
84
            }
183
184
155
            data_left -= temp_data_size;
185
155
        }
186
187
27
        return 1;
188
111
    }
189
190
6
    return -1;
191
117
}
192
193
enum Tcp_Socks5_Proxy_Hs {
194
    TCP_SOCKS5_PROXY_HS_VERSION_SOCKS5          = 0x05,
195
    TCP_SOCKS5_PROXY_HS_COMM_ESTABLISH_REQUEST  = 0x01,
196
    TCP_SOCKS5_PROXY_HS_COMM_REQUEST_GRANTED    = 0x00,
197
    TCP_SOCKS5_PROXY_HS_AUTH_METHODS_SUPPORTED  = 0x01,
198
    TCP_SOCKS5_PROXY_HS_NO_AUTH                 = 0x00,
199
    TCP_SOCKS5_PROXY_HS_RESERVED                = 0x00,
200
    TCP_SOCKS5_PROXY_HS_ADDR_TYPE_IPV4          = 0x01,
201
    TCP_SOCKS5_PROXY_HS_ADDR_TYPE_IPV6          = 0x04,
202
};
203
204
non_null()
205
static void proxy_socks5_generate_greetings(TCP_Client_Connection *tcp_conn)
206
36
{
207
36
    tcp_conn->con.last_packet[0] = TCP_SOCKS5_PROXY_HS_VERSION_SOCKS5;
208
36
    tcp_conn->con.last_packet[1] = TCP_SOCKS5_PROXY_HS_AUTH_METHODS_SUPPORTED;
209
36
    tcp_conn->con.last_packet[2] = TCP_SOCKS5_PROXY_HS_NO_AUTH;
210
211
36
    tcp_conn->con.last_packet_length = 3;
212
36
    tcp_conn->con.last_packet_sent = 0;
213
36
}
214
215
/**
216
 * @retval 1 on success.
217
 * @retval 0 if no data received.
218
 * @retval -1 on failure (connection refused).
219
 */
220
non_null()
221
static int socks5_read_handshake_response(const Logger *logger, const TCP_Client_Connection *tcp_conn)
222
197
{
223
197
    uint8_t data[2];
224
197
    const TCP_Connection *con = &tcp_conn->con;
225
197
    const int ret = read_tcp_packet(logger, con->mem, con->ns, con->sock, data, sizeof(data), &con->ip_port);
226
227
197
    if (ret == -1) {
228
179
        return 0;
229
179
    }
230
231
18
    if (data[0] == TCP_SOCKS5_PROXY_HS_VERSION_SOCKS5 && data[1] == TCP_SOCKS5_PROXY_HS_COMM_REQUEST_GRANTED) {
232
11
        return 1;
233
11
    }
234
235
7
    return -1;
236
18
}
237
238
non_null()
239
static void proxy_socks5_generate_connection_request(TCP_Client_Connection *tcp_conn)
240
11
{
241
11
    tcp_conn->con.last_packet[0] = TCP_SOCKS5_PROXY_HS_VERSION_SOCKS5;
242
11
    tcp_conn->con.last_packet[1] = TCP_SOCKS5_PROXY_HS_COMM_ESTABLISH_REQUEST;
243
11
    tcp_conn->con.last_packet[2] = TCP_SOCKS5_PROXY_HS_RESERVED;
244
11
    uint16_t length = 3;
245
246
11
    if (net_family_is_ipv4(tcp_conn->ip_port.ip.family)) {
247
11
        tcp_conn->con.last_packet[3] = TCP_SOCKS5_PROXY_HS_ADDR_TYPE_IPV4;
248
11
        ++length;
249
11
        memcpy(tcp_conn->con.last_packet + length, tcp_conn->ip_port.ip.ip.v4.uint8, sizeof(IP4));
250
11
        length += sizeof(IP4);
251
11
    } else {
252
0
        tcp_conn->con.last_packet[3] = TCP_SOCKS5_PROXY_HS_ADDR_TYPE_IPV6;
253
0
        ++length;
254
0
        memcpy(tcp_conn->con.last_packet + length, tcp_conn->ip_port.ip.ip.v6.uint8, sizeof(IP6));
255
0
        length += sizeof(IP6);
256
0
    }
257
258
11
    memcpy(tcp_conn->con.last_packet + length, &tcp_conn->ip_port.port, sizeof(uint16_t));
259
11
    length += sizeof(uint16_t);
260
261
11
    tcp_conn->con.last_packet_length = length;
262
11
    tcp_conn->con.last_packet_sent = 0;
263
11
}
264
265
/**
266
 * @retval 1 on success.
267
 * @retval 0 if no data received.
268
 * @retval -1 on failure (connection refused).
269
 */
270
non_null()
271
static int proxy_socks5_read_connection_response(const Logger *logger, const TCP_Client_Connection *tcp_conn)
272
79
{
273
79
    if (net_family_is_ipv4(tcp_conn->ip_port.ip.family)) {
274
79
        uint8_t data[4 + sizeof(IP4) + sizeof(uint16_t)];
275
79
        const TCP_Connection *con = &tcp_conn->con;
276
79
        const int ret = read_tcp_packet(logger, con->mem, con->ns, con->sock, data, sizeof(data), &con->ip_port);
277
278
79
        if (ret == -1) {
279
72
            return 0;
280
72
        }
281
282
7
        if (data[0] == TCP_SOCKS5_PROXY_HS_VERSION_SOCKS5 && data[1] == TCP_SOCKS5_PROXY_HS_COMM_REQUEST_GRANTED) {
283
2
            return 1;
284
2
        }
285
7
    } else {
286
0
        uint8_t data[4 + sizeof(IP6) + sizeof(uint16_t)];
287
0
        const TCP_Connection *con = &tcp_conn->con;
288
0
        int ret = read_tcp_packet(logger, con->mem, con->ns, con->sock, data, sizeof(data), &con->ip_port);
289
290
0
        if (ret == -1) {
291
0
            return 0;
292
0
        }
293
294
0
        if (data[0] == TCP_SOCKS5_PROXY_HS_VERSION_SOCKS5 && data[1] == TCP_SOCKS5_PROXY_HS_COMM_REQUEST_GRANTED) {
295
0
            return 1;
296
0
        }
297
0
    }
298
299
5
    return -1;
300
79
}
301
302
/**
303
 * @retval 0 on success.
304
 * @retval -1 on failure.
305
 */
306
non_null()
307
static int generate_handshake(TCP_Client_Connection *tcp_conn)
308
341
{
309
341
    uint8_t plain[CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE];
310
341
    crypto_new_keypair(tcp_conn->con.rng, plain, tcp_conn->temp_secret_key);
311
341
    random_nonce(tcp_conn->con.rng, tcp_conn->con.sent_nonce);
312
341
    memcpy(plain + CRYPTO_PUBLIC_KEY_SIZE, tcp_conn->con.sent_nonce, CRYPTO_NONCE_SIZE);
313
341
    memcpy(tcp_conn->con.last_packet, tcp_conn->self_public_key, CRYPTO_PUBLIC_KEY_SIZE);
314
341
    random_nonce(tcp_conn->con.rng, tcp_conn->con.last_packet + CRYPTO_PUBLIC_KEY_SIZE);
315
341
    const int len = encrypt_data_symmetric(tcp_conn->con.shared_key, tcp_conn->con.last_packet + CRYPTO_PUBLIC_KEY_SIZE, plain,
316
341
                                     sizeof(plain), tcp_conn->con.last_packet + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE);
317
318
341
    if (len != sizeof(plain) + CRYPTO_MAC_SIZE) {
319
0
        return -1;
320
0
    }
321
322
341
    tcp_conn->con.last_packet_length = CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + sizeof(plain) + CRYPTO_MAC_SIZE;
323
341
    tcp_conn->con.last_packet_sent = 0;
324
341
    return 0;
325
341
}
326
327
/**
328
 * @param data must be of length TCP_SERVER_HANDSHAKE_SIZE
329
 *
330
 * @retval 0 on success.
331
 * @retval -1 on failure.
332
 */
333
non_null()
334
static int handle_handshake(TCP_Client_Connection *tcp_conn, const uint8_t *data)
335
218
{
336
218
    uint8_t plain[CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE];
337
218
    const int len = decrypt_data_symmetric(tcp_conn->con.shared_key, data, data + CRYPTO_NONCE_SIZE,
338
218
                                     TCP_SERVER_HANDSHAKE_SIZE - CRYPTO_NONCE_SIZE, plain);
339
340
218
    if (len != sizeof(plain)) {
341
0
        return -1;
342
0
    }
343
344
218
    memcpy(tcp_conn->recv_nonce, plain + CRYPTO_PUBLIC_KEY_SIZE, CRYPTO_NONCE_SIZE);
345
218
    encrypt_precompute(plain, tcp_conn->temp_secret_key, tcp_conn->con.shared_key);
346
218
    crypto_memzero(tcp_conn->temp_secret_key, CRYPTO_SECRET_KEY_SIZE);
347
218
    return 0;
348
218
}
349
350
/**
351
 * @retval 1 on success.
352
 * @retval 0 if could not send packet.
353
 * @retval -1 on failure (connection must be killed).
354
 */
355
int send_routing_request(const Logger *logger, TCP_Client_Connection *con, const uint8_t *public_key)
356
109
{
357
109
    uint8_t packet[1 + CRYPTO_PUBLIC_KEY_SIZE];
358
109
    packet[0] = TCP_PACKET_ROUTING_REQUEST;
359
109
    memcpy(packet + 1, public_key, CRYPTO_PUBLIC_KEY_SIZE);
360
109
    return write_packet_tcp_secure_connection(logger, &con->con, packet, sizeof(packet), true);
361
109
}
362
363
void routing_response_handler(TCP_Client_Connection *con, tcp_routing_response_cb *response_callback, void *object)
364
201
{
365
201
    con->response_callback = response_callback;
366
201
    con->response_callback_object = object;
367
201
}
368
369
void routing_status_handler(TCP_Client_Connection *con, tcp_routing_status_cb *status_callback, void *object)
370
201
{
371
201
    con->status_callback = status_callback;
372
201
    con->status_callback_object = object;
373
201
}
374
375
non_null() static int tcp_send_ping_response(const Logger *logger, TCP_Client_Connection *con);
376
non_null() static int tcp_send_ping_request(const Logger *logger, TCP_Client_Connection *con);
377
378
/**
379
 * @retval 1 on success.
380
 * @retval 0 if could not send packet.
381
 * @retval -1 on failure.
382
 */
383
int send_data(const Logger *logger, TCP_Client_Connection *con, uint8_t con_id, const uint8_t *data, uint16_t length)
384
1.06k
{
385
1.06k
    if (con_id >= NUM_CLIENT_CONNECTIONS) {
386
0
        return -1;
387
0
    }
388
389
1.06k
    if (con->connections[con_id].status != 2) {
390
0
        return -1;
391
0
    }
392
393
1.06k
    if (tcp_send_ping_response(logger, con) == 0 || tcp_send_ping_request(logger, con) == 0) {
394
0
        return 0;
395
0
    }
396
397
1.06k
    const uint16_t packet_size = 1 + length;
398
1.06k
    VLA(uint8_t, packet, packet_size);
399
1.06k
    packet[0] = con_id + NUM_RESERVED_PORTS;
400
1.06k
    memcpy(packet + 1, data, length);
401
1.06k
    return write_packet_tcp_secure_connection(logger, &con->con, packet, packet_size, false);
402
1.06k
}
403
404
/**
405
 * @retval 1 on success.
406
 * @retval 0 if could not send packet.
407
 * @retval -1 on failure.
408
 */
409
int send_oob_packet(const Logger *logger, TCP_Client_Connection *con, const uint8_t *public_key, const uint8_t *data,
410
                    uint16_t length)
411
173
{
412
173
    if (length == 0 || length > TCP_MAX_OOB_DATA_LENGTH) {
413
0
        return -1;
414
0
    }
415
416
173
    const uint16_t packet_size = 1 + CRYPTO_PUBLIC_KEY_SIZE + length;
417
173
    VLA(uint8_t, packet, packet_size);
418
173
    packet[0] = TCP_PACKET_OOB_SEND;
419
173
    memcpy(packet + 1, public_key, CRYPTO_PUBLIC_KEY_SIZE);
420
173
    memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, data, length);
421
173
    return write_packet_tcp_secure_connection(logger, &con->con, packet, packet_size, false);
422
173
}
423
424
425
/** @brief Set the number that will be used as an argument in the callbacks related to con_id.
426
 *
427
 * When not set by this function, the number is -1.
428
 *
429
 * return 0 on success.
430
 * return -1 on failure.
431
 */
432
int set_tcp_connection_number(TCP_Client_Connection *con, uint8_t con_id, uint32_t number)
433
108
{
434
108
    if (con_id >= NUM_CLIENT_CONNECTIONS) {
435
0
        return -1;
436
0
    }
437
438
108
    if (con->connections[con_id].status == 0) {
439
0
        return -1;
440
0
    }
441
442
108
    con->connections[con_id].number = number;
443
108
    return 0;
444
108
}
445
446
void routing_data_handler(TCP_Client_Connection *con, tcp_routing_data_cb *data_callback, void *object)
447
201
{
448
201
    con->data_callback = data_callback;
449
201
    con->data_callback_object = object;
450
201
}
451
452
void oob_data_handler(TCP_Client_Connection *con, tcp_oob_data_cb *oob_data_callback, void *object)
453
201
{
454
201
    con->oob_data_callback = oob_data_callback;
455
201
    con->oob_data_callback_object = object;
456
201
}
457
458
/**
459
 * @retval 1 on success.
460
 * @retval 0 if could not send packet.
461
 * @retval -1 on failure (connection must be killed).
462
 */
463
non_null()
464
static int client_send_disconnect_notification(const Logger *logger, TCP_Client_Connection *con, uint8_t id)
465
108
{
466
108
    uint8_t packet[1 + 1];
467
108
    packet[0] = TCP_PACKET_DISCONNECT_NOTIFICATION;
468
108
    packet[1] = id;
469
108
    return write_packet_tcp_secure_connection(logger, &con->con, packet, sizeof(packet), true);
470
108
}
471
472
/**
473
 * @retval 1 on success.
474
 * @retval 0 if could not send packet.
475
 * @retval -1 on failure (connection must be killed).
476
 */
477
static int tcp_send_ping_request(const Logger *logger, TCP_Client_Connection *con)
478
16.9k
{
479
16.9k
    if (con->ping_request_id == 0) {
480
16.7k
        return 1;
481
16.7k
    }
482
483
224
    uint8_t packet[1 + sizeof(uint64_t)];
484
224
    packet[0] = TCP_PACKET_PING;
485
224
    memcpy(packet + 1, &con->ping_request_id, sizeof(uint64_t));
486
224
    const int ret = write_packet_tcp_secure_connection(logger, &con->con, packet, sizeof(packet), true);
487
488
224
    if (ret == 1) {
489
224
        con->ping_request_id = 0;
490
224
    }
491
492
224
    return ret;
493
16.9k
}
494
495
/**
496
 * @retval 1 on success.
497
 * @retval 0 if could not send packet.
498
 * @retval -1 on failure (connection must be killed).
499
 */
500
static int tcp_send_ping_response(const Logger *logger, TCP_Client_Connection *con)
501
16.7k
{
502
16.7k
    if (con->ping_response_id == 0) {
503
16.7k
        return 1;
504
16.7k
    }
505
506
17
    uint8_t packet[1 + sizeof(uint64_t)];
507
17
    packet[0] = TCP_PACKET_PONG;
508
17
    memcpy(packet + 1, &con->ping_response_id, sizeof(uint64_t));
509
17
    const int ret = write_packet_tcp_secure_connection(logger, &con->con, packet, sizeof(packet), true);
510
511
17
    if (ret == 1) {
512
17
        con->ping_response_id = 0;
513
17
    }
514
515
17
    return ret;
516
16.7k
}
517
518
/**
519
 * @retval 1 on success.
520
 * @retval 0 if could not send packet.
521
 * @retval -1 on failure (connection must be killed).
522
 */
523
int send_disconnect_request(const Logger *logger, TCP_Client_Connection *con, uint8_t con_id)
524
108
{
525
108
    if (con_id >= NUM_CLIENT_CONNECTIONS) {
526
0
        return -1;
527
0
    }
528
529
108
    con->connections[con_id].status = 0;
530
108
    con->connections[con_id].number = 0;
531
108
    return client_send_disconnect_notification(logger, con, con_id + NUM_RESERVED_PORTS);
532
108
}
533
534
/**
535
 * @retval 1 on success.
536
 * @retval 0 if could not send packet.
537
 * @retval -1 on failure (connection must be killed).
538
 */
539
int send_onion_request(const Logger *logger, TCP_Client_Connection *con, const uint8_t *data, uint16_t length)
540
1.02k
{
541
1.02k
    const uint16_t packet_size = 1 + length;
542
1.02k
    VLA(uint8_t, packet, packet_size);
543
1.02k
    packet[0] = TCP_PACKET_ONION_REQUEST;
544
1.02k
    memcpy(packet + 1, data, length);
545
1.02k
    return write_packet_tcp_secure_connection(logger, &con->con, packet, packet_size, false);
546
1.02k
}
547
548
void onion_response_handler(TCP_Client_Connection *con, tcp_onion_response_cb *onion_callback, void *object)
549
200
{
550
200
    con->onion_callback = onion_callback;
551
200
    con->onion_callback_object = object;
552
200
}
553
554
/** @retval 1 on success.
555
 * @retval 0 if could not send packet.
556
 * @retval -1 on failure (connection must be killed).
557
 */
558
int send_forward_request_tcp(const Logger *logger, TCP_Client_Connection *con, const IP_Port *dest, const uint8_t *data, uint16_t length)
559
9
{
560
9
    if (length > MAX_FORWARD_DATA_SIZE) {
561
0
        return -1;
562
0
    }
563
564
9
    VLA(uint8_t, packet, 1 + MAX_PACKED_IPPORT_SIZE + length);
565
9
    packet[0] = TCP_PACKET_FORWARD_REQUEST;
566
9
    const int ipport_length = pack_ip_port(logger, packet + 1, MAX_PACKED_IPPORT_SIZE, dest);
567
568
9
    if (ipport_length == -1) {
569
0
        return 0;
570
0
    }
571
572
9
    memcpy(packet + 1 + ipport_length, data, length);
573
9
    return write_packet_tcp_secure_connection(logger, &con->con, packet, 1 + ipport_length + length, false);
574
9
}
575
576
void forwarding_handler(TCP_Client_Connection *con, forwarded_response_cb *forwarded_response_callback, void *object)
577
200
{
578
200
    con->forwarded_response_callback = forwarded_response_callback;
579
200
    con->forwarded_response_callback_object = object;
580
200
}
581
582
/** Create new TCP connection to ip_port/public_key */
583
TCP_Client_Connection *new_tcp_connection(
584
        const Logger *logger, const Memory *mem, const Mono_Time *mono_time, const Random *rng, const Network *ns,
585
        const IP_Port *ip_port, const uint8_t *public_key, const uint8_t *self_public_key, const uint8_t *self_secret_key,
586
        const TCP_Proxy_Info *proxy_info)
587
437
{
588
437
    assert(logger != nullptr);
589
437
    assert(mem != nullptr);
590
437
    assert(mono_time != nullptr);
591
437
    assert(rng != nullptr);
592
437
    assert(ns != nullptr);
593
594
437
    if (!net_family_is_ipv4(ip_port->ip.family) && !net_family_is_ipv6(ip_port->ip.family)) {
595
0
        return nullptr;
596
0
    }
597
598
437
    const TCP_Proxy_Info default_proxyinfo = {{{{0}}}};
599
600
437
    if (proxy_info == nullptr) {
601
3
        proxy_info = &default_proxyinfo;
602
3
    }
603
604
437
    Family family = ip_port->ip.family;
605
606
437
    if (proxy_info->proxy_type != TCP_PROXY_NONE) {
607
191
        family = proxy_info->ip_port.ip.family;
608
191
    }
609
610
437
    const Socket sock = net_socket(ns, family, TOX_SOCK_STREAM, TOX_PROTO_TCP);
611
612
437
    if (!sock_valid(sock)) {
613
0
        return nullptr;
614
0
    }
615
616
437
    if (!set_socket_nosigpipe(ns, sock)) {
617
0
        kill_sock(ns, sock);
618
0
        return nullptr;
619
0
    }
620
621
437
    if (!(set_socket_nonblock(ns, sock) && connect_sock_to(logger, mem, sock, ip_port, proxy_info))) {
622
0
        kill_sock(ns, sock);
623
0
        return nullptr;
624
0
    }
625
626
437
    TCP_Client_Connection *temp = (TCP_Client_Connection *)mem_alloc(mem, sizeof(TCP_Client_Connection));
627
628
437
    if (temp == nullptr) {
629
25
        kill_sock(ns, sock);
630
25
        return nullptr;
631
25
    }
632
633
412
    temp->con.ns = ns;
634
412
    temp->con.mem = mem;
635
412
    temp->con.rng = rng;
636
412
    temp->con.sock = sock;
637
412
    temp->con.ip_port = *ip_port;
638
412
    memcpy(temp->public_key, public_key, CRYPTO_PUBLIC_KEY_SIZE);
639
412
    memcpy(temp->self_public_key, self_public_key, CRYPTO_PUBLIC_KEY_SIZE);
640
412
    encrypt_precompute(temp->public_key, self_secret_key, temp->con.shared_key);
641
412
    temp->ip_port = *ip_port;
642
412
    temp->proxy_info = *proxy_info;
643
644
412
    switch (proxy_info->proxy_type) {
645
148
        case TCP_PROXY_HTTP: {
646
148
            temp->status = TCP_CLIENT_PROXY_HTTP_CONNECTING;
647
148
            proxy_http_generate_connection_request(temp);
648
148
            break;
649
0
        }
650
651
36
        case TCP_PROXY_SOCKS5: {
652
36
            temp->status = TCP_CLIENT_PROXY_SOCKS5_CONNECTING;
653
36
            proxy_socks5_generate_greetings(temp);
654
36
            break;
655
0
        }
656
657
228
        case TCP_PROXY_NONE: {
658
228
            temp->status = TCP_CLIENT_CONNECTING;
659
660
228
            if (generate_handshake(temp) == -1) {
661
0
                kill_sock(ns, sock);
662
0
                mem_delete(mem, temp);
663
0
                return nullptr;
664
0
            }
665
666
228
            break;
667
228
        }
668
412
    }
669
670
412
    temp->kill_at = mono_time_get(mono_time) + TCP_CONNECTION_TIMEOUT;
671
672
412
    return temp;
673
412
}
674
675
non_null()
676
static int handle_tcp_client_routing_response(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length)
677
115
{
678
115
    if (length != 1 + 1 + CRYPTO_PUBLIC_KEY_SIZE) {
679
6
        return -1;
680
6
    }
681
682
109
    if (data[1] < NUM_RESERVED_PORTS) {
683
0
        return 0;
684
0
    }
685
686
109
    const uint8_t con_id = data[1] - NUM_RESERVED_PORTS;
687
688
109
    if (conn->connections[con_id].status != 0) {
689
0
        return 0;
690
0
    }
691
692
109
    conn->connections[con_id].status = 1;
693
109
    conn->connections[con_id].number = -1;
694
109
    memcpy(conn->connections[con_id].public_key, data + 2, CRYPTO_PUBLIC_KEY_SIZE);
695
696
109
    if (conn->response_callback != nullptr) {
697
108
        conn->response_callback(conn->response_callback_object, con_id, conn->connections[con_id].public_key);
698
108
    }
699
700
109
    return 0;
701
109
}
702
703
non_null()
704
static int handle_tcp_client_connection_notification(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length)
705
109
{
706
109
    if (length != 1 + 1) {
707
1
        return -1;
708
1
    }
709
710
108
    if (data[1] < NUM_RESERVED_PORTS) {
711
0
        return -1;
712
0
    }
713
714
108
    const uint8_t con_id = data[1] - NUM_RESERVED_PORTS;
715
716
108
    if (conn->connections[con_id].status != 1) {
717
0
        return 0;
718
0
    }
719
720
108
    conn->connections[con_id].status = 2;
721
722
108
    if (conn->status_callback != nullptr) {
723
107
        conn->status_callback(conn->status_callback_object, conn->connections[con_id].number, con_id,
724
107
                              conn->connections[con_id].status);
725
107
    }
726
727
108
    return 0;
728
108
}
729
730
non_null()
731
static int handle_tcp_client_disconnect_notification(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length)
732
3
{
733
3
    if (length != 1 + 1) {
734
1
        return -1;
735
1
    }
736
737
2
    if (data[1] < NUM_RESERVED_PORTS) {
738
0
        return -1;
739
0
    }
740
741
2
    const uint8_t con_id = data[1] - NUM_RESERVED_PORTS;
742
743
2
    if (conn->connections[con_id].status == 0) {
744
0
        return 0;
745
0
    }
746
747
2
    if (conn->connections[con_id].status != 2) {
748
0
        return 0;
749
0
    }
750
751
2
    conn->connections[con_id].status = 1;
752
753
2
    if (conn->status_callback != nullptr) {
754
2
        conn->status_callback(conn->status_callback_object, conn->connections[con_id].number, con_id,
755
2
                              conn->connections[con_id].status);
756
2
    }
757
758
2
    return 0;
759
2
}
760
761
non_null()
762
static int handle_tcp_client_ping(const Logger *logger, TCP_Client_Connection *conn, const uint8_t *data, uint16_t length)
763
18
{
764
18
    if (length != 1 + sizeof(uint64_t)) {
765
1
        return -1;
766
1
    }
767
768
17
    uint64_t ping_id;
769
17
    memcpy(&ping_id, data + 1, sizeof(uint64_t));
770
17
    conn->ping_response_id = ping_id;
771
17
    tcp_send_ping_response(logger, conn);
772
17
    return 0;
773
18
}
774
775
non_null()
776
static int handle_tcp_client_pong(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length)
777
67
{
778
67
    if (length != 1 + sizeof(uint64_t)) {
779
1
        return -1;
780
1
    }
781
782
66
    uint64_t ping_id;
783
66
    memcpy(&ping_id, data + 1, sizeof(uint64_t));
784
785
66
    if (ping_id != 0) {
786
66
        if (ping_id == conn->ping_id) {
787
66
            conn->ping_id = 0;
788
66
        }
789
790
66
        return 0;
791
66
    }
792
793
0
    return -1;
794
66
}
795
796
non_null(1, 2) nullable(4)
797
static int handle_tcp_client_oob_recv(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length, void *userdata)
798
181
{
799
181
    if (length <= 1 + CRYPTO_PUBLIC_KEY_SIZE) {
800
1
        return -1;
801
1
    }
802
803
180
    if (conn->oob_data_callback != nullptr) {
804
179
        conn->oob_data_callback(conn->oob_data_callback_object, data + 1, data + 1 + CRYPTO_PUBLIC_KEY_SIZE,
805
179
                                length - (1 + CRYPTO_PUBLIC_KEY_SIZE), userdata);
806
179
    }
807
808
180
    return 0;
809
181
}
810
811
/**
812
 * @retval 0 on success
813
 * @retval -1 on failure
814
 */
815
non_null(1, 2, 3) nullable(5)
816
static int handle_tcp_client_packet(const Logger *logger, TCP_Client_Connection *conn, const uint8_t *data,
817
                                    uint16_t length, void *userdata)
818
2.18k
{
819
2.18k
    if (length <= 1) {
820
1
        return -1;
821
1
    }
822
823
2.18k
    switch (data[0]) {
824
115
        case TCP_PACKET_ROUTING_RESPONSE:
825
115
            return handle_tcp_client_routing_response(conn, data, length);
826
827
109
        case TCP_PACKET_CONNECTION_NOTIFICATION:
828
109
            return handle_tcp_client_connection_notification(conn, data, length);
829
830
3
        case TCP_PACKET_DISCONNECT_NOTIFICATION:
831
3
            return handle_tcp_client_disconnect_notification(conn, data, length);
832
833
18
        case TCP_PACKET_PING:
834
18
            return handle_tcp_client_ping(logger, conn, data, length);
835
836
67
        case TCP_PACKET_PONG:
837
67
            return handle_tcp_client_pong(conn, data, length);
838
839
181
        case TCP_PACKET_OOB_RECV:
840
181
            return handle_tcp_client_oob_recv(conn, data, length, userdata);
841
842
809
        case TCP_PACKET_ONION_RESPONSE: {
843
809
            if (conn->onion_callback != nullptr) {
844
808
                conn->onion_callback(conn->onion_callback_object, data + 1, length - 1, userdata);
845
808
            }
846
809
            return 0;
847
0
        }
848
849
17
        case TCP_PACKET_FORWARDING: {
850
17
            if (conn->forwarded_response_callback != nullptr) {
851
11
                conn->forwarded_response_callback(conn->forwarded_response_callback_object, data + 1, length - 1, userdata);
852
11
            }
853
17
            return 0;
854
0
        }
855
856
862
        default: {
857
862
            if (data[0] < NUM_RESERVED_PORTS) {
858
1
                return -1;
859
1
            }
860
861
861
            const uint8_t con_id = data[0] - NUM_RESERVED_PORTS;
862
863
861
            if (conn->data_callback != nullptr) {
864
854
                conn->data_callback(conn->data_callback_object, conn->connections[con_id].number, con_id, data + 1, length - 1,
865
854
                                    userdata);
866
854
            }
867
861
        }
868
2.18k
    }
869
870
861
    return 0;
871
2.18k
}
872
873
non_null(1, 2) nullable(3)
874
static bool tcp_process_packet(const Logger *logger, TCP_Client_Connection *conn, void *userdata)
875
17.8k
{
876
17.8k
    uint8_t packet[MAX_PACKET_SIZE];
877
17.8k
    const int len = read_packet_tcp_secure_connection(logger, conn->con.mem, conn->con.ns, conn->con.sock, &conn->next_packet_length, conn->con.shared_key, conn->recv_nonce, packet, sizeof(packet), &conn->ip_port);
878
879
17.8k
    if (len == 0) {
880
15.5k
        return false;
881
15.5k
    }
882
883
2.26k
    if (len == -1) {
884
87
        conn->status = TCP_CLIENT_DISCONNECTED;
885
87
        return false;
886
87
    }
887
888
2.18k
    if (handle_tcp_client_packet(logger, conn, packet, len, userdata) == -1) {
889
13
        conn->status = TCP_CLIENT_DISCONNECTED;
890
13
        return false;
891
13
    }
892
893
2.16k
    return true;
894
2.18k
}
895
896
non_null(1, 2, 3) nullable(4)
897
static int do_confirmed_tcp(const Logger *logger, TCP_Client_Connection *conn, const Mono_Time *mono_time,
898
                            void *userdata)
899
15.6k
{
900
15.6k
    send_pending_data(logger, &conn->con);
901
15.6k
    tcp_send_ping_response(logger, conn);
902
15.6k
    tcp_send_ping_request(logger, conn);
903
904
15.6k
    if (mono_time_is_timeout(mono_time, conn->last_pinged, TCP_PING_FREQUENCY)) {
905
224
        uint64_t ping_id = random_u64(conn->con.rng);
906
907
224
        if (ping_id == 0) {
908
29
            ++ping_id;
909
29
        }
910
911
224
        conn->ping_request_id = ping_id;
912
224
        conn->ping_id = ping_id;
913
224
        tcp_send_ping_request(logger, conn);
914
224
        conn->last_pinged = mono_time_get(mono_time);
915
224
    }
916
917
15.6k
    if (conn->ping_id != 0 && mono_time_is_timeout(mono_time, conn->last_pinged, TCP_PING_TIMEOUT)) {
918
11
        conn->status = TCP_CLIENT_DISCONNECTED;
919
11
        return 0;
920
11
    }
921
922
17.8k
    while (tcp_process_packet(logger, conn, userdata)) {
923
        /* Keep reading until error or out of data. */
924
2.16k
    }
925
926
15.6k
    return 0;
927
15.6k
}
928
929
/** Run the TCP connection */
930
void do_tcp_connection(const Logger *logger, const Mono_Time *mono_time,
931
                       TCP_Client_Connection *tcp_connection, void *userdata)
932
17.7k
{
933
17.7k
    if (tcp_connection->status == TCP_CLIENT_DISCONNECTED) {
934
0
        return;
935
0
    }
936
937
17.7k
    if (tcp_connection->status == TCP_CLIENT_PROXY_HTTP_CONNECTING) {
938
268
        if (send_pending_data(logger, &tcp_connection->con) == 0) {
939
268
            const int ret = proxy_http_read_connection_response(logger, tcp_connection);
940
941
268
            if (ret == -1) {
942
6
                tcp_connection->kill_at = 0;
943
6
                tcp_connection->status = TCP_CLIENT_DISCONNECTED;
944
6
            }
945
946
268
            if (ret == 1) {
947
111
                generate_handshake(tcp_connection);
948
111
                tcp_connection->status = TCP_CLIENT_CONNECTING;
949
111
            }
950
268
        }
951
268
    }
952
953
17.7k
    if (tcp_connection->status == TCP_CLIENT_PROXY_SOCKS5_CONNECTING) {
954
313
        if (send_pending_data(logger, &tcp_connection->con) == 0) {
955
197
            int ret = socks5_read_handshake_response(logger, tcp_connection);
956
957
197
            if (ret == -1) {
958
7
                tcp_connection->kill_at = 0;
959
7
                tcp_connection->status = TCP_CLIENT_DISCONNECTED;
960
7
            }
961
962
197
            if (ret == 1) {
963
11
                proxy_socks5_generate_connection_request(tcp_connection);
964
11
                tcp_connection->status = TCP_CLIENT_PROXY_SOCKS5_UNCONFIRMED;
965
11
            }
966
197
        }
967
313
    }
968
969
17.7k
    if (tcp_connection->status == TCP_CLIENT_PROXY_SOCKS5_UNCONFIRMED) {
970
79
        if (send_pending_data(logger, &tcp_connection->con) == 0) {
971
79
            int ret = proxy_socks5_read_connection_response(logger, tcp_connection);
972
973
79
            if (ret == -1) {
974
5
                tcp_connection->kill_at = 0;
975
5
                tcp_connection->status = TCP_CLIENT_DISCONNECTED;
976
5
            }
977
978
79
            if (ret == 1) {
979
2
                generate_handshake(tcp_connection);
980
2
                tcp_connection->status = TCP_CLIENT_CONNECTING;
981
2
            }
982
79
        }
983
79
    }
984
985
17.7k
    if (tcp_connection->status == TCP_CLIENT_CONNECTING) {
986
328
        if (send_pending_data(logger, &tcp_connection->con) == 0) {
987
325
            tcp_connection->status = TCP_CLIENT_UNCONFIRMED;
988
325
        }
989
328
    }
990
991
17.7k
    if (tcp_connection->status == TCP_CLIENT_UNCONFIRMED) {
992
1.74k
        uint8_t data[TCP_SERVER_HANDSHAKE_SIZE];
993
1.74k
        const TCP_Connection *con = &tcp_connection->con;
994
1.74k
        const int len = read_tcp_packet(logger, con->mem, con->ns, con->sock, data, sizeof(data), &con->ip_port);
995
996
1.74k
        if (sizeof(data) == len) {
997
218
            if (handle_handshake(tcp_connection, data) == 0) {
998
218
                tcp_connection->kill_at = UINT64_MAX;
999
218
                tcp_connection->status = TCP_CLIENT_CONFIRMED;
1000
218
            } else {
1001
0
                tcp_connection->kill_at = 0;
1002
0
                tcp_connection->status = TCP_CLIENT_DISCONNECTED;
1003
0
            }
1004
218
        }
1005
1.74k
    }
1006
1007
17.7k
    if (tcp_connection->status == TCP_CLIENT_CONFIRMED) {
1008
15.6k
        do_confirmed_tcp(logger, tcp_connection, mono_time, userdata);
1009
15.6k
    }
1010
1011
17.7k
    if (tcp_connection->kill_at <= mono_time_get(mono_time)) {
1012
41
        tcp_connection->status = TCP_CLIENT_DISCONNECTED;
1013
41
    }
1014
17.7k
}
1015
1016
/** Kill the TCP connection */
1017
void kill_tcp_connection(TCP_Client_Connection *tcp_connection)
1018
437
{
1019
437
    if (tcp_connection == nullptr) {
1020
25
        return;
1021
25
    }
1022
1023
412
    const Memory *mem = tcp_connection->con.mem;
1024
1025
412
    wipe_priority_list(tcp_connection->con.mem, tcp_connection->con.priority_queue_start);
1026
412
    kill_sock(tcp_connection->con.ns, tcp_connection->con.sock);
1027
412
    crypto_memzero(tcp_connection, sizeof(TCP_Client_Connection));
1028
412
    mem_delete(mem, tcp_connection);
1029
412
}