1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4 
5 #include <stdlib.h>
6 #include <string.h>
7 
8 #include "../testing/misc_tools.h"
9 #include "../toxcore/TCP_client.h"
10 #include "../toxcore/TCP_server.h"
11 #include "../toxcore/crypto_core.h"
12 #include "../toxcore/mono_time.h"
13 #include "../toxcore/util.h"
14 #include "check_compat.h"
15 
16 #define NUM_PORTS 3
17 
18 #ifndef USE_IPV6
19 #define USE_IPV6 1
20 #endif
21 
22 #if !USE_IPV6
23 #define net_family_ipv6 net_family_ipv4
24 #endif
25 
get_loopback(void)26 static inline IP get_loopback(void)
27 {
28     IP ip;
29 #if USE_IPV6
30     ip.family = net_family_ipv6;
31     ip.ip.v6 = get_ip6_loopback();
32 #else
33     ip.family = net_family_ipv4;
34     ip.ip.v4 = get_ip4_loopback();
35 #endif
36     return ip;
37 }
38 
do_TCP_server_delay(TCP_Server * tcp_s,Mono_Time * mono_time,int delay)39 static void do_TCP_server_delay(TCP_Server *tcp_s, Mono_Time *mono_time, int delay)
40 {
41     c_sleep(delay);
42     mono_time_update(mono_time);
43     do_TCP_server(tcp_s, mono_time);
44     c_sleep(delay);
45 }
46 static uint16_t ports[NUM_PORTS] = {13215, 33445, 25643};
47 
START_TEST(test_basic)48 START_TEST(test_basic)
49 {
50     Mono_Time *mono_time = mono_time_new();
51     Logger *logger = logger_new();
52 
53     // Attempt to create a new TCP_Server instance.
54     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
55     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
56     crypto_new_keypair(self_public_key, self_secret_key);
57     TCP_Server *tcp_s = new_TCP_server(logger, USE_IPV6, NUM_PORTS, ports, self_secret_key, nullptr);
58     ck_assert_msg(tcp_s != nullptr, "Failed to create a TCP relay server.");
59     ck_assert_msg(tcp_server_listen_count(tcp_s) == NUM_PORTS,
60                   "Failed to bind a TCP relay server to all %d attempted ports.", NUM_PORTS);
61 
62     Socket sock = {0};
63 
64     // Check all opened ports for connectivity.
65     for (uint8_t i = 0; i < NUM_PORTS; i++) {
66         sock = net_socket(net_family_ipv6, TOX_SOCK_STREAM, TOX_PROTO_TCP);
67         IP_Port ip_port_loopback;
68         ip_port_loopback.ip = get_loopback();
69         ip_port_loopback.port = net_htons(ports[i]);
70         int ret = net_connect(sock, ip_port_loopback);
71         ck_assert_msg(ret == 0, "Failed to connect to created TCP relay server on port %d.", ports[i]);
72 
73         // Leave open one connection for the next test.
74         if (i + 1 < NUM_PORTS) {
75             kill_sock(sock);
76         }
77     }
78 
79     // Key creation.
80     uint8_t f_public_key[CRYPTO_PUBLIC_KEY_SIZE];
81     uint8_t f_secret_key[CRYPTO_SECRET_KEY_SIZE];
82     uint8_t f_nonce[CRYPTO_NONCE_SIZE];
83     crypto_new_keypair(f_public_key, f_secret_key);
84     random_nonce(f_nonce);
85 
86     // Generation of the initial handshake.
87     uint8_t t_secret_key[CRYPTO_SECRET_KEY_SIZE];
88     uint8_t handshake_plain[TCP_HANDSHAKE_PLAIN_SIZE];
89     crypto_new_keypair(handshake_plain, t_secret_key);
90     memcpy(handshake_plain + CRYPTO_PUBLIC_KEY_SIZE, f_nonce, CRYPTO_NONCE_SIZE);
91     uint8_t handshake[TCP_CLIENT_HANDSHAKE_SIZE];
92     memcpy(handshake, f_public_key, CRYPTO_PUBLIC_KEY_SIZE);
93     random_nonce(handshake + CRYPTO_PUBLIC_KEY_SIZE);
94 
95     // Encrypting handshake
96     int ret = encrypt_data(self_public_key, f_secret_key, handshake + CRYPTO_PUBLIC_KEY_SIZE, handshake_plain,
97                            TCP_HANDSHAKE_PLAIN_SIZE, handshake + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE);
98     ck_assert_msg(ret == TCP_CLIENT_HANDSHAKE_SIZE - (CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE),
99                   "encrypt_data() call failed.");
100 
101     // Sending the handshake
102     ck_assert_msg(net_send(sock, handshake, TCP_CLIENT_HANDSHAKE_SIZE - 1) == TCP_CLIENT_HANDSHAKE_SIZE - 1,
103                   "An attempt to send the initial handshake minus last byte failed.");
104 
105     do_TCP_server_delay(tcp_s, mono_time, 50);
106 
107     ck_assert_msg(net_send(sock, handshake + (TCP_CLIENT_HANDSHAKE_SIZE - 1), 1) == 1,
108                   "The attempt to send the last byte of handshake failed.");
109 
110     do_TCP_server_delay(tcp_s, mono_time, 50);
111 
112     // Receiving server response and decrypting it
113     uint8_t response[TCP_SERVER_HANDSHAKE_SIZE];
114     uint8_t response_plain[TCP_HANDSHAKE_PLAIN_SIZE];
115     ck_assert_msg(net_recv(sock, response, TCP_SERVER_HANDSHAKE_SIZE) == TCP_SERVER_HANDSHAKE_SIZE,
116                   "Could/did not receive a server response to the initial handshake.");
117     ret = decrypt_data(self_public_key, f_secret_key, response, response + CRYPTO_NONCE_SIZE,
118                        TCP_SERVER_HANDSHAKE_SIZE - CRYPTO_NONCE_SIZE, response_plain);
119     ck_assert_msg(ret == TCP_HANDSHAKE_PLAIN_SIZE, "Failed to decrypt handshake response.");
120     uint8_t f_nonce_r[CRYPTO_NONCE_SIZE];
121     uint8_t f_shared_key[CRYPTO_SHARED_KEY_SIZE];
122     encrypt_precompute(response_plain, t_secret_key, f_shared_key);
123     memcpy(f_nonce_r, response_plain + CRYPTO_SHARED_KEY_SIZE, CRYPTO_NONCE_SIZE);
124 
125     // Building a request
126     uint8_t r_req_p[1 + CRYPTO_PUBLIC_KEY_SIZE];
127     r_req_p[0] = TCP_PACKET_ROUTING_REQUEST;
128     memcpy(r_req_p + 1, f_public_key, CRYPTO_PUBLIC_KEY_SIZE);
129     uint8_t r_req[2 + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE];
130     uint16_t size = 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE;
131     size = net_htons(size);
132     encrypt_data_symmetric(f_shared_key, f_nonce, r_req_p, 1 + CRYPTO_PUBLIC_KEY_SIZE, r_req + 2);
133     increment_nonce(f_nonce);
134     memcpy(r_req, &size, 2);
135 
136     // Sending the request at random intervals in random pieces.
137     for (uint32_t i = 0; i < sizeof(r_req);) {
138         uint8_t msg_length = rand() % 5 + 1; // msg_length = 1 to 5
139 
140         if (i + msg_length >= sizeof(r_req)) {
141             msg_length = sizeof(r_req) - i;
142         }
143 
144         ck_assert_msg(net_send(sock, r_req + i, msg_length) == msg_length,
145                       "Failed to send request after completing the handshake.");
146         i += msg_length;
147 
148         c_sleep(50);
149         mono_time_update(mono_time);
150         do_TCP_server(tcp_s, mono_time);
151     }
152 
153     // Receiving the second response and verifying its validity
154     uint8_t packet_resp[4096];
155     int recv_data_len = net_recv(sock, packet_resp, 2 + 2 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE);
156     ck_assert_msg(recv_data_len == 2 + 2 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE,
157                   "Failed to receive server response to request. %u", recv_data_len);
158     memcpy(&size, packet_resp, 2);
159     ck_assert_msg(net_ntohs(size) == 2 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE,
160                   "Wrong packet size for request response.");
161 
162     uint8_t packet_resp_plain[4096];
163     ret = decrypt_data_symmetric(f_shared_key, f_nonce_r, packet_resp + 2, recv_data_len - 2, packet_resp_plain);
164     ck_assert_msg(ret != -1, "Failed to decrypt the TCP server's response.");
165     increment_nonce(f_nonce_r);
166 
167     ck_assert_msg(packet_resp_plain[0] == TCP_PACKET_ROUTING_RESPONSE, "Server sent the wrong packet id: %u",
168                   packet_resp_plain[0]);
169     ck_assert_msg(packet_resp_plain[1] == 0, "Server did not refuse the connection.");
170     ck_assert_msg(public_key_cmp(packet_resp_plain + 2, f_public_key) == 0, "Server sent the wrong public key.");
171 
172     // Closing connections.
173     kill_sock(sock);
174     kill_TCP_server(tcp_s);
175 
176     logger_kill(logger);
177     mono_time_free(mono_time);
178 }
179 END_TEST
180 
181 struct sec_TCP_con {
182     Socket sock;
183     uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE];
184     uint8_t recv_nonce[CRYPTO_NONCE_SIZE];
185     uint8_t sent_nonce[CRYPTO_NONCE_SIZE];
186     uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
187 };
188 
new_TCP_con(TCP_Server * tcp_s,Mono_Time * mono_time)189 static struct sec_TCP_con *new_TCP_con(TCP_Server *tcp_s, Mono_Time *mono_time)
190 {
191     struct sec_TCP_con *sec_c = (struct sec_TCP_con *)malloc(sizeof(struct sec_TCP_con));
192     ck_assert(sec_c != nullptr);
193     Socket sock = net_socket(net_family_ipv6, TOX_SOCK_STREAM, TOX_PROTO_TCP);
194 
195     IP_Port ip_port_loopback;
196     ip_port_loopback.ip = get_loopback();
197     ip_port_loopback.port = net_htons(ports[random_u32() % NUM_PORTS]);
198 
199     int ret = net_connect(sock, ip_port_loopback);
200     ck_assert_msg(ret == 0, "Failed to connect to the test TCP relay server.");
201 
202     uint8_t f_secret_key[CRYPTO_SECRET_KEY_SIZE];
203     crypto_new_keypair(sec_c->public_key, f_secret_key);
204     random_nonce(sec_c->sent_nonce);
205 
206     uint8_t t_secret_key[CRYPTO_SECRET_KEY_SIZE];
207     uint8_t handshake_plain[TCP_HANDSHAKE_PLAIN_SIZE];
208     crypto_new_keypair(handshake_plain, t_secret_key);
209     memcpy(handshake_plain + CRYPTO_PUBLIC_KEY_SIZE, sec_c->sent_nonce, CRYPTO_NONCE_SIZE);
210     uint8_t handshake[TCP_CLIENT_HANDSHAKE_SIZE];
211     memcpy(handshake, sec_c->public_key, CRYPTO_PUBLIC_KEY_SIZE);
212     random_nonce(handshake + CRYPTO_PUBLIC_KEY_SIZE);
213 
214     ret = encrypt_data(tcp_server_public_key(tcp_s), f_secret_key, handshake + CRYPTO_PUBLIC_KEY_SIZE, handshake_plain,
215                        TCP_HANDSHAKE_PLAIN_SIZE, handshake + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE);
216     ck_assert_msg(ret == TCP_CLIENT_HANDSHAKE_SIZE - (CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE),
217                   "Failed to encrypt the outgoing handshake.");
218 
219     ck_assert_msg(net_send(sock, handshake, TCP_CLIENT_HANDSHAKE_SIZE - 1) == TCP_CLIENT_HANDSHAKE_SIZE - 1,
220                   "Failed to send the first portion of the handshake to the TCP relay server.");
221 
222     do_TCP_server_delay(tcp_s, mono_time, 50);
223 
224     ck_assert_msg(net_send(sock, handshake + (TCP_CLIENT_HANDSHAKE_SIZE - 1), 1) == 1,
225                   "Failed to send last byte of handshake.");
226 
227     do_TCP_server_delay(tcp_s, mono_time, 50);
228 
229     uint8_t response[TCP_SERVER_HANDSHAKE_SIZE];
230     uint8_t response_plain[TCP_HANDSHAKE_PLAIN_SIZE];
231     ck_assert_msg(net_recv(sock, response, TCP_SERVER_HANDSHAKE_SIZE) == TCP_SERVER_HANDSHAKE_SIZE,
232                   "Failed to receive server handshake response.");
233     ret = decrypt_data(tcp_server_public_key(tcp_s), f_secret_key, response, response + CRYPTO_NONCE_SIZE,
234                        TCP_SERVER_HANDSHAKE_SIZE - CRYPTO_NONCE_SIZE, response_plain);
235     ck_assert_msg(ret == TCP_HANDSHAKE_PLAIN_SIZE, "Failed to decrypt server handshake response.");
236     encrypt_precompute(response_plain, t_secret_key, sec_c->shared_key);
237     memcpy(sec_c->recv_nonce, response_plain + CRYPTO_SHARED_KEY_SIZE, CRYPTO_NONCE_SIZE);
238     sec_c->sock = sock;
239     return sec_c;
240 }
241 
kill_TCP_con(struct sec_TCP_con * con)242 static void kill_TCP_con(struct sec_TCP_con *con)
243 {
244     kill_sock(con->sock);
245     free(con);
246 }
247 
write_packet_TCP_secure_connection(struct sec_TCP_con * con,uint8_t * data,uint16_t length)248 static int write_packet_TCP_secure_connection(struct sec_TCP_con *con, uint8_t *data, uint16_t length)
249 {
250     VLA(uint8_t, packet, sizeof(uint16_t) + length + CRYPTO_MAC_SIZE);
251 
252     uint16_t c_length = net_htons(length + CRYPTO_MAC_SIZE);
253     memcpy(packet, &c_length, sizeof(uint16_t));
254     int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t));
255 
256     if ((unsigned int)len != (SIZEOF_VLA(packet) - sizeof(uint16_t))) {
257         return -1;
258     }
259 
260     increment_nonce(con->sent_nonce);
261 
262     ck_assert_msg(net_send(con->sock, packet, SIZEOF_VLA(packet)) == SIZEOF_VLA(packet), "Failed to send a packet.");
263     return 0;
264 }
265 
read_packet_sec_TCP(struct sec_TCP_con * con,uint8_t * data,uint16_t length)266 static int read_packet_sec_TCP(struct sec_TCP_con *con, uint8_t *data, uint16_t length)
267 {
268     int rlen = net_recv(con->sock, data, length);
269     ck_assert_msg(rlen == length, "Did not receive packet of correct length. Wanted %i, instead got %i", length, rlen);
270     rlen = decrypt_data_symmetric(con->shared_key, con->recv_nonce, data + 2, length - 2, data);
271     ck_assert_msg(rlen != -1, "Failed to decrypt a received packet from the Relay server.");
272     increment_nonce(con->recv_nonce);
273     return rlen;
274 }
275 
START_TEST(test_some)276 START_TEST(test_some)
277 {
278     Mono_Time *mono_time = mono_time_new();
279     Logger *logger = logger_new();
280 
281     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
282     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
283     crypto_new_keypair(self_public_key, self_secret_key);
284     TCP_Server *tcp_s = new_TCP_server(logger, USE_IPV6, NUM_PORTS, ports, self_secret_key, nullptr);
285     ck_assert_msg(tcp_s != nullptr, "Failed to create TCP relay server");
286     ck_assert_msg(tcp_server_listen_count(tcp_s) == NUM_PORTS, "Failed to bind to all ports.");
287 
288     struct sec_TCP_con *con1 = new_TCP_con(tcp_s, mono_time);
289     struct sec_TCP_con *con2 = new_TCP_con(tcp_s, mono_time);
290     struct sec_TCP_con *con3 = new_TCP_con(tcp_s, mono_time);
291 
292     uint8_t requ_p[1 + CRYPTO_PUBLIC_KEY_SIZE];
293     requ_p[0] = TCP_PACKET_ROUTING_REQUEST;
294 
295     // Sending wrong public keys to test server response.
296     memcpy(requ_p + 1, con3->public_key, CRYPTO_PUBLIC_KEY_SIZE);
297     write_packet_TCP_secure_connection(con1, requ_p, sizeof(requ_p));
298     memcpy(requ_p + 1, con1->public_key, CRYPTO_PUBLIC_KEY_SIZE);
299     write_packet_TCP_secure_connection(con3, requ_p, sizeof(requ_p));
300 
301     do_TCP_server_delay(tcp_s, mono_time, 50);
302 
303     // Testing response from connection 1
304     uint8_t data[2048];
305     int len = read_packet_sec_TCP(con1, data, 2 + 1 + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE);
306     ck_assert_msg(len == 1 + 1 + CRYPTO_PUBLIC_KEY_SIZE, "Wrong response packet length of %d.", len);
307     ck_assert_msg(data[0] == TCP_PACKET_ROUTING_RESPONSE, "Wrong response packet id of %d.", data[0]);
308     ck_assert_msg(data[1] == 16, "Server didn't refuse connection using wrong public key.");
309     ck_assert_msg(public_key_cmp(data + 2, con3->public_key) == 0, "Key in response packet wrong.");
310 
311     // Connection 3
312     len = read_packet_sec_TCP(con3, data, 2 + 1 + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_MAC_SIZE);
313     ck_assert_msg(len == 1 + 1 + CRYPTO_PUBLIC_KEY_SIZE, "Wrong response packet length of %d.", len);
314     ck_assert_msg(data[0] == TCP_PACKET_ROUTING_RESPONSE, "Wrong response packet id of %d.", data[0]);
315     ck_assert_msg(data[1] == 16, "Server didn't refuse connection using wrong public key.");
316     ck_assert_msg(public_key_cmp(data + 2, con1->public_key) == 0, "Key in response packet wrong.");
317 
318     uint8_t test_packet[512] = {16, 17, 16, 86, 99, 127, 255, 189, 78}; // What is this packet????
319 
320     write_packet_TCP_secure_connection(con3, test_packet, sizeof(test_packet));
321     write_packet_TCP_secure_connection(con3, test_packet, sizeof(test_packet));
322     write_packet_TCP_secure_connection(con3, test_packet, sizeof(test_packet));
323 
324     do_TCP_server_delay(tcp_s, mono_time, 50);
325 
326     len = read_packet_sec_TCP(con1, data, 2 + 2 + CRYPTO_MAC_SIZE);
327     ck_assert_msg(len == 2, "wrong len %d", len);
328     ck_assert_msg(data[0] == TCP_PACKET_CONNECTION_NOTIFICATION, "wrong packet id %u", data[0]);
329     ck_assert_msg(data[1] == 16, "wrong peer id %u", data[1]);
330     len = read_packet_sec_TCP(con3, data, 2 + 2 + CRYPTO_MAC_SIZE);
331     ck_assert_msg(len == 2, "wrong len %d", len);
332     ck_assert_msg(data[0] == TCP_PACKET_CONNECTION_NOTIFICATION, "wrong packet id %u", data[0]);
333     ck_assert_msg(data[1] == 16, "wrong peer id %u", data[1]);
334     len = read_packet_sec_TCP(con1, data, 2 + sizeof(test_packet) + CRYPTO_MAC_SIZE);
335     ck_assert_msg(len == sizeof(test_packet), "wrong len %d", len);
336     ck_assert_msg(memcmp(data, test_packet, sizeof(test_packet)) == 0, "packet is wrong %u %u %u %u", data[0], data[1],
337                   data[sizeof(test_packet) - 2], data[sizeof(test_packet) - 1]);
338     len = read_packet_sec_TCP(con1, data, 2 + sizeof(test_packet) + CRYPTO_MAC_SIZE);
339     ck_assert_msg(len == sizeof(test_packet), "wrong len %d", len);
340     ck_assert_msg(memcmp(data, test_packet, sizeof(test_packet)) == 0, "packet is wrong %u %u %u %u", data[0], data[1],
341                   data[sizeof(test_packet) - 2], data[sizeof(test_packet) - 1]);
342     len = read_packet_sec_TCP(con1, data, 2 + sizeof(test_packet) + CRYPTO_MAC_SIZE);
343     ck_assert_msg(len == sizeof(test_packet), "wrong len %d", len);
344     ck_assert_msg(memcmp(data, test_packet, sizeof(test_packet)) == 0, "packet is wrong %u %u %u %u", data[0], data[1],
345                   data[sizeof(test_packet) - 2], data[sizeof(test_packet) - 1]);
346     write_packet_TCP_secure_connection(con1, test_packet, sizeof(test_packet));
347     write_packet_TCP_secure_connection(con1, test_packet, sizeof(test_packet));
348     write_packet_TCP_secure_connection(con1, test_packet, sizeof(test_packet));
349     do_TCP_server_delay(tcp_s, mono_time, 50);
350     len = read_packet_sec_TCP(con3, data, 2 + sizeof(test_packet) + CRYPTO_MAC_SIZE);
351     ck_assert_msg(len == sizeof(test_packet), "wrong len %d", len);
352     ck_assert_msg(memcmp(data, test_packet, sizeof(test_packet)) == 0, "packet is wrong %u %u %u %u", data[0], data[1],
353                   data[sizeof(test_packet) - 2], data[sizeof(test_packet) - 1]);
354     len = read_packet_sec_TCP(con3, data, 2 + sizeof(test_packet) + CRYPTO_MAC_SIZE);
355     ck_assert_msg(len == sizeof(test_packet), "wrong len %d", len);
356     ck_assert_msg(memcmp(data, test_packet, sizeof(test_packet)) == 0, "packet is wrong %u %u %u %u", data[0], data[1],
357                   data[sizeof(test_packet) - 2], data[sizeof(test_packet) - 1]);
358     len = read_packet_sec_TCP(con3, data, 2 + sizeof(test_packet) + CRYPTO_MAC_SIZE);
359     ck_assert_msg(len == sizeof(test_packet), "wrong len %d", len);
360     ck_assert_msg(memcmp(data, test_packet, sizeof(test_packet)) == 0, "packet is wrong %u %u %u %u", data[0], data[1],
361                   data[sizeof(test_packet) - 2], data[sizeof(test_packet) - 1]);
362 
363     uint8_t ping_packet[1 + sizeof(uint64_t)] = {TCP_PACKET_PING, 8, 6, 9, 67};
364     write_packet_TCP_secure_connection(con1, ping_packet, sizeof(ping_packet));
365 
366     do_TCP_server_delay(tcp_s, mono_time, 50);
367 
368     len = read_packet_sec_TCP(con1, data, 2 + sizeof(ping_packet) + CRYPTO_MAC_SIZE);
369     ck_assert_msg(len == sizeof(ping_packet), "wrong len %d", len);
370     ck_assert_msg(data[0] == TCP_PACKET_PONG, "wrong packet id %u", data[0]);
371     ck_assert_msg(memcmp(ping_packet + 1, data + 1, sizeof(uint64_t)) == 0, "wrong packet data");
372 
373     // Kill off the connections
374     kill_TCP_server(tcp_s);
375     kill_TCP_con(con1);
376     kill_TCP_con(con2);
377     kill_TCP_con(con3);
378 
379     logger_kill(logger);
380     mono_time_free(mono_time);
381 }
382 END_TEST
383 
384 static int response_callback_good;
385 static uint8_t response_callback_connection_id;
386 static uint8_t response_callback_public_key[CRYPTO_PUBLIC_KEY_SIZE];
response_callback(void * object,uint8_t connection_id,const uint8_t * public_key)387 static int response_callback(void *object, uint8_t connection_id, const uint8_t *public_key)
388 {
389     if (set_tcp_connection_number((TCP_Client_Connection *)((char *)object - 2), connection_id, 7) != 0) {
390         return 1;
391     }
392 
393     response_callback_connection_id = connection_id;
394     memcpy(response_callback_public_key, public_key, CRYPTO_PUBLIC_KEY_SIZE);
395     response_callback_good++;
396     return 0;
397 }
398 static int status_callback_good;
399 static uint8_t status_callback_connection_id;
400 static uint8_t status_callback_status;
status_callback(void * object,uint32_t number,uint8_t connection_id,uint8_t status)401 static int status_callback(void *object, uint32_t number, uint8_t connection_id, uint8_t status)
402 {
403     if (object != (void *)2) {
404         return 1;
405     }
406 
407     if (number != 7) {
408         return 1;
409     }
410 
411     status_callback_connection_id = connection_id;
412     status_callback_status = status;
413     status_callback_good++;
414     return 0;
415 }
416 static int data_callback_good;
data_callback(void * object,uint32_t number,uint8_t connection_id,const uint8_t * data,uint16_t length,void * userdata)417 static int data_callback(void *object, uint32_t number, uint8_t connection_id, const uint8_t *data, uint16_t length,
418                          void *userdata)
419 {
420     if (object != (void *)3) {
421         return 1;
422     }
423 
424     if (number != 7) {
425         return 1;
426     }
427 
428     if (length != 5) {
429         return 1;
430     }
431 
432     if (data[0] == 1 && data[1] == 2 && data[2] == 3 && data[3] == 4 && data[4] == 5) {
433         data_callback_good++;
434         return 0;
435     }
436 
437     return 1;
438 }
439 
440 static int oob_data_callback_good;
441 static uint8_t oob_pubkey[CRYPTO_PUBLIC_KEY_SIZE];
oob_data_callback(void * object,const uint8_t * public_key,const uint8_t * data,uint16_t length,void * userdata)442 static int oob_data_callback(void *object, const uint8_t *public_key, const uint8_t *data, uint16_t length,
443                              void *userdata)
444 {
445     if (object != (void *)4) {
446         return 1;
447     }
448 
449     if (length != 5) {
450         return 1;
451     }
452 
453     if (public_key_cmp(public_key, oob_pubkey) != 0) {
454         return 1;
455     }
456 
457     if (data[0] == 1 && data[1] == 2 && data[2] == 3 && data[3] == 4 && data[4] == 5) {
458         oob_data_callback_good++;
459         return 0;
460     }
461 
462     return 1;
463 }
464 
START_TEST(test_client)465 START_TEST(test_client)
466 {
467     Mono_Time *mono_time = mono_time_new();
468     Logger *logger = logger_new();
469 
470     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
471     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
472     crypto_new_keypair(self_public_key, self_secret_key);
473     TCP_Server *tcp_s = new_TCP_server(logger, USE_IPV6, NUM_PORTS, ports, self_secret_key, nullptr);
474     ck_assert_msg(tcp_s != nullptr, "Failed to create a TCP relay server.");
475     ck_assert_msg(tcp_server_listen_count(tcp_s) == NUM_PORTS, "Failed to bind the relay server to all ports.");
476 
477     uint8_t f_public_key[CRYPTO_PUBLIC_KEY_SIZE];
478     uint8_t f_secret_key[CRYPTO_SECRET_KEY_SIZE];
479     crypto_new_keypair(f_public_key, f_secret_key);
480     IP_Port ip_port_tcp_s;
481 
482     ip_port_tcp_s.port = net_htons(ports[random_u32() % NUM_PORTS]);
483     ip_port_tcp_s.ip = get_loopback();
484 
485     TCP_Client_Connection *conn = new_TCP_connection(mono_time, ip_port_tcp_s, self_public_key, f_public_key, f_secret_key,
486                                   nullptr);
487     do_TCP_connection(logger, mono_time, conn, nullptr);
488     c_sleep(50);
489 
490     // The connection status should be unconfirmed here because we have finished
491     // sending our data and are awaiting a response.
492     ck_assert_msg(tcp_con_status(conn) == TCP_CLIENT_UNCONFIRMED, "Wrong connection status. Expected: %d, is: %d.",
493                   TCP_CLIENT_UNCONFIRMED, tcp_con_status(conn));
494 
495     do_TCP_server_delay(tcp_s, mono_time, 50); // Now let the server handle requests...
496 
497     const uint8_t LOOP_SIZE = 3;
498 
499     for (uint8_t i = 0; i < LOOP_SIZE; i++) {
500         mono_time_update(mono_time);
501         do_TCP_connection(logger, mono_time, conn, nullptr); // Run the connection loop.
502 
503         // The status of the connection should continue to be TCP_CLIENT_CONFIRMED after multiple subsequent do_TCP_connection() calls.
504         ck_assert_msg(tcp_con_status(conn) == TCP_CLIENT_CONFIRMED, "Wrong connection status. Expected: %d, is: %d",
505                       TCP_CLIENT_CONFIRMED, tcp_con_status(conn));
506 
507         c_sleep(i == LOOP_SIZE - 1 ? 0 : 500); // Sleep for 500ms on all except third loop.
508     }
509 
510     do_TCP_server_delay(tcp_s, mono_time, 50);
511 
512     // And still after the server runs again.
513     ck_assert_msg(tcp_con_status(conn) == TCP_CLIENT_CONFIRMED, "Wrong status. Expected: %d, is: %d", TCP_CLIENT_CONFIRMED,
514                   tcp_con_status(conn));
515 
516     uint8_t f2_public_key[CRYPTO_PUBLIC_KEY_SIZE];
517     uint8_t f2_secret_key[CRYPTO_SECRET_KEY_SIZE];
518     crypto_new_keypair(f2_public_key, f2_secret_key);
519     ip_port_tcp_s.port = net_htons(ports[random_u32() % NUM_PORTS]);
520     TCP_Client_Connection *conn2 = new_TCP_connection(mono_time, ip_port_tcp_s, self_public_key, f2_public_key,
521                                    f2_secret_key, nullptr);
522 
523     // The client should call this function (defined earlier) during the routing process.
524     routing_response_handler(conn, response_callback, (char *)conn + 2);
525     // The client should call this function when it receives a connection notification.
526     routing_status_handler(conn, status_callback, (void *)2);
527     // The client should call this function when
528     routing_data_handler(conn, data_callback, (void *)3);
529     // The client should call this function when sending out of band packets.
530     oob_data_handler(conn, oob_data_callback, (void *)4);
531 
532     // These integers will increment per successful callback.
533     oob_data_callback_good = response_callback_good = status_callback_good = data_callback_good = 0;
534 
535     do_TCP_connection(logger, mono_time, conn, nullptr);
536     do_TCP_connection(logger, mono_time, conn2, nullptr);
537 
538     do_TCP_server_delay(tcp_s, mono_time, 50);
539 
540     do_TCP_connection(logger, mono_time, conn, nullptr);
541     do_TCP_connection(logger, mono_time, conn2, nullptr);
542     c_sleep(50);
543 
544     uint8_t data[5] = {1, 2, 3, 4, 5};
545     memcpy(oob_pubkey, f2_public_key, CRYPTO_PUBLIC_KEY_SIZE);
546     send_oob_packet(conn2, f_public_key, data, 5);
547     send_routing_request(conn, f2_public_key);
548     send_routing_request(conn2, f_public_key);
549 
550     do_TCP_server_delay(tcp_s, mono_time, 50);
551 
552     do_TCP_connection(logger, mono_time, conn, nullptr);
553     do_TCP_connection(logger, mono_time, conn2, nullptr);
554 
555     // All callback methods save data should have run during the above network prodding.
556     ck_assert_msg(oob_data_callback_good == 1, "OOB callback not called");
557     ck_assert_msg(response_callback_good == 1, "Response callback not called.");
558     ck_assert_msg(public_key_cmp(response_callback_public_key, f2_public_key) == 0, "Wrong public key.");
559     ck_assert_msg(status_callback_good == 1, "Status callback not called.");
560     ck_assert_msg(status_callback_status == 2, "Wrong status callback status.");
561     ck_assert_msg(status_callback_connection_id == response_callback_connection_id,
562                   "Status and response callback connection IDs are not equal.");
563 
564     do_TCP_server_delay(tcp_s, mono_time, 50);
565 
566     ck_assert_msg(send_data(conn2, 0, data, 5) == 1, "Failed a send_data() call.");
567 
568     do_TCP_server_delay(tcp_s, mono_time, 50);
569 
570     do_TCP_connection(logger, mono_time, conn, nullptr);
571     do_TCP_connection(logger, mono_time, conn2, nullptr);
572     ck_assert_msg(data_callback_good == 1, "Data callback was not called.");
573     status_callback_good = 0;
574     send_disconnect_request(conn2, 0);
575 
576     do_TCP_server_delay(tcp_s, mono_time, 50);
577 
578     do_TCP_connection(logger, mono_time, conn, nullptr);
579     do_TCP_connection(logger, mono_time, conn2, nullptr);
580     ck_assert_msg(status_callback_good == 1, "Status callback not called");
581     ck_assert_msg(status_callback_status == 1, "Wrong status callback status.");
582 
583     // Kill off all connections and servers.
584     kill_TCP_server(tcp_s);
585     kill_TCP_connection(conn);
586     kill_TCP_connection(conn2);
587 
588     logger_kill(logger);
589     mono_time_free(mono_time);
590 }
591 END_TEST
592 
593 // Test how the client handles servers that don't respond.
START_TEST(test_client_invalid)594 START_TEST(test_client_invalid)
595 {
596     Mono_Time *mono_time = mono_time_new();
597     Logger *logger = logger_new();
598 
599     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
600     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
601     crypto_new_keypair(self_public_key, self_secret_key);
602 
603     uint8_t f_public_key[CRYPTO_PUBLIC_KEY_SIZE];
604     uint8_t f_secret_key[CRYPTO_SECRET_KEY_SIZE];
605     crypto_new_keypair(f_public_key, f_secret_key);
606     IP_Port ip_port_tcp_s;
607 
608     ip_port_tcp_s.port = net_htons(ports[random_u32() % NUM_PORTS]);
609     ip_port_tcp_s.ip = get_loopback();
610     TCP_Client_Connection *conn = new_TCP_connection(mono_time, ip_port_tcp_s, self_public_key, f_public_key, f_secret_key,
611                                   nullptr);
612 
613     // Run the client's main loop but not the server.
614     mono_time_update(mono_time);
615     do_TCP_connection(logger, mono_time, conn, nullptr);
616     c_sleep(50);
617 
618     // After 50ms of no response...
619     ck_assert_msg(tcp_con_status(conn) == TCP_CLIENT_CONNECTING, "Wrong status. Expected: %d, is: %d.",
620                   TCP_CLIENT_CONNECTING, tcp_con_status(conn));
621     // After 5s...
622     c_sleep(5000);
623     mono_time_update(mono_time);
624     do_TCP_connection(logger, mono_time, conn, nullptr);
625     ck_assert_msg(tcp_con_status(conn) == TCP_CLIENT_CONNECTING, "Wrong status. Expected: %d, is: %d.",
626                   TCP_CLIENT_CONNECTING, tcp_con_status(conn));
627     // 11s... (Should wait for 10 before giving up.)
628     c_sleep(6000);
629     mono_time_update(mono_time);
630     do_TCP_connection(logger, mono_time, conn, nullptr);
631     ck_assert_msg(tcp_con_status(conn) == TCP_CLIENT_DISCONNECTED, "Wrong status. Expected: %d, is: %d.",
632                   TCP_CLIENT_DISCONNECTED, tcp_con_status(conn));
633 
634     kill_TCP_connection(conn);
635 
636     logger_kill(logger);
637     mono_time_free(mono_time);
638 }
639 END_TEST
640 
641 #include "../toxcore/TCP_connection.h"
642 
643 static bool tcp_data_callback_called;
tcp_data_callback(void * object,int id,const uint8_t * data,uint16_t length,void * userdata)644 static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t length, void *userdata)
645 {
646     if (object != (void *)120397) {
647         return -1;
648     }
649 
650     if (id != 123) {
651         return -1;
652     }
653 
654     if (length != 6) {
655         return -1;
656     }
657 
658     if (memcmp(data, "Gentoo", length) != 0) {
659         return -1;
660     }
661 
662     tcp_data_callback_called = 1;
663     return 0;
664 }
665 
666 
START_TEST(test_tcp_connection)667 START_TEST(test_tcp_connection)
668 {
669     Mono_Time *mono_time = mono_time_new();
670     Logger *logger = logger_new();
671 
672     tcp_data_callback_called = 0;
673     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
674     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
675     crypto_new_keypair(self_public_key, self_secret_key);
676     TCP_Server *tcp_s = new_TCP_server(logger, USE_IPV6, NUM_PORTS, ports, self_secret_key, nullptr);
677     ck_assert_msg(public_key_cmp(tcp_server_public_key(tcp_s), self_public_key) == 0, "Wrong public key");
678 
679     TCP_Proxy_Info proxy_info;
680     proxy_info.proxy_type = TCP_PROXY_NONE;
681     crypto_new_keypair(self_public_key, self_secret_key);
682     TCP_Connections *tc_1 = new_tcp_connections(mono_time, self_secret_key, &proxy_info);
683     ck_assert_msg(public_key_cmp(tcp_connections_public_key(tc_1), self_public_key) == 0, "Wrong public key");
684 
685     crypto_new_keypair(self_public_key, self_secret_key);
686     TCP_Connections *tc_2 = new_tcp_connections(mono_time, self_secret_key, &proxy_info);
687     ck_assert_msg(public_key_cmp(tcp_connections_public_key(tc_2), self_public_key) == 0, "Wrong public key");
688 
689     IP_Port ip_port_tcp_s;
690 
691     ip_port_tcp_s.port = net_htons(ports[random_u32() % NUM_PORTS]);
692     ip_port_tcp_s.ip = get_loopback();
693 
694     int connection = new_tcp_connection_to(tc_1, tcp_connections_public_key(tc_2), 123);
695     ck_assert_msg(connection == 0, "Connection id wrong");
696     ck_assert_msg(add_tcp_relay_connection(tc_1, connection, ip_port_tcp_s, tcp_server_public_key(tcp_s)) == 0,
697                   "Could not add tcp relay to connection\n");
698 
699     ip_port_tcp_s.port = net_htons(ports[random_u32() % NUM_PORTS]);
700     connection = new_tcp_connection_to(tc_2, tcp_connections_public_key(tc_1), 123);
701     ck_assert_msg(connection == 0, "Connection id wrong");
702     ck_assert_msg(add_tcp_relay_connection(tc_2, connection, ip_port_tcp_s, tcp_server_public_key(tcp_s)) == 0,
703                   "Could not add tcp relay to connection\n");
704 
705     ck_assert_msg(new_tcp_connection_to(tc_2, tcp_connections_public_key(tc_1), 123) == -1,
706                   "Managed to read same connection\n");
707 
708     do_TCP_server_delay(tcp_s, mono_time, 50);
709 
710     do_tcp_connections(logger, tc_1, nullptr);
711     do_tcp_connections(logger, tc_2, nullptr);
712 
713     do_TCP_server_delay(tcp_s, mono_time, 50);
714 
715     do_tcp_connections(logger, tc_1, nullptr);
716     do_tcp_connections(logger, tc_2, nullptr);
717 
718     do_TCP_server_delay(tcp_s, mono_time, 50);
719 
720     do_tcp_connections(logger, tc_1, nullptr);
721     do_tcp_connections(logger, tc_2, nullptr);
722 
723     int ret = send_packet_tcp_connection(tc_1, 0, (const uint8_t *)"Gentoo", 6);
724     ck_assert_msg(ret == 0, "could not send packet.");
725     set_packet_tcp_connection_callback(tc_2, &tcp_data_callback, (void *) 120397);
726 
727     do_TCP_server_delay(tcp_s, mono_time, 50);
728 
729     do_tcp_connections(logger, tc_1, nullptr);
730     do_tcp_connections(logger, tc_2, nullptr);
731 
732     ck_assert_msg(tcp_data_callback_called, "could not recv packet.");
733     ck_assert_msg(tcp_connection_to_online_tcp_relays(tc_1, 0) == 1, "Wrong number of connected relays");
734     ck_assert_msg(kill_tcp_connection_to(tc_1, 0) == 0, "could not kill connection to\n");
735 
736     do_TCP_server_delay(tcp_s, mono_time, 50);
737 
738     do_tcp_connections(logger, tc_1, nullptr);
739     do_tcp_connections(logger, tc_2, nullptr);
740 
741     ck_assert_msg(send_packet_tcp_connection(tc_1, 0, (const uint8_t *)"Gentoo", 6) == -1, "could send packet.");
742     ck_assert_msg(kill_tcp_connection_to(tc_2, 0) == 0, "could not kill connection to\n");
743 
744     kill_TCP_server(tcp_s);
745     kill_tcp_connections(tc_1);
746     kill_tcp_connections(tc_2);
747 
748     logger_kill(logger);
749     mono_time_free(mono_time);
750 }
751 END_TEST
752 
753 static bool tcp_oobdata_callback_called;
tcp_oobdata_callback(void * object,const uint8_t * public_key,unsigned int id,const uint8_t * data,uint16_t length,void * userdata)754 static int tcp_oobdata_callback(void *object, const uint8_t *public_key, unsigned int id, const uint8_t *data,
755                                 uint16_t length, void *userdata)
756 {
757     TCP_Connections *tcp_c = (TCP_Connections *)object;
758 
759     if (length != 6) {
760         return -1;
761     }
762 
763     if (memcmp(data, "Gentoo", length) != 0) {
764         return -1;
765     }
766 
767     if (tcp_send_oob_packet(tcp_c, id, public_key, data, length) == 0) {
768         tcp_oobdata_callback_called = 1;
769     }
770 
771     return 0;
772 }
773 
START_TEST(test_tcp_connection2)774 START_TEST(test_tcp_connection2)
775 {
776     Mono_Time *mono_time = mono_time_new();
777     Logger *logger = logger_new();
778 
779     tcp_oobdata_callback_called = 0;
780     tcp_data_callback_called = 0;
781 
782     uint8_t self_public_key[CRYPTO_PUBLIC_KEY_SIZE];
783     uint8_t self_secret_key[CRYPTO_SECRET_KEY_SIZE];
784     crypto_new_keypair(self_public_key, self_secret_key);
785     TCP_Server *tcp_s = new_TCP_server(logger, USE_IPV6, NUM_PORTS, ports, self_secret_key, nullptr);
786     ck_assert_msg(public_key_cmp(tcp_server_public_key(tcp_s), self_public_key) == 0, "Wrong public key");
787 
788     TCP_Proxy_Info proxy_info;
789     proxy_info.proxy_type = TCP_PROXY_NONE;
790     crypto_new_keypair(self_public_key, self_secret_key);
791     TCP_Connections *tc_1 = new_tcp_connections(mono_time, self_secret_key, &proxy_info);
792     ck_assert_msg(public_key_cmp(tcp_connections_public_key(tc_1), self_public_key) == 0, "Wrong public key");
793 
794     crypto_new_keypair(self_public_key, self_secret_key);
795     TCP_Connections *tc_2 = new_tcp_connections(mono_time, self_secret_key, &proxy_info);
796     ck_assert_msg(public_key_cmp(tcp_connections_public_key(tc_2), self_public_key) == 0, "Wrong public key");
797 
798     IP_Port ip_port_tcp_s;
799 
800     ip_port_tcp_s.port = net_htons(ports[random_u32() % NUM_PORTS]);
801     ip_port_tcp_s.ip = get_loopback();
802 
803     int connection = new_tcp_connection_to(tc_1, tcp_connections_public_key(tc_2), 123);
804     ck_assert_msg(connection == 0, "Connection id wrong");
805     ck_assert_msg(add_tcp_relay_connection(tc_1, connection, ip_port_tcp_s, tcp_server_public_key(tcp_s)) == 0,
806                   "Could not add tcp relay to connection\n");
807 
808     ck_assert_msg(add_tcp_relay_global(tc_2, ip_port_tcp_s, tcp_server_public_key(tcp_s)) == 0,
809                   "Could not add global relay");
810 
811     do_TCP_server_delay(tcp_s, mono_time, 50);
812 
813     do_tcp_connections(logger, tc_1, nullptr);
814     do_tcp_connections(logger, tc_2, nullptr);
815 
816     do_TCP_server_delay(tcp_s, mono_time, 50);
817 
818     do_tcp_connections(logger, tc_1, nullptr);
819     do_tcp_connections(logger, tc_2, nullptr);
820 
821     do_TCP_server_delay(tcp_s, mono_time, 50);
822 
823     do_tcp_connections(logger, tc_1, nullptr);
824     do_tcp_connections(logger, tc_2, nullptr);
825 
826     int ret = send_packet_tcp_connection(tc_1, 0, (const uint8_t *)"Gentoo", 6);
827     ck_assert_msg(ret == 0, "could not send packet.");
828     set_oob_packet_tcp_connection_callback(tc_2, &tcp_oobdata_callback, tc_2);
829     set_packet_tcp_connection_callback(tc_1, &tcp_data_callback, (void *) 120397);
830 
831     do_TCP_server_delay(tcp_s, mono_time, 50);
832 
833     do_tcp_connections(logger, tc_1, nullptr);
834     do_tcp_connections(logger, tc_2, nullptr);
835 
836     ck_assert_msg(tcp_oobdata_callback_called, "could not recv packet.");
837 
838     do_TCP_server_delay(tcp_s, mono_time, 50);
839 
840     do_tcp_connections(logger, tc_1, nullptr);
841     do_tcp_connections(logger, tc_2, nullptr);
842 
843     ck_assert_msg(tcp_data_callback_called, "could not recv packet.");
844     ck_assert_msg(kill_tcp_connection_to(tc_1, 0) == 0, "could not kill connection to\n");
845 
846     kill_TCP_server(tcp_s);
847     kill_tcp_connections(tc_1);
848     kill_tcp_connections(tc_2);
849 
850     logger_kill(logger);
851     mono_time_free(mono_time);
852 }
853 END_TEST
854 
TCP_suite(void)855 static Suite *TCP_suite(void)
856 {
857     Suite *s = suite_create("TCP");
858 
859     DEFTESTCASE_SLOW(basic, 5);
860     DEFTESTCASE_SLOW(some, 10);
861     DEFTESTCASE_SLOW(client, 10);
862     DEFTESTCASE_SLOW(client_invalid, 15);
863     DEFTESTCASE_SLOW(tcp_connection, 20);
864     DEFTESTCASE_SLOW(tcp_connection2, 20);
865     return s;
866 }
867 
main(void)868 int main(void)
869 {
870     setvbuf(stdout, nullptr, _IONBF, 0);
871 
872     Suite *TCP = TCP_suite();
873     SRunner *test_runner = srunner_create(TCP);
874 
875     int number_failed = 0;
876     srunner_run_all(test_runner, CK_NORMAL);
877     number_failed = srunner_ntests_failed(test_runner);
878 
879     srunner_free(test_runner);
880 
881     return number_failed;
882 }
883