summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoriphydf <iphydf@users.noreply.github.com>2016-08-31 19:12:19 +0100
committeriphydf <iphydf@users.noreply.github.com>2016-08-31 20:04:16 +0100
commit633da98ae69866efb195e00d9a3a22ace6bada66 (patch)
tree875535f3d2257c4ea5bb97a553b2f1beab4a1590
parent6356eb4e4fe407fa7870f2a685d0d08b5c2ec5bb (diff)
Add braces to all if statements.
-rw-r--r--auto_tests/TCP_test.c51
-rw-r--r--auto_tests/assoc_test.c3
-rw-r--r--auto_tests/crypto_test.c6
-rw-r--r--auto_tests/dht_test.c52
-rw-r--r--auto_tests/encryptsave_test.c3
-rw-r--r--auto_tests/messenger_test.c14
-rw-r--r--auto_tests/onion_test.c37
-rw-r--r--auto_tests/tox_test.c133
-rw-r--r--auto_tests/toxav_basic_test.c24
-rw-r--r--auto_tests/toxav_many_test.c6
-rw-r--r--other/DHT_bootstrap.c3
-rw-r--r--other/bootstrap_daemon/src/tox-bootstrapd.c3
-rw-r--r--other/bootstrap_node_packets.c9
-rw-r--r--testing/DHT_test.c26
-rw-r--r--testing/Messenger_test.c16
-rw-r--r--testing/av_test.c38
-rw-r--r--testing/dns3_test.c22
-rw-r--r--testing/irc_syncbot.c48
-rw-r--r--testing/misc_tools.c12
-rw-r--r--testing/nTox.c147
-rw-r--r--testing/tox_shell.c11
-rw-r--r--testing/tox_sync.c38
-rw-r--r--toxav/audio.c39
-rw-r--r--toxav/bwcontroller.c24
-rw-r--r--toxav/group.c85
-rw-r--r--toxav/msi.c59
-rw-r--r--toxav/rtp.c45
-rw-r--r--toxav/toxav.c118
-rw-r--r--toxav/video.c28
-rw-r--r--toxcore/DHT.c416
-rw-r--r--toxcore/LAN_discovery.c63
-rw-r--r--toxcore/Messenger.c589
-rw-r--r--toxcore/TCP_client.c135
-rw-r--r--toxcore/TCP_connection.c222
-rw-r--r--toxcore/TCP_server.c168
-rw-r--r--toxcore/assoc.c275
-rw-r--r--toxcore/crypto_core.c42
-rw-r--r--toxcore/friend_connection.c153
-rw-r--r--toxcore/friend_requests.c27
-rw-r--r--toxcore/group.c485
-rw-r--r--toxcore/logger.c3
-rw-r--r--toxcore/net_crypto.c519
-rw-r--r--toxcore/network.c132
-rw-r--r--toxcore/onion.c165
-rw-r--r--toxcore/onion_announce.c96
-rw-r--r--toxcore/onion_client.c351
-rw-r--r--toxcore/ping.c81
-rw-r--r--toxcore/ping_array.c30
-rw-r--r--toxcore/tox.c9
-rw-r--r--toxcore/util.c25
-rw-r--r--toxdns/toxdns.c18
-rw-r--r--toxencryptsave/toxencryptsave.c8
52 files changed, 3386 insertions, 1726 deletions
diff --git a/auto_tests/TCP_test.c b/auto_tests/TCP_test.c
index 06049467..2721fbd2 100644
--- a/auto_tests/TCP_test.c
+++ b/auto_tests/TCP_test.c
@@ -190,8 +190,9 @@ int write_packet_TCP_secure_connection(struct sec_TCP_con *con, uint8_t *data, u
190 memcpy(packet, &c_length, sizeof(uint16_t)); 190 memcpy(packet, &c_length, sizeof(uint16_t));
191 int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t)); 191 int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t));
192 192
193 if ((unsigned int)len != (sizeof(packet) - sizeof(uint16_t))) 193 if ((unsigned int)len != (sizeof(packet) - sizeof(uint16_t))) {
194 return -1; 194 return -1;
195 }
195 196
196 increment_nonce(con->sent_nonce); 197 increment_nonce(con->sent_nonce);
197 198
@@ -309,8 +310,9 @@ static uint8_t response_callback_connection_id;
309static uint8_t response_callback_public_key[crypto_box_PUBLICKEYBYTES]; 310static uint8_t response_callback_public_key[crypto_box_PUBLICKEYBYTES];
310static int response_callback(void *object, uint8_t connection_id, const uint8_t *public_key) 311static int response_callback(void *object, uint8_t connection_id, const uint8_t *public_key)
311{ 312{
312 if (set_tcp_connection_number(object - 2, connection_id, 7) != 0) 313 if (set_tcp_connection_number(object - 2, connection_id, 7) != 0) {
313 return 1; 314 return 1;
315 }
314 316
315 response_callback_connection_id = connection_id; 317 response_callback_connection_id = connection_id;
316 memcpy(response_callback_public_key, public_key, crypto_box_PUBLICKEYBYTES); 318 memcpy(response_callback_public_key, public_key, crypto_box_PUBLICKEYBYTES);
@@ -322,11 +324,13 @@ static uint8_t status_callback_connection_id;
322static uint8_t status_callback_status; 324static uint8_t status_callback_status;
323static int status_callback(void *object, uint32_t number, uint8_t connection_id, uint8_t status) 325static int status_callback(void *object, uint32_t number, uint8_t connection_id, uint8_t status)
324{ 326{
325 if (object != (void *)2) 327 if (object != (void *)2) {
326 return 1; 328 return 1;
329 }
327 330
328 if (number != 7) 331 if (number != 7) {
329 return 1; 332 return 1;
333 }
330 334
331 status_callback_connection_id = connection_id; 335 status_callback_connection_id = connection_id;
332 status_callback_status = status; 336 status_callback_status = status;
@@ -337,14 +341,17 @@ static int data_callback_good;
337static int data_callback(void *object, uint32_t number, uint8_t connection_id, const uint8_t *data, uint16_t length, 341static int data_callback(void *object, uint32_t number, uint8_t connection_id, const uint8_t *data, uint16_t length,
338 void *userdata) 342 void *userdata)
339{ 343{
340 if (object != (void *)3) 344 if (object != (void *)3) {
341 return 1; 345 return 1;
346 }
342 347
343 if (number != 7) 348 if (number != 7) {
344 return 1; 349 return 1;
350 }
345 351
346 if (length != 5) 352 if (length != 5) {
347 return 1; 353 return 1;
354 }
348 355
349 if (data[0] == 1 && data[1] == 2 && data[2] == 3 && data[3] == 4 && data[4] == 5) { 356 if (data[0] == 1 && data[1] == 2 && data[2] == 3 && data[3] == 4 && data[4] == 5) {
350 data_callback_good++; 357 data_callback_good++;
@@ -359,14 +366,17 @@ static uint8_t oob_pubkey[crypto_box_PUBLICKEYBYTES];
359static int oob_data_callback(void *object, const uint8_t *public_key, const uint8_t *data, uint16_t length, 366static int oob_data_callback(void *object, const uint8_t *public_key, const uint8_t *data, uint16_t length,
360 void *userdata) 367 void *userdata)
361{ 368{
362 if (object != (void *)4) 369 if (object != (void *)4) {
363 return 1; 370 return 1;
371 }
364 372
365 if (length != 5) 373 if (length != 5) {
366 return 1; 374 return 1;
375 }
367 376
368 if (public_key_cmp(public_key, oob_pubkey) != 0) 377 if (public_key_cmp(public_key, oob_pubkey) != 0) {
369 return 1; 378 return 1;
379 }
370 380
371 if (data[0] == 1 && data[1] == 2 && data[2] == 3 && data[3] == 4 && data[4] == 5) { 381 if (data[0] == 1 && data[1] == 2 && data[2] == 3 && data[3] == 4 && data[4] == 5) {
372 oob_data_callback_good++; 382 oob_data_callback_good++;
@@ -515,17 +525,21 @@ END_TEST
515_Bool tcp_data_callback_called; 525_Bool tcp_data_callback_called;
516static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t length, void *userdata) 526static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t length, void *userdata)
517{ 527{
518 if (object != (void *)120397) 528 if (object != (void *)120397) {
519 return -1; 529 return -1;
530 }
520 531
521 if (id != 123) 532 if (id != 123) {
522 return -1; 533 return -1;
534 }
523 535
524 if (length != 6) 536 if (length != 6) {
525 return -1; 537 return -1;
538 }
526 539
527 if (memcmp(data, "Gentoo", length) != 0) 540 if (memcmp(data, "Gentoo", length) != 0) {
528 return -1; 541 return -1;
542 }
529 543
530 tcp_data_callback_called = 1; 544 tcp_data_callback_called = 1;
531 return 0; 545 return 0;
@@ -621,14 +635,17 @@ _Bool tcp_oobdata_callback_called;
621static int tcp_oobdata_callback(void *object, const uint8_t *public_key, unsigned int id, const uint8_t *data, 635static int tcp_oobdata_callback(void *object, const uint8_t *public_key, unsigned int id, const uint8_t *data,
622 uint16_t length) 636 uint16_t length)
623{ 637{
624 if (length != 6) 638 if (length != 6) {
625 return -1; 639 return -1;
640 }
626 641
627 if (memcmp(data, "Gentoo", length) != 0) 642 if (memcmp(data, "Gentoo", length) != 0) {
628 return -1; 643 return -1;
644 }
629 645
630 if (tcp_send_oob_packet(object, id, public_key, data, length) == 0) 646 if (tcp_send_oob_packet(object, id, public_key, data, length) == 0) {
631 tcp_oobdata_callback_called = 1; 647 tcp_oobdata_callback_called = 1;
648 }
632 649
633 return 0; 650 return 0;
634} 651}
diff --git a/auto_tests/assoc_test.c b/auto_tests/assoc_test.c
index 837372fc..05c8d2f3 100644
--- a/auto_tests/assoc_test.c
+++ b/auto_tests/assoc_test.c
@@ -123,8 +123,9 @@ START_TEST(test_fillup)
123 123
124 for (i = 0; i < 8; ++i) { 124 for (i = 0; i < 8; ++i) {
125 for (j = 0; j < 8; ++j) { 125 for (j = 0; j < 8; ++j) {
126 if (id_equal(entri[j]->public_key, closest[i].id)) 126 if (id_equal(entri[j]->public_key, closest[i].id)) {
127 ++good; 127 ++good;
128 }
128 } 129 }
129 } 130 }
130 131
diff --git a/auto_tests/crypto_test.c b/auto_tests/crypto_test.c
index 4a77b49a..e7201a34 100644
--- a/auto_tests/crypto_test.c
+++ b/auto_tests/crypto_test.c
@@ -285,8 +285,9 @@ void increment_nonce_number_cmp(uint8_t *nonce, uint32_t num)
285 for (i = crypto_box_NONCEBYTES - sizeof(num1); i != 0; --i) { 285 for (i = crypto_box_NONCEBYTES - sizeof(num1); i != 0; --i) {
286 ++nonce[i - 1]; 286 ++nonce[i - 1];
287 287
288 if (nonce[i - 1] != 0) 288 if (nonce[i - 1] != 0) {
289 break; 289 break;
290 }
290 } 291 }
291 } 292 }
292 293
@@ -300,8 +301,9 @@ START_TEST(test_increment_nonce)
300 301
301 uint8_t n[crypto_box_NONCEBYTES]; 302 uint8_t n[crypto_box_NONCEBYTES];
302 303
303 for (i = 0; i < crypto_box_NONCEBYTES; ++i) 304 for (i = 0; i < crypto_box_NONCEBYTES; ++i) {
304 n[i] = rand(); 305 n[i] = rand();
306 }
305 307
306 uint8_t n1[crypto_box_NONCEBYTES]; 308 uint8_t n1[crypto_box_NONCEBYTES];
307 309
diff --git a/auto_tests/dht_test.c b/auto_tests/dht_test.c
index 369356b5..b5d979f4 100644
--- a/auto_tests/dht_test.c
+++ b/auto_tests/dht_test.c
@@ -47,10 +47,11 @@ void mark_all_good(Client_data *list, uint32_t length, uint8_t ipv6)
47 uint32_t i; 47 uint32_t i;
48 48
49 for (i = 0; i < length; ++i) { 49 for (i = 0; i < length; ++i) {
50 if (ipv6) 50 if (ipv6) {
51 mark_good(&list[i].assoc6); 51 mark_good(&list[i].assoc6);
52 else 52 } else {
53 mark_good(&list[i].assoc4); 53 mark_good(&list[i].assoc4);
54 }
54 } 55 }
55} 56}
56 57
@@ -60,9 +61,11 @@ uint8_t is_furthest(const uint8_t *comp_client_id, Client_data *list, uint32_t l
60{ 61{
61 uint32_t i; 62 uint32_t i;
62 63
63 for (i = 0; i < length; ++i) 64 for (i = 0; i < length; ++i) {
64 if (id_closest(comp_client_id, public_key, list[i].public_key) == 1) 65 if (id_closest(comp_client_id, public_key, list[i].public_key) == 1) {
65 return 0; 66 return 0;
67 }
68 }
66 69
67 return 1; 70 return 1;
68} 71}
@@ -71,9 +74,11 @@ int client_in_list(Client_data *list, uint32_t length, const uint8_t *public_key
71{ 74{
72 int i; 75 int i;
73 76
74 for (i = 0; i < (int)length; ++i) 77 for (i = 0; i < (int)length; ++i) {
75 if (id_equal(public_key, list[i].public_key)) 78 if (id_equal(public_key, list[i].public_key)) {
76 return i; 79 return i;
80 }
81 }
77 82
78 return -1; 83 return -1;
79} 84}
@@ -120,8 +125,11 @@ void test_addto_lists_update(DHT *dht,
120 ipport_copy(&test_ipp, ipv6 ? &list[test1].assoc6.ip_port : &list[test1].assoc4.ip_port); 125 ipport_copy(&test_ipp, ipv6 ? &list[test1].assoc6.ip_port : &list[test1].assoc4.ip_port);
121 id_copy(test_id, list[test2].public_key); 126 id_copy(test_id, list[test2].public_key);
122 127
123 if (ipv6) list[test2].assoc6.ip_port.port = -1; 128 if (ipv6) {
124 else list[test2].assoc4.ip_port.port = -1; 129 list[test2].assoc6.ip_port.port = -1;
130 } else {
131 list[test2].assoc4.ip_port.port = -1;
132 }
125 133
126 used = addto_lists(dht, test_ipp, test_id); 134 used = addto_lists(dht, test_ipp, test_id);
127 ck_assert_msg(used >= 1, "Wrong number of added clients"); 135 ck_assert_msg(used >= 1, "Wrong number of added clients");
@@ -136,8 +144,11 @@ void test_addto_lists_update(DHT *dht,
136 ipport_copy(&test_ipp, ipv6 ? &list[test2].assoc6.ip_port : &list[test2].assoc4.ip_port); 144 ipport_copy(&test_ipp, ipv6 ? &list[test2].assoc6.ip_port : &list[test2].assoc4.ip_port);
137 id_copy(test_id, list[test1].public_key); 145 id_copy(test_id, list[test1].public_key);
138 146
139 if (ipv6) list[test1].assoc6.ip_port.port = -1; 147 if (ipv6) {
140 else list[test1].assoc4.ip_port.port = -1; 148 list[test1].assoc6.ip_port.port = -1;
149 } else {
150 list[test1].assoc4.ip_port.port = -1;
151 }
141 152
142 used = addto_lists(dht, test_ipp, test_id); 153 used = addto_lists(dht, test_ipp, test_id);
143 ck_assert_msg(used >= 1, "Wrong number of added clients"); 154 ck_assert_msg(used >= 1, "Wrong number of added clients");
@@ -441,8 +452,9 @@ void test_list_main()
441 452
442 for (j = 0; j < NUM_DHT; ++j) { 453 for (j = 0; j < NUM_DHT; ++j) {
443 for (i = 0; i < NUM_DHT; ++i) { 454 for (i = 0; i < NUM_DHT; ++i) {
444 if (i == j) 455 if (i == j) {
445 continue; 456 continue;
457 }
446 458
447 IP_Port ip_port; 459 IP_Port ip_port;
448 ip_init(&ip_port.ip, 0); 460 ip_init(&ip_port.ip, 0);
@@ -467,15 +479,17 @@ void test_list_main()
467 for (l = 0; l < NUM_DHT; ++l) { 479 for (l = 0; l < NUM_DHT; ++l) {
468 for (i = 0; i < MAX_FRIEND_CLIENTS; ++i) { 480 for (i = 0; i < MAX_FRIEND_CLIENTS; ++i) {
469 for (j = 1; j < NUM_DHT; ++j) { 481 for (j = 1; j < NUM_DHT; ++j) {
470 if (memcmp(cmp_list1[l][i], dhts[(l + j) % NUM_DHT]->self_public_key, crypto_box_PUBLICKEYBYTES) != 0) 482 if (memcmp(cmp_list1[l][i], dhts[(l + j) % NUM_DHT]->self_public_key, crypto_box_PUBLICKEYBYTES) != 0) {
471 continue; 483 continue;
484 }
472 485
473 unsigned int count = 0; 486 unsigned int count = 0;
474 487
475 for (k = 0; k < LCLIENT_LIST; ++k) { 488 for (k = 0; k < LCLIENT_LIST; ++k) {
476 if (memcmp(dhts[l]->self_public_key, dhts[(l + j) % NUM_DHT]->close_clientlist[k].public_key, 489 if (memcmp(dhts[l]->self_public_key, dhts[(l + j) % NUM_DHT]->close_clientlist[k].public_key,
477 crypto_box_PUBLICKEYBYTES) == 0) 490 crypto_box_PUBLICKEYBYTES) == 0) {
478 ++count; 491 ++count;
492 }
479 } 493 }
480 494
481 if (count != 1) { 495 if (count != 1) {
@@ -504,8 +518,9 @@ void test_list_main()
504 count = 0; 518 count = 0;
505 519
506 for (k = 0; k < MAX_SENT_NODES; ++k) { 520 for (k = 0; k < MAX_SENT_NODES; ++k) {
507 if (memcmp(dhts[l]->self_public_key, ln[k].public_key, crypto_box_PUBLICKEYBYTES) == 0) 521 if (memcmp(dhts[l]->self_public_key, ln[k].public_key, crypto_box_PUBLICKEYBYTES) == 0) {
508 ++count; 522 ++count;
523 }
509 } 524 }
510 525
511 ck_assert_msg(count == 1, "Nodes in search don't know ip of friend. %u %u %u", i, j, count); 526 ck_assert_msg(count == 1, "Nodes in search don't know ip of friend. %u %u %u", i, j, count);
@@ -534,8 +549,9 @@ START_TEST(test_list)
534{ 549{
535 unsigned int i; 550 unsigned int i;
536 551
537 for (i = 0; i < 10; ++i) 552 for (i = 0; i < 10; ++i) {
538 test_list_main(); 553 test_list_main();
554 }
539} 555}
540END_TEST 556END_TEST
541 557
@@ -582,8 +598,9 @@ loop_top:
582 pairs[i].tox2 = (pairs[i].tox1 + (rand() % (NUM_DHT - 1)) + 1) % NUM_DHT; 598 pairs[i].tox2 = (pairs[i].tox1 + (rand() % (NUM_DHT - 1)) + 1) % NUM_DHT;
583 599
584 for (j = 0; j < i; ++j) { 600 for (j = 0; j < i; ++j) {
585 if (pairs[j].tox2 == pairs[i].tox2 && pairs[j].tox1 == pairs[i].tox1) 601 if (pairs[j].tox2 == pairs[i].tox2 && pairs[j].tox1 == pairs[i].tox1) {
586 goto loop_top; 602 goto loop_top;
603 }
587 } 604 }
588 605
589 uint16_t lock_count = 0; 606 uint16_t lock_count = 0;
@@ -606,8 +623,9 @@ loop_top:
606 for (i = 0; i < NUM_DHT_FRIENDS; ++i) { 623 for (i = 0; i < NUM_DHT_FRIENDS; ++i) {
607 IP_Port a; 624 IP_Port a;
608 625
609 if (DHT_getfriendip(dhts[pairs[i].tox2], dhts[pairs[i].tox1]->self_public_key, &a) == 1) 626 if (DHT_getfriendip(dhts[pairs[i].tox2], dhts[pairs[i].tox1]->self_public_key, &a) == 1) {
610 ++counter; 627 ++counter;
628 }
611 } 629 }
612 630
613 if (counter == NUM_DHT_FRIENDS) { 631 if (counter == NUM_DHT_FRIENDS) {
diff --git a/auto_tests/encryptsave_test.c b/auto_tests/encryptsave_test.c
index a2a95758..d27f7d6b 100644
--- a/auto_tests/encryptsave_test.c
+++ b/auto_tests/encryptsave_test.c
@@ -30,8 +30,9 @@ unsigned char known_key2[crypto_box_BEFORENMBYTES] = {0x7a, 0xfa, 0x95, 0x45, 0x
30/* cause I'm shameless */ 30/* cause I'm shameless */
31void accept_friend_request(Tox *m, const uint8_t *public_key, const uint8_t *data, size_t length, void *userdata) 31void accept_friend_request(Tox *m, const uint8_t *public_key, const uint8_t *data, size_t length, void *userdata)
32{ 32{
33 if (*((uint32_t *)userdata) != 974536) 33 if (*((uint32_t *)userdata) != 974536) {
34 return; 34 return;
35 }
35 36
36 if (length == 7 && memcmp("Gentoo", data, 7) == 0) { 37 if (length == 7 && memcmp("Gentoo", data, 7) == 0) {
37 tox_friend_add_norequest(m, public_key, 0); 38 tox_friend_add_norequest(m, public_key, 0);
diff --git a/auto_tests/messenger_test.c b/auto_tests/messenger_test.c
index 9d72ca46..b8559b17 100644
--- a/auto_tests/messenger_test.c
+++ b/auto_tests/messenger_test.c
@@ -237,9 +237,9 @@ START_TEST(test_dht_state_saveloadsave)
237 237
238 int res = DHT_load(m->dht, buffer + extra, size); 238 int res = DHT_load(m->dht, buffer + extra, size);
239 239
240 if (res == -1) 240 if (res == -1) {
241 ck_assert_msg(res == 0, "Failed to load back stored buffer: res == -1"); 241 ck_assert_msg(res == 0, "Failed to load back stored buffer: res == -1");
242 else { 242 } else {
243 char msg[128]; 243 char msg[128];
244 size_t offset = res >> 4; 244 size_t offset = res >> 4;
245 uint8_t *ptr = buffer + extra + offset; 245 uint8_t *ptr = buffer + extra + offset;
@@ -279,9 +279,9 @@ START_TEST(test_messenger_state_saveloadsave)
279 279
280 int res = messenger_load(m, buffer + extra, size); 280 int res = messenger_load(m, buffer + extra, size);
281 281
282 if (res == -1) 282 if (res == -1) {
283 ck_assert_msg(res == 0, "Failed to load back stored buffer: res == -1"); 283 ck_assert_msg(res == 0, "Failed to load back stored buffer: res == -1");
284 else { 284 } else {
285 char msg[128]; 285 char msg[128];
286 size_t offset = res >> 4; 286 size_t offset = res >> 4;
287 uint8_t *ptr = buffer + extra + offset; 287 uint8_t *ptr = buffer + extra + offset;
@@ -340,15 +340,17 @@ int main(int argc, char *argv[])
340 m = new_messenger(NULL, &options, 0); 340 m = new_messenger(NULL, &options, 0);
341 341
342 /* setup a default friend and friendnum */ 342 /* setup a default friend and friendnum */
343 if (m_addfriend_norequest(m, (uint8_t *)friend_id) < 0) 343 if (m_addfriend_norequest(m, (uint8_t *)friend_id) < 0) {
344 fputs("m_addfriend_norequest() failed on a valid ID!\n" 344 fputs("m_addfriend_norequest() failed on a valid ID!\n"
345 "this was CRITICAL to the test, and the build WILL fail.\n" 345 "this was CRITICAL to the test, and the build WILL fail.\n"
346 "the tests will continue now...\n\n", stderr); 346 "the tests will continue now...\n\n", stderr);
347 }
347 348
348 if ((friend_id_num = getfriend_id(m, (uint8_t *)friend_id)) < 0) 349 if ((friend_id_num = getfriend_id(m, (uint8_t *)friend_id)) < 0) {
349 fputs("getfriend_id() failed on a valid ID!\n" 350 fputs("getfriend_id() failed on a valid ID!\n"
350 "this was CRITICAL to the test, and the build WILL fail.\n" 351 "this was CRITICAL to the test, and the build WILL fail.\n"
351 "the tests will continue now...\n\n", stderr); 352 "the tests will continue now...\n\n", stderr);
353 }
352 354
353 srunner_run_all(test_runner, CK_NORMAL); 355 srunner_run_all(test_runner, CK_NORMAL);
354 number_failed = srunner_ntests_failed(test_runner); 356 number_failed = srunner_ntests_failed(test_runner);
diff --git a/auto_tests/onion_test.c b/auto_tests/onion_test.c
index 08904218..fe764517 100644
--- a/auto_tests/onion_test.c
+++ b/auto_tests/onion_test.c
@@ -34,12 +34,14 @@ static int handle_test_1(void *object, IP_Port source, const uint8_t *packet, ui
34{ 34{
35 Onion *onion = object; 35 Onion *onion = object;
36 36
37 if (memcmp(packet, "Install Gentoo", sizeof("Install Gentoo")) != 0) 37 if (memcmp(packet, "Install Gentoo", sizeof("Install Gentoo")) != 0) {
38 return 1; 38 return 1;
39 }
39 40
40 if (send_onion_response(onion->net, source, (uint8_t *)"install gentoo", sizeof("install gentoo"), 41 if (send_onion_response(onion->net, source, (uint8_t *)"install gentoo", sizeof("install gentoo"),
41 packet + sizeof("Install Gentoo")) == -1) 42 packet + sizeof("Install Gentoo")) == -1) {
42 return 1; 43 return 1;
44 }
43 45
44 handled_test_1 = 1; 46 handled_test_1 = 1;
45 return 0; 47 return 0;
@@ -48,11 +50,13 @@ static int handle_test_1(void *object, IP_Port source, const uint8_t *packet, ui
48static int handled_test_2; 50static int handled_test_2;
49static int handle_test_2(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata) 51static int handle_test_2(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata)
50{ 52{
51 if (length != sizeof("install Gentoo")) 53 if (length != sizeof("install Gentoo")) {
52 return 1; 54 return 1;
55 }
53 56
54 if (memcmp(packet, (uint8_t *)"install gentoo", sizeof("install gentoo")) != 0) 57 if (memcmp(packet, (uint8_t *)"install gentoo", sizeof("install gentoo")) != 0) {
55 return 1; 58 return 1;
59 }
56 60
57 handled_test_2 = 1; 61 handled_test_2 = 1;
58 return 0; 62 return 0;
@@ -77,8 +81,9 @@ static int handle_test_3(void *object, IP_Port source, const uint8_t *packet, ui
77 Onion *onion = object; 81 Onion *onion = object;
78 82
79 if (length != (1 + crypto_box_NONCEBYTES + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + 1 + crypto_hash_sha256_BYTES + 83 if (length != (1 + crypto_box_NONCEBYTES + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + 1 + crypto_hash_sha256_BYTES +
80 crypto_box_MACBYTES)) 84 crypto_box_MACBYTES)) {
81 return 1; 85 return 1;
86 }
82 87
83 uint8_t plain[1 + crypto_hash_sha256_BYTES]; 88 uint8_t plain[1 + crypto_hash_sha256_BYTES];
84 //print_client_id(packet, length); 89 //print_client_id(packet, length);
@@ -86,12 +91,14 @@ static int handle_test_3(void *object, IP_Port source, const uint8_t *packet, ui
86 packet + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES, 91 packet + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES,
87 1 + crypto_hash_sha256_BYTES + crypto_box_MACBYTES, plain); 92 1 + crypto_hash_sha256_BYTES + crypto_box_MACBYTES, plain);
88 93
89 if (len == -1) 94 if (len == -1) {
90 return 1; 95 return 1;
96 }
91 97
92 98
93 if (memcmp(packet + 1, sb_data, ONION_ANNOUNCE_SENDBACK_DATA_LENGTH) != 0) 99 if (memcmp(packet + 1, sb_data, ONION_ANNOUNCE_SENDBACK_DATA_LENGTH) != 0) {
94 return 1; 100 return 1;
101 }
95 102
96 memcpy(test_3_ping_id, plain + 1, crypto_hash_sha256_BYTES); 103 memcpy(test_3_ping_id, plain + 1, crypto_hash_sha256_BYTES);
97 //print_client_id(test_3_ping_id, sizeof(test_3_ping_id)); 104 //print_client_id(test_3_ping_id, sizeof(test_3_ping_id));
@@ -105,22 +112,27 @@ static int handle_test_4(void *object, IP_Port source, const uint8_t *packet, ui
105{ 112{
106 Onion *onion = object; 113 Onion *onion = object;
107 114
108 if (length != (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + sizeof("Install gentoo") + crypto_box_MACBYTES)) 115 if (length != (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + sizeof("Install gentoo") +
116 crypto_box_MACBYTES)) {
109 return 1; 117 return 1;
118 }
110 119
111 uint8_t plain[sizeof("Install gentoo")] = {0}; 120 uint8_t plain[sizeof("Install gentoo")] = {0};
112 121
113 if (memcmp(nonce, packet + 1, crypto_box_NONCEBYTES) != 0) 122 if (memcmp(nonce, packet + 1, crypto_box_NONCEBYTES) != 0) {
114 return 1; 123 return 1;
124 }
115 125
116 int len = decrypt_data(packet + 1 + crypto_box_NONCEBYTES, onion->dht->self_secret_key, packet + 1, 126 int len = decrypt_data(packet + 1 + crypto_box_NONCEBYTES, onion->dht->self_secret_key, packet + 1,
117 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, sizeof("Install gentoo") + crypto_box_MACBYTES, plain); 127 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, sizeof("Install gentoo") + crypto_box_MACBYTES, plain);
118 128
119 if (len == -1) 129 if (len == -1) {
120 return 1; 130 return 1;
131 }
121 132
122 if (memcmp(plain, "Install gentoo", sizeof("Install gentoo")) != 0) 133 if (memcmp(plain, "Install gentoo", sizeof("Install gentoo")) != 0) {
123 return 1; 134 return 1;
135 }
124 136
125 handled_test_4 = 1; 137 handled_test_4 = 1;
126 return 0; 138 return 0;
@@ -278,8 +290,9 @@ Onions *new_onions(uint16_t port)
278 TCP_Proxy_Info inf = {{{0}}}; 290 TCP_Proxy_Info inf = {{{0}}};
279 on->onion_c = new_onion_client(new_net_crypto(NULL, dht, &inf)); 291 on->onion_c = new_onion_client(new_net_crypto(NULL, dht, &inf));
280 292
281 if (on->onion && on->onion_a && on->onion_c) 293 if (on->onion && on->onion_a && on->onion_c) {
282 return on; 294 return on;
295 }
283 296
284 return NULL; 297 return NULL;
285} 298}
diff --git a/auto_tests/tox_test.c b/auto_tests/tox_test.c
index c436636e..a8fba35d 100644
--- a/auto_tests/tox_test.c
+++ b/auto_tests/tox_test.c
@@ -44,8 +44,9 @@
44 44
45void accept_friend_request(Tox *m, const uint8_t *public_key, const uint8_t *data, size_t length, void *userdata) 45void accept_friend_request(Tox *m, const uint8_t *public_key, const uint8_t *data, size_t length, void *userdata)
46{ 46{
47 if (*((uint32_t *)userdata) != 974536) 47 if (*((uint32_t *)userdata) != 974536) {
48 return; 48 return;
49 }
49 50
50 if (length == 7 && memcmp("Gentoo", data, 7) == 0) { 51 if (length == 7 && memcmp("Gentoo", data, 7) == 0) {
51 tox_friend_add_norequest(m, public_key, 0); 52 tox_friend_add_norequest(m, public_key, 0);
@@ -56,8 +57,9 @@ uint32_t messages_received;
56void print_message(Tox *m, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const uint8_t *string, size_t length, 57void print_message(Tox *m, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const uint8_t *string, size_t length,
57 void *userdata) 58 void *userdata)
58{ 59{
59 if (*((uint32_t *)userdata) != 974536) 60 if (*((uint32_t *)userdata) != 974536) {
60 return; 61 return;
62 }
61 63
62 if (type != TOX_MESSAGE_TYPE_NORMAL) { 64 if (type != TOX_MESSAGE_TYPE_NORMAL) {
63 ck_abort_msg("Bad type"); 65 ck_abort_msg("Bad type");
@@ -66,42 +68,49 @@ void print_message(Tox *m, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const u
66 uint8_t cmp_msg[TOX_MAX_MESSAGE_LENGTH]; 68 uint8_t cmp_msg[TOX_MAX_MESSAGE_LENGTH];
67 memset(cmp_msg, 'G', sizeof(cmp_msg)); 69 memset(cmp_msg, 'G', sizeof(cmp_msg));
68 70
69 if (length == TOX_MAX_MESSAGE_LENGTH && memcmp(string, cmp_msg, sizeof(cmp_msg)) == 0) 71 if (length == TOX_MAX_MESSAGE_LENGTH && memcmp(string, cmp_msg, sizeof(cmp_msg)) == 0) {
70 ++messages_received; 72 ++messages_received;
73 }
71} 74}
72 75
73uint32_t name_changes; 76uint32_t name_changes;
74 77
75void print_nickchange(Tox *m, uint32_t friendnumber, const uint8_t *string, size_t length, void *userdata) 78void print_nickchange(Tox *m, uint32_t friendnumber, const uint8_t *string, size_t length, void *userdata)
76{ 79{
77 if (*((uint32_t *)userdata) != 974536) 80 if (*((uint32_t *)userdata) != 974536) {
78 return; 81 return;
82 }
79 83
80 if (length == sizeof("Gentoo") && memcmp(string, "Gentoo", sizeof("Gentoo")) == 0) 84 if (length == sizeof("Gentoo") && memcmp(string, "Gentoo", sizeof("Gentoo")) == 0) {
81 ++name_changes; 85 ++name_changes;
86 }
82} 87}
83 88
84uint32_t status_m_changes; 89uint32_t status_m_changes;
85void print_status_m_change(Tox *tox, uint32_t friend_number, const uint8_t *message, size_t length, void *user_data) 90void print_status_m_change(Tox *tox, uint32_t friend_number, const uint8_t *message, size_t length, void *user_data)
86{ 91{
87 if (*((uint32_t *)user_data) != 974536) 92 if (*((uint32_t *)user_data) != 974536) {
88 return; 93 return;
94 }
89 95
90 if (length == sizeof("Installing Gentoo") && memcmp(message, "Installing Gentoo", sizeof("Installing Gentoo")) == 0) 96 if (length == sizeof("Installing Gentoo") && memcmp(message, "Installing Gentoo", sizeof("Installing Gentoo")) == 0) {
91 ++status_m_changes; 97 ++status_m_changes;
98 }
92} 99}
93 100
94uint32_t typing_changes; 101uint32_t typing_changes;
95 102
96void print_typingchange(Tox *m, uint32_t friendnumber, bool typing, void *userdata) 103void print_typingchange(Tox *m, uint32_t friendnumber, bool typing, void *userdata)
97{ 104{
98 if (*((uint32_t *)userdata) != 974536) 105 if (*((uint32_t *)userdata) != 974536) {
99 return; 106 return;
107 }
100 108
101 if (!typing) 109 if (!typing) {
102 typing_changes = 1; 110 typing_changes = 1;
103 else 111 } else {
104 typing_changes = 2; 112 typing_changes = 2;
113 }
105} 114}
106 115
107uint32_t custom_packet; 116uint32_t custom_packet;
@@ -110,8 +119,9 @@ void handle_custom_packet(Tox *m, uint32_t friend_num, const uint8_t *data, size
110{ 119{
111 uint8_t number = *((uint32_t *)object); 120 uint8_t number = *((uint32_t *)object);
112 121
113 if (len != TOX_MAX_CUSTOM_PACKET_SIZE) 122 if (len != TOX_MAX_CUSTOM_PACKET_SIZE) {
114 return; 123 return;
124 }
115 125
116 uint8_t f_data[len]; 126 uint8_t f_data[len];
117 memset(f_data, number, len); 127 memset(f_data, number, len);
@@ -135,8 +145,9 @@ uint64_t file_size;
135void tox_file_receive(Tox *tox, uint32_t friend_number, uint32_t file_number, uint32_t kind, uint64_t filesize, 145void tox_file_receive(Tox *tox, uint32_t friend_number, uint32_t file_number, uint32_t kind, uint64_t filesize,
136 const uint8_t *filename, size_t filename_length, void *userdata) 146 const uint8_t *filename, size_t filename_length, void *userdata)
137{ 147{
138 if (*((uint32_t *)userdata) != 974536) 148 if (*((uint32_t *)userdata) != 974536) {
139 return; 149 return;
150 }
140 151
141 if (kind != TOX_FILE_KIND_DATA) { 152 if (kind != TOX_FILE_KIND_DATA) {
142 ck_abort_msg("Bad kind"); 153 ck_abort_msg("Bad kind");
@@ -201,12 +212,14 @@ uint32_t sendf_ok;
201void file_print_control(Tox *tox, uint32_t friend_number, uint32_t file_number, TOX_FILE_CONTROL control, 212void file_print_control(Tox *tox, uint32_t friend_number, uint32_t file_number, TOX_FILE_CONTROL control,
202 void *userdata) 213 void *userdata)
203{ 214{
204 if (*((uint32_t *)userdata) != 974536) 215 if (*((uint32_t *)userdata) != 974536) {
205 return; 216 return;
217 }
206 218
207 /* First send file num is 0.*/ 219 /* First send file num is 0.*/
208 if (file_number == 0 && control == TOX_FILE_CONTROL_RESUME) 220 if (file_number == 0 && control == TOX_FILE_CONTROL_RESUME) {
209 sendf_ok = 1; 221 sendf_ok = 1;
222 }
210} 223}
211 224
212uint64_t max_sending; 225uint64_t max_sending;
@@ -216,8 +229,9 @@ _Bool file_sending_done;
216void tox_file_chunk_request(Tox *tox, uint32_t friend_number, uint32_t file_number, uint64_t position, size_t length, 229void tox_file_chunk_request(Tox *tox, uint32_t friend_number, uint32_t file_number, uint64_t position, size_t length,
217 void *user_data) 230 void *user_data)
218{ 231{
219 if (*((uint32_t *)user_data) != 974536) 232 if (*((uint32_t *)user_data) != 974536) {
220 return; 233 return;
234 }
221 235
222 if (!sendf_ok) { 236 if (!sendf_ok) {
223 ck_abort_msg("Didn't get resume control"); 237 ck_abort_msg("Didn't get resume control");
@@ -268,8 +282,9 @@ _Bool file_recv;
268void write_file(Tox *tox, uint32_t friendnumber, uint32_t filenumber, uint64_t position, const uint8_t *data, 282void write_file(Tox *tox, uint32_t friendnumber, uint32_t filenumber, uint64_t position, const uint8_t *data,
269 size_t length, void *user_data) 283 size_t length, void *user_data)
270{ 284{
271 if (*((uint32_t *)user_data) != 974536) 285 if (*((uint32_t *)user_data) != 974536) {
272 return; 286 return;
287 }
273 288
274 if (size_recv != position) { 289 if (size_recv != position) {
275 ck_abort_msg("Bad position"); 290 ck_abort_msg("Bad position");
@@ -295,11 +310,13 @@ void write_file(Tox *tox, uint32_t friendnumber, uint32_t filenumber, uint64_t p
295unsigned int connected_t1; 310unsigned int connected_t1;
296void tox_connection_status(Tox *tox, TOX_CONNECTION connection_status, void *user_data) 311void tox_connection_status(Tox *tox, TOX_CONNECTION connection_status, void *user_data)
297{ 312{
298 if (*((uint32_t *)user_data) != 974536) 313 if (*((uint32_t *)user_data) != 974536) {
299 return; 314 return;
315 }
300 316
301 if (connected_t1 && !connection_status) 317 if (connected_t1 && !connection_status) {
302 ck_abort_msg("Tox went offline"); 318 ck_abort_msg("Tox went offline");
319 }
303 320
304 ck_assert_msg(connection_status == TOX_CONNECTION_UDP, "wrong status %u", connection_status); 321 ck_assert_msg(connection_status == TOX_CONNECTION_UDP, "wrong status %u", connection_status);
305 322
@@ -467,8 +484,9 @@ START_TEST(test_few_clients)
467 } 484 }
468 485
469 if (tox_friend_get_connection_status(tox2, 0, 0) == TOX_CONNECTION_UDP 486 if (tox_friend_get_connection_status(tox2, 0, 0) == TOX_CONNECTION_UDP
470 && tox_friend_get_connection_status(tox3, 0, 0) == TOX_CONNECTION_UDP) 487 && tox_friend_get_connection_status(tox3, 0, 0) == TOX_CONNECTION_UDP) {
471 break; 488 break;
489 }
472 } 490 }
473 491
474 c_sleep(50); 492 c_sleep(50);
@@ -492,8 +510,9 @@ START_TEST(test_few_clients)
492 tox_iterate(tox2, &to_compare); 510 tox_iterate(tox2, &to_compare);
493 tox_iterate(tox3, &to_compare); 511 tox_iterate(tox3, &to_compare);
494 512
495 if (messages_received) 513 if (messages_received) {
496 break; 514 break;
515 }
497 516
498 c_sleep(50); 517 c_sleep(50);
499 } 518 }
@@ -530,8 +549,9 @@ START_TEST(test_few_clients)
530 } 549 }
531 550
532 if (tox_friend_get_connection_status(tox2, 0, 0) == TOX_CONNECTION_UDP 551 if (tox_friend_get_connection_status(tox2, 0, 0) == TOX_CONNECTION_UDP
533 && tox_friend_get_connection_status(tox3, 0, 0) == TOX_CONNECTION_UDP) 552 && tox_friend_get_connection_status(tox3, 0, 0) == TOX_CONNECTION_UDP) {
534 break; 553 break;
554 }
535 } 555 }
536 556
537 c_sleep(50); 557 c_sleep(50);
@@ -549,8 +569,9 @@ START_TEST(test_few_clients)
549 tox_iterate(tox2, &to_compare); 569 tox_iterate(tox2, &to_compare);
550 tox_iterate(tox3, &to_compare); 570 tox_iterate(tox3, &to_compare);
551 571
552 if (name_changes) 572 if (name_changes) {
553 break; 573 break;
574 }
554 575
555 c_sleep(50); 576 c_sleep(50);
556 } 577 }
@@ -570,8 +591,9 @@ START_TEST(test_few_clients)
570 tox_iterate(tox2, &to_compare); 591 tox_iterate(tox2, &to_compare);
571 tox_iterate(tox3, &to_compare); 592 tox_iterate(tox3, &to_compare);
572 593
573 if (status_m_changes) 594 if (status_m_changes) {
574 break; 595 break;
596 }
575 597
576 c_sleep(50); 598 c_sleep(50);
577 } 599 }
@@ -593,10 +615,11 @@ START_TEST(test_few_clients)
593 tox_iterate(tox3, &to_compare); 615 tox_iterate(tox3, &to_compare);
594 616
595 617
596 if (typing_changes == 2) 618 if (typing_changes == 2) {
597 break; 619 break;
598 else 620 } else {
599 ck_assert_msg(typing_changes == 0, "Typing fail"); 621 ck_assert_msg(typing_changes == 0, "Typing fail");
622 }
600 623
601 c_sleep(50); 624 c_sleep(50);
602 } 625 }
@@ -610,10 +633,11 @@ START_TEST(test_few_clients)
610 tox_iterate(tox2, &to_compare); 633 tox_iterate(tox2, &to_compare);
611 tox_iterate(tox3, &to_compare); 634 tox_iterate(tox3, &to_compare);
612 635
613 if (typing_changes == 1) 636 if (typing_changes == 1) {
614 break; 637 break;
615 else 638 } else {
616 ck_assert_msg(typing_changes == 0, "Typing fail"); 639 ck_assert_msg(typing_changes == 0, "Typing fail");
640 }
617 641
618 c_sleep(50); 642 c_sleep(50);
619 } 643 }
@@ -637,10 +661,11 @@ START_TEST(test_few_clients)
637 tox_iterate(tox2, &to_compare); 661 tox_iterate(tox2, &to_compare);
638 tox_iterate(tox3, &to_compare); 662 tox_iterate(tox3, &to_compare);
639 663
640 if (custom_packet == 1) 664 if (custom_packet == 1) {
641 break; 665 break;
642 else 666 } else {
643 ck_assert_msg(custom_packet == 0, "Lossless packet fail"); 667 ck_assert_msg(custom_packet == 0, "Lossless packet fail");
668 }
644 669
645 c_sleep(50); 670 c_sleep(50);
646 } 671 }
@@ -659,10 +684,11 @@ START_TEST(test_few_clients)
659 tox_iterate(tox2, &to_compare); 684 tox_iterate(tox2, &to_compare);
660 tox_iterate(tox3, &to_compare); 685 tox_iterate(tox3, &to_compare);
661 686
662 if (custom_packet == 1) 687 if (custom_packet == 1) {
663 break; 688 break;
664 else 689 } else {
665 ck_assert_msg(custom_packet == 0, "lossy packet fail"); 690 ck_assert_msg(custom_packet == 0, "lossy packet fail");
691 }
666 692
667 c_sleep(50); 693 c_sleep(50);
668 } 694 }
@@ -855,8 +881,9 @@ loop_top:
855 pairs[i].tox2 = (pairs[i].tox1 + rand() % (NUM_TOXES - 1) + 1) % NUM_TOXES; 881 pairs[i].tox2 = (pairs[i].tox1 + rand() % (NUM_TOXES - 1) + 1) % NUM_TOXES;
856 882
857 for (j = 0; j < i; ++j) { 883 for (j = 0; j < i; ++j) {
858 if (pairs[j].tox2 == pairs[i].tox1 && pairs[j].tox1 == pairs[i].tox2) 884 if (pairs[j].tox2 == pairs[i].tox1 && pairs[j].tox1 == pairs[i].tox2) {
859 goto loop_top; 885 goto loop_top;
886 }
860 } 887 }
861 888
862 tox_self_get_address(toxes[pairs[i].tox1], address); 889 tox_self_get_address(toxes[pairs[i].tox1], address);
@@ -881,9 +908,11 @@ loop_top:
881 uint16_t counter = 0; 908 uint16_t counter = 0;
882 909
883 for (i = 0; i < NUM_TOXES; ++i) { 910 for (i = 0; i < NUM_TOXES; ++i) {
884 for (j = 0; j < tox_self_get_friend_list_size(toxes[i]); ++j) 911 for (j = 0; j < tox_self_get_friend_list_size(toxes[i]); ++j) {
885 if (tox_friend_get_connection_status(toxes[i], j, 0) == TOX_CONNECTION_UDP) 912 if (tox_friend_get_connection_status(toxes[i], j, 0) == TOX_CONNECTION_UDP) {
886 ++counter; 913 ++counter;
914 }
915 }
887 } 916 }
888 917
889 if (counter == NUM_FRIENDS * 2) { 918 if (counter == NUM_FRIENDS * 2) {
@@ -958,8 +987,9 @@ loop_top:
958 pairs[i].tox2 = (pairs[i].tox1 + rand() % (NUM_TOXES_TCP - 1) + 1) % NUM_TOXES_TCP; 987 pairs[i].tox2 = (pairs[i].tox1 + rand() % (NUM_TOXES_TCP - 1) + 1) % NUM_TOXES_TCP;
959 988
960 for (j = 0; j < i; ++j) { 989 for (j = 0; j < i; ++j) {
961 if (pairs[j].tox2 == pairs[i].tox1 && pairs[j].tox1 == pairs[i].tox2) 990 if (pairs[j].tox2 == pairs[i].tox1 && pairs[j].tox1 == pairs[i].tox2) {
962 goto loop_top; 991 goto loop_top;
992 }
963 } 993 }
964 994
965 tox_self_get_address(toxes[pairs[i].tox1], address); 995 tox_self_get_address(toxes[pairs[i].tox1], address);
@@ -978,9 +1008,11 @@ loop_top:
978 uint16_t counter = 0; 1008 uint16_t counter = 0;
979 1009
980 for (i = 0; i < NUM_TOXES_TCP; ++i) { 1010 for (i = 0; i < NUM_TOXES_TCP; ++i) {
981 for (j = 0; j < tox_self_get_friend_list_size(toxes[i]); ++j) 1011 for (j = 0; j < tox_self_get_friend_list_size(toxes[i]); ++j) {
982 if (tox_friend_get_connection_status(toxes[i], j, 0) == TOX_CONNECTION_TCP) 1012 if (tox_friend_get_connection_status(toxes[i], j, 0) == TOX_CONNECTION_TCP) {
983 ++counter; 1013 ++counter;
1014 }
1015 }
984 1016
985 } 1017 }
986 1018
@@ -1055,8 +1087,9 @@ loop_top:
1055 pairs[i].tox2 = (pairs[i].tox1 + rand() % (NUM_TOXES_TCP - 1) + 1) % NUM_TOXES_TCP; 1087 pairs[i].tox2 = (pairs[i].tox1 + rand() % (NUM_TOXES_TCP - 1) + 1) % NUM_TOXES_TCP;
1056 1088
1057 for (j = 0; j < i; ++j) { 1089 for (j = 0; j < i; ++j) {
1058 if (pairs[j].tox2 == pairs[i].tox1 && pairs[j].tox1 == pairs[i].tox2) 1090 if (pairs[j].tox2 == pairs[i].tox1 && pairs[j].tox1 == pairs[i].tox2) {
1059 goto loop_top; 1091 goto loop_top;
1092 }
1060 } 1093 }
1061 1094
1062 tox_self_get_address(toxes[pairs[i].tox1], address); 1095 tox_self_get_address(toxes[pairs[i].tox1], address);
@@ -1075,9 +1108,11 @@ loop_top:
1075 uint16_t counter = 0; 1108 uint16_t counter = 0;
1076 1109
1077 for (i = 0; i < NUM_TOXES_TCP; ++i) { 1110 for (i = 0; i < NUM_TOXES_TCP; ++i) {
1078 for (j = 0; j < tox_self_get_friend_list_size(toxes[i]); ++j) 1111 for (j = 0; j < tox_self_get_friend_list_size(toxes[i]); ++j) {
1079 if (tox_friend_get_connection_status(toxes[i], j, 0) == TOX_CONNECTION_TCP) 1112 if (tox_friend_get_connection_status(toxes[i], j, 0) == TOX_CONNECTION_TCP) {
1080 ++counter; 1113 ++counter;
1114 }
1115 }
1081 } 1116 }
1082 1117
1083 if (counter == NUM_FRIENDS * 2) { 1118 if (counter == NUM_FRIENDS * 2) {
@@ -1104,8 +1139,9 @@ END_TEST
1104 1139
1105void g_accept_friend_request(Tox *m, const uint8_t *public_key, const uint8_t *data, size_t length, void *userdata) 1140void g_accept_friend_request(Tox *m, const uint8_t *public_key, const uint8_t *data, size_t length, void *userdata)
1106{ 1141{
1107 if (*((uint32_t *)userdata) != 234212) 1142 if (*((uint32_t *)userdata) != 234212) {
1108 return; 1143 return;
1144 }
1109 1145
1110 if (length == 7 && memcmp("Gentoo", data, 7) == 0) { 1146 if (length == 7 && memcmp("Gentoo", data, 7) == 0) {
1111 tox_friend_add_norequest(m, public_key, 0); 1147 tox_friend_add_norequest(m, public_key, 0);
@@ -1118,16 +1154,19 @@ static unsigned int invite_counter;
1118void print_group_invite_callback(Tox *tox, int32_t friendnumber, uint8_t type, const uint8_t *data, uint16_t length, 1154void print_group_invite_callback(Tox *tox, int32_t friendnumber, uint8_t type, const uint8_t *data, uint16_t length,
1119 void *userdata) 1155 void *userdata)
1120{ 1156{
1121 if (*((uint32_t *)userdata) != 234212) 1157 if (*((uint32_t *)userdata) != 234212) {
1122 return; 1158 return;
1159 }
1123 1160
1124 if (type != TOX_GROUPCHAT_TYPE_TEXT) 1161 if (type != TOX_GROUPCHAT_TYPE_TEXT) {
1125 return; 1162 return;
1163 }
1126 1164
1127 int g_num; 1165 int g_num;
1128 1166
1129 if ((g_num = tox_join_groupchat(tox, friendnumber, data, length)) == -1) 1167 if ((g_num = tox_join_groupchat(tox, friendnumber, data, length)) == -1) {
1130 return; 1168 return;
1169 }
1131 1170
1132 ck_assert_msg(g_num == 0, "Group number was not 0"); 1171 ck_assert_msg(g_num == 0, "Group number was not 0");
1133 ck_assert_msg(tox_join_groupchat(tox, friendnumber, data, length) == -1, 1172 ck_assert_msg(tox_join_groupchat(tox, friendnumber, data, length) == -1,
@@ -1142,8 +1181,9 @@ static unsigned int num_recv;
1142void print_group_message(Tox *tox, int groupnumber, int peernumber, const uint8_t *message, uint16_t length, 1181void print_group_message(Tox *tox, int groupnumber, int peernumber, const uint8_t *message, uint16_t length,
1143 void *userdata) 1182 void *userdata)
1144{ 1183{
1145 if (*((uint32_t *)userdata) != 234212) 1184 if (*((uint32_t *)userdata) != 234212) {
1146 return; 1185 return;
1186 }
1147 1187
1148 if (length == (sizeof("Install Gentoo") - 1) && memcmp(message, "Install Gentoo", sizeof("Install Gentoo") - 1) == 0) { 1188 if (length == (sizeof("Install Gentoo") - 1) && memcmp(message, "Install Gentoo", sizeof("Install Gentoo") - 1) == 0) {
1149 ++num_recv; 1189 ++num_recv;
@@ -1189,8 +1229,9 @@ group_test_restart:
1189 } 1229 }
1190 } 1230 }
1191 1231
1192 if (i == NUM_GROUP_TOX) 1232 if (i == NUM_GROUP_TOX) {
1193 break; 1233 break;
1234 }
1194 1235
1195 for (i = 0; i < NUM_GROUP_TOX; ++i) { 1236 for (i = 0; i < NUM_GROUP_TOX; ++i) {
1196 tox_iterate(toxes[i], NULL); 1237 tox_iterate(toxes[i], NULL);
diff --git a/auto_tests/toxav_basic_test.c b/auto_tests/toxav_basic_test.c
index f66846c5..701cf841 100644
--- a/auto_tests/toxav_basic_test.c
+++ b/auto_tests/toxav_basic_test.c
@@ -179,8 +179,9 @@ START_TEST(test_AV_flows)
179 } 179 }
180 180
181 if (tox_friend_get_connection_status(Alice, 0, NULL) == TOX_CONNECTION_UDP && 181 if (tox_friend_get_connection_status(Alice, 0, NULL) == TOX_CONNECTION_UDP &&
182 tox_friend_get_connection_status(Bob, 0, NULL) == TOX_CONNECTION_UDP) 182 tox_friend_get_connection_status(Bob, 0, NULL) == TOX_CONNECTION_UDP) {
183 break; 183 break;
184 }
184 185
185 c_sleep(20); 186 c_sleep(20);
186 } 187 }
@@ -290,8 +291,9 @@ START_TEST(test_AV_flows)
290 } 291 }
291 } 292 }
292 293
293 while (!BobCC.incoming) 294 while (!BobCC.incoming) {
294 iterate_tox(bootstrap, Alice, Bob); 295 iterate_tox(bootstrap, Alice, Bob);
296 }
295 297
296 /* Reject */ 298 /* Reject */
297 { 299 {
@@ -304,8 +306,9 @@ START_TEST(test_AV_flows)
304 } 306 }
305 } 307 }
306 308
307 while (AliceCC.state != TOXAV_FRIEND_CALL_STATE_FINISHED) 309 while (AliceCC.state != TOXAV_FRIEND_CALL_STATE_FINISHED) {
308 iterate_tox(bootstrap, Alice, Bob); 310 iterate_tox(bootstrap, Alice, Bob);
311 }
309 312
310 printf("Success!\n"); 313 printf("Success!\n");
311 } 314 }
@@ -326,8 +329,9 @@ START_TEST(test_AV_flows)
326 } 329 }
327 } 330 }
328 331
329 while (!BobCC.incoming) 332 while (!BobCC.incoming) {
330 iterate_tox(bootstrap, Alice, Bob); 333 iterate_tox(bootstrap, Alice, Bob);
334 }
331 335
332 /* Cancel */ 336 /* Cancel */
333 { 337 {
@@ -341,8 +345,9 @@ START_TEST(test_AV_flows)
341 } 345 }
342 346
343 /* Alice will not receive end state */ 347 /* Alice will not receive end state */
344 while (BobCC.state != TOXAV_FRIEND_CALL_STATE_FINISHED) 348 while (BobCC.state != TOXAV_FRIEND_CALL_STATE_FINISHED) {
345 iterate_tox(bootstrap, Alice, Bob); 349 iterate_tox(bootstrap, Alice, Bob);
350 }
346 351
347 printf("Success!\n"); 352 printf("Success!\n");
348 } 353 }
@@ -364,8 +369,9 @@ START_TEST(test_AV_flows)
364 } 369 }
365 } 370 }
366 371
367 while (!BobCC.incoming) 372 while (!BobCC.incoming) {
368 iterate_tox(bootstrap, Alice, Bob); 373 iterate_tox(bootstrap, Alice, Bob);
374 }
369 375
370 /* At first try all stuff while in invalid state */ 376 /* At first try all stuff while in invalid state */
371 ck_assert(!toxav_call_control(AliceAV, 0, TOXAV_CALL_CONTROL_PAUSE, NULL)); 377 ck_assert(!toxav_call_control(AliceAV, 0, TOXAV_CALL_CONTROL_PAUSE, NULL));
@@ -453,8 +459,9 @@ START_TEST(test_AV_flows)
453 } 459 }
454 } 460 }
455 461
456 while (!BobCC.incoming) 462 while (!BobCC.incoming) {
457 iterate_tox(bootstrap, Alice, Bob); 463 iterate_tox(bootstrap, Alice, Bob);
464 }
458 465
459 { 466 {
460 TOXAV_ERR_ANSWER rc; 467 TOXAV_ERR_ANSWER rc;
@@ -520,8 +527,9 @@ START_TEST(test_AV_flows)
520 } 527 }
521 } 528 }
522 529
523 while (!BobCC.incoming) 530 while (!BobCC.incoming) {
524 iterate_tox(bootstrap, Alice, Bob); 531 iterate_tox(bootstrap, Alice, Bob);
532 }
525 533
526 { 534 {
527 TOXAV_ERR_ANSWER rc; 535 TOXAV_ERR_ANSWER rc;
diff --git a/auto_tests/toxav_many_test.c b/auto_tests/toxav_many_test.c
index cd9d514c..24d2ae6e 100644
--- a/auto_tests/toxav_many_test.c
+++ b/auto_tests/toxav_many_test.c
@@ -147,8 +147,9 @@ void *call_thread(void *pd)
147 } 147 }
148 } 148 }
149 149
150 while (!BobCC->incoming) 150 while (!BobCC->incoming) {
151 c_sleep(10); 151 c_sleep(10);
152 }
152 153
153 { /* Answer */ 154 { /* Answer */
154 TOXAV_ERR_ANSWER rc; 155 TOXAV_ERR_ANSWER rc;
@@ -267,8 +268,9 @@ START_TEST(test_AV_three_calls)
267 tox_friend_get_connection_status(Alice, 2, NULL) == TOX_CONNECTION_UDP && 268 tox_friend_get_connection_status(Alice, 2, NULL) == TOX_CONNECTION_UDP &&
268 tox_friend_get_connection_status(Bobs[0], 0, NULL) == TOX_CONNECTION_UDP && 269 tox_friend_get_connection_status(Bobs[0], 0, NULL) == TOX_CONNECTION_UDP &&
269 tox_friend_get_connection_status(Bobs[1], 0, NULL) == TOX_CONNECTION_UDP && 270 tox_friend_get_connection_status(Bobs[1], 0, NULL) == TOX_CONNECTION_UDP &&
270 tox_friend_get_connection_status(Bobs[2], 0, NULL) == TOX_CONNECTION_UDP) 271 tox_friend_get_connection_status(Bobs[2], 0, NULL) == TOX_CONNECTION_UDP) {
271 break; 272 break;
273 }
272 274
273 c_sleep(20); 275 c_sleep(20);
274 } 276 }
diff --git a/other/DHT_bootstrap.c b/other/DHT_bootstrap.c
index a1b5f11e..5ce8e40d 100644
--- a/other/DHT_bootstrap.c
+++ b/other/DHT_bootstrap.c
@@ -111,8 +111,9 @@ int main(int argc, char *argv[])
111 uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */ 111 uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */
112 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 112 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
113 113
114 if (argvoffset < 0) 114 if (argvoffset < 0) {
115 exit(1); 115 exit(1);
116 }
116 117
117 /* Initialize networking - 118 /* Initialize networking -
118 Bind to ip 0.0.0.0 / [::] : PORT */ 119 Bind to ip 0.0.0.0 / [::] : PORT */
diff --git a/other/bootstrap_daemon/src/tox-bootstrapd.c b/other/bootstrap_daemon/src/tox-bootstrapd.c
index 14ee9148..e1ae7cc6 100644
--- a/other/bootstrap_daemon/src/tox-bootstrapd.c
+++ b/other/bootstrap_daemon/src/tox-bootstrapd.c
@@ -79,8 +79,9 @@ int manage_keys(DHT *dht, char *keys_file_path)
79 79
80 keys_file = fopen(keys_file_path, "w"); 80 keys_file = fopen(keys_file_path, "w");
81 81
82 if (!keys_file) 82 if (!keys_file) {
83 return 0; 83 return 0;
84 }
84 85
85 const size_t write_size = fwrite(keys, sizeof(uint8_t), KEYS_SIZE, keys_file); 86 const size_t write_size = fwrite(keys, sizeof(uint8_t), KEYS_SIZE, keys_file);
86 87
diff --git a/other/bootstrap_node_packets.c b/other/bootstrap_node_packets.c
index a560550e..8ee26786 100644
--- a/other/bootstrap_node_packets.c
+++ b/other/bootstrap_node_packets.c
@@ -36,8 +36,9 @@ static uint16_t bootstrap_motd_length;
36 */ 36 */
37static int handle_info_request(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata) 37static int handle_info_request(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata)
38{ 38{
39 if (length != INFO_REQUEST_PACKET_LENGTH) 39 if (length != INFO_REQUEST_PACKET_LENGTH) {
40 return 1; 40 return 1;
41 }
41 42
42 uint8_t data[1 + sizeof(bootstrap_version) + MAX_MOTD_LENGTH]; 43 uint8_t data[1 + sizeof(bootstrap_version) + MAX_MOTD_LENGTH];
43 data[0] = BOOTSTRAP_INFO_PACKET_ID; 44 data[0] = BOOTSTRAP_INFO_PACKET_ID;
@@ -45,16 +46,18 @@ static int handle_info_request(void *object, IP_Port source, const uint8_t *pack
45 uint16_t len = 1 + sizeof(bootstrap_version) + bootstrap_motd_length; 46 uint16_t len = 1 + sizeof(bootstrap_version) + bootstrap_motd_length;
46 memcpy(data + 1 + sizeof(bootstrap_version), bootstrap_motd, bootstrap_motd_length); 47 memcpy(data + 1 + sizeof(bootstrap_version), bootstrap_motd, bootstrap_motd_length);
47 48
48 if (sendpacket(object, source, data, len) == len) 49 if (sendpacket(object, source, data, len) == len) {
49 return 0; 50 return 0;
51 }
50 52
51 return 1; 53 return 1;
52} 54}
53 55
54int bootstrap_set_callbacks(Networking_Core *net, uint32_t version, uint8_t *motd, uint16_t motd_length) 56int bootstrap_set_callbacks(Networking_Core *net, uint32_t version, uint8_t *motd, uint16_t motd_length)
55{ 57{
56 if (motd_length > MAX_MOTD_LENGTH) 58 if (motd_length > MAX_MOTD_LENGTH) {
57 return -1; 59 return -1;
60 }
58 61
59 bootstrap_version = htonl(version); 62 bootstrap_version = htonl(version);
60 memcpy(bootstrap_motd, motd, motd_length); 63 memcpy(bootstrap_motd, motd, motd_length);
diff --git a/testing/DHT_test.c b/testing/DHT_test.c
index 91e556c6..cd3ff5f7 100644
--- a/testing/DHT_test.c
+++ b/testing/DHT_test.c
@@ -90,10 +90,11 @@ void print_assoc(IPPTsPng *assoc, uint8_t ours)
90 90
91 ipp = &assoc->ret_ip_port; 91 ipp = &assoc->ret_ip_port;
92 92
93 if (ours) 93 if (ours) {
94 printf("OUR IP: %s Port: %u\n", ip_ntoa(&ipp->ip), ntohs(ipp->port)); 94 printf("OUR IP: %s Port: %u\n", ip_ntoa(&ipp->ip), ntohs(ipp->port));
95 else 95 } else {
96 printf("RET IP: %s Port: %u\n", ip_ntoa(&ipp->ip), ntohs(ipp->port)); 96 printf("RET IP: %s Port: %u\n", ip_ntoa(&ipp->ip), ntohs(ipp->port));
97 }
97 98
98 printf("Timestamp: %llu\n", (long long unsigned int) assoc->ret_timestamp); 99 printf("Timestamp: %llu\n", (long long unsigned int) assoc->ret_timestamp);
99 print_hardening(&assoc->hardening); 100 print_hardening(&assoc->hardening);
@@ -108,8 +109,9 @@ void print_clientlist(DHT *dht)
108 for (i = 0; i < LCLIENT_LIST; i++) { 109 for (i = 0; i < LCLIENT_LIST; i++) {
109 Client_data *client = &dht->close_clientlist[i]; 110 Client_data *client = &dht->close_clientlist[i];
110 111
111 if (public_key_cmp(client->public_key, zeroes_cid) == 0) 112 if (public_key_cmp(client->public_key, zeroes_cid) == 0) {
112 continue; 113 continue;
114 }
113 115
114 printf("ClientID: "); 116 printf("ClientID: ");
115 print_client_id(client->public_key); 117 print_client_id(client->public_key);
@@ -139,8 +141,9 @@ void print_friendlist(DHT *dht)
139 for (i = 0; i < MAX_FRIEND_CLIENTS; i++) { 141 for (i = 0; i < MAX_FRIEND_CLIENTS; i++) {
140 Client_data *client = &dht->friends_list[k].client_list[i]; 142 Client_data *client = &dht->friends_list[k].client_list[i];
141 143
142 if (public_key_cmp(client->public_key, zeroes_cid) == 0) 144 if (public_key_cmp(client->public_key, zeroes_cid) == 0) {
143 continue; 145 continue;
146 }
144 147
145 printf("ClientID: "); 148 printf("ClientID: ");
146 print_client_id(client->public_key); 149 print_client_id(client->public_key);
@@ -158,8 +161,9 @@ void printpacket(uint8_t *data, uint32_t length, IP_Port ip_port)
158 printf("--------------------BEGIN-----------------------------\n"); 161 printf("--------------------BEGIN-----------------------------\n");
159 162
160 for (i = 0; i < length; i++) { 163 for (i = 0; i < length; i++) {
161 if (data[i] < 16) 164 if (data[i] < 16) {
162 printf("0"); 165 printf("0");
166 }
163 167
164 printf("%hhX", data[i]); 168 printf("%hhX", data[i]);
165 } 169 }
@@ -178,8 +182,9 @@ int main(int argc, char *argv[])
178 uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */ 182 uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */
179 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 183 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
180 184
181 if (argvoffset < 0) 185 if (argvoffset < 0) {
182 exit(1); 186 exit(1);
187 }
183 188
184 //memcpy(self_client_id, "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", 32); 189 //memcpy(self_client_id, "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", 32);
185 /* initialize networking */ 190 /* initialize networking */
@@ -192,8 +197,9 @@ int main(int argc, char *argv[])
192 uint32_t i; 197 uint32_t i;
193 198
194 for (i = 0; i < 32; i++) { 199 for (i = 0; i < 32; i++) {
195 if (dht->self_public_key[i] < 16) 200 if (dht->self_public_key[i] < 16) {
196 printf("0"); 201 printf("0");
202 }
197 203
198 printf("%hhX", dht->self_public_key[i]); 204 printf("%hhX", dht->self_public_key[i]);
199 } 205 }
@@ -201,11 +207,13 @@ int main(int argc, char *argv[])
201 char temp_id[128]; 207 char temp_id[128];
202 printf("\nEnter the public_key of the friend you wish to add (32 bytes HEX format):\n"); 208 printf("\nEnter the public_key of the friend you wish to add (32 bytes HEX format):\n");
203 209
204 if (!fgets(temp_id, sizeof(temp_id), stdin)) 210 if (!fgets(temp_id, sizeof(temp_id), stdin)) {
205 exit(0); 211 exit(0);
212 }
206 213
207 if ((strlen(temp_id) > 0) && (temp_id[strlen(temp_id) - 1] == '\n')) 214 if ((strlen(temp_id) > 0) && (temp_id[strlen(temp_id) - 1] == '\n')) {
208 temp_id[strlen(temp_id) - 1] = '\0'; 215 temp_id[strlen(temp_id) - 1] = '\0';
216 }
209 217
210 uint8_t *bin_id = hex_string_to_bin(temp_id); 218 uint8_t *bin_id = hex_string_to_bin(temp_id);
211 DHT_addfriend(dht, bin_id, 0, 0, 0, 0); 219 DHT_addfriend(dht, bin_id, 0, 0, 0, 0);
diff --git a/testing/Messenger_test.c b/testing/Messenger_test.c
index e39a1182..f31052e3 100644
--- a/testing/Messenger_test.c
+++ b/testing/Messenger_test.c
@@ -74,8 +74,9 @@ void print_request(Messenger *m, const uint8_t *public_key, const uint8_t *data,
74 uint32_t j; 74 uint32_t j;
75 75
76 for (j = 0; j < 32; j++) { 76 for (j = 0; j < 32; j++) {
77 if (public_key[j] < 16) 77 if (public_key[j] < 16) {
78 printf("0"); 78 printf("0");
79 }
79 80
80 printf("%hhX", public_key[j]); 81 printf("%hhX", public_key[j]);
81 } 82 }
@@ -100,8 +101,9 @@ int main(int argc, char *argv[])
100 uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */ 101 uint8_t ipv6enabled = TOX_ENABLE_IPV6_DEFAULT; /* x */
101 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 102 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
102 103
103 if (argvoffset < 0) 104 if (argvoffset < 0) {
104 exit(1); 105 exit(1);
106 }
105 107
106 /* with optional --ipvx, now it can be 1-4 arguments... */ 108 /* with optional --ipvx, now it can be 1-4 arguments... */
107 if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) { 109 if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) {
@@ -156,8 +158,9 @@ int main(int argc, char *argv[])
156 getaddress(m, address); 158 getaddress(m, address);
157 159
158 for (i = 0; i < FRIEND_ADDRESS_SIZE; i++) { 160 for (i = 0; i < FRIEND_ADDRESS_SIZE; i++) {
159 if (address[i] < 16) 161 if (address[i] < 16) {
160 printf("0"); 162 printf("0");
163 }
161 164
162 printf("%hhX", address[i]); 165 printf("%hhX", address[i]);
163 } 166 }
@@ -167,12 +170,13 @@ int main(int argc, char *argv[])
167 char temp_hex_id[128]; 170 char temp_hex_id[128];
168 printf("\nEnter the address of the friend you wish to add (38 bytes HEX format):\n"); 171 printf("\nEnter the address of the friend you wish to add (38 bytes HEX format):\n");
169 172
170 if (!fgets(temp_hex_id, sizeof(temp_hex_id), stdin)) 173 if (!fgets(temp_hex_id, sizeof(temp_hex_id), stdin)) {
171 exit(0); 174 exit(0);
175 }
172 176
173 if ((strlen(temp_hex_id) > 0) && (temp_hex_id[strlen(temp_hex_id) - 1] == '\n')) 177 if ((strlen(temp_hex_id) > 0) && (temp_hex_id[strlen(temp_hex_id) - 1] == '\n')) {
174 temp_hex_id[strlen(temp_hex_id) - 1] = '\0'; 178 temp_hex_id[strlen(temp_hex_id) - 1] = '\0';
175 179 }
176 180
177 uint8_t *bin_id = hex_string_to_bin(temp_hex_id); 181 uint8_t *bin_id = hex_string_to_bin(temp_hex_id);
178 int num = m_addfriend(m, bin_id, (uint8_t *)"Install Gentoo", sizeof("Install Gentoo")); 182 int num = m_addfriend(m, bin_id, (uint8_t *)"Install Gentoo", sizeof("Install Gentoo"));
diff --git a/testing/av_test.c b/testing/av_test.c
index 7c2922b7..e724bb0e 100644
--- a/testing/av_test.c
+++ b/testing/av_test.c
@@ -258,8 +258,9 @@ void initialize_tox(Tox **bootstrap, ToxAV **AliceAV, CallControl *AliceCC, ToxA
258 } 258 }
259 259
260 if (tox_friend_get_connection_status(Alice, 0, NULL) == TOX_CONNECTION_UDP && 260 if (tox_friend_get_connection_status(Alice, 0, NULL) == TOX_CONNECTION_UDP &&
261 tox_friend_get_connection_status(Bob, 0, NULL) == TOX_CONNECTION_UDP) 261 tox_friend_get_connection_status(Bob, 0, NULL) == TOX_CONNECTION_UDP) {
262 break; 262 break;
263 }
263 264
264 c_sleep(20); 265 c_sleep(20);
265 } 266 }
@@ -316,8 +317,9 @@ void *iterate_toxav (void *data)
316 317
317#if defined TEST_TRANSFER_V && TEST_TRANSFER_V == 1 318#if defined TEST_TRANSFER_V && TEST_TRANSFER_V == 1
318 319
319 if (!rc) 320 if (!rc) {
320 rc = 1; 321 rc = 1;
322 }
321 323
322 cvWaitKey(rc); 324 cvWaitKey(rc);
323#else 325#else
@@ -379,8 +381,9 @@ int print_audio_devices()
379 for (i = 0; i < Pa_GetDeviceCount(); ++i) { 381 for (i = 0; i < Pa_GetDeviceCount(); ++i) {
380 const PaDeviceInfo *info = Pa_GetDeviceInfo(i); 382 const PaDeviceInfo *info = Pa_GetDeviceInfo(i);
381 383
382 if (info) 384 if (info) {
383 printf("%d) %s\n", i, info->name); 385 printf("%d) %s\n", i, info->name);
386 }
384 } 387 }
385 388
386 return 0; 389 return 0;
@@ -498,8 +501,9 @@ CHECK_ARG:
498 } 501 }
499 } 502 }
500 503
501 if (audio_out_dev_idx < 0) 504 if (audio_out_dev_idx < 0) {
502 audio_out_dev_idx = Pa_GetDefaultOutputDevice(); 505 audio_out_dev_idx = Pa_GetDefaultOutputDevice();
506 }
503 507
504 const PaDeviceInfo *audio_dev = Pa_GetDeviceInfo(audio_out_dev_idx); 508 const PaDeviceInfo *audio_dev = Pa_GetDeviceInfo(audio_out_dev_idx);
505 509
@@ -548,8 +552,9 @@ CHECK_ARG:
548 } 552 }
549 } 553 }
550 554
551 while (!BobCC.incoming) 555 while (!BobCC.incoming) {
552 iterate_tox(bootstrap, AliceAV, BobAV, NULL); 556 iterate_tox(bootstrap, AliceAV, BobAV, NULL);
557 }
553 558
554 { /* Answer */ 559 { /* Answer */
555 TOXAV_ERR_ANSWER rc; 560 TOXAV_ERR_ANSWER rc;
@@ -561,8 +566,9 @@ CHECK_ARG:
561 } 566 }
562 } 567 }
563 568
564 while (AliceCC.state == 0) 569 while (AliceCC.state == 0) {
565 iterate_tox(bootstrap, AliceAV, BobAV, NULL); 570 iterate_tox(bootstrap, AliceAV, BobAV, NULL);
571 }
566 572
567 /* Open audio file */ 573 /* Open audio file */
568 af_handle = sf_open(af_name, SFM_READ, &af_info); 574 af_handle = sf_open(af_name, SFM_READ, &af_info);
@@ -627,7 +633,7 @@ CHECK_ARG:
627 } 633 }
628 634
629 iterate_tox(bootstrap, AliceAV, BobAV, NULL); 635 iterate_tox(bootstrap, AliceAV, BobAV, NULL);
630 c_sleep(abs(audio_frame_duration - (current_time_monotonic() - enc_start_time) - 1)); 636 c_sleep((audio_frame_duration - (current_time_monotonic() - enc_start_time) - 1));
631 } 637 }
632 638
633 printf("Played file in: %lu; stopping stream...\n", time(NULL) - start_time); 639 printf("Played file in: %lu; stopping stream...\n", time(NULL) - start_time);
@@ -651,19 +657,22 @@ CHECK_ARG:
651 /* Stop decode thread */ 657 /* Stop decode thread */
652 data.sig = -1; 658 data.sig = -1;
653 659
654 while (data.sig != 1) 660 while (data.sig != 1) {
655 pthread_yield(); 661 pthread_yield();
662 }
656 663
657 pthread_mutex_destroy(AliceCC.arb_mutex); 664 pthread_mutex_destroy(AliceCC.arb_mutex);
658 pthread_mutex_destroy(BobCC.arb_mutex); 665 pthread_mutex_destroy(BobCC.arb_mutex);
659 666
660 void *f = NULL; 667 void *f = NULL;
661 668
662 while (rb_read(AliceCC.arb, &f)) 669 while (rb_read(AliceCC.arb, &f)) {
663 free(f); 670 free(f);
671 }
664 672
665 while (rb_read(BobCC.arb, &f)) 673 while (rb_read(BobCC.arb, &f)) {
666 free(f); 674 free(f);
675 }
667 676
668 printf("Success!"); 677 printf("Success!");
669 } 678 }
@@ -684,8 +693,9 @@ CHECK_ARG:
684 } 693 }
685 } 694 }
686 695
687 while (!BobCC.incoming) 696 while (!BobCC.incoming) {
688 iterate_tox(bootstrap, AliceAV, BobAV, NULL); 697 iterate_tox(bootstrap, AliceAV, BobAV, NULL);
698 }
689 699
690 { /* Answer */ 700 { /* Answer */
691 TOXAV_ERR_ANSWER rc; 701 TOXAV_ERR_ANSWER rc;
@@ -724,8 +734,9 @@ CHECK_ARG:
724 while (start_time + 90 > time(NULL)) { 734 while (start_time + 90 > time(NULL)) {
725 IplImage *frame = cvQueryFrame(capture ); 735 IplImage *frame = cvQueryFrame(capture );
726 736
727 if (!frame) 737 if (!frame) {
728 break; 738 break;
739 }
729 740
730 send_opencv_img(AliceAV, 0, frame); 741 send_opencv_img(AliceAV, 0, frame);
731 iterate_tox(bootstrap, AliceAV, BobAV, NULL); 742 iterate_tox(bootstrap, AliceAV, BobAV, NULL);
@@ -751,8 +762,9 @@ CHECK_ARG:
751 printf("Stopping decode thread\n"); 762 printf("Stopping decode thread\n");
752 data.sig = -1; 763 data.sig = -1;
753 764
754 while (data.sig != 1) 765 while (data.sig != 1) {
755 pthread_yield(); 766 pthread_yield();
767 }
756 768
757 printf("Success!"); 769 printf("Success!");
758 } 770 }
diff --git a/testing/dns3_test.c b/testing/dns3_test.c
index 1f6c6a12..975bc17b 100644
--- a/testing/dns3_test.c
+++ b/testing/dns3_test.c
@@ -54,11 +54,13 @@ int main(int argc, char *argv[])
54 ip.family = AF_INET; 54 ip.family = AF_INET;
55 sock_t sock = socket(ip.family, SOCK_DGRAM, IPPROTO_UDP); 55 sock_t sock = socket(ip.family, SOCK_DGRAM, IPPROTO_UDP);
56 56
57 if (!sock_valid(sock)) 57 if (!sock_valid(sock)) {
58 return -1; 58 return -1;
59 }
59 60
60 if (!addr_resolve_or_parse_ip(argv[1], &ip, 0)) 61 if (!addr_resolve_or_parse_ip(argv[1], &ip, 0)) {
61 return -1; 62 return -1;
63 }
62 64
63 struct sockaddr_in target; 65 struct sockaddr_in target;
64 size_t addrsize = sizeof(struct sockaddr_in); 66 size_t addrsize = sizeof(struct sockaddr_in);
@@ -77,8 +79,9 @@ int main(int argc, char *argv[])
77 }*/ 79 }*/
78 int len = tox_generate_dns3_string(d, string + 1, sizeof(string) - 1, &request_id, (uint8_t *)argv[3], strlen(argv[3])); 80 int len = tox_generate_dns3_string(d, string + 1, sizeof(string) - 1, &request_id, (uint8_t *)argv[3], strlen(argv[3]));
79 81
80 if (len == -1) 82 if (len == -1) {
81 return -1; 83 return -1;
84 }
82 85
83 string[0] = '_'; 86 string[0] = '_';
84 memcpy(string + len + 1, "._tox.", sizeof("._tox.")); 87 memcpy(string + len + 1, "._tox.", sizeof("._tox."));
@@ -87,21 +90,26 @@ int main(int argc, char *argv[])
87 uint8_t id = rand(); 90 uint8_t id = rand();
88 uint32_t p_len = create_packet(packet, string, strlen((char *)string), id); 91 uint32_t p_len = create_packet(packet, string, strlen((char *)string), id);
89 92
90 if (sendto(sock, (char *) packet, p_len, 0, (struct sockaddr *)&target, addrsize) != p_len) 93 if (sendto(sock, (char *) packet, p_len, 0, (struct sockaddr *)&target, addrsize) != p_len) {
91 return -1; 94 return -1;
95 }
92 96
93 uint8_t buffer[512] = {}; 97 uint8_t buffer[512] = {};
94 int r_len = recv(sock, buffer, sizeof(buffer), 0); 98 int r_len = recv(sock, buffer, sizeof(buffer), 0);
95 99
96 if (r_len < (int)p_len) 100 if (r_len < (int)p_len) {
97 return -1; 101 return -1;
102 }
98 103
99 for (i = r_len - 1; i != 0 && buffer[i] != '='; --i); 104 for (i = r_len - 1; i != 0 && buffer[i] != '='; --i) {
105 ;
106 }
100 107
101 uint8_t tox_id[TOX_ADDRESS_SIZE]; 108 uint8_t tox_id[TOX_ADDRESS_SIZE];
102 109
103 if (tox_decrypt_dns3_TXT(d, tox_id, buffer + i + 1, r_len - (i + 1), request_id) != 0) 110 if (tox_decrypt_dns3_TXT(d, tox_id, buffer + i + 1, r_len - (i + 1), request_id) != 0) {
104 return -1; 111 return -1;
112 }
105 113
106 printf("The Tox id for username %s is:\n", argv[3]); 114 printf("The Tox id for username %s is:\n", argv[3]);
107 115
diff --git a/testing/irc_syncbot.c b/testing/irc_syncbot.c
index 8ee28d80..01e557d5 100644
--- a/testing/irc_syncbot.c
+++ b/testing/irc_syncbot.c
@@ -85,16 +85,18 @@ int current_group = -1;
85 85
86static void callback_group_invite(Tox *tox, int fid, uint8_t type, const uint8_t *data, uint16_t length, void *userdata) 86static void callback_group_invite(Tox *tox, int fid, uint8_t type, const uint8_t *data, uint16_t length, void *userdata)
87{ 87{
88 if (current_group == -1) 88 if (current_group == -1) {
89 current_group = tox_join_groupchat(tox, fid, data, length); 89 current_group = tox_join_groupchat(tox, fid, data, length);
90 }
90} 91}
91 92
92void callback_friend_message(Tox *tox, uint32_t fid, TOX_MESSAGE_TYPE type, const uint8_t *message, size_t length, 93void callback_friend_message(Tox *tox, uint32_t fid, TOX_MESSAGE_TYPE type, const uint8_t *message, size_t length,
93 void *userdata) 94 void *userdata)
94{ 95{
95 if (length == 1 && *message == 'c') { 96 if (length == 1 && *message == 'c') {
96 if (tox_del_groupchat(tox, current_group) == 0) 97 if (tox_del_groupchat(tox, current_group) == 0) {
97 current_group = -1; 98 current_group = -1;
99 }
98 } 100 }
99 101
100 if (length == 1 && *message == 'i') { 102 if (length == 1 && *message == 'i') {
@@ -109,8 +111,9 @@ void callback_friend_message(Tox *tox, uint32_t fid, TOX_MESSAGE_TYPE type, cons
109static void copy_groupmessage(Tox *tox, int groupnumber, int friendgroupnumber, const uint8_t *message, uint16_t length, 111static void copy_groupmessage(Tox *tox, int groupnumber, int friendgroupnumber, const uint8_t *message, uint16_t length,
110 void *userdata) 112 void *userdata)
111{ 113{
112 if (tox_group_peernumber_is_ours(tox, groupnumber, friendgroupnumber)) 114 if (tox_group_peernumber_is_ours(tox, groupnumber, friendgroupnumber)) {
113 return; 115 return;
116 }
114 117
115 uint8_t name[TOX_MAX_NAME_LENGTH]; 118 uint8_t name[TOX_MAX_NAME_LENGTH];
116 int namelen = tox_group_peername(tox, groupnumber, friendgroupnumber, name); 119 int namelen = tox_group_peername(tox, groupnumber, friendgroupnumber, name);
@@ -136,29 +139,34 @@ static void copy_groupmessage(Tox *tox, int groupnumber, int friendgroupnumber,
136 unsigned int i; 139 unsigned int i;
137 140
138 for (i = 0; i < send_len; ++i) { 141 for (i = 0; i < send_len; ++i) {
139 if (sendbuf[i] == '\n') 142 if (sendbuf[i] == '\n') {
140 sendbuf[i] = '|'; 143 sendbuf[i] = '|';
144 }
141 145
142 if (sendbuf[i] == 0) 146 if (sendbuf[i] == 0) {
143 sendbuf[i] = ' '; 147 sendbuf[i] = ' ';
148 }
144 } 149 }
145 150
146 sendbuf[send_len] = '\n'; 151 sendbuf[send_len] = '\n';
147 send_len += 1; 152 send_len += 1;
148 153
149 if (sock >= 0) 154 if (sock >= 0) {
150 send(sock, sendbuf, send_len, MSG_NOSIGNAL); 155 send(sock, sendbuf, send_len, MSG_NOSIGNAL);
156 }
151} 157}
152 158
153void send_irc_group(Tox *tox, uint8_t *msg, uint16_t len) 159void send_irc_group(Tox *tox, uint8_t *msg, uint16_t len)
154{ 160{
155 if (len > 1350 || len == 0 || len == 1) 161 if (len > 1350 || len == 0 || len == 1) {
156 return; 162 return;
163 }
157 164
158 --len; 165 --len;
159 166
160 if (*msg != ':') 167 if (*msg != ':') {
161 return; 168 return;
169 }
162 170
163 uint8_t req[len]; 171 uint8_t req[len];
164 unsigned int i; 172 unsigned int i;
@@ -185,8 +193,9 @@ void send_irc_group(Tox *tox, uint8_t *msg, uint16_t len)
185 193
186 uint8_t *pmsg = (uint8_t *)strstr((char *)req, " PRIVMSG"); 194 uint8_t *pmsg = (uint8_t *)strstr((char *)req, " PRIVMSG");
187 195
188 if (pmsg == NULL) 196 if (pmsg == NULL) {
189 return; 197 return;
198 }
190 199
191 uint8_t *dt; 200 uint8_t *dt;
192 201
@@ -200,8 +209,9 @@ void send_irc_group(Tox *tox, uint8_t *msg, uint16_t len)
200 message[length] = ' '; 209 message[length] = ' ';
201 length += 1; 210 length += 1;
202 211
203 if ((req_len + 2) >= len) 212 if ((req_len + 2) >= len) {
204 return; 213 return;
214 }
205 215
206 memcpy(message + length, msg + req_len + 2, len - (req_len + 2)); 216 memcpy(message + length, msg + req_len + 2, len - (req_len + 2));
207 length += len - (req_len + 2); 217 length += len - (req_len + 2);
@@ -213,8 +223,9 @@ Tox *init_tox(int argc, char *argv[])
213 uint8_t ipv6enabled = 1; /* x */ 223 uint8_t ipv6enabled = 1; /* x */
214 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 224 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
215 225
216 if (argvoffset < 0) 226 if (argvoffset < 0) {
217 exit(1); 227 exit(1);
228 }
218 229
219 /* with optional --ipvx, now it can be 1-4 arguments... */ 230 /* with optional --ipvx, now it can be 1-4 arguments... */
220 if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) { 231 if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) {
@@ -224,8 +235,9 @@ Tox *init_tox(int argc, char *argv[])
224 235
225 Tox *tox = tox_new(0, 0); 236 Tox *tox = tox_new(0, 0);
226 237
227 if (!tox) 238 if (!tox) {
228 exit(1); 239 exit(1);
240 }
229 241
230 tox_self_set_name(tox, (uint8_t *)IRC_NAME, sizeof(IRC_NAME) - 1, 0); 242 tox_self_set_name(tox, (uint8_t *)IRC_NAME, sizeof(IRC_NAME) - 1, 0);
231 tox_callback_friend_message(tox, &callback_friend_message); 243 tox_callback_friend_message(tox, &callback_friend_message);
@@ -263,8 +275,9 @@ int main(int argc, char *argv[])
263 275
264 sock = reconnect(); 276 sock = reconnect();
265 277
266 if (sock < 0) 278 if (sock < 0) {
267 return 1; 279 return 1;
280 }
268 281
269 uint64_t last_get = get_monotime_sec(); 282 uint64_t last_get = get_monotime_sec();
270 int connected = 0, ping_sent = 0; 283 int connected = 0, ping_sent = 0;
@@ -281,8 +294,9 @@ int main(int argc, char *argv[])
281 recv(sock, data, count, MSG_NOSIGNAL); 294 recv(sock, data, count, MSG_NOSIGNAL);
282 printf("%s", data); 295 printf("%s", data);
283 296
284 if (!connected) 297 if (!connected) {
285 connected = 1; 298 connected = 1;
299 }
286 300
287 if (count > 6 && data[0] == 'P' && data[1] == 'I' && data[2] == 'N' && data[3] == 'G') { 301 if (count > 6 && data[0] == 'P' && data[1] == 'I' && data[2] == 'N' && data[3] == 'G') {
288 data[1] = 'O'; 302 data[1] = 'O';
@@ -309,8 +323,9 @@ int main(int argc, char *argv[])
309 break; 323 break;
310 } 324 }
311 325
312 if (data[i] == ':') 326 if (data[i] == ':') {
313 break; 327 break;
328 }
314 } 329 }
315 330
316 for (i = 0; i < count; ++i) { 331 for (i = 0; i < count; ++i) {
@@ -329,8 +344,9 @@ int main(int argc, char *argv[])
329 if (!ping_sent && last_get + (SILENT_TIMEOUT / 2) < get_monotime_sec()) { 344 if (!ping_sent && last_get + (SILENT_TIMEOUT / 2) < get_monotime_sec()) {
330 unsigned int p_s = sizeof("PING :test\n") - 1; 345 unsigned int p_s = sizeof("PING :test\n") - 1;
331 346
332 if (send(sock, "PING :test\n", p_s, MSG_NOSIGNAL) == p_s) 347 if (send(sock, "PING :test\n", p_s, MSG_NOSIGNAL) == p_s) {
333 ping_sent = 1; 348 ping_sent = 1;
349 }
334 } 350 }
335 351
336 int error = 0; 352 int error = 0;
diff --git a/testing/misc_tools.c b/testing/misc_tools.c
index 52b739dc..ba49ebc8 100644
--- a/testing/misc_tools.c
+++ b/testing/misc_tools.c
@@ -46,8 +46,9 @@ uint8_t *hex_string_to_bin(char *hex_string)
46 uint8_t *ret = malloc(len); 46 uint8_t *ret = malloc(len);
47 char *pos = hex_string; 47 char *pos = hex_string;
48 48
49 for (i = 0; i < len; ++i, pos += 2) 49 for (i = 0; i < len; ++i, pos += 2) {
50 sscanf(pos, "%2hhx", &ret[i]); 50 sscanf(pos, "%2hhx", &ret[i]);
51 }
51 52
52 return ret; 53 return ret;
53} 54}
@@ -56,16 +57,16 @@ int cmdline_parsefor_ipv46(int argc, char **argv, uint8_t *ipv6enabled)
56{ 57{
57 int argvoffset = 0, argi; 58 int argvoffset = 0, argi;
58 59
59 for (argi = 1; argi < argc; argi++) 60 for (argi = 1; argi < argc; argi++) {
60 if (!strncasecmp(argv[argi], "--ipv", 5)) { 61 if (!strncasecmp(argv[argi], "--ipv", 5)) {
61 if (argv[argi][5] && !argv[argi][6]) { 62 if (argv[argi][5] && !argv[argi][6]) {
62 char c = argv[argi][5]; 63 char c = argv[argi][5];
63 64
64 if (c == '4') 65 if (c == '4') {
65 *ipv6enabled = 0; 66 *ipv6enabled = 0;
66 else if (c == '6') 67 } else if (c == '6') {
67 *ipv6enabled = 1; 68 *ipv6enabled = 1;
68 else { 69 } else {
69 printf("Invalid argument: %s. Try --ipv4 or --ipv6!\n", argv[argi]); 70 printf("Invalid argument: %s. Try --ipv4 or --ipv6!\n", argv[argi]);
70 return -1; 71 return -1;
71 } 72 }
@@ -81,6 +82,7 @@ int cmdline_parsefor_ipv46(int argc, char **argv, uint8_t *ipv6enabled)
81 82
82 argvoffset++; 83 argvoffset++;
83 } 84 }
85 }
84 86
85 return argvoffset; 87 return argvoffset;
86}; 88};
diff --git a/testing/nTox.c b/testing/nTox.c
index 8cc633bc..3494015c 100644
--- a/testing/nTox.c
+++ b/testing/nTox.c
@@ -152,8 +152,9 @@ uint32_t add_filesender(Tox *m, uint16_t friendnum, char *filename)
152{ 152{
153 FILE *tempfile = fopen(filename, "rb"); 153 FILE *tempfile = fopen(filename, "rb");
154 154
155 if (tempfile == 0) 155 if (tempfile == 0) {
156 return -1; 156 return -1;
157 }
157 158
158 fseek(tempfile, 0, SEEK_END); 159 fseek(tempfile, 0, SEEK_END);
159 uint64_t filesize = ftell(tempfile); 160 uint64_t filesize = ftell(tempfile);
@@ -161,8 +162,9 @@ uint32_t add_filesender(Tox *m, uint16_t friendnum, char *filename)
161 uint32_t filenum = tox_file_send(m, friendnum, TOX_FILE_KIND_DATA, filesize, 0, (uint8_t *)filename, 162 uint32_t filenum = tox_file_send(m, friendnum, TOX_FILE_KIND_DATA, filesize, 0, (uint8_t *)filename,
162 strlen(filename), 0); 163 strlen(filename), 0);
163 164
164 if (filenum == -1) 165 if (filenum == -1) {
165 return -1; 166 return -1;
167 }
166 168
167 file_senders[numfilesenders].file = tempfile; 169 file_senders[numfilesenders].file = tempfile;
168 file_senders[numfilesenders].friendnum = friendnum; 170 file_senders[numfilesenders].friendnum = friendnum;
@@ -183,11 +185,13 @@ static void fraddr_to_str(uint8_t *id_bin, char *id_str)
183 for (i = 0; i < TOX_ADDRESS_SIZE; i++) { 185 for (i = 0; i < TOX_ADDRESS_SIZE; i++) {
184 sprintf(&id_str[2 * i + delta], "%02hhX", id_bin[i]); 186 sprintf(&id_str[2 * i + delta], "%02hhX", id_bin[i]);
185 187
186 if ((i + 1) == TOX_PUBLIC_KEY_SIZE) 188 if ((i + 1) == TOX_PUBLIC_KEY_SIZE) {
187 pos_extra = 2 * (i + 1) + delta; 189 pos_extra = 2 * (i + 1) + delta;
190 }
188 191
189 if (i >= TOX_PUBLIC_KEY_SIZE) 192 if (i >= TOX_PUBLIC_KEY_SIZE) {
190 sum_extra |= id_bin[i]; 193 sum_extra |= id_bin[i];
194 }
191 195
192 if (!((i + 1) % FRADDR_TOSTR_CHUNK_LEN)) { 196 if (!((i + 1) % FRADDR_TOSTR_CHUNK_LEN)) {
193 id_str[2 * (i + 1) + delta] = ' '; 197 id_str[2 * (i + 1) + delta] = ' ';
@@ -197,8 +201,9 @@ static void fraddr_to_str(uint8_t *id_bin, char *id_str)
197 201
198 id_str[2 * i + delta] = 0; 202 id_str[2 * i + delta] = 0;
199 203
200 if (!sum_extra) 204 if (!sum_extra) {
201 id_str[pos_extra] = 0; 205 id_str[pos_extra] = 0;
206 }
202} 207}
203 208
204void get_id(Tox *m, char *data) 209void get_id(Tox *m, char *data)
@@ -215,10 +220,11 @@ int getfriendname_terminated(Tox *m, int friendnum, char *namebuf)
215 tox_friend_get_name(m, friendnum, (uint8_t *)namebuf, NULL); 220 tox_friend_get_name(m, friendnum, (uint8_t *)namebuf, NULL);
216 int res = tox_friend_get_name_size(m, friendnum, NULL); 221 int res = tox_friend_get_name_size(m, friendnum, NULL);
217 222
218 if (res >= 0) 223 if (res >= 0) {
219 namebuf[res] = 0; 224 namebuf[res] = 0;
220 else 225 } else {
221 namebuf[0] = 0; 226 namebuf[0] = 0;
227 }
222 228
223 return res; 229 return res;
224} 230}
@@ -260,10 +266,11 @@ void print_friendlist(Tox *m)
260 uint32_t i = 0; 266 uint32_t i = 0;
261 267
262 while (getfriendname_terminated(m, i, name) != -1) { 268 while (getfriendname_terminated(m, i, name) != -1) {
263 if (tox_friend_get_public_key(m, i, fraddr_bin, NULL)) 269 if (tox_friend_get_public_key(m, i, fraddr_bin, NULL)) {
264 fraddr_to_str(fraddr_bin, fraddr_str); 270 fraddr_to_str(fraddr_bin, fraddr_str);
265 else 271 } else {
266 sprintf(fraddr_str, "???"); 272 sprintf(fraddr_str, "???");
273 }
267 274
268 if (strlen(name) <= 0) { 275 if (strlen(name) <= 0) {
269 sprintf(fstring, ptrn_friend, i, "No name?", fraddr_str); 276 sprintf(fstring, ptrn_friend, i, "No name?", fraddr_str);
@@ -275,8 +282,9 @@ void print_friendlist(Tox *m)
275 new_lines(fstring); 282 new_lines(fstring);
276 } 283 }
277 284
278 if (i == 0) 285 if (i == 0) {
279 new_lines("+ no friends! D:"); 286 new_lines("+ no friends! D:");
287 }
280} 288}
281 289
282static int fmtmsg_tm_mday = -1; 290static int fmtmsg_tm_mday = -1;
@@ -338,8 +346,9 @@ void line_eval(Tox *m, char *line)
338 for (i = 0; i < 128; i++) { 346 for (i = 0; i < 128; i++) {
339 temp_id[i - delta] = line[i + prompt_offset]; 347 temp_id[i - delta] = line[i + prompt_offset];
340 348
341 if ((temp_id[i - delta] == ' ') || (temp_id[i - delta] == '+')) 349 if ((temp_id[i - delta] == ' ') || (temp_id[i - delta] == '+')) {
342 delta++; 350 delta++;
351 }
343 } 352 }
344 353
345 unsigned char *bin_string = hex_string_to_bin(temp_id); 354 unsigned char *bin_string = hex_string_to_bin(temp_id);
@@ -402,14 +411,17 @@ void line_eval(Tox *m, char *line)
402 } else { 411 } else {
403 print_formatted_message(m, *posi + 1, num, 1); 412 print_formatted_message(m, *posi + 1, num, 1);
404 } 413 }
405 } else 414 } else {
406 new_lines("Error, bad input."); 415 new_lines("Error, bad input.");
416 }
407 } else if (inpt_command == 'n') { 417 } else if (inpt_command == 'n') {
408 uint8_t name[TOX_MAX_NAME_LENGTH]; 418 uint8_t name[TOX_MAX_NAME_LENGTH];
409 size_t i, len = strlen(line); 419 size_t i, len = strlen(line);
410 420
411 for (i = 3; i < len; i++) { 421 for (i = 3; i < len; i++) {
412 if (line[i] == 0 || line[i] == '\n') break; 422 if (line[i] == 0 || line[i] == '\n') {
423 break;
424 }
413 425
414 name[i - 3] = line[i]; 426 name[i - 3] = line[i];
415 } 427 }
@@ -426,7 +438,9 @@ void line_eval(Tox *m, char *line)
426 size_t i, len = strlen(line); 438 size_t i, len = strlen(line);
427 439
428 for (i = 3; i < len; i++) { 440 for (i = 3; i < len; i++) {
429 if (line[i] == 0 || line[i] == '\n') break; 441 if (line[i] == 0 || line[i] == '\n') {
442 break;
443 }
430 444
431 status[i - 3] = line[i]; 445 status[i - 3] = line[i];
432 } 446 }
@@ -482,10 +496,11 @@ void line_eval(Tox *m, char *line)
482 if (c == 'y') { 496 if (c == 'y') {
483 int res = tox_friend_delete(m, numf, NULL); 497 int res = tox_friend_delete(m, numf, NULL);
484 498
485 if (res) 499 if (res) {
486 sprintf(msg, "[i] [%i: %s] is no longer your friend", numf, fname); 500 sprintf(msg, "[i] [%i: %s] is no longer your friend", numf, fname);
487 else 501 } else {
488 sprintf(msg, "[i] failed to remove friend"); 502 sprintf(msg, "[i] failed to remove friend");
503 }
489 504
490 new_lines(msg); 505 new_lines(msg);
491 } 506 }
@@ -555,20 +570,22 @@ void line_eval(Tox *m, char *line)
555 if (conversation_default != 0) { 570 if (conversation_default != 0) {
556 conversation_default = 0; 571 conversation_default = 0;
557 new_lines("[i] default conversation reset"); 572 new_lines("[i] default conversation reset");
558 } else 573 } else {
559 new_lines("[i] default conversation wasn't set, nothing to do"); 574 new_lines("[i] default conversation wasn't set, nothing to do");
575 }
560 } else if (line[3] != ' ') { 576 } else if (line[3] != ' ') {
561 new_lines("[i] invalid command"); 577 new_lines("[i] invalid command");
562 } else { 578 } else {
563 int num = atoi(line + 4); 579 int num = atoi(line + 4);
564 580
565 /* zero is also returned for not-a-number */ 581 /* zero is also returned for not-a-number */
566 if (!num && strcmp(line + 4, "0")) 582 if (!num && strcmp(line + 4, "0")) {
567 num = -1; 583 num = -1;
584 }
568 585
569 if (num < 0) 586 if (num < 0) {
570 new_lines("[i] invalid command parameter"); 587 new_lines("[i] invalid command parameter");
571 else if (line[2] == 'f') { 588 } else if (line[2] == 'f') {
572 conversation_default = num + 1; 589 conversation_default = num + 1;
573 char buffer[128]; 590 char buffer[128];
574 sprintf(buffer, "[i] default conversation is now to friend %i", num); 591 sprintf(buffer, "[i] default conversation is now to friend %i", num);
@@ -578,8 +595,9 @@ void line_eval(Tox *m, char *line)
578 conversation_default = - (num + 1); 595 conversation_default = - (num + 1);
579 sprintf(buffer, "[i] default conversation is now to group %i", num); 596 sprintf(buffer, "[i] default conversation is now to group %i", num);
580 new_lines(buffer); 597 new_lines(buffer);
581 } else 598 } else {
582 new_lines("[i] invalid command"); 599 new_lines("[i] invalid command");
600 }
583 } 601 }
584 } else if (inpt_command == 'p') { //list peers 602 } else if (inpt_command == 'p') { //list peers
585 char *posi = NULL; 603 char *posi = NULL;
@@ -613,8 +631,9 @@ void line_eval(Tox *m, char *line)
613 char sss[128]; 631 char sss[128];
614 sprintf(sss, "[i] could not send message to friend no. %u", friendnumber); 632 sprintf(sss, "[i] could not send message to friend no. %u", friendnumber);
615 new_lines(sss); 633 new_lines(sss);
616 } else 634 } else {
617 print_formatted_message(m, line, friendnumber, 1); 635 print_formatted_message(m, line, friendnumber, 1);
636 }
618 } else { 637 } else {
619 int groupnumber = - conversation_default - 1; 638 int groupnumber = - conversation_default - 1;
620 int res = tox_group_message_send(m, groupnumber, (uint8_t *)line, strlen(line)); 639 int res = tox_group_message_send(m, groupnumber, (uint8_t *)line, strlen(line));
@@ -629,8 +648,9 @@ void line_eval(Tox *m, char *line)
629 new_lines(msg); 648 new_lines(msg);
630 } 649 }
631 } 650 }
632 } else 651 } else {
633 new_lines("[i] invalid input: neither command nor in conversation"); 652 new_lines("[i] invalid input: neither command nor in conversation");
653 }
634 } 654 }
635} 655}
636 656
@@ -652,8 +672,9 @@ void wrap(char output[STRING_LENGTH_WRAPPED], char input[STRING_LENGTH], int lin
652 672
653 /* if the line is very very short, don't insert continuation markers, 673 /* if the line is very very short, don't insert continuation markers,
654 * as they would use up too much of the line */ 674 * as they would use up too much of the line */
655 if ((size_t)line_width < 2 * wrap_cont_len) 675 if ((size_t)line_width < 2 * wrap_cont_len) {
656 delta_remain = 0; 676 delta_remain = 0;
677 }
657 678
658 for (i = line_width; i < len; i += line_width) { 679 for (i = line_width; i < len; i += line_width) {
659 /* look backward for a space to expand/turn into a new line */ 680 /* look backward for a space to expand/turn into a new line */
@@ -685,8 +706,9 @@ void wrap(char output[STRING_LENGTH_WRAPPED], char input[STRING_LENGTH], int lin
685 } else { 706 } else {
686 /* string ends right here: 707 /* string ends right here:
687 * don't add a continuation marker with nothing following */ 708 * don't add a continuation marker with nothing following */
688 if (i == len - 1) 709 if (i == len - 1) {
689 break; 710 break;
711 }
690 712
691 /* nothing found backwards */ 713 /* nothing found backwards */
692 if (delta_remain > wrap_cont_len) { 714 if (delta_remain > wrap_cont_len) {
@@ -728,8 +750,9 @@ void wrap_bars(char output[STRING_LENGTH_WRAPPED], char input[STRING_LENGTH], si
728 /* not yet at the limit */ 750 /* not yet at the limit */
729 char c = input[ipos]; 751 char c = input[ipos];
730 752
731 if (c == ' ') 753 if (c == ' ') {
732 space_avail = opos; 754 space_avail = opos;
755 }
733 756
734 output[opos++] = input[ipos]; 757 output[opos++] = input[ipos];
735 758
@@ -751,8 +774,9 @@ void wrap_bars(char output[STRING_LENGTH_WRAPPED], char input[STRING_LENGTH], si
751 output[opos++] = ' '; 774 output[opos++] = ' ';
752 } 775 }
753 776
754 if (c == '\n') 777 if (c == '\n') {
755 nl_got = opos; 778 nl_got = opos;
779 }
756 780
757 continue; 781 continue;
758 } else { 782 } else {
@@ -807,8 +831,9 @@ void wrap_bars(char output[STRING_LENGTH_WRAPPED], char input[STRING_LENGTH], si
807 } 831 }
808 } 832 }
809 833
810 if (opos >= STRING_LENGTH_WRAPPED) 834 if (opos >= STRING_LENGTH_WRAPPED) {
811 opos = STRING_LENGTH_WRAPPED - 1; 835 opos = STRING_LENGTH_WRAPPED - 1;
836 }
812 837
813 output[opos] = 0; 838 output[opos] = 0;
814} 839}
@@ -819,8 +844,9 @@ int count_lines(char *string)
819 int count = 1; 844 int count = 1;
820 845
821 for (i = 0; i < len; i++) { 846 for (i = 0; i < len; i++) {
822 if (string[i] == '\n') 847 if (string[i] == '\n') {
823 count++; 848 count++;
849 }
824 } 850 }
825 851
826 return count; 852 return count;
@@ -845,10 +871,11 @@ void do_refresh()
845 int i; 871 int i;
846 872
847 for (i = 0; i < HISTORY; i++) { 873 for (i = 0; i < HISTORY; i++) {
848 if (flag[i]) 874 if (flag[i]) {
849 wrap_bars(wrap_output, lines[i], x); 875 wrap_bars(wrap_output, lines[i], x);
850 else 876 } else {
851 wrap(wrap_output, lines[i], x); 877 wrap(wrap_output, lines[i], x);
878 }
852 879
853 int L = count_lines(wrap_output); 880 int L = count_lines(wrap_output);
854 count = count + L; 881 count = count + L;
@@ -898,10 +925,11 @@ void print_nickchange(Tox *m, uint32_t friendnumber, const uint8_t *string, size
898 if (getfriendname_terminated(m, friendnumber, name) != -1) { 925 if (getfriendname_terminated(m, friendnumber, name) != -1) {
899 char msg[100 + length]; 926 char msg[100 + length];
900 927
901 if (name[0] != 0) 928 if (name[0] != 0) {
902 sprintf(msg, "[i] [%d] %s is now known as %s.", friendnumber, name, string); 929 sprintf(msg, "[i] [%d] %s is now known as %s.", friendnumber, name, string);
903 else 930 } else {
904 sprintf(msg, "[i] [%d] Friend's name is %s.", friendnumber, string); 931 sprintf(msg, "[i] [%d] Friend's name is %s.", friendnumber, string);
932 }
905 933
906 new_lines(msg); 934 new_lines(msg);
907 } 935 }
@@ -914,10 +942,11 @@ void print_statuschange(Tox *m, uint32_t friendnumber, const uint8_t *string, si
914 if (getfriendname_terminated(m, friendnumber, name) != -1) { 942 if (getfriendname_terminated(m, friendnumber, name) != -1) {
915 char msg[100 + length + strlen(name) + 1]; 943 char msg[100 + length + strlen(name) + 1];
916 944
917 if (name[0] != 0) 945 if (name[0] != 0) {
918 sprintf(msg, "[i] [%d] %s's status changed to %s.", friendnumber, name, string); 946 sprintf(msg, "[i] [%d] %s's status changed to %s.", friendnumber, name, string);
919 else 947 } else {
920 sprintf(msg, "[i] [%d] Their status changed to %s.", friendnumber, string); 948 sprintf(msg, "[i] [%d] Their status changed to %s.", friendnumber, string);
949 }
921 950
922 new_lines(msg); 951 new_lines(msg);
923 } 952 }
@@ -997,8 +1026,9 @@ static int save_data_file(Tox *m, char *path)
997{ 1026{
998 data_file_name = path; 1027 data_file_name = path;
999 1028
1000 if (save_data(m)) 1029 if (save_data(m)) {
1001 return 1; 1030 return 1;
1031 }
1002 1032
1003 return 0; 1033 return 0;
1004} 1034}
@@ -1032,8 +1062,9 @@ void print_groupchatpeers(Tox *m, int groupnumber)
1032{ 1062{
1033 int num = tox_group_number_peers(m, groupnumber); 1063 int num = tox_group_number_peers(m, groupnumber);
1034 1064
1035 if (num < 0) 1065 if (num < 0) {
1036 return; 1066 return;
1067 }
1037 1068
1038 if (!num) { 1069 if (!num) {
1039 new_lines("[g]+ no peers left in group."); 1070 new_lines("[g]+ no peers left in group.");
@@ -1084,13 +1115,15 @@ void print_groupmessage(Tox *m, int groupnumber, int peernumber, const uint8_t *
1084 int len = tox_group_peername(m, groupnumber, peernumber, name); 1115 int len = tox_group_peername(m, groupnumber, peernumber, name);
1085 1116
1086 //print_groupchatpeers(m, groupnumber); 1117 //print_groupchatpeers(m, groupnumber);
1087 if (len <= 0) 1118 if (len <= 0) {
1088 name[0] = 0; 1119 name[0] = 0;
1120 }
1089 1121
1090 if (name[0] != 0) 1122 if (name[0] != 0) {
1091 sprintf(msg, "[g] %u: %u <%s>: %s", groupnumber, peernumber, name, message); 1123 sprintf(msg, "[g] %u: %u <%s>: %s", groupnumber, peernumber, name, message);
1092 else 1124 } else {
1093 sprintf(msg, "[g] #%u: %u Unknown: %s", groupnumber, peernumber, message); 1125 sprintf(msg, "[g] #%u: %u Unknown: %s", groupnumber, peernumber, message);
1126 }
1094 1127
1095 new_lines(msg); 1128 new_lines(msg);
1096} 1129}
@@ -1116,8 +1149,9 @@ void print_groupnamelistchange(Tox *m, int groupnumber, int peernumber, uint8_t
1116 uint8_t peername[TOX_MAX_NAME_LENGTH] = {0}; 1149 uint8_t peername[TOX_MAX_NAME_LENGTH] = {0};
1117 int len = tox_group_peername(m, groupnumber, peernumber, peername); 1150 int len = tox_group_peername(m, groupnumber, peernumber, peername);
1118 1151
1119 if (len <= 0) 1152 if (len <= 0) {
1120 peername[0] = 0; 1153 peername[0] = 0;
1154 }
1121 1155
1122 sprintf(msg, "[g] #%i: Peer %i left. Former peer [%i: <%s>] is now peer %i.", groupnumber, peernumber, 1156 sprintf(msg, "[g] #%i: Peer %i left. Former peer [%i: <%s>] is now peer %i.", groupnumber, peernumber,
1123 peers_total, peername, peernumber); 1157 peers_total, peername, peernumber);
@@ -1127,8 +1161,9 @@ void print_groupnamelistchange(Tox *m, int groupnumber, int peernumber, uint8_t
1127 uint8_t peername[TOX_MAX_NAME_LENGTH] = {0}; 1161 uint8_t peername[TOX_MAX_NAME_LENGTH] = {0};
1128 int len = tox_group_peername(m, groupnumber, peernumber, peername); 1162 int len = tox_group_peername(m, groupnumber, peernumber, peername);
1129 1163
1130 if (len <= 0) 1164 if (len <= 0) {
1131 peername[0] = 0; 1165 peername[0] = 0;
1166 }
1132 1167
1133 sprintf(msg, "[g] #%i: Peer %i's name changed: %s", groupnumber, peernumber, peername); 1168 sprintf(msg, "[g] #%i: Peer %i's name changed: %s", groupnumber, peernumber, peername);
1134 new_lines(msg); 1169 new_lines(msg);
@@ -1154,8 +1189,9 @@ void file_request_accept(Tox *tox, uint32_t friend_number, uint32_t file_number,
1154 if (tox_file_control(tox, friend_number, file_number, TOX_FILE_CONTROL_RESUME, 0)) { 1189 if (tox_file_control(tox, friend_number, file_number, TOX_FILE_CONTROL_RESUME, 0)) {
1155 sprintf(msg, "Accepted file transfer. (saving file as: %u.%u.bin)", friend_number, file_number); 1190 sprintf(msg, "Accepted file transfer. (saving file as: %u.%u.bin)", friend_number, file_number);
1156 new_lines(msg); 1191 new_lines(msg);
1157 } else 1192 } else {
1158 new_lines("Could not accept file transfer."); 1193 new_lines("Could not accept file transfer.");
1194 }
1159} 1195}
1160 1196
1161void file_print_control(Tox *tox, uint32_t friend_number, uint32_t file_number, TOX_FILE_CONTROL control, 1197void file_print_control(Tox *tox, uint32_t friend_number, uint32_t file_number, TOX_FILE_CONTROL control,
@@ -1195,30 +1231,33 @@ void write_file(Tox *tox, uint32_t friendnumber, uint32_t filenumber, uint64_t p
1195 sprintf(filename, "%u.%u.bin", friendnumber, filenumber); 1231 sprintf(filename, "%u.%u.bin", friendnumber, filenumber);
1196 FILE *pFile = fopen(filename, "r+b"); 1232 FILE *pFile = fopen(filename, "r+b");
1197 1233
1198 if (pFile == NULL) 1234 if (pFile == NULL) {
1199 pFile = fopen(filename, "wb"); 1235 pFile = fopen(filename, "wb");
1236 }
1200 1237
1201 fseek(pFile, position, SEEK_SET); 1238 fseek(pFile, position, SEEK_SET);
1202 1239
1203 if (fwrite(data, length, 1, pFile) != 1) 1240 if (fwrite(data, length, 1, pFile) != 1) {
1204 new_lines("Error writing to file"); 1241 new_lines("Error writing to file");
1242 }
1205 1243
1206 fclose(pFile); 1244 fclose(pFile);
1207} 1245}
1208 1246
1209void print_online(Tox *tox, uint32_t friendnumber, TOX_CONNECTION status, void *userdata) 1247void print_online(Tox *tox, uint32_t friendnumber, TOX_CONNECTION status, void *userdata)
1210{ 1248{
1211 if (status) 1249 if (status) {
1212 printf("\nOther went online.\n"); 1250 printf("\nOther went online.\n");
1213 else { 1251 } else {
1214 printf("\nOther went offline.\n"); 1252 printf("\nOther went offline.\n");
1215 unsigned int i; 1253 unsigned int i;
1216 1254
1217 for (i = 0; i < NUM_FILE_SENDERS; ++i) 1255 for (i = 0; i < NUM_FILE_SENDERS; ++i) {
1218 if (file_senders[i].file != 0 && file_senders[i].friendnum == friendnumber) { 1256 if (file_senders[i].file != 0 && file_senders[i].friendnum == friendnumber) {
1219 fclose(file_senders[i].file); 1257 fclose(file_senders[i].file);
1220 file_senders[i].file = 0; 1258 file_senders[i].file = 0;
1221 } 1259 }
1260 }
1222 } 1261 }
1223} 1262}
1224 1263
@@ -1266,8 +1305,9 @@ int main(int argc, char *argv[])
1266 uint8_t ipv6enabled = 1; /* x */ 1305 uint8_t ipv6enabled = 1; /* x */
1267 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 1306 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
1268 1307
1269 if (argvoffset < 0) 1308 if (argvoffset < 0) {
1270 exit(1); 1309 exit(1);
1310 }
1271 1311
1272 int on = 0; 1312 int on = 0;
1273 char *filename = "data"; 1313 char *filename = "data";
@@ -1276,9 +1316,11 @@ int main(int argc, char *argv[])
1276 1316
1277 /* [-f keyfile] MUST be last two arguments, no point in walking over the list 1317 /* [-f keyfile] MUST be last two arguments, no point in walking over the list
1278 * especially not a good idea to accept it anywhere in the middle */ 1318 * especially not a good idea to accept it anywhere in the middle */
1279 if (argc > argvoffset + 3) 1319 if (argc > argvoffset + 3) {
1280 if (!strcmp(argv[argc - 2], "-f")) 1320 if (!strcmp(argv[argc - 2], "-f")) {
1281 filename = argv[argc - 1]; 1321 filename = argv[argc - 1];
1322 }
1323 }
1282 1324
1283 data_file_name = filename; 1325 data_file_name = filename;
1284 m = load_data(); 1326 m = load_data();
@@ -1359,8 +1401,9 @@ int main(int argc, char *argv[])
1359 1401
1360 int c = timeout_getch(m); 1402 int c = timeout_getch(m);
1361 1403
1362 if (c == ERR || c == 27) 1404 if (c == ERR || c == 27) {
1363 continue; 1405 continue;
1406 }
1364 1407
1365 getmaxyx(stdscr, y, x); 1408 getmaxyx(stdscr, y, x);
1366 1409
diff --git a/testing/tox_shell.c b/testing/tox_shell.c
index 9c71a2d7..f6dae7b9 100644
--- a/testing/tox_shell.c
+++ b/testing/tox_shell.c
@@ -47,10 +47,11 @@
47 47
48void print_online(Tox *tox, uint32_t friendnumber, TOX_CONNECTION status, void *userdata) 48void print_online(Tox *tox, uint32_t friendnumber, TOX_CONNECTION status, void *userdata)
49{ 49{
50 if (status) 50 if (status) {
51 printf("\nOther went online.\n"); 51 printf("\nOther went online.\n");
52 else 52 } else {
53 printf("\nOther went offline.\n"); 53 printf("\nOther went offline.\n");
54 }
54} 55}
55 56
56void print_message(Tox *tox, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const uint8_t *string, size_t length, 57void print_message(Tox *tox, uint32_t friendnumber, TOX_MESSAGE_TYPE type, const uint8_t *string, size_t length,
@@ -66,8 +67,9 @@ int main(int argc, char *argv[])
66 uint8_t ipv6enabled = 1; /* x */ 67 uint8_t ipv6enabled = 1; /* x */
67 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 68 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
68 69
69 if (argvoffset < 0) 70 if (argvoffset < 0) {
70 exit(1); 71 exit(1);
72 }
71 73
72 /* with optional --ipvx, now it can be 1-4 arguments... */ 74 /* with optional --ipvx, now it can be 1-4 arguments... */
73 if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) { 75 if ((argc != argvoffset + 2) && (argc != argvoffset + 4)) {
@@ -147,8 +149,9 @@ int main(int argc, char *argv[])
147 uint8_t buf[TOX_MAX_MESSAGE_LENGTH]; 149 uint8_t buf[TOX_MAX_MESSAGE_LENGTH];
148 ret = read(*master, buf, sizeof(buf)); 150 ret = read(*master, buf, sizeof(buf));
149 151
150 if (ret <= 0) 152 if (ret <= 0) {
151 break; 153 break;
154 }
152 155
153 tox_friend_send_message(tox, num, TOX_MESSAGE_TYPE_NORMAL, buf, ret, 0); 156 tox_friend_send_message(tox, num, TOX_MESSAGE_TYPE_NORMAL, buf, ret, 0);
154 } 157 }
diff --git a/testing/tox_sync.c b/testing/tox_sync.c
index a90e343e..c80db339 100644
--- a/testing/tox_sync.c
+++ b/testing/tox_sync.c
@@ -82,8 +82,9 @@ uint32_t add_filesender(Tox *m, uint16_t friendnum, char *filename)
82{ 82{
83 FILE *tempfile = fopen(filename, "rb"); 83 FILE *tempfile = fopen(filename, "rb");
84 84
85 if (tempfile == 0) 85 if (tempfile == 0) {
86 return -1; 86 return -1;
87 }
87 88
88 fseek(tempfile, 0, SEEK_END); 89 fseek(tempfile, 0, SEEK_END);
89 uint64_t filesize = ftell(tempfile); 90 uint64_t filesize = ftell(tempfile);
@@ -91,8 +92,9 @@ uint32_t add_filesender(Tox *m, uint16_t friendnum, char *filename)
91 uint32_t filenum = tox_file_send(m, friendnum, TOX_FILE_KIND_DATA, filesize, 0, (uint8_t *)filename, 92 uint32_t filenum = tox_file_send(m, friendnum, TOX_FILE_KIND_DATA, filesize, 0, (uint8_t *)filename,
92 strlen(filename), 0); 93 strlen(filename), 0);
93 94
94 if (filenum == -1) 95 if (filenum == -1) {
95 return -1; 96 return -1;
97 }
96 98
97 file_senders[numfilesenders].file = tempfile; 99 file_senders[numfilesenders].file = tempfile;
98 file_senders[numfilesenders].friendnum = friendnum; 100 file_senders[numfilesenders].friendnum = friendnum;
@@ -105,19 +107,22 @@ void kill_filesender(Tox *m, uint32_t filenum)
105{ 107{
106 uint32_t i; 108 uint32_t i;
107 109
108 for (i = 0; i < NUM_FILE_SENDERS; ++i) 110 for (i = 0; i < NUM_FILE_SENDERS; ++i) {
109 if (file_senders[i].file != 0 && file_senders[i].filenumber == filenum) { 111 if (file_senders[i].file != 0 && file_senders[i].filenumber == filenum) {
110 fclose(file_senders[i].file); 112 fclose(file_senders[i].file);
111 file_senders[i].file = 0; 113 file_senders[i].file = 0;
112 } 114 }
115 }
113} 116}
114int not_sending() 117int not_sending()
115{ 118{
116 uint32_t i; 119 uint32_t i;
117 120
118 for (i = 0; i < NUM_FILE_SENDERS; ++i) 121 for (i = 0; i < NUM_FILE_SENDERS; ++i) {
119 if (file_senders[i].file != 0) 122 if (file_senders[i].file != 0) {
120 return 0; 123 return 0;
124 }
125 }
121 126
122 return 1; 127 return 1;
123} 128}
@@ -138,14 +143,16 @@ void file_request_accept(Tox *tox, uint32_t friend_number, uint32_t file_number,
138 uint16_t rm = 0; 143 uint16_t rm = 0;
139 144
140 for (i = 0; i < strlen((char *)filename); ++i) { 145 for (i = 0; i < strlen((char *)filename); ++i) {
141 if (filename[i] == '/') 146 if (filename[i] == '/') {
142 rm = i; 147 rm = i;
148 }
143 } 149 }
144 150
145 if (path[strlen(path) - 1] == '/') 151 if (path[strlen(path) - 1] == '/') {
146 sprintf(fullpath, "%s%s", path, filename + rm + 1); 152 sprintf(fullpath, "%s%s", path, filename + rm + 1);
147 else 153 } else {
148 sprintf(fullpath, "%s/%s", path, filename + rm + 1); 154 sprintf(fullpath, "%s/%s", path, filename + rm + 1);
155 }
149 156
150 FILE *tempfile = fopen(fullpath, "rb"); 157 FILE *tempfile = fopen(fullpath, "rb");
151 158
@@ -202,16 +209,17 @@ void write_file(Tox *tox, uint32_t friendnumber, uint32_t filenumber, uint64_t p
202 if (file_recv[file_index].file != 0) { 209 if (file_recv[file_index].file != 0) {
203 fseek(file_recv[file_index].file, position, SEEK_SET); 210 fseek(file_recv[file_index].file, position, SEEK_SET);
204 211
205 if (fwrite(data, length, 1, file_recv[file_index].file) != 1) 212 if (fwrite(data, length, 1, file_recv[file_index].file) != 1) {
206 printf("Error writing data\n"); 213 printf("Error writing data\n");
214 }
207 } 215 }
208} 216}
209 217
210void print_online(Tox *tox, uint32_t friendnumber, TOX_CONNECTION status, void *userdata) 218void print_online(Tox *tox, uint32_t friendnumber, TOX_CONNECTION status, void *userdata)
211{ 219{
212 if (status) 220 if (status) {
213 printf("\nOther went online.\n"); 221 printf("\nOther went online.\n");
214 else { 222 } else {
215 printf("\nOther went offline.\n"); 223 printf("\nOther went offline.\n");
216 unsigned int i; 224 unsigned int i;
217 225
@@ -234,8 +242,9 @@ int main(int argc, char *argv[])
234 uint8_t ipv6enabled = 1; /* x */ 242 uint8_t ipv6enabled = 1; /* x */
235 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled); 243 int argvoffset = cmdline_parsefor_ipv46(argc, argv, &ipv6enabled);
236 244
237 if (argvoffset < 0) 245 if (argvoffset < 0) {
238 exit(1); 246 exit(1);
247 }
239 248
240 /* with optional --ipvx, now it can be 1-4 arguments... */ 249 /* with optional --ipvx, now it can be 1-4 arguments... */
241 if ((argc != argvoffset + 3) && (argc != argvoffset + 5)) { 250 if ((argc != argvoffset + 3) && (argc != argvoffset + 5)) {
@@ -303,10 +312,11 @@ int main(int argc, char *argv[])
303 if (dir->d_type == DT_REG) { 312 if (dir->d_type == DT_REG) {
304 char fullpath[1024]; 313 char fullpath[1024];
305 314
306 if (path[strlen(path) - 1] == '/') 315 if (path[strlen(path) - 1] == '/') {
307 sprintf(fullpath, "%s%s", path, dir->d_name); 316 sprintf(fullpath, "%s%s", path, dir->d_name);
308 else 317 } else {
309 sprintf(fullpath, "%s/%s", path, dir->d_name); 318 sprintf(fullpath, "%s/%s", path, dir->d_name);
319 }
310 320
311 add_filesender(tox, num, fullpath); 321 add_filesender(tox, num, fullpath);
312 } 322 }
diff --git a/toxav/audio.c b/toxav/audio.c
index 9fd8f6f1..eaa1f6d0 100644
--- a/toxav/audio.c
+++ b/toxav/audio.c
@@ -76,8 +76,9 @@ ACSession *ac_new(Logger *log, ToxAV *av, uint32_t friend_number, toxav_audio_re
76 /* Initialize encoders with default values */ 76 /* Initialize encoders with default values */
77 ac->encoder = create_audio_encoder(log, 48000, 48000, 2); 77 ac->encoder = create_audio_encoder(log, 48000, 48000, 2);
78 78
79 if (ac->encoder == NULL) 79 if (ac->encoder == NULL) {
80 goto DECODER_CLEANUP; 80 goto DECODER_CLEANUP;
81 }
81 82
82 ac->le_bit_rate = 48000; 83 ac->le_bit_rate = 48000;
83 ac->le_sample_rate = 48000; 84 ac->le_sample_rate = 48000;
@@ -110,8 +111,9 @@ BASE_CLEANUP:
110} 111}
111void ac_kill(ACSession *ac) 112void ac_kill(ACSession *ac)
112{ 113{
113 if (!ac) 114 if (!ac) {
114 return; 115 return;
116 }
115 117
116 opus_encoder_destroy(ac->encoder); 118 opus_encoder_destroy(ac->encoder);
117 opus_decoder_destroy(ac->decoder); 119 opus_decoder_destroy(ac->decoder);
@@ -124,8 +126,9 @@ void ac_kill(ACSession *ac)
124} 126}
125void ac_iterate(ACSession *ac) 127void ac_iterate(ACSession *ac)
126{ 128{
127 if (!ac) 129 if (!ac) {
128 return; 130 return;
131 }
129 132
130 /* TODO fix this and jitter buffering */ 133 /* TODO fix this and jitter buffering */
131 134
@@ -196,8 +199,9 @@ void ac_iterate(ACSession *ac)
196} 199}
197int ac_queue_message(void *acp, struct RTPMessage *msg) 200int ac_queue_message(void *acp, struct RTPMessage *msg)
198{ 201{
199 if (!acp || !msg) 202 if (!acp || !msg) {
200 return -1; 203 return -1;
204 }
201 205
202 ACSession *ac = acp; 206 ACSession *ac = acp;
203 207
@@ -231,8 +235,9 @@ int ac_reconfigure_encoder(ACSession *ac, int32_t bit_rate, int32_t sampling_rat
231 sampling_rate, channels, 235 sampling_rate, channels,
232 &ac->le_bit_rate, 236 &ac->le_bit_rate,
233 &ac->le_sample_rate, 237 &ac->le_sample_rate,
234 &ac->le_channel_count)) 238 &ac->le_channel_count)) {
235 return -1; 239 return -1;
240 }
236 241
237 return 0; 242 return 0;
238} 243}
@@ -257,7 +262,9 @@ static struct JitterBuffer *jbuf_new(uint32_t capacity)
257 262
258 struct JitterBuffer *q; 263 struct JitterBuffer *q;
259 264
260 if (!(q = calloc(sizeof(struct JitterBuffer), 1))) return NULL; 265 if (!(q = calloc(sizeof(struct JitterBuffer), 1))) {
266 return NULL;
267 }
261 268
262 if (!(q->queue = calloc(sizeof(struct RTPMessage *), size))) { 269 if (!(q->queue = calloc(sizeof(struct RTPMessage *), size))) {
263 free(q); 270 free(q);
@@ -279,7 +286,9 @@ static void jbuf_clear(struct JitterBuffer *q)
279} 286}
280static void jbuf_free(struct JitterBuffer *q) 287static void jbuf_free(struct JitterBuffer *q)
281{ 288{
282 if (!q) return; 289 if (!q) {
290 return;
291 }
283 292
284 jbuf_clear(q); 293 jbuf_clear(q);
285 free(q->queue); 294 free(q->queue);
@@ -301,13 +310,15 @@ static int jbuf_write(Logger *log, struct JitterBuffer *q, struct RTPMessage *m)
301 return 0; 310 return 0;
302 } 311 }
303 312
304 if (q->queue[num]) 313 if (q->queue[num]) {
305 return -1; 314 return -1;
315 }
306 316
307 q->queue[num] = m; 317 q->queue[num] = m;
308 318
309 if ((sequnum - q->bottom) >= (q->top - q->bottom)) 319 if ((sequnum - q->bottom) >= (q->top - q->bottom)) {
310 q->top = sequnum + 1; 320 q->top = sequnum + 1;
321 }
311 322
312 return 0; 323 return 0;
313} 324}
@@ -394,14 +405,15 @@ bool reconfigure_audio_encoder(Logger *log, OpusEncoder **e, int32_t new_br, int
394 if (*old_sr != new_sr || *old_ch != new_ch) { 405 if (*old_sr != new_sr || *old_ch != new_ch) {
395 OpusEncoder *new_encoder = create_audio_encoder(log, new_br, new_sr, new_ch); 406 OpusEncoder *new_encoder = create_audio_encoder(log, new_br, new_sr, new_ch);
396 407
397 if (new_encoder == NULL) 408 if (new_encoder == NULL) {
398 return false; 409 return false;
410 }
399 411
400 opus_encoder_destroy(*e); 412 opus_encoder_destroy(*e);
401 *e = new_encoder; 413 *e = new_encoder;
402 } else if (*old_br == new_br) 414 } else if (*old_br == new_br) {
403 return true; /* Nothing changed */ 415 return true; /* Nothing changed */
404 else { 416 } else {
405 int status = opus_encoder_ctl(*e, OPUS_SET_BITRATE(new_br)); 417 int status = opus_encoder_ctl(*e, OPUS_SET_BITRATE(new_br));
406 418
407 if (status != OPUS_OK) { 419 if (status != OPUS_OK) {
@@ -420,8 +432,9 @@ bool reconfigure_audio_encoder(Logger *log, OpusEncoder **e, int32_t new_br, int
420bool reconfigure_audio_decoder(ACSession *ac, int32_t sampling_rate, int8_t channels) 432bool reconfigure_audio_decoder(ACSession *ac, int32_t sampling_rate, int8_t channels)
421{ 433{
422 if (sampling_rate != ac->ld_sample_rate || channels != ac->ld_channel_count) { 434 if (sampling_rate != ac->ld_sample_rate || channels != ac->ld_channel_count) {
423 if (current_time_monotonic() - ac->ldrts < 500) 435 if (current_time_monotonic() - ac->ldrts < 500) {
424 return false; 436 return false;
437 }
425 438
426 int status; 439 int status;
427 OpusDecoder *new_dec = opus_decoder_create(sampling_rate, channels, &status); 440 OpusDecoder *new_dec = opus_decoder_create(sampling_rate, channels, &status);
diff --git a/toxav/bwcontroller.c b/toxav/bwcontroller.c
index cd574266..4d3b7f7d 100644
--- a/toxav/bwcontroller.c
+++ b/toxav/bwcontroller.c
@@ -78,8 +78,9 @@ BWController *bwc_new(Messenger *m, uint32_t friendnumber,
78 /* Fill with zeros */ 78 /* Fill with zeros */
79 int i = 0; 79 int i = 0;
80 80
81 for (; i < BWC_AVG_PKT_COUNT; i ++) 81 for (; i < BWC_AVG_PKT_COUNT; i ++) {
82 rb_write(retu->rcvpkt.rb, retu->rcvpkt.rb_s + i); 82 rb_write(retu->rcvpkt.rb, retu->rcvpkt.rb_s + i);
83 }
83 84
84 m_callback_rtp_packet(m, friendnumber, BWC_PACKET_ID, bwc_handle_data, retu); 85 m_callback_rtp_packet(m, friendnumber, BWC_PACKET_ID, bwc_handle_data, retu);
85 86
@@ -87,8 +88,9 @@ BWController *bwc_new(Messenger *m, uint32_t friendnumber,
87} 88}
88void bwc_kill(BWController *bwc) 89void bwc_kill(BWController *bwc)
89{ 90{
90 if (!bwc) 91 if (!bwc) {
91 return; 92 return;
93 }
92 94
93 m_callback_rtp_packet(bwc->m, bwc->friend_number, BWC_PACKET_ID, NULL, NULL); 95 m_callback_rtp_packet(bwc->m, bwc->friend_number, BWC_PACKET_ID, NULL, NULL);
94 96
@@ -106,8 +108,9 @@ void bwc_feed_avg(BWController *bwc, uint32_t bytes)
106} 108}
107void bwc_add_lost(BWController *bwc, uint32_t bytes) 109void bwc_add_lost(BWController *bwc, uint32_t bytes)
108{ 110{
109 if (!bwc) 111 if (!bwc) {
110 return; 112 return;
113 }
111 114
112 if (!bytes) { 115 if (!bytes) {
113 uint32_t *t_avg[BWC_AVG_PKT_COUNT], c = 1; 116 uint32_t *t_avg[BWC_AVG_PKT_COUNT], c = 1;
@@ -119,8 +122,9 @@ void bwc_add_lost(BWController *bwc, uint32_t bytes)
119 for (; i < BWC_AVG_PKT_COUNT; i ++) { 122 for (; i < BWC_AVG_PKT_COUNT; i ++) {
120 bytes += *(t_avg[i]); 123 bytes += *(t_avg[i]);
121 124
122 if (*(t_avg[i])) 125 if (*(t_avg[i])) {
123 c++; 126 c++;
127 }
124 } 128 }
125 129
126 bytes /= c; 130 bytes /= c;
@@ -131,8 +135,9 @@ void bwc_add_lost(BWController *bwc, uint32_t bytes)
131} 135}
132void bwc_add_recv(BWController *bwc, uint32_t bytes) 136void bwc_add_recv(BWController *bwc, uint32_t bytes)
133{ 137{
134 if (!bwc || !bytes) 138 if (!bwc || !bytes) {
135 return; 139 return;
140 }
136 141
137 bwc->cycle.recv += bytes; 142 bwc->cycle.recv += bytes;
138 send_update(bwc); 143 send_update(bwc);
@@ -164,8 +169,9 @@ void send_update(BWController *bwc)
164 b_msg->lost = htonl(bwc->cycle.lost); 169 b_msg->lost = htonl(bwc->cycle.lost);
165 b_msg->recv = htonl(bwc->cycle.recv); 170 b_msg->recv = htonl(bwc->cycle.recv);
166 171
167 if (-1 == send_custom_lossy_packet(bwc->m, bwc->friend_number, p_msg, sizeof(p_msg))) 172 if (-1 == send_custom_lossy_packet(bwc->m, bwc->friend_number, p_msg, sizeof(p_msg))) {
168 LOGGER_WARNING(bwc->m->log, "BWC send failed (len: %d)! std error: %s", sizeof(p_msg), strerror(errno)); 173 LOGGER_WARNING(bwc->m->log, "BWC send failed (len: %d)! std error: %s", sizeof(p_msg), strerror(errno));
174 }
169 } 175 }
170 176
171 bwc->cycle.lsu = current_time_monotonic(); 177 bwc->cycle.lsu = current_time_monotonic();
@@ -188,17 +194,19 @@ int on_update (BWController *bwc, struct BWCMessage *msg)
188 194
189 LOGGER_DEBUG(bwc->m->log, "recved: %u lost: %u", msg->recv, msg->lost); 195 LOGGER_DEBUG(bwc->m->log, "recved: %u lost: %u", msg->recv, msg->lost);
190 196
191 if (msg->lost && bwc->mcb) 197 if (msg->lost && bwc->mcb) {
192 bwc->mcb(bwc, bwc->friend_number, 198 bwc->mcb(bwc, bwc->friend_number,
193 ((float) (msg->lost) / (msg->recv + msg->lost)), 199 ((float) (msg->lost) / (msg->recv + msg->lost)),
194 bwc->mcb_data); 200 bwc->mcb_data);
201 }
195 202
196 return 0; 203 return 0;
197} 204}
198int bwc_handle_data(Messenger *m, uint32_t friendnumber, const uint8_t *data, uint16_t length, void *object) 205int bwc_handle_data(Messenger *m, uint32_t friendnumber, const uint8_t *data, uint16_t length, void *object)
199{ 206{
200 if (length - 1 != sizeof(struct BWCMessage)) 207 if (length - 1 != sizeof(struct BWCMessage)) {
201 return -1; 208 return -1;
209 }
202 210
203 /* NOTE the data is mutable */ 211 /* NOTE the data is mutable */
204 return on_update(object, (struct BWCMessage *) (data + 1)); 212 return on_update(object, (struct BWCMessage *) (data + 1));
diff --git a/toxav/group.c b/toxav/group.c
index 1d083444..88d9bd5a 100644
--- a/toxav/group.c
+++ b/toxav/group.c
@@ -54,7 +54,9 @@ static Group_JitterBuffer *create_queue(unsigned int capacity)
54 54
55 Group_JitterBuffer *q; 55 Group_JitterBuffer *q;
56 56
57 if (!(q = calloc(sizeof(Group_JitterBuffer), 1))) return NULL; 57 if (!(q = calloc(sizeof(Group_JitterBuffer), 1))) {
58 return NULL;
59 }
58 60
59 if (!(q->queue = calloc(sizeof(Group_Audio_Packet *), size))) { 61 if (!(q->queue = calloc(sizeof(Group_Audio_Packet *), size))) {
60 free(q); 62 free(q);
@@ -78,7 +80,9 @@ static void clear_queue(Group_JitterBuffer *q)
78 80
79static void terminate_queue(Group_JitterBuffer *q) 81static void terminate_queue(Group_JitterBuffer *q)
80{ 82{
81 if (!q) return; 83 if (!q) {
84 return;
85 }
82 86
83 clear_queue(q); 87 clear_queue(q);
84 free(q->queue); 88 free(q->queue);
@@ -109,13 +113,15 @@ static int queue(Group_JitterBuffer *q, Group_Audio_Packet *pk)
109 return 0; 113 return 0;
110 } 114 }
111 115
112 if (q->queue[num]) 116 if (q->queue[num]) {
113 return -1; 117 return -1;
118 }
114 119
115 q->queue[num] = pk; 120 q->queue[num] = pk;
116 121
117 if ((sequnum - q->bottom) >= (q->top - q->bottom)) 122 if ((sequnum - q->bottom) >= (q->top - q->bottom)) {
118 q->top = sequnum + 1; 123 q->top = sequnum + 1;
124 }
119 125
120 q->last_queued_time = unix_time(); 126 q->last_queued_time = unix_time();
121 return 0; 127 return 0;
@@ -222,13 +228,15 @@ static Group_AV *new_group_av(Logger *log, Group_Chats *g_c, void (*audio_callba
222 const int16_t *, 228 const int16_t *,
223 unsigned int, uint8_t, unsigned int, void *), void *userdata) 229 unsigned int, uint8_t, unsigned int, void *), void *userdata)
224{ 230{
225 if (!g_c) 231 if (!g_c) {
226 return NULL; 232 return NULL;
233 }
227 234
228 Group_AV *group_av = calloc(1, sizeof(Group_AV)); 235 Group_AV *group_av = calloc(1, sizeof(Group_AV));
229 236
230 if (!group_av) 237 if (!group_av) {
231 return NULL; 238 return NULL;
239 }
232 240
233 group_av->log = log; 241 group_av->log = log;
234 group_av->g_c = g_c; 242 group_av->g_c = g_c;
@@ -244,8 +252,9 @@ static void group_av_peer_new(void *object, int groupnumber, int friendgroupnumb
244 Group_AV *group_av = object; 252 Group_AV *group_av = object;
245 Group_Peer_AV *peer_av = calloc(1, sizeof(Group_Peer_AV)); 253 Group_Peer_AV *peer_av = calloc(1, sizeof(Group_Peer_AV));
246 254
247 if (!peer_av) 255 if (!peer_av) {
248 return; 256 return;
257 }
249 258
250 peer_av->buffer = create_queue(GROUP_JBUF_SIZE); 259 peer_av->buffer = create_queue(GROUP_JBUF_SIZE);
251 group_peer_set_object(group_av->g_c, groupnumber, friendgroupnumber, peer_av); 260 group_peer_set_object(group_av->g_c, groupnumber, friendgroupnumber, peer_av);
@@ -255,11 +264,13 @@ static void group_av_peer_delete(void *object, int groupnumber, int friendgroupn
255{ 264{
256 Group_Peer_AV *peer_av = peer_object; 265 Group_Peer_AV *peer_av = peer_object;
257 266
258 if (!peer_av) 267 if (!peer_av) {
259 return; 268 return;
269 }
260 270
261 if (peer_av->audio_decoder) 271 if (peer_av->audio_decoder) {
262 opus_decoder_destroy(peer_av->audio_decoder); 272 opus_decoder_destroy(peer_av->audio_decoder);
273 }
263 274
264 terminate_queue(peer_av->buffer); 275 terminate_queue(peer_av->buffer);
265 free(peer_object); 276 free(peer_object);
@@ -267,20 +278,23 @@ static void group_av_peer_delete(void *object, int groupnumber, int friendgroupn
267 278
268static void group_av_groupchat_delete(void *object, int groupnumber) 279static void group_av_groupchat_delete(void *object, int groupnumber)
269{ 280{
270 if (object) 281 if (object) {
271 kill_group_av(object); 282 kill_group_av(object);
283 }
272} 284}
273 285
274static int decode_audio_packet(Group_AV *group_av, Group_Peer_AV *peer_av, int groupnumber, int friendgroupnumber) 286static int decode_audio_packet(Group_AV *group_av, Group_Peer_AV *peer_av, int groupnumber, int friendgroupnumber)
275{ 287{
276 if (!group_av || !peer_av) 288 if (!group_av || !peer_av) {
277 return -1; 289 return -1;
290 }
278 291
279 int success; 292 int success;
280 Group_Audio_Packet *pk = dequeue(peer_av->buffer, &success); 293 Group_Audio_Packet *pk = dequeue(peer_av->buffer, &success);
281 294
282 if (success == 0) 295 if (success == 0) {
283 return -1; 296 return -1;
297 }
284 298
285 int16_t *out_audio = NULL; 299 int16_t *out_audio = NULL;
286 int out_audio_samples = 0; 300 int out_audio_samples = 0;
@@ -330,16 +344,19 @@ static int decode_audio_packet(Group_AV *group_av, Group_Peer_AV *peer_av, int g
330 out_audio_samples = opus_decode(peer_av->audio_decoder, pk->data, pk->length, out_audio, num_samples, 0); 344 out_audio_samples = opus_decode(peer_av->audio_decoder, pk->data, pk->length, out_audio, num_samples, 0);
331 free(pk); 345 free(pk);
332 346
333 if (out_audio_samples <= 0) 347 if (out_audio_samples <= 0) {
334 return -1; 348 return -1;
349 }
335 350
336 peer_av->last_packet_samples = out_audio_samples; 351 peer_av->last_packet_samples = out_audio_samples;
337 } else { 352 } else {
338 if (!peer_av->audio_decoder) 353 if (!peer_av->audio_decoder) {
339 return -1; 354 return -1;
355 }
340 356
341 if (!peer_av->last_packet_samples) 357 if (!peer_av->last_packet_samples) {
342 return -1; 358 return -1;
359 }
343 360
344 out_audio = malloc(peer_av->last_packet_samples * peer_av->decoder_channels * sizeof(int16_t)); 361 out_audio = malloc(peer_av->last_packet_samples * peer_av->decoder_channels * sizeof(int16_t));
345 362
@@ -350,16 +367,18 @@ static int decode_audio_packet(Group_AV *group_av, Group_Peer_AV *peer_av, int g
350 367
351 out_audio_samples = opus_decode(peer_av->audio_decoder, NULL, 0, out_audio, peer_av->last_packet_samples, 1); 368 out_audio_samples = opus_decode(peer_av->audio_decoder, NULL, 0, out_audio, peer_av->last_packet_samples, 1);
352 369
353 if (out_audio_samples <= 0) 370 if (out_audio_samples <= 0) {
354 return -1; 371 return -1;
372 }
355 373
356 } 374 }
357 375
358 if (out_audio) { 376 if (out_audio) {
359 377
360 if (group_av->audio_data) 378 if (group_av->audio_data) {
361 group_av->audio_data(group_av->g_c->m, groupnumber, friendgroupnumber, out_audio, out_audio_samples, 379 group_av->audio_data(group_av->g_c->m, groupnumber, friendgroupnumber, out_audio, out_audio_samples,
362 peer_av->decoder_channels, sample_rate, group_av->userdata); 380 peer_av->decoder_channels, sample_rate, group_av->userdata);
381 }
363 382
364 free(out_audio); 383 free(out_audio);
365 return 0; 384 return 0;
@@ -394,7 +413,9 @@ static int handle_group_audio_packet(void *object, int groupnumber, int friendgr
394 return -1; 413 return -1;
395 } 414 }
396 415
397 while (decode_audio_packet(object, peer_av, groupnumber, friendgroupnumber) == 0); 416 while (decode_audio_packet(object, peer_av, groupnumber, friendgroupnumber) == 0) {
417 ;
418 }
398 419
399 return 0; 420 return 0;
400} 421}
@@ -408,13 +429,15 @@ static int groupchat_enable_av(Logger *log, Group_Chats *g_c, int groupnumber, v
408 int, 429 int,
409 const int16_t *, unsigned int, uint8_t, unsigned int, void *), void *userdata) 430 const int16_t *, unsigned int, uint8_t, unsigned int, void *), void *userdata)
410{ 431{
411 if (groupnumber == -1) 432 if (groupnumber == -1) {
412 return -1; 433 return -1;
434 }
413 435
414 Group_AV *group_av = new_group_av(log, g_c, audio_callback, userdata); 436 Group_AV *group_av = new_group_av(log, g_c, audio_callback, userdata);
415 437
416 if (group_av == NULL) 438 if (group_av == NULL) {
417 return -1; 439 return -1;
440 }
418 441
419 if (group_set_object(g_c, groupnumber, group_av) == -1 442 if (group_set_object(g_c, groupnumber, group_av) == -1
420 || callback_groupchat_peer_new(g_c, groupnumber, group_av_peer_new) == -1 443 || callback_groupchat_peer_new(g_c, groupnumber, group_av_peer_new) == -1
@@ -481,8 +504,9 @@ int join_av_groupchat(Logger *log, Group_Chats *g_c, int32_t friendnumber, const
481 */ 504 */
482static int send_audio_packet(Group_Chats *g_c, int groupnumber, uint8_t *packet, uint16_t length) 505static int send_audio_packet(Group_Chats *g_c, int groupnumber, uint8_t *packet, uint16_t length)
483{ 506{
484 if (!length) 507 if (!length) {
485 return -1; 508 return -1;
509 }
486 510
487 Group_AV *group_av = group_get_object(g_c, groupnumber); 511 Group_AV *group_av = group_get_object(g_c, groupnumber);
488 uint8_t data[1 + sizeof(uint16_t) + length]; 512 uint8_t data[1 + sizeof(uint16_t) + length];
@@ -492,8 +516,9 @@ static int send_audio_packet(Group_Chats *g_c, int groupnumber, uint8_t *packet,
492 memcpy(data + 1, &sequnum, sizeof(sequnum)); 516 memcpy(data + 1, &sequnum, sizeof(sequnum));
493 memcpy(data + 1 + sizeof(sequnum), packet, length); 517 memcpy(data + 1 + sizeof(sequnum), packet, length);
494 518
495 if (send_group_lossy_packet(g_c, groupnumber, data, sizeof(data)) == -1) 519 if (send_group_lossy_packet(g_c, groupnumber, data, sizeof(data)) == -1) {
496 return -1; 520 return -1;
521 }
497 522
498 ++group_av->audio_sequnum; 523 ++group_av->audio_sequnum;
499 return 0; 524 return 0;
@@ -509,14 +534,18 @@ int group_send_audio(Group_Chats *g_c, int groupnumber, const int16_t *pcm, unsi
509{ 534{
510 Group_AV *group_av = group_get_object(g_c, groupnumber); 535 Group_AV *group_av = group_get_object(g_c, groupnumber);
511 536
512 if (!group_av) 537 if (!group_av) {
513 return -1; 538 return -1;
539 }
514 540
515 if (channels != 1 && channels != 2) 541 if (channels != 1 && channels != 2) {
516 return -1; 542 return -1;
543 }
517 544
518 if (sample_rate != 8000 && sample_rate != 12000 && sample_rate != 16000 && sample_rate != 24000 && sample_rate != 48000) 545 if (sample_rate != 8000 && sample_rate != 12000 && sample_rate != 16000 && sample_rate != 24000
546 && sample_rate != 48000) {
519 return -1; 547 return -1;
548 }
520 549
521 if (!group_av->audio_encoder || group_av->audio_channels != channels || group_av->audio_sample_rate != sample_rate) { 550 if (!group_av->audio_encoder || group_av->audio_channels != channels || group_av->audio_sample_rate != sample_rate) {
522 group_av->audio_channels = channels; 551 group_av->audio_channels = channels;
@@ -528,15 +557,17 @@ int group_send_audio(Group_Chats *g_c, int groupnumber, const int16_t *pcm, unsi
528 group_av->audio_bitrate = 64000; //TODO: add way of adjusting bitrate 557 group_av->audio_bitrate = 64000; //TODO: add way of adjusting bitrate
529 } 558 }
530 559
531 if (recreate_encoder(group_av) == -1) 560 if (recreate_encoder(group_av) == -1) {
532 return -1; 561 return -1;
562 }
533 } 563 }
534 564
535 uint8_t encoded[1024]; 565 uint8_t encoded[1024];
536 int32_t size = opus_encode(group_av->audio_encoder, pcm, samples, encoded, sizeof(encoded)); 566 int32_t size = opus_encode(group_av->audio_encoder, pcm, samples, encoded, sizeof(encoded));
537 567
538 if (size <= 0) 568 if (size <= 0) {
539 return -1; 569 return -1;
570 }
540 571
541 return send_audio_packet(g_c, groupnumber, encoded, size); 572 return send_audio_packet(g_c, groupnumber, encoded, size);
542} 573}
diff --git a/toxav/msi.c b/toxav/msi.c
index b98c58de..cdc3c879 100644
--- a/toxav/msi.c
+++ b/toxav/msi.c
@@ -97,8 +97,9 @@ void handle_msi_packet (Messenger *m, uint32_t friend_number, const uint8_t *dat
97 */ 97 */
98void msi_register_callback (MSISession *session, msi_action_cb *callback, MSICallbackID id) 98void msi_register_callback (MSISession *session, msi_action_cb *callback, MSICallbackID id)
99{ 99{
100 if (!session) 100 if (!session) {
101 return; 101 return;
102 }
102 103
103 pthread_mutex_lock(session->mutex); 104 pthread_mutex_lock(session->mutex);
104 session->callbacks[id] = callback; 105 session->callbacks[id] = callback;
@@ -170,8 +171,9 @@ int msi_kill (MSISession *session)
170} 171}
171int msi_invite (MSISession *session, MSICall **call, uint32_t friend_number, uint8_t capabilities) 172int msi_invite (MSISession *session, MSICall **call, uint32_t friend_number, uint8_t capabilities)
172{ 173{
173 if (!session) 174 if (!session) {
174 return -1; 175 return -1;
176 }
175 177
176 LOGGER_DEBUG(session->messenger->log, "Session: %p Inviting friend: %u", session, friend_number); 178 LOGGER_DEBUG(session->messenger->log, "Session: %p Inviting friend: %u", session, friend_number);
177 179
@@ -211,8 +213,9 @@ int msi_invite (MSISession *session, MSICall **call, uint32_t friend_number, uin
211} 213}
212int msi_hangup (MSICall *call) 214int msi_hangup (MSICall *call)
213{ 215{
214 if (!call || !call->session) 216 if (!call || !call->session) {
215 return -1; 217 return -1;
218 }
216 219
217 MSISession *session = call->session; 220 MSISession *session = call->session;
218 221
@@ -241,8 +244,9 @@ int msi_hangup (MSICall *call)
241} 244}
242int msi_answer (MSICall *call, uint8_t capabilities) 245int msi_answer (MSICall *call, uint8_t capabilities)
243{ 246{
244 if (!call || !call->session) 247 if (!call || !call->session) {
245 return -1; 248 return -1;
249 }
246 250
247 MSISession *session = call->session; 251 MSISession *session = call->session;
248 252
@@ -278,8 +282,9 @@ int msi_answer (MSICall *call, uint8_t capabilities)
278} 282}
279int msi_change_capabilities(MSICall *call, uint8_t capabilities) 283int msi_change_capabilities(MSICall *call, uint8_t capabilities)
280{ 284{
281 if (!call || !call->session) 285 if (!call || !call->session) {
282 return -1; 286 return -1;
287 }
283 288
284 MSISession *session = call->session; 289 MSISession *session = call->session;
285 290
@@ -495,8 +500,9 @@ FAILURE:
495 * an error message will be sent to friend 500 * an error message will be sent to friend
496 */ 501 */
497 502
498 if (call->error == msi_ENone) 503 if (call->error == msi_ENone) {
499 call->error = msi_EHandle; 504 call->error = msi_EHandle;
505 }
500 506
501 return -1; 507 return -1;
502} 508}
@@ -504,8 +510,9 @@ static MSICall *get_call (MSISession *session, uint32_t friend_number)
504{ 510{
505 assert(session); 511 assert(session);
506 512
507 if (session->calls == NULL || session->calls_tail < friend_number) 513 if (session->calls == NULL || session->calls_tail < friend_number) {
508 return NULL; 514 return NULL;
515 }
509 516
510 return session->calls[friend_number]; 517 return session->calls[friend_number];
511} 518}
@@ -515,8 +522,9 @@ MSICall *new_call (MSISession *session, uint32_t friend_number)
515 522
516 MSICall *rc = calloc(sizeof(MSICall), 1); 523 MSICall *rc = calloc(sizeof(MSICall), 1);
517 524
518 if (rc == NULL) 525 if (rc == NULL) {
519 return NULL; 526 return NULL;
527 }
520 528
521 rc->session = session; 529 rc->session = session;
522 rc->friend_number = friend_number; 530 rc->friend_number = friend_number;
@@ -544,8 +552,9 @@ MSICall *new_call (MSISession *session, uint32_t friend_number)
544 /* Set fields in between to null */ 552 /* Set fields in between to null */
545 uint32_t i = session->calls_tail + 1; 553 uint32_t i = session->calls_tail + 1;
546 554
547 for (; i < friend_number; i ++) 555 for (; i < friend_number; i ++) {
548 session->calls[i] = NULL; 556 session->calls[i] = NULL;
557 }
549 558
550 rc->prev = session->calls[session->calls_tail]; 559 rc->prev = session->calls[session->calls_tail];
551 session->calls[session->calls_tail]->next = rc; 560 session->calls[session->calls_tail]->next = rc;
@@ -564,8 +573,9 @@ MSICall *new_call (MSISession *session, uint32_t friend_number)
564void kill_call (MSICall *call) 573void kill_call (MSICall *call)
565{ 574{
566 /* Assume that session mutex is locked */ 575 /* Assume that session mutex is locked */
567 if (call == NULL) 576 if (call == NULL) {
568 return; 577 return;
578 }
569 579
570 MSISession *session = call->session; 580 MSISession *session = call->session;
571 581
@@ -574,17 +584,21 @@ void kill_call (MSICall *call)
574 MSICall *prev = call->prev; 584 MSICall *prev = call->prev;
575 MSICall *next = call->next; 585 MSICall *next = call->next;
576 586
577 if (prev) 587 if (prev) {
578 prev->next = next; 588 prev->next = next;
579 else if (next) 589 } else if (next) {
580 session->calls_head = next->friend_number; 590 session->calls_head = next->friend_number;
581 else goto CLEAR_CONTAINER; 591 } else {
592 goto CLEAR_CONTAINER;
593 }
582 594
583 if (next) 595 if (next) {
584 next->prev = prev; 596 next->prev = prev;
585 else if (prev) 597 } else if (prev) {
586 session->calls_tail = prev->friend_number; 598 session->calls_tail = prev->friend_number;
587 else goto CLEAR_CONTAINER; 599 } else {
600 goto CLEAR_CONTAINER;
601 }
588 602
589 session->calls[call->friend_number] = NULL; 603 session->calls[call->friend_number] = NULL;
590 free(call); 604 free(call);
@@ -641,8 +655,9 @@ void handle_init (MSICall *call, const MSIMessage *msg)
641 call->peer_capabilities = msg->capabilities.value; 655 call->peer_capabilities = msg->capabilities.value;
642 call->state = msi_CallRequested; 656 call->state = msi_CallRequested;
643 657
644 if (invoke_callback(call, msi_OnInvite) == -1) 658 if (invoke_callback(call, msi_OnInvite) == -1) {
645 goto FAILURE; 659 goto FAILURE;
660 }
646 } 661 }
647 break; 662 break;
648 663
@@ -704,8 +719,9 @@ void handle_push (MSICall *call, const MSIMessage *msg)
704 719
705 call->peer_capabilities = msg->capabilities.value; 720 call->peer_capabilities = msg->capabilities.value;
706 721
707 if (invoke_callback(call, msi_OnCapabilities) == -1) 722 if (invoke_callback(call, msi_OnCapabilities) == -1) {
708 goto FAILURE; 723 goto FAILURE;
724 }
709 } 725 }
710 } 726 }
711 break; 727 break;
@@ -717,8 +733,9 @@ void handle_push (MSICall *call, const MSIMessage *msg)
717 call->peer_capabilities = msg->capabilities.value; 733 call->peer_capabilities = msg->capabilities.value;
718 call->state = msi_CallActive; 734 call->state = msi_CallActive;
719 735
720 if (invoke_callback(call, msi_OnStart) == -1) 736 if (invoke_callback(call, msi_OnStart) == -1) {
721 goto FAILURE; 737 goto FAILURE;
738 }
722 739
723 } 740 }
724 break; 741 break;
@@ -751,7 +768,8 @@ void handle_pop (MSICall *call, const MSIMessage *msg)
751 call->error = msg->error.value; 768 call->error = msg->error.value;
752 invoke_callback(call, msi_OnError); 769 invoke_callback(call, msi_OnError);
753 770
754 } else switch (call->state) { 771 } else {
772 switch (call->state) {
755 case msi_CallInactive: { 773 case msi_CallInactive: {
756 LOGGER_ERROR(call->session->messenger->log, "Handling what should be impossible case"); 774 LOGGER_ERROR(call->session->messenger->log, "Handling what should be impossible case");
757 abort(); 775 abort();
@@ -779,6 +797,7 @@ void handle_pop (MSICall *call, const MSIMessage *msg)
779 } 797 }
780 break; 798 break;
781 } 799 }
800 }
782 801
783 kill_call (call); 802 kill_call (call);
784} 803}
diff --git a/toxav/rtp.c b/toxav/rtp.c
index 5fe37021..a226f3ff 100644
--- a/toxav/rtp.c
+++ b/toxav/rtp.c
@@ -73,8 +73,9 @@ RTPSession *rtp_new (int payload_type, Messenger *m, uint32_t friendnumber,
73} 73}
74void rtp_kill (RTPSession *session) 74void rtp_kill (RTPSession *session)
75{ 75{
76 if (!session) 76 if (!session) {
77 return; 77 return;
78 }
78 79
79 LOGGER_DEBUG(session->m->log, "Terminated RTP session: %p", session); 80 LOGGER_DEBUG(session->m->log, "Terminated RTP session: %p", session);
80 81
@@ -83,8 +84,9 @@ void rtp_kill (RTPSession *session)
83} 84}
84int rtp_allow_receiving(RTPSession *session) 85int rtp_allow_receiving(RTPSession *session)
85{ 86{
86 if (session == NULL) 87 if (session == NULL) {
87 return -1; 88 return -1;
89 }
88 90
89 if (m_callback_rtp_packet(session->m, session->friend_number, session->payload_type, 91 if (m_callback_rtp_packet(session->m, session->friend_number, session->payload_type,
90 handle_rtp_packet, session) == -1) { 92 handle_rtp_packet, session) == -1) {
@@ -97,8 +99,9 @@ int rtp_allow_receiving(RTPSession *session)
97} 99}
98int rtp_stop_receiving(RTPSession *session) 100int rtp_stop_receiving(RTPSession *session)
99{ 101{
100 if (session == NULL) 102 if (session == NULL) {
101 return -1; 103 return -1;
104 }
102 105
103 m_callback_rtp_packet(session->m, session->friend_number, session->payload_type, NULL, NULL); 106 m_callback_rtp_packet(session->m, session->friend_number, session->payload_type, NULL, NULL);
104 107
@@ -143,8 +146,9 @@ int rtp_send_data (RTPSession *session, const uint8_t *data, uint16_t length)
143 146
144 memcpy(rdata + 1 + sizeof(struct RTPHeader), data, length); 147 memcpy(rdata + 1 + sizeof(struct RTPHeader), data, length);
145 148
146 if (-1 == send_custom_lossy_packet(session->m, session->friend_number, rdata, sizeof(rdata))) 149 if (-1 == send_custom_lossy_packet(session->m, session->friend_number, rdata, sizeof(rdata))) {
147 LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! std error: %s", sizeof(rdata), strerror(errno)); 150 LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! std error: %s", sizeof(rdata), strerror(errno));
151 }
148 } else { 152 } else {
149 153
150 /** 154 /**
@@ -159,9 +163,10 @@ int rtp_send_data (RTPSession *session, const uint8_t *data, uint16_t length)
159 memcpy(rdata + 1 + sizeof(struct RTPHeader), data + sent, piece); 163 memcpy(rdata + 1 + sizeof(struct RTPHeader), data + sent, piece);
160 164
161 if (-1 == send_custom_lossy_packet(session->m, session->friend_number, 165 if (-1 == send_custom_lossy_packet(session->m, session->friend_number,
162 rdata, piece + sizeof(struct RTPHeader) + 1)) 166 rdata, piece + sizeof(struct RTPHeader) + 1)) {
163 LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! std error: %s", 167 LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! std error: %s",
164 piece + sizeof(struct RTPHeader) + 1, strerror(errno)); 168 piece + sizeof(struct RTPHeader) + 1, strerror(errno));
169 }
165 170
166 sent += piece; 171 sent += piece;
167 header->cpart = htons(sent); 172 header->cpart = htons(sent);
@@ -174,9 +179,10 @@ int rtp_send_data (RTPSession *session, const uint8_t *data, uint16_t length)
174 memcpy(rdata + 1 + sizeof(struct RTPHeader), data + sent, piece); 179 memcpy(rdata + 1 + sizeof(struct RTPHeader), data + sent, piece);
175 180
176 if (-1 == send_custom_lossy_packet(session->m, session->friend_number, rdata, 181 if (-1 == send_custom_lossy_packet(session->m, session->friend_number, rdata,
177 piece + sizeof(struct RTPHeader) + 1)) 182 piece + sizeof(struct RTPHeader) + 1)) {
178 LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! std error: %s", 183 LOGGER_WARNING(session->m->log, "RTP send failed (len: %d)! std error: %s",
179 piece + sizeof(struct RTPHeader) + 1, strerror(errno)); 184 piece + sizeof(struct RTPHeader) + 1, strerror(errno));
185 }
180 } 186 }
181 } 187 }
182 188
@@ -198,8 +204,9 @@ bool chloss (const RTPSession *session, const struct RTPHeader *header)
198 204
199 fprintf (stderr, "Lost packet\n"); 205 fprintf (stderr, "Lost packet\n");
200 206
201 while (lost --) 207 while (lost --) {
202 bwc_add_lost(session->bwc , 0); 208 bwc_add_lost(session->bwc , 0);
209 }
203 210
204 return true; 211 return true;
205 } 212 }
@@ -271,10 +278,11 @@ int handle_rtp_packet (Messenger *m, uint32_t friendnumber, const uint8_t *data,
271 278
272 /* Invoke processing of active multiparted message */ 279 /* Invoke processing of active multiparted message */
273 if (session->mp) { 280 if (session->mp) {
274 if (session->mcb) 281 if (session->mcb) {
275 session->mcb (session->cs, session->mp); 282 session->mcb (session->cs, session->mp);
276 else 283 } else {
277 free(session->mp); 284 free(session->mp);
285 }
278 286
279 session->mp = NULL; 287 session->mp = NULL;
280 } 288 }
@@ -283,8 +291,9 @@ int handle_rtp_packet (Messenger *m, uint32_t friendnumber, const uint8_t *data,
283 * process it only if handler for the session is present. 291 * process it only if handler for the session is present.
284 */ 292 */
285 293
286 if (!session->mcb) 294 if (!session->mcb) {
287 return 0; 295 return 0;
296 }
288 297
289 return session->mcb (session->cs, new_message(length, data, length)); 298 return session->mcb (session->cs, new_message(length, data, length));
290 } else { 299 } else {
@@ -323,21 +332,23 @@ int handle_rtp_packet (Messenger *m, uint32_t friendnumber, const uint8_t *data,
323 /* Received a full message; now push it for the further 332 /* Received a full message; now push it for the further
324 * processing. 333 * processing.
325 */ 334 */
326 if (session->mcb) 335 if (session->mcb) {
327 session->mcb (session->cs, session->mp); 336 session->mcb (session->cs, session->mp);
328 else 337 } else {
329 free(session->mp); 338 free(session->mp);
339 }
330 340
331 session->mp = NULL; 341 session->mp = NULL;
332 } 342 }
333 } else { 343 } else {
334 /* Second case */ 344 /* Second case */
335 345
336 if (session->mp->header.timestamp > ntohl(header->timestamp)) 346 if (session->mp->header.timestamp > ntohl(header->timestamp)) {
337 /* The received message part is from the old message; 347 /* The received message part is from the old message;
338 * discard it. 348 * discard it.
339 */ 349 */
340 return 0; 350 return 0;
351 }
341 352
342 /* Measure missing parts of the old message */ 353 /* Measure missing parts of the old message */
343 bwc_add_lost(session->bwc, 354 bwc_add_lost(session->bwc,
@@ -348,10 +359,11 @@ int handle_rtp_packet (Messenger *m, uint32_t friendnumber, const uint8_t *data,
348 MAX_CRYPTO_DATA_SIZE) * sizeof(struct RTPHeader) ); 359 MAX_CRYPTO_DATA_SIZE) * sizeof(struct RTPHeader) );
349 360
350 /* Push the previous message for processing */ 361 /* Push the previous message for processing */
351 if (session->mcb) 362 if (session->mcb) {
352 session->mcb (session->cs, session->mp); 363 session->mcb (session->cs, session->mp);
353 else 364 } else {
354 free(session->mp); 365 free(session->mp);
366 }
355 367
356 session->mp = NULL; 368 session->mp = NULL;
357 goto NEW_MULTIPARTED; 369 goto NEW_MULTIPARTED;
@@ -382,8 +394,9 @@ NEW_MULTIPARTED:
382 session->mp = new_message(ntohs(header->tlen) + sizeof(struct RTPHeader), data, length); 394 session->mp = new_message(ntohs(header->tlen) + sizeof(struct RTPHeader), data, length);
383 395
384 /* Reposition data if necessary */ 396 /* Reposition data if necessary */
385 if (ntohs(header->cpart)) 397 if (ntohs(header->cpart)) {
386 ; 398 ;
399 }
387 400
388 memmove(session->mp->data + ntohs(header->cpart), session->mp->data, session->mp->len); 401 memmove(session->mp->data + ntohs(header->cpart), session->mp->data, session->mp->len);
389 } 402 }
diff --git a/toxav/toxav.c b/toxav/toxav.c
index 4ef5d2b3..d7b367f7 100644
--- a/toxav/toxav.c
+++ b/toxav/toxav.c
@@ -179,8 +179,9 @@ ToxAV *toxav_new(Tox *tox, TOXAV_ERR_NEW *error)
179 179
180END: 180END:
181 181
182 if (error) 182 if (error) {
183 *error = rc; 183 *error = rc;
184 }
184 185
185 if (rc != TOXAV_ERR_NEW_OK) { 186 if (rc != TOXAV_ERR_NEW_OK) {
186 free(av); 187 free(av);
@@ -191,8 +192,9 @@ END:
191} 192}
192void toxav_kill(ToxAV *av) 193void toxav_kill(ToxAV *av)
193{ 194{
194 if (av == NULL) 195 if (av == NULL) {
195 return; 196 return;
197 }
196 198
197 pthread_mutex_lock(av->mutex); 199 pthread_mutex_lock(av->mutex);
198 200
@@ -249,12 +251,14 @@ void toxav_iterate(ToxAV *av)
249 vc_iterate(i->video.second); 251 vc_iterate(i->video.second);
250 252
251 if (i->msi_call->self_capabilities & msi_CapRAudio && 253 if (i->msi_call->self_capabilities & msi_CapRAudio &&
252 i->msi_call->peer_capabilities & msi_CapSAudio) 254 i->msi_call->peer_capabilities & msi_CapSAudio) {
253 rc = MIN(i->audio.second->lp_frame_duration, rc); 255 rc = MIN(i->audio.second->lp_frame_duration, rc);
256 }
254 257
255 if (i->msi_call->self_capabilities & msi_CapRVideo && 258 if (i->msi_call->self_capabilities & msi_CapRVideo &&
256 i->msi_call->peer_capabilities & msi_CapSVideo) 259 i->msi_call->peer_capabilities & msi_CapSVideo) {
257 rc = MIN(i->video.second->lcfd, (uint32_t) rc); 260 rc = MIN(i->video.second->lcfd, (uint32_t) rc);
261 }
258 262
259 uint32_t fid = i->friend_number; 263 uint32_t fid = i->friend_number;
260 264
@@ -262,8 +266,9 @@ void toxav_iterate(ToxAV *av)
262 pthread_mutex_lock(av->mutex); 266 pthread_mutex_lock(av->mutex);
263 267
264 /* In case this call is popped from container stop iteration */ 268 /* In case this call is popped from container stop iteration */
265 if (call_get(av, fid) != i) 269 if (call_get(av, fid) != i) {
266 break; 270 break;
271 }
267 } 272 }
268 } 273 }
269 274
@@ -293,8 +298,9 @@ bool toxav_call(ToxAV *av, uint32_t friend_number, uint32_t audio_bit_rate, uint
293 298
294 ToxAVCall *call = call_new(av, friend_number, &rc); 299 ToxAVCall *call = call_new(av, friend_number, &rc);
295 300
296 if (call == NULL) 301 if (call == NULL) {
297 goto END; 302 goto END;
303 }
298 304
299 call->audio_bit_rate = audio_bit_rate; 305 call->audio_bit_rate = audio_bit_rate;
300 call->video_bit_rate = video_bit_rate; 306 call->video_bit_rate = video_bit_rate;
@@ -315,8 +321,9 @@ bool toxav_call(ToxAV *av, uint32_t friend_number, uint32_t audio_bit_rate, uint
315END: 321END:
316 pthread_mutex_unlock(av->mutex); 322 pthread_mutex_unlock(av->mutex);
317 323
318 if (error) 324 if (error) {
319 *error = rc; 325 *error = rc;
326 }
320 327
321 return rc == TOXAV_ERR_CALL_OK; 328 return rc == TOXAV_ERR_CALL_OK;
322} 329}
@@ -366,14 +373,16 @@ bool toxav_answer(ToxAV *av, uint32_t friend_number, uint32_t audio_bit_rate, ui
366 call->previous_self_capabilities |= audio_bit_rate > 0 ? msi_CapSAudio : 0; 373 call->previous_self_capabilities |= audio_bit_rate > 0 ? msi_CapSAudio : 0;
367 call->previous_self_capabilities |= video_bit_rate > 0 ? msi_CapSVideo : 0; 374 call->previous_self_capabilities |= video_bit_rate > 0 ? msi_CapSVideo : 0;
368 375
369 if (msi_answer(call->msi_call, call->previous_self_capabilities) != 0) 376 if (msi_answer(call->msi_call, call->previous_self_capabilities) != 0) {
370 rc = TOXAV_ERR_ANSWER_SYNC; 377 rc = TOXAV_ERR_ANSWER_SYNC;
378 }
371 379
372END: 380END:
373 pthread_mutex_unlock(av->mutex); 381 pthread_mutex_unlock(av->mutex);
374 382
375 if (error) 383 if (error) {
376 *error = rc; 384 *error = rc;
385 }
377 386
378 return rc == TOXAV_ERR_ANSWER_OK; 387 return rc == TOXAV_ERR_ANSWER_OK;
379} 388}
@@ -528,8 +537,9 @@ bool toxav_call_control(ToxAV *av, uint32_t friend_number, TOXAV_CALL_CONTROL co
528END: 537END:
529 pthread_mutex_unlock(av->mutex); 538 pthread_mutex_unlock(av->mutex);
530 539
531 if (error) 540 if (error) {
532 *error = rc; 541 *error = rc;
542 }
533 543
534 return rc == TOXAV_ERR_CALL_CONTROL_OK; 544 return rc == TOXAV_ERR_CALL_CONTROL_OK;
535} 545}
@@ -594,8 +604,9 @@ bool toxav_bit_rate_set(ToxAV *av, uint32_t friend_number, int32_t audio_bit_rat
594 rc = TOXAV_ERR_BIT_RATE_SET_SYNC; 604 rc = TOXAV_ERR_BIT_RATE_SET_SYNC;
595 goto END; 605 goto END;
596 } 606 }
597 } else 607 } else {
598 LOGGER_DEBUG(av->m->log, "Set new audio bit rate %d", audio_bit_rate); 608 LOGGER_DEBUG(av->m->log, "Set new audio bit rate %d", audio_bit_rate);
609 }
599 610
600 call->audio_bit_rate = audio_bit_rate; 611 call->audio_bit_rate = audio_bit_rate;
601 pthread_mutex_unlock(call->mutex); 612 pthread_mutex_unlock(call->mutex);
@@ -633,8 +644,9 @@ bool toxav_bit_rate_set(ToxAV *av, uint32_t friend_number, int32_t audio_bit_rat
633 rc = TOXAV_ERR_BIT_RATE_SET_SYNC; 644 rc = TOXAV_ERR_BIT_RATE_SET_SYNC;
634 goto END; 645 goto END;
635 } 646 }
636 } else 647 } else {
637 LOGGER_DEBUG(av->m->log, "Set new video bit rate %d", video_bit_rate); 648 LOGGER_DEBUG(av->m->log, "Set new video bit rate %d", video_bit_rate);
649 }
638 650
639 call->video_bit_rate = video_bit_rate; 651 call->video_bit_rate = video_bit_rate;
640 pthread_mutex_unlock(call->mutex); 652 pthread_mutex_unlock(call->mutex);
@@ -644,8 +656,9 @@ bool toxav_bit_rate_set(ToxAV *av, uint32_t friend_number, int32_t audio_bit_rat
644 pthread_mutex_unlock(av->mutex); 656 pthread_mutex_unlock(av->mutex);
645END: 657END:
646 658
647 if (error) 659 if (error) {
648 *error = rc; 660 *error = rc;
661 }
649 662
650 return rc == TOXAV_ERR_BIT_RATE_SET_OK; 663 return rc == TOXAV_ERR_BIT_RATE_SET_OK;
651} 664}
@@ -735,8 +748,9 @@ bool toxav_audio_send_frame(ToxAV *av, uint32_t friend_number, const int16_t *pc
735 748
736END: 749END:
737 750
738 if (error) 751 if (error) {
739 *error = rc; 752 *error = rc;
753 }
740 754
741 return rc == TOXAV_ERR_SEND_FRAME_OK; 755 return rc == TOXAV_ERR_SEND_FRAME_OK;
742} 756}
@@ -834,8 +848,9 @@ bool toxav_video_send_frame(ToxAV *av, uint32_t friend_number, uint16_t width, u
834 848
835END: 849END:
836 850
837 if (error) 851 if (error) {
838 *error = rc; 852 *error = rc;
853 }
839 854
840 return rc == TOXAV_ERR_SEND_FRAME_OK; 855 return rc == TOXAV_ERR_SEND_FRAME_OK;
841} 856}
@@ -874,8 +889,9 @@ void callback_bwc(BWController *bwc, uint32_t friend_number, float loss, void *u
874 889
875 LOGGER_DEBUG(call->av->m->log, "Reported loss of %f%%", loss * 100); 890 LOGGER_DEBUG(call->av->m->log, "Reported loss of %f%%", loss * 100);
876 891
877 if (loss < .01f) 892 if (loss < .01f) {
878 return; 893 return;
894 }
879 895
880 pthread_mutex_lock(call->av->mutex); 896 pthread_mutex_lock(call->av->mutex);
881 897
@@ -885,14 +901,15 @@ void callback_bwc(BWController *bwc, uint32_t friend_number, float loss, void *u
885 return; 901 return;
886 } 902 }
887 903
888 if (call->video_bit_rate) 904 if (call->video_bit_rate) {
889 (*call->av->bcb.first) (call->av, friend_number, call->audio_bit_rate, 905 (*call->av->bcb.first) (call->av, friend_number, call->audio_bit_rate,
890 call->video_bit_rate - (call->video_bit_rate * loss), 906 call->video_bit_rate - (call->video_bit_rate * loss),
891 call->av->bcb.second); 907 call->av->bcb.second);
892 else if (call->audio_bit_rate) 908 } else if (call->audio_bit_rate) {
893 (*call->av->bcb.first) (call->av, friend_number, 909 (*call->av->bcb.first) (call->av, friend_number,
894 call->audio_bit_rate - (call->audio_bit_rate * loss), 910 call->audio_bit_rate - (call->audio_bit_rate * loss),
895 0, call->av->bcb.second); 911 0, call->av->bcb.second);
912 }
896 913
897 pthread_mutex_unlock(call->av->mutex); 914 pthread_mutex_unlock(call->av->mutex);
898} 915}
@@ -912,10 +929,10 @@ int callback_invite(void *toxav_inst, MSICall *call)
912 call->av_call = av_call; 929 call->av_call = av_call;
913 av_call->msi_call = call; 930 av_call->msi_call = call;
914 931
915 if (toxav->ccb.first) 932 if (toxav->ccb.first) {
916 toxav->ccb.first(toxav, call->friend_number, call->peer_capabilities & msi_CapSAudio, 933 toxav->ccb.first(toxav, call->friend_number, call->peer_capabilities & msi_CapSAudio,
917 call->peer_capabilities & msi_CapSVideo, toxav->ccb.second); 934 call->peer_capabilities & msi_CapSVideo, toxav->ccb.second);
918 else { 935 } else {
919 /* No handler to capture the call request, send failure */ 936 /* No handler to capture the call request, send failure */
920 pthread_mutex_unlock(toxav->mutex); 937 pthread_mutex_unlock(toxav->mutex);
921 return -1; 938 return -1;
@@ -987,15 +1004,17 @@ int callback_capabilites(void *toxav_inst, MSICall *call)
987 ToxAV *toxav = toxav_inst; 1004 ToxAV *toxav = toxav_inst;
988 pthread_mutex_lock(toxav->mutex); 1005 pthread_mutex_lock(toxav->mutex);
989 1006
990 if (call->peer_capabilities & msi_CapSAudio) 1007 if (call->peer_capabilities & msi_CapSAudio) {
991 rtp_allow_receiving(((ToxAVCall *)call->av_call)->audio.first); 1008 rtp_allow_receiving(((ToxAVCall *)call->av_call)->audio.first);
992 else 1009 } else {
993 rtp_stop_receiving(((ToxAVCall *)call->av_call)->audio.first); 1010 rtp_stop_receiving(((ToxAVCall *)call->av_call)->audio.first);
1011 }
994 1012
995 if (call->peer_capabilities & msi_CapSVideo) 1013 if (call->peer_capabilities & msi_CapSVideo) {
996 rtp_allow_receiving(((ToxAVCall *)call->av_call)->video.first); 1014 rtp_allow_receiving(((ToxAVCall *)call->av_call)->video.first);
997 else 1015 } else {
998 rtp_stop_receiving(((ToxAVCall *)call->av_call)->video.first); 1016 rtp_stop_receiving(((ToxAVCall *)call->av_call)->video.first);
1017 }
999 1018
1000 invoke_call_state_callback(toxav, call->friend_number, call->peer_capabilities); 1019 invoke_call_state_callback(toxav, call->friend_number, call->peer_capabilities);
1001 1020
@@ -1017,10 +1036,11 @@ bool video_bit_rate_invalid(uint32_t bit_rate)
1017} 1036}
1018bool invoke_call_state_callback(ToxAV *av, uint32_t friend_number, uint32_t state) 1037bool invoke_call_state_callback(ToxAV *av, uint32_t friend_number, uint32_t state)
1019{ 1038{
1020 if (av->scb.first) 1039 if (av->scb.first) {
1021 av->scb.first(av, friend_number, state, av->scb.second); 1040 av->scb.first(av, friend_number, state, av->scb.second);
1022 else 1041 } else {
1023 return false; 1042 return false;
1043 }
1024 1044
1025 return true; 1045 return true;
1026} 1046}
@@ -1083,8 +1103,9 @@ ToxAVCall *call_new(ToxAV *av, uint32_t friend_number, TOXAV_ERR_CALL *error)
1083 /* Set fields in between to null */ 1103 /* Set fields in between to null */
1084 uint32_t i = av->calls_tail + 1; 1104 uint32_t i = av->calls_tail + 1;
1085 1105
1086 for (; i < friend_number; i ++) 1106 for (; i < friend_number; i ++) {
1087 av->calls[i] = NULL; 1107 av->calls[i] = NULL;
1108 }
1088 1109
1089 call->prev = av->calls[av->calls_tail]; 1110 call->prev = av->calls[av->calls_tail];
1090 av->calls[av->calls_tail]->next = call; 1111 av->calls[av->calls_tail]->next = call;
@@ -1101,23 +1122,26 @@ ToxAVCall *call_new(ToxAV *av, uint32_t friend_number, TOXAV_ERR_CALL *error)
1101 1122
1102END: 1123END:
1103 1124
1104 if (error) 1125 if (error) {
1105 *error = rc; 1126 *error = rc;
1127 }
1106 1128
1107 return call; 1129 return call;
1108} 1130}
1109ToxAVCall *call_get(ToxAV *av, uint32_t friend_number) 1131ToxAVCall *call_get(ToxAV *av, uint32_t friend_number)
1110{ 1132{
1111 /* Assumes mutex locked */ 1133 /* Assumes mutex locked */
1112 if (av->calls == NULL || av->calls_tail < friend_number) 1134 if (av->calls == NULL || av->calls_tail < friend_number) {
1113 return NULL; 1135 return NULL;
1136 }
1114 1137
1115 return av->calls[friend_number]; 1138 return av->calls[friend_number];
1116} 1139}
1117ToxAVCall *call_remove(ToxAVCall *call) 1140ToxAVCall *call_remove(ToxAVCall *call)
1118{ 1141{
1119 if (call == NULL) 1142 if (call == NULL) {
1120 return NULL; 1143 return NULL;
1144 }
1121 1145
1122 uint32_t friend_number = call->friend_number; 1146 uint32_t friend_number = call->friend_number;
1123 ToxAV *av = call->av; 1147 ToxAV *av = call->av;
@@ -1134,17 +1158,21 @@ ToxAVCall *call_remove(ToxAVCall *call)
1134 1158
1135 free(call); 1159 free(call);
1136 1160
1137 if (prev) 1161 if (prev) {
1138 prev->next = next; 1162 prev->next = next;
1139 else if (next) 1163 } else if (next) {
1140 av->calls_head = next->friend_number; 1164 av->calls_head = next->friend_number;
1141 else goto CLEAR; 1165 } else {
1166 goto CLEAR;
1167 }
1142 1168
1143 if (next) 1169 if (next) {
1144 next->prev = prev; 1170 next->prev = prev;
1145 else if (prev) 1171 } else if (prev) {
1146 av->calls_tail = prev->friend_number; 1172 av->calls_tail = prev->friend_number;
1147 else goto CLEAR; 1173 } else {
1174 goto CLEAR;
1175 }
1148 1176
1149 av->calls[friend_number] = NULL; 1177 av->calls[friend_number] = NULL;
1150 return next; 1178 return next;
@@ -1160,28 +1188,33 @@ bool call_prepare_transmission(ToxAVCall *call)
1160{ 1188{
1161 /* Assumes mutex locked */ 1189 /* Assumes mutex locked */
1162 1190
1163 if (call == NULL) 1191 if (call == NULL) {
1164 return false; 1192 return false;
1193 }
1165 1194
1166 ToxAV *av = call->av; 1195 ToxAV *av = call->av;
1167 1196
1168 if (!av->acb.first && !av->vcb.first) 1197 if (!av->acb.first && !av->vcb.first) {
1169 /* It makes no sense to have CSession without callbacks */ 1198 /* It makes no sense to have CSession without callbacks */
1170 return false; 1199 return false;
1200 }
1171 1201
1172 if (call->active) { 1202 if (call->active) {
1173 LOGGER_WARNING(av->m->log, "Call already active!\n"); 1203 LOGGER_WARNING(av->m->log, "Call already active!\n");
1174 return true; 1204 return true;
1175 } 1205 }
1176 1206
1177 if (create_recursive_mutex(call->mutex_audio) != 0) 1207 if (create_recursive_mutex(call->mutex_audio) != 0) {
1178 return false; 1208 return false;
1209 }
1179 1210
1180 if (create_recursive_mutex(call->mutex_video) != 0) 1211 if (create_recursive_mutex(call->mutex_video) != 0) {
1181 goto FAILURE_3; 1212 goto FAILURE_3;
1213 }
1182 1214
1183 if (create_recursive_mutex(call->mutex) != 0) 1215 if (create_recursive_mutex(call->mutex) != 0) {
1184 goto FAILURE_2; 1216 goto FAILURE_2;
1217 }
1185 1218
1186 /* Prepare bwc */ 1219 /* Prepare bwc */
1187 call->bwc = bwc_new(av->m, call->friend_number, callback_bwc, call); 1220 call->bwc = bwc_new(av->m, call->friend_number, callback_bwc, call);
@@ -1241,8 +1274,9 @@ FAILURE_3:
1241} 1274}
1242void call_kill_transmission(ToxAVCall *call) 1275void call_kill_transmission(ToxAVCall *call)
1243{ 1276{
1244 if (call == NULL || call->active == 0) 1277 if (call == NULL || call->active == 0) {
1245 return; 1278 return;
1279 }
1246 1280
1247 call->active = 0; 1281 call->active = 0;
1248 1282
diff --git a/toxav/video.c b/toxav/video.c
index 300eb377..c94579a6 100644
--- a/toxav/video.c
+++ b/toxav/video.c
@@ -51,8 +51,9 @@ VCSession *vc_new(Logger *log, ToxAV *av, uint32_t friend_number, toxav_video_re
51 return NULL; 51 return NULL;
52 } 52 }
53 53
54 if (!(vc->vbuf_raw = rb_new(VIDEO_DECODE_BUFFER_SIZE))) 54 if (!(vc->vbuf_raw = rb_new(VIDEO_DECODE_BUFFER_SIZE))) {
55 goto BASE_CLEANUP; 55 goto BASE_CLEANUP;
56 }
56 57
57 int rc = vpx_codec_dec_init(vc->decoder, VIDEO_CODEC_DECODER_INTERFACE, NULL, 0); 58 int rc = vpx_codec_dec_init(vc->decoder, VIDEO_CODEC_DECODER_INTERFACE, NULL, 0);
58 59
@@ -118,16 +119,18 @@ BASE_CLEANUP:
118} 119}
119void vc_kill(VCSession *vc) 120void vc_kill(VCSession *vc)
120{ 121{
121 if (!vc) 122 if (!vc) {
122 return; 123 return;
124 }
123 125
124 vpx_codec_destroy(vc->encoder); 126 vpx_codec_destroy(vc->encoder);
125 vpx_codec_destroy(vc->decoder); 127 vpx_codec_destroy(vc->decoder);
126 128
127 void *p; 129 void *p;
128 130
129 while (rb_read(vc->vbuf_raw, (void **)&p)) 131 while (rb_read(vc->vbuf_raw, (void **)&p)) {
130 free(p); 132 free(p);
133 }
131 134
132 rb_kill(vc->vbuf_raw); 135 rb_kill(vc->vbuf_raw);
133 136
@@ -138,8 +141,9 @@ void vc_kill(VCSession *vc)
138} 141}
139void vc_iterate(VCSession *vc) 142void vc_iterate(VCSession *vc)
140{ 143{
141 if (!vc) 144 if (!vc) {
142 return; 145 return;
146 }
143 147
144 struct RTPMessage *p; 148 struct RTPMessage *p;
145 int rc; 149 int rc;
@@ -152,18 +156,19 @@ void vc_iterate(VCSession *vc)
152 rc = vpx_codec_decode(vc->decoder, p->data, p->len, NULL, MAX_DECODE_TIME_US); 156 rc = vpx_codec_decode(vc->decoder, p->data, p->len, NULL, MAX_DECODE_TIME_US);
153 free(p); 157 free(p);
154 158
155 if (rc != VPX_CODEC_OK) 159 if (rc != VPX_CODEC_OK) {
156 LOGGER_ERROR(vc->log, "Error decoding video: %s", vpx_codec_err_to_string(rc)); 160 LOGGER_ERROR(vc->log, "Error decoding video: %s", vpx_codec_err_to_string(rc));
157 else { 161 } else {
158 vpx_codec_iter_t iter = NULL; 162 vpx_codec_iter_t iter = NULL;
159 vpx_image_t *dest = vpx_codec_get_frame(vc->decoder, &iter); 163 vpx_image_t *dest = vpx_codec_get_frame(vc->decoder, &iter);
160 164
161 /* Play decoded images */ 165 /* Play decoded images */
162 for (; dest; dest = vpx_codec_get_frame(vc->decoder, &iter)) { 166 for (; dest; dest = vpx_codec_get_frame(vc->decoder, &iter)) {
163 if (vc->vcb.first) 167 if (vc->vcb.first) {
164 vc->vcb.first(vc->av, vc->friend_number, dest->d_w, dest->d_h, 168 vc->vcb.first(vc->av, vc->friend_number, dest->d_w, dest->d_h,
165 (const uint8_t *)dest->planes[0], (const uint8_t *)dest->planes[1], (const uint8_t *)dest->planes[2], 169 (const uint8_t *)dest->planes[0], (const uint8_t *)dest->planes[1], (const uint8_t *)dest->planes[2],
166 dest->stride[0], dest->stride[1], dest->stride[2], vc->vcb.second); 170 dest->stride[0], dest->stride[1], dest->stride[2], vc->vcb.second);
171 }
167 172
168 vpx_img_free(dest); 173 vpx_img_free(dest);
169 } 174 }
@@ -179,8 +184,9 @@ int vc_queue_message(void *vcp, struct RTPMessage *msg)
179 /* This function does the reconstruction of video packets. 184 /* This function does the reconstruction of video packets.
180 * See more info about video splitting in docs 185 * See more info about video splitting in docs
181 */ 186 */
182 if (!vcp || !msg) 187 if (!vcp || !msg) {
183 return -1; 188 return -1;
189 }
184 190
185 VCSession *vc = vcp; 191 VCSession *vc = vcp;
186 192
@@ -210,14 +216,16 @@ int vc_queue_message(void *vcp, struct RTPMessage *msg)
210} 216}
211int vc_reconfigure_encoder(VCSession *vc, uint32_t bit_rate, uint16_t width, uint16_t height) 217int vc_reconfigure_encoder(VCSession *vc, uint32_t bit_rate, uint16_t width, uint16_t height)
212{ 218{
213 if (!vc) 219 if (!vc) {
214 return -1; 220 return -1;
221 }
215 222
216 vpx_codec_enc_cfg_t cfg = *vc->encoder->config.enc; 223 vpx_codec_enc_cfg_t cfg = *vc->encoder->config.enc;
217 int rc; 224 int rc;
218 225
219 if (cfg.rc_target_bitrate == bit_rate && cfg.g_w == width && cfg.g_h == height) 226 if (cfg.rc_target_bitrate == bit_rate && cfg.g_w == width && cfg.g_h == height) {
220 return 0; /* Nothing changed */ 227 return 0; /* Nothing changed */
228 }
221 229
222 if (cfg.g_w == width && cfg.g_h == height) { 230 if (cfg.g_w == width && cfg.g_h == height) {
223 /* Only bit rate changed */ 231 /* Only bit rate changed */
diff --git a/toxcore/DHT.c b/toxcore/DHT.c
index 98859856..538cd220 100644
--- a/toxcore/DHT.c
+++ b/toxcore/DHT.c
@@ -81,11 +81,13 @@ int id_closest(const uint8_t *pk, const uint8_t *pk1, const uint8_t *pk2)
81 distance1 = pk[i] ^ pk1[i]; 81 distance1 = pk[i] ^ pk1[i];
82 distance2 = pk[i] ^ pk2[i]; 82 distance2 = pk[i] ^ pk2[i];
83 83
84 if (distance1 < distance2) 84 if (distance1 < distance2) {
85 return 1; 85 return 1;
86 }
86 87
87 if (distance1 > distance2) 88 if (distance1 > distance2) {
88 return 2; 89 return 2;
90 }
89 } 91 }
90 92
91 return 0; 93 return 0;
@@ -98,12 +100,14 @@ static unsigned int bit_by_bit_cmp(const uint8_t *pk1, const uint8_t *pk2)
98 unsigned int i, j = 0; 100 unsigned int i, j = 0;
99 101
100 for (i = 0; i < crypto_box_PUBLICKEYBYTES; ++i) { 102 for (i = 0; i < crypto_box_PUBLICKEYBYTES; ++i) {
101 if (pk1[i] == pk2[i]) 103 if (pk1[i] == pk2[i]) {
102 continue; 104 continue;
105 }
103 106
104 for (j = 0; j < 8; ++j) { 107 for (j = 0; j < 8; ++j) {
105 if ((pk1[i] & (1 << (7 - j))) != (pk2[i] & (1 << (7 - j)))) 108 if ((pk1[i] & (1 << (7 - j))) != (pk2[i] & (1 << (7 - j)))) {
106 break; 109 break;
110 }
107 } 111 }
108 112
109 break; 113 break;
@@ -179,10 +183,11 @@ void DHT_get_shared_key_sent(DHT *dht, uint8_t *shared_key, const uint8_t *publi
179 183
180void to_net_family(IP *ip) 184void to_net_family(IP *ip)
181{ 185{
182 if (ip->family == AF_INET) 186 if (ip->family == AF_INET) {
183 ip->family = TOX_AF_INET; 187 ip->family = TOX_AF_INET;
184 else if (ip->family == AF_INET6) 188 } else if (ip->family == AF_INET6) {
185 ip->family = TOX_AF_INET6; 189 ip->family = TOX_AF_INET6;
190 }
186} 191}
187 192
188int to_host_family(IP *ip) 193int to_host_family(IP *ip)
@@ -253,8 +258,9 @@ int pack_nodes(uint8_t *data, uint16_t length, const Node_format *nodes, uint16_
253 if (ipv6 == 0) { 258 if (ipv6 == 0) {
254 uint32_t size = PACKED_NODE_SIZE_IP4; 259 uint32_t size = PACKED_NODE_SIZE_IP4;
255 260
256 if (packed_length + size > length) 261 if (packed_length + size > length) {
257 return -1; 262 return -1;
263 }
258 264
259 data[packed_length] = net_family; 265 data[packed_length] = net_family;
260 memcpy(data + packed_length + 1, &nodes[i].ip_port.ip.ip4, SIZE_IP4); 266 memcpy(data + packed_length + 1, &nodes[i].ip_port.ip.ip4, SIZE_IP4);
@@ -264,8 +270,9 @@ int pack_nodes(uint8_t *data, uint16_t length, const Node_format *nodes, uint16_
264 } else if (ipv6 == 1) { 270 } else if (ipv6 == 1) {
265 uint32_t size = PACKED_NODE_SIZE_IP6; 271 uint32_t size = PACKED_NODE_SIZE_IP6;
266 272
267 if (packed_length + size > length) 273 if (packed_length + size > length) {
268 return -1; 274 return -1;
275 }
269 276
270 data[packed_length] = net_family; 277 data[packed_length] = net_family;
271 memcpy(data + packed_length + 1, &nodes[i].ip_port.ip.ip6, SIZE_IP6); 278 memcpy(data + packed_length + 1, &nodes[i].ip_port.ip.ip6, SIZE_IP6);
@@ -300,8 +307,9 @@ int unpack_nodes(Node_format *nodes, uint16_t max_num_nodes, uint16_t *processed
300 ipv6 = 0; 307 ipv6 = 0;
301 host_family = AF_INET; 308 host_family = AF_INET;
302 } else if (data[len_processed] == TOX_TCP_INET) { 309 } else if (data[len_processed] == TOX_TCP_INET) {
303 if (!tcp_enabled) 310 if (!tcp_enabled) {
304 return -1; 311 return -1;
312 }
305 313
306 ipv6 = 0; 314 ipv6 = 0;
307 host_family = TCP_INET; 315 host_family = TCP_INET;
@@ -309,8 +317,9 @@ int unpack_nodes(Node_format *nodes, uint16_t max_num_nodes, uint16_t *processed
309 ipv6 = 1; 317 ipv6 = 1;
310 host_family = AF_INET6; 318 host_family = AF_INET6;
311 } else if (data[len_processed] == TOX_TCP_INET6) { 319 } else if (data[len_processed] == TOX_TCP_INET6) {
312 if (!tcp_enabled) 320 if (!tcp_enabled) {
313 return -1; 321 return -1;
322 }
314 323
315 ipv6 = 1; 324 ipv6 = 1;
316 host_family = TCP_INET6; 325 host_family = TCP_INET6;
@@ -321,8 +330,9 @@ int unpack_nodes(Node_format *nodes, uint16_t max_num_nodes, uint16_t *processed
321 if (ipv6 == 0) { 330 if (ipv6 == 0) {
322 uint32_t size = PACKED_NODE_SIZE_IP4; 331 uint32_t size = PACKED_NODE_SIZE_IP4;
323 332
324 if (len_processed + size > length) 333 if (len_processed + size > length) {
325 return -1; 334 return -1;
335 }
326 336
327 nodes[num].ip_port.ip.family = host_family; 337 nodes[num].ip_port.ip.family = host_family;
328 memcpy(&nodes[num].ip_port.ip.ip4, data + len_processed + 1, SIZE_IP4); 338 memcpy(&nodes[num].ip_port.ip.ip4, data + len_processed + 1, SIZE_IP4);
@@ -333,8 +343,9 @@ int unpack_nodes(Node_format *nodes, uint16_t max_num_nodes, uint16_t *processed
333 } else if (ipv6 == 1) { 343 } else if (ipv6 == 1) {
334 uint32_t size = PACKED_NODE_SIZE_IP6; 344 uint32_t size = PACKED_NODE_SIZE_IP6;
335 345
336 if (len_processed + size > length) 346 if (len_processed + size > length) {
337 return -1; 347 return -1;
348 }
338 349
339 nodes[num].ip_port.ip.family = host_family; 350 nodes[num].ip_port.ip.family = host_family;
340 memcpy(&nodes[num].ip_port.ip.ip6, data + len_processed + 1, SIZE_IP6); 351 memcpy(&nodes[num].ip_port.ip.ip6, data + len_processed + 1, SIZE_IP6);
@@ -347,8 +358,9 @@ int unpack_nodes(Node_format *nodes, uint16_t max_num_nodes, uint16_t *processed
347 } 358 }
348 } 359 }
349 360
350 if (processed_data_len) 361 if (processed_data_len) {
351 *processed_data_len = len_processed; 362 *processed_data_len = len_processed;
363 }
352 364
353 return num; 365 return num;
354} 366}
@@ -369,7 +381,7 @@ static int client_or_ip_port_in_list(Logger *log, Client_data *list, uint16_t le
369 uint64_t temp_time = unix_time(); 381 uint64_t temp_time = unix_time();
370 382
371 /* if public_key is in list, find it and maybe overwrite ip_port */ 383 /* if public_key is in list, find it and maybe overwrite ip_port */
372 for (i = 0; i < length; ++i) 384 for (i = 0; i < length; ++i) {
373 if (id_equal(list[i].public_key, public_key)) { 385 if (id_equal(list[i].public_key, public_key)) {
374 /* Refresh the client timestamp. */ 386 /* Refresh the client timestamp. */
375 if (ip_port.ip.family == AF_INET) { 387 if (ip_port.ip.family == AF_INET) {
@@ -380,8 +392,9 @@ static int client_or_ip_port_in_list(Logger *log, Client_data *list, uint16_t le
380 ip_ntoa(&ip_port.ip), ntohs(ip_port.port)); 392 ip_ntoa(&ip_port.ip), ntohs(ip_port.port));
381 } 393 }
382 394
383 if (LAN_ip(list[i].assoc4.ip_port.ip) != 0 && LAN_ip(ip_port.ip) == 0) 395 if (LAN_ip(list[i].assoc4.ip_port.ip) != 0 && LAN_ip(ip_port.ip) == 0) {
384 return 1; 396 return 1;
397 }
385 398
386 list[i].assoc4.ip_port = ip_port; 399 list[i].assoc4.ip_port = ip_port;
387 list[i].assoc4.timestamp = temp_time; 400 list[i].assoc4.timestamp = temp_time;
@@ -393,8 +406,9 @@ static int client_or_ip_port_in_list(Logger *log, Client_data *list, uint16_t le
393 ip_ntoa(&ip_port.ip), ntohs(ip_port.port)); 406 ip_ntoa(&ip_port.ip), ntohs(ip_port.port));
394 } 407 }
395 408
396 if (LAN_ip(list[i].assoc6.ip_port.ip) != 0 && LAN_ip(ip_port.ip) == 0) 409 if (LAN_ip(list[i].assoc6.ip_port.ip) != 0 && LAN_ip(ip_port.ip) == 0) {
397 return 1; 410 return 1;
411 }
398 412
399 list[i].assoc6.ip_port = ip_port; 413 list[i].assoc6.ip_port = ip_port;
400 list[i].assoc6.timestamp = temp_time; 414 list[i].assoc6.timestamp = temp_time;
@@ -402,6 +416,7 @@ static int client_or_ip_port_in_list(Logger *log, Client_data *list, uint16_t le
402 416
403 return 1; 417 return 1;
404 } 418 }
419 }
405 420
406 /* public_key not in list yet: see if we can find an identical ip_port, in 421 /* public_key not in list yet: see if we can find an identical ip_port, in
407 * that case we kill the old public_key by overwriting it with the new one 422 * that case we kill the old public_key by overwriting it with the new one
@@ -445,8 +460,9 @@ static int client_in_nodelist(const Node_format *list, uint16_t length, const ui
445 uint32_t i; 460 uint32_t i;
446 461
447 for (i = 0; i < length; ++i) { 462 for (i = 0; i < length; ++i) {
448 if (id_equal(list[i].public_key, public_key)) 463 if (id_equal(list[i].public_key, public_key)) {
449 return 1; 464 return 1;
465 }
450 } 466 }
451 467
452 return 0; 468 return 0;
@@ -460,8 +476,9 @@ static int friend_number(const DHT *dht, const uint8_t *public_key)
460 uint32_t i; 476 uint32_t i;
461 477
462 for (i = 0; i < dht->num_friends; ++i) { 478 for (i = 0; i < dht->num_friends; ++i) {
463 if (id_equal(dht->friends_list[i].public_key, public_key)) 479 if (id_equal(dht->friends_list[i].public_key, public_key)) {
464 return i; 480 return i;
481 }
465 } 482 }
466 483
467 return -1; 484 return -1;
@@ -484,8 +501,9 @@ _Bool add_to_list(Node_format *nodes_list, unsigned int length, const uint8_t *p
484 memcpy(nodes_list[i].public_key, pk, crypto_box_PUBLICKEYBYTES); 501 memcpy(nodes_list[i].public_key, pk, crypto_box_PUBLICKEYBYTES);
485 nodes_list[i].ip_port = ip_port; 502 nodes_list[i].ip_port = ip_port;
486 503
487 if (i != (length - 1)) 504 if (i != (length - 1)) {
488 add_to_list(nodes_list, length, pk_bak, ip_port_bak, cmp_pk); 505 add_to_list(nodes_list, length, pk_bak, ip_port_bak, cmp_pk);
506 }
489 507
490 return 1; 508 return 1;
491 } 509 }
@@ -513,8 +531,9 @@ static void get_close_nodes_inner(const uint8_t *public_key, Node_format *nodes_
513 sa_family_t sa_family, const Client_data *client_list, uint32_t client_list_length, 531 sa_family_t sa_family, const Client_data *client_list, uint32_t client_list_length,
514 uint32_t *num_nodes_ptr, uint8_t is_LAN, uint8_t want_good) 532 uint32_t *num_nodes_ptr, uint8_t is_LAN, uint8_t want_good)
515{ 533{
516 if ((sa_family != AF_INET) && (sa_family != AF_INET6) && (sa_family != 0)) 534 if ((sa_family != AF_INET) && (sa_family != AF_INET6) && (sa_family != 0)) {
517 return; 535 return;
536 }
518 537
519 uint32_t num_nodes = *num_nodes_ptr; 538 uint32_t num_nodes = *num_nodes_ptr;
520 uint32_t i; 539 uint32_t i;
@@ -523,8 +542,9 @@ static void get_close_nodes_inner(const uint8_t *public_key, Node_format *nodes_
523 const Client_data *client = &client_list[i]; 542 const Client_data *client = &client_list[i];
524 543
525 /* node already in list? */ 544 /* node already in list? */
526 if (client_in_nodelist(nodes_list, MAX_SENT_NODES, client->public_key)) 545 if (client_in_nodelist(nodes_list, MAX_SENT_NODES, client->public_key)) {
527 continue; 546 continue;
547 }
528 548
529 const IPPTsPng *ipptp = NULL; 549 const IPPTsPng *ipptp = NULL;
530 550
@@ -541,16 +561,19 @@ static void get_close_nodes_inner(const uint8_t *public_key, Node_format *nodes_
541 } 561 }
542 562
543 /* node not in a good condition? */ 563 /* node not in a good condition? */
544 if (is_timeout(ipptp->timestamp, BAD_NODE_TIMEOUT)) 564 if (is_timeout(ipptp->timestamp, BAD_NODE_TIMEOUT)) {
545 continue; 565 continue;
566 }
546 567
547 /* don't send LAN ips to non LAN peers */ 568 /* don't send LAN ips to non LAN peers */
548 if (LAN_ip(ipptp->ip_port.ip) == 0 && !is_LAN) 569 if (LAN_ip(ipptp->ip_port.ip) == 0 && !is_LAN) {
549 continue; 570 continue;
571 }
550 572
551 if (LAN_ip(ipptp->ip_port.ip) != 0 && want_good && hardening_correct(&ipptp->hardening) != HARDENING_ALL_OK 573 if (LAN_ip(ipptp->ip_port.ip) != 0 && want_good && hardening_correct(&ipptp->hardening) != HARDENING_ALL_OK
552 && !id_equal(public_key, client->public_key)) 574 && !id_equal(public_key, client->public_key)) {
553 continue; 575 continue;
576 }
554 577
555 if (num_nodes < MAX_SENT_NODES) { 578 if (num_nodes < MAX_SENT_NODES) {
556 memcpy(nodes_list[num_nodes].public_key, 579 memcpy(nodes_list[num_nodes].public_key,
@@ -588,10 +611,11 @@ static int get_somewhat_close_nodes(const DHT *dht, const uint8_t *public_key, N
588 dht->friends_list[i].client_list, MAX_FRIEND_CLIENTS, 611 dht->friends_list[i].client_list, MAX_FRIEND_CLIENTS,
589 &num_nodes, is_LAN, want_good); 612 &num_nodes, is_LAN, want_good);
590 */ 613 */
591 for (i = 0; i < dht->num_friends; ++i) 614 for (i = 0; i < dht->num_friends; ++i) {
592 get_close_nodes_inner(public_key, nodes_list, sa_family, 615 get_close_nodes_inner(public_key, nodes_list, sa_family,
593 dht->friends_list[i].client_list, MAX_FRIEND_CLIENTS, 616 dht->friends_list[i].client_list, MAX_FRIEND_CLIENTS,
594 &num_nodes, is_LAN, 0); 617 &num_nodes, is_LAN, 0);
618 }
595 619
596 return num_nodes; 620 return num_nodes;
597} 621}
@@ -665,14 +689,17 @@ static int cmp_dht_entry(const void *a, const void *b)
665 int t1 = is_timeout(entry1.assoc4.timestamp, BAD_NODE_TIMEOUT) && is_timeout(entry1.assoc6.timestamp, BAD_NODE_TIMEOUT); 689 int t1 = is_timeout(entry1.assoc4.timestamp, BAD_NODE_TIMEOUT) && is_timeout(entry1.assoc6.timestamp, BAD_NODE_TIMEOUT);
666 int t2 = is_timeout(entry2.assoc4.timestamp, BAD_NODE_TIMEOUT) && is_timeout(entry2.assoc6.timestamp, BAD_NODE_TIMEOUT); 690 int t2 = is_timeout(entry2.assoc4.timestamp, BAD_NODE_TIMEOUT) && is_timeout(entry2.assoc6.timestamp, BAD_NODE_TIMEOUT);
667 691
668 if (t1 && t2) 692 if (t1 && t2) {
669 return 0; 693 return 0;
694 }
670 695
671 if (t1) 696 if (t1) {
672 return -1; 697 return -1;
698 }
673 699
674 if (t2) 700 if (t2) {
675 return 1; 701 return 1;
702 }
676 703
677 t1 = hardening_correct(&entry1.assoc4.hardening) != HARDENING_ALL_OK 704 t1 = hardening_correct(&entry1.assoc4.hardening) != HARDENING_ALL_OK
678 && hardening_correct(&entry1.assoc6.hardening) != HARDENING_ALL_OK; 705 && hardening_correct(&entry1.assoc6.hardening) != HARDENING_ALL_OK;
@@ -680,20 +707,24 @@ static int cmp_dht_entry(const void *a, const void *b)
680 && hardening_correct(&entry2.assoc6.hardening) != HARDENING_ALL_OK; 707 && hardening_correct(&entry2.assoc6.hardening) != HARDENING_ALL_OK;
681 708
682 if (t1 != t2) { 709 if (t1 != t2) {
683 if (t1) 710 if (t1) {
684 return -1; 711 return -1;
712 }
685 713
686 if (t2) 714 if (t2) {
687 return 1; 715 return 1;
716 }
688 } 717 }
689 718
690 int close = id_closest(cmp_public_key, entry1.public_key, entry2.public_key); 719 int close = id_closest(cmp_public_key, entry1.public_key, entry2.public_key);
691 720
692 if (close == 1) 721 if (close == 1) {
693 return 1; 722 return 1;
723 }
694 724
695 if (close == 2) 725 if (close == 2) {
696 return -1; 726 return -1;
727 }
697 728
698 return 0; 729 return 0;
699} 730}
@@ -738,8 +769,9 @@ static int replace_all( Client_data *list,
738 IP_Port ip_port, 769 IP_Port ip_port,
739 const uint8_t *comp_public_key ) 770 const uint8_t *comp_public_key )
740{ 771{
741 if ((ip_port.ip.family != AF_INET) && (ip_port.ip.family != AF_INET6)) 772 if ((ip_port.ip.family != AF_INET) && (ip_port.ip.family != AF_INET6)) {
742 return 0; 773 return 0;
774 }
743 775
744 if (store_node_ok(&list[1], public_key, comp_public_key) || store_node_ok(&list[0], public_key, comp_public_key)) { 776 if (store_node_ok(&list[1], public_key, comp_public_key) || store_node_ok(&list[0], public_key, comp_public_key)) {
745 sort_client_list(list, length, comp_public_key); 777 sort_client_list(list, length, comp_public_key);
@@ -787,8 +819,9 @@ static int add_to_close(DHT *dht, const uint8_t *public_key, IP_Port ip_port, _B
787 819
788 unsigned int index = bit_by_bit_cmp(public_key, dht->self_public_key); 820 unsigned int index = bit_by_bit_cmp(public_key, dht->self_public_key);
789 821
790 if (index > LCLIENT_LENGTH) 822 if (index > LCLIENT_LENGTH) {
791 index = LCLIENT_LENGTH - 1; 823 index = LCLIENT_LENGTH - 1;
824 }
792 825
793 for (i = 0; i < LCLIENT_NODES; ++i) { 826 for (i = 0; i < LCLIENT_NODES; ++i) {
794 Client_data *client = &dht->close_clientlist[(index * LCLIENT_NODES) + i]; 827 Client_data *client = &dht->close_clientlist[(index * LCLIENT_NODES) + i];
@@ -929,10 +962,12 @@ int addto_lists(DHT *dht, IP_Port ip_port, const uint8_t *public_key)
929 * to replace the first ip by the second. 962 * to replace the first ip by the second.
930 */ 963 */
931 if (!client_or_ip_port_in_list(dht->log, dht->close_clientlist, LCLIENT_LIST, public_key, ip_port)) { 964 if (!client_or_ip_port_in_list(dht->log, dht->close_clientlist, LCLIENT_LIST, public_key, ip_port)) {
932 if (add_to_close(dht, public_key, ip_port, 0)) 965 if (add_to_close(dht, public_key, ip_port, 0)) {
933 used++; 966 used++;
934 } else 967 }
968 } else {
935 used++; 969 used++;
970 }
936 971
937 DHT_Friend *friend_foundip = 0; 972 DHT_Friend *friend_foundip = 0;
938 973
@@ -965,9 +1000,10 @@ int addto_lists(DHT *dht, IP_Port ip_port, const uint8_t *public_key)
965 uint32_t j; 1000 uint32_t j;
966 1001
967 for (j = 0; j < friend_foundip->lock_count; ++j) { 1002 for (j = 0; j < friend_foundip->lock_count; ++j) {
968 if (friend_foundip->callbacks[j].ip_callback) 1003 if (friend_foundip->callbacks[j].ip_callback) {
969 friend_foundip->callbacks[j].ip_callback(friend_foundip->callbacks[j].data, friend_foundip->callbacks[j].number, 1004 friend_foundip->callbacks[j].ip_callback(friend_foundip->callbacks[j].data, friend_foundip->callbacks[j].number,
970 ip_port); 1005 ip_port);
1006 }
971 } 1007 }
972 } 1008 }
973 1009
@@ -1060,8 +1096,9 @@ static int getnodes(DHT *dht, IP_Port ip_port, const uint8_t *public_key, const
1060 const Node_format *sendback_node) 1096 const Node_format *sendback_node)
1061{ 1097{
1062 /* Check if packet is going to be sent to ourself. */ 1098 /* Check if packet is going to be sent to ourself. */
1063 if (id_equal(public_key, dht->self_public_key)) 1099 if (id_equal(public_key, dht->self_public_key)) {
1064 return -1; 1100 return -1;
1101 }
1065 1102
1066 uint8_t plain_message[sizeof(Node_format) * 2] = {0}; 1103 uint8_t plain_message[sizeof(Node_format) * 2] = {0};
1067 1104
@@ -1079,8 +1116,9 @@ static int getnodes(DHT *dht, IP_Port ip_port, const uint8_t *public_key, const
1079 ping_id = ping_array_add(&dht->dht_ping_array, plain_message, sizeof(receiver)); 1116 ping_id = ping_array_add(&dht->dht_ping_array, plain_message, sizeof(receiver));
1080 } 1117 }
1081 1118
1082 if (ping_id == 0) 1119 if (ping_id == 0) {
1083 return -1; 1120 return -1;
1121 }
1084 1122
1085 uint8_t plain[crypto_box_PUBLICKEYBYTES + sizeof(ping_id)]; 1123 uint8_t plain[crypto_box_PUBLICKEYBYTES + sizeof(ping_id)];
1086 uint8_t encrypt[sizeof(plain) + crypto_box_MACBYTES]; 1124 uint8_t encrypt[sizeof(plain) + crypto_box_MACBYTES];
@@ -1101,8 +1139,9 @@ static int getnodes(DHT *dht, IP_Port ip_port, const uint8_t *public_key, const
1101 sizeof(plain), 1139 sizeof(plain),
1102 encrypt ); 1140 encrypt );
1103 1141
1104 if (len != sizeof(encrypt)) 1142 if (len != sizeof(encrypt)) {
1105 return -1; 1143 return -1;
1144 }
1106 1145
1107 data[0] = NET_PACKET_GET_NODES; 1146 data[0] = NET_PACKET_GET_NODES;
1108 memcpy(data + 1, dht->self_public_key, crypto_box_PUBLICKEYBYTES); 1147 memcpy(data + 1, dht->self_public_key, crypto_box_PUBLICKEYBYTES);
@@ -1117,11 +1156,13 @@ static int sendnodes_ipv6(const DHT *dht, IP_Port ip_port, const uint8_t *public
1117 const uint8_t *sendback_data, uint16_t length, const uint8_t *shared_encryption_key) 1156 const uint8_t *sendback_data, uint16_t length, const uint8_t *shared_encryption_key)
1118{ 1157{
1119 /* Check if packet is going to be sent to ourself. */ 1158 /* Check if packet is going to be sent to ourself. */
1120 if (id_equal(public_key, dht->self_public_key)) 1159 if (id_equal(public_key, dht->self_public_key)) {
1121 return -1; 1160 return -1;
1161 }
1122 1162
1123 if (length != sizeof(uint64_t)) 1163 if (length != sizeof(uint64_t)) {
1124 return -1; 1164 return -1;
1165 }
1125 1166
1126 size_t Node_format_size = sizeof(Node_format); 1167 size_t Node_format_size = sizeof(Node_format);
1127 uint8_t data[1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES 1168 uint8_t data[1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES
@@ -1140,8 +1181,9 @@ static int sendnodes_ipv6(const DHT *dht, IP_Port ip_port, const uint8_t *public
1140 if (num_nodes) { 1181 if (num_nodes) {
1141 nodes_length = pack_nodes(plain + 1, Node_format_size * MAX_SENT_NODES, nodes_list, num_nodes); 1182 nodes_length = pack_nodes(plain + 1, Node_format_size * MAX_SENT_NODES, nodes_list, num_nodes);
1142 1183
1143 if (nodes_length <= 0) 1184 if (nodes_length <= 0) {
1144 return -1; 1185 return -1;
1186 }
1145 } 1187 }
1146 1188
1147 plain[0] = num_nodes; 1189 plain[0] = num_nodes;
@@ -1152,8 +1194,9 @@ static int sendnodes_ipv6(const DHT *dht, IP_Port ip_port, const uint8_t *public
1152 1 + nodes_length + length, 1194 1 + nodes_length + length,
1153 encrypt ); 1195 encrypt );
1154 1196
1155 if (len != 1 + nodes_length + length + crypto_box_MACBYTES) 1197 if (len != 1 + nodes_length + length + crypto_box_MACBYTES) {
1156 return -1; 1198 return -1;
1199 }
1157 1200
1158 data[0] = NET_PACKET_SEND_NODES_IPV6; 1201 data[0] = NET_PACKET_SEND_NODES_IPV6;
1159 memcpy(data + 1, dht->self_public_key, crypto_box_PUBLICKEYBYTES); 1202 memcpy(data + 1, dht->self_public_key, crypto_box_PUBLICKEYBYTES);
@@ -1166,14 +1209,16 @@ static int sendnodes_ipv6(const DHT *dht, IP_Port ip_port, const uint8_t *public
1166static int handle_getnodes(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata) 1209static int handle_getnodes(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata)
1167{ 1210{
1168 if (length != (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + sizeof( 1211 if (length != (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + sizeof(
1169 uint64_t) + crypto_box_MACBYTES)) 1212 uint64_t) + crypto_box_MACBYTES)) {
1170 return 1; 1213 return 1;
1214 }
1171 1215
1172 DHT *dht = object; 1216 DHT *dht = object;
1173 1217
1174 /* Check if packet is from ourself. */ 1218 /* Check if packet is from ourself. */
1175 if (id_equal(packet + 1, dht->self_public_key)) 1219 if (id_equal(packet + 1, dht->self_public_key)) {
1176 return 1; 1220 return 1;
1221 }
1177 1222
1178 uint8_t plain[crypto_box_PUBLICKEYBYTES + sizeof(uint64_t)]; 1223 uint8_t plain[crypto_box_PUBLICKEYBYTES + sizeof(uint64_t)];
1179 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 1224 uint8_t shared_key[crypto_box_BEFORENMBYTES];
@@ -1185,8 +1230,9 @@ static int handle_getnodes(void *object, IP_Port source, const uint8_t *packet,
1185 crypto_box_PUBLICKEYBYTES + sizeof(uint64_t) + crypto_box_MACBYTES, 1230 crypto_box_PUBLICKEYBYTES + sizeof(uint64_t) + crypto_box_MACBYTES,
1186 plain ); 1231 plain );
1187 1232
1188 if (len != crypto_box_PUBLICKEYBYTES + sizeof(uint64_t)) 1233 if (len != crypto_box_PUBLICKEYBYTES + sizeof(uint64_t)) {
1189 return 1; 1234 return 1;
1235 }
1190 1236
1191 sendnodes_ipv6(dht, source, packet + 1, plain, plain + crypto_box_PUBLICKEYBYTES, sizeof(uint64_t), shared_key); 1237 sendnodes_ipv6(dht, source, packet + 1, plain, plain + crypto_box_PUBLICKEYBYTES, sizeof(uint64_t), shared_key);
1192 1238
@@ -1212,8 +1258,9 @@ static uint8_t sent_getnode_to_node(DHT *dht, const uint8_t *public_key, IP_Port
1212 Node_format test; 1258 Node_format test;
1213 memcpy(&test, data, sizeof(Node_format)); 1259 memcpy(&test, data, sizeof(Node_format));
1214 1260
1215 if (!ipport_equal(&test.ip_port, &node_ip_port) || public_key_cmp(test.public_key, public_key) != 0) 1261 if (!ipport_equal(&test.ip_port, &node_ip_port) || public_key_cmp(test.public_key, public_key) != 0) {
1216 return 0; 1262 return 0;
1263 }
1217 1264
1218 return 1; 1265 return 1;
1219} 1266}
@@ -1228,16 +1275,19 @@ static int handle_sendnodes_core(void *object, IP_Port source, const uint8_t *pa
1228 DHT *dht = object; 1275 DHT *dht = object;
1229 uint32_t cid_size = 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + 1 + sizeof(uint64_t) + crypto_box_MACBYTES; 1276 uint32_t cid_size = 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + 1 + sizeof(uint64_t) + crypto_box_MACBYTES;
1230 1277
1231 if (length < cid_size) /* too short */ 1278 if (length < cid_size) { /* too short */
1232 return 1; 1279 return 1;
1280 }
1233 1281
1234 uint32_t data_size = length - cid_size; 1282 uint32_t data_size = length - cid_size;
1235 1283
1236 if (data_size == 0) 1284 if (data_size == 0) {
1237 return 1; 1285 return 1;
1286 }
1238 1287
1239 if (data_size > sizeof(Node_format) * MAX_SENT_NODES) /* invalid length */ 1288 if (data_size > sizeof(Node_format) * MAX_SENT_NODES) { /* invalid length */
1240 return 1; 1289 return 1;
1290 }
1241 1291
1242 uint8_t plain[1 + data_size + sizeof(uint64_t)]; 1292 uint8_t plain[1 + data_size + sizeof(uint64_t)];
1243 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 1293 uint8_t shared_key[crypto_box_BEFORENMBYTES];
@@ -1249,31 +1299,37 @@ static int handle_sendnodes_core(void *object, IP_Port source, const uint8_t *pa
1249 1 + data_size + sizeof(uint64_t) + crypto_box_MACBYTES, 1299 1 + data_size + sizeof(uint64_t) + crypto_box_MACBYTES,
1250 plain); 1300 plain);
1251 1301
1252 if ((unsigned int)len != sizeof(plain)) 1302 if ((unsigned int)len != sizeof(plain)) {
1253 return 1; 1303 return 1;
1304 }
1254 1305
1255 if (plain[0] > size_plain_nodes) 1306 if (plain[0] > size_plain_nodes) {
1256 return 1; 1307 return 1;
1308 }
1257 1309
1258 Node_format sendback_node; 1310 Node_format sendback_node;
1259 1311
1260 uint64_t ping_id; 1312 uint64_t ping_id;
1261 memcpy(&ping_id, plain + 1 + data_size, sizeof(ping_id)); 1313 memcpy(&ping_id, plain + 1 + data_size, sizeof(ping_id));
1262 1314
1263 if (!sent_getnode_to_node(dht, packet + 1, source, ping_id, &sendback_node)) 1315 if (!sent_getnode_to_node(dht, packet + 1, source, ping_id, &sendback_node)) {
1264 return 1; 1316 return 1;
1317 }
1265 1318
1266 uint16_t length_nodes = 0; 1319 uint16_t length_nodes = 0;
1267 int num_nodes = unpack_nodes(plain_nodes, plain[0], &length_nodes, plain + 1, data_size, 0); 1320 int num_nodes = unpack_nodes(plain_nodes, plain[0], &length_nodes, plain + 1, data_size, 0);
1268 1321
1269 if (length_nodes != data_size) 1322 if (length_nodes != data_size) {
1270 return 1; 1323 return 1;
1324 }
1271 1325
1272 if (num_nodes != plain[0]) 1326 if (num_nodes != plain[0]) {
1273 return 1; 1327 return 1;
1328 }
1274 1329
1275 if (num_nodes < 0) 1330 if (num_nodes < 0) {
1276 return 1; 1331 return 1;
1332 }
1277 1333
1278 /* store the address the *request* was sent to */ 1334 /* store the address the *request* was sent to */
1279 addto_lists(dht, source, packet + 1); 1335 addto_lists(dht, source, packet + 1);
@@ -1290,11 +1346,13 @@ static int handle_sendnodes_ipv6(void *object, IP_Port source, const uint8_t *pa
1290 Node_format plain_nodes[MAX_SENT_NODES]; 1346 Node_format plain_nodes[MAX_SENT_NODES];
1291 uint32_t num_nodes; 1347 uint32_t num_nodes;
1292 1348
1293 if (handle_sendnodes_core(object, source, packet, length, plain_nodes, MAX_SENT_NODES, &num_nodes)) 1349 if (handle_sendnodes_core(object, source, packet, length, plain_nodes, MAX_SENT_NODES, &num_nodes)) {
1294 return 1; 1350 return 1;
1351 }
1295 1352
1296 if (num_nodes == 0) 1353 if (num_nodes == 0) {
1297 return 0; 1354 return 0;
1355 }
1298 1356
1299 uint32_t i; 1357 uint32_t i;
1300 1358
@@ -1322,8 +1380,9 @@ int DHT_addfriend(DHT *dht, const uint8_t *public_key, void (*ip_callback)(void
1322 if (friend_num != -1) { /* Is friend already in DHT? */ 1380 if (friend_num != -1) { /* Is friend already in DHT? */
1323 DHT_Friend *friend = &dht->friends_list[friend_num]; 1381 DHT_Friend *friend = &dht->friends_list[friend_num];
1324 1382
1325 if (friend->lock_count == DHT_FRIEND_MAX_LOCKS) 1383 if (friend->lock_count == DHT_FRIEND_MAX_LOCKS) {
1326 return -1; 1384 return -1;
1385 }
1327 1386
1328 lock_num = friend->lock_count; 1387 lock_num = friend->lock_count;
1329 ++friend->lock_count; 1388 ++friend->lock_count;
@@ -1331,8 +1390,9 @@ int DHT_addfriend(DHT *dht, const uint8_t *public_key, void (*ip_callback)(void
1331 friend->callbacks[lock_num].data = data; 1390 friend->callbacks[lock_num].data = data;
1332 friend->callbacks[lock_num].number = number; 1391 friend->callbacks[lock_num].number = number;
1333 1392
1334 if (lock_count) 1393 if (lock_count) {
1335 *lock_count = lock_num + 1; 1394 *lock_count = lock_num + 1;
1395 }
1336 1396
1337 return 0; 1397 return 0;
1338 } 1398 }
@@ -1340,8 +1400,9 @@ int DHT_addfriend(DHT *dht, const uint8_t *public_key, void (*ip_callback)(void
1340 DHT_Friend *temp; 1400 DHT_Friend *temp;
1341 temp = realloc(dht->friends_list, sizeof(DHT_Friend) * (dht->num_friends + 1)); 1401 temp = realloc(dht->friends_list, sizeof(DHT_Friend) * (dht->num_friends + 1));
1342 1402
1343 if (temp == NULL) 1403 if (temp == NULL) {
1344 return -1; 1404 return -1;
1405 }
1345 1406
1346 dht->friends_list = temp; 1407 dht->friends_list = temp;
1347 DHT_Friend *friend = &dht->friends_list[dht->num_friends]; 1408 DHT_Friend *friend = &dht->friends_list[dht->num_friends];
@@ -1357,8 +1418,9 @@ int DHT_addfriend(DHT *dht, const uint8_t *public_key, void (*ip_callback)(void
1357 friend->callbacks[lock_num].data = data; 1418 friend->callbacks[lock_num].data = data;
1358 friend->callbacks[lock_num].number = number; 1419 friend->callbacks[lock_num].number = number;
1359 1420
1360 if (lock_count) 1421 if (lock_count) {
1361 *lock_count = lock_num + 1; 1422 *lock_count = lock_num + 1;
1423 }
1362 1424
1363 friend->num_to_bootstrap = get_close_nodes(dht, friend->public_key, friend->to_bootstrap, 0, 1, 0); 1425 friend->num_to_bootstrap = get_close_nodes(dht, friend->public_key, friend->to_bootstrap, 0, 1, 0);
1364 1426
@@ -1402,8 +1464,9 @@ int DHT_delfriend(DHT *dht, const uint8_t *public_key, uint16_t lock_count)
1402 1464
1403 temp = realloc(dht->friends_list, sizeof(DHT_Friend) * (dht->num_friends)); 1465 temp = realloc(dht->friends_list, sizeof(DHT_Friend) * (dht->num_friends));
1404 1466
1405 if (temp == NULL) 1467 if (temp == NULL) {
1406 return -1; 1468 return -1;
1469 }
1407 1470
1408 dht->friends_list = temp; 1471 dht->friends_list = temp;
1409 return 0; 1472 return 0;
@@ -1427,11 +1490,12 @@ int DHT_getfriendip(const DHT *dht, const uint8_t *public_key, IP_Port *ip_port)
1427 IPPTsPng *assoc = NULL; 1490 IPPTsPng *assoc = NULL;
1428 uint32_t a; 1491 uint32_t a;
1429 1492
1430 for (a = 0, assoc = &client->assoc6; a < 2; a++, assoc = &client->assoc4) 1493 for (a = 0, assoc = &client->assoc6; a < 2; a++, assoc = &client->assoc4) {
1431 if (!is_timeout(assoc->timestamp, BAD_NODE_TIMEOUT)) { 1494 if (!is_timeout(assoc->timestamp, BAD_NODE_TIMEOUT)) {
1432 *ip_port = assoc->ip_port; 1495 *ip_port = assoc->ip_port;
1433 return 1; 1496 return 1;
1434 } 1497 }
1498 }
1435 } 1499 }
1436 } 1500 }
1437 1501
@@ -1462,7 +1526,7 @@ static uint8_t do_ping_and_sendnode_requests(DHT *dht, uint64_t *lastgetnode, co
1462 IPPTsPng *assoc; 1526 IPPTsPng *assoc;
1463 uint32_t a; 1527 uint32_t a;
1464 1528
1465 for (a = 0, assoc = &client->assoc6; a < 2; a++, assoc = &client->assoc4) 1529 for (a = 0, assoc = &client->assoc6; a < 2; a++, assoc = &client->assoc4) {
1466 if (!is_timeout(assoc->timestamp, KILL_NODE_TIMEOUT)) { 1530 if (!is_timeout(assoc->timestamp, KILL_NODE_TIMEOUT)) {
1467 sort = 0; 1531 sort = 0;
1468 not_kill++; 1532 not_kill++;
@@ -1486,6 +1550,7 @@ static uint8_t do_ping_and_sendnode_requests(DHT *dht, uint64_t *lastgetnode, co
1486 sort_ok = 1; 1550 sort_ok = 1;
1487 } 1551 }
1488 } 1552 }
1553 }
1489 } 1554 }
1490 1555
1491 if (sortable && sort_ok) { 1556 if (sortable && sort_ok) {
@@ -1559,9 +1624,11 @@ static void do_Close(DHT *dht)
1559 Client_data *client = &dht->close_clientlist[i]; 1624 Client_data *client = &dht->close_clientlist[i];
1560 IPPTsPng *assoc; 1625 IPPTsPng *assoc;
1561 1626
1562 for (a = 0, assoc = &client->assoc4; a < 2; a++, assoc = &client->assoc6) 1627 for (a = 0, assoc = &client->assoc4; a < 2; a++, assoc = &client->assoc6) {
1563 if (assoc->timestamp) 1628 if (assoc->timestamp) {
1564 assoc->timestamp = badonly; 1629 assoc->timestamp = badonly;
1630 }
1631 }
1565 } 1632 }
1566 } 1633 }
1567} 1634}
@@ -1610,8 +1677,9 @@ int DHT_bootstrap_from_address(DHT *dht, const char *address, uint8_t ipv6enable
1610 } 1677 }
1611 1678
1612 return 1; 1679 return 1;
1613 } else 1680 } else {
1614 return 0; 1681 return 0;
1682 }
1615} 1683}
1616 1684
1617/* Send the given packet to node with public_key 1685/* Send the given packet to node with public_key
@@ -1626,12 +1694,13 @@ int route_packet(const DHT *dht, const uint8_t *public_key, const uint8_t *packe
1626 if (id_equal(public_key, dht->close_clientlist[i].public_key)) { 1694 if (id_equal(public_key, dht->close_clientlist[i].public_key)) {
1627 const Client_data *client = &dht->close_clientlist[i]; 1695 const Client_data *client = &dht->close_clientlist[i];
1628 1696
1629 if (ip_isset(&client->assoc6.ip_port.ip)) 1697 if (ip_isset(&client->assoc6.ip_port.ip)) {
1630 return sendpacket(dht->net, client->assoc6.ip_port, packet, length); 1698 return sendpacket(dht->net, client->assoc6.ip_port, packet, length);
1631 else if (ip_isset(&client->assoc4.ip_port.ip)) 1699 } else if (ip_isset(&client->assoc4.ip_port.ip)) {
1632 return sendpacket(dht->net, client->assoc4.ip_port, packet, length); 1700 return sendpacket(dht->net, client->assoc4.ip_port, packet, length);
1633 else 1701 } else {
1634 break; 1702 break;
1703 }
1635 } 1704 }
1636 } 1705 }
1637 1706
@@ -1647,8 +1716,9 @@ int route_packet(const DHT *dht, const uint8_t *public_key, const uint8_t *packe
1647 */ 1716 */
1648static int friend_iplist(const DHT *dht, IP_Port *ip_portlist, uint16_t friend_num) 1717static int friend_iplist(const DHT *dht, IP_Port *ip_portlist, uint16_t friend_num)
1649{ 1718{
1650 if (friend_num >= dht->num_friends) 1719 if (friend_num >= dht->num_friends) {
1651 return -1; 1720 return -1;
1721 }
1652 1722
1653 DHT_Friend *friend = &dht->friends_list[friend_num]; 1723 DHT_Friend *friend = &dht->friends_list[friend_num];
1654 Client_data *client; 1724 Client_data *client;
@@ -1672,9 +1742,12 @@ static int friend_iplist(const DHT *dht, IP_Port *ip_portlist, uint16_t friend_n
1672 ++num_ipv6s; 1742 ++num_ipv6s;
1673 } 1743 }
1674 1744
1675 if (id_equal(client->public_key, friend->public_key)) 1745 if (id_equal(client->public_key, friend->public_key)) {
1676 if (!is_timeout(client->assoc6.timestamp, BAD_NODE_TIMEOUT) || !is_timeout(client->assoc4.timestamp, BAD_NODE_TIMEOUT)) 1746 if (!is_timeout(client->assoc6.timestamp, BAD_NODE_TIMEOUT)
1747 || !is_timeout(client->assoc4.timestamp, BAD_NODE_TIMEOUT)) {
1677 return 0; /* direct connectivity */ 1748 return 0; /* direct connectivity */
1749 }
1750 }
1678 } 1751 }
1679 1752
1680#ifdef FRIEND_IPLIST_PAD 1753#ifdef FRIEND_IPLIST_PAD
@@ -1717,8 +1790,9 @@ int route_tofriend(const DHT *dht, const uint8_t *friend_id, const uint8_t *pack
1717{ 1790{
1718 int num = friend_number(dht, friend_id); 1791 int num = friend_number(dht, friend_id);
1719 1792
1720 if (num == -1) 1793 if (num == -1) {
1721 return 0; 1794 return 0;
1795 }
1722 1796
1723 uint32_t i, sent = 0; 1797 uint32_t i, sent = 0;
1724 uint8_t friend_sent[MAX_FRIEND_CLIENTS] = {0}; 1798 uint8_t friend_sent[MAX_FRIEND_CLIENTS] = {0};
@@ -1726,8 +1800,9 @@ int route_tofriend(const DHT *dht, const uint8_t *friend_id, const uint8_t *pack
1726 IP_Port ip_list[MAX_FRIEND_CLIENTS]; 1800 IP_Port ip_list[MAX_FRIEND_CLIENTS];
1727 int ip_num = friend_iplist(dht, ip_list, num); 1801 int ip_num = friend_iplist(dht, ip_list, num);
1728 1802
1729 if (ip_num < (MAX_FRIEND_CLIENTS / 4)) 1803 if (ip_num < (MAX_FRIEND_CLIENTS / 4)) {
1730 return 0; /* Reason for that? */ 1804 return 0; /* Reason for that? */
1805 }
1731 1806
1732 DHT_Friend *friend = &dht->friends_list[num]; 1807 DHT_Friend *friend = &dht->friends_list[num];
1733 Client_data *client; 1808 Client_data *client;
@@ -1736,18 +1811,20 @@ int route_tofriend(const DHT *dht, const uint8_t *friend_id, const uint8_t *pack
1736 * is *usually* good(tm) (bites us in the behind in this case though) */ 1811 * is *usually* good(tm) (bites us in the behind in this case though) */
1737 uint32_t a; 1812 uint32_t a;
1738 1813
1739 for (a = 0; a < 2; a++) 1814 for (a = 0; a < 2; a++) {
1740 for (i = 0; i < MAX_FRIEND_CLIENTS; ++i) { 1815 for (i = 0; i < MAX_FRIEND_CLIENTS; ++i) {
1741 if (friend_sent[i])/* Send one packet per client.*/ 1816 if (friend_sent[i]) {/* Send one packet per client.*/
1742 continue; 1817 continue;
1818 }
1743 1819
1744 client = &friend->client_list[i]; 1820 client = &friend->client_list[i];
1745 IPPTsPng *assoc = NULL; 1821 IPPTsPng *assoc = NULL;
1746 1822
1747 if (!a) 1823 if (!a) {
1748 assoc = &client->assoc4; 1824 assoc = &client->assoc4;
1749 else 1825 } else {
1750 assoc = &client->assoc6; 1826 assoc = &client->assoc6;
1827 }
1751 1828
1752 /* If ip is not zero and node is good. */ 1829 /* If ip is not zero and node is good. */
1753 if (ip_isset(&assoc->ret_ip_port.ip) && 1830 if (ip_isset(&assoc->ret_ip_port.ip) &&
@@ -1760,6 +1837,7 @@ int route_tofriend(const DHT *dht, const uint8_t *friend_id, const uint8_t *pack
1760 } 1837 }
1761 } 1838 }
1762 } 1839 }
1840 }
1763 1841
1764 return sent; 1842 return sent;
1765} 1843}
@@ -1772,8 +1850,9 @@ static int routeone_tofriend(DHT *dht, const uint8_t *friend_id, const uint8_t *
1772{ 1850{
1773 int num = friend_number(dht, friend_id); 1851 int num = friend_number(dht, friend_id);
1774 1852
1775 if (num == -1) 1853 if (num == -1) {
1776 return 0; 1854 return 0;
1855 }
1777 1856
1778 DHT_Friend *friend = &dht->friends_list[num]; 1857 DHT_Friend *friend = &dht->friends_list[num];
1779 Client_data *client; 1858 Client_data *client;
@@ -1786,15 +1865,16 @@ static int routeone_tofriend(DHT *dht, const uint8_t *friend_id, const uint8_t *
1786 * is *usually* good(tm) (bites us in the behind in this case though) */ 1865 * is *usually* good(tm) (bites us in the behind in this case though) */
1787 uint32_t a; 1866 uint32_t a;
1788 1867
1789 for (a = 0; a < 2; a++) 1868 for (a = 0; a < 2; a++) {
1790 for (i = 0; i < MAX_FRIEND_CLIENTS; ++i) { 1869 for (i = 0; i < MAX_FRIEND_CLIENTS; ++i) {
1791 client = &friend->client_list[i]; 1870 client = &friend->client_list[i];
1792 IPPTsPng *assoc = NULL; 1871 IPPTsPng *assoc = NULL;
1793 1872
1794 if (!a) 1873 if (!a) {
1795 assoc = &client->assoc4; 1874 assoc = &client->assoc4;
1796 else 1875 } else {
1797 assoc = &client->assoc6; 1876 assoc = &client->assoc6;
1877 }
1798 1878
1799 /* If ip is not zero and node is good. */ 1879 /* If ip is not zero and node is good. */
1800 if (ip_isset(&assoc->ret_ip_port.ip) && !is_timeout(assoc->ret_timestamp, BAD_NODE_TIMEOUT)) { 1880 if (ip_isset(&assoc->ret_ip_port.ip) && !is_timeout(assoc->ret_timestamp, BAD_NODE_TIMEOUT)) {
@@ -1802,14 +1882,17 @@ static int routeone_tofriend(DHT *dht, const uint8_t *friend_id, const uint8_t *
1802 ++n; 1882 ++n;
1803 } 1883 }
1804 } 1884 }
1885 }
1805 1886
1806 if (n < 1) 1887 if (n < 1) {
1807 return 0; 1888 return 0;
1889 }
1808 1890
1809 int retval = sendpacket(dht->net, ip_list[rand() % n], packet, length); 1891 int retval = sendpacket(dht->net, ip_list[rand() % n], packet, length);
1810 1892
1811 if ((unsigned int)retval == length) 1893 if ((unsigned int)retval == length) {
1812 return 1; 1894 return 1;
1895 }
1813 1896
1814 return 0; 1897 return 0;
1815} 1898}
@@ -1830,16 +1913,19 @@ static int send_NATping(DHT *dht, const uint8_t *public_key, uint64_t ping_id, u
1830 int len = create_request(dht->self_public_key, dht->self_secret_key, packet, public_key, data, 1913 int len = create_request(dht->self_public_key, dht->self_secret_key, packet, public_key, data,
1831 sizeof(uint64_t) + 1, CRYPTO_PACKET_NAT_PING); 1914 sizeof(uint64_t) + 1, CRYPTO_PACKET_NAT_PING);
1832 1915
1833 if (len == -1) 1916 if (len == -1) {
1834 return -1; 1917 return -1;
1918 }
1835 1919
1836 if (type == 0) /* If packet is request use many people to route it. */ 1920 if (type == 0) { /* If packet is request use many people to route it. */
1837 num = route_tofriend(dht, public_key, packet, len); 1921 num = route_tofriend(dht, public_key, packet, len);
1838 else if (type == 1) /* If packet is response use only one person to route it */ 1922 } else if (type == 1) { /* If packet is response use only one person to route it */
1839 num = routeone_tofriend(dht, public_key, packet, len); 1923 num = routeone_tofriend(dht, public_key, packet, len);
1924 }
1840 1925
1841 if (num == 0) 1926 if (num == 0) {
1842 return -1; 1927 return -1;
1928 }
1843 1929
1844 return num; 1930 return num;
1845} 1931}
@@ -1848,8 +1934,9 @@ static int send_NATping(DHT *dht, const uint8_t *public_key, uint64_t ping_id, u
1848static int handle_NATping(void *object, IP_Port source, const uint8_t *source_pubkey, const uint8_t *packet, 1934static int handle_NATping(void *object, IP_Port source, const uint8_t *source_pubkey, const uint8_t *packet,
1849 uint16_t length) 1935 uint16_t length)
1850{ 1936{
1851 if (length != sizeof(uint64_t) + 1) 1937 if (length != sizeof(uint64_t) + 1) {
1852 return 1; 1938 return 1;
1939 }
1853 1940
1854 DHT *dht = object; 1941 DHT *dht = object;
1855 uint64_t ping_id; 1942 uint64_t ping_id;
@@ -1857,8 +1944,9 @@ static int handle_NATping(void *object, IP_Port source, const uint8_t *source_pu
1857 1944
1858 int friendnumber = friend_number(dht, source_pubkey); 1945 int friendnumber = friend_number(dht, source_pubkey);
1859 1946
1860 if (friendnumber == -1) 1947 if (friendnumber == -1) {
1861 return 1; 1948 return 1;
1949 }
1862 1950
1863 DHT_Friend *friend = &dht->friends_list[friendnumber]; 1951 DHT_Friend *friend = &dht->friends_list[friendnumber];
1864 1952
@@ -1889,20 +1977,23 @@ static IP NAT_commonip(IP_Port *ip_portlist, uint16_t len, uint16_t min_num)
1889 IP zero; 1977 IP zero;
1890 ip_reset(&zero); 1978 ip_reset(&zero);
1891 1979
1892 if (len > MAX_FRIEND_CLIENTS) 1980 if (len > MAX_FRIEND_CLIENTS) {
1893 return zero; 1981 return zero;
1982 }
1894 1983
1895 uint32_t i, j; 1984 uint32_t i, j;
1896 uint16_t numbers[MAX_FRIEND_CLIENTS] = {0}; 1985 uint16_t numbers[MAX_FRIEND_CLIENTS] = {0};
1897 1986
1898 for (i = 0; i < len; ++i) { 1987 for (i = 0; i < len; ++i) {
1899 for (j = 0; j < len; ++j) { 1988 for (j = 0; j < len; ++j) {
1900 if (ip_equal(&ip_portlist[i].ip, &ip_portlist[j].ip)) 1989 if (ip_equal(&ip_portlist[i].ip, &ip_portlist[j].ip)) {
1901 ++numbers[i]; 1990 ++numbers[i];
1991 }
1902 } 1992 }
1903 1993
1904 if (numbers[i] >= min_num) 1994 if (numbers[i] >= min_num) {
1905 return ip_portlist[i].ip; 1995 return ip_portlist[i].ip;
1996 }
1906 } 1997 }
1907 1998
1908 return zero; 1999 return zero;
@@ -1931,16 +2022,18 @@ static uint16_t NAT_getports(uint16_t *portlist, IP_Port *ip_portlist, uint16_t
1931 2022
1932static void punch_holes(DHT *dht, IP ip, uint16_t *port_list, uint16_t numports, uint16_t friend_num) 2023static void punch_holes(DHT *dht, IP ip, uint16_t *port_list, uint16_t numports, uint16_t friend_num)
1933{ 2024{
1934 if (numports > MAX_FRIEND_CLIENTS || numports == 0) 2025 if (numports > MAX_FRIEND_CLIENTS || numports == 0) {
1935 return; 2026 return;
2027 }
1936 2028
1937 uint32_t i; 2029 uint32_t i;
1938 uint32_t top = dht->friends_list[friend_num].nat.punching_index + MAX_PUNCHING_PORTS; 2030 uint32_t top = dht->friends_list[friend_num].nat.punching_index + MAX_PUNCHING_PORTS;
1939 uint16_t firstport = port_list[0]; 2031 uint16_t firstport = port_list[0];
1940 2032
1941 for (i = 0; i < numports; ++i) { 2033 for (i = 0; i < numports; ++i) {
1942 if (firstport != port_list[i]) 2034 if (firstport != port_list[i]) {
1943 break; 2035 break;
2036 }
1944 } 2037 }
1945 2038
1946 if (i == numports) { /* If all ports are the same, only try that one port. */ 2039 if (i == numports) { /* If all ports are the same, only try that one port. */
@@ -1988,8 +2081,9 @@ static void do_NAT(DHT *dht)
1988 int num = friend_iplist(dht, ip_list, i); 2081 int num = friend_iplist(dht, ip_list, i);
1989 2082
1990 /* If already connected or friend is not online don't try to hole punch. */ 2083 /* If already connected or friend is not online don't try to hole punch. */
1991 if (num < MAX_FRIEND_CLIENTS / 2) 2084 if (num < MAX_FRIEND_CLIENTS / 2) {
1992 continue; 2085 continue;
2086 }
1993 2087
1994 if (dht->friends_list[i].nat.NATping_timestamp + PUNCH_INTERVAL < temp_time) { 2088 if (dht->friends_list[i].nat.NATping_timestamp + PUNCH_INTERVAL < temp_time) {
1995 send_NATping(dht, dht->friends_list[i].public_key, dht->friends_list[i].nat.NATping_id, NAT_PING_REQUEST); 2089 send_NATping(dht, dht->friends_list[i].public_key, dht->friends_list[i].nat.NATping_id, NAT_PING_REQUEST);
@@ -2002,8 +2096,9 @@ static void do_NAT(DHT *dht)
2002 2096
2003 IP ip = NAT_commonip(ip_list, num, MAX_FRIEND_CLIENTS / 2); 2097 IP ip = NAT_commonip(ip_list, num, MAX_FRIEND_CLIENTS / 2);
2004 2098
2005 if (!ip_isset(&ip)) 2099 if (!ip_isset(&ip)) {
2006 continue; 2100 continue;
2101 }
2007 2102
2008 uint16_t port_list[MAX_FRIEND_CLIENTS]; 2103 uint16_t port_list[MAX_FRIEND_CLIENTS];
2009 uint16_t numports = NAT_getports(port_list, ip_list, num, ip); 2104 uint16_t numports = NAT_getports(port_list, ip_list, num, ip);
@@ -2029,8 +2124,9 @@ static void do_NAT(DHT *dht)
2029 2124
2030static int send_hardening_req(DHT *dht, Node_format *sendto, uint8_t type, uint8_t *contents, uint16_t length) 2125static int send_hardening_req(DHT *dht, Node_format *sendto, uint8_t type, uint8_t *contents, uint16_t length)
2031{ 2126{
2032 if (length > HARDREQ_DATA_SIZE - 1) 2127 if (length > HARDREQ_DATA_SIZE - 1) {
2033 return -1; 2128 return -1;
2129 }
2034 2130
2035 uint8_t packet[MAX_CRYPTO_REQUEST_SIZE]; 2131 uint8_t packet[MAX_CRYPTO_REQUEST_SIZE];
2036 uint8_t data[HARDREQ_DATA_SIZE] = {0}; 2132 uint8_t data[HARDREQ_DATA_SIZE] = {0};
@@ -2039,8 +2135,9 @@ static int send_hardening_req(DHT *dht, Node_format *sendto, uint8_t type, uint8
2039 int len = create_request(dht->self_public_key, dht->self_secret_key, packet, sendto->public_key, data, 2135 int len = create_request(dht->self_public_key, dht->self_secret_key, packet, sendto->public_key, data,
2040 sizeof(data), CRYPTO_PACKET_HARDENING); 2136 sizeof(data), CRYPTO_PACKET_HARDENING);
2041 2137
2042 if (len == -1) 2138 if (len == -1) {
2043 return -1; 2139 return -1;
2140 }
2044 2141
2045 return sendpacket(dht->net, sendto->ip_port, packet, len); 2142 return sendpacket(dht->net, sendto->ip_port, packet, len);
2046} 2143}
@@ -2058,8 +2155,9 @@ static int send_hardening_getnode_req(DHT *dht, Node_format *dest, Node_format *
2058static int send_hardening_getnode_res(const DHT *dht, const Node_format *sendto, const uint8_t *queried_client_id, 2155static int send_hardening_getnode_res(const DHT *dht, const Node_format *sendto, const uint8_t *queried_client_id,
2059 const uint8_t *nodes_data, uint16_t nodes_data_length) 2156 const uint8_t *nodes_data, uint16_t nodes_data_length)
2060{ 2157{
2061 if (!ip_isset(&sendto->ip_port.ip)) 2158 if (!ip_isset(&sendto->ip_port.ip)) {
2062 return -1; 2159 return -1;
2160 }
2063 2161
2064 uint8_t packet[MAX_CRYPTO_REQUEST_SIZE]; 2162 uint8_t packet[MAX_CRYPTO_REQUEST_SIZE];
2065 uint8_t data[1 + crypto_box_PUBLICKEYBYTES + nodes_data_length]; 2163 uint8_t data[1 + crypto_box_PUBLICKEYBYTES + nodes_data_length];
@@ -2069,8 +2167,9 @@ static int send_hardening_getnode_res(const DHT *dht, const Node_format *sendto,
2069 int len = create_request(dht->self_public_key, dht->self_secret_key, packet, sendto->public_key, data, 2167 int len = create_request(dht->self_public_key, dht->self_secret_key, packet, sendto->public_key, data,
2070 sizeof(data), CRYPTO_PACKET_HARDENING); 2168 sizeof(data), CRYPTO_PACKET_HARDENING);
2071 2169
2072 if (len == -1) 2170 if (len == -1) {
2073 return -1; 2171 return -1;
2172 }
2074 2173
2075 return sendpacket(dht->net, sendto->ip_port, packet, len); 2174 return sendpacket(dht->net, sendto->ip_port, packet, len);
2076} 2175}
@@ -2081,13 +2180,15 @@ static IPPTsPng *get_closelist_IPPTsPng(DHT *dht, const uint8_t *public_key, sa_
2081 uint32_t i; 2180 uint32_t i;
2082 2181
2083 for (i = 0; i < LCLIENT_LIST; ++i) { 2182 for (i = 0; i < LCLIENT_LIST; ++i) {
2084 if (public_key_cmp(dht->close_clientlist[i].public_key, public_key) != 0) 2183 if (public_key_cmp(dht->close_clientlist[i].public_key, public_key) != 0) {
2085 continue; 2184 continue;
2185 }
2086 2186
2087 if (sa_family == AF_INET) 2187 if (sa_family == AF_INET) {
2088 return &dht->close_clientlist[i].assoc4; 2188 return &dht->close_clientlist[i].assoc4;
2089 else if (sa_family == AF_INET6) 2189 } else if (sa_family == AF_INET6) {
2090 return &dht->close_clientlist[i].assoc6; 2190 return &dht->close_clientlist[i].assoc6;
2191 }
2091 } 2192 }
2092 2193
2093 return NULL; 2194 return NULL;
@@ -2136,26 +2237,30 @@ static int handle_hardening(void *object, IP_Port source, const uint8_t *source_
2136 2237
2137 switch (packet[0]) { 2238 switch (packet[0]) {
2138 case CHECK_TYPE_GETNODE_REQ: { 2239 case CHECK_TYPE_GETNODE_REQ: {
2139 if (length != HARDREQ_DATA_SIZE) 2240 if (length != HARDREQ_DATA_SIZE) {
2140 return 1; 2241 return 1;
2242 }
2141 2243
2142 Node_format node, tocheck_node; 2244 Node_format node, tocheck_node;
2143 node.ip_port = source; 2245 node.ip_port = source;
2144 memcpy(node.public_key, source_pubkey, crypto_box_PUBLICKEYBYTES); 2246 memcpy(node.public_key, source_pubkey, crypto_box_PUBLICKEYBYTES);
2145 memcpy(&tocheck_node, packet + 1, sizeof(Node_format)); 2247 memcpy(&tocheck_node, packet + 1, sizeof(Node_format));
2146 2248
2147 if (getnodes(dht, tocheck_node.ip_port, tocheck_node.public_key, packet + 1 + sizeof(Node_format), &node) == -1) 2249 if (getnodes(dht, tocheck_node.ip_port, tocheck_node.public_key, packet + 1 + sizeof(Node_format), &node) == -1) {
2148 return 1; 2250 return 1;
2251 }
2149 2252
2150 return 0; 2253 return 0;
2151 } 2254 }
2152 2255
2153 case CHECK_TYPE_GETNODE_RES: { 2256 case CHECK_TYPE_GETNODE_RES: {
2154 if (length <= crypto_box_PUBLICKEYBYTES + 1) 2257 if (length <= crypto_box_PUBLICKEYBYTES + 1) {
2155 return 1; 2258 return 1;
2259 }
2156 2260
2157 if (length > 1 + crypto_box_PUBLICKEYBYTES + sizeof(Node_format) * MAX_SENT_NODES) 2261 if (length > 1 + crypto_box_PUBLICKEYBYTES + sizeof(Node_format) * MAX_SENT_NODES) {
2158 return 1; 2262 return 1;
2263 }
2159 2264
2160 uint16_t length_nodes = length - 1 - crypto_box_PUBLICKEYBYTES; 2265 uint16_t length_nodes = length - 1 - crypto_box_PUBLICKEYBYTES;
2161 Node_format nodes[MAX_SENT_NODES]; 2266 Node_format nodes[MAX_SENT_NODES];
@@ -2163,23 +2268,28 @@ static int handle_hardening(void *object, IP_Port source, const uint8_t *source_
2163 2268
2164 /* TODO: MAX_SENT_NODES nodes should be returned at all times 2269 /* TODO: MAX_SENT_NODES nodes should be returned at all times
2165 (right now we have a small network size so it could cause problems for testing and etc..) */ 2270 (right now we have a small network size so it could cause problems for testing and etc..) */
2166 if (num_nodes <= 0) 2271 if (num_nodes <= 0) {
2167 return 1; 2272 return 1;
2273 }
2168 2274
2169 /* NOTE: This should work for now but should be changed to something better. */ 2275 /* NOTE: This should work for now but should be changed to something better. */
2170 if (have_nodes_closelist(dht, nodes, num_nodes) < (uint32_t)((num_nodes + 2) / 2)) 2276 if (have_nodes_closelist(dht, nodes, num_nodes) < (uint32_t)((num_nodes + 2) / 2)) {
2171 return 1; 2277 return 1;
2278 }
2172 2279
2173 IPPTsPng *temp = get_closelist_IPPTsPng(dht, packet + 1, nodes[0].ip_port.ip.family); 2280 IPPTsPng *temp = get_closelist_IPPTsPng(dht, packet + 1, nodes[0].ip_port.ip.family);
2174 2281
2175 if (temp == NULL) 2282 if (temp == NULL) {
2176 return 1; 2283 return 1;
2284 }
2177 2285
2178 if (is_timeout(temp->hardening.send_nodes_timestamp, HARDENING_INTERVAL)) 2286 if (is_timeout(temp->hardening.send_nodes_timestamp, HARDENING_INTERVAL)) {
2179 return 1; 2287 return 1;
2288 }
2180 2289
2181 if (public_key_cmp(temp->hardening.send_nodes_pingedid, source_pubkey) != 0) 2290 if (public_key_cmp(temp->hardening.send_nodes_pingedid, source_pubkey) != 0) {
2182 return 1; 2291 return 1;
2292 }
2183 2293
2184 /* If Nodes look good and the request checks out */ 2294 /* If Nodes look good and the request checks out */
2185 temp->hardening.send_nodes_ok = 1; 2295 temp->hardening.send_nodes_ok = 1;
@@ -2207,10 +2317,11 @@ Node_format random_node(DHT *dht, sa_family_t sa_family)
2207 memset(nodes_list, 0, sizeof(nodes_list)); 2317 memset(nodes_list, 0, sizeof(nodes_list));
2208 uint32_t num_nodes = get_close_nodes(dht, id, nodes_list, sa_family, 1, 0); 2318 uint32_t num_nodes = get_close_nodes(dht, id, nodes_list, sa_family, 1, 0);
2209 2319
2210 if (num_nodes == 0) 2320 if (num_nodes == 0) {
2211 return nodes_list[0]; 2321 return nodes_list[0];
2212 else 2322 } else {
2213 return nodes_list[rand() % num_nodes]; 2323 return nodes_list[rand() % num_nodes];
2324 }
2214} 2325}
2215 2326
2216/* Put up to max_num nodes in nodes from the closelist. 2327/* Put up to max_num nodes in nodes from the closelist.
@@ -2219,8 +2330,9 @@ Node_format random_node(DHT *dht, sa_family_t sa_family)
2219 */ 2330 */
2220uint16_t list_nodes(Client_data *list, unsigned int length, Node_format *nodes, uint16_t max_num) 2331uint16_t list_nodes(Client_data *list, unsigned int length, Node_format *nodes, uint16_t max_num)
2221{ 2332{
2222 if (max_num == 0) 2333 if (max_num == 0) {
2223 return 0; 2334 return 0;
2335 }
2224 2336
2225 uint16_t count = 0; 2337 uint16_t count = 0;
2226 2338
@@ -2229,14 +2341,16 @@ uint16_t list_nodes(Client_data *list, unsigned int length, Node_format *nodes,
2229 for (i = length; i != 0; --i) { 2341 for (i = length; i != 0; --i) {
2230 IPPTsPng *assoc = NULL; 2342 IPPTsPng *assoc = NULL;
2231 2343
2232 if (!is_timeout(list[i - 1].assoc4.timestamp, BAD_NODE_TIMEOUT)) 2344 if (!is_timeout(list[i - 1].assoc4.timestamp, BAD_NODE_TIMEOUT)) {
2233 assoc = &list[i - 1].assoc4; 2345 assoc = &list[i - 1].assoc4;
2346 }
2234 2347
2235 if (!is_timeout(list[i - 1].assoc6.timestamp, BAD_NODE_TIMEOUT)) { 2348 if (!is_timeout(list[i - 1].assoc6.timestamp, BAD_NODE_TIMEOUT)) {
2236 if (assoc == NULL) 2349 if (assoc == NULL) {
2237 assoc = &list[i - 1].assoc6; 2350 assoc = &list[i - 1].assoc6;
2238 else if (rand() % 2) 2351 } else if (rand() % 2) {
2239 assoc = &list[i - 1].assoc6; 2352 assoc = &list[i - 1].assoc6;
2353 }
2240 } 2354 }
2241 2355
2242 if (assoc != NULL) { 2356 if (assoc != NULL) {
@@ -2244,8 +2358,9 @@ uint16_t list_nodes(Client_data *list, unsigned int length, Node_format *nodes,
2244 nodes[count].ip_port = assoc->ip_port; 2358 nodes[count].ip_port = assoc->ip_port;
2245 ++count; 2359 ++count;
2246 2360
2247 if (count >= max_num) 2361 if (count >= max_num) {
2248 return count; 2362 return count;
2363 }
2249 } 2364 }
2250 } 2365 }
2251 2366
@@ -2258,8 +2373,9 @@ uint16_t list_nodes(Client_data *list, unsigned int length, Node_format *nodes,
2258 */ 2373 */
2259uint16_t randfriends_nodes(DHT *dht, Node_format *nodes, uint16_t max_num) 2374uint16_t randfriends_nodes(DHT *dht, Node_format *nodes, uint16_t max_num)
2260{ 2375{
2261 if (max_num == 0) 2376 if (max_num == 0) {
2262 return 0; 2377 return 0;
2378 }
2263 2379
2264 uint16_t count = 0; 2380 uint16_t count = 0;
2265 unsigned int i, r = rand(); 2381 unsigned int i, r = rand();
@@ -2268,8 +2384,9 @@ uint16_t randfriends_nodes(DHT *dht, Node_format *nodes, uint16_t max_num)
2268 count += list_nodes(dht->friends_list[(i + r) % DHT_FAKE_FRIEND_NUMBER].client_list, MAX_FRIEND_CLIENTS, nodes + count, 2384 count += list_nodes(dht->friends_list[(i + r) % DHT_FAKE_FRIEND_NUMBER].client_list, MAX_FRIEND_CLIENTS, nodes + count,
2269 max_num - count); 2385 max_num - count);
2270 2386
2271 if (count >= max_num) 2387 if (count >= max_num) {
2272 break; 2388 break;
2389 }
2273 } 2390 }
2274 2391
2275 return count; 2392 return count;
@@ -2301,18 +2418,21 @@ void do_hardening(DHT *dht)
2301 sa_family = AF_INET6; 2418 sa_family = AF_INET6;
2302 } 2419 }
2303 2420
2304 if (is_timeout(cur_iptspng->timestamp, BAD_NODE_TIMEOUT)) 2421 if (is_timeout(cur_iptspng->timestamp, BAD_NODE_TIMEOUT)) {
2305 continue; 2422 continue;
2423 }
2306 2424
2307 if (cur_iptspng->hardening.send_nodes_ok == 0) { 2425 if (cur_iptspng->hardening.send_nodes_ok == 0) {
2308 if (is_timeout(cur_iptspng->hardening.send_nodes_timestamp, HARDENING_INTERVAL)) { 2426 if (is_timeout(cur_iptspng->hardening.send_nodes_timestamp, HARDENING_INTERVAL)) {
2309 Node_format rand_node = random_node(dht, sa_family); 2427 Node_format rand_node = random_node(dht, sa_family);
2310 2428
2311 if (!ipport_isset(&rand_node.ip_port)) 2429 if (!ipport_isset(&rand_node.ip_port)) {
2312 continue; 2430 continue;
2431 }
2313 2432
2314 if (id_equal(public_key, rand_node.public_key)) 2433 if (id_equal(public_key, rand_node.public_key)) {
2315 continue; 2434 continue;
2435 }
2316 2436
2317 Node_format to_test; 2437 Node_format to_test;
2318 to_test.ip_port = cur_iptspng->ip_port; 2438 to_test.ip_port = cur_iptspng->ip_port;
@@ -2348,8 +2468,9 @@ static int cryptopacket_handle(void *object, IP_Port source, const uint8_t *pack
2348 2468
2349 if (packet[0] == NET_PACKET_CRYPTO) { 2469 if (packet[0] == NET_PACKET_CRYPTO) {
2350 if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES || 2470 if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES ||
2351 length > MAX_CRYPTO_REQUEST_SIZE + crypto_box_MACBYTES) 2471 length > MAX_CRYPTO_REQUEST_SIZE + crypto_box_MACBYTES) {
2352 return 1; 2472 return 1;
2473 }
2353 2474
2354 if (public_key_cmp(packet + 1, dht->self_public_key) == 0) { // Check if request is for us. 2475 if (public_key_cmp(packet + 1, dht->self_public_key) == 0) { // Check if request is for us.
2355 uint8_t public_key[crypto_box_PUBLICKEYBYTES]; 2476 uint8_t public_key[crypto_box_PUBLICKEYBYTES];
@@ -2357,10 +2478,13 @@ static int cryptopacket_handle(void *object, IP_Port source, const uint8_t *pack
2357 uint8_t number; 2478 uint8_t number;
2358 int len = handle_request(dht->self_public_key, dht->self_secret_key, public_key, data, &number, packet, length); 2479 int len = handle_request(dht->self_public_key, dht->self_secret_key, public_key, data, &number, packet, length);
2359 2480
2360 if (len == -1 || len == 0) 2481 if (len == -1 || len == 0) {
2361 return 1; 2482 return 1;
2483 }
2362 2484
2363 if (!dht->cryptopackethandlers[number].function) return 1; 2485 if (!dht->cryptopackethandlers[number].function) {
2486 return 1;
2487 }
2364 2488
2365 return dht->cryptopackethandlers[number].function(dht->cryptopackethandlers[number].object, source, public_key, 2489 return dht->cryptopackethandlers[number].function(dht->cryptopackethandlers[number].object, source, public_key,
2366 data, len); 2490 data, len);
@@ -2368,8 +2492,9 @@ static int cryptopacket_handle(void *object, IP_Port source, const uint8_t *pack
2368 } else { /* If request is not for us, try routing it. */ 2492 } else { /* If request is not for us, try routing it. */
2369 int retval = route_packet(dht, packet + 1, packet, length); 2493 int retval = route_packet(dht, packet + 1, packet, length);
2370 2494
2371 if ((unsigned int)retval == length) 2495 if ((unsigned int)retval == length) {
2372 return 0; 2496 return 0;
2497 }
2373 } 2498 }
2374 } 2499 }
2375 2500
@@ -2383,13 +2508,15 @@ DHT *new_DHT(Logger *log, Networking_Core *net)
2383 /* init time */ 2508 /* init time */
2384 unix_time_update(); 2509 unix_time_update();
2385 2510
2386 if (net == NULL) 2511 if (net == NULL) {
2387 return NULL; 2512 return NULL;
2513 }
2388 2514
2389 DHT *dht = calloc(1, sizeof(DHT)); 2515 DHT *dht = calloc(1, sizeof(DHT));
2390 2516
2391 if (dht == NULL) 2517 if (dht == NULL) {
2392 return NULL; 2518 return NULL;
2519 }
2393 2520
2394 dht->log = log; 2521 dht->log = log;
2395 dht->net = net; 2522 dht->net = net;
@@ -2571,11 +2698,13 @@ void DHT_save(DHT *dht, uint8_t *data)
2571/* Start sending packets after DHT loaded_friends_list and loaded_clients_list are set */ 2698/* Start sending packets after DHT loaded_friends_list and loaded_clients_list are set */
2572int DHT_connect_after_load(DHT *dht) 2699int DHT_connect_after_load(DHT *dht)
2573{ 2700{
2574 if (dht == NULL) 2701 if (dht == NULL) {
2575 return -1; 2702 return -1;
2703 }
2576 2704
2577 if (!dht->loaded_nodes_list) 2705 if (!dht->loaded_nodes_list) {
2578 return -1; 2706 return -1;
2707 }
2579 2708
2580 /* DHT is connected, stop. */ 2709 /* DHT is connected, stop. */
2581 if (DHT_non_lan_connected(dht)) { 2710 if (DHT_non_lan_connected(dht)) {
@@ -2602,8 +2731,9 @@ static int dht_load_state_callback(void *outer, const uint8_t *data, uint32_t le
2602 2731
2603 switch (type) { 2732 switch (type) {
2604 case DHT_STATE_TYPE_NODES: 2733 case DHT_STATE_TYPE_NODES:
2605 if (length == 0) 2734 if (length == 0) {
2606 break; 2735 break;
2736 }
2607 2737
2608 { 2738 {
2609 free(dht->loaded_nodes_list); 2739 free(dht->loaded_nodes_list);
@@ -2647,9 +2777,10 @@ int DHT_load(DHT *dht, const uint8_t *data, uint32_t length)
2647 uint32_t data32; 2777 uint32_t data32;
2648 lendian_to_host32(&data32, data); 2778 lendian_to_host32(&data32, data);
2649 2779
2650 if (data32 == DHT_STATE_COOKIE_GLOBAL) 2780 if (data32 == DHT_STATE_COOKIE_GLOBAL) {
2651 return load_state(dht_load_state_callback, dht, data + cookie_len, 2781 return load_state(dht_load_state_callback, dht, data + cookie_len,
2652 length - cookie_len, DHT_STATE_COOKIE_TYPE); 2782 length - cookie_len, DHT_STATE_COOKIE_TYPE);
2783 }
2653 } 2784 }
2654 2785
2655 return -1; 2786 return -1;
@@ -2667,8 +2798,9 @@ int DHT_isconnected(const DHT *dht)
2667 const Client_data *client = &dht->close_clientlist[i]; 2798 const Client_data *client = &dht->close_clientlist[i];
2668 2799
2669 if (!is_timeout(client->assoc4.timestamp, BAD_NODE_TIMEOUT) || 2800 if (!is_timeout(client->assoc4.timestamp, BAD_NODE_TIMEOUT) ||
2670 !is_timeout(client->assoc6.timestamp, BAD_NODE_TIMEOUT)) 2801 !is_timeout(client->assoc6.timestamp, BAD_NODE_TIMEOUT)) {
2671 return 1; 2802 return 1;
2803 }
2672 } 2804 }
2673 2805
2674 return 0; 2806 return 0;
@@ -2685,11 +2817,13 @@ int DHT_non_lan_connected(const DHT *dht)
2685 for (i = 0; i < LCLIENT_LIST; ++i) { 2817 for (i = 0; i < LCLIENT_LIST; ++i) {
2686 const Client_data *client = &dht->close_clientlist[i]; 2818 const Client_data *client = &dht->close_clientlist[i];
2687 2819
2688 if (!is_timeout(client->assoc4.timestamp, BAD_NODE_TIMEOUT) && LAN_ip(client->assoc4.ip_port.ip) == -1) 2820 if (!is_timeout(client->assoc4.timestamp, BAD_NODE_TIMEOUT) && LAN_ip(client->assoc4.ip_port.ip) == -1) {
2689 return 1; 2821 return 1;
2822 }
2690 2823
2691 if (!is_timeout(client->assoc6.timestamp, BAD_NODE_TIMEOUT) && LAN_ip(client->assoc6.ip_port.ip) == -1) 2824 if (!is_timeout(client->assoc6.timestamp, BAD_NODE_TIMEOUT) && LAN_ip(client->assoc6.ip_port.ip) == -1) {
2692 return 1; 2825 return 1;
2826 }
2693 2827
2694 } 2828 }
2695 2829
diff --git a/toxcore/LAN_discovery.c b/toxcore/LAN_discovery.c
index 44684e8f..d430c3fe 100644
--- a/toxcore/LAN_discovery.c
+++ b/toxcore/LAN_discovery.c
@@ -110,8 +110,9 @@ static void fetch_broadcast_info(uint16_t port)
110 broadcast_count = 0; 110 broadcast_count = 0;
111 sock_t sock = 0; 111 sock_t sock = 0;
112 112
113 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) 113 if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
114 return; 114 return;
115 }
115 116
116 /* Configure ifconf for the ioctl call. */ 117 /* Configure ifconf for the ioctl call. */
117 struct ifreq i_faces[MAX_INTERFACES]; 118 struct ifreq i_faces[MAX_INTERFACES];
@@ -135,12 +136,14 @@ static void fetch_broadcast_info(uint16_t port)
135 136
136 for (i = 0; i < count; i++) { 137 for (i = 0; i < count; i++) {
137 /* there are interfaces with are incapable of broadcast */ 138 /* there are interfaces with are incapable of broadcast */
138 if (ioctl(sock, SIOCGIFBRDADDR, &i_faces[i]) < 0) 139 if (ioctl(sock, SIOCGIFBRDADDR, &i_faces[i]) < 0) {
139 continue; 140 continue;
141 }
140 142
141 /* moot check: only AF_INET returned (backwards compat.) */ 143 /* moot check: only AF_INET returned (backwards compat.) */
142 if (i_faces[i].ifr_broadaddr.sa_family != AF_INET) 144 if (i_faces[i].ifr_broadaddr.sa_family != AF_INET) {
143 continue; 145 continue;
146 }
144 147
145 struct sockaddr_in *sock4 = (struct sockaddr_in *)&i_faces[i].ifr_broadaddr; 148 struct sockaddr_in *sock4 = (struct sockaddr_in *)&i_faces[i].ifr_broadaddr;
146 149
@@ -181,16 +184,19 @@ static uint32_t send_broadcasts(Networking_Core *net, uint16_t port, const uint8
181{ 184{
182 /* fetch only once? on every packet? every X seconds? 185 /* fetch only once? on every packet? every X seconds?
183 * old: every packet, new: once */ 186 * old: every packet, new: once */
184 if (broadcast_count < 0) 187 if (broadcast_count < 0) {
185 fetch_broadcast_info(port); 188 fetch_broadcast_info(port);
189 }
186 190
187 if (!broadcast_count) 191 if (!broadcast_count) {
188 return 0; 192 return 0;
193 }
189 194
190 int i; 195 int i;
191 196
192 for (i = 0; i < broadcast_count; i++) 197 for (i = 0; i < broadcast_count; i++) {
193 sendpacket(net, broadcast_ip_port[i], data, length); 198 sendpacket(net, broadcast_ip_port[i], data, length);
199 }
194 200
195 return 1; 201 return 1;
196} 202}
@@ -234,8 +240,9 @@ _Bool Local_ip(IP ip)
234 IP4 ip4 = ip.ip4; 240 IP4 ip4 = ip.ip4;
235 241
236 /* Loopback. */ 242 /* Loopback. */
237 if (ip4.uint8[0] == 127) 243 if (ip4.uint8[0] == 127) {
238 return 1; 244 return 1;
245 }
239 } else { 246 } else {
240 /* embedded IPv4-in-IPv6 */ 247 /* embedded IPv4-in-IPv6 */
241 if (IPV6_IPV4_IN_V6(ip.ip6)) { 248 if (IPV6_IPV4_IN_V6(ip.ip6)) {
@@ -246,8 +253,9 @@ _Bool Local_ip(IP ip)
246 } 253 }
247 254
248 /* localhost in IPv6 (::1) */ 255 /* localhost in IPv6 (::1) */
249 if (ip.ip6.uint64[0] == 0 && ip.ip6.uint32[2] == 0 && ip.ip6.uint32[3] == htonl(1)) 256 if (ip.ip6.uint64[0] == 0 && ip.ip6.uint32[2] == 0 && ip.ip6.uint32[3] == htonl(1)) {
250 return 1; 257 return 1;
258 }
251 } 259 }
252 260
253 return 0; 261 return 0;
@@ -258,41 +266,48 @@ _Bool Local_ip(IP ip)
258 */ 266 */
259int LAN_ip(IP ip) 267int LAN_ip(IP ip)
260{ 268{
261 if (Local_ip(ip)) 269 if (Local_ip(ip)) {
262 return 0; 270 return 0;
271 }
263 272
264 if (ip.family == AF_INET) { 273 if (ip.family == AF_INET) {
265 IP4 ip4 = ip.ip4; 274 IP4 ip4 = ip.ip4;
266 275
267 /* 10.0.0.0 to 10.255.255.255 range. */ 276 /* 10.0.0.0 to 10.255.255.255 range. */
268 if (ip4.uint8[0] == 10) 277 if (ip4.uint8[0] == 10) {
269 return 0; 278 return 0;
279 }
270 280
271 /* 172.16.0.0 to 172.31.255.255 range. */ 281 /* 172.16.0.0 to 172.31.255.255 range. */
272 if (ip4.uint8[0] == 172 && ip4.uint8[1] >= 16 && ip4.uint8[1] <= 31) 282 if (ip4.uint8[0] == 172 && ip4.uint8[1] >= 16 && ip4.uint8[1] <= 31) {
273 return 0; 283 return 0;
284 }
274 285
275 /* 192.168.0.0 to 192.168.255.255 range. */ 286 /* 192.168.0.0 to 192.168.255.255 range. */
276 if (ip4.uint8[0] == 192 && ip4.uint8[1] == 168) 287 if (ip4.uint8[0] == 192 && ip4.uint8[1] == 168) {
277 return 0; 288 return 0;
289 }
278 290
279 /* 169.254.1.0 to 169.254.254.255 range. */ 291 /* 169.254.1.0 to 169.254.254.255 range. */
280 if (ip4.uint8[0] == 169 && ip4.uint8[1] == 254 && ip4.uint8[2] != 0 292 if (ip4.uint8[0] == 169 && ip4.uint8[1] == 254 && ip4.uint8[2] != 0
281 && ip4.uint8[2] != 255) 293 && ip4.uint8[2] != 255) {
282 return 0; 294 return 0;
295 }
283 296
284 /* RFC 6598: 100.64.0.0 to 100.127.255.255 (100.64.0.0/10) 297 /* RFC 6598: 100.64.0.0 to 100.127.255.255 (100.64.0.0/10)
285 * (shared address space to stack another layer of NAT) */ 298 * (shared address space to stack another layer of NAT) */
286 if ((ip4.uint8[0] == 100) && ((ip4.uint8[1] & 0xC0) == 0x40)) 299 if ((ip4.uint8[0] == 100) && ((ip4.uint8[1] & 0xC0) == 0x40)) {
287 return 0; 300 return 0;
301 }
288 302
289 } else if (ip.family == AF_INET6) { 303 } else if (ip.family == AF_INET6) {
290 304
291 /* autogenerated for each interface: FE80::* (up to FEBF::*) 305 /* autogenerated for each interface: FE80::* (up to FEBF::*)
292 FF02::1 is - according to RFC 4291 - multicast all-nodes link-local */ 306 FF02::1 is - according to RFC 4291 - multicast all-nodes link-local */
293 if (((ip.ip6.uint8[0] == 0xFF) && (ip.ip6.uint8[1] < 3) && (ip.ip6.uint8[15] == 1)) || 307 if (((ip.ip6.uint8[0] == 0xFF) && (ip.ip6.uint8[1] < 3) && (ip.ip6.uint8[15] == 1)) ||
294 ((ip.ip6.uint8[0] == 0xFE) && ((ip.ip6.uint8[1] & 0xC0) == 0x80))) 308 ((ip.ip6.uint8[0] == 0xFE) && ((ip.ip6.uint8[1] & 0xC0) == 0x80))) {
295 return 0; 309 return 0;
310 }
296 311
297 /* embedded IPv4-in-IPv6 */ 312 /* embedded IPv4-in-IPv6 */
298 if (IPV6_IPV4_IN_V6(ip.ip6)) { 313 if (IPV6_IPV4_IN_V6(ip.ip6)) {
@@ -310,11 +325,13 @@ static int handle_LANdiscovery(void *object, IP_Port source, const uint8_t *pack
310{ 325{
311 DHT *dht = object; 326 DHT *dht = object;
312 327
313 if (LAN_ip(source.ip) == -1) 328 if (LAN_ip(source.ip) == -1) {
314 return 1; 329 return 1;
330 }
315 331
316 if (length != crypto_box_PUBLICKEYBYTES + 1) 332 if (length != crypto_box_PUBLICKEYBYTES + 1) {
317 return 1; 333 return 1;
334 }
318 335
319 DHT_bootstrap(dht, source, packet + 1); 336 DHT_bootstrap(dht, source, packet + 1);
320 return 0; 337 return 0;
@@ -337,17 +354,21 @@ int send_LANdiscovery(uint16_t port, DHT *dht)
337 if (dht->net->family == AF_INET6) { 354 if (dht->net->family == AF_INET6) {
338 ip_port.ip = broadcast_ip(AF_INET6, AF_INET6); 355 ip_port.ip = broadcast_ip(AF_INET6, AF_INET6);
339 356
340 if (ip_isset(&ip_port.ip)) 357 if (ip_isset(&ip_port.ip)) {
341 if (sendpacket(dht->net, ip_port, data, 1 + crypto_box_PUBLICKEYBYTES) > 0) 358 if (sendpacket(dht->net, ip_port, data, 1 + crypto_box_PUBLICKEYBYTES) > 0) {
342 res = 1; 359 res = 1;
360 }
361 }
343 } 362 }
344 363
345 /* IPv4 broadcast (has to be IPv4-in-IPv6 mapping if socket is AF_INET6 */ 364 /* IPv4 broadcast (has to be IPv4-in-IPv6 mapping if socket is AF_INET6 */
346 ip_port.ip = broadcast_ip(dht->net->family, AF_INET); 365 ip_port.ip = broadcast_ip(dht->net->family, AF_INET);
347 366
348 if (ip_isset(&ip_port.ip)) 367 if (ip_isset(&ip_port.ip)) {
349 if (sendpacket(dht->net, ip_port, data, 1 + crypto_box_PUBLICKEYBYTES)) 368 if (sendpacket(dht->net, ip_port, data, 1 + crypto_box_PUBLICKEYBYTES)) {
350 res = 1; 369 res = 1;
370 }
371 }
351 372
352 return res; 373 return res;
353} 374}
diff --git a/toxcore/Messenger.c b/toxcore/Messenger.c
index a1e4c110..b2d7d209 100644
--- a/toxcore/Messenger.c
+++ b/toxcore/Messenger.c
@@ -66,8 +66,9 @@ int realloc_friendlist(Messenger *m, uint32_t num)
66 66
67 Friend *newfriendlist = realloc(m->friendlist, num * sizeof(Friend)); 67 Friend *newfriendlist = realloc(m->friendlist, num * sizeof(Friend));
68 68
69 if (newfriendlist == NULL) 69 if (newfriendlist == NULL) {
70 return -1; 70 return -1;
71 }
71 72
72 m->friendlist = newfriendlist; 73 m->friendlist = newfriendlist;
73 return 0; 74 return 0;
@@ -81,9 +82,11 @@ int32_t getfriend_id(const Messenger *m, const uint8_t *real_pk)
81 uint32_t i; 82 uint32_t i;
82 83
83 for (i = 0; i < m->numfriends; ++i) { 84 for (i = 0; i < m->numfriends; ++i) {
84 if (m->friendlist[i].status > 0) 85 if (m->friendlist[i].status > 0) {
85 if (id_equal(real_pk, m->friendlist[i].real_pk)) 86 if (id_equal(real_pk, m->friendlist[i].real_pk)) {
86 return i; 87 return i;
88 }
89 }
87 } 90 }
88 91
89 return -1; 92 return -1;
@@ -97,8 +100,9 @@ int32_t getfriend_id(const Messenger *m, const uint8_t *real_pk)
97 */ 100 */
98int get_real_pk(const Messenger *m, int32_t friendnumber, uint8_t *real_pk) 101int get_real_pk(const Messenger *m, int32_t friendnumber, uint8_t *real_pk)
99{ 102{
100 if (friend_not_valid(m, friendnumber)) 103 if (friend_not_valid(m, friendnumber)) {
101 return -1; 104 return -1;
105 }
102 106
103 memcpy(real_pk, m->friendlist[friendnumber].real_pk, crypto_box_PUBLICKEYBYTES); 107 memcpy(real_pk, m->friendlist[friendnumber].real_pk, crypto_box_PUBLICKEYBYTES);
104 return 0; 108 return 0;
@@ -109,8 +113,9 @@ int get_real_pk(const Messenger *m, int32_t friendnumber, uint8_t *real_pk)
109 */ 113 */
110int getfriendcon_id(const Messenger *m, int32_t friendnumber) 114int getfriendcon_id(const Messenger *m, int32_t friendnumber)
111{ 115{
112 if (friend_not_valid(m, friendnumber)) 116 if (friend_not_valid(m, friendnumber)) {
113 return -1; 117 return -1;
118 }
114 119
115 return m->friendlist[friendnumber].friendcon_id; 120 return m->friendlist[friendnumber].friendcon_id;
116} 121}
@@ -124,8 +129,9 @@ static uint16_t address_checksum(const uint8_t *address, uint32_t len)
124 uint16_t check; 129 uint16_t check;
125 uint32_t i; 130 uint32_t i;
126 131
127 for (i = 0; i < len; ++i) 132 for (i = 0; i < len; ++i) {
128 checksum[i % 2] ^= address[i]; 133 checksum[i % 2] ^= address[i];
134 }
129 135
130 memcpy(&check, checksum, sizeof(check)); 136 memcpy(&check, checksum, sizeof(check));
131 return check; 137 return check;
@@ -146,8 +152,9 @@ void getaddress(const Messenger *m, uint8_t *address)
146 152
147static int send_online_packet(Messenger *m, int32_t friendnumber) 153static int send_online_packet(Messenger *m, int32_t friendnumber)
148{ 154{
149 if (friend_not_valid(m, friendnumber)) 155 if (friend_not_valid(m, friendnumber)) {
150 return 0; 156 return 0;
157 }
151 158
152 uint8_t packet = PACKET_ID_ONLINE; 159 uint8_t packet = PACKET_ID_ONLINE;
153 return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 160 return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
@@ -168,15 +175,17 @@ static int handle_custom_lossy_packet(void *object, int friend_num, const uint8_
168static int32_t init_new_friend(Messenger *m, const uint8_t *real_pk, uint8_t status) 175static int32_t init_new_friend(Messenger *m, const uint8_t *real_pk, uint8_t status)
169{ 176{
170 /* Resize the friend list if necessary. */ 177 /* Resize the friend list if necessary. */
171 if (realloc_friendlist(m, m->numfriends + 1) != 0) 178 if (realloc_friendlist(m, m->numfriends + 1) != 0) {
172 return FAERR_NOMEM; 179 return FAERR_NOMEM;
180 }
173 181
174 memset(&(m->friendlist[m->numfriends]), 0, sizeof(Friend)); 182 memset(&(m->friendlist[m->numfriends]), 0, sizeof(Friend));
175 183
176 int friendcon_id = new_friend_connection(m->fr_c, real_pk); 184 int friendcon_id = new_friend_connection(m->fr_c, real_pk);
177 185
178 if (friendcon_id == -1) 186 if (friendcon_id == -1) {
179 return FAERR_NOMEM; 187 return FAERR_NOMEM;
188 }
180 189
181 uint32_t i; 190 uint32_t i;
182 191
@@ -193,8 +202,9 @@ static int32_t init_new_friend(Messenger *m, const uint8_t *real_pk, uint8_t sta
193 friend_connection_callbacks(m->fr_c, friendcon_id, MESSENGER_CALLBACK_INDEX, &handle_status, &handle_packet, 202 friend_connection_callbacks(m->fr_c, friendcon_id, MESSENGER_CALLBACK_INDEX, &handle_status, &handle_packet,
194 &handle_custom_lossy_packet, m, i); 203 &handle_custom_lossy_packet, m, i);
195 204
196 if (m->numfriends == i) 205 if (m->numfriends == i) {
197 ++m->numfriends; 206 ++m->numfriends;
207 }
198 208
199 if (friend_con_connected(m->fr_c, friendcon_id) == FRIENDCONN_STATUS_CONNECTED) { 209 if (friend_con_connected(m->fr_c, friendcon_id) == FRIENDCONN_STATUS_CONNECTED) {
200 send_online_packet(m, i); 210 send_online_packet(m, i);
@@ -225,38 +235,45 @@ static int32_t init_new_friend(Messenger *m, const uint8_t *real_pk, uint8_t sta
225 */ 235 */
226int32_t m_addfriend(Messenger *m, const uint8_t *address, const uint8_t *data, uint16_t length) 236int32_t m_addfriend(Messenger *m, const uint8_t *address, const uint8_t *data, uint16_t length)
227{ 237{
228 if (length > MAX_FRIEND_REQUEST_DATA_SIZE) 238 if (length > MAX_FRIEND_REQUEST_DATA_SIZE) {
229 return FAERR_TOOLONG; 239 return FAERR_TOOLONG;
240 }
230 241
231 uint8_t real_pk[crypto_box_PUBLICKEYBYTES]; 242 uint8_t real_pk[crypto_box_PUBLICKEYBYTES];
232 id_copy(real_pk, address); 243 id_copy(real_pk, address);
233 244
234 if (!public_key_valid(real_pk)) 245 if (!public_key_valid(real_pk)) {
235 return FAERR_BADCHECKSUM; 246 return FAERR_BADCHECKSUM;
247 }
236 248
237 uint16_t check, checksum = address_checksum(address, FRIEND_ADDRESS_SIZE - sizeof(checksum)); 249 uint16_t check, checksum = address_checksum(address, FRIEND_ADDRESS_SIZE - sizeof(checksum));
238 memcpy(&check, address + crypto_box_PUBLICKEYBYTES + sizeof(uint32_t), sizeof(check)); 250 memcpy(&check, address + crypto_box_PUBLICKEYBYTES + sizeof(uint32_t), sizeof(check));
239 251
240 if (check != checksum) 252 if (check != checksum) {
241 return FAERR_BADCHECKSUM; 253 return FAERR_BADCHECKSUM;
254 }
242 255
243 if (length < 1) 256 if (length < 1) {
244 return FAERR_NOMESSAGE; 257 return FAERR_NOMESSAGE;
258 }
245 259
246 if (id_equal(real_pk, m->net_crypto->self_public_key)) 260 if (id_equal(real_pk, m->net_crypto->self_public_key)) {
247 return FAERR_OWNKEY; 261 return FAERR_OWNKEY;
262 }
248 263
249 int32_t friend_id = getfriend_id(m, real_pk); 264 int32_t friend_id = getfriend_id(m, real_pk);
250 265
251 if (friend_id != -1) { 266 if (friend_id != -1) {
252 if (m->friendlist[friend_id].status >= FRIEND_CONFIRMED) 267 if (m->friendlist[friend_id].status >= FRIEND_CONFIRMED) {
253 return FAERR_ALREADYSENT; 268 return FAERR_ALREADYSENT;
269 }
254 270
255 uint32_t nospam; 271 uint32_t nospam;
256 memcpy(&nospam, address + crypto_box_PUBLICKEYBYTES, sizeof(nospam)); 272 memcpy(&nospam, address + crypto_box_PUBLICKEYBYTES, sizeof(nospam));
257 273
258 if (m->friendlist[friend_id].friendrequest_nospam == nospam) 274 if (m->friendlist[friend_id].friendrequest_nospam == nospam) {
259 return FAERR_ALREADYSENT; 275 return FAERR_ALREADYSENT;
276 }
260 277
261 m->friendlist[friend_id].friendrequest_nospam = nospam; 278 m->friendlist[friend_id].friendrequest_nospam = nospam;
262 return FAERR_SETNEWNOSPAM; 279 return FAERR_SETNEWNOSPAM;
@@ -278,22 +295,26 @@ int32_t m_addfriend(Messenger *m, const uint8_t *address, const uint8_t *data, u
278 295
279int32_t m_addfriend_norequest(Messenger *m, const uint8_t *real_pk) 296int32_t m_addfriend_norequest(Messenger *m, const uint8_t *real_pk)
280{ 297{
281 if (getfriend_id(m, real_pk) != -1) 298 if (getfriend_id(m, real_pk) != -1) {
282 return FAERR_ALREADYSENT; 299 return FAERR_ALREADYSENT;
300 }
283 301
284 if (!public_key_valid(real_pk)) 302 if (!public_key_valid(real_pk)) {
285 return FAERR_BADCHECKSUM; 303 return FAERR_BADCHECKSUM;
304 }
286 305
287 if (id_equal(real_pk, m->net_crypto->self_public_key)) 306 if (id_equal(real_pk, m->net_crypto->self_public_key)) {
288 return FAERR_OWNKEY; 307 return FAERR_OWNKEY;
308 }
289 309
290 return init_new_friend(m, real_pk, FRIEND_CONFIRMED); 310 return init_new_friend(m, real_pk, FRIEND_CONFIRMED);
291} 311}
292 312
293static int clear_receipts(Messenger *m, int32_t friendnumber) 313static int clear_receipts(Messenger *m, int32_t friendnumber)
294{ 314{
295 if (friend_not_valid(m, friendnumber)) 315 if (friend_not_valid(m, friendnumber)) {
296 return -1; 316 return -1;
317 }
297 318
298 struct Receipts *receipts = m->friendlist[friendnumber].receipts_start; 319 struct Receipts *receipts = m->friendlist[friendnumber].receipts_start;
299 320
@@ -310,13 +331,15 @@ static int clear_receipts(Messenger *m, int32_t friendnumber)
310 331
311static int add_receipt(Messenger *m, int32_t friendnumber, uint32_t packet_num, uint32_t msg_id) 332static int add_receipt(Messenger *m, int32_t friendnumber, uint32_t packet_num, uint32_t msg_id)
312{ 333{
313 if (friend_not_valid(m, friendnumber)) 334 if (friend_not_valid(m, friendnumber)) {
314 return -1; 335 return -1;
336 }
315 337
316 struct Receipts *new = calloc(1, sizeof(struct Receipts)); 338 struct Receipts *new = calloc(1, sizeof(struct Receipts));
317 339
318 if (!new) 340 if (!new) {
319 return -1; 341 return -1;
342 }
320 343
321 new->packet_num = packet_num; 344 new->packet_num = packet_num;
322 new->msg_id = msg_id; 345 new->msg_id = msg_id;
@@ -337,8 +360,9 @@ static int add_receipt(Messenger *m, int32_t friendnumber, uint32_t packet_num,
337 */ 360 */
338static int friend_received_packet(const Messenger *m, int32_t friendnumber, uint32_t number) 361static int friend_received_packet(const Messenger *m, int32_t friendnumber, uint32_t number)
339{ 362{
340 if (friend_not_valid(m, friendnumber)) 363 if (friend_not_valid(m, friendnumber)) {
341 return -1; 364 return -1;
365 }
342 366
343 return cryptpacket_received(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 367 return cryptpacket_received(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
344 m->friendlist[friendnumber].friendcon_id), number); 368 m->friendlist[friendnumber].friendcon_id), number);
@@ -346,16 +370,18 @@ static int friend_received_packet(const Messenger *m, int32_t friendnumber, uint
346 370
347static int do_receipts(Messenger *m, int32_t friendnumber, void *userdata) 371static int do_receipts(Messenger *m, int32_t friendnumber, void *userdata)
348{ 372{
349 if (friend_not_valid(m, friendnumber)) 373 if (friend_not_valid(m, friendnumber)) {
350 return -1; 374 return -1;
375 }
351 376
352 struct Receipts *receipts = m->friendlist[friendnumber].receipts_start; 377 struct Receipts *receipts = m->friendlist[friendnumber].receipts_start;
353 378
354 while (receipts) { 379 while (receipts) {
355 struct Receipts *temp_r = receipts->next; 380 struct Receipts *temp_r = receipts->next;
356 381
357 if (friend_received_packet(m, friendnumber, receipts->packet_num) == -1) 382 if (friend_received_packet(m, friendnumber, receipts->packet_num) == -1) {
358 break; 383 break;
384 }
359 385
360 if (m->read_receipt) { 386 if (m->read_receipt) {
361 (*m->read_receipt)(m, friendnumber, receipts->msg_id, userdata); 387 (*m->read_receipt)(m, friendnumber, receipts->msg_id, userdata);
@@ -366,8 +392,9 @@ static int do_receipts(Messenger *m, int32_t friendnumber, void *userdata)
366 receipts = temp_r; 392 receipts = temp_r;
367 } 393 }
368 394
369 if (!m->friendlist[friendnumber].receipts_start) 395 if (!m->friendlist[friendnumber].receipts_start) {
370 m->friendlist[friendnumber].receipts_end = NULL; 396 m->friendlist[friendnumber].receipts_end = NULL;
397 }
371 398
372 return 0; 399 return 0;
373} 400}
@@ -379,11 +406,13 @@ static int do_receipts(Messenger *m, int32_t friendnumber, void *userdata)
379 */ 406 */
380int m_delfriend(Messenger *m, int32_t friendnumber) 407int m_delfriend(Messenger *m, int32_t friendnumber)
381{ 408{
382 if (friend_not_valid(m, friendnumber)) 409 if (friend_not_valid(m, friendnumber)) {
383 return -1; 410 return -1;
411 }
384 412
385 if (m->friend_connectionstatuschange_internal) 413 if (m->friend_connectionstatuschange_internal) {
386 m->friend_connectionstatuschange_internal(m, friendnumber, 0, m->friend_connectionstatuschange_internal_userdata); 414 m->friend_connectionstatuschange_internal(m, friendnumber, 0, m->friend_connectionstatuschange_internal_userdata);
415 }
387 416
388 clear_receipts(m, friendnumber); 417 clear_receipts(m, friendnumber);
389 remove_request_received(&(m->fr), m->friendlist[friendnumber].real_pk); 418 remove_request_received(&(m->fr), m->friendlist[friendnumber].real_pk);
@@ -398,22 +427,25 @@ int m_delfriend(Messenger *m, int32_t friendnumber)
398 uint32_t i; 427 uint32_t i;
399 428
400 for (i = m->numfriends; i != 0; --i) { 429 for (i = m->numfriends; i != 0; --i) {
401 if (m->friendlist[i - 1].status != NOFRIEND) 430 if (m->friendlist[i - 1].status != NOFRIEND) {
402 break; 431 break;
432 }
403 } 433 }
404 434
405 m->numfriends = i; 435 m->numfriends = i;
406 436
407 if (realloc_friendlist(m, m->numfriends) != 0) 437 if (realloc_friendlist(m, m->numfriends) != 0) {
408 return FAERR_NOMEM; 438 return FAERR_NOMEM;
439 }
409 440
410 return 0; 441 return 0;
411} 442}
412 443
413int m_get_friend_connectionstatus(const Messenger *m, int32_t friendnumber) 444int m_get_friend_connectionstatus(const Messenger *m, int32_t friendnumber)
414{ 445{
415 if (friend_not_valid(m, friendnumber)) 446 if (friend_not_valid(m, friendnumber)) {
416 return -1; 447 return -1;
448 }
417 449
418 if (m->friendlist[friendnumber].status == FRIEND_ONLINE) { 450 if (m->friendlist[friendnumber].status == FRIEND_ONLINE) {
419 _Bool direct_connected = 0; 451 _Bool direct_connected = 0;
@@ -437,8 +469,9 @@ int m_get_friend_connectionstatus(const Messenger *m, int32_t friendnumber)
437 469
438int m_friend_exists(const Messenger *m, int32_t friendnumber) 470int m_friend_exists(const Messenger *m, int32_t friendnumber)
439{ 471{
440 if (friend_not_valid(m, friendnumber)) 472 if (friend_not_valid(m, friendnumber)) {
441 return 0; 473 return 0;
474 }
442 475
443 return 1; 476 return 1;
444} 477}
@@ -455,36 +488,43 @@ int m_friend_exists(const Messenger *m, int32_t friendnumber)
455int m_send_message_generic(Messenger *m, int32_t friendnumber, uint8_t type, const uint8_t *message, uint32_t length, 488int m_send_message_generic(Messenger *m, int32_t friendnumber, uint8_t type, const uint8_t *message, uint32_t length,
456 uint32_t *message_id) 489 uint32_t *message_id)
457{ 490{
458 if (type > MESSAGE_ACTION) 491 if (type > MESSAGE_ACTION) {
459 return -5; 492 return -5;
493 }
460 494
461 if (friend_not_valid(m, friendnumber)) 495 if (friend_not_valid(m, friendnumber)) {
462 return -1; 496 return -1;
497 }
463 498
464 if (length >= MAX_CRYPTO_DATA_SIZE) 499 if (length >= MAX_CRYPTO_DATA_SIZE) {
465 return -2; 500 return -2;
501 }
466 502
467 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 503 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
468 return -3; 504 return -3;
505 }
469 506
470 uint8_t packet[length + 1]; 507 uint8_t packet[length + 1];
471 packet[0] = type + PACKET_ID_MESSAGE; 508 packet[0] = type + PACKET_ID_MESSAGE;
472 509
473 if (length != 0) 510 if (length != 0) {
474 memcpy(packet + 1, message, length); 511 memcpy(packet + 1, message, length);
512 }
475 513
476 int64_t packet_num = write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 514 int64_t packet_num = write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
477 m->friendlist[friendnumber].friendcon_id), packet, length + 1, 0); 515 m->friendlist[friendnumber].friendcon_id), packet, length + 1, 0);
478 516
479 if (packet_num == -1) 517 if (packet_num == -1) {
480 return -4; 518 return -4;
519 }
481 520
482 uint32_t msg_id = ++m->friendlist[friendnumber].message_id; 521 uint32_t msg_id = ++m->friendlist[friendnumber].message_id;
483 522
484 add_receipt(m, friendnumber, packet_num, msg_id); 523 add_receipt(m, friendnumber, packet_num, msg_id);
485 524
486 if (message_id) 525 if (message_id) {
487 *message_id = msg_id; 526 *message_id = msg_id;
527 }
488 528
489 return 0; 529 return 0;
490} 530}
@@ -494,8 +534,9 @@ int m_send_message_generic(Messenger *m, int32_t friendnumber, uint8_t type, con
494 */ 534 */
495static int m_sendname(const Messenger *m, int32_t friendnumber, const uint8_t *name, uint16_t length) 535static int m_sendname(const Messenger *m, int32_t friendnumber, const uint8_t *name, uint16_t length)
496{ 536{
497 if (length > MAX_NAME_LENGTH) 537 if (length > MAX_NAME_LENGTH) {
498 return 0; 538 return 0;
539 }
499 540
500 return write_cryptpacket_id(m, friendnumber, PACKET_ID_NICKNAME, name, length, 0); 541 return write_cryptpacket_id(m, friendnumber, PACKET_ID_NICKNAME, name, length, 0);
501} 542}
@@ -507,11 +548,13 @@ static int m_sendname(const Messenger *m, int32_t friendnumber, const uint8_t *n
507 */ 548 */
508int setfriendname(Messenger *m, int32_t friendnumber, const uint8_t *name, uint16_t length) 549int setfriendname(Messenger *m, int32_t friendnumber, const uint8_t *name, uint16_t length)
509{ 550{
510 if (friend_not_valid(m, friendnumber)) 551 if (friend_not_valid(m, friendnumber)) {
511 return -1; 552 return -1;
553 }
512 554
513 if (length > MAX_NAME_LENGTH || length == 0) 555 if (length > MAX_NAME_LENGTH || length == 0) {
514 return -1; 556 return -1;
557 }
515 558
516 m->friendlist[friendnumber].name_length = length; 559 m->friendlist[friendnumber].name_length = length;
517 memcpy(m->friendlist[friendnumber].name, name, length); 560 memcpy(m->friendlist[friendnumber].name, name, length);
@@ -528,20 +571,24 @@ int setfriendname(Messenger *m, int32_t friendnumber, const uint8_t *name, uint1
528 */ 571 */
529int setname(Messenger *m, const uint8_t *name, uint16_t length) 572int setname(Messenger *m, const uint8_t *name, uint16_t length)
530{ 573{
531 if (length > MAX_NAME_LENGTH) 574 if (length > MAX_NAME_LENGTH) {
532 return -1; 575 return -1;
576 }
533 577
534 if (m->name_length == length && (length == 0 || memcmp(name, m->name, length) == 0)) 578 if (m->name_length == length && (length == 0 || memcmp(name, m->name, length) == 0)) {
535 return 0; 579 return 0;
580 }
536 581
537 if (length) 582 if (length) {
538 memcpy(m->name, name, length); 583 memcpy(m->name, name, length);
584 }
539 585
540 m->name_length = length; 586 m->name_length = length;
541 uint32_t i; 587 uint32_t i;
542 588
543 for (i = 0; i < m->numfriends; ++i) 589 for (i = 0; i < m->numfriends; ++i) {
544 m->friendlist[i].name_sent = 0; 590 m->friendlist[i].name_sent = 0;
591 }
545 592
546 return 0; 593 return 0;
547} 594}
@@ -570,8 +617,9 @@ uint16_t getself_name(const Messenger *m, uint8_t *name)
570 */ 617 */
571int getname(const Messenger *m, int32_t friendnumber, uint8_t *name) 618int getname(const Messenger *m, int32_t friendnumber, uint8_t *name)
572{ 619{
573 if (friend_not_valid(m, friendnumber)) 620 if (friend_not_valid(m, friendnumber)) {
574 return -1; 621 return -1;
622 }
575 623
576 memcpy(name, m->friendlist[friendnumber].name, m->friendlist[friendnumber].name_length); 624 memcpy(name, m->friendlist[friendnumber].name, m->friendlist[friendnumber].name_length);
577 return m->friendlist[friendnumber].name_length; 625 return m->friendlist[friendnumber].name_length;
@@ -579,8 +627,9 @@ int getname(const Messenger *m, int32_t friendnumber, uint8_t *name)
579 627
580int m_get_name_size(const Messenger *m, int32_t friendnumber) 628int m_get_name_size(const Messenger *m, int32_t friendnumber)
581{ 629{
582 if (friend_not_valid(m, friendnumber)) 630 if (friend_not_valid(m, friendnumber)) {
583 return -1; 631 return -1;
632 }
584 633
585 return m->friendlist[friendnumber].name_length; 634 return m->friendlist[friendnumber].name_length;
586} 635}
@@ -592,38 +641,45 @@ int m_get_self_name_size(const Messenger *m)
592 641
593int m_set_statusmessage(Messenger *m, const uint8_t *status, uint16_t length) 642int m_set_statusmessage(Messenger *m, const uint8_t *status, uint16_t length)
594{ 643{
595 if (length > MAX_STATUSMESSAGE_LENGTH) 644 if (length > MAX_STATUSMESSAGE_LENGTH) {
596 return -1; 645 return -1;
646 }
597 647
598 if (m->statusmessage_length == length && (length == 0 || memcmp(m->statusmessage, status, length) == 0)) 648 if (m->statusmessage_length == length && (length == 0 || memcmp(m->statusmessage, status, length) == 0)) {
599 return 0; 649 return 0;
650 }
600 651
601 if (length) 652 if (length) {
602 memcpy(m->statusmessage, status, length); 653 memcpy(m->statusmessage, status, length);
654 }
603 655
604 m->statusmessage_length = length; 656 m->statusmessage_length = length;
605 657
606 uint32_t i; 658 uint32_t i;
607 659
608 for (i = 0; i < m->numfriends; ++i) 660 for (i = 0; i < m->numfriends; ++i) {
609 m->friendlist[i].statusmessage_sent = 0; 661 m->friendlist[i].statusmessage_sent = 0;
662 }
610 663
611 return 0; 664 return 0;
612} 665}
613 666
614int m_set_userstatus(Messenger *m, uint8_t status) 667int m_set_userstatus(Messenger *m, uint8_t status)
615{ 668{
616 if (status >= USERSTATUS_INVALID) 669 if (status >= USERSTATUS_INVALID) {
617 return -1; 670 return -1;
671 }
618 672
619 if (m->userstatus == status) 673 if (m->userstatus == status) {
620 return 0; 674 return 0;
675 }
621 676
622 m->userstatus = status; 677 m->userstatus = status;
623 uint32_t i; 678 uint32_t i;
624 679
625 for (i = 0; i < m->numfriends; ++i) 680 for (i = 0; i < m->numfriends; ++i) {
626 m->friendlist[i].userstatus_sent = 0; 681 m->friendlist[i].userstatus_sent = 0;
682 }
627 683
628 return 0; 684 return 0;
629} 685}
@@ -633,8 +689,9 @@ int m_set_userstatus(Messenger *m, uint8_t status)
633 */ 689 */
634int m_get_statusmessage_size(const Messenger *m, int32_t friendnumber) 690int m_get_statusmessage_size(const Messenger *m, int32_t friendnumber)
635{ 691{
636 if (friend_not_valid(m, friendnumber)) 692 if (friend_not_valid(m, friendnumber)) {
637 return -1; 693 return -1;
694 }
638 695
639 return m->friendlist[friendnumber].statusmessage_length; 696 return m->friendlist[friendnumber].statusmessage_length;
640} 697}
@@ -644,8 +701,9 @@ int m_get_statusmessage_size(const Messenger *m, int32_t friendnumber)
644 */ 701 */
645int m_copy_statusmessage(const Messenger *m, int32_t friendnumber, uint8_t *buf, uint32_t maxlen) 702int m_copy_statusmessage(const Messenger *m, int32_t friendnumber, uint8_t *buf, uint32_t maxlen)
646{ 703{
647 if (friend_not_valid(m, friendnumber)) 704 if (friend_not_valid(m, friendnumber)) {
648 return -1; 705 return -1;
706 }
649 707
650 int msglen = MIN(maxlen, m->friendlist[friendnumber].statusmessage_length); 708 int msglen = MIN(maxlen, m->friendlist[friendnumber].statusmessage_length);
651 709
@@ -670,8 +728,9 @@ int m_copy_self_statusmessage(const Messenger *m, uint8_t *buf)
670 728
671uint8_t m_get_userstatus(const Messenger *m, int32_t friendnumber) 729uint8_t m_get_userstatus(const Messenger *m, int32_t friendnumber)
672{ 730{
673 if (friend_not_valid(m, friendnumber)) 731 if (friend_not_valid(m, friendnumber)) {
674 return USERSTATUS_INVALID; 732 return USERSTATUS_INVALID;
733 }
675 734
676 uint8_t status = m->friendlist[friendnumber].userstatus; 735 uint8_t status = m->friendlist[friendnumber].userstatus;
677 736
@@ -689,8 +748,9 @@ uint8_t m_get_self_userstatus(const Messenger *m)
689 748
690uint64_t m_get_last_online(const Messenger *m, int32_t friendnumber) 749uint64_t m_get_last_online(const Messenger *m, int32_t friendnumber)
691{ 750{
692 if (friend_not_valid(m, friendnumber)) 751 if (friend_not_valid(m, friendnumber)) {
693 return UINT64_MAX; 752 return UINT64_MAX;
753 }
694 754
695 return m->friendlist[friendnumber].last_seen_time; 755 return m->friendlist[friendnumber].last_seen_time;
696} 756}
@@ -698,14 +758,17 @@ uint64_t m_get_last_online(const Messenger *m, int32_t friendnumber)
698int m_set_usertyping(Messenger *m, int32_t friendnumber, uint8_t is_typing) 758int m_set_usertyping(Messenger *m, int32_t friendnumber, uint8_t is_typing)
699 759
700{ 760{
701 if (is_typing != 0 && is_typing != 1) 761 if (is_typing != 0 && is_typing != 1) {
702 return -1; 762 return -1;
763 }
703 764
704 if (friend_not_valid(m, friendnumber)) 765 if (friend_not_valid(m, friendnumber)) {
705 return -1; 766 return -1;
767 }
706 768
707 if (m->friendlist[friendnumber].user_istyping == is_typing) 769 if (m->friendlist[friendnumber].user_istyping == is_typing) {
708 return 0; 770 return 0;
771 }
709 772
710 m->friendlist[friendnumber].user_istyping = is_typing; 773 m->friendlist[friendnumber].user_istyping = is_typing;
711 m->friendlist[friendnumber].user_istyping_sent = 0; 774 m->friendlist[friendnumber].user_istyping_sent = 0;
@@ -715,8 +778,9 @@ int m_set_usertyping(Messenger *m, int32_t friendnumber, uint8_t is_typing)
715 778
716int m_get_istyping(const Messenger *m, int32_t friendnumber) 779int m_get_istyping(const Messenger *m, int32_t friendnumber)
717{ 780{
718 if (friend_not_valid(m, friendnumber)) 781 if (friend_not_valid(m, friendnumber)) {
719 return -1; 782 return -1;
783 }
720 784
721 return m->friendlist[friendnumber].is_typing; 785 return m->friendlist[friendnumber].is_typing;
722} 786}
@@ -739,14 +803,17 @@ static int send_user_istyping(const Messenger *m, int32_t friendnumber, uint8_t
739 803
740static int set_friend_statusmessage(const Messenger *m, int32_t friendnumber, const uint8_t *status, uint16_t length) 804static int set_friend_statusmessage(const Messenger *m, int32_t friendnumber, const uint8_t *status, uint16_t length)
741{ 805{
742 if (friend_not_valid(m, friendnumber)) 806 if (friend_not_valid(m, friendnumber)) {
743 return -1; 807 return -1;
808 }
744 809
745 if (length > MAX_STATUSMESSAGE_LENGTH) 810 if (length > MAX_STATUSMESSAGE_LENGTH) {
746 return -1; 811 return -1;
812 }
747 813
748 if (length) 814 if (length) {
749 memcpy(m->friendlist[friendnumber].statusmessage, status, length); 815 memcpy(m->friendlist[friendnumber].statusmessage, status, length);
816 }
750 817
751 m->friendlist[friendnumber].statusmessage_length = length; 818 m->friendlist[friendnumber].statusmessage_length = length;
752 return 0; 819 return 0;
@@ -832,8 +899,9 @@ static void check_friend_tcp_udp(Messenger *m, int32_t friendnumber)
832 899
833 int ret = m_get_friend_connectionstatus(m, friendnumber); 900 int ret = m_get_friend_connectionstatus(m, friendnumber);
834 901
835 if (ret == -1) 902 if (ret == -1) {
836 return; 903 return;
904 }
837 905
838 if (ret == CONNECTION_UNKNOWN) { 906 if (ret == CONNECTION_UNKNOWN) {
839 if (last_connection_udp_tcp == CONNECTION_UDP) { 907 if (last_connection_udp_tcp == CONNECTION_UDP) {
@@ -844,8 +912,9 @@ static void check_friend_tcp_udp(Messenger *m, int32_t friendnumber)
844 } 912 }
845 913
846 if (last_connection_udp_tcp != ret) { 914 if (last_connection_udp_tcp != ret) {
847 if (m->friend_connectionstatuschange) 915 if (m->friend_connectionstatuschange) {
848 m->friend_connectionstatuschange(m, friendnumber, ret, m->friend_connectionstatuschange_userdata); 916 m->friend_connectionstatuschange(m, friendnumber, ret, m->friend_connectionstatuschange_userdata);
917 }
849 } 918 }
850 919
851 m->friendlist[friendnumber].last_connection_udp_tcp = ret; 920 m->friendlist[friendnumber].last_connection_udp_tcp = ret;
@@ -854,8 +923,9 @@ static void check_friend_tcp_udp(Messenger *m, int32_t friendnumber)
854static void break_files(const Messenger *m, int32_t friendnumber); 923static void break_files(const Messenger *m, int32_t friendnumber);
855static void check_friend_connectionstatus(Messenger *m, int32_t friendnumber, uint8_t status) 924static void check_friend_connectionstatus(Messenger *m, int32_t friendnumber, uint8_t status)
856{ 925{
857 if (status == NOFRIEND) 926 if (status == NOFRIEND) {
858 return; 927 return;
928 }
859 929
860 const uint8_t was_online = m->friendlist[friendnumber].status == FRIEND_ONLINE; 930 const uint8_t was_online = m->friendlist[friendnumber].status == FRIEND_ONLINE;
861 const uint8_t is_online = status == FRIEND_ONLINE; 931 const uint8_t is_online = status == FRIEND_ONLINE;
@@ -875,9 +945,10 @@ static void check_friend_connectionstatus(Messenger *m, int32_t friendnumber, ui
875 945
876 check_friend_tcp_udp(m, friendnumber); 946 check_friend_tcp_udp(m, friendnumber);
877 947
878 if (m->friend_connectionstatuschange_internal) 948 if (m->friend_connectionstatuschange_internal) {
879 m->friend_connectionstatuschange_internal(m, friendnumber, is_online, 949 m->friend_connectionstatuschange_internal(m, friendnumber, is_online,
880 m->friend_connectionstatuschange_internal_userdata); 950 m->friend_connectionstatuschange_internal_userdata);
951 }
881 } 952 }
882} 953}
883 954
@@ -890,17 +961,20 @@ void set_friend_status(Messenger *m, int32_t friendnumber, uint8_t status)
890static int write_cryptpacket_id(const Messenger *m, int32_t friendnumber, uint8_t packet_id, const uint8_t *data, 961static int write_cryptpacket_id(const Messenger *m, int32_t friendnumber, uint8_t packet_id, const uint8_t *data,
891 uint32_t length, uint8_t congestion_control) 962 uint32_t length, uint8_t congestion_control)
892{ 963{
893 if (friend_not_valid(m, friendnumber)) 964 if (friend_not_valid(m, friendnumber)) {
894 return 0; 965 return 0;
966 }
895 967
896 if (length >= MAX_CRYPTO_DATA_SIZE || m->friendlist[friendnumber].status != FRIEND_ONLINE) 968 if (length >= MAX_CRYPTO_DATA_SIZE || m->friendlist[friendnumber].status != FRIEND_ONLINE) {
897 return 0; 969 return 0;
970 }
898 971
899 uint8_t packet[length + 1]; 972 uint8_t packet[length + 1];
900 packet[0] = packet_id; 973 packet[0] = packet_id;
901 974
902 if (length != 0) 975 if (length != 0) {
903 memcpy(packet + 1, data, length); 976 memcpy(packet + 1, data, length);
977 }
904 978
905 return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 979 return write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
906 m->friendlist[friendnumber].friendcon_id), packet, length + 1, congestion_control) != -1; 980 m->friendlist[friendnumber].friendcon_id), packet, length + 1, congestion_control) != -1;
@@ -989,11 +1063,13 @@ void callback_file_reqchunk(Messenger *m, void (*function)(Messenger *m, uint32_
989 */ 1063 */
990int file_get_id(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint8_t *file_id) 1064int file_get_id(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint8_t *file_id)
991{ 1065{
992 if (friend_not_valid(m, friendnumber)) 1066 if (friend_not_valid(m, friendnumber)) {
993 return -1; 1067 return -1;
1068 }
994 1069
995 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 1070 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
996 return -2; 1071 return -2;
1072 }
997 1073
998 uint32_t temp_filenum; 1074 uint32_t temp_filenum;
999 uint8_t send_receive, file_number; 1075 uint8_t send_receive, file_number;
@@ -1006,8 +1082,9 @@ int file_get_id(const Messenger *m, int32_t friendnumber, uint32_t filenumber, u
1006 temp_filenum = filenumber; 1082 temp_filenum = filenumber;
1007 } 1083 }
1008 1084
1009 if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) 1085 if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) {
1010 return -2; 1086 return -2;
1087 }
1011 1088
1012 file_number = temp_filenum; 1089 file_number = temp_filenum;
1013 1090
@@ -1019,8 +1096,9 @@ int file_get_id(const Messenger *m, int32_t friendnumber, uint32_t filenumber, u
1019 ft = &m->friendlist[friendnumber].file_sending[file_number]; 1096 ft = &m->friendlist[friendnumber].file_sending[file_number];
1020 } 1097 }
1021 1098
1022 if (ft->status == FILESTATUS_NONE) 1099 if (ft->status == FILESTATUS_NONE) {
1023 return -2; 1100 return -2;
1101 }
1024 1102
1025 memcpy(file_id, ft->id, FILE_ID_LENGTH); 1103 memcpy(file_id, ft->id, FILE_ID_LENGTH);
1026 return 0; 1104 return 0;
@@ -1034,11 +1112,13 @@ int file_get_id(const Messenger *m, int32_t friendnumber, uint32_t filenumber, u
1034static int file_sendrequest(const Messenger *m, int32_t friendnumber, uint8_t filenumber, uint32_t file_type, 1112static int file_sendrequest(const Messenger *m, int32_t friendnumber, uint8_t filenumber, uint32_t file_type,
1035 uint64_t filesize, const uint8_t *file_id, const uint8_t *filename, uint16_t filename_length) 1113 uint64_t filesize, const uint8_t *file_id, const uint8_t *filename, uint16_t filename_length)
1036{ 1114{
1037 if (friend_not_valid(m, friendnumber)) 1115 if (friend_not_valid(m, friendnumber)) {
1038 return 0; 1116 return 0;
1117 }
1039 1118
1040 if (filename_length > MAX_FILENAME_LENGTH) 1119 if (filename_length > MAX_FILENAME_LENGTH) {
1041 return 0; 1120 return 0;
1121 }
1042 1122
1043 uint8_t packet[1 + sizeof(file_type) + sizeof(filesize) + FILE_ID_LENGTH + filename_length]; 1123 uint8_t packet[1 + sizeof(file_type) + sizeof(filesize) + FILE_ID_LENGTH + filename_length];
1044 packet[0] = filenumber; 1124 packet[0] = filenumber;
@@ -1067,24 +1147,29 @@ static int file_sendrequest(const Messenger *m, int32_t friendnumber, uint8_t fi
1067long int new_filesender(const Messenger *m, int32_t friendnumber, uint32_t file_type, uint64_t filesize, 1147long int new_filesender(const Messenger *m, int32_t friendnumber, uint32_t file_type, uint64_t filesize,
1068 const uint8_t *file_id, const uint8_t *filename, uint16_t filename_length) 1148 const uint8_t *file_id, const uint8_t *filename, uint16_t filename_length)
1069{ 1149{
1070 if (friend_not_valid(m, friendnumber)) 1150 if (friend_not_valid(m, friendnumber)) {
1071 return -1; 1151 return -1;
1152 }
1072 1153
1073 if (filename_length > MAX_FILENAME_LENGTH) 1154 if (filename_length > MAX_FILENAME_LENGTH) {
1074 return -2; 1155 return -2;
1156 }
1075 1157
1076 uint32_t i; 1158 uint32_t i;
1077 1159
1078 for (i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) { 1160 for (i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) {
1079 if (m->friendlist[friendnumber].file_sending[i].status == FILESTATUS_NONE) 1161 if (m->friendlist[friendnumber].file_sending[i].status == FILESTATUS_NONE) {
1080 break; 1162 break;
1163 }
1081 } 1164 }
1082 1165
1083 if (i == MAX_CONCURRENT_FILE_PIPES) 1166 if (i == MAX_CONCURRENT_FILE_PIPES) {
1084 return -3; 1167 return -3;
1168 }
1085 1169
1086 if (file_sendrequest(m, friendnumber, i, file_type, filesize, file_id, filename, filename_length) == 0) 1170 if (file_sendrequest(m, friendnumber, i, file_type, filesize, file_id, filename, filename_length) == 0) {
1087 return -4; 1171 return -4;
1172 }
1088 1173
1089 struct File_Transfers *ft = &m->friendlist[friendnumber].file_sending[i]; 1174 struct File_Transfers *ft = &m->friendlist[friendnumber].file_sending[i];
1090 ft->status = FILESTATUS_NOT_ACCEPTED; 1175 ft->status = FILESTATUS_NOT_ACCEPTED;
@@ -1103,8 +1188,9 @@ long int new_filesender(const Messenger *m, int32_t friendnumber, uint32_t file_
1103int send_file_control_packet(const Messenger *m, int32_t friendnumber, uint8_t send_receive, uint8_t filenumber, 1188int send_file_control_packet(const Messenger *m, int32_t friendnumber, uint8_t send_receive, uint8_t filenumber,
1104 uint8_t control_type, uint8_t *data, uint16_t data_length) 1189 uint8_t control_type, uint8_t *data, uint16_t data_length)
1105{ 1190{
1106 if ((unsigned int)(1 + 3 + data_length) > MAX_CRYPTO_DATA_SIZE) 1191 if ((unsigned int)(1 + 3 + data_length) > MAX_CRYPTO_DATA_SIZE) {
1107 return -1; 1192 return -1;
1193 }
1108 1194
1109 uint8_t packet[3 + data_length]; 1195 uint8_t packet[3 + data_length];
1110 1196
@@ -1133,11 +1219,13 @@ int send_file_control_packet(const Messenger *m, int32_t friendnumber, uint8_t s
1133 */ 1219 */
1134int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber, unsigned int control) 1220int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber, unsigned int control)
1135{ 1221{
1136 if (friend_not_valid(m, friendnumber)) 1222 if (friend_not_valid(m, friendnumber)) {
1137 return -1; 1223 return -1;
1224 }
1138 1225
1139 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 1226 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1140 return -2; 1227 return -2;
1228 }
1141 1229
1142 uint32_t temp_filenum; 1230 uint32_t temp_filenum;
1143 uint8_t send_receive, file_number; 1231 uint8_t send_receive, file_number;
@@ -1150,8 +1238,9 @@ int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber,
1150 temp_filenum = filenumber; 1238 temp_filenum = filenumber;
1151 } 1239 }
1152 1240
1153 if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) 1241 if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) {
1154 return -3; 1242 return -3;
1243 }
1155 1244
1156 file_number = temp_filenum; 1245 file_number = temp_filenum;
1157 1246
@@ -1163,14 +1252,17 @@ int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber,
1163 ft = &m->friendlist[friendnumber].file_sending[file_number]; 1252 ft = &m->friendlist[friendnumber].file_sending[file_number];
1164 } 1253 }
1165 1254
1166 if (ft->status == FILESTATUS_NONE) 1255 if (ft->status == FILESTATUS_NONE) {
1167 return -3; 1256 return -3;
1257 }
1168 1258
1169 if (control > FILECONTROL_KILL) 1259 if (control > FILECONTROL_KILL) {
1170 return -4; 1260 return -4;
1261 }
1171 1262
1172 if (control == FILECONTROL_PAUSE && ((ft->paused & FILE_PAUSE_US) || ft->status != FILESTATUS_TRANSFERRING)) 1263 if (control == FILECONTROL_PAUSE && ((ft->paused & FILE_PAUSE_US) || ft->status != FILESTATUS_TRANSFERRING)) {
1173 return -5; 1264 return -5;
1265 }
1174 1266
1175 if (control == FILECONTROL_ACCEPT) { 1267 if (control == FILECONTROL_ACCEPT) {
1176 if (ft->status == FILESTATUS_TRANSFERRING) { 1268 if (ft->status == FILESTATUS_TRANSFERRING) {
@@ -1182,11 +1274,13 @@ int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber,
1182 } 1274 }
1183 } 1275 }
1184 } else { 1276 } else {
1185 if (ft->status != FILESTATUS_NOT_ACCEPTED) 1277 if (ft->status != FILESTATUS_NOT_ACCEPTED) {
1186 return -7; 1278 return -7;
1279 }
1187 1280
1188 if (!send_receive) 1281 if (!send_receive) {
1189 return -6; 1282 return -6;
1283 }
1190 } 1284 }
1191 } 1285 }
1192 1286
@@ -1226,11 +1320,13 @@ int file_control(const Messenger *m, int32_t friendnumber, uint32_t filenumber,
1226 */ 1320 */
1227int file_seek(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint64_t position) 1321int file_seek(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint64_t position)
1228{ 1322{
1229 if (friend_not_valid(m, friendnumber)) 1323 if (friend_not_valid(m, friendnumber)) {
1230 return -1; 1324 return -1;
1325 }
1231 1326
1232 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 1327 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1233 return -2; 1328 return -2;
1329 }
1234 1330
1235 uint32_t temp_filenum; 1331 uint32_t temp_filenum;
1236 uint8_t send_receive, file_number; 1332 uint8_t send_receive, file_number;
@@ -1242,8 +1338,9 @@ int file_seek(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uin
1242 return -4; 1338 return -4;
1243 } 1339 }
1244 1340
1245 if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) 1341 if (temp_filenum >= MAX_CONCURRENT_FILE_PIPES) {
1246 return -3; 1342 return -3;
1343 }
1247 1344
1248 file_number = temp_filenum; 1345 file_number = temp_filenum;
1249 1346
@@ -1255,11 +1352,13 @@ int file_seek(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uin
1255 ft = &m->friendlist[friendnumber].file_sending[file_number]; 1352 ft = &m->friendlist[friendnumber].file_sending[file_number];
1256 } 1353 }
1257 1354
1258 if (ft->status == FILESTATUS_NONE) 1355 if (ft->status == FILESTATUS_NONE) {
1259 return -3; 1356 return -3;
1357 }
1260 1358
1261 if (ft->status != FILESTATUS_NOT_ACCEPTED) 1359 if (ft->status != FILESTATUS_NOT_ACCEPTED) {
1262 return -5; 1360 return -5;
1361 }
1263 1362
1264 if (position >= ft->size) { 1363 if (position >= ft->size) {
1265 return -6; 1364 return -6;
@@ -1284,8 +1383,9 @@ int file_seek(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uin
1284static int64_t send_file_data_packet(const Messenger *m, int32_t friendnumber, uint8_t filenumber, const uint8_t *data, 1383static int64_t send_file_data_packet(const Messenger *m, int32_t friendnumber, uint8_t filenumber, const uint8_t *data,
1285 uint16_t length) 1384 uint16_t length)
1286{ 1385{
1287 if (friend_not_valid(m, friendnumber)) 1386 if (friend_not_valid(m, friendnumber)) {
1288 return -1; 1387 return -1;
1388 }
1289 1389
1290 uint8_t packet[2 + length]; 1390 uint8_t packet[2 + length];
1291 packet[0] = PACKET_ID_FILE_DATA; 1391 packet[0] = PACKET_ID_FILE_DATA;
@@ -1315,22 +1415,27 @@ static int64_t send_file_data_packet(const Messenger *m, int32_t friendnumber, u
1315int file_data(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint64_t position, const uint8_t *data, 1415int file_data(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uint64_t position, const uint8_t *data,
1316 uint16_t length) 1416 uint16_t length)
1317{ 1417{
1318 if (friend_not_valid(m, friendnumber)) 1418 if (friend_not_valid(m, friendnumber)) {
1319 return -1; 1419 return -1;
1420 }
1320 1421
1321 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 1422 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1322 return -2; 1423 return -2;
1424 }
1323 1425
1324 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) 1426 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
1325 return -3; 1427 return -3;
1428 }
1326 1429
1327 struct File_Transfers *ft = &m->friendlist[friendnumber].file_sending[filenumber]; 1430 struct File_Transfers *ft = &m->friendlist[friendnumber].file_sending[filenumber];
1328 1431
1329 if (ft->status != FILESTATUS_TRANSFERRING) 1432 if (ft->status != FILESTATUS_TRANSFERRING) {
1330 return -4; 1433 return -4;
1434 }
1331 1435
1332 if (length > MAX_FILE_DATA_SIZE) 1436 if (length > MAX_FILE_DATA_SIZE) {
1333 return -5; 1437 return -5;
1438 }
1334 1439
1335 if (ft->size - ft->transferred < length) { 1440 if (ft->size - ft->transferred < length) {
1336 return -5; 1441 return -5;
@@ -1346,8 +1451,9 @@ int file_data(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uin
1346 1451
1347 /* Prevent file sending from filling up the entire buffer preventing messages from being sent. TODO: remove */ 1452 /* Prevent file sending from filling up the entire buffer preventing messages from being sent. TODO: remove */
1348 if (crypto_num_free_sendqueue_slots(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 1453 if (crypto_num_free_sendqueue_slots(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1349 m->friendlist[friendnumber].friendcon_id)) < MIN_SLOTS_FREE) 1454 m->friendlist[friendnumber].friendcon_id)) < MIN_SLOTS_FREE) {
1350 return -6; 1455 return -6;
1456 }
1351 1457
1352 int64_t ret = send_file_data_packet(m, friendnumber, filenumber, data, length); 1458 int64_t ret = send_file_data_packet(m, friendnumber, filenumber, data, length);
1353 1459
@@ -1380,18 +1486,21 @@ int file_data(const Messenger *m, int32_t friendnumber, uint32_t filenumber, uin
1380 */ 1486 */
1381uint64_t file_dataremaining(const Messenger *m, int32_t friendnumber, uint8_t filenumber, uint8_t send_receive) 1487uint64_t file_dataremaining(const Messenger *m, int32_t friendnumber, uint8_t filenumber, uint8_t send_receive)
1382{ 1488{
1383 if (friend_not_valid(m, friendnumber)) 1489 if (friend_not_valid(m, friendnumber)) {
1384 return 0; 1490 return 0;
1491 }
1385 1492
1386 if (send_receive == 0) { 1493 if (send_receive == 0) {
1387 if (m->friendlist[friendnumber].file_sending[filenumber].status == FILESTATUS_NONE) 1494 if (m->friendlist[friendnumber].file_sending[filenumber].status == FILESTATUS_NONE) {
1388 return 0; 1495 return 0;
1496 }
1389 1497
1390 return m->friendlist[friendnumber].file_sending[filenumber].size - 1498 return m->friendlist[friendnumber].file_sending[filenumber].size -
1391 m->friendlist[friendnumber].file_sending[filenumber].transferred; 1499 m->friendlist[friendnumber].file_sending[filenumber].transferred;
1392 } else { 1500 } else {
1393 if (m->friendlist[friendnumber].file_receiving[filenumber].status == FILESTATUS_NONE) 1501 if (m->friendlist[friendnumber].file_receiving[filenumber].status == FILESTATUS_NONE) {
1394 return 0; 1502 return 0;
1503 }
1395 1504
1396 return m->friendlist[friendnumber].file_receiving[filenumber].size - 1505 return m->friendlist[friendnumber].file_receiving[filenumber].size -
1397 m->friendlist[friendnumber].file_receiving[filenumber].transferred; 1506 m->friendlist[friendnumber].file_receiving[filenumber].transferred;
@@ -1400,8 +1509,9 @@ uint64_t file_dataremaining(const Messenger *m, int32_t friendnumber, uint8_t fi
1400 1509
1401static void do_reqchunk_filecb(Messenger *m, int32_t friendnumber) 1510static void do_reqchunk_filecb(Messenger *m, int32_t friendnumber)
1402{ 1511{
1403 if (!m->friendlist[friendnumber].num_sending_files) 1512 if (!m->friendlist[friendnumber].num_sending_files) {
1404 return; 1513 return;
1514 }
1405 1515
1406 int free_slots = crypto_num_free_sendqueue_slots(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 1516 int free_slots = crypto_num_free_sendqueue_slots(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1407 m->friendlist[friendnumber].friendcon_id)); 1517 m->friendlist[friendnumber].friendcon_id));
@@ -1423,8 +1533,9 @@ static void do_reqchunk_filecb(Messenger *m, int32_t friendnumber)
1423 if (ft->status == FILESTATUS_FINISHED) { 1533 if (ft->status == FILESTATUS_FINISHED) {
1424 /* Check if file was entirely sent. */ 1534 /* Check if file was entirely sent. */
1425 if (friend_received_packet(m, friendnumber, ft->last_packet_number) == 0) { 1535 if (friend_received_packet(m, friendnumber, ft->last_packet_number) == 0) {
1426 if (m->file_reqchunk) 1536 if (m->file_reqchunk) {
1427 (*m->file_reqchunk)(m, friendnumber, i, ft->transferred, 0, m->file_reqchunk_userdata); 1537 (*m->file_reqchunk)(m, friendnumber, i, ft->transferred, 0, m->file_reqchunk_userdata);
1538 }
1428 1539
1429 ft->status = FILESTATUS_NONE; 1540 ft->status = FILESTATUS_NONE;
1430 --m->friendlist[friendnumber].num_sending_files; 1541 --m->friendlist[friendnumber].num_sending_files;
@@ -1445,8 +1556,9 @@ static void do_reqchunk_filecb(Messenger *m, int32_t friendnumber)
1445 free_slots = 0; 1556 free_slots = 0;
1446 } 1557 }
1447 1558
1448 if (free_slots == 0) 1559 if (free_slots == 0) {
1449 break; 1560 break;
1561 }
1450 1562
1451 uint16_t length = MAX_FILE_DATA_SIZE; 1563 uint16_t length = MAX_FILE_DATA_SIZE;
1452 1564
@@ -1469,15 +1581,17 @@ static void do_reqchunk_filecb(Messenger *m, int32_t friendnumber)
1469 uint64_t position = ft->requested; 1581 uint64_t position = ft->requested;
1470 ft->requested += length; 1582 ft->requested += length;
1471 1583
1472 if (m->file_reqchunk) 1584 if (m->file_reqchunk) {
1473 (*m->file_reqchunk)(m, friendnumber, i, position, length, m->file_reqchunk_userdata); 1585 (*m->file_reqchunk)(m, friendnumber, i, position, length, m->file_reqchunk_userdata);
1586 }
1474 1587
1475 --free_slots; 1588 --free_slots;
1476 1589
1477 } 1590 }
1478 1591
1479 if (num == 0) 1592 if (num == 0) {
1480 break; 1593 break;
1594 }
1481 } 1595 }
1482} 1596}
1483 1597
@@ -1490,11 +1604,13 @@ static void break_files(const Messenger *m, int32_t friendnumber)
1490 1604
1491 //TODO: Inform the client which file transfers get killed with a callback? 1605 //TODO: Inform the client which file transfers get killed with a callback?
1492 for (i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) { 1606 for (i = 0; i < MAX_CONCURRENT_FILE_PIPES; ++i) {
1493 if (m->friendlist[friendnumber].file_sending[i].status != FILESTATUS_NONE) 1607 if (m->friendlist[friendnumber].file_sending[i].status != FILESTATUS_NONE) {
1494 m->friendlist[friendnumber].file_sending[i].status = FILESTATUS_NONE; 1608 m->friendlist[friendnumber].file_sending[i].status = FILESTATUS_NONE;
1609 }
1495 1610
1496 if (m->friendlist[friendnumber].file_receiving[i].status != FILESTATUS_NONE) 1611 if (m->friendlist[friendnumber].file_receiving[i].status != FILESTATUS_NONE) {
1497 m->friendlist[friendnumber].file_receiving[i].status = FILESTATUS_NONE; 1612 m->friendlist[friendnumber].file_receiving[i].status = FILESTATUS_NONE;
1613 }
1498 } 1614 }
1499} 1615}
1500 1616
@@ -1503,11 +1619,13 @@ static void break_files(const Messenger *m, int32_t friendnumber)
1503static int handle_filecontrol(Messenger *m, int32_t friendnumber, uint8_t receive_send, uint8_t filenumber, 1619static int handle_filecontrol(Messenger *m, int32_t friendnumber, uint8_t receive_send, uint8_t filenumber,
1504 uint8_t control_type, uint8_t *data, uint16_t length) 1620 uint8_t control_type, uint8_t *data, uint16_t length)
1505{ 1621{
1506 if (receive_send > 1) 1622 if (receive_send > 1) {
1507 return -1; 1623 return -1;
1624 }
1508 1625
1509 if (control_type > FILECONTROL_SEEK) 1626 if (control_type > FILECONTROL_SEEK) {
1510 return -1; 1627 return -1;
1628 }
1511 1629
1512 uint32_t real_filenumber = filenumber; 1630 uint32_t real_filenumber = filenumber;
1513 struct File_Transfers *ft; 1631 struct File_Transfers *ft;
@@ -1537,8 +1655,9 @@ static int handle_filecontrol(Messenger *m, int32_t friendnumber, uint8_t receiv
1537 } 1655 }
1538 } 1656 }
1539 1657
1540 if (m->file_filecontrol) 1658 if (m->file_filecontrol) {
1541 (*m->file_filecontrol)(m, friendnumber, real_filenumber, control_type, m->file_filecontrol_userdata); 1659 (*m->file_filecontrol)(m, friendnumber, real_filenumber, control_type, m->file_filecontrol_userdata);
1660 }
1542 } else if (control_type == FILECONTROL_PAUSE) { 1661 } else if (control_type == FILECONTROL_PAUSE) {
1543 if ((ft->paused & FILE_PAUSE_OTHER) || ft->status != FILESTATUS_TRANSFERRING) { 1662 if ((ft->paused & FILE_PAUSE_OTHER) || ft->status != FILESTATUS_TRANSFERRING) {
1544 return -1; 1663 return -1;
@@ -1546,12 +1665,14 @@ static int handle_filecontrol(Messenger *m, int32_t friendnumber, uint8_t receiv
1546 1665
1547 ft->paused |= FILE_PAUSE_OTHER; 1666 ft->paused |= FILE_PAUSE_OTHER;
1548 1667
1549 if (m->file_filecontrol) 1668 if (m->file_filecontrol) {
1550 (*m->file_filecontrol)(m, friendnumber, real_filenumber, control_type, m->file_filecontrol_userdata); 1669 (*m->file_filecontrol)(m, friendnumber, real_filenumber, control_type, m->file_filecontrol_userdata);
1670 }
1551 } else if (control_type == FILECONTROL_KILL) { 1671 } else if (control_type == FILECONTROL_KILL) {
1552 1672
1553 if (m->file_filecontrol) 1673 if (m->file_filecontrol) {
1554 (*m->file_filecontrol)(m, friendnumber, real_filenumber, control_type, m->file_filecontrol_userdata); 1674 (*m->file_filecontrol)(m, friendnumber, real_filenumber, control_type, m->file_filecontrol_userdata);
1675 }
1555 1676
1556 ft->status = FILESTATUS_NONE; 1677 ft->status = FILESTATUS_NONE;
1557 1678
@@ -1613,20 +1734,23 @@ static int handle_custom_lossy_packet(void *object, int friend_num, const uint8_
1613{ 1734{
1614 Messenger *m = object; 1735 Messenger *m = object;
1615 1736
1616 if (friend_not_valid(m, friend_num)) 1737 if (friend_not_valid(m, friend_num)) {
1617 return 1; 1738 return 1;
1739 }
1618 1740
1619 if (packet[0] < (PACKET_ID_LOSSY_RANGE_START + PACKET_LOSSY_AV_RESERVED)) { 1741 if (packet[0] < (PACKET_ID_LOSSY_RANGE_START + PACKET_LOSSY_AV_RESERVED)) {
1620 if (m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] % PACKET_LOSSY_AV_RESERVED].function) 1742 if (m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] % PACKET_LOSSY_AV_RESERVED].function) {
1621 return m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] % PACKET_LOSSY_AV_RESERVED].function( 1743 return m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] % PACKET_LOSSY_AV_RESERVED].function(
1622 m, friend_num, packet, length, m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] % 1744 m, friend_num, packet, length, m->friendlist[friend_num].lossy_rtp_packethandlers[packet[0] %
1623 PACKET_LOSSY_AV_RESERVED].object); 1745 PACKET_LOSSY_AV_RESERVED].object);
1746 }
1624 1747
1625 return 1; 1748 return 1;
1626 } 1749 }
1627 1750
1628 if (m->lossy_packethandler) 1751 if (m->lossy_packethandler) {
1629 m->lossy_packethandler(m, friend_num, packet, length, m->lossy_packethandler_userdata); 1752 m->lossy_packethandler(m, friend_num, packet, length, m->lossy_packethandler_userdata);
1753 }
1630 1754
1631 return 1; 1755 return 1;
1632} 1756}
@@ -1641,14 +1765,17 @@ void custom_lossy_packet_registerhandler(Messenger *m, void (*packet_handler_cal
1641int m_callback_rtp_packet(Messenger *m, int32_t friendnumber, uint8_t byte, int (*packet_handler_callback)(Messenger *m, 1765int m_callback_rtp_packet(Messenger *m, int32_t friendnumber, uint8_t byte, int (*packet_handler_callback)(Messenger *m,
1642 uint32_t friendnumber, const uint8_t *data, uint16_t len, void *object), void *object) 1766 uint32_t friendnumber, const uint8_t *data, uint16_t len, void *object), void *object)
1643{ 1767{
1644 if (friend_not_valid(m, friendnumber)) 1768 if (friend_not_valid(m, friendnumber)) {
1645 return -1; 1769 return -1;
1770 }
1646 1771
1647 if (byte < PACKET_ID_LOSSY_RANGE_START) 1772 if (byte < PACKET_ID_LOSSY_RANGE_START) {
1648 return -1; 1773 return -1;
1774 }
1649 1775
1650 if (byte >= (PACKET_ID_LOSSY_RANGE_START + PACKET_LOSSY_AV_RESERVED)) 1776 if (byte >= (PACKET_ID_LOSSY_RANGE_START + PACKET_LOSSY_AV_RESERVED)) {
1651 return -1; 1777 return -1;
1778 }
1652 1779
1653 m->friendlist[friendnumber].lossy_rtp_packethandlers[byte % PACKET_LOSSY_AV_RESERVED].function = 1780 m->friendlist[friendnumber].lossy_rtp_packethandlers[byte % PACKET_LOSSY_AV_RESERVED].function =
1654 packet_handler_callback; 1781 packet_handler_callback;
@@ -1659,20 +1786,25 @@ int m_callback_rtp_packet(Messenger *m, int32_t friendnumber, uint8_t byte, int
1659 1786
1660int send_custom_lossy_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint32_t length) 1787int send_custom_lossy_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint32_t length)
1661{ 1788{
1662 if (friend_not_valid(m, friendnumber)) 1789 if (friend_not_valid(m, friendnumber)) {
1663 return -1; 1790 return -1;
1791 }
1664 1792
1665 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) 1793 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
1666 return -2; 1794 return -2;
1795 }
1667 1796
1668 if (data[0] < PACKET_ID_LOSSY_RANGE_START) 1797 if (data[0] < PACKET_ID_LOSSY_RANGE_START) {
1669 return -3; 1798 return -3;
1799 }
1670 1800
1671 if (data[0] >= (PACKET_ID_LOSSY_RANGE_START + PACKET_ID_LOSSY_RANGE_SIZE)) 1801 if (data[0] >= (PACKET_ID_LOSSY_RANGE_START + PACKET_ID_LOSSY_RANGE_SIZE)) {
1672 return -3; 1802 return -3;
1803 }
1673 1804
1674 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 1805 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1675 return -4; 1806 return -4;
1807 }
1676 1808
1677 if (send_lossy_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 1809 if (send_lossy_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1678 m->friendlist[friendnumber].friendcon_id), data, length) == -1) { 1810 m->friendlist[friendnumber].friendcon_id), data, length) == -1) {
@@ -1686,17 +1818,21 @@ static int handle_custom_lossless_packet(void *object, int friend_num, const uin
1686{ 1818{
1687 Messenger *m = object; 1819 Messenger *m = object;
1688 1820
1689 if (friend_not_valid(m, friend_num)) 1821 if (friend_not_valid(m, friend_num)) {
1690 return -1; 1822 return -1;
1823 }
1691 1824
1692 if (packet[0] < PACKET_ID_LOSSLESS_RANGE_START) 1825 if (packet[0] < PACKET_ID_LOSSLESS_RANGE_START) {
1693 return -1; 1826 return -1;
1827 }
1694 1828
1695 if (packet[0] >= (PACKET_ID_LOSSLESS_RANGE_START + PACKET_ID_LOSSLESS_RANGE_SIZE)) 1829 if (packet[0] >= (PACKET_ID_LOSSLESS_RANGE_START + PACKET_ID_LOSSLESS_RANGE_SIZE)) {
1696 return -1; 1830 return -1;
1831 }
1697 1832
1698 if (m->lossless_packethandler) 1833 if (m->lossless_packethandler) {
1699 m->lossless_packethandler(m, friend_num, packet, length, m->lossless_packethandler_userdata); 1834 m->lossless_packethandler(m, friend_num, packet, length, m->lossless_packethandler_userdata);
1835 }
1700 1836
1701 return 1; 1837 return 1;
1702} 1838}
@@ -1710,20 +1846,25 @@ void custom_lossless_packet_registerhandler(Messenger *m, void (*packet_handler_
1710 1846
1711int send_custom_lossless_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint32_t length) 1847int send_custom_lossless_packet(const Messenger *m, int32_t friendnumber, const uint8_t *data, uint32_t length)
1712{ 1848{
1713 if (friend_not_valid(m, friendnumber)) 1849 if (friend_not_valid(m, friendnumber)) {
1714 return -1; 1850 return -1;
1851 }
1715 1852
1716 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) 1853 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
1717 return -2; 1854 return -2;
1855 }
1718 1856
1719 if (data[0] < PACKET_ID_LOSSLESS_RANGE_START) 1857 if (data[0] < PACKET_ID_LOSSLESS_RANGE_START) {
1720 return -3; 1858 return -3;
1859 }
1721 1860
1722 if (data[0] >= (PACKET_ID_LOSSLESS_RANGE_START + PACKET_ID_LOSSLESS_RANGE_SIZE)) 1861 if (data[0] >= (PACKET_ID_LOSSLESS_RANGE_START + PACKET_ID_LOSSLESS_RANGE_SIZE)) {
1723 return -3; 1862 return -3;
1863 }
1724 1864
1725 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) 1865 if (m->friendlist[friendnumber].status != FRIEND_ONLINE) {
1726 return -4; 1866 return -4;
1867 }
1727 1868
1728 if (write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c, 1869 if (write_cryptpacket(m->net_crypto, friend_connection_crypt_connection_id(m->fr_c,
1729 m->friendlist[friendnumber].friendcon_id), data, length, 1) == -1) { 1870 m->friendlist[friendnumber].friendcon_id), data, length, 1) == -1) {
@@ -1738,8 +1879,9 @@ static int friend_already_added(const uint8_t *real_pk, void *data)
1738{ 1879{
1739 const Messenger *m = data; 1880 const Messenger *m = data;
1740 1881
1741 if (getfriend_id(m, real_pk) == -1) 1882 if (getfriend_id(m, real_pk) == -1) {
1742 return 0; 1883 return 0;
1884 }
1743 1885
1744 return -1; 1886 return -1;
1745} 1887}
@@ -1749,11 +1891,13 @@ Messenger *new_messenger(Logger *log, Messenger_Options *options, unsigned int *
1749{ 1891{
1750 Messenger *m = calloc(1, sizeof(Messenger)); 1892 Messenger *m = calloc(1, sizeof(Messenger));
1751 1893
1752 if (error) 1894 if (error) {
1753 *error = MESSENGER_ERROR_OTHER; 1895 *error = MESSENGER_ERROR_OTHER;
1896 }
1754 1897
1755 if ( ! m ) 1898 if ( ! m ) {
1756 return NULL; 1899 return NULL;
1900 }
1757 1901
1758 m->log = log; 1902 m->log = log;
1759 1903
@@ -1825,8 +1969,9 @@ Messenger *new_messenger(Logger *log, Messenger_Options *options, unsigned int *
1825 kill_networking(m->net); 1969 kill_networking(m->net);
1826 free(m); 1970 free(m);
1827 1971
1828 if (error) 1972 if (error) {
1829 *error = MESSENGER_ERROR_TCP_SERVER; 1973 *error = MESSENGER_ERROR_TCP_SERVER;
1974 }
1830 1975
1831 return NULL; 1976 return NULL;
1832 } 1977 }
@@ -1837,8 +1982,9 @@ Messenger *new_messenger(Logger *log, Messenger_Options *options, unsigned int *
1837 set_nospam(&(m->fr), random_int()); 1982 set_nospam(&(m->fr), random_int());
1838 set_filter_function(&(m->fr), &friend_already_added, m); 1983 set_filter_function(&(m->fr), &friend_already_added, m);
1839 1984
1840 if (error) 1985 if (error) {
1841 *error = MESSENGER_ERROR_NONE; 1986 *error = MESSENGER_ERROR_NONE;
1987 }
1842 1988
1843 return m; 1989 return m;
1844} 1990}
@@ -1846,8 +1992,9 @@ Messenger *new_messenger(Logger *log, Messenger_Options *options, unsigned int *
1846/* Run this before closing shop. */ 1992/* Run this before closing shop. */
1847void kill_messenger(Messenger *m) 1993void kill_messenger(Messenger *m)
1848{ 1994{
1849 if (!m) 1995 if (!m) {
1850 return; 1996 return;
1997 }
1851 1998
1852 uint32_t i; 1999 uint32_t i;
1853 2000
@@ -1906,8 +2053,9 @@ static int handle_status(void *object, int i, uint8_t status)
1906 2053
1907static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void *userdata) 2054static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void *userdata)
1908{ 2055{
1909 if (len == 0) 2056 if (len == 0) {
1910 return -1; 2057 return -1;
2058 }
1911 2059
1912 Messenger *m = object; 2060 Messenger *m = object;
1913 uint8_t packet_id = temp[0]; 2061 uint8_t packet_id = temp[0];
@@ -1925,16 +2073,18 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
1925 2073
1926 switch (packet_id) { 2074 switch (packet_id) {
1927 case PACKET_ID_OFFLINE: { 2075 case PACKET_ID_OFFLINE: {
1928 if (data_length != 0) 2076 if (data_length != 0) {
1929 break; 2077 break;
2078 }
1930 2079
1931 set_friend_status(m, i, FRIEND_CONFIRMED); 2080 set_friend_status(m, i, FRIEND_CONFIRMED);
1932 break; 2081 break;
1933 } 2082 }
1934 2083
1935 case PACKET_ID_NICKNAME: { 2084 case PACKET_ID_NICKNAME: {
1936 if (data_length > MAX_NAME_LENGTH) 2085 if (data_length > MAX_NAME_LENGTH) {
1937 break; 2086 break;
2087 }
1938 2088
1939 /* Make sure the NULL terminator is present. */ 2089 /* Make sure the NULL terminator is present. */
1940 uint8_t data_terminated[data_length + 1]; 2090 uint8_t data_terminated[data_length + 1];
@@ -1942,8 +2092,9 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
1942 data_terminated[data_length] = 0; 2092 data_terminated[data_length] = 0;
1943 2093
1944 /* inform of namechange before we overwrite the old name */ 2094 /* inform of namechange before we overwrite the old name */
1945 if (m->friend_namechange) 2095 if (m->friend_namechange) {
1946 m->friend_namechange(m, i, data_terminated, data_length, userdata); 2096 m->friend_namechange(m, i, data_terminated, data_length, userdata);
2097 }
1947 2098
1948 memcpy(m->friendlist[i].name, data_terminated, data_length); 2099 memcpy(m->friendlist[i].name, data_terminated, data_length);
1949 m->friendlist[i].name_length = data_length; 2100 m->friendlist[i].name_length = data_length;
@@ -1952,40 +2103,46 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
1952 } 2103 }
1953 2104
1954 case PACKET_ID_STATUSMESSAGE: { 2105 case PACKET_ID_STATUSMESSAGE: {
1955 if (data_length > MAX_STATUSMESSAGE_LENGTH) 2106 if (data_length > MAX_STATUSMESSAGE_LENGTH) {
1956 break; 2107 break;
2108 }
1957 2109
1958 /* Make sure the NULL terminator is present. */ 2110 /* Make sure the NULL terminator is present. */
1959 uint8_t data_terminated[data_length + 1]; 2111 uint8_t data_terminated[data_length + 1];
1960 memcpy(data_terminated, data, data_length); 2112 memcpy(data_terminated, data, data_length);
1961 data_terminated[data_length] = 0; 2113 data_terminated[data_length] = 0;
1962 2114
1963 if (m->friend_statusmessagechange) 2115 if (m->friend_statusmessagechange) {
1964 m->friend_statusmessagechange(m, i, data_terminated, data_length, userdata); 2116 m->friend_statusmessagechange(m, i, data_terminated, data_length, userdata);
2117 }
1965 2118
1966 set_friend_statusmessage(m, i, data_terminated, data_length); 2119 set_friend_statusmessage(m, i, data_terminated, data_length);
1967 break; 2120 break;
1968 } 2121 }
1969 2122
1970 case PACKET_ID_USERSTATUS: { 2123 case PACKET_ID_USERSTATUS: {
1971 if (data_length != 1) 2124 if (data_length != 1) {
1972 break; 2125 break;
2126 }
1973 2127
1974 USERSTATUS status = data[0]; 2128 USERSTATUS status = data[0];
1975 2129
1976 if (status >= USERSTATUS_INVALID) 2130 if (status >= USERSTATUS_INVALID) {
1977 break; 2131 break;
2132 }
1978 2133
1979 if (m->friend_userstatuschange) 2134 if (m->friend_userstatuschange) {
1980 m->friend_userstatuschange(m, i, status, userdata); 2135 m->friend_userstatuschange(m, i, status, userdata);
2136 }
1981 2137
1982 set_friend_userstatus(m, i, status); 2138 set_friend_userstatus(m, i, status);
1983 break; 2139 break;
1984 } 2140 }
1985 2141
1986 case PACKET_ID_TYPING: { 2142 case PACKET_ID_TYPING: {
1987 if (data_length != 1) 2143 if (data_length != 1) {
1988 break; 2144 break;
2145 }
1989 2146
1990 _Bool typing = !!data[0]; 2147 _Bool typing = !!data[0];
1991 2148
@@ -2000,8 +2157,9 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2000 2157
2001 case PACKET_ID_MESSAGE: 2158 case PACKET_ID_MESSAGE:
2002 case PACKET_ID_ACTION: { 2159 case PACKET_ID_ACTION: {
2003 if (data_length == 0) 2160 if (data_length == 0) {
2004 break; 2161 break;
2162 }
2005 2163
2006 const uint8_t *message = data; 2164 const uint8_t *message = data;
2007 uint16_t message_length = data_length; 2165 uint16_t message_length = data_length;
@@ -2020,11 +2178,13 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2020 } 2178 }
2021 2179
2022 case PACKET_ID_INVITE_GROUPCHAT: { 2180 case PACKET_ID_INVITE_GROUPCHAT: {
2023 if (data_length == 0) 2181 if (data_length == 0) {
2024 break; 2182 break;
2183 }
2025 2184
2026 if (m->group_invite) 2185 if (m->group_invite) {
2027 (*m->group_invite)(m, i, data, data_length); 2186 (*m->group_invite)(m, i, data, data_length);
2187 }
2028 2188
2029 break; 2189 break;
2030 } 2190 }
@@ -2032,20 +2192,23 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2032 case PACKET_ID_FILE_SENDREQUEST: { 2192 case PACKET_ID_FILE_SENDREQUEST: {
2033 const unsigned int head_length = 1 + sizeof(uint32_t) + sizeof(uint64_t) + FILE_ID_LENGTH; 2193 const unsigned int head_length = 1 + sizeof(uint32_t) + sizeof(uint64_t) + FILE_ID_LENGTH;
2034 2194
2035 if (data_length < head_length) 2195 if (data_length < head_length) {
2036 break; 2196 break;
2197 }
2037 2198
2038 uint8_t filenumber = data[0]; 2199 uint8_t filenumber = data[0];
2039 2200
2040 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) 2201 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
2041 break; 2202 break;
2203 }
2042 2204
2043 uint64_t filesize; 2205 uint64_t filesize;
2044 uint32_t file_type; 2206 uint32_t file_type;
2045 uint16_t filename_length = data_length - head_length; 2207 uint16_t filename_length = data_length - head_length;
2046 2208
2047 if (filename_length > MAX_FILENAME_LENGTH) 2209 if (filename_length > MAX_FILENAME_LENGTH) {
2048 break; 2210 break;
2211 }
2049 2212
2050 memcpy(&file_type, data + 1, sizeof(file_type)); 2213 memcpy(&file_type, data + 1, sizeof(file_type));
2051 file_type = ntohl(file_type); 2214 file_type = ntohl(file_type);
@@ -2054,8 +2217,9 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2054 net_to_host((uint8_t *) &filesize, sizeof(filesize)); 2217 net_to_host((uint8_t *) &filesize, sizeof(filesize));
2055 struct File_Transfers *ft = &m->friendlist[i].file_receiving[filenumber]; 2218 struct File_Transfers *ft = &m->friendlist[i].file_receiving[filenumber];
2056 2219
2057 if (ft->status != FILESTATUS_NONE) 2220 if (ft->status != FILESTATUS_NONE) {
2058 break; 2221 break;
2222 }
2059 2223
2060 ft->status = FILESTATUS_NOT_ACCEPTED; 2224 ft->status = FILESTATUS_NOT_ACCEPTED;
2061 ft->size = filesize; 2225 ft->size = filesize;
@@ -2077,43 +2241,50 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2077 real_filenumber += 1; 2241 real_filenumber += 1;
2078 real_filenumber <<= 16; 2242 real_filenumber <<= 16;
2079 2243
2080 if (m->file_sendrequest) 2244 if (m->file_sendrequest) {
2081 (*m->file_sendrequest)(m, i, real_filenumber, file_type, filesize, filename, filename_length, 2245 (*m->file_sendrequest)(m, i, real_filenumber, file_type, filesize, filename, filename_length,
2082 m->file_sendrequest_userdata); 2246 m->file_sendrequest_userdata);
2247 }
2083 2248
2084 break; 2249 break;
2085 } 2250 }
2086 2251
2087 case PACKET_ID_FILE_CONTROL: { 2252 case PACKET_ID_FILE_CONTROL: {
2088 if (data_length < 3) 2253 if (data_length < 3) {
2089 break; 2254 break;
2255 }
2090 2256
2091 uint8_t send_receive = data[0]; 2257 uint8_t send_receive = data[0];
2092 uint8_t filenumber = data[1]; 2258 uint8_t filenumber = data[1];
2093 uint8_t control_type = data[2]; 2259 uint8_t control_type = data[2];
2094 2260
2095 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) 2261 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
2096 break; 2262 break;
2263 }
2097 2264
2098 if (handle_filecontrol(m, i, send_receive, filenumber, control_type, data + 3, data_length - 3) == -1) 2265 if (handle_filecontrol(m, i, send_receive, filenumber, control_type, data + 3, data_length - 3) == -1) {
2099 break; 2266 break;
2267 }
2100 2268
2101 break; 2269 break;
2102 } 2270 }
2103 2271
2104 case PACKET_ID_FILE_DATA: { 2272 case PACKET_ID_FILE_DATA: {
2105 if (data_length < 1) 2273 if (data_length < 1) {
2106 break; 2274 break;
2275 }
2107 2276
2108 uint8_t filenumber = data[0]; 2277 uint8_t filenumber = data[0];
2109 2278
2110 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) 2279 if (filenumber >= MAX_CONCURRENT_FILE_PIPES) {
2111 break; 2280 break;
2281 }
2112 2282
2113 struct File_Transfers *ft = &m->friendlist[i].file_receiving[filenumber]; 2283 struct File_Transfers *ft = &m->friendlist[i].file_receiving[filenumber];
2114 2284
2115 if (ft->status != FILESTATUS_TRANSFERRING) 2285 if (ft->status != FILESTATUS_TRANSFERRING) {
2116 break; 2286 break;
2287 }
2117 2288
2118 uint64_t position = ft->transferred; 2289 uint64_t position = ft->transferred;
2119 uint32_t real_filenumber = filenumber; 2290 uint32_t real_filenumber = filenumber;
@@ -2133,8 +2304,9 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2133 file_data_length = ft->size - ft->transferred; 2304 file_data_length = ft->size - ft->transferred;
2134 } 2305 }
2135 2306
2136 if (m->file_filedata) 2307 if (m->file_filedata) {
2137 (*m->file_filedata)(m, i, real_filenumber, position, file_data, file_data_length, m->file_filedata_userdata); 2308 (*m->file_filedata)(m, i, real_filenumber, position, file_data, file_data_length, m->file_filedata_userdata);
2309 }
2138 2310
2139 ft->transferred += file_data_length; 2311 ft->transferred += file_data_length;
2140 2312
@@ -2144,8 +2316,9 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2144 position = ft->transferred; 2316 position = ft->transferred;
2145 2317
2146 /* Full file received. */ 2318 /* Full file received. */
2147 if (m->file_filedata) 2319 if (m->file_filedata) {
2148 (*m->file_filedata)(m, i, real_filenumber, position, file_data, file_data_length, m->file_filedata_userdata); 2320 (*m->file_filedata)(m, i, real_filenumber, position, file_data, file_data_length, m->file_filedata_userdata);
2321 }
2149 } 2322 }
2150 2323
2151 /* Data is zero, filetransfer is over. */ 2324 /* Data is zero, filetransfer is over. */
@@ -2157,11 +2330,13 @@ static int handle_packet(void *object, int i, uint8_t *temp, uint16_t len, void
2157 } 2330 }
2158 2331
2159 case PACKET_ID_MSI: { 2332 case PACKET_ID_MSI: {
2160 if (data_length == 0) 2333 if (data_length == 0) {
2161 break; 2334 break;
2335 }
2162 2336
2163 if (m->msi_packet) 2337 if (m->msi_packet) {
2164 (*m->msi_packet)(m, i, data, data_length, m->msi_packet_userdata); 2338 (*m->msi_packet)(m, i, data, data_length, m->msi_packet_userdata);
2339 }
2165 2340
2166 break; 2341 break;
2167 } 2342 }
@@ -2204,23 +2379,27 @@ static void do_friends(Messenger *m, void *userdata)
2204 2379
2205 if (m->friendlist[i].status == FRIEND_ONLINE) { /* friend is online. */ 2380 if (m->friendlist[i].status == FRIEND_ONLINE) { /* friend is online. */
2206 if (m->friendlist[i].name_sent == 0) { 2381 if (m->friendlist[i].name_sent == 0) {
2207 if (m_sendname(m, i, m->name, m->name_length)) 2382 if (m_sendname(m, i, m->name, m->name_length)) {
2208 m->friendlist[i].name_sent = 1; 2383 m->friendlist[i].name_sent = 1;
2384 }
2209 } 2385 }
2210 2386
2211 if (m->friendlist[i].statusmessage_sent == 0) { 2387 if (m->friendlist[i].statusmessage_sent == 0) {
2212 if (send_statusmessage(m, i, m->statusmessage, m->statusmessage_length)) 2388 if (send_statusmessage(m, i, m->statusmessage, m->statusmessage_length)) {
2213 m->friendlist[i].statusmessage_sent = 1; 2389 m->friendlist[i].statusmessage_sent = 1;
2390 }
2214 } 2391 }
2215 2392
2216 if (m->friendlist[i].userstatus_sent == 0) { 2393 if (m->friendlist[i].userstatus_sent == 0) {
2217 if (send_userstatus(m, i, m->userstatus)) 2394 if (send_userstatus(m, i, m->userstatus)) {
2218 m->friendlist[i].userstatus_sent = 1; 2395 m->friendlist[i].userstatus_sent = 1;
2396 }
2219 } 2397 }
2220 2398
2221 if (m->friendlist[i].user_istyping_sent == 0) { 2399 if (m->friendlist[i].user_istyping_sent == 0) {
2222 if (send_user_istyping(m, i, m->friendlist[i].user_istyping)) 2400 if (send_user_istyping(m, i, m->friendlist[i].user_istyping)) {
2223 m->friendlist[i].user_istyping_sent = 1; 2401 m->friendlist[i].user_istyping_sent = 1;
2402 }
2224 } 2403 }
2225 2404
2226 check_friend_tcp_udp(m, i); 2405 check_friend_tcp_udp(m, i);
@@ -2237,8 +2416,9 @@ static void connection_status_cb(Messenger *m, void *userdata)
2237 unsigned int conn_status = onion_connection_status(m->onion_c); 2416 unsigned int conn_status = onion_connection_status(m->onion_c);
2238 2417
2239 if (conn_status != m->last_connection_status) { 2418 if (conn_status != m->last_connection_status) {
2240 if (m->core_connection_change) 2419 if (m->core_connection_change) {
2241 (*m->core_connection_change)(m, conn_status, userdata); 2420 (*m->core_connection_change)(m, conn_status, userdata);
2421 }
2242 2422
2243 m->last_connection_status = conn_status; 2423 m->last_connection_status = conn_status;
2244 } 2424 }
@@ -2252,8 +2432,9 @@ static char *ID2String(const uint8_t *pk)
2252{ 2432{
2253 uint32_t i; 2433 uint32_t i;
2254 2434
2255 for (i = 0; i < crypto_box_PUBLICKEYBYTES; i++) 2435 for (i = 0; i < crypto_box_PUBLICKEYBYTES; i++) {
2256 sprintf(&IDString[i * 2], "%02X", pk[i]); 2436 sprintf(&IDString[i * 2], "%02X", pk[i]);
2437 }
2257 2438
2258 IDString[crypto_box_PUBLICKEYBYTES * 2] = 0; 2439 IDString[crypto_box_PUBLICKEYBYTES * 2] = 0;
2259 return IDString; 2440 return IDString;
@@ -2333,17 +2514,19 @@ void do_messenger(Messenger *m, void *userdata)
2333 IPPTsPng *assoc = NULL; 2514 IPPTsPng *assoc = NULL;
2334 uint32_t a; 2515 uint32_t a;
2335 2516
2336 for (a = 0, assoc = &cptr->assoc4; a < 2; a++, assoc = &cptr->assoc6) 2517 for (a = 0, assoc = &cptr->assoc4; a < 2; a++, assoc = &cptr->assoc6) {
2337 if (ip_isset(&assoc->ip_port.ip)) { 2518 if (ip_isset(&assoc->ip_port.ip)) {
2338 last_pinged = lastdump - assoc->last_pinged; 2519 last_pinged = lastdump - assoc->last_pinged;
2339 2520
2340 if (last_pinged > 999) 2521 if (last_pinged > 999) {
2341 last_pinged = 999; 2522 last_pinged = 999;
2523 }
2342 2524
2343 LOGGER_TRACE(m->log, "C[%2u] %s:%u [%3u] %s", 2525 LOGGER_TRACE(m->log, "C[%2u] %s:%u [%3u] %s",
2344 client, ip_ntoa(&assoc->ip_port.ip), ntohs(assoc->ip_port.port), 2526 client, ip_ntoa(&assoc->ip_port.ip), ntohs(assoc->ip_port.port),
2345 last_pinged, ID2String(cptr->public_key)); 2527 last_pinged, ID2String(cptr->public_key));
2346 } 2528 }
2529 }
2347 } 2530 }
2348 2531
2349 2532
@@ -2358,19 +2541,23 @@ void do_messenger(Messenger *m, void *userdata)
2358 m2dht[friend] = -1; 2541 m2dht[friend] = -1;
2359 dht2m[friend] = -1; 2542 dht2m[friend] = -1;
2360 2543
2361 if (friend >= m->numfriends) 2544 if (friend >= m->numfriends) {
2362 continue; 2545 continue;
2546 }
2363 2547
2364 for (dhtfriend = 0; dhtfriend < m->dht->num_friends; dhtfriend++) 2548 for (dhtfriend = 0; dhtfriend < m->dht->num_friends; dhtfriend++) {
2365 if (id_equal(m->friendlist[friend].real_pk, m->dht->friends_list[dhtfriend].public_key)) { 2549 if (id_equal(m->friendlist[friend].real_pk, m->dht->friends_list[dhtfriend].public_key)) {
2366 m2dht[friend] = dhtfriend; 2550 m2dht[friend] = dhtfriend;
2367 break; 2551 break;
2368 } 2552 }
2553 }
2369 } 2554 }
2370 2555
2371 for (friend = 0; friend < num_dhtfriends; friend++) 2556 for (friend = 0; friend < num_dhtfriends; friend++) {
2372 if (m2dht[friend] >= 0) 2557 if (m2dht[friend] >= 0) {
2373 dht2m[m2dht[friend]] = friend; 2558 dht2m[m2dht[friend]] = friend;
2559 }
2560 }
2374 2561
2375 if (m->numfriends != m->dht->num_friends) { 2562 if (m->numfriends != m->dht->num_friends) {
2376 LOGGER_TRACE(m->log, "Friend num in DHT %u != friend num in msger %u\n", m->dht->num_friends, m->numfriends); 2563 LOGGER_TRACE(m->log, "Friend num in DHT %u != friend num in msger %u\n", m->dht->num_friends, m->numfriends);
@@ -2380,10 +2567,11 @@ void do_messenger(Messenger *m, void *userdata)
2380 DHT_Friend *dhtfptr; 2567 DHT_Friend *dhtfptr;
2381 2568
2382 for (friend = 0; friend < num_dhtfriends; friend++) { 2569 for (friend = 0; friend < num_dhtfriends; friend++) {
2383 if (dht2m[friend] >= 0) 2570 if (dht2m[friend] >= 0) {
2384 msgfptr = &m->friendlist[dht2m[friend]]; 2571 msgfptr = &m->friendlist[dht2m[friend]];
2385 else 2572 } else {
2386 msgfptr = NULL; 2573 msgfptr = NULL;
2574 }
2387 2575
2388 dhtfptr = &m->dht->friends_list[friend]; 2576 dhtfptr = &m->dht->friends_list[friend];
2389 2577
@@ -2400,18 +2588,20 @@ void do_messenger(Messenger *m, void *userdata)
2400 IPPTsPng *assoc = NULL; 2588 IPPTsPng *assoc = NULL;
2401 uint32_t a; 2589 uint32_t a;
2402 2590
2403 for (a = 0, assoc = &cptr->assoc4; a < 2; a++, assoc = &cptr->assoc6) 2591 for (a = 0, assoc = &cptr->assoc4; a < 2; a++, assoc = &cptr->assoc6) {
2404 if (ip_isset(&assoc->ip_port.ip)) { 2592 if (ip_isset(&assoc->ip_port.ip)) {
2405 last_pinged = lastdump - assoc->last_pinged; 2593 last_pinged = lastdump - assoc->last_pinged;
2406 2594
2407 if (last_pinged > 999) 2595 if (last_pinged > 999) {
2408 last_pinged = 999; 2596 last_pinged = 999;
2597 }
2409 2598
2410 LOGGER_TRACE(m->log, "F[%2u] => C[%2u] %s:%u [%3u] %s", 2599 LOGGER_TRACE(m->log, "F[%2u] => C[%2u] %s:%u [%3u] %s",
2411 friend, client, ip_ntoa(&assoc->ip_port.ip), 2600 friend, client, ip_ntoa(&assoc->ip_port.ip),
2412 ntohs(assoc->ip_port.port), last_pinged, 2601 ntohs(assoc->ip_port.port), last_pinged,
2413 ID2String(cptr->public_key)); 2602 ID2String(cptr->public_key));
2414 } 2603 }
2604 }
2415 } 2605 }
2416 } 2606 }
2417 } 2607 }
@@ -2511,8 +2701,9 @@ static int friends_list_load(Messenger *m, const uint8_t *data, uint32_t length)
2511 if (temp.status >= 3) { 2701 if (temp.status >= 3) {
2512 int fnum = m_addfriend_norequest(m, temp.real_pk); 2702 int fnum = m_addfriend_norequest(m, temp.real_pk);
2513 2703
2514 if (fnum < 0) 2704 if (fnum < 0) {
2515 continue; 2705 continue;
2706 }
2516 2707
2517 setfriendname(m, fnum, temp.name, ntohs(temp.name_length)); 2708 setfriendname(m, fnum, temp.name, ntohs(temp.name_length));
2518 set_friend_statusmessage(m, fnum, temp.statusmessage, ntohs(temp.statusmessage_length)); 2709 set_friend_statusmessage(m, fnum, temp.statusmessage, ntohs(temp.statusmessage_length));
@@ -2657,8 +2848,9 @@ static int messenger_load_state_callback(void *outer, const uint8_t *data, uint3
2657 if (public_key_cmp((&data[sizeof(uint32_t)]), m->net_crypto->self_public_key) != 0) { 2848 if (public_key_cmp((&data[sizeof(uint32_t)]), m->net_crypto->self_public_key) != 0) {
2658 return -1; 2849 return -1;
2659 } 2850 }
2660 } else 2851 } else {
2661 return -1; /* critical */ 2852 return -1; /* critical */
2853 }
2662 2854
2663 break; 2855 break;
2664 2856
@@ -2745,17 +2937,19 @@ int messenger_load(Messenger *m, const uint8_t *data, uint32_t length)
2745 uint32_t data32[2]; 2937 uint32_t data32[2];
2746 uint32_t cookie_len = sizeof(data32); 2938 uint32_t cookie_len = sizeof(data32);
2747 2939
2748 if (length < cookie_len) 2940 if (length < cookie_len) {
2749 return -1; 2941 return -1;
2942 }
2750 2943
2751 memcpy(data32, data, sizeof(uint32_t)); 2944 memcpy(data32, data, sizeof(uint32_t));
2752 lendian_to_host32(data32 + 1, data + sizeof(uint32_t)); 2945 lendian_to_host32(data32 + 1, data + sizeof(uint32_t));
2753 2946
2754 if (!data32[0] && (data32[1] == MESSENGER_STATE_COOKIE_GLOBAL)) 2947 if (!data32[0] && (data32[1] == MESSENGER_STATE_COOKIE_GLOBAL)) {
2755 return load_state(messenger_load_state_callback, m, data + cookie_len, 2948 return load_state(messenger_load_state_callback, m, data + cookie_len,
2756 length - cookie_len, MESSENGER_STATE_COOKIE_TYPE); 2949 length - cookie_len, MESSENGER_STATE_COOKIE_TYPE);
2757 else 2950 } else {
2758 return -1; 2951 return -1;
2952 }
2759} 2953}
2760 2954
2761/* Return the number of friends in the instance m. 2955/* Return the number of friends in the instance m.
@@ -2782,8 +2976,9 @@ uint32_t count_friendlist(const Messenger *m)
2782 * of out_list will be truncated to list_size. */ 2976 * of out_list will be truncated to list_size. */
2783uint32_t copy_friendlist(Messenger const *m, uint32_t *out_list, uint32_t list_size) 2977uint32_t copy_friendlist(Messenger const *m, uint32_t *out_list, uint32_t list_size)
2784{ 2978{
2785 if (!out_list) 2979 if (!out_list) {
2786 return 0; 2980 return 0;
2981 }
2787 2982
2788 if (m->numfriends == 0) { 2983 if (m->numfriends == 0) {
2789 return 0; 2984 return 0;
diff --git a/toxcore/TCP_client.c b/toxcore/TCP_client.c
index 824e5dd1..641760ae 100644
--- a/toxcore/TCP_client.c
+++ b/toxcore/TCP_client.c
@@ -148,11 +148,13 @@ static int socks5_read_handshake_response(TCP_Client_Connection *TCP_conn)
148 uint8_t data[2]; 148 uint8_t data[2];
149 int ret = read_TCP_packet(TCP_conn->sock, data, sizeof(data)); 149 int ret = read_TCP_packet(TCP_conn->sock, data, sizeof(data));
150 150
151 if (ret == -1) 151 if (ret == -1) {
152 return 0; 152 return 0;
153 }
153 154
154 if (data[0] == 5 && data[1] == 0) // FIXME magic numbers 155 if (data[0] == 5 && data[1] == 0) { // FIXME magic numbers
155 return 1; 156 return 1;
157 }
156 158
157 return -1; 159 return -1;
158} 160}
@@ -193,21 +195,25 @@ static int proxy_socks5_read_connection_response(TCP_Client_Connection *TCP_conn
193 uint8_t data[4 + sizeof(IP4) + sizeof(uint16_t)]; 195 uint8_t data[4 + sizeof(IP4) + sizeof(uint16_t)];
194 int ret = read_TCP_packet(TCP_conn->sock, data, sizeof(data)); 196 int ret = read_TCP_packet(TCP_conn->sock, data, sizeof(data));
195 197
196 if (ret == -1) 198 if (ret == -1) {
197 return 0; 199 return 0;
200 }
198 201
199 if (data[0] == 5 && data[1] == 0) 202 if (data[0] == 5 && data[1] == 0) {
200 return 1; 203 return 1;
204 }
201 205
202 } else { 206 } else {
203 uint8_t data[4 + sizeof(IP6) + sizeof(uint16_t)]; 207 uint8_t data[4 + sizeof(IP6) + sizeof(uint16_t)];
204 int ret = read_TCP_packet(TCP_conn->sock, data, sizeof(data)); 208 int ret = read_TCP_packet(TCP_conn->sock, data, sizeof(data));
205 209
206 if (ret == -1) 210 if (ret == -1) {
207 return 0; 211 return 0;
212 }
208 213
209 if (data[0] == 5 && data[1] == 0) 214 if (data[0] == 5 && data[1] == 0) {
210 return 1; 215 return 1;
216 }
211 } 217 }
212 218
213 return -1; 219 return -1;
@@ -227,8 +233,9 @@ static int generate_handshake(TCP_Client_Connection *TCP_conn)
227 int len = encrypt_data_symmetric(TCP_conn->shared_key, TCP_conn->last_packet + crypto_box_PUBLICKEYBYTES, plain, 233 int len = encrypt_data_symmetric(TCP_conn->shared_key, TCP_conn->last_packet + crypto_box_PUBLICKEYBYTES, plain,
228 sizeof(plain), TCP_conn->last_packet + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES); 234 sizeof(plain), TCP_conn->last_packet + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
229 235
230 if (len != sizeof(plain) + crypto_box_MACBYTES) 236 if (len != sizeof(plain) + crypto_box_MACBYTES) {
231 return -1; 237 return -1;
238 }
232 239
233 TCP_conn->last_packet_length = crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + sizeof(plain) + crypto_box_MACBYTES; 240 TCP_conn->last_packet_length = crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + sizeof(plain) + crypto_box_MACBYTES;
234 TCP_conn->last_packet_sent = 0; 241 TCP_conn->last_packet_sent = 0;
@@ -246,8 +253,9 @@ static int handle_handshake(TCP_Client_Connection *TCP_conn, const uint8_t *data
246 int len = decrypt_data_symmetric(TCP_conn->shared_key, data, data + crypto_box_NONCEBYTES, 253 int len = decrypt_data_symmetric(TCP_conn->shared_key, data, data + crypto_box_NONCEBYTES,
247 TCP_SERVER_HANDSHAKE_SIZE - crypto_box_NONCEBYTES, plain); 254 TCP_SERVER_HANDSHAKE_SIZE - crypto_box_NONCEBYTES, plain);
248 255
249 if (len != sizeof(plain)) 256 if (len != sizeof(plain)) {
250 return -1; 257 return -1;
258 }
251 259
252 memcpy(TCP_conn->recv_nonce, plain + crypto_box_PUBLICKEYBYTES, crypto_box_NONCEBYTES); 260 memcpy(TCP_conn->recv_nonce, plain + crypto_box_PUBLICKEYBYTES, crypto_box_NONCEBYTES);
253 encrypt_precompute(plain, TCP_conn->temp_secret_key, TCP_conn->shared_key); 261 encrypt_precompute(plain, TCP_conn->temp_secret_key, TCP_conn->shared_key);
@@ -267,8 +275,9 @@ static int send_pending_data_nonpriority(TCP_Client_Connection *con)
267 uint16_t left = con->last_packet_length - con->last_packet_sent; 275 uint16_t left = con->last_packet_length - con->last_packet_sent;
268 int len = send(con->sock, con->last_packet + con->last_packet_sent, left, MSG_NOSIGNAL); 276 int len = send(con->sock, con->last_packet + con->last_packet_sent, left, MSG_NOSIGNAL);
269 277
270 if (len <= 0) 278 if (len <= 0) {
271 return -1; 279 return -1;
280 }
272 281
273 if (len == left) { 282 if (len == left) {
274 con->last_packet_length = 0; 283 con->last_packet_length = 0;
@@ -365,8 +374,9 @@ static void wipe_priority_list(TCP_Client_Connection *con)
365static int write_packet_TCP_secure_connection(TCP_Client_Connection *con, const uint8_t *data, uint16_t length, 374static int write_packet_TCP_secure_connection(TCP_Client_Connection *con, const uint8_t *data, uint16_t length,
366 _Bool priority) 375 _Bool priority)
367{ 376{
368 if (length + crypto_box_MACBYTES > MAX_PACKET_SIZE) 377 if (length + crypto_box_MACBYTES > MAX_PACKET_SIZE) {
369 return -1; 378 return -1;
379 }
370 380
371 _Bool sendpriority = 1; 381 _Bool sendpriority = 1;
372 382
@@ -384,8 +394,9 @@ static int write_packet_TCP_secure_connection(TCP_Client_Connection *con, const
384 memcpy(packet, &c_length, sizeof(uint16_t)); 394 memcpy(packet, &c_length, sizeof(uint16_t));
385 int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t)); 395 int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t));
386 396
387 if ((unsigned int)len != (sizeof(packet) - sizeof(uint16_t))) 397 if ((unsigned int)len != (sizeof(packet) - sizeof(uint16_t))) {
388 return -1; 398 return -1;
399 }
389 400
390 if (priority) { 401 if (priority) {
391 len = sendpriority ? send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL) : 0; 402 len = sendpriority ? send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL) : 0;
@@ -405,13 +416,15 @@ static int write_packet_TCP_secure_connection(TCP_Client_Connection *con, const
405 416
406 len = send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL); 417 len = send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL);
407 418
408 if (len <= 0) 419 if (len <= 0) {
409 return 0; 420 return 0;
421 }
410 422
411 increment_nonce(con->sent_nonce); 423 increment_nonce(con->sent_nonce);
412 424
413 if ((unsigned int)len == sizeof(packet)) 425 if ((unsigned int)len == sizeof(packet)) {
414 return 1; 426 return 1;
427 }
415 428
416 memcpy(con->last_packet, packet, sizeof(packet)); 429 memcpy(con->last_packet, packet, sizeof(packet));
417 con->last_packet_length = sizeof(packet); 430 con->last_packet_length = sizeof(packet);
@@ -454,14 +467,17 @@ static int send_ping_request(TCP_Client_Connection *con);
454 */ 467 */
455int send_data(TCP_Client_Connection *con, uint8_t con_id, const uint8_t *data, uint16_t length) 468int send_data(TCP_Client_Connection *con, uint8_t con_id, const uint8_t *data, uint16_t length)
456{ 469{
457 if (con_id >= NUM_CLIENT_CONNECTIONS) 470 if (con_id >= NUM_CLIENT_CONNECTIONS) {
458 return -1; 471 return -1;
472 }
459 473
460 if (con->connections[con_id].status != 2) 474 if (con->connections[con_id].status != 2) {
461 return -1; 475 return -1;
476 }
462 477
463 if (send_ping_response(con) == 0 || send_ping_request(con) == 0) 478 if (send_ping_response(con) == 0 || send_ping_request(con) == 0) {
464 return 0; 479 return 0;
480 }
465 481
466 uint8_t packet[1 + length]; 482 uint8_t packet[1 + length];
467 packet[0] = con_id + NUM_RESERVED_PORTS; 483 packet[0] = con_id + NUM_RESERVED_PORTS;
@@ -475,8 +491,9 @@ int send_data(TCP_Client_Connection *con, uint8_t con_id, const uint8_t *data, u
475 */ 491 */
476int send_oob_packet(TCP_Client_Connection *con, const uint8_t *public_key, const uint8_t *data, uint16_t length) 492int send_oob_packet(TCP_Client_Connection *con, const uint8_t *public_key, const uint8_t *data, uint16_t length)
477{ 493{
478 if (length == 0 || length > TCP_MAX_OOB_DATA_LENGTH) 494 if (length == 0 || length > TCP_MAX_OOB_DATA_LENGTH) {
479 return -1; 495 return -1;
496 }
480 497
481 uint8_t packet[1 + crypto_box_PUBLICKEYBYTES + length]; 498 uint8_t packet[1 + crypto_box_PUBLICKEYBYTES + length];
482 packet[0] = TCP_PACKET_OOB_SEND; 499 packet[0] = TCP_PACKET_OOB_SEND;
@@ -495,11 +512,13 @@ int send_oob_packet(TCP_Client_Connection *con, const uint8_t *public_key, const
495 */ 512 */
496int set_tcp_connection_number(TCP_Client_Connection *con, uint8_t con_id, uint32_t number) 513int set_tcp_connection_number(TCP_Client_Connection *con, uint8_t con_id, uint32_t number)
497{ 514{
498 if (con_id >= NUM_CLIENT_CONNECTIONS) 515 if (con_id >= NUM_CLIENT_CONNECTIONS) {
499 return -1; 516 return -1;
517 }
500 518
501 if (con->connections[con_id].status == 0) 519 if (con->connections[con_id].status == 0) {
502 return -1; 520 return -1;
521 }
503 522
504 con->connections[con_id].number = number; 523 con->connections[con_id].number = number;
505 return 0; 524 return 0;
@@ -537,8 +556,9 @@ static int send_disconnect_notification(TCP_Client_Connection *con, uint8_t id)
537 */ 556 */
538static int send_ping_request(TCP_Client_Connection *con) 557static int send_ping_request(TCP_Client_Connection *con)
539{ 558{
540 if (!con->ping_request_id) 559 if (!con->ping_request_id) {
541 return 1; 560 return 1;
561 }
542 562
543 uint8_t packet[1 + sizeof(uint64_t)]; 563 uint8_t packet[1 + sizeof(uint64_t)];
544 packet[0] = TCP_PACKET_PING; 564 packet[0] = TCP_PACKET_PING;
@@ -558,8 +578,9 @@ static int send_ping_request(TCP_Client_Connection *con)
558 */ 578 */
559static int send_ping_response(TCP_Client_Connection *con) 579static int send_ping_response(TCP_Client_Connection *con)
560{ 580{
561 if (!con->ping_response_id) 581 if (!con->ping_response_id) {
562 return 1; 582 return 1;
583 }
563 584
564 uint8_t packet[1 + sizeof(uint64_t)]; 585 uint8_t packet[1 + sizeof(uint64_t)];
565 packet[0] = TCP_PACKET_PONG; 586 packet[0] = TCP_PACKET_PONG;
@@ -579,8 +600,9 @@ static int send_ping_response(TCP_Client_Connection *con)
579 */ 600 */
580int send_disconnect_request(TCP_Client_Connection *con, uint8_t con_id) 601int send_disconnect_request(TCP_Client_Connection *con, uint8_t con_id)
581{ 602{
582 if (con_id >= NUM_CLIENT_CONNECTIONS) 603 if (con_id >= NUM_CLIENT_CONNECTIONS) {
583 return -1; 604 return -1;
605 }
584 606
585 con->connections[con_id].status = 0; 607 con->connections[con_id].status = 0;
586 con->connections[con_id].number = 0; 608 con->connections[con_id].number = 0;
@@ -615,8 +637,9 @@ TCP_Client_Connection *new_TCP_connection(IP_Port ip_port, const uint8_t *public
615 return NULL; 637 return NULL;
616 } 638 }
617 639
618 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) 640 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) {
619 return NULL; 641 return NULL;
642 }
620 643
621 uint8_t family = ip_port.ip.family; 644 uint8_t family = ip_port.ip.family;
622 645
@@ -694,80 +717,95 @@ TCP_Client_Connection *new_TCP_connection(IP_Port ip_port, const uint8_t *public
694 */ 717 */
695static int handle_TCP_packet(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length, void *userdata) 718static int handle_TCP_packet(TCP_Client_Connection *conn, const uint8_t *data, uint16_t length, void *userdata)
696{ 719{
697 if (length <= 1) 720 if (length <= 1) {
698 return -1; 721 return -1;
722 }
699 723
700 switch (data[0]) { 724 switch (data[0]) {
701 case TCP_PACKET_ROUTING_RESPONSE: { 725 case TCP_PACKET_ROUTING_RESPONSE: {
702 if (length != 1 + 1 + crypto_box_PUBLICKEYBYTES) 726 if (length != 1 + 1 + crypto_box_PUBLICKEYBYTES) {
703 return -1; 727 return -1;
728 }
704 729
705 if (data[1] < NUM_RESERVED_PORTS) 730 if (data[1] < NUM_RESERVED_PORTS) {
706 return 0; 731 return 0;
732 }
707 733
708 uint8_t con_id = data[1] - NUM_RESERVED_PORTS; 734 uint8_t con_id = data[1] - NUM_RESERVED_PORTS;
709 735
710 if (conn->connections[con_id].status != 0) 736 if (conn->connections[con_id].status != 0) {
711 return 0; 737 return 0;
738 }
712 739
713 conn->connections[con_id].status = 1; 740 conn->connections[con_id].status = 1;
714 conn->connections[con_id].number = ~0; 741 conn->connections[con_id].number = ~0;
715 memcpy(conn->connections[con_id].public_key, data + 2, crypto_box_PUBLICKEYBYTES); 742 memcpy(conn->connections[con_id].public_key, data + 2, crypto_box_PUBLICKEYBYTES);
716 743
717 if (conn->response_callback) 744 if (conn->response_callback) {
718 conn->response_callback(conn->response_callback_object, con_id, conn->connections[con_id].public_key); 745 conn->response_callback(conn->response_callback_object, con_id, conn->connections[con_id].public_key);
746 }
719 747
720 return 0; 748 return 0;
721 } 749 }
722 750
723 case TCP_PACKET_CONNECTION_NOTIFICATION: { 751 case TCP_PACKET_CONNECTION_NOTIFICATION: {
724 if (length != 1 + 1) 752 if (length != 1 + 1) {
725 return -1; 753 return -1;
754 }
726 755
727 if (data[1] < NUM_RESERVED_PORTS) 756 if (data[1] < NUM_RESERVED_PORTS) {
728 return -1; 757 return -1;
758 }
729 759
730 uint8_t con_id = data[1] - NUM_RESERVED_PORTS; 760 uint8_t con_id = data[1] - NUM_RESERVED_PORTS;
731 761
732 if (conn->connections[con_id].status != 1) 762 if (conn->connections[con_id].status != 1) {
733 return 0; 763 return 0;
764 }
734 765
735 conn->connections[con_id].status = 2; 766 conn->connections[con_id].status = 2;
736 767
737 if (conn->status_callback) 768 if (conn->status_callback) {
738 conn->status_callback(conn->status_callback_object, conn->connections[con_id].number, con_id, 769 conn->status_callback(conn->status_callback_object, conn->connections[con_id].number, con_id,
739 conn->connections[con_id].status); 770 conn->connections[con_id].status);
771 }
740 772
741 return 0; 773 return 0;
742 } 774 }
743 775
744 case TCP_PACKET_DISCONNECT_NOTIFICATION: { 776 case TCP_PACKET_DISCONNECT_NOTIFICATION: {
745 if (length != 1 + 1) 777 if (length != 1 + 1) {
746 return -1; 778 return -1;
779 }
747 780
748 if (data[1] < NUM_RESERVED_PORTS) 781 if (data[1] < NUM_RESERVED_PORTS) {
749 return -1; 782 return -1;
783 }
750 784
751 uint8_t con_id = data[1] - NUM_RESERVED_PORTS; 785 uint8_t con_id = data[1] - NUM_RESERVED_PORTS;
752 786
753 if (conn->connections[con_id].status == 0) 787 if (conn->connections[con_id].status == 0) {
754 return 0; 788 return 0;
789 }
755 790
756 if (conn->connections[con_id].status != 2) 791 if (conn->connections[con_id].status != 2) {
757 return 0; 792 return 0;
793 }
758 794
759 conn->connections[con_id].status = 1; 795 conn->connections[con_id].status = 1;
760 796
761 if (conn->status_callback) 797 if (conn->status_callback) {
762 conn->status_callback(conn->status_callback_object, conn->connections[con_id].number, con_id, 798 conn->status_callback(conn->status_callback_object, conn->connections[con_id].number, con_id,
763 conn->connections[con_id].status); 799 conn->connections[con_id].status);
800 }
764 801
765 return 0; 802 return 0;
766 } 803 }
767 804
768 case TCP_PACKET_PING: { 805 case TCP_PACKET_PING: {
769 if (length != 1 + sizeof(uint64_t)) 806 if (length != 1 + sizeof(uint64_t)) {
770 return -1; 807 return -1;
808 }
771 809
772 uint64_t ping_id; 810 uint64_t ping_id;
773 memcpy(&ping_id, data + 1, sizeof(uint64_t)); 811 memcpy(&ping_id, data + 1, sizeof(uint64_t));
@@ -777,8 +815,9 @@ static int handle_TCP_packet(TCP_Client_Connection *conn, const uint8_t *data, u
777 } 815 }
778 816
779 case TCP_PACKET_PONG: { 817 case TCP_PACKET_PONG: {
780 if (length != 1 + sizeof(uint64_t)) 818 if (length != 1 + sizeof(uint64_t)) {
781 return -1; 819 return -1;
820 }
782 821
783 uint64_t ping_id; 822 uint64_t ping_id;
784 memcpy(&ping_id, data + 1, sizeof(uint64_t)); 823 memcpy(&ping_id, data + 1, sizeof(uint64_t));
@@ -795,12 +834,14 @@ static int handle_TCP_packet(TCP_Client_Connection *conn, const uint8_t *data, u
795 } 834 }
796 835
797 case TCP_PACKET_OOB_RECV: { 836 case TCP_PACKET_OOB_RECV: {
798 if (length <= 1 + crypto_box_PUBLICKEYBYTES) 837 if (length <= 1 + crypto_box_PUBLICKEYBYTES) {
799 return -1; 838 return -1;
839 }
800 840
801 if (conn->oob_data_callback) 841 if (conn->oob_data_callback) {
802 conn->oob_data_callback(conn->oob_data_callback_object, data + 1, data + 1 + crypto_box_PUBLICKEYBYTES, 842 conn->oob_data_callback(conn->oob_data_callback_object, data + 1, data + 1 + crypto_box_PUBLICKEYBYTES,
803 length - (1 + crypto_box_PUBLICKEYBYTES), userdata); 843 length - (1 + crypto_box_PUBLICKEYBYTES), userdata);
844 }
804 845
805 return 0; 846 return 0;
806 } 847 }
@@ -811,14 +852,16 @@ static int handle_TCP_packet(TCP_Client_Connection *conn, const uint8_t *data, u
811 } 852 }
812 853
813 default: { 854 default: {
814 if (data[0] < NUM_RESERVED_PORTS) 855 if (data[0] < NUM_RESERVED_PORTS) {
815 return -1; 856 return -1;
857 }
816 858
817 uint8_t con_id = data[0] - NUM_RESERVED_PORTS; 859 uint8_t con_id = data[0] - NUM_RESERVED_PORTS;
818 860
819 if (conn->data_callback) 861 if (conn->data_callback) {
820 conn->data_callback(conn->data_callback_object, conn->connections[con_id].number, con_id, data + 1, length - 1, 862 conn->data_callback(conn->data_callback_object, conn->connections[con_id].number, con_id, data + 1, length - 1,
821 userdata); 863 userdata);
864 }
822 } 865 }
823 } 866 }
824 867
@@ -837,8 +880,9 @@ static int do_confirmed_TCP(TCP_Client_Connection *conn, void *userdata)
837 if (is_timeout(conn->last_pinged, TCP_PING_FREQUENCY)) { 880 if (is_timeout(conn->last_pinged, TCP_PING_FREQUENCY)) {
838 uint64_t ping_id = random_64b(); 881 uint64_t ping_id = random_64b();
839 882
840 if (!ping_id) 883 if (!ping_id) {
841 ++ping_id; 884 ++ping_id;
885 }
842 886
843 conn->ping_request_id = conn->ping_id = ping_id; 887 conn->ping_request_id = conn->ping_id = ping_id;
844 send_ping_request(conn); 888 send_ping_request(conn);
@@ -958,8 +1002,9 @@ void do_TCP_connection(TCP_Client_Connection *TCP_connection, void *userdata)
958 */ 1002 */
959void kill_TCP_connection(TCP_Client_Connection *TCP_connection) 1003void kill_TCP_connection(TCP_Client_Connection *TCP_connection)
960{ 1004{
961 if (TCP_connection == NULL) 1005 if (TCP_connection == NULL) {
962 return; 1006 return;
1007 }
963 1008
964 wipe_priority_list(TCP_connection); 1009 wipe_priority_list(TCP_connection);
965 kill_sock(TCP_connection->sock); 1010 kill_sock(TCP_connection->sock);
diff --git a/toxcore/TCP_connection.c b/toxcore/TCP_connection.c
index d564762a..786cb164 100644
--- a/toxcore/TCP_connection.c
+++ b/toxcore/TCP_connection.c
@@ -41,14 +41,17 @@
41 */ 41 */
42static _Bool connections_number_not_valid(const TCP_Connections *tcp_c, int connections_number) 42static _Bool connections_number_not_valid(const TCP_Connections *tcp_c, int connections_number)
43{ 43{
44 if ((unsigned int)connections_number >= tcp_c->connections_length) 44 if ((unsigned int)connections_number >= tcp_c->connections_length) {
45 return 1; 45 return 1;
46 }
46 47
47 if (tcp_c->connections == NULL) 48 if (tcp_c->connections == NULL) {
48 return 1; 49 return 1;
50 }
49 51
50 if (tcp_c->connections[connections_number].status == TCP_CONN_NONE) 52 if (tcp_c->connections[connections_number].status == TCP_CONN_NONE) {
51 return 1; 53 return 1;
54 }
52 55
53 return 0; 56 return 0;
54} 57}
@@ -58,14 +61,17 @@ static _Bool connections_number_not_valid(const TCP_Connections *tcp_c, int conn
58 */ 61 */
59static _Bool tcp_connections_number_not_valid(const TCP_Connections *tcp_c, int tcp_connections_number) 62static _Bool tcp_connections_number_not_valid(const TCP_Connections *tcp_c, int tcp_connections_number)
60{ 63{
61 if ((unsigned int)tcp_connections_number >= tcp_c->tcp_connections_length) 64 if ((unsigned int)tcp_connections_number >= tcp_c->tcp_connections_length) {
62 return 1; 65 return 1;
66 }
63 67
64 if (tcp_c->tcp_connections == NULL) 68 if (tcp_c->tcp_connections == NULL) {
65 return 1; 69 return 1;
70 }
66 71
67 if (tcp_c->tcp_connections[tcp_connections_number].status == TCP_CONN_NONE) 72 if (tcp_c->tcp_connections[tcp_connections_number].status == TCP_CONN_NONE) {
68 return 1; 73 return 1;
74 }
69 75
70 return 0; 76 return 0;
71} 77}
@@ -80,8 +86,9 @@ static int create_connection(TCP_Connections *tcp_c)
80 uint32_t i; 86 uint32_t i;
81 87
82 for (i = 0; i < tcp_c->connections_length; ++i) { 88 for (i = 0; i < tcp_c->connections_length; ++i) {
83 if (tcp_c->connections[i].status == TCP_CONN_NONE) 89 if (tcp_c->connections[i].status == TCP_CONN_NONE) {
84 return i; 90 return i;
91 }
85 } 92 }
86 93
87 int id = -1; 94 int id = -1;
@@ -108,8 +115,9 @@ static int create_tcp_connection(TCP_Connections *tcp_c)
108 uint32_t i; 115 uint32_t i;
109 116
110 for (i = 0; i < tcp_c->tcp_connections_length; ++i) { 117 for (i = 0; i < tcp_c->tcp_connections_length; ++i) {
111 if (tcp_c->tcp_connections[i].status == TCP_CONN_NONE) 118 if (tcp_c->tcp_connections[i].status == TCP_CONN_NONE) {
112 return i; 119 return i;
120 }
113 } 121 }
114 122
115 int id = -1; 123 int id = -1;
@@ -132,15 +140,17 @@ static int create_tcp_connection(TCP_Connections *tcp_c)
132 */ 140 */
133static int wipe_connection(TCP_Connections *tcp_c, int connections_number) 141static int wipe_connection(TCP_Connections *tcp_c, int connections_number)
134{ 142{
135 if (connections_number_not_valid(tcp_c, connections_number)) 143 if (connections_number_not_valid(tcp_c, connections_number)) {
136 return -1; 144 return -1;
145 }
137 146
138 uint32_t i; 147 uint32_t i;
139 memset(&(tcp_c->connections[connections_number]), 0 , sizeof(TCP_Connection_to)); 148 memset(&(tcp_c->connections[connections_number]), 0 , sizeof(TCP_Connection_to));
140 149
141 for (i = tcp_c->connections_length; i != 0; --i) { 150 for (i = tcp_c->connections_length; i != 0; --i) {
142 if (tcp_c->connections[i - 1].status != TCP_CONN_NONE) 151 if (tcp_c->connections[i - 1].status != TCP_CONN_NONE) {
143 break; 152 break;
153 }
144 } 154 }
145 155
146 if (tcp_c->connections_length != i) { 156 if (tcp_c->connections_length != i) {
@@ -159,15 +169,17 @@ static int wipe_connection(TCP_Connections *tcp_c, int connections_number)
159 */ 169 */
160static int wipe_tcp_connection(TCP_Connections *tcp_c, int tcp_connections_number) 170static int wipe_tcp_connection(TCP_Connections *tcp_c, int tcp_connections_number)
161{ 171{
162 if (tcp_connections_number_not_valid(tcp_c, tcp_connections_number)) 172 if (tcp_connections_number_not_valid(tcp_c, tcp_connections_number)) {
163 return -1; 173 return -1;
174 }
164 175
165 uint32_t i; 176 uint32_t i;
166 memset(&(tcp_c->tcp_connections[tcp_connections_number]), 0 , sizeof(TCP_con)); 177 memset(&(tcp_c->tcp_connections[tcp_connections_number]), 0 , sizeof(TCP_con));
167 178
168 for (i = tcp_c->tcp_connections_length; i != 0; --i) { 179 for (i = tcp_c->tcp_connections_length; i != 0; --i) {
169 if (tcp_c->tcp_connections[i - 1].status != TCP_CONN_NONE) 180 if (tcp_c->tcp_connections[i - 1].status != TCP_CONN_NONE) {
170 break; 181 break;
182 }
171 } 183 }
172 184
173 if (tcp_c->tcp_connections_length != i) { 185 if (tcp_c->tcp_connections_length != i) {
@@ -181,16 +193,18 @@ static int wipe_tcp_connection(TCP_Connections *tcp_c, int tcp_connections_numbe
181 193
182static TCP_Connection_to *get_connection(const TCP_Connections *tcp_c, int connections_number) 194static TCP_Connection_to *get_connection(const TCP_Connections *tcp_c, int connections_number)
183{ 195{
184 if (connections_number_not_valid(tcp_c, connections_number)) 196 if (connections_number_not_valid(tcp_c, connections_number)) {
185 return 0; 197 return 0;
198 }
186 199
187 return &tcp_c->connections[connections_number]; 200 return &tcp_c->connections[connections_number];
188} 201}
189 202
190static TCP_con *get_tcp_connection(const TCP_Connections *tcp_c, int tcp_connections_number) 203static TCP_con *get_tcp_connection(const TCP_Connections *tcp_c, int tcp_connections_number)
191{ 204{
192 if (tcp_connections_number_not_valid(tcp_c, tcp_connections_number)) 205 if (tcp_connections_number_not_valid(tcp_c, tcp_connections_number)) {
193 return 0; 206 return 0;
207 }
194 208
195 return &tcp_c->tcp_connections[tcp_connections_number]; 209 return &tcp_c->tcp_connections[tcp_connections_number];
196} 210}
@@ -312,8 +326,9 @@ int tcp_send_onion_request(TCP_Connections *tcp_c, unsigned int tcp_connections_
312 if (tcp_c->tcp_connections[tcp_connections_number].status == TCP_CONN_CONNECTED) { 326 if (tcp_c->tcp_connections[tcp_connections_number].status == TCP_CONN_CONNECTED) {
313 int ret = send_onion_request(tcp_c->tcp_connections[tcp_connections_number].connection, data, length); 327 int ret = send_onion_request(tcp_c->tcp_connections[tcp_connections_number].connection, data, length);
314 328
315 if (ret == 1) 329 if (ret == 1) {
316 return 0; 330 return 0;
331 }
317 } 332 }
318 333
319 return -1; 334 return -1;
@@ -329,16 +344,19 @@ int tcp_send_oob_packet(TCP_Connections *tcp_c, unsigned int tcp_connections_num
329{ 344{
330 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 345 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
331 346
332 if (!tcp_con) 347 if (!tcp_con) {
333 return -1; 348 return -1;
349 }
334 350
335 if (tcp_con->status != TCP_CONN_CONNECTED) 351 if (tcp_con->status != TCP_CONN_CONNECTED) {
336 return -1; 352 return -1;
353 }
337 354
338 int ret = send_oob_packet(tcp_con->connection, public_key, packet, length); 355 int ret = send_oob_packet(tcp_con->connection, public_key, packet, length);
339 356
340 if (ret == 1) 357 if (ret == 1) {
341 return 0; 358 return 0;
359 }
342 360
343 return -1; 361 return -1;
344} 362}
@@ -432,13 +450,15 @@ static int find_tcp_connection_relay(TCP_Connections *tcp_c, const uint8_t *rela
432 */ 450 */
433int new_tcp_connection_to(TCP_Connections *tcp_c, const uint8_t *public_key, int id) 451int new_tcp_connection_to(TCP_Connections *tcp_c, const uint8_t *public_key, int id)
434{ 452{
435 if (find_tcp_connection_to(tcp_c, public_key) != -1) 453 if (find_tcp_connection_to(tcp_c, public_key) != -1) {
436 return -1; 454 return -1;
455 }
437 456
438 int connections_number = create_connection(tcp_c); 457 int connections_number = create_connection(tcp_c);
439 458
440 if (connections_number == -1) 459 if (connections_number == -1) {
441 return -1; 460 return -1;
461 }
442 462
443 TCP_Connection_to *con_to = &tcp_c->connections[connections_number]; 463 TCP_Connection_to *con_to = &tcp_c->connections[connections_number];
444 464
@@ -456,8 +476,9 @@ int kill_tcp_connection_to(TCP_Connections *tcp_c, int connections_number)
456{ 476{
457 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number); 477 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);
458 478
459 if (!con_to) 479 if (!con_to) {
460 return -1; 480 return -1;
481 }
461 482
462 unsigned int i; 483 unsigned int i;
463 484
@@ -466,8 +487,9 @@ int kill_tcp_connection_to(TCP_Connections *tcp_c, int connections_number)
466 unsigned int tcp_connections_number = con_to->connections[i].tcp_connection - 1; 487 unsigned int tcp_connections_number = con_to->connections[i].tcp_connection - 1;
467 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 488 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
468 489
469 if (!tcp_con) 490 if (!tcp_con) {
470 continue; 491 continue;
492 }
471 493
472 if (tcp_con->status == TCP_CONN_CONNECTED) { 494 if (tcp_con->status == TCP_CONN_CONNECTED) {
473 send_disconnect_request(tcp_con->connection, con_to->connections[i].connection_id); 495 send_disconnect_request(tcp_con->connection, con_to->connections[i].connection_id);
@@ -500,13 +522,15 @@ int set_tcp_connection_to_status(TCP_Connections *tcp_c, int connections_number,
500{ 522{
501 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number); 523 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);
502 524
503 if (!con_to) 525 if (!con_to) {
504 return -1; 526 return -1;
527 }
505 528
506 if (status) { 529 if (status) {
507 /* Conection is unsleeping. */ 530 /* Conection is unsleeping. */
508 if (con_to->status != TCP_CONN_SLEEPING) 531 if (con_to->status != TCP_CONN_SLEEPING) {
509 return -1; 532 return -1;
533 }
510 534
511 unsigned int i; 535 unsigned int i;
512 536
@@ -515,8 +539,9 @@ int set_tcp_connection_to_status(TCP_Connections *tcp_c, int connections_number,
515 unsigned int tcp_connections_number = con_to->connections[i].tcp_connection - 1; 539 unsigned int tcp_connections_number = con_to->connections[i].tcp_connection - 1;
516 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 540 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
517 541
518 if (!tcp_con) 542 if (!tcp_con) {
519 continue; 543 continue;
544 }
520 545
521 if (tcp_con->status == TCP_CONN_SLEEPING) { 546 if (tcp_con->status == TCP_CONN_SLEEPING) {
522 tcp_con->unsleep = 1; 547 tcp_con->unsleep = 1;
@@ -528,8 +553,9 @@ int set_tcp_connection_to_status(TCP_Connections *tcp_c, int connections_number,
528 return 0; 553 return 0;
529 } else { 554 } else {
530 /* Conection is going to sleep. */ 555 /* Conection is going to sleep. */
531 if (con_to->status != TCP_CONN_VALID) 556 if (con_to->status != TCP_CONN_VALID) {
532 return -1; 557 return -1;
558 }
533 559
534 unsigned int i; 560 unsigned int i;
535 561
@@ -538,8 +564,9 @@ int set_tcp_connection_to_status(TCP_Connections *tcp_c, int connections_number,
538 unsigned int tcp_connections_number = con_to->connections[i].tcp_connection - 1; 564 unsigned int tcp_connections_number = con_to->connections[i].tcp_connection - 1;
539 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 565 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
540 566
541 if (!tcp_con) 567 if (!tcp_con) {
542 continue; 568 continue;
569 }
543 570
544 if (con_to->connections[i].status == TCP_CONNECTIONS_STATUS_ONLINE) { 571 if (con_to->connections[i].status == TCP_CONNECTIONS_STATUS_ONLINE) {
545 ++tcp_con->sleep_count; 572 ++tcp_con->sleep_count;
@@ -572,8 +599,9 @@ static int add_tcp_connection_to_conn(TCP_Connection_to *con_to, unsigned int tc
572{ 599{
573 unsigned int i; 600 unsigned int i;
574 601
575 if (tcp_connection_in_conn(con_to, tcp_connections_number)) 602 if (tcp_connection_in_conn(con_to, tcp_connections_number)) {
576 return -1; 603 return -1;
604 }
577 605
578 for (i = 0; i < MAX_FRIEND_TCP_CONNECTIONS; ++i) { 606 for (i = 0; i < MAX_FRIEND_TCP_CONNECTIONS; ++i) {
579 if (con_to->connections[i].tcp_connection == 0) { 607 if (con_to->connections[i].tcp_connection == 0) {
@@ -657,8 +685,9 @@ static int kill_tcp_relay_connection(TCP_Connections *tcp_c, int tcp_connections
657{ 685{
658 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 686 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
659 687
660 if (!tcp_con) 688 if (!tcp_con) {
661 return -1; 689 return -1;
690 }
662 691
663 unsigned int i; 692 unsigned int i;
664 693
@@ -683,11 +712,13 @@ static int reconnect_tcp_relay_connection(TCP_Connections *tcp_c, int tcp_connec
683{ 712{
684 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 713 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
685 714
686 if (!tcp_con) 715 if (!tcp_con) {
687 return -1; 716 return -1;
717 }
688 718
689 if (tcp_con->status == TCP_CONN_SLEEPING) 719 if (tcp_con->status == TCP_CONN_SLEEPING) {
690 return -1; 720 return -1;
721 }
691 722
692 IP_Port ip_port = tcp_con->connection->ip_port; 723 IP_Port ip_port = tcp_con->connection->ip_port;
693 uint8_t relay_pk[crypto_box_PUBLICKEYBYTES]; 724 uint8_t relay_pk[crypto_box_PUBLICKEYBYTES];
@@ -729,14 +760,17 @@ static int sleep_tcp_relay_connection(TCP_Connections *tcp_c, int tcp_connection
729{ 760{
730 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 761 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
731 762
732 if (!tcp_con) 763 if (!tcp_con) {
733 return -1; 764 return -1;
765 }
734 766
735 if (tcp_con->status != TCP_CONN_CONNECTED) 767 if (tcp_con->status != TCP_CONN_CONNECTED) {
736 return -1; 768 return -1;
769 }
737 770
738 if (tcp_con->lock_count != tcp_con->sleep_count) 771 if (tcp_con->lock_count != tcp_con->sleep_count) {
739 return -1; 772 return -1;
773 }
740 774
741 tcp_con->ip_port = tcp_con->connection->ip_port; 775 tcp_con->ip_port = tcp_con->connection->ip_port;
742 memcpy(tcp_con->relay_pk, tcp_con->connection->public_key, crypto_box_PUBLICKEYBYTES); 776 memcpy(tcp_con->relay_pk, tcp_con->connection->public_key, crypto_box_PUBLICKEYBYTES);
@@ -772,11 +806,13 @@ static int unsleep_tcp_relay_connection(TCP_Connections *tcp_c, int tcp_connecti
772{ 806{
773 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 807 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
774 808
775 if (!tcp_con) 809 if (!tcp_con) {
776 return -1; 810 return -1;
811 }
777 812
778 if (tcp_con->status != TCP_CONN_SLEEPING) 813 if (tcp_con->status != TCP_CONN_SLEEPING) {
779 return -1; 814 return -1;
815 }
780 816
781 tcp_con->connection = new_TCP_connection(tcp_con->ip_port, tcp_con->relay_pk, tcp_c->self_public_key, 817 tcp_con->connection = new_TCP_connection(tcp_con->ip_port, tcp_con->relay_pk, tcp_c->self_public_key,
782 tcp_c->self_secret_key, &tcp_c->proxy_info); 818 tcp_c->self_secret_key, &tcp_c->proxy_info);
@@ -803,14 +839,17 @@ static int send_tcp_relay_routing_request(TCP_Connections *tcp_c, int tcp_connec
803{ 839{
804 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 840 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
805 841
806 if (!tcp_con) 842 if (!tcp_con) {
807 return -1; 843 return -1;
844 }
808 845
809 if (tcp_con->status == TCP_CONN_SLEEPING) 846 if (tcp_con->status == TCP_CONN_SLEEPING) {
810 return -1; 847 return -1;
848 }
811 849
812 if (send_routing_request(tcp_con->connection, public_key) != 1) 850 if (send_routing_request(tcp_con->connection, public_key) != 1) {
813 return -1; 851 return -1;
852 }
814 853
815 return 0; 854 return 0;
816} 855}
@@ -823,21 +862,25 @@ static int tcp_response_callback(void *object, uint8_t connection_id, const uint
823 unsigned int tcp_connections_number = TCP_client_con->custom_uint; 862 unsigned int tcp_connections_number = TCP_client_con->custom_uint;
824 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 863 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
825 864
826 if (!tcp_con) 865 if (!tcp_con) {
827 return -1; 866 return -1;
867 }
828 868
829 int connections_number = find_tcp_connection_to(tcp_c, public_key); 869 int connections_number = find_tcp_connection_to(tcp_c, public_key);
830 870
831 if (connections_number == -1) 871 if (connections_number == -1) {
832 return -1; 872 return -1;
873 }
833 874
834 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number); 875 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);
835 876
836 if (con_to == NULL) 877 if (con_to == NULL) {
837 return -1; 878 return -1;
879 }
838 880
839 if (set_tcp_connection_status(con_to, tcp_connections_number, TCP_CONNECTIONS_STATUS_REGISTERED, connection_id) == -1) 881 if (set_tcp_connection_status(con_to, tcp_connections_number, TCP_CONNECTIONS_STATUS_REGISTERED, connection_id) == -1) {
840 return -1; 882 return -1;
883 }
841 884
842 set_tcp_connection_number(tcp_con->connection, connection_id, connections_number); 885 set_tcp_connection_number(tcp_con->connection, connection_id, connections_number);
843 886
@@ -853,12 +896,14 @@ static int tcp_status_callback(void *object, uint32_t number, uint8_t connection
853 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 896 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
854 TCP_Connection_to *con_to = get_connection(tcp_c, number); 897 TCP_Connection_to *con_to = get_connection(tcp_c, number);
855 898
856 if (!con_to || !tcp_con) 899 if (!con_to || !tcp_con) {
857 return -1; 900 return -1;
901 }
858 902
859 if (status == 1) { 903 if (status == 1) {
860 if (set_tcp_connection_status(con_to, tcp_connections_number, TCP_CONNECTIONS_STATUS_REGISTERED, connection_id) == -1) 904 if (set_tcp_connection_status(con_to, tcp_connections_number, TCP_CONNECTIONS_STATUS_REGISTERED, connection_id) == -1) {
861 return -1; 905 return -1;
906 }
862 907
863 --tcp_con->lock_count; 908 --tcp_con->lock_count;
864 909
@@ -866,8 +911,9 @@ static int tcp_status_callback(void *object, uint32_t number, uint8_t connection
866 --tcp_con->sleep_count; 911 --tcp_con->sleep_count;
867 } 912 }
868 } else if (status == 2) { 913 } else if (status == 2) {
869 if (set_tcp_connection_status(con_to, tcp_connections_number, TCP_CONNECTIONS_STATUS_ONLINE, connection_id) == -1) 914 if (set_tcp_connection_status(con_to, tcp_connections_number, TCP_CONNECTIONS_STATUS_ONLINE, connection_id) == -1) {
870 return -1; 915 return -1;
916 }
871 917
872 ++tcp_con->lock_count; 918 ++tcp_con->lock_count;
873 919
@@ -883,8 +929,9 @@ static int tcp_data_callback(void *object, uint32_t number, uint8_t connection_i
883 void *userdata) 929 void *userdata)
884{ 930{
885 931
886 if (length == 0) 932 if (length == 0) {
887 return -1; 933 return -1;
934 }
888 935
889 TCP_Client_Connection *TCP_client_con = object; 936 TCP_Client_Connection *TCP_client_con = object;
890 TCP_Connections *tcp_c = TCP_client_con->custom_object; 937 TCP_Connections *tcp_c = TCP_client_con->custom_object;
@@ -892,16 +939,19 @@ static int tcp_data_callback(void *object, uint32_t number, uint8_t connection_i
892 unsigned int tcp_connections_number = TCP_client_con->custom_uint; 939 unsigned int tcp_connections_number = TCP_client_con->custom_uint;
893 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 940 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
894 941
895 if (!tcp_con) 942 if (!tcp_con) {
896 return -1; 943 return -1;
944 }
897 945
898 TCP_Connection_to *con_to = get_connection(tcp_c, number); 946 TCP_Connection_to *con_to = get_connection(tcp_c, number);
899 947
900 if (!con_to) 948 if (!con_to) {
901 return -1; 949 return -1;
950 }
902 951
903 if (tcp_c->tcp_data_callback) 952 if (tcp_c->tcp_data_callback) {
904 tcp_c->tcp_data_callback(tcp_c->tcp_data_callback_object, con_to->id, data, length, userdata); 953 tcp_c->tcp_data_callback(tcp_c->tcp_data_callback_object, con_to->id, data, length, userdata);
954 }
905 955
906 return 0; 956 return 0;
907} 957}
@@ -909,8 +959,9 @@ static int tcp_data_callback(void *object, uint32_t number, uint8_t connection_i
909static int tcp_oob_callback(void *object, const uint8_t *public_key, const uint8_t *data, uint16_t length, 959static int tcp_oob_callback(void *object, const uint8_t *public_key, const uint8_t *data, uint16_t length,
910 void *userdata) 960 void *userdata)
911{ 961{
912 if (length == 0) 962 if (length == 0) {
913 return -1; 963 return -1;
964 }
914 965
915 TCP_Client_Connection *TCP_client_con = object; 966 TCP_Client_Connection *TCP_client_con = object;
916 TCP_Connections *tcp_c = TCP_client_con->custom_object; 967 TCP_Connections *tcp_c = TCP_client_con->custom_object;
@@ -918,8 +969,9 @@ static int tcp_oob_callback(void *object, const uint8_t *public_key, const uint8
918 unsigned int tcp_connections_number = TCP_client_con->custom_uint; 969 unsigned int tcp_connections_number = TCP_client_con->custom_uint;
919 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 970 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
920 971
921 if (!tcp_con) 972 if (!tcp_con) {
922 return -1; 973 return -1;
974 }
923 975
924 /* TODO: optimize */ 976 /* TODO: optimize */
925 int connections_number = find_tcp_connection_to(tcp_c, public_key); 977 int connections_number = find_tcp_connection_to(tcp_c, public_key);
@@ -929,8 +981,9 @@ static int tcp_oob_callback(void *object, const uint8_t *public_key, const uint8
929 if (con_to && tcp_connection_in_conn(con_to, tcp_connections_number)) { 981 if (con_to && tcp_connection_in_conn(con_to, tcp_connections_number)) {
930 return tcp_data_callback(object, connections_number, 0, data, length, userdata); 982 return tcp_data_callback(object, connections_number, 0, data, length, userdata);
931 } else { 983 } else {
932 if (tcp_c->tcp_oob_callback) 984 if (tcp_c->tcp_oob_callback) {
933 tcp_c->tcp_oob_callback(tcp_c->tcp_oob_callback_object, public_key, tcp_connections_number, data, length); 985 tcp_c->tcp_oob_callback(tcp_c->tcp_oob_callback_object, public_key, tcp_connections_number, data, length);
986 }
934 } 987 }
935 988
936 return 0; 989 return 0;
@@ -940,8 +993,9 @@ static int tcp_onion_callback(void *object, const uint8_t *data, uint16_t length
940{ 993{
941 TCP_Connections *tcp_c = object; 994 TCP_Connections *tcp_c = object;
942 995
943 if (tcp_c->tcp_onion_callback) 996 if (tcp_c->tcp_onion_callback) {
944 tcp_c->tcp_onion_callback(tcp_c->tcp_onion_callback_object, data, length, userdata); 997 tcp_c->tcp_onion_callback(tcp_c->tcp_onion_callback_object, data, length, userdata);
998 }
945 999
946 return 0; 1000 return 0;
947} 1001}
@@ -955,8 +1009,9 @@ static int tcp_relay_set_callbacks(TCP_Connections *tcp_c, int tcp_connections_n
955{ 1009{
956 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 1010 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
957 1011
958 if (!tcp_con) 1012 if (!tcp_con) {
959 return -1; 1013 return -1;
1014 }
960 1015
961 TCP_Client_Connection *con = tcp_con->connection; 1016 TCP_Client_Connection *con = tcp_con->connection;
962 1017
@@ -975,8 +1030,9 @@ static int tcp_relay_on_online(TCP_Connections *tcp_c, int tcp_connections_numbe
975{ 1030{
976 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 1031 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
977 1032
978 if (!tcp_con) 1033 if (!tcp_con) {
979 return -1; 1034 return -1;
1035 }
980 1036
981 unsigned int i, sent = 0; 1037 unsigned int i, sent = 0;
982 1038
@@ -1018,13 +1074,15 @@ static int add_tcp_relay_instance(TCP_Connections *tcp_c, IP_Port ip_port, const
1018 ip_port.ip.family = AF_INET6; 1074 ip_port.ip.family = AF_INET6;
1019 } 1075 }
1020 1076
1021 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) 1077 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) {
1022 return -1; 1078 return -1;
1079 }
1023 1080
1024 int tcp_connections_number = create_tcp_connection(tcp_c); 1081 int tcp_connections_number = create_tcp_connection(tcp_c);
1025 1082
1026 if (tcp_connections_number == -1) 1083 if (tcp_connections_number == -1) {
1027 return -1; 1084 return -1;
1085 }
1028 1086
1029 TCP_con *tcp_con = &tcp_c->tcp_connections[tcp_connections_number]; 1087 TCP_con *tcp_con = &tcp_c->tcp_connections[tcp_connections_number];
1030 1088
@@ -1032,8 +1090,9 @@ static int add_tcp_relay_instance(TCP_Connections *tcp_c, IP_Port ip_port, const
1032 tcp_con->connection = new_TCP_connection(ip_port, relay_pk, tcp_c->self_public_key, tcp_c->self_secret_key, 1090 tcp_con->connection = new_TCP_connection(ip_port, relay_pk, tcp_c->self_public_key, tcp_c->self_secret_key,
1033 &tcp_c->proxy_info); 1091 &tcp_c->proxy_info);
1034 1092
1035 if (!tcp_con->connection) 1093 if (!tcp_con->connection) {
1036 return -1; 1094 return -1;
1095 }
1037 1096
1038 tcp_con->status = TCP_CONN_VALID; 1097 tcp_con->status = TCP_CONN_VALID;
1039 1098
@@ -1049,11 +1108,13 @@ int add_tcp_relay_global(TCP_Connections *tcp_c, IP_Port ip_port, const uint8_t
1049{ 1108{
1050 int tcp_connections_number = find_tcp_connection_relay(tcp_c, relay_pk); 1109 int tcp_connections_number = find_tcp_connection_relay(tcp_c, relay_pk);
1051 1110
1052 if (tcp_connections_number != -1) 1111 if (tcp_connections_number != -1) {
1053 return -1; 1112 return -1;
1113 }
1054 1114
1055 if (add_tcp_relay_instance(tcp_c, ip_port, relay_pk) == -1) 1115 if (add_tcp_relay_instance(tcp_c, ip_port, relay_pk) == -1) {
1056 return -1; 1116 return -1;
1117 }
1057 1118
1058 return 0; 1119 return 0;
1059} 1120}
@@ -1067,20 +1128,23 @@ int add_tcp_number_relay_connection(TCP_Connections *tcp_c, int connections_numb
1067{ 1128{
1068 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number); 1129 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);
1069 1130
1070 if (!con_to) 1131 if (!con_to) {
1071 return -1; 1132 return -1;
1133 }
1072 1134
1073 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 1135 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
1074 1136
1075 if (!tcp_con) 1137 if (!tcp_con) {
1076 return -1; 1138 return -1;
1139 }
1077 1140
1078 if (con_to->status != TCP_CONN_SLEEPING && tcp_con->status == TCP_CONN_SLEEPING) { 1141 if (con_to->status != TCP_CONN_SLEEPING && tcp_con->status == TCP_CONN_SLEEPING) {
1079 tcp_con->unsleep = 1; 1142 tcp_con->unsleep = 1;
1080 } 1143 }
1081 1144
1082 if (add_tcp_connection_to_conn(con_to, tcp_connections_number) == -1) 1145 if (add_tcp_connection_to_conn(con_to, tcp_connections_number) == -1) {
1083 return -1; 1146 return -1;
1147 }
1084 1148
1085 if (tcp_con->status == TCP_CONN_CONNECTED) { 1149 if (tcp_con->status == TCP_CONN_CONNECTED) {
1086 if (send_tcp_relay_routing_request(tcp_c, tcp_connections_number, con_to->public_key) == 0) { 1150 if (send_tcp_relay_routing_request(tcp_c, tcp_connections_number, con_to->public_key) == 0) {
@@ -1102,8 +1166,9 @@ int add_tcp_relay_connection(TCP_Connections *tcp_c, int connections_number, IP_
1102{ 1166{
1103 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number); 1167 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);
1104 1168
1105 if (!con_to) 1169 if (!con_to) {
1106 return -1; 1170 return -1;
1171 }
1107 1172
1108 int tcp_connections_number = find_tcp_connection_relay(tcp_c, relay_pk); 1173 int tcp_connections_number = find_tcp_connection_relay(tcp_c, relay_pk);
1109 1174
@@ -1118,8 +1183,9 @@ int add_tcp_relay_connection(TCP_Connections *tcp_c, int connections_number, IP_
1118 1183
1119 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number); 1184 TCP_con *tcp_con = get_tcp_connection(tcp_c, tcp_connections_number);
1120 1185
1121 if (!tcp_con) 1186 if (!tcp_con) {
1122 return -1; 1187 return -1;
1188 }
1123 1189
1124 if (add_tcp_connection_to_conn(con_to, tcp_connections_number) == -1) { 1190 if (add_tcp_connection_to_conn(con_to, tcp_connections_number) == -1) {
1125 return -1; 1191 return -1;
@@ -1136,8 +1202,9 @@ unsigned int tcp_connection_to_online_tcp_relays(TCP_Connections *tcp_c, int con
1136{ 1202{
1137 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number); 1203 TCP_Connection_to *con_to = get_connection(tcp_c, connections_number);
1138 1204
1139 if (!con_to) 1205 if (!con_to) {
1140 return 0; 1206 return 0;
1207 }
1141 1208
1142 return online_tcp_connection_from_conn(con_to); 1209 return online_tcp_connection_from_conn(con_to);
1143} 1210}
@@ -1185,8 +1252,9 @@ unsigned int tcp_copy_connected_relays(TCP_Connections *tcp_c, Node_format *tcp_
1185 */ 1252 */
1186int set_tcp_onion_status(TCP_Connections *tcp_c, _Bool status) 1253int set_tcp_onion_status(TCP_Connections *tcp_c, _Bool status)
1187{ 1254{
1188 if (tcp_c->onion_status == status) 1255 if (tcp_c->onion_status == status) {
1189 return -1; 1256 return -1;
1257 }
1190 1258
1191 if (status) { 1259 if (status) {
1192 unsigned int i; 1260 unsigned int i;
@@ -1201,8 +1269,9 @@ int set_tcp_onion_status(TCP_Connections *tcp_c, _Bool status)
1201 } 1269 }
1202 } 1270 }
1203 1271
1204 if (tcp_c->onion_num_conns >= NUM_ONION_TCP_CONNECTIONS) 1272 if (tcp_c->onion_num_conns >= NUM_ONION_TCP_CONNECTIONS) {
1205 break; 1273 break;
1274 }
1206 } 1275 }
1207 1276
1208 if (tcp_c->onion_num_conns < NUM_ONION_TCP_CONNECTIONS) { 1277 if (tcp_c->onion_num_conns < NUM_ONION_TCP_CONNECTIONS) {
@@ -1217,8 +1286,9 @@ int set_tcp_onion_status(TCP_Connections *tcp_c, _Bool status)
1217 } 1286 }
1218 } 1287 }
1219 1288
1220 if (!wakeup) 1289 if (!wakeup) {
1221 break; 1290 break;
1291 }
1222 } 1292 }
1223 } 1293 }
1224 1294
@@ -1252,13 +1322,15 @@ int set_tcp_onion_status(TCP_Connections *tcp_c, _Bool status)
1252 */ 1322 */
1253TCP_Connections *new_tcp_connections(const uint8_t *secret_key, TCP_Proxy_Info *proxy_info) 1323TCP_Connections *new_tcp_connections(const uint8_t *secret_key, TCP_Proxy_Info *proxy_info)
1254{ 1324{
1255 if (secret_key == NULL) 1325 if (secret_key == NULL) {
1256 return NULL; 1326 return NULL;
1327 }
1257 1328
1258 TCP_Connections *temp = calloc(1, sizeof(TCP_Connections)); 1329 TCP_Connections *temp = calloc(1, sizeof(TCP_Connections));
1259 1330
1260 if (temp == NULL) 1331 if (temp == NULL) {
1261 return NULL; 1332 return NULL;
1333 }
1262 1334
1263 memcpy(temp->self_secret_key, secret_key, crypto_box_SECRETKEYBYTES); 1335 memcpy(temp->self_secret_key, secret_key, crypto_box_SECRETKEYBYTES);
1264 crypto_scalarmult_curve25519_base(temp->self_public_key, temp->self_secret_key); 1336 crypto_scalarmult_curve25519_base(temp->self_public_key, temp->self_secret_key);
@@ -1311,8 +1383,9 @@ static void do_tcp_conns(TCP_Connections *tcp_c, void *userdata)
1311 1383
1312static void kill_nonused_tcp(TCP_Connections *tcp_c) 1384static void kill_nonused_tcp(TCP_Connections *tcp_c)
1313{ 1385{
1314 if (tcp_c->tcp_connections_length == 0) 1386 if (tcp_c->tcp_connections_length == 0) {
1315 return; 1387 return;
1388 }
1316 1389
1317 unsigned int i, num_online = 0, num_kill = 0, to_kill[tcp_c->tcp_connections_length]; 1390 unsigned int i, num_online = 0, num_kill = 0, to_kill[tcp_c->tcp_connections_length];
1318 1391
@@ -1336,8 +1409,9 @@ static void kill_nonused_tcp(TCP_Connections *tcp_c)
1336 } else { 1409 } else {
1337 unsigned int n = num_online - RECOMMENDED_FRIEND_TCP_CONNECTIONS; 1410 unsigned int n = num_online - RECOMMENDED_FRIEND_TCP_CONNECTIONS;
1338 1411
1339 if (n < num_kill) 1412 if (n < num_kill) {
1340 num_kill = n; 1413 num_kill = n;
1414 }
1341 } 1415 }
1342 1416
1343 for (i = 0; i < num_kill; ++i) { 1417 for (i = 0; i < num_kill; ++i) {
diff --git a/toxcore/TCP_server.c b/toxcore/TCP_server.c
index d4944aed..d689e817 100644
--- a/toxcore/TCP_server.c
+++ b/toxcore/TCP_server.c
@@ -80,8 +80,9 @@ static int realloc_connection(TCP_Server *TCP_server, uint32_t num)
80 TCP_Secure_Connection *new_connections = realloc(TCP_server->accepted_connection_array, 80 TCP_Secure_Connection *new_connections = realloc(TCP_server->accepted_connection_array,
81 num * sizeof(TCP_Secure_Connection)); 81 num * sizeof(TCP_Secure_Connection));
82 82
83 if (new_connections == NULL) 83 if (new_connections == NULL) {
84 return -1; 84 return -1;
85 }
85 86
86 if (num > TCP_server->size_accepted_connections) { 87 if (num > TCP_server->size_accepted_connections) {
87 uint32_t old_size = TCP_server->size_accepted_connections; 88 uint32_t old_size = TCP_server->size_accepted_connections;
@@ -120,8 +121,9 @@ static int add_accepted(TCP_Server *TCP_server, const TCP_Secure_Connection *con
120 } 121 }
121 122
122 if (TCP_server->size_accepted_connections == TCP_server->num_accepted_connections) { 123 if (TCP_server->size_accepted_connections == TCP_server->num_accepted_connections) {
123 if (realloc_connection(TCP_server, TCP_server->size_accepted_connections + 4) == -1) 124 if (realloc_connection(TCP_server, TCP_server->size_accepted_connections + 4) == -1) {
124 return -1; 125 return -1;
126 }
125 127
126 index = TCP_server->num_accepted_connections; 128 index = TCP_server->num_accepted_connections;
127 } else { 129 } else {
@@ -140,8 +142,9 @@ static int add_accepted(TCP_Server *TCP_server, const TCP_Secure_Connection *con
140 return -1; 142 return -1;
141 } 143 }
142 144
143 if (!bs_list_add(&TCP_server->accepted_key_list, con->public_key, index)) 145 if (!bs_list_add(&TCP_server->accepted_key_list, con->public_key, index)) {
144 return -1; 146 return -1;
147 }
145 148
146 memcpy(&TCP_server->accepted_connection_array[index], con, sizeof(TCP_Secure_Connection)); 149 memcpy(&TCP_server->accepted_connection_array[index], con, sizeof(TCP_Secure_Connection));
147 TCP_server->accepted_connection_array[index].status = TCP_STATUS_CONFIRMED; 150 TCP_server->accepted_connection_array[index].status = TCP_STATUS_CONFIRMED;
@@ -160,20 +163,24 @@ static int add_accepted(TCP_Server *TCP_server, const TCP_Secure_Connection *con
160 */ 163 */
161static int del_accepted(TCP_Server *TCP_server, int index) 164static int del_accepted(TCP_Server *TCP_server, int index)
162{ 165{
163 if ((uint32_t)index >= TCP_server->size_accepted_connections) 166 if ((uint32_t)index >= TCP_server->size_accepted_connections) {
164 return -1; 167 return -1;
168 }
165 169
166 if (TCP_server->accepted_connection_array[index].status == TCP_STATUS_NO_STATUS) 170 if (TCP_server->accepted_connection_array[index].status == TCP_STATUS_NO_STATUS) {
167 return -1; 171 return -1;
172 }
168 173
169 if (!bs_list_remove(&TCP_server->accepted_key_list, TCP_server->accepted_connection_array[index].public_key, index)) 174 if (!bs_list_remove(&TCP_server->accepted_key_list, TCP_server->accepted_connection_array[index].public_key, index)) {
170 return -1; 175 return -1;
176 }
171 177
172 sodium_memzero(&TCP_server->accepted_connection_array[index], sizeof(TCP_Secure_Connection)); 178 sodium_memzero(&TCP_server->accepted_connection_array[index], sizeof(TCP_Secure_Connection));
173 --TCP_server->num_accepted_connections; 179 --TCP_server->num_accepted_connections;
174 180
175 if (TCP_server->num_accepted_connections == 0) 181 if (TCP_server->num_accepted_connections == 0) {
176 realloc_connection(TCP_server, 0); 182 realloc_connection(TCP_server, 0);
183 }
177 184
178 return 0; 185 return 0;
179} 186}
@@ -259,30 +266,35 @@ int read_packet_TCP_secure_connection(sock_t sock, uint16_t *next_packet_length,
259 if (*next_packet_length == 0) { 266 if (*next_packet_length == 0) {
260 uint16_t len = read_TCP_length(sock); 267 uint16_t len = read_TCP_length(sock);
261 268
262 if (len == (uint16_t)~0) 269 if (len == (uint16_t)~0) {
263 return -1; 270 return -1;
271 }
264 272
265 if (len == 0) 273 if (len == 0) {
266 return 0; 274 return 0;
275 }
267 276
268 *next_packet_length = len; 277 *next_packet_length = len;
269 } 278 }
270 279
271 if (max_len + crypto_box_MACBYTES < *next_packet_length) 280 if (max_len + crypto_box_MACBYTES < *next_packet_length) {
272 return -1; 281 return -1;
282 }
273 283
274 uint8_t data_encrypted[*next_packet_length]; 284 uint8_t data_encrypted[*next_packet_length];
275 int len_packet = read_TCP_packet(sock, data_encrypted, *next_packet_length); 285 int len_packet = read_TCP_packet(sock, data_encrypted, *next_packet_length);
276 286
277 if (len_packet != *next_packet_length) 287 if (len_packet != *next_packet_length) {
278 return 0; 288 return 0;
289 }
279 290
280 *next_packet_length = 0; 291 *next_packet_length = 0;
281 292
282 int len = decrypt_data_symmetric(shared_key, recv_nonce, data_encrypted, len_packet, data); 293 int len = decrypt_data_symmetric(shared_key, recv_nonce, data_encrypted, len_packet, data);
283 294
284 if (len + crypto_box_MACBYTES != len_packet) 295 if (len + crypto_box_MACBYTES != len_packet) {
285 return -1; 296 return -1;
297 }
286 298
287 increment_nonce(recv_nonce); 299 increment_nonce(recv_nonce);
288 300
@@ -301,8 +313,9 @@ static int send_pending_data_nonpriority(TCP_Secure_Connection *con)
301 uint16_t left = con->last_packet_length - con->last_packet_sent; 313 uint16_t left = con->last_packet_length - con->last_packet_sent;
302 int len = send(con->sock, con->last_packet + con->last_packet_sent, left, MSG_NOSIGNAL); 314 int len = send(con->sock, con->last_packet + con->last_packet_sent, left, MSG_NOSIGNAL);
303 315
304 if (len <= 0) 316 if (len <= 0) {
305 return -1; 317 return -1;
318 }
306 319
307 if (len == left) { 320 if (len == left) {
308 con->last_packet_length = 0; 321 con->last_packet_length = 0;
@@ -388,8 +401,9 @@ static _Bool add_priority(TCP_Secure_Connection *con, const uint8_t *packet, uin
388static int write_packet_TCP_secure_connection(TCP_Secure_Connection *con, const uint8_t *data, uint16_t length, 401static int write_packet_TCP_secure_connection(TCP_Secure_Connection *con, const uint8_t *data, uint16_t length,
389 _Bool priority) 402 _Bool priority)
390{ 403{
391 if (length + crypto_box_MACBYTES > MAX_PACKET_SIZE) 404 if (length + crypto_box_MACBYTES > MAX_PACKET_SIZE) {
392 return -1; 405 return -1;
406 }
393 407
394 _Bool sendpriority = 1; 408 _Bool sendpriority = 1;
395 409
@@ -407,8 +421,9 @@ static int write_packet_TCP_secure_connection(TCP_Secure_Connection *con, const
407 memcpy(packet, &c_length, sizeof(uint16_t)); 421 memcpy(packet, &c_length, sizeof(uint16_t));
408 int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t)); 422 int len = encrypt_data_symmetric(con->shared_key, con->sent_nonce, data, length, packet + sizeof(uint16_t));
409 423
410 if ((unsigned int)len != (sizeof(packet) - sizeof(uint16_t))) 424 if ((unsigned int)len != (sizeof(packet) - sizeof(uint16_t))) {
411 return -1; 425 return -1;
426 }
412 427
413 if (priority) { 428 if (priority) {
414 len = sendpriority ? send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL) : 0; 429 len = sendpriority ? send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL) : 0;
@@ -428,13 +443,15 @@ static int write_packet_TCP_secure_connection(TCP_Secure_Connection *con, const
428 443
429 len = send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL); 444 len = send(con->sock, packet, sizeof(packet), MSG_NOSIGNAL);
430 445
431 if (len <= 0) 446 if (len <= 0) {
432 return 0; 447 return 0;
448 }
433 449
434 increment_nonce(con->sent_nonce); 450 increment_nonce(con->sent_nonce);
435 451
436 if ((unsigned int)len == sizeof(packet)) 452 if ((unsigned int)len == sizeof(packet)) {
437 return 1; 453 return 1;
454 }
438 455
439 memcpy(con->last_packet, packet, sizeof(packet)); 456 memcpy(con->last_packet, packet, sizeof(packet));
440 con->last_packet_length = sizeof(packet); 457 con->last_packet_length = sizeof(packet);
@@ -459,8 +476,9 @@ static int rm_connection_index(TCP_Server *TCP_server, TCP_Secure_Connection *co
459 */ 476 */
460static int kill_accepted(TCP_Server *TCP_server, int index) 477static int kill_accepted(TCP_Server *TCP_server, int index)
461{ 478{
462 if ((uint32_t)index >= TCP_server->size_accepted_connections) 479 if ((uint32_t)index >= TCP_server->size_accepted_connections) {
463 return -1; 480 return -1;
481 }
464 482
465 uint32_t i; 483 uint32_t i;
466 484
@@ -470,8 +488,9 @@ static int kill_accepted(TCP_Server *TCP_server, int index)
470 488
471 sock_t sock = TCP_server->accepted_connection_array[index].sock; 489 sock_t sock = TCP_server->accepted_connection_array[index].sock;
472 490
473 if (del_accepted(TCP_server, index) != 0) 491 if (del_accepted(TCP_server, index) != 0) {
474 return -1; 492 return -1;
493 }
475 494
476 kill_sock(sock); 495 kill_sock(sock);
477 return 0; 496 return 0;
@@ -483,11 +502,13 @@ static int kill_accepted(TCP_Server *TCP_server, int index)
483static int handle_TCP_handshake(TCP_Secure_Connection *con, const uint8_t *data, uint16_t length, 502static int handle_TCP_handshake(TCP_Secure_Connection *con, const uint8_t *data, uint16_t length,
484 const uint8_t *self_secret_key) 503 const uint8_t *self_secret_key)
485{ 504{
486 if (length != TCP_CLIENT_HANDSHAKE_SIZE) 505 if (length != TCP_CLIENT_HANDSHAKE_SIZE) {
487 return -1; 506 return -1;
507 }
488 508
489 if (con->status != TCP_STATUS_CONNECTED) 509 if (con->status != TCP_STATUS_CONNECTED) {
490 return -1; 510 return -1;
511 }
491 512
492 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 513 uint8_t shared_key[crypto_box_BEFORENMBYTES];
493 encrypt_precompute(data, self_secret_key, shared_key); 514 encrypt_precompute(data, self_secret_key, shared_key);
@@ -495,8 +516,9 @@ static int handle_TCP_handshake(TCP_Secure_Connection *con, const uint8_t *data,
495 int len = decrypt_data_symmetric(shared_key, data + crypto_box_PUBLICKEYBYTES, 516 int len = decrypt_data_symmetric(shared_key, data + crypto_box_PUBLICKEYBYTES,
496 data + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, TCP_HANDSHAKE_PLAIN_SIZE + crypto_box_MACBYTES, plain); 517 data + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, TCP_HANDSHAKE_PLAIN_SIZE + crypto_box_MACBYTES, plain);
497 518
498 if (len != TCP_HANDSHAKE_PLAIN_SIZE) 519 if (len != TCP_HANDSHAKE_PLAIN_SIZE) {
499 return -1; 520 return -1;
521 }
500 522
501 memcpy(con->public_key, data, crypto_box_PUBLICKEYBYTES); 523 memcpy(con->public_key, data, crypto_box_PUBLICKEYBYTES);
502 uint8_t temp_secret_key[crypto_box_SECRETKEYBYTES]; 524 uint8_t temp_secret_key[crypto_box_SECRETKEYBYTES];
@@ -512,11 +534,13 @@ static int handle_TCP_handshake(TCP_Secure_Connection *con, const uint8_t *data,
512 len = encrypt_data_symmetric(shared_key, response, resp_plain, TCP_HANDSHAKE_PLAIN_SIZE, 534 len = encrypt_data_symmetric(shared_key, response, resp_plain, TCP_HANDSHAKE_PLAIN_SIZE,
513 response + crypto_box_NONCEBYTES); 535 response + crypto_box_NONCEBYTES);
514 536
515 if (len != TCP_HANDSHAKE_PLAIN_SIZE + crypto_box_MACBYTES) 537 if (len != TCP_HANDSHAKE_PLAIN_SIZE + crypto_box_MACBYTES) {
516 return -1; 538 return -1;
539 }
517 540
518 if (TCP_SERVER_HANDSHAKE_SIZE != send(con->sock, response, TCP_SERVER_HANDSHAKE_SIZE, MSG_NOSIGNAL)) 541 if (TCP_SERVER_HANDSHAKE_SIZE != send(con->sock, response, TCP_SERVER_HANDSHAKE_SIZE, MSG_NOSIGNAL)) {
519 return -1; 542 return -1;
543 }
520 544
521 encrypt_precompute(plain, temp_secret_key, con->shared_key); 545 encrypt_precompute(plain, temp_secret_key, con->shared_key);
522 con->status = TCP_STATUS_UNCONFIRMED; 546 con->status = TCP_STATUS_UNCONFIRMED;
@@ -584,8 +608,9 @@ static int handle_TCP_routing_req(TCP_Server *TCP_server, uint32_t con_id, const
584 608
585 /* If person tries to cennect to himself we deny the request*/ 609 /* If person tries to cennect to himself we deny the request*/
586 if (public_key_cmp(con->public_key, public_key) == 0) { 610 if (public_key_cmp(con->public_key, public_key) == 0) {
587 if (send_routing_response(con, 0, public_key) == -1) 611 if (send_routing_response(con, 0, public_key) == -1) {
588 return -1; 612 return -1;
613 }
589 614
590 return 0; 615 return 0;
591 } 616 }
@@ -605,19 +630,22 @@ static int handle_TCP_routing_req(TCP_Server *TCP_server, uint32_t con_id, const
605 } 630 }
606 631
607 if (index == (uint32_t)~0) { 632 if (index == (uint32_t)~0) {
608 if (send_routing_response(con, 0, public_key) == -1) 633 if (send_routing_response(con, 0, public_key) == -1) {
609 return -1; 634 return -1;
635 }
610 636
611 return 0; 637 return 0;
612 } 638 }
613 639
614 int ret = send_routing_response(con, index + NUM_RESERVED_PORTS, public_key); 640 int ret = send_routing_response(con, index + NUM_RESERVED_PORTS, public_key);
615 641
616 if (ret == 0) 642 if (ret == 0) {
617 return 0; 643 return 0;
644 }
618 645
619 if (ret == -1) 646 if (ret == -1) {
620 return -1; 647 return -1;
648 }
621 649
622 con->connections[index].status = 1; 650 con->connections[index].status = 1;
623 memcpy(con->connections[index].public_key, public_key, crypto_box_PUBLICKEYBYTES); 651 memcpy(con->connections[index].public_key, public_key, crypto_box_PUBLICKEYBYTES);
@@ -657,8 +685,9 @@ static int handle_TCP_routing_req(TCP_Server *TCP_server, uint32_t con_id, const
657static int handle_TCP_oob_send(TCP_Server *TCP_server, uint32_t con_id, const uint8_t *public_key, const uint8_t *data, 685static int handle_TCP_oob_send(TCP_Server *TCP_server, uint32_t con_id, const uint8_t *public_key, const uint8_t *data,
658 uint16_t length) 686 uint16_t length)
659{ 687{
660 if (length == 0 || length > TCP_MAX_OOB_DATA_LENGTH) 688 if (length == 0 || length > TCP_MAX_OOB_DATA_LENGTH) {
661 return -1; 689 return -1;
690 }
662 691
663 TCP_Secure_Connection *con = &TCP_server->accepted_connection_array[con_id]; 692 TCP_Secure_Connection *con = &TCP_server->accepted_connection_array[con_id];
664 693
@@ -683,8 +712,9 @@ static int handle_TCP_oob_send(TCP_Server *TCP_server, uint32_t con_id, const ui
683 */ 712 */
684static int rm_connection_index(TCP_Server *TCP_server, TCP_Secure_Connection *con, uint8_t con_number) 713static int rm_connection_index(TCP_Server *TCP_server, TCP_Secure_Connection *con, uint8_t con_number)
685{ 714{
686 if (con_number >= NUM_CLIENT_CONNECTIONS) 715 if (con_number >= NUM_CLIENT_CONNECTIONS) {
687 return -1; 716 return -1;
717 }
688 718
689 if (con->connections[con_number].status) { 719 if (con->connections[con_number].status) {
690 uint32_t index = con->connections[con_number].index; 720 uint32_t index = con->connections[con_number].index;
@@ -692,8 +722,9 @@ static int rm_connection_index(TCP_Server *TCP_server, TCP_Secure_Connection *co
692 722
693 if (con->connections[con_number].status == 2) { 723 if (con->connections[con_number].status == 2) {
694 724
695 if (index >= TCP_server->size_accepted_connections) 725 if (index >= TCP_server->size_accepted_connections) {
696 return -1; 726 return -1;
727 }
697 728
698 TCP_server->accepted_connection_array[index].connections[other_id].other_id = 0; 729 TCP_server->accepted_connection_array[index].connections[other_id].other_id = 0;
699 TCP_server->accepted_connection_array[index].connections[other_id].index = 0; 730 TCP_server->accepted_connection_array[index].connections[other_id].index = 0;
@@ -716,20 +747,23 @@ static int handle_onion_recv_1(void *object, IP_Port dest, const uint8_t *data,
716 TCP_Server *TCP_server = object; 747 TCP_Server *TCP_server = object;
717 uint32_t index = dest.ip.ip6.uint32[0]; 748 uint32_t index = dest.ip.ip6.uint32[0];
718 749
719 if (index >= TCP_server->size_accepted_connections) 750 if (index >= TCP_server->size_accepted_connections) {
720 return 1; 751 return 1;
752 }
721 753
722 TCP_Secure_Connection *con = &TCP_server->accepted_connection_array[index]; 754 TCP_Secure_Connection *con = &TCP_server->accepted_connection_array[index];
723 755
724 if (con->identifier != dest.ip.ip6.uint64[1]) 756 if (con->identifier != dest.ip.ip6.uint64[1]) {
725 return 1; 757 return 1;
758 }
726 759
727 uint8_t packet[1 + length]; 760 uint8_t packet[1 + length];
728 memcpy(packet + 1, data, length); 761 memcpy(packet + 1, data, length);
729 packet[0] = TCP_PACKET_ONION_RESPONSE; 762 packet[0] = TCP_PACKET_ONION_RESPONSE;
730 763
731 if (write_packet_TCP_secure_connection(con, packet, sizeof(packet), 0) != 1) 764 if (write_packet_TCP_secure_connection(con, packet, sizeof(packet), 0) != 1) {
732 return 1; 765 return 1;
766 }
733 767
734 return 0; 768 return 0;
735} 769}
@@ -739,36 +773,41 @@ static int handle_onion_recv_1(void *object, IP_Port dest, const uint8_t *data,
739 */ 773 */
740static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint8_t *data, uint16_t length) 774static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint8_t *data, uint16_t length)
741{ 775{
742 if (length == 0) 776 if (length == 0) {
743 return -1; 777 return -1;
778 }
744 779
745 TCP_Secure_Connection *con = &TCP_server->accepted_connection_array[con_id]; 780 TCP_Secure_Connection *con = &TCP_server->accepted_connection_array[con_id];
746 781
747 switch (data[0]) { 782 switch (data[0]) {
748 case TCP_PACKET_ROUTING_REQUEST: { 783 case TCP_PACKET_ROUTING_REQUEST: {
749 if (length != 1 + crypto_box_PUBLICKEYBYTES) 784 if (length != 1 + crypto_box_PUBLICKEYBYTES) {
750 return -1; 785 return -1;
786 }
751 787
752 return handle_TCP_routing_req(TCP_server, con_id, data + 1); 788 return handle_TCP_routing_req(TCP_server, con_id, data + 1);
753 } 789 }
754 790
755 case TCP_PACKET_CONNECTION_NOTIFICATION: { 791 case TCP_PACKET_CONNECTION_NOTIFICATION: {
756 if (length != 2) 792 if (length != 2) {
757 return -1; 793 return -1;
794 }
758 795
759 break; 796 break;
760 } 797 }
761 798
762 case TCP_PACKET_DISCONNECT_NOTIFICATION: { 799 case TCP_PACKET_DISCONNECT_NOTIFICATION: {
763 if (length != 2) 800 if (length != 2) {
764 return -1; 801 return -1;
802 }
765 803
766 return rm_connection_index(TCP_server, con, data[1] - NUM_RESERVED_PORTS); 804 return rm_connection_index(TCP_server, con, data[1] - NUM_RESERVED_PORTS);
767 } 805 }
768 806
769 case TCP_PACKET_PING: { 807 case TCP_PACKET_PING: {
770 if (length != 1 + sizeof(uint64_t)) 808 if (length != 1 + sizeof(uint64_t)) {
771 return -1; 809 return -1;
810 }
772 811
773 uint8_t response[1 + sizeof(uint64_t)]; 812 uint8_t response[1 + sizeof(uint64_t)];
774 response[0] = TCP_PACKET_PONG; 813 response[0] = TCP_PACKET_PONG;
@@ -778,8 +817,9 @@ static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint
778 } 817 }
779 818
780 case TCP_PACKET_PONG: { 819 case TCP_PACKET_PONG: {
781 if (length != 1 + sizeof(uint64_t)) 820 if (length != 1 + sizeof(uint64_t)) {
782 return -1; 821 return -1;
822 }
783 823
784 uint64_t ping_id; 824 uint64_t ping_id;
785 memcpy(&ping_id, data + 1, sizeof(uint64_t)); 825 memcpy(&ping_id, data + 1, sizeof(uint64_t));
@@ -796,8 +836,9 @@ static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint
796 } 836 }
797 837
798 case TCP_PACKET_OOB_SEND: { 838 case TCP_PACKET_OOB_SEND: {
799 if (length <= 1 + crypto_box_PUBLICKEYBYTES) 839 if (length <= 1 + crypto_box_PUBLICKEYBYTES) {
800 return -1; 840 return -1;
841 }
801 842
802 return handle_TCP_oob_send(TCP_server, con_id, data + 1, data + 1 + crypto_box_PUBLICKEYBYTES, 843 return handle_TCP_oob_send(TCP_server, con_id, data + 1, data + 1 + crypto_box_PUBLICKEYBYTES,
803 length - (1 + crypto_box_PUBLICKEYBYTES)); 844 length - (1 + crypto_box_PUBLICKEYBYTES));
@@ -805,8 +846,9 @@ static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint
805 846
806 case TCP_PACKET_ONION_REQUEST: { 847 case TCP_PACKET_ONION_REQUEST: {
807 if (TCP_server->onion) { 848 if (TCP_server->onion) {
808 if (length <= 1 + crypto_box_NONCEBYTES + ONION_SEND_BASE * 2) 849 if (length <= 1 + crypto_box_NONCEBYTES + ONION_SEND_BASE * 2) {
809 return -1; 850 return -1;
851 }
810 852
811 IP_Port source; 853 IP_Port source;
812 source.port = 0; // dummy initialise 854 source.port = 0; // dummy initialise
@@ -826,19 +868,23 @@ static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint
826 } 868 }
827 869
828 default: { 870 default: {
829 if (data[0] < NUM_RESERVED_PORTS) 871 if (data[0] < NUM_RESERVED_PORTS) {
830 return -1; 872 return -1;
873 }
831 874
832 uint8_t c_id = data[0] - NUM_RESERVED_PORTS; 875 uint8_t c_id = data[0] - NUM_RESERVED_PORTS;
833 876
834 if (c_id >= NUM_CLIENT_CONNECTIONS) 877 if (c_id >= NUM_CLIENT_CONNECTIONS) {
835 return -1; 878 return -1;
879 }
836 880
837 if (con->connections[c_id].status == 0) 881 if (con->connections[c_id].status == 0) {
838 return -1; 882 return -1;
883 }
839 884
840 if (con->connections[c_id].status != 2) 885 if (con->connections[c_id].status != 2) {
841 return 0; 886 return 0;
887 }
842 888
843 uint32_t index = con->connections[c_id].index; 889 uint32_t index = con->connections[c_id].index;
844 uint8_t other_c_id = con->connections[c_id].other_id + NUM_RESERVED_PORTS; 890 uint8_t other_c_id = con->connections[c_id].other_id + NUM_RESERVED_PORTS;
@@ -847,8 +893,9 @@ static int handle_TCP_packet(TCP_Server *TCP_server, uint32_t con_id, const uint
847 new_data[0] = other_c_id; 893 new_data[0] = other_c_id;
848 int ret = write_packet_TCP_secure_connection(&TCP_server->accepted_connection_array[index], new_data, length, 0); 894 int ret = write_packet_TCP_secure_connection(&TCP_server->accepted_connection_array[index], new_data, length, 0);
849 895
850 if (ret == -1) 896 if (ret == -1) {
851 return -1; 897 return -1;
898 }
852 899
853 return 0; 900 return 0;
854 } 901 }
@@ -883,8 +930,9 @@ static int confirm_TCP_connection(TCP_Server *TCP_server, TCP_Secure_Connection
883 */ 930 */
884static int accept_connection(TCP_Server *TCP_server, sock_t sock) 931static int accept_connection(TCP_Server *TCP_server, sock_t sock)
885{ 932{
886 if (!sock_valid(sock)) 933 if (!sock_valid(sock)) {
887 return -1; 934 return -1;
935 }
888 936
889 if (!set_socket_nonblock(sock)) { 937 if (!set_socket_nonblock(sock)) {
890 kill_sock(sock); 938 kill_sock(sock);
@@ -900,8 +948,9 @@ static int accept_connection(TCP_Server *TCP_server, sock_t sock)
900 948
901 TCP_Secure_Connection *conn = &TCP_server->incomming_connection_queue[index]; 949 TCP_Secure_Connection *conn = &TCP_server->incomming_connection_queue[index];
902 950
903 if (conn->status != TCP_STATUS_NO_STATUS) 951 if (conn->status != TCP_STATUS_NO_STATUS) {
904 kill_TCP_connection(conn); 952 kill_TCP_connection(conn);
953 }
905 954
906 conn->status = TCP_STATUS_CONNECTED; 955 conn->status = TCP_STATUS_CONNECTED;
907 conn->sock = sock; 956 conn->sock = sock;
@@ -942,8 +991,9 @@ static sock_t new_listening_TCP_socket(int family, uint16_t port)
942TCP_Server *new_TCP_server(uint8_t ipv6_enabled, uint16_t num_sockets, const uint16_t *ports, const uint8_t *secret_key, 991TCP_Server *new_TCP_server(uint8_t ipv6_enabled, uint16_t num_sockets, const uint16_t *ports, const uint8_t *secret_key,
943 Onion *onion) 992 Onion *onion)
944{ 993{
945 if (num_sockets == 0 || ports == NULL) 994 if (num_sockets == 0 || ports == NULL) {
946 return NULL; 995 return NULL;
996 }
947 997
948 if (networking_at_startup() != 0) { 998 if (networking_at_startup() != 0) {
949 return NULL; 999 return NULL;
@@ -951,8 +1001,9 @@ TCP_Server *new_TCP_server(uint8_t ipv6_enabled, uint16_t num_sockets, const uin
951 1001
952 TCP_Server *temp = calloc(1, sizeof(TCP_Server)); 1002 TCP_Server *temp = calloc(1, sizeof(TCP_Server));
953 1003
954 if (temp == NULL) 1004 if (temp == NULL) {
955 return NULL; 1005 return NULL;
1006 }
956 1007
957 temp->socks_listening = calloc(num_sockets, sizeof(sock_t)); 1008 temp->socks_listening = calloc(num_sockets, sizeof(sock_t));
958 1009
@@ -1040,8 +1091,9 @@ static void do_TCP_accept_new(TCP_Server *TCP_server)
1040 1091
1041static int do_incoming(TCP_Server *TCP_server, uint32_t i) 1092static int do_incoming(TCP_Server *TCP_server, uint32_t i)
1042{ 1093{
1043 if (TCP_server->incomming_connection_queue[i].status != TCP_STATUS_CONNECTED) 1094 if (TCP_server->incomming_connection_queue[i].status != TCP_STATUS_CONNECTED) {
1044 return -1; 1095 return -1;
1096 }
1045 1097
1046 int ret = read_connection_handshake(&TCP_server->incomming_connection_queue[i], TCP_server->secret_key); 1098 int ret = read_connection_handshake(&TCP_server->incomming_connection_queue[i], TCP_server->secret_key);
1047 1099
@@ -1052,8 +1104,9 @@ static int do_incoming(TCP_Server *TCP_server, uint32_t i)
1052 TCP_Secure_Connection *conn_old = &TCP_server->incomming_connection_queue[i]; 1104 TCP_Secure_Connection *conn_old = &TCP_server->incomming_connection_queue[i];
1053 TCP_Secure_Connection *conn_new = &TCP_server->unconfirmed_connection_queue[index_new]; 1105 TCP_Secure_Connection *conn_new = &TCP_server->unconfirmed_connection_queue[index_new];
1054 1106
1055 if (conn_new->status != TCP_STATUS_NO_STATUS) 1107 if (conn_new->status != TCP_STATUS_NO_STATUS) {
1056 kill_TCP_connection(conn_new); 1108 kill_TCP_connection(conn_new);
1109 }
1057 1110
1058 memcpy(conn_new, conn_old, sizeof(TCP_Secure_Connection)); 1111 memcpy(conn_new, conn_old, sizeof(TCP_Secure_Connection));
1059 sodium_memzero(conn_old, sizeof(TCP_Secure_Connection)); 1112 sodium_memzero(conn_old, sizeof(TCP_Secure_Connection));
@@ -1069,8 +1122,9 @@ static int do_unconfirmed(TCP_Server *TCP_server, uint32_t i)
1069{ 1122{
1070 TCP_Secure_Connection *conn = &TCP_server->unconfirmed_connection_queue[i]; 1123 TCP_Secure_Connection *conn = &TCP_server->unconfirmed_connection_queue[i];
1071 1124
1072 if (conn->status != TCP_STATUS_UNCONFIRMED) 1125 if (conn->status != TCP_STATUS_UNCONFIRMED) {
1073 return -1; 1126 return -1;
1127 }
1074 1128
1075 uint8_t packet[MAX_PACKET_SIZE]; 1129 uint8_t packet[MAX_PACKET_SIZE];
1076 int len = read_packet_TCP_secure_connection(conn->sock, &conn->next_packet_length, conn->shared_key, conn->recv_nonce, 1130 int len = read_packet_TCP_secure_connection(conn->sock, &conn->next_packet_length, conn->shared_key, conn->recv_nonce,
@@ -1139,16 +1193,18 @@ static void do_TCP_confirmed(TCP_Server *TCP_server)
1139 for (i = 0; i < TCP_server->size_accepted_connections; ++i) { 1193 for (i = 0; i < TCP_server->size_accepted_connections; ++i) {
1140 TCP_Secure_Connection *conn = &TCP_server->accepted_connection_array[i]; 1194 TCP_Secure_Connection *conn = &TCP_server->accepted_connection_array[i];
1141 1195
1142 if (conn->status != TCP_STATUS_CONFIRMED) 1196 if (conn->status != TCP_STATUS_CONFIRMED) {
1143 continue; 1197 continue;
1198 }
1144 1199
1145 if (is_timeout(conn->last_pinged, TCP_PING_FREQUENCY)) { 1200 if (is_timeout(conn->last_pinged, TCP_PING_FREQUENCY)) {
1146 uint8_t ping[1 + sizeof(uint64_t)]; 1201 uint8_t ping[1 + sizeof(uint64_t)];
1147 ping[0] = TCP_PACKET_PING; 1202 ping[0] = TCP_PACKET_PING;
1148 uint64_t ping_id = random_64b(); 1203 uint64_t ping_id = random_64b();
1149 1204
1150 if (!ping_id) 1205 if (!ping_id) {
1151 ++ping_id; 1206 ++ping_id;
1207 }
1152 1208
1153 memcpy(ping + 1, &ping_id, sizeof(uint64_t)); 1209 memcpy(ping + 1, &ping_id, sizeof(uint64_t));
1154 int ret = write_packet_TCP_secure_connection(conn, ping, sizeof(ping), 1); 1210 int ret = write_packet_TCP_secure_connection(conn, ping, sizeof(ping), 1);
diff --git a/toxcore/assoc.c b/toxcore/assoc.c
index 33ba1f4a..14f56fb3 100644
--- a/toxcore/assoc.c
+++ b/toxcore/assoc.c
@@ -127,11 +127,13 @@ static int dist_index_comp(const void *a, const void *b)
127 const uint64_t *_a = a; 127 const uint64_t *_a = a;
128 const uint64_t *_b = b; 128 const uint64_t *_b = b;
129 129
130 if (*_a < *_b) 130 if (*_a < *_b) {
131 return -1; 131 return -1;
132 }
132 133
133 if (*_a > *_b) 134 if (*_a > *_b) {
134 return 1; 135 return 1;
136 }
135 137
136 return 0; 138 return 0;
137} 139}
@@ -139,8 +141,9 @@ static int dist_index_comp(const void *a, const void *b)
139/* get actual entry to a distance_index */ 141/* get actual entry to a distance_index */
140static Client_entry *dist_index_entry(Assoc *assoc, uint64_t dist_ind) 142static Client_entry *dist_index_entry(Assoc *assoc, uint64_t dist_ind)
141{ 143{
142 if ((dist_ind & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) 144 if ((dist_ind & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) {
143 return NULL; 145 return NULL;
146 }
144 147
145 size_t total = assoc->candidates_bucket_count * assoc->candidates_bucket_size; 148 size_t total = assoc->candidates_bucket_count * assoc->candidates_bucket_size;
146 uint32_t index = dist_ind & DISTANCE_INDEX_INDEX_MASK; 149 uint32_t index = dist_ind & DISTANCE_INDEX_INDEX_MASK;
@@ -151,8 +154,9 @@ static Client_entry *dist_index_entry(Assoc *assoc, uint64_t dist_ind)
151 size_t b_ix = index % assoc->candidates_bucket_size; 154 size_t b_ix = index % assoc->candidates_bucket_size;
152 Client_entry *entry = &cnd_bckt->list[b_ix]; 155 Client_entry *entry = &cnd_bckt->list[b_ix];
153 156
154 if (entry->hash) 157 if (entry->hash) {
155 return entry; 158 return entry;
159 }
156 } 160 }
157 161
158 return NULL; 162 return NULL;
@@ -163,8 +167,9 @@ static uint8_t *dist_index_id(Assoc *assoc, uint64_t dist_ind)
163{ 167{
164 Client_entry *entry = dist_index_entry(assoc, dist_ind); 168 Client_entry *entry = dist_index_entry(assoc, dist_ind);
165 169
166 if (entry) 170 if (entry) {
167 return entry->client.public_key; 171 return entry->client.public_key;
172 }
168 173
169 return NULL; 174 return NULL;
170} 175}
@@ -181,12 +186,13 @@ static void dist_index_bubble(Assoc *assoc, uint64_t *dist_list, size_t first, s
181 for (k = i + 1; k <= last; k++) { 186 for (k = i + 1; k <= last; k++) {
182 uint8_t *id2 = dist_index_id(assoc, dist_list[k]); 187 uint8_t *id2 = dist_index_id(assoc, dist_list[k]);
183 188
184 if (id1 && id2) 189 if (id1 && id2) {
185 if (dist_rel_func(assoc, custom_data, id, id1, id2) == 2) { 190 if (dist_rel_func(assoc, custom_data, id, id1, id2) == 2) {
186 uint64_t swap = dist_list[i]; 191 uint64_t swap = dist_list[i];
187 dist_list[i] = dist_list[k]; 192 dist_list[i] = dist_list[k];
188 dist_list[k] = swap; 193 dist_list[k] = swap;
189 } 194 }
195 }
190 } 196 }
191 } 197 }
192} 198}
@@ -201,13 +207,15 @@ static hash_t id_hash(const Assoc *assoc, const uint8_t *id)
201{ 207{
202 uint32_t i, res = 0x19a64e82; 208 uint32_t i, res = 0x19a64e82;
203 209
204 for (i = 0; i < crypto_box_PUBLICKEYBYTES; i++) 210 for (i = 0; i < crypto_box_PUBLICKEYBYTES; i++) {
205 res = ((res << 1) ^ id[i]) + (res >> 31); 211 res = ((res << 1) ^ id[i]) + (res >> 31);
212 }
206 213
207 /* can't have zero as hash, a) marks an unused spot, 214 /* can't have zero as hash, a) marks an unused spot,
208 * b) collision function is multiplicative */ 215 * b) collision function is multiplicative */
209 if (!(res % assoc->candidates_bucket_size)) 216 if (!(res % assoc->candidates_bucket_size)) {
210 res++; 217 res++;
218 }
211 219
212 return res; 220 return res;
213} 221}
@@ -244,14 +252,17 @@ static hash_t hash_collide(const Assoc *assoc, hash_t hash)
244/* returns the "seen" assoc related to the ipp */ 252/* returns the "seen" assoc related to the ipp */
245static IPPTsPng *entry_assoc(Client_entry *cl_entry, const IP_Port *ipp) 253static IPPTsPng *entry_assoc(Client_entry *cl_entry, const IP_Port *ipp)
246{ 254{
247 if (!cl_entry) 255 if (!cl_entry) {
248 return NULL; 256 return NULL;
257 }
249 258
250 if (ipp->ip.family == AF_INET) 259 if (ipp->ip.family == AF_INET) {
251 return &cl_entry->client.assoc4; 260 return &cl_entry->client.assoc4;
261 }
252 262
253 if (ipp->ip.family == AF_INET6) 263 if (ipp->ip.family == AF_INET6) {
254 return &cl_entry->client.assoc6; 264 return &cl_entry->client.assoc6;
265 }
255 266
256 return NULL; 267 return NULL;
257} 268}
@@ -259,12 +270,13 @@ static IPPTsPng *entry_assoc(Client_entry *cl_entry, const IP_Port *ipp)
259/* returns the "heard" assoc related to the ipp */ 270/* returns the "heard" assoc related to the ipp */
260static IP_Port *entry_heard_get(Client_entry *entry, const IP_Port *ipp) 271static IP_Port *entry_heard_get(Client_entry *entry, const IP_Port *ipp)
261{ 272{
262 if (ipp->ip.family == AF_INET) 273 if (ipp->ip.family == AF_INET) {
263 return &entry->assoc_heard4; 274 return &entry->assoc_heard4;
264 else if (ipp->ip.family == AF_INET6) 275 } else if (ipp->ip.family == AF_INET6) {
265 return &entry->assoc_heard6; 276 return &entry->assoc_heard6;
266 else 277 } else {
267 return NULL; 278 return NULL;
279 }
268} 280}
269 281
270/* store a "heard" entry 282/* store a "heard" entry
@@ -274,24 +286,28 @@ static IP_Port *entry_heard_get(Client_entry *entry, const IP_Port *ipp)
274 * returns 1 if the entry did change */ 286 * returns 1 if the entry did change */
275static int entry_heard_store(Client_entry *entry, const IPPTs *ippts) 287static int entry_heard_store(Client_entry *entry, const IPPTs *ippts)
276{ 288{
277 if (!entry || !ippts) 289 if (!entry || !ippts) {
278 return 0; 290 return 0;
291 }
279 292
280 if (!ipport_isset(&ippts->ip_port)) 293 if (!ipport_isset(&ippts->ip_port)) {
281 return 0; 294 return 0;
295 }
282 296
283 IP_Port *heard; 297 IP_Port *heard;
284 const IP_Port *ipp = &ippts->ip_port; 298 const IP_Port *ipp = &ippts->ip_port;
285 299
286 if (ipp->ip.family == AF_INET) 300 if (ipp->ip.family == AF_INET) {
287 heard = &entry->assoc_heard4; 301 heard = &entry->assoc_heard4;
288 else if (ipp->ip.family == AF_INET6) 302 } else if (ipp->ip.family == AF_INET6) {
289 heard = &entry->assoc_heard6; 303 heard = &entry->assoc_heard6;
290 else 304 } else {
291 return 0; 305 return 0;
306 }
292 307
293 if (ipport_equal(ipp, heard)) 308 if (ipport_equal(ipp, heard)) {
294 return 0; 309 return 0;
310 }
295 311
296 if (!ipport_isset(heard)) { 312 if (!ipport_isset(heard)) {
297 *heard = *ipp; 313 *heard = *ipp;
@@ -305,8 +321,9 @@ static int entry_heard_store(Client_entry *entry, const IPPTs *ippts)
305 uint8_t LAN_ipp = LAN_ip(ipp->ip) == 0; 321 uint8_t LAN_ipp = LAN_ip(ipp->ip) == 0;
306 uint8_t LAN_entry = LAN_ip(heard->ip) == 0; 322 uint8_t LAN_entry = LAN_ip(heard->ip) == 0;
307 323
308 if (LAN_ipp && !LAN_entry && !is_timeout(entry->heard_at, CANDIDATES_HEARD_TIMEOUT)) 324 if (LAN_ipp && !LAN_entry && !is_timeout(entry->heard_at, CANDIDATES_HEARD_TIMEOUT)) {
309 return 0; 325 return 0;
326 }
310 327
311 *heard = *ipp; 328 *heard = *ipp;
312 entry->heard_at = ippts->timestamp; 329 entry->heard_at = ippts->timestamp;
@@ -356,11 +373,12 @@ static uint8_t candidates_search(const Assoc *assoc, const uint8_t *id, hash_t h
356 for (coll = 0; coll < HASH_COLLIDE_COUNT; pos = hash_collide(assoc, pos) , coll++) { 373 for (coll = 0; coll < HASH_COLLIDE_COUNT; pos = hash_collide(assoc, pos) , coll++) {
357 Client_entry *entry = &cnd_bckt->list[pos]; 374 Client_entry *entry = &cnd_bckt->list[pos];
358 375
359 if (entry->hash == hash) 376 if (entry->hash == hash) {
360 if (id_equal(entry->client.public_key, id)) { 377 if (id_equal(entry->client.public_key, id)) {
361 *entryptr = entry; 378 *entryptr = entry;
362 return 1; 379 return 1;
363 } 380 }
381 }
364 } 382 }
365 383
366 *entryptr = NULL; 384 *entryptr = NULL;
@@ -370,16 +388,19 @@ static uint8_t candidates_search(const Assoc *assoc, const uint8_t *id, hash_t h
370static void candidates_update_assoc(const Assoc *assoc, Client_entry *entry, uint8_t used, const IPPTs *ippts_send, 388static void candidates_update_assoc(const Assoc *assoc, Client_entry *entry, uint8_t used, const IPPTs *ippts_send,
371 const IP_Port *ipp_recv) 389 const IP_Port *ipp_recv)
372{ 390{
373 if (!assoc || !entry || !ippts_send) 391 if (!assoc || !entry || !ippts_send) {
374 return; 392 return;
393 }
375 394
376 IPPTsPng *ipptsp = entry_assoc(entry, &ippts_send->ip_port); 395 IPPTsPng *ipptsp = entry_assoc(entry, &ippts_send->ip_port);
377 396
378 if (!ipptsp) 397 if (!ipptsp) {
379 return; 398 return;
399 }
380 400
381 if (used) 401 if (used) {
382 entry->used_at = unix_time(); 402 entry->used_at = unix_time();
403 }
383 404
384 /* do NOT do anything related to wanted, that's handled outside, 405 /* do NOT do anything related to wanted, that's handled outside,
385 * just update the assoc (in the most sensible way) 406 * just update the assoc (in the most sensible way)
@@ -402,8 +423,9 @@ static void candidates_update_assoc(const Assoc *assoc, Client_entry *entry, uin
402static uint8_t candidates_create_internal(const Assoc *assoc, hash_t const hash, const uint8_t *id, uint8_t seen, 423static uint8_t candidates_create_internal(const Assoc *assoc, hash_t const hash, const uint8_t *id, uint8_t seen,
403 uint8_t used, bucket_t *bucketptr, size_t *posptr) 424 uint8_t used, bucket_t *bucketptr, size_t *posptr)
404{ 425{
405 if (!assoc || !id || !bucketptr || !posptr) 426 if (!assoc || !id || !bucketptr || !posptr) {
406 return 0; 427 return 0;
428 }
407 429
408 bucket_t bucket = candidates_id_bucket(assoc, id); 430 bucket_t bucket = candidates_id_bucket(assoc, id);
409 candidates_bucket *cnd_bckt = &assoc->candidates[bucket]; 431 candidates_bucket *cnd_bckt = &assoc->candidates[bucket];
@@ -429,29 +451,32 @@ static uint8_t candidates_create_internal(const Assoc *assoc, hash_t const hash,
429 * 2. seen good 451 * 2. seen good
430 * 3. used */ 452 * 3. used */
431 // enumerated lists are superior to magic numbers 453 // enumerated lists are superior to magic numbers
432 if (!is_timeout(entry->used_at, BAD_NODE_TIMEOUT)) 454 if (!is_timeout(entry->used_at, BAD_NODE_TIMEOUT)) {
433 check = USED; 455 check = USED;
434 else if (!is_timeout(entry->seen_at, CANDIDATES_SEEN_TIMEOUT)) 456 } else if (!is_timeout(entry->seen_at, CANDIDATES_SEEN_TIMEOUT)) {
435 check = SEENG; 457 check = SEENG;
436 else if (!is_timeout(entry->heard_at, CANDIDATES_HEARD_TIMEOUT)) 458 } else if (!is_timeout(entry->heard_at, CANDIDATES_HEARD_TIMEOUT)) {
437 check = SEENB_HEARDG; 459 check = SEENB_HEARDG;
438 else 460 } else {
439 check = BAD; 461 check = BAD;
462 }
440 463
441 if (!pos_check[check]) 464 if (!pos_check[check]) {
442 pos_check[check] = pos + 1; 465 pos_check[check] = pos + 1;
466 }
443 } 467 }
444 468
445 /* used > seen > heard > bad */ 469 /* used > seen > heard > bad */
446 size_t i, pos_max = used ? USED : (seen ? SEENG : SEENB_HEARDG); 470 size_t i, pos_max = used ? USED : (seen ? SEENG : SEENB_HEARDG);
447 471
448 for (i = 0; i < pos_max; i++) 472 for (i = 0; i < pos_max; i++) {
449 if (pos_check[i]) { 473 if (pos_check[i]) {
450 *bucketptr = bucket; 474 *bucketptr = bucket;
451 *posptr = pos_check[i] - 1; 475 *posptr = pos_check[i] - 1;
452 476
453 return 1; 477 return 1;
454 } 478 }
479 }
455 480
456 return 0; 481 return 0;
457} 482}
@@ -459,31 +484,36 @@ static uint8_t candidates_create_internal(const Assoc *assoc, hash_t const hash,
459static uint8_t candidates_create_new(const Assoc *assoc, hash_t hash, const uint8_t *id, uint8_t used, 484static uint8_t candidates_create_new(const Assoc *assoc, hash_t hash, const uint8_t *id, uint8_t used,
460 const IPPTs *ippts_send, const IP_Port *ipp_recv) 485 const IPPTs *ippts_send, const IP_Port *ipp_recv)
461{ 486{
462 if (!assoc || !id || !ippts_send) 487 if (!assoc || !id || !ippts_send) {
463 return 0; 488 return 0;
489 }
464 490
465 bucket_t bucket; 491 bucket_t bucket;
466 size_t pos; 492 size_t pos;
467 493
468 if (!candidates_create_internal(assoc, hash, id, ipp_recv != NULL, used, &bucket, &pos)) 494 if (!candidates_create_internal(assoc, hash, id, ipp_recv != NULL, used, &bucket, &pos)) {
469 return 0; 495 return 0;
496 }
470 497
471 candidates_bucket *cnd_bckt = &assoc->candidates[bucket]; 498 candidates_bucket *cnd_bckt = &assoc->candidates[bucket];
472 Client_entry *entry = &cnd_bckt->list[pos]; 499 Client_entry *entry = &cnd_bckt->list[pos];
473 memset(entry, 0, sizeof(*entry)); 500 memset(entry, 0, sizeof(*entry));
474 IPPTsPng *ipptsp = entry_assoc(entry, &ippts_send->ip_port); 501 IPPTsPng *ipptsp = entry_assoc(entry, &ippts_send->ip_port);
475 502
476 if (!ipptsp) 503 if (!ipptsp) {
477 return 0; 504 return 0;
505 }
478 506
479 entry->hash = hash; 507 entry->hash = hash;
480 id_copy(entry->client.public_key, id); 508 id_copy(entry->client.public_key, id);
481 509
482 if (used) 510 if (used) {
483 entry->used_at = unix_time(); 511 entry->used_at = unix_time();
512 }
484 513
485 if (ipp_recv && !ipport_isset(ipp_recv)) 514 if (ipp_recv && !ipport_isset(ipp_recv)) {
486 ipp_recv = NULL; 515 ipp_recv = NULL;
516 }
487 517
488 if (ipp_recv) { 518 if (ipp_recv) {
489 entry->seen_at = ippts_send->timestamp; 519 entry->seen_at = ippts_send->timestamp;
@@ -511,16 +541,19 @@ static uint8_t candidates_create_new(const Assoc *assoc, hash_t hash, const uint
511 541
512static void client_id_self_update(Assoc *assoc) 542static void client_id_self_update(Assoc *assoc)
513{ 543{
514 if (assoc->self_hash) 544 if (assoc->self_hash) {
515 return; 545 return;
546 }
516 547
517 size_t i, sum = 0; 548 size_t i, sum = 0;
518 549
519 for (i = 0; i < crypto_box_PUBLICKEYBYTES; i++) 550 for (i = 0; i < crypto_box_PUBLICKEYBYTES; i++) {
520 sum |= assoc->self_client_id[i]; 551 sum |= assoc->self_client_id[i];
552 }
521 553
522 if (!sum) 554 if (!sum) {
523 return; 555 return;
556 }
524 557
525 assoc->self_hash = id_hash(assoc, assoc->self_client_id); 558 assoc->self_hash = id_hash(assoc, assoc->self_client_id);
526 559
@@ -536,9 +569,11 @@ static void client_id_self_update(Assoc *assoc)
536 for (i = 0; i < HASH_COLLIDE_COUNT; pos = hash_collide(assoc, pos), i++) { 569 for (i = 0; i < HASH_COLLIDE_COUNT; pos = hash_collide(assoc, pos), i++) {
537 Client_entry *entry = &cnd_bckt->list[pos]; 570 Client_entry *entry = &cnd_bckt->list[pos];
538 571
539 if (entry->hash == assoc->self_hash) 572 if (entry->hash == assoc->self_hash) {
540 if (id_equal(entry->client.public_key, assoc->self_client_id)) 573 if (id_equal(entry->client.public_key, assoc->self_client_id)) {
541 entry->hash = 0; 574 entry->hash = 0;
575 }
576 }
542 } 577 }
543} 578}
544 579
@@ -552,27 +587,33 @@ static void client_id_self_update(Assoc *assoc)
552 */ 587 */
553uint8_t Assoc_add_entry(Assoc *assoc, const uint8_t *id, const IPPTs *ippts_send, const IP_Port *ipp_recv, uint8_t used) 588uint8_t Assoc_add_entry(Assoc *assoc, const uint8_t *id, const IPPTs *ippts_send, const IP_Port *ipp_recv, uint8_t used)
554{ 589{
555 if (!assoc || !id || !ippts_send) 590 if (!assoc || !id || !ippts_send) {
556 return 0; 591 return 0;
592 }
557 593
558 if (!assoc->self_hash) { 594 if (!assoc->self_hash) {
559 client_id_self_update(assoc); 595 client_id_self_update(assoc);
560 596
561 if (!assoc->self_hash) 597 if (!assoc->self_hash) {
562 return 0; 598 return 0;
599 }
563 } 600 }
564 601
565 if (!ipport_isset(&ippts_send->ip_port)) 602 if (!ipport_isset(&ippts_send->ip_port)) {
566 return 0; 603 return 0;
604 }
567 605
568 if (ipp_recv && !ipport_isset(ipp_recv)) 606 if (ipp_recv && !ipport_isset(ipp_recv)) {
569 ipp_recv = NULL; 607 ipp_recv = NULL;
608 }
570 609
571 hash_t hash = id_hash(assoc, id); 610 hash_t hash = id_hash(assoc, id);
572 611
573 if (hash == assoc->self_hash) 612 if (hash == assoc->self_hash) {
574 if (id_equal(id, assoc->self_client_id)) 613 if (id_equal(id, assoc->self_client_id)) {
575 return 0; 614 return 0;
615 }
616 }
576 617
577 /* if it's new: 618 /* if it's new:
578 * callback, if there's desire, add to clients, else to candidates 619 * callback, if there's desire, add to clients, else to candidates
@@ -586,10 +627,11 @@ uint8_t Assoc_add_entry(Assoc *assoc, const uint8_t *id, const IPPTs *ippts_send
586 Client_entry *cnd_entry; 627 Client_entry *cnd_entry;
587 628
588 if (!candidates_search(assoc, id, hash, &cnd_entry)) { 629 if (!candidates_search(assoc, id, hash, &cnd_entry)) {
589 if (candidates_create_new(assoc, hash, id, used, ippts_send, ipp_recv)) 630 if (candidates_create_new(assoc, hash, id, used, ippts_send, ipp_recv)) {
590 return 1; 631 return 1;
591 else 632 } else {
592 return 0; 633 return 0;
634 }
593 } else { 635 } else {
594 candidates_update_assoc(assoc, cnd_entry, used, ippts_send, ipp_recv); 636 candidates_update_assoc(assoc, cnd_entry, used, ippts_send, ipp_recv);
595 return 2; 637 return 2;
@@ -602,21 +644,25 @@ uint8_t Assoc_add_entry(Assoc *assoc, const uint8_t *id, const IPPTs *ippts_send
602 644
603uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state) 645uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
604{ 646{
605 if (!assoc || !state || !state->wanted_id || !state->result) 647 if (!assoc || !state || !state->wanted_id || !state->result) {
606 return 0; 648 return 0;
649 }
607 650
608 if (!assoc->self_hash) { 651 if (!assoc->self_hash) {
609 client_id_self_update(assoc); 652 client_id_self_update(assoc);
610 653
611 if (!assoc->self_hash) 654 if (!assoc->self_hash) {
612 return 0; 655 return 0;
656 }
613 } 657 }
614 658
615 if (!state->distance_relative_func) 659 if (!state->distance_relative_func) {
616 state->distance_relative_func = assoc_id_closest; 660 state->distance_relative_func = assoc_id_closest;
661 }
617 662
618 if (!state->distance_absolute_func) 663 if (!state->distance_absolute_func) {
619 state->distance_absolute_func = id_distance; 664 state->distance_absolute_func = id_distance;
665 }
620 666
621 size_t dist_list_len = assoc->candidates_bucket_count * assoc->candidates_bucket_size; 667 size_t dist_list_len = assoc->candidates_bucket_count * assoc->candidates_bucket_size;
622 uint64_t dist_list[dist_list_len]; 668 uint64_t dist_list[dist_list_len];
@@ -632,21 +678,27 @@ uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
632 678
633 if (entry->hash) { 679 if (entry->hash) {
634 if (state->flags & ProtoIPv4) { 680 if (state->flags & ProtoIPv4) {
635 if (!ipport_isset(&entry->client.assoc4.ip_port)) 681 if (!ipport_isset(&entry->client.assoc4.ip_port)) {
636 continue; 682 continue;
683 }
637 684
638 if (!(state->flags & LANOk)) 685 if (!(state->flags & LANOk)) {
639 if (!LAN_ip(entry->client.assoc4.ip_port.ip)) 686 if (!LAN_ip(entry->client.assoc4.ip_port.ip)) {
640 continue; 687 continue;
688 }
689 }
641 } 690 }
642 691
643 if (state->flags & ProtoIPv6) { 692 if (state->flags & ProtoIPv6) {
644 if (!ipport_isset(&entry->client.assoc6.ip_port)) 693 if (!ipport_isset(&entry->client.assoc6.ip_port)) {
645 continue; 694 continue;
695 }
646 696
647 if (!(state->flags & LANOk)) 697 if (!(state->flags & LANOk)) {
648 if (!LAN_ip(entry->client.assoc6.ip_port.ip)) 698 if (!LAN_ip(entry->client.assoc6.ip_port.ip)) {
649 continue; 699 continue;
700 }
701 }
650 } 702 }
651 703
652 uint64_t dist = state->distance_absolute_func(assoc, state->custom_data, state->wanted_id, entry->client.public_key); 704 uint64_t dist = state->distance_absolute_func(assoc, state->custom_data, state->wanted_id, entry->client.public_key);
@@ -668,17 +720,19 @@ uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
668 720
669 for (ind_curr = 0; ind_curr < dist_list_len; ind_curr++) { 721 for (ind_curr = 0; ind_curr < dist_list_len; ind_curr++) {
670 /* sorted increasingly, so an invalid entry marks the end */ 722 /* sorted increasingly, so an invalid entry marks the end */
671 if ((dist_list[ind_curr] & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) 723 if ((dist_list[ind_curr] & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) {
672 break; 724 break;
725 }
673 726
674 uint64_t dist_curr = dist_list[ind_curr] >> DISTANCE_INDEX_INDEX_BITS; 727 uint64_t dist_curr = dist_list[ind_curr] >> DISTANCE_INDEX_INDEX_BITS;
675 728
676 if (dist_prev == dist_curr) 729 if (dist_prev == dist_curr) {
677 len++; 730 len++;
678 else { 731 } else {
679 if (len > 1) 732 if (len > 1) {
680 dist_index_bubble(assoc, dist_list, ind_prev, ind_curr - 1, state->wanted_id, state->custom_data, 733 dist_index_bubble(assoc, dist_list, ind_prev, ind_curr - 1, state->wanted_id, state->custom_data,
681 state->distance_relative_func); 734 state->distance_relative_func);
735 }
682 736
683 dist_prev = dist_curr; 737 dist_prev = dist_curr;
684 ind_prev = ind_curr; 738 ind_prev = ind_curr;
@@ -686,9 +740,10 @@ uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
686 } 740 }
687 } 741 }
688 742
689 if (len > 1) 743 if (len > 1) {
690 dist_index_bubble(assoc, dist_list, ind_prev, ind_curr - 1, state->wanted_id, state->custom_data, 744 dist_index_bubble(assoc, dist_list, ind_prev, ind_curr - 1, state->wanted_id, state->custom_data,
691 state->distance_relative_func); 745 state->distance_relative_func);
746 }
692 747
693 /* ok, now dist_list is a strictly ascending sorted list of nodes 748 /* ok, now dist_list is a strictly ascending sorted list of nodes
694 * a) extract CLOSE_QUOTA_USED clients, not timed out 749 * a) extract CLOSE_QUOTA_USED clients, not timed out
@@ -701,8 +756,9 @@ uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
701 756
702 for (i = 0; (i < dist_list_len) && (pos < state->count); i++) { 757 for (i = 0; (i < dist_list_len) && (pos < state->count); i++) {
703 /* sorted increasingly, so an invalid entry marks the end */ 758 /* sorted increasingly, so an invalid entry marks the end */
704 if ((dist_list[i] & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) 759 if ((dist_list[i] & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) {
705 break; 760 break;
761 }
706 762
707 Client_entry *entry = dist_index_entry(assoc, dist_list[i]); 763 Client_entry *entry = dist_index_entry(assoc, dist_list[i]);
708 764
@@ -712,13 +768,16 @@ uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
712 taken_last = i; 768 taken_last = i;
713 } else { 769 } else {
714 if (state->flags & (ProtoIPv4 | ProtoIPv6)) { 770 if (state->flags & (ProtoIPv4 | ProtoIPv6)) {
715 if ((state->flags & ProtoIPv4) && is_timeout(entry->client.assoc4.timestamp, BAD_NODE_TIMEOUT)) 771 if ((state->flags & ProtoIPv4) && is_timeout(entry->client.assoc4.timestamp, BAD_NODE_TIMEOUT)) {
716 continue; 772 continue;
773 }
717 774
718 if ((state->flags & ProtoIPv6) && is_timeout(entry->client.assoc6.timestamp, BAD_NODE_TIMEOUT)) 775 if ((state->flags & ProtoIPv6) && is_timeout(entry->client.assoc6.timestamp, BAD_NODE_TIMEOUT)) {
719 continue; 776 continue;
720 } else if (is_timeout(entry->seen_at, BAD_NODE_TIMEOUT)) 777 }
778 } else if (is_timeout(entry->seen_at, BAD_NODE_TIMEOUT)) {
721 continue; 779 continue;
780 }
722 781
723 state->result[pos++] = &entry->client; 782 state->result[pos++] = &entry->client;
724 client_quota_good++; 783 client_quota_good++;
@@ -734,13 +793,15 @@ uint8_t Assoc_get_close_entries(Assoc *assoc, Assoc_close_entries *state)
734 if (pos < state->count) { 793 if (pos < state->count) {
735 for (i = taken_last + 1; (i < dist_list_len) && (pos < state->count); i++) { 794 for (i = taken_last + 1; (i < dist_list_len) && (pos < state->count); i++) {
736 /* sorted increasingly, so an invalid entry marks the end */ 795 /* sorted increasingly, so an invalid entry marks the end */
737 if ((dist_list[i] & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) 796 if ((dist_list[i] & DISTANCE_INDEX_INDEX_MASK) == DISTANCE_INDEX_INDEX_MASK) {
738 break; 797 break;
798 }
739 799
740 Client_entry *entry = dist_index_entry(assoc, dist_list[i]); 800 Client_entry *entry = dist_index_entry(assoc, dist_list[i]);
741 801
742 if (entry && entry->hash) 802 if (entry && entry->hash) {
743 state->result[pos++] = &entry->client; 803 state->result[pos++] = &entry->client;
804 }
744 } 805 }
745 } 806 }
746 807
@@ -756,8 +817,9 @@ static uint8_t odd_min9_is_prime(size_t value)
756 size_t i = 3; 817 size_t i = 3;
757 818
758 while (i * i <= value) { 819 while (i * i <= value) {
759 if (!(value % i)) 820 if (!(value % i)) {
760 return 0; 821 return 0;
822 }
761 823
762 i += 2; 824 i += 2;
763 } 825 }
@@ -770,8 +832,9 @@ static size_t prime_upto_min9(size_t limit)
770 /* even => odd */ 832 /* even => odd */
771 limit = limit - (1 - (limit % 2)); 833 limit = limit - (1 - (limit % 2));
772 834
773 while (!odd_min9_is_prime(limit)) 835 while (!odd_min9_is_prime(limit)) {
774 limit -= 2; 836 limit -= 2;
837 }
775 838
776 return limit; 839 return limit;
777} 840}
@@ -779,13 +842,15 @@ static size_t prime_upto_min9(size_t limit)
779/* create */ 842/* create */
780Assoc *new_Assoc(Logger *log, size_t bits, size_t entries, const uint8_t *public_id) 843Assoc *new_Assoc(Logger *log, size_t bits, size_t entries, const uint8_t *public_id)
781{ 844{
782 if (!public_id) 845 if (!public_id) {
783 return NULL; 846 return NULL;
847 }
784 848
785 Assoc *assoc = calloc(1, sizeof(*assoc)); 849 Assoc *assoc = calloc(1, sizeof(*assoc));
786 850
787 if (!assoc) 851 if (!assoc) {
788 return NULL; 852 return NULL;
853 }
789 854
790 assoc->log = log; 855 assoc->log = log;
791 856
@@ -793,32 +858,35 @@ Assoc *new_Assoc(Logger *log, size_t bits, size_t entries, const uint8_t *public
793 * bits must be in [ 2 .. 15 ] 858 * bits must be in [ 2 .. 15 ]
794 * entries must be a prime 859 * entries must be a prime
795 */ 860 */
796 if (bits < 2) 861 if (bits < 2) {
797 bits = 2; 862 bits = 2;
798 else if (bits > 15) 863 } else if (bits > 15) {
799 bits = 15; 864 bits = 15;
865 }
800 866
801 assoc->candidates_bucket_bits = bits; 867 assoc->candidates_bucket_bits = bits;
802 assoc->candidates_bucket_count = 1U << bits; 868 assoc->candidates_bucket_count = 1U << bits;
803 869
804 if (entries < 25) { 870 if (entries < 25) {
805 if (entries <= 6) 871 if (entries <= 6) {
806 entries = 5; 872 entries = 5;
807 else { 873 } else {
808 entries = entries - (1 - (entries % 2)); /* even => odd */ 874 entries = entries - (1 - (entries % 2)); /* even => odd */
809 875
810 /* 7..23: all odds but 9&15 are prime */ 876 /* 7..23: all odds but 9&15 are prime */
811 if (!(entries % 3)) /* 9, 15 */ 877 if (!(entries % 3)) { /* 9, 15 */
812 entries -= 2; /* 7, 13 */ 878 entries -= 2; /* 7, 13 */
879 }
813 } 880 }
814 } else if (entries > ((1 << 17) - 1)) /* 130k+ */ 881 } else if (entries > ((1 << 17) - 1)) { /* 130k+ */
815 entries = (1 << 17) - 1; 882 entries = (1 << 17) - 1;
816 else { 883 } else {
817 /* 9+: test and find a prime less or equal */ 884 /* 9+: test and find a prime less or equal */
818 size_t entries_test = prime_upto_min9(entries); 885 size_t entries_test = prime_upto_min9(entries);
819 886
820 if (entries_test == HASH_COLLIDE_PRIME) /* disallowed */ 887 if (entries_test == HASH_COLLIDE_PRIME) { /* disallowed */
821 entries_test = prime_upto_min9(entries_test - 1); 888 entries_test = prime_upto_min9(entries_test - 1);
889 }
822 890
823 if (entries_test != entries) { 891 if (entries_test != entries) {
824 892
@@ -851,8 +919,9 @@ Assoc *new_Assoc(Logger *log, size_t bits, size_t entries, const uint8_t *public
851 919
852 list->list = &clients[bckt * assoc->candidates_bucket_size]; 920 list->list = &clients[bckt * assoc->candidates_bucket_size];
853 921
854 for (cix = 0; cix < assoc->candidates_bucket_size; cix++) 922 for (cix = 0; cix < assoc->candidates_bucket_size; cix++) {
855 list->list[cix].hash = 0; 923 list->list[cix].hash = 0;
924 }
856 } 925 }
857 926
858 assoc->candidates = lists; 927 assoc->candidates = lists;
@@ -900,41 +969,51 @@ void do_Assoc(Assoc *assoc, DHT *dht)
900 size_t i, k, m; 969 size_t i, k, m;
901 970
902 for (i = 1; i < assoc->candidates_bucket_count; i++) { 971 for (i = 1; i < assoc->candidates_bucket_count; i++) {
903 if (i % 2) 972 if (i % 2) {
904 k = - (i >> 1); 973 k = - (i >> 1);
905 else 974 } else {
906 k = i >> 1; 975 k = i >> 1;
976 }
907 977
908 size_t bckt = (candidate + k) % assoc->candidates_bucket_count; 978 size_t bckt = (candidate + k) % assoc->candidates_bucket_count;
909 979
910 for (m = 0; m < assoc->candidates_bucket_size; m++) 980 for (m = 0; m < assoc->candidates_bucket_size; m++) {
911 if (assoc->candidates[bckt].list[m].hash) { 981 if (assoc->candidates[bckt].list[m].hash) {
912 Client_entry *entry = &assoc->candidates[bckt].list[m]; 982 Client_entry *entry = &assoc->candidates[bckt].list[m];
913 983
914 if (!is_timeout(entry->getnodes, CANDIDATES_SEEN_TIMEOUT)) 984 if (!is_timeout(entry->getnodes, CANDIDATES_SEEN_TIMEOUT)) {
915 continue; 985 continue;
986 }
916 987
917 if (!target_id) 988 if (!target_id) {
918 target_id = entry->client.public_key; 989 target_id = entry->client.public_key;
990 }
919 991
920 if (entry->seen_at) { 992 if (entry->seen_at) {
921 if (!seen) 993 if (!seen) {
922 if (!is_timeout(entry->seen_at, CANDIDATES_SEEN_TIMEOUT)) 994 if (!is_timeout(entry->seen_at, CANDIDATES_SEEN_TIMEOUT)) {
923 seen = entry; 995 seen = entry;
996 }
997 }
924 } 998 }
925 999
926 if (entry->heard_at) { 1000 if (entry->heard_at) {
927 if (!heard) 1001 if (!heard) {
928 if (!is_timeout(entry->heard_at, CANDIDATES_HEARD_TIMEOUT)) 1002 if (!is_timeout(entry->heard_at, CANDIDATES_HEARD_TIMEOUT)) {
929 heard = entry; 1003 heard = entry;
1004 }
1005 }
930 } 1006 }
931 1007
932 if (seen && heard) 1008 if (seen && heard) {
933 break; 1009 break;
1010 }
934 } 1011 }
1012 }
935 1013
936 if (seen && heard) 1014 if (seen && heard) {
937 break; 1015 break;
1016 }
938 } 1017 }
939 1018
940 if (seen) { 1019 if (seen) {
@@ -976,13 +1055,15 @@ void kill_Assoc(Assoc *assoc)
976static char buffer[crypto_box_PUBLICKEYBYTES * 2 + 1]; 1055static char buffer[crypto_box_PUBLICKEYBYTES * 2 + 1];
977static char *idpart2str(uint8_t *id, size_t len) 1056static char *idpart2str(uint8_t *id, size_t len)
978{ 1057{
979 if (len > crypto_box_PUBLICKEYBYTES) 1058 if (len > crypto_box_PUBLICKEYBYTES) {
980 len = crypto_box_PUBLICKEYBYTES; 1059 len = crypto_box_PUBLICKEYBYTES;
1060 }
981 1061
982 size_t i; 1062 size_t i;
983 1063
984 for (i = 0; i < len; i++) 1064 for (i = 0; i < len; i++) {
985 sprintf(buffer + i * 2, "%02hhx", id[i]); 1065 sprintf(buffer + i * 2, "%02hhx", id[i]);
1066 }
986 1067
987 buffer[len * 2] = 0; 1068 buffer[len * 2] = 0;
988 return buffer; 1069 return buffer;
diff --git a/toxcore/crypto_core.c b/toxcore/crypto_core.c
index 3b379ca6..bcfd7e60 100644
--- a/toxcore/crypto_core.c
+++ b/toxcore/crypto_core.c
@@ -65,8 +65,9 @@ uint64_t random_64b(void)
65 */ 65 */
66int public_key_valid(const uint8_t *public_key) 66int public_key_valid(const uint8_t *public_key)
67{ 67{
68 if (public_key[31] >= 128) /* Last bit of key is always zero. */ 68 if (public_key[31] >= 128) { /* Last bit of key is always zero. */
69 return 0; 69 return 0;
70 }
70 71
71 return 1; 72 return 1;
72} 73}
@@ -84,8 +85,9 @@ int encrypt_precompute(const uint8_t *public_key, const uint8_t *secret_key, uin
84int encrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, const uint8_t *plain, uint32_t length, 85int encrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, const uint8_t *plain, uint32_t length,
85 uint8_t *encrypted) 86 uint8_t *encrypted)
86{ 87{
87 if (length == 0 || !secret_key || !nonce || !plain || !encrypted) 88 if (length == 0 || !secret_key || !nonce || !plain || !encrypted) {
88 return -1; 89 return -1;
90 }
89 91
90 uint8_t temp_plain[length + crypto_box_ZEROBYTES]; 92 uint8_t temp_plain[length + crypto_box_ZEROBYTES];
91 uint8_t temp_encrypted[length + crypto_box_MACBYTES + crypto_box_BOXZEROBYTES]; 93 uint8_t temp_encrypted[length + crypto_box_MACBYTES + crypto_box_BOXZEROBYTES];
@@ -93,8 +95,9 @@ int encrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, cons
93 memset(temp_plain, 0, crypto_box_ZEROBYTES); 95 memset(temp_plain, 0, crypto_box_ZEROBYTES);
94 memcpy(temp_plain + crypto_box_ZEROBYTES, plain, length); // Pad the message with 32 0 bytes. 96 memcpy(temp_plain + crypto_box_ZEROBYTES, plain, length); // Pad the message with 32 0 bytes.
95 97
96 if (crypto_box_afternm(temp_encrypted, temp_plain, length + crypto_box_ZEROBYTES, nonce, secret_key) != 0) 98 if (crypto_box_afternm(temp_encrypted, temp_plain, length + crypto_box_ZEROBYTES, nonce, secret_key) != 0) {
97 return -1; 99 return -1;
100 }
98 101
99 /* Unpad the encrypted message. */ 102 /* Unpad the encrypted message. */
100 memcpy(encrypted, temp_encrypted + crypto_box_BOXZEROBYTES, length + crypto_box_MACBYTES); 103 memcpy(encrypted, temp_encrypted + crypto_box_BOXZEROBYTES, length + crypto_box_MACBYTES);
@@ -104,8 +107,9 @@ int encrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, cons
104int decrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, const uint8_t *encrypted, uint32_t length, 107int decrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, const uint8_t *encrypted, uint32_t length,
105 uint8_t *plain) 108 uint8_t *plain)
106{ 109{
107 if (length <= crypto_box_BOXZEROBYTES || !secret_key || !nonce || !encrypted || !plain) 110 if (length <= crypto_box_BOXZEROBYTES || !secret_key || !nonce || !encrypted || !plain) {
108 return -1; 111 return -1;
112 }
109 113
110 uint8_t temp_plain[length + crypto_box_ZEROBYTES]; 114 uint8_t temp_plain[length + crypto_box_ZEROBYTES];
111 uint8_t temp_encrypted[length + crypto_box_BOXZEROBYTES]; 115 uint8_t temp_encrypted[length + crypto_box_BOXZEROBYTES];
@@ -113,8 +117,9 @@ int decrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, cons
113 memset(temp_encrypted, 0, crypto_box_BOXZEROBYTES); 117 memset(temp_encrypted, 0, crypto_box_BOXZEROBYTES);
114 memcpy(temp_encrypted + crypto_box_BOXZEROBYTES, encrypted, length); // Pad the message with 16 0 bytes. 118 memcpy(temp_encrypted + crypto_box_BOXZEROBYTES, encrypted, length); // Pad the message with 16 0 bytes.
115 119
116 if (crypto_box_open_afternm(temp_plain, temp_encrypted, length + crypto_box_BOXZEROBYTES, nonce, secret_key) != 0) 120 if (crypto_box_open_afternm(temp_plain, temp_encrypted, length + crypto_box_BOXZEROBYTES, nonce, secret_key) != 0) {
117 return -1; 121 return -1;
122 }
118 123
119 memcpy(plain, temp_plain + crypto_box_ZEROBYTES, length - crypto_box_MACBYTES); 124 memcpy(plain, temp_plain + crypto_box_ZEROBYTES, length - crypto_box_MACBYTES);
120 return length - crypto_box_MACBYTES; 125 return length - crypto_box_MACBYTES;
@@ -123,8 +128,9 @@ int decrypt_data_symmetric(const uint8_t *secret_key, const uint8_t *nonce, cons
123int encrypt_data(const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *nonce, 128int encrypt_data(const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *nonce,
124 const uint8_t *plain, uint32_t length, uint8_t *encrypted) 129 const uint8_t *plain, uint32_t length, uint8_t *encrypted)
125{ 130{
126 if (!public_key || !secret_key) 131 if (!public_key || !secret_key) {
127 return -1; 132 return -1;
133 }
128 134
129 uint8_t k[crypto_box_BEFORENMBYTES]; 135 uint8_t k[crypto_box_BEFORENMBYTES];
130 encrypt_precompute(public_key, secret_key, k); 136 encrypt_precompute(public_key, secret_key, k);
@@ -136,8 +142,9 @@ int encrypt_data(const uint8_t *public_key, const uint8_t *secret_key, const uin
136int decrypt_data(const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *nonce, 142int decrypt_data(const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *nonce,
137 const uint8_t *encrypted, uint32_t length, uint8_t *plain) 143 const uint8_t *encrypted, uint32_t length, uint8_t *plain)
138{ 144{
139 if (!public_key || !secret_key) 145 if (!public_key || !secret_key) {
140 return -1; 146 return -1;
147 }
141 148
142 uint8_t k[crypto_box_BEFORENMBYTES]; 149 uint8_t k[crypto_box_BEFORENMBYTES];
143 encrypt_precompute(public_key, secret_key, k); 150 encrypt_precompute(public_key, secret_key, k);
@@ -222,12 +229,14 @@ void new_nonce(uint8_t *nonce)
222int create_request(const uint8_t *send_public_key, const uint8_t *send_secret_key, uint8_t *packet, 229int create_request(const uint8_t *send_public_key, const uint8_t *send_secret_key, uint8_t *packet,
223 const uint8_t *recv_public_key, const uint8_t *data, uint32_t length, uint8_t request_id) 230 const uint8_t *recv_public_key, const uint8_t *data, uint32_t length, uint8_t request_id)
224{ 231{
225 if (!send_public_key || !packet || !recv_public_key || !data) 232 if (!send_public_key || !packet || !recv_public_key || !data) {
226 return -1; 233 return -1;
234 }
227 235
228 if (MAX_CRYPTO_REQUEST_SIZE < length + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + 236 if (MAX_CRYPTO_REQUEST_SIZE < length + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 +
229 crypto_box_MACBYTES) 237 crypto_box_MACBYTES) {
230 return -1; 238 return -1;
239 }
231 240
232 uint8_t *nonce = packet + 1 + crypto_box_PUBLICKEYBYTES * 2; 241 uint8_t *nonce = packet + 1 + crypto_box_PUBLICKEYBYTES * 2;
233 new_nonce(nonce); 242 new_nonce(nonce);
@@ -237,8 +246,9 @@ int create_request(const uint8_t *send_public_key, const uint8_t *send_secret_ke
237 int len = encrypt_data(recv_public_key, send_secret_key, nonce, temp, length + 1, 246 int len = encrypt_data(recv_public_key, send_secret_key, nonce, temp, length + 1,
238 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + packet); 247 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + packet);
239 248
240 if (len == -1) 249 if (len == -1) {
241 return -1; 250 return -1;
251 }
242 252
243 packet[0] = NET_PACKET_CRYPTO; 253 packet[0] = NET_PACKET_CRYPTO;
244 memcpy(packet + 1, recv_public_key, crypto_box_PUBLICKEYBYTES); 254 memcpy(packet + 1, recv_public_key, crypto_box_PUBLICKEYBYTES);
@@ -256,15 +266,18 @@ int create_request(const uint8_t *send_public_key, const uint8_t *send_secret_ke
256int handle_request(const uint8_t *self_public_key, const uint8_t *self_secret_key, uint8_t *public_key, uint8_t *data, 266int handle_request(const uint8_t *self_public_key, const uint8_t *self_secret_key, uint8_t *public_key, uint8_t *data,
257 uint8_t *request_id, const uint8_t *packet, uint16_t length) 267 uint8_t *request_id, const uint8_t *packet, uint16_t length)
258{ 268{
259 if (!self_public_key || !public_key || !data || !request_id || !packet) 269 if (!self_public_key || !public_key || !data || !request_id || !packet) {
260 return -1; 270 return -1;
271 }
261 272
262 if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES || 273 if (length <= crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + crypto_box_MACBYTES ||
263 length > MAX_CRYPTO_REQUEST_SIZE) 274 length > MAX_CRYPTO_REQUEST_SIZE) {
264 return -1; 275 return -1;
276 }
265 277
266 if (public_key_cmp(packet + 1, self_public_key) != 0) 278 if (public_key_cmp(packet + 1, self_public_key) != 0) {
267 return -1; 279 return -1;
280 }
268 281
269 memcpy(public_key, packet + 1 + crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES); 282 memcpy(public_key, packet + 1 + crypto_box_PUBLICKEYBYTES, crypto_box_PUBLICKEYBYTES);
270 const uint8_t *nonce = packet + 1 + crypto_box_PUBLICKEYBYTES * 2; 283 const uint8_t *nonce = packet + 1 + crypto_box_PUBLICKEYBYTES * 2;
@@ -273,8 +286,9 @@ int handle_request(const uint8_t *self_public_key, const uint8_t *self_secret_ke
273 packet + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES, 286 packet + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES,
274 length - (crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1), temp); 287 length - (crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1), temp);
275 288
276 if (len1 == -1 || len1 == 0) 289 if (len1 == -1 || len1 == 0) {
277 return -1; 290 return -1;
291 }
278 292
279 request_id[0] = temp[0]; 293 request_id[0] = temp[0];
280 --len1; 294 --len1;
diff --git a/toxcore/friend_connection.c b/toxcore/friend_connection.c
index 858e54b3..31a7d187 100644
--- a/toxcore/friend_connection.c
+++ b/toxcore/friend_connection.c
@@ -33,14 +33,17 @@
33 */ 33 */
34static uint8_t friendconn_id_not_valid(const Friend_Connections *fr_c, int friendcon_id) 34static uint8_t friendconn_id_not_valid(const Friend_Connections *fr_c, int friendcon_id)
35{ 35{
36 if ((unsigned int)friendcon_id >= fr_c->num_cons) 36 if ((unsigned int)friendcon_id >= fr_c->num_cons) {
37 return 1; 37 return 1;
38 }
38 39
39 if (fr_c->conns == NULL) 40 if (fr_c->conns == NULL) {
40 return 1; 41 return 1;
42 }
41 43
42 if (fr_c->conns[friendcon_id].status == FRIENDCONN_STATUS_NONE) 44 if (fr_c->conns[friendcon_id].status == FRIENDCONN_STATUS_NONE) {
43 return 1; 45 return 1;
46 }
44 47
45 return 0; 48 return 0;
46} 49}
@@ -61,8 +64,9 @@ static int realloc_friendconns(Friend_Connections *fr_c, uint32_t num)
61 64
62 Friend_Conn *newgroup_cons = realloc(fr_c->conns, num * sizeof(Friend_Conn)); 65 Friend_Conn *newgroup_cons = realloc(fr_c->conns, num * sizeof(Friend_Conn));
63 66
64 if (newgroup_cons == NULL) 67 if (newgroup_cons == NULL) {
65 return -1; 68 return -1;
69 }
66 70
67 fr_c->conns = newgroup_cons; 71 fr_c->conns = newgroup_cons;
68 return 0; 72 return 0;
@@ -78,8 +82,9 @@ static int create_friend_conn(Friend_Connections *fr_c)
78 uint32_t i; 82 uint32_t i;
79 83
80 for (i = 0; i < fr_c->num_cons; ++i) { 84 for (i = 0; i < fr_c->num_cons; ++i) {
81 if (fr_c->conns[i].status == FRIENDCONN_STATUS_NONE) 85 if (fr_c->conns[i].status == FRIENDCONN_STATUS_NONE) {
82 return i; 86 return i;
87 }
83 } 88 }
84 89
85 int id = -1; 90 int id = -1;
@@ -100,15 +105,17 @@ static int create_friend_conn(Friend_Connections *fr_c)
100 */ 105 */
101static int wipe_friend_conn(Friend_Connections *fr_c, int friendcon_id) 106static int wipe_friend_conn(Friend_Connections *fr_c, int friendcon_id)
102{ 107{
103 if (friendconn_id_not_valid(fr_c, friendcon_id)) 108 if (friendconn_id_not_valid(fr_c, friendcon_id)) {
104 return -1; 109 return -1;
110 }
105 111
106 uint32_t i; 112 uint32_t i;
107 memset(&(fr_c->conns[friendcon_id]), 0 , sizeof(Friend_Conn)); 113 memset(&(fr_c->conns[friendcon_id]), 0 , sizeof(Friend_Conn));
108 114
109 for (i = fr_c->num_cons; i != 0; --i) { 115 for (i = fr_c->num_cons; i != 0; --i) {
110 if (fr_c->conns[i - 1].status != FRIENDCONN_STATUS_NONE) 116 if (fr_c->conns[i - 1].status != FRIENDCONN_STATUS_NONE) {
111 break; 117 break;
118 }
112 } 119 }
113 120
114 if (fr_c->num_cons != i) { 121 if (fr_c->num_cons != i) {
@@ -121,8 +128,9 @@ static int wipe_friend_conn(Friend_Connections *fr_c, int friendcon_id)
121 128
122static Friend_Conn *get_conn(const Friend_Connections *fr_c, int friendcon_id) 129static Friend_Conn *get_conn(const Friend_Connections *fr_c, int friendcon_id)
123{ 130{
124 if (friendconn_id_not_valid(fr_c, friendcon_id)) 131 if (friendconn_id_not_valid(fr_c, friendcon_id)) {
125 return 0; 132 return 0;
133 }
126 134
127 return &fr_c->conns[friendcon_id]; 135 return &fr_c->conns[friendcon_id];
128} 136}
@@ -138,8 +146,9 @@ int getfriend_conn_id_pk(Friend_Connections *fr_c, const uint8_t *real_pk)
138 Friend_Conn *friend_con = get_conn(fr_c, i); 146 Friend_Conn *friend_con = get_conn(fr_c, i);
139 147
140 if (friend_con) { 148 if (friend_con) {
141 if (public_key_cmp(friend_con->real_public_key, real_pk) == 0) 149 if (public_key_cmp(friend_con->real_public_key, real_pk) == 0) {
142 return i; 150 return i;
151 }
143 } 152 }
144 } 153 }
145 154
@@ -155,8 +164,9 @@ int friend_add_tcp_relay(Friend_Connections *fr_c, int friendcon_id, IP_Port ip_
155{ 164{
156 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 165 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
157 166
158 if (!friend_con) 167 if (!friend_con) {
159 return -1; 168 return -1;
169 }
160 170
161 /* Local ip and same pk means that they are hosting a TCP relay. */ 171 /* Local ip and same pk means that they are hosting a TCP relay. */
162 if (Local_ip(ip_port.ip) && public_key_cmp(friend_con->dht_temp_pk, public_key) == 0) { 172 if (Local_ip(ip_port.ip) && public_key_cmp(friend_con->dht_temp_pk, public_key) == 0) {
@@ -190,8 +200,9 @@ static void connect_to_saved_tcp_relays(Friend_Connections *fr_c, int friendcon_
190{ 200{
191 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 201 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
192 202
193 if (!friend_con) 203 if (!friend_con) {
194 return; 204 return;
205 }
195 206
196 unsigned int i; 207 unsigned int i;
197 208
@@ -211,8 +222,9 @@ static unsigned int send_relays(Friend_Connections *fr_c, int friendcon_id)
211{ 222{
212 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 223 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
213 224
214 if (!friend_con) 225 if (!friend_con) {
215 return 0; 226 return 0;
227 }
216 228
217 Node_format nodes[MAX_SHARED_RELAYS]; 229 Node_format nodes[MAX_SHARED_RELAYS];
218 uint8_t data[1024]; 230 uint8_t data[1024];
@@ -230,8 +242,9 @@ static unsigned int send_relays(Friend_Connections *fr_c, int friendcon_id)
230 242
231 length = pack_nodes(data + 1, sizeof(data) - 1, nodes, n); 243 length = pack_nodes(data + 1, sizeof(data) - 1, nodes, n);
232 244
233 if (length <= 0) 245 if (length <= 0) {
234 return 0; 246 return 0;
247 }
235 248
236 data[0] = PACKET_ID_SHARE_RELAYS; 249 data[0] = PACKET_ID_SHARE_RELAYS;
237 ++length; 250 ++length;
@@ -250,8 +263,9 @@ static int tcp_relay_node_callback(void *object, uint32_t number, IP_Port ip_por
250 Friend_Connections *fr_c = object; 263 Friend_Connections *fr_c = object;
251 Friend_Conn *friend_con = get_conn(fr_c, number); 264 Friend_Conn *friend_con = get_conn(fr_c, number);
252 265
253 if (!friend_con) 266 if (!friend_con) {
254 return -1; 267 return -1;
268 }
255 269
256 if (friend_con->crypt_connection_id != -1) { 270 if (friend_con->crypt_connection_id != -1) {
257 return friend_add_tcp_relay(fr_c, number, ip_port, public_key); 271 return friend_add_tcp_relay(fr_c, number, ip_port, public_key);
@@ -267,8 +281,9 @@ static void dht_ip_callback(void *object, int32_t number, IP_Port ip_port)
267 Friend_Connections *fr_c = object; 281 Friend_Connections *fr_c = object;
268 Friend_Conn *friend_con = get_conn(fr_c, number); 282 Friend_Conn *friend_con = get_conn(fr_c, number);
269 283
270 if (!friend_con) 284 if (!friend_con) {
271 return; 285 return;
286 }
272 287
273 if (friend_con->crypt_connection_id == -1) { 288 if (friend_con->crypt_connection_id == -1) {
274 friend_new_connection(fr_c, number); 289 friend_new_connection(fr_c, number);
@@ -288,8 +303,9 @@ static void change_dht_pk(Friend_Connections *fr_c, int friendcon_id, const uint
288{ 303{
289 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 304 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
290 305
291 if (!friend_con) 306 if (!friend_con) {
292 return; 307 return;
308 }
293 309
294 friend_con->dht_pk_lastrecv = unix_time(); 310 friend_con->dht_pk_lastrecv = unix_time();
295 311
@@ -311,8 +327,9 @@ static int handle_status(void *object, int number, uint8_t status)
311 Friend_Connections *fr_c = object; 327 Friend_Connections *fr_c = object;
312 Friend_Conn *friend_con = get_conn(fr_c, number); 328 Friend_Conn *friend_con = get_conn(fr_c, number);
313 329
314 if (!friend_con) 330 if (!friend_con) {
315 return -1; 331 return -1;
332 }
316 333
317 _Bool call_cb = 0; 334 _Bool call_cb = 0;
318 335
@@ -338,9 +355,10 @@ static int handle_status(void *object, int number, uint8_t status)
338 unsigned int i; 355 unsigned int i;
339 356
340 for (i = 0; i < MAX_FRIEND_CONNECTION_CALLBACKS; ++i) { 357 for (i = 0; i < MAX_FRIEND_CONNECTION_CALLBACKS; ++i) {
341 if (friend_con->callbacks[i].status_callback) 358 if (friend_con->callbacks[i].status_callback) {
342 friend_con->callbacks[i].status_callback(friend_con->callbacks[i].status_callback_object, 359 friend_con->callbacks[i].status_callback(friend_con->callbacks[i].status_callback_object,
343 friend_con->callbacks[i].status_callback_id, status); 360 friend_con->callbacks[i].status_callback_id, status);
361 }
344 } 362 }
345 } 363 }
346 364
@@ -353,11 +371,13 @@ static void dht_pk_callback(void *object, int32_t number, const uint8_t *dht_pub
353 Friend_Connections *fr_c = object; 371 Friend_Connections *fr_c = object;
354 Friend_Conn *friend_con = get_conn(fr_c, number); 372 Friend_Conn *friend_con = get_conn(fr_c, number);
355 373
356 if (!friend_con) 374 if (!friend_con) {
357 return; 375 return;
376 }
358 377
359 if (public_key_cmp(friend_con->dht_temp_pk, dht_public_key) == 0) 378 if (public_key_cmp(friend_con->dht_temp_pk, dht_public_key) == 0) {
360 return; 379 return;
380 }
361 381
362 change_dht_pk(fr_c, number, dht_public_key); 382 change_dht_pk(fr_c, number, dht_public_key);
363 383
@@ -374,18 +394,21 @@ static void dht_pk_callback(void *object, int32_t number, const uint8_t *dht_pub
374 394
375static int handle_packet(void *object, int number, uint8_t *data, uint16_t length, void *userdata) 395static int handle_packet(void *object, int number, uint8_t *data, uint16_t length, void *userdata)
376{ 396{
377 if (length == 0) 397 if (length == 0) {
378 return -1; 398 return -1;
399 }
379 400
380 Friend_Connections *fr_c = object; 401 Friend_Connections *fr_c = object;
381 Friend_Conn *friend_con = get_conn(fr_c, number); 402 Friend_Conn *friend_con = get_conn(fr_c, number);
382 403
383 if (!friend_con) 404 if (!friend_con) {
384 return -1; 405 return -1;
406 }
385 407
386 if (data[0] == PACKET_ID_FRIEND_REQUESTS) { 408 if (data[0] == PACKET_ID_FRIEND_REQUESTS) {
387 if (fr_c->fr_request_callback) 409 if (fr_c->fr_request_callback) {
388 fr_c->fr_request_callback(fr_c->fr_request_object, friend_con->real_public_key, data, length); 410 fr_c->fr_request_callback(fr_c->fr_request_object, friend_con->real_public_key, data, length);
411 }
389 412
390 return 0; 413 return 0;
391 } else if (data[0] == PACKET_ID_ALIVE) { 414 } else if (data[0] == PACKET_ID_ALIVE) {
@@ -395,8 +418,9 @@ static int handle_packet(void *object, int number, uint8_t *data, uint16_t lengt
395 Node_format nodes[MAX_SHARED_RELAYS]; 418 Node_format nodes[MAX_SHARED_RELAYS];
396 int n; 419 int n;
397 420
398 if ((n = unpack_nodes(nodes, MAX_SHARED_RELAYS, NULL, data + 1, length - 1, 1)) == -1) 421 if ((n = unpack_nodes(nodes, MAX_SHARED_RELAYS, NULL, data + 1, length - 1, 1)) == -1) {
399 return -1; 422 return -1;
423 }
400 424
401 int j; 425 int j;
402 426
@@ -410,15 +434,17 @@ static int handle_packet(void *object, int number, uint8_t *data, uint16_t lengt
410 unsigned int i; 434 unsigned int i;
411 435
412 for (i = 0; i < MAX_FRIEND_CONNECTION_CALLBACKS; ++i) { 436 for (i = 0; i < MAX_FRIEND_CONNECTION_CALLBACKS; ++i) {
413 if (friend_con->callbacks[i].data_callback) 437 if (friend_con->callbacks[i].data_callback) {
414 friend_con->callbacks[i].data_callback( 438 friend_con->callbacks[i].data_callback(
415 friend_con->callbacks[i].data_callback_object, 439 friend_con->callbacks[i].data_callback_object,
416 friend_con->callbacks[i].data_callback_id, data, length, userdata); 440 friend_con->callbacks[i].data_callback_id, data, length, userdata);
441 }
417 442
418 friend_con = get_conn(fr_c, number); 443 friend_con = get_conn(fr_c, number);
419 444
420 if (!friend_con) 445 if (!friend_con) {
421 return -1; 446 return -1;
447 }
422 } 448 }
423 449
424 return 0; 450 return 0;
@@ -426,26 +452,30 @@ static int handle_packet(void *object, int number, uint8_t *data, uint16_t lengt
426 452
427static int handle_lossy_packet(void *object, int number, const uint8_t *data, uint16_t length) 453static int handle_lossy_packet(void *object, int number, const uint8_t *data, uint16_t length)
428{ 454{
429 if (length == 0) 455 if (length == 0) {
430 return -1; 456 return -1;
457 }
431 458
432 Friend_Connections *fr_c = object; 459 Friend_Connections *fr_c = object;
433 Friend_Conn *friend_con = get_conn(fr_c, number); 460 Friend_Conn *friend_con = get_conn(fr_c, number);
434 461
435 if (!friend_con) 462 if (!friend_con) {
436 return -1; 463 return -1;
464 }
437 465
438 unsigned int i; 466 unsigned int i;
439 467
440 for (i = 0; i < MAX_FRIEND_CONNECTION_CALLBACKS; ++i) { 468 for (i = 0; i < MAX_FRIEND_CONNECTION_CALLBACKS; ++i) {
441 if (friend_con->callbacks[i].lossy_data_callback) 469 if (friend_con->callbacks[i].lossy_data_callback) {
442 friend_con->callbacks[i].lossy_data_callback(friend_con->callbacks[i].lossy_data_callback_object, 470 friend_con->callbacks[i].lossy_data_callback(friend_con->callbacks[i].lossy_data_callback_object,
443 friend_con->callbacks[i].lossy_data_callback_id, data, length); 471 friend_con->callbacks[i].lossy_data_callback_id, data, length);
472 }
444 473
445 friend_con = get_conn(fr_c, number); 474 friend_con = get_conn(fr_c, number);
446 475
447 if (!friend_con) 476 if (!friend_con) {
448 return -1; 477 return -1;
478 }
449 } 479 }
450 480
451 return 0; 481 return 0;
@@ -459,8 +489,9 @@ static int handle_new_connections(void *object, New_Connection *n_c)
459 489
460 if (friend_con) { 490 if (friend_con) {
461 491
462 if (friend_con->crypt_connection_id != -1) 492 if (friend_con->crypt_connection_id != -1) {
463 return -1; 493 return -1;
494 }
464 495
465 int id = accept_crypto_connection(fr_c->net_crypto, n_c); 496 int id = accept_crypto_connection(fr_c->net_crypto, n_c);
466 497
@@ -495,8 +526,9 @@ static int friend_new_connection(Friend_Connections *fr_c, int friendcon_id)
495{ 526{
496 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 527 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
497 528
498 if (!friend_con) 529 if (!friend_con) {
499 return -1; 530 return -1;
531 }
500 532
501 if (friend_con->crypt_connection_id != -1) { 533 if (friend_con->crypt_connection_id != -1) {
502 return -1; 534 return -1;
@@ -509,8 +541,9 @@ static int friend_new_connection(Friend_Connections *fr_c, int friendcon_id)
509 541
510 int id = new_crypto_connection(fr_c->net_crypto, friend_con->real_public_key, friend_con->dht_temp_pk); 542 int id = new_crypto_connection(fr_c->net_crypto, friend_con->real_public_key, friend_con->dht_temp_pk);
511 543
512 if (id == -1) 544 if (id == -1) {
513 return -1; 545 return -1;
546 }
514 547
515 friend_con->crypt_connection_id = id; 548 friend_con->crypt_connection_id = id;
516 connection_status_handler(fr_c->net_crypto, id, &handle_status, fr_c, friendcon_id); 549 connection_status_handler(fr_c->net_crypto, id, &handle_status, fr_c, friendcon_id);
@@ -525,8 +558,9 @@ static int send_ping(const Friend_Connections *fr_c, int friendcon_id)
525{ 558{
526 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 559 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
527 560
528 if (!friend_con) 561 if (!friend_con) {
529 return -1; 562 return -1;
563 }
530 564
531 uint8_t ping = PACKET_ID_ALIVE; 565 uint8_t ping = PACKET_ID_ALIVE;
532 int64_t ret = write_cryptpacket(fr_c->net_crypto, friend_con->crypt_connection_id, &ping, sizeof(ping), 0); 566 int64_t ret = write_cryptpacket(fr_c->net_crypto, friend_con->crypt_connection_id, &ping, sizeof(ping), 0);
@@ -548,8 +582,9 @@ int friend_connection_lock(Friend_Connections *fr_c, int friendcon_id)
548{ 582{
549 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 583 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
550 584
551 if (!friend_con) 585 if (!friend_con) {
552 return -1; 586 return -1;
587 }
553 588
554 ++friend_con->lock_count; 589 ++friend_con->lock_count;
555 return 0; 590 return 0;
@@ -563,8 +598,9 @@ unsigned int friend_con_connected(Friend_Connections *fr_c, int friendcon_id)
563{ 598{
564 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 599 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
565 600
566 if (!friend_con) 601 if (!friend_con) {
567 return 0; 602 return 0;
603 }
568 604
569 return friend_con->status; 605 return friend_con->status;
570} 606}
@@ -578,14 +614,17 @@ int get_friendcon_public_keys(uint8_t *real_pk, uint8_t *dht_temp_pk, Friend_Con
578{ 614{
579 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 615 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
580 616
581 if (!friend_con) 617 if (!friend_con) {
582 return -1; 618 return -1;
619 }
583 620
584 if (real_pk) 621 if (real_pk) {
585 memcpy(real_pk, friend_con->real_public_key, crypto_box_PUBLICKEYBYTES); 622 memcpy(real_pk, friend_con->real_public_key, crypto_box_PUBLICKEYBYTES);
623 }
586 624
587 if (dht_temp_pk) 625 if (dht_temp_pk) {
588 memcpy(dht_temp_pk, friend_con->dht_temp_pk, crypto_box_PUBLICKEYBYTES); 626 memcpy(dht_temp_pk, friend_con->dht_temp_pk, crypto_box_PUBLICKEYBYTES);
627 }
589 628
590 return 0; 629 return 0;
591} 630}
@@ -611,11 +650,13 @@ int friend_connection_callbacks(Friend_Connections *fr_c, int friendcon_id, unsi
611{ 650{
612 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 651 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
613 652
614 if (!friend_con) 653 if (!friend_con) {
615 return -1; 654 return -1;
655 }
616 656
617 if (index >= MAX_FRIEND_CONNECTION_CALLBACKS) 657 if (index >= MAX_FRIEND_CONNECTION_CALLBACKS) {
618 return -1; 658 return -1;
659 }
619 660
620 friend_con->callbacks[index].status_callback = status_callback; 661 friend_con->callbacks[index].status_callback = status_callback;
621 friend_con->callbacks[index].data_callback = data_callback; 662 friend_con->callbacks[index].data_callback = data_callback;
@@ -640,8 +681,9 @@ int friend_connection_crypt_connection_id(Friend_Connections *fr_c, int friendco
640{ 681{
641 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 682 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
642 683
643 if (!friend_con) 684 if (!friend_con) {
644 return -1; 685 return -1;
686 }
645 687
646 return friend_con->crypt_connection_id; 688 return friend_con->crypt_connection_id;
647} 689}
@@ -663,13 +705,15 @@ int new_friend_connection(Friend_Connections *fr_c, const uint8_t *real_public_k
663 705
664 friendcon_id = create_friend_conn(fr_c); 706 friendcon_id = create_friend_conn(fr_c);
665 707
666 if (friendcon_id == -1) 708 if (friendcon_id == -1) {
667 return -1; 709 return -1;
710 }
668 711
669 int32_t onion_friendnum = onion_addfriend(fr_c->onion_c, real_public_key); 712 int32_t onion_friendnum = onion_addfriend(fr_c->onion_c, real_public_key);
670 713
671 if (onion_friendnum == -1) 714 if (onion_friendnum == -1) {
672 return -1; 715 return -1;
716 }
673 717
674 Friend_Conn *friend_con = &fr_c->conns[friendcon_id]; 718 Friend_Conn *friend_con = &fr_c->conns[friendcon_id];
675 719
@@ -693,8 +737,9 @@ int kill_friend_connection(Friend_Connections *fr_c, int friendcon_id)
693{ 737{
694 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 738 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
695 739
696 if (!friend_con) 740 if (!friend_con) {
697 return -1; 741 return -1;
742 }
698 743
699 if (friend_con->lock_count) { 744 if (friend_con->lock_count) {
700 --friend_con->lock_count; 745 --friend_con->lock_count;
@@ -733,13 +778,15 @@ void set_friend_request_callback(Friend_Connections *fr_c, int (*fr_request_call
733int send_friend_request_packet(Friend_Connections *fr_c, int friendcon_id, uint32_t nospam_num, const uint8_t *data, 778int send_friend_request_packet(Friend_Connections *fr_c, int friendcon_id, uint32_t nospam_num, const uint8_t *data,
734 uint16_t length) 779 uint16_t length)
735{ 780{
736 if (1 + sizeof(nospam_num) + length > ONION_CLIENT_MAX_DATA_SIZE || length == 0) 781 if (1 + sizeof(nospam_num) + length > ONION_CLIENT_MAX_DATA_SIZE || length == 0) {
737 return -1; 782 return -1;
783 }
738 784
739 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id); 785 Friend_Conn *friend_con = get_conn(fr_c, friendcon_id);
740 786
741 if (!friend_con) 787 if (!friend_con) {
742 return -1; 788 return -1;
789 }
743 790
744 uint8_t packet[1 + sizeof(nospam_num) + length]; 791 uint8_t packet[1 + sizeof(nospam_num) + length];
745 memcpy(packet + 1, &nospam_num, sizeof(nospam_num)); 792 memcpy(packet + 1, &nospam_num, sizeof(nospam_num));
@@ -752,8 +799,9 @@ int send_friend_request_packet(Friend_Connections *fr_c, int friendcon_id, uint3
752 packet[0] = CRYPTO_PACKET_FRIEND_REQ; 799 packet[0] = CRYPTO_PACKET_FRIEND_REQ;
753 int num = send_onion_data(fr_c->onion_c, friend_con->onion_friendnum, packet, sizeof(packet)); 800 int num = send_onion_data(fr_c->onion_c, friend_con->onion_friendnum, packet, sizeof(packet));
754 801
755 if (num <= 0) 802 if (num <= 0) {
756 return -1; 803 return -1;
804 }
757 805
758 return num; 806 return num;
759 } 807 }
@@ -762,13 +810,15 @@ int send_friend_request_packet(Friend_Connections *fr_c, int friendcon_id, uint3
762/* Create new friend_connections instance. */ 810/* Create new friend_connections instance. */
763Friend_Connections *new_friend_connections(Onion_Client *onion_c) 811Friend_Connections *new_friend_connections(Onion_Client *onion_c)
764{ 812{
765 if (!onion_c) 813 if (!onion_c) {
766 return NULL; 814 return NULL;
815 }
767 816
768 Friend_Connections *temp = calloc(1, sizeof(Friend_Connections)); 817 Friend_Connections *temp = calloc(1, sizeof(Friend_Connections));
769 818
770 if (temp == NULL) 819 if (temp == NULL) {
771 return NULL; 820 return NULL;
821 }
772 822
773 temp->dht = onion_c->dht; 823 temp->dht = onion_c->dht;
774 temp->net_crypto = onion_c->c; 824 temp->net_crypto = onion_c->c;
@@ -843,8 +893,9 @@ void do_friend_connections(Friend_Connections *fr_c)
843/* Free everything related with friend_connections. */ 893/* Free everything related with friend_connections. */
844void kill_friend_connections(Friend_Connections *fr_c) 894void kill_friend_connections(Friend_Connections *fr_c)
845{ 895{
846 if (!fr_c) 896 if (!fr_c) {
847 return; 897 return;
898 }
848 899
849 uint32_t i; 900 uint32_t i;
850 901
diff --git a/toxcore/friend_requests.c b/toxcore/friend_requests.c
index 7d4fecd1..122bef3b 100644
--- a/toxcore/friend_requests.c
+++ b/toxcore/friend_requests.c
@@ -60,8 +60,9 @@ void set_filter_function(Friend_Requests *fr, int (*function)(const uint8_t *, v
60/* Add to list of received friend requests. */ 60/* Add to list of received friend requests. */
61static void addto_receivedlist(Friend_Requests *fr, const uint8_t *real_pk) 61static void addto_receivedlist(Friend_Requests *fr, const uint8_t *real_pk)
62{ 62{
63 if (fr->received_requests_index >= MAX_RECEIVED_STORED) 63 if (fr->received_requests_index >= MAX_RECEIVED_STORED) {
64 fr->received_requests_index = 0; 64 fr->received_requests_index = 0;
65 }
65 66
66 id_copy(fr->received_requests[fr->received_requests_index], real_pk); 67 id_copy(fr->received_requests[fr->received_requests_index], real_pk);
67 ++fr->received_requests_index; 68 ++fr->received_requests_index;
@@ -76,9 +77,11 @@ static int request_received(Friend_Requests *fr, const uint8_t *real_pk)
76{ 77{
77 uint32_t i; 78 uint32_t i;
78 79
79 for (i = 0; i < MAX_RECEIVED_STORED; ++i) 80 for (i = 0; i < MAX_RECEIVED_STORED; ++i) {
80 if (id_equal(fr->received_requests[i], real_pk)) 81 if (id_equal(fr->received_requests[i], real_pk)) {
81 return 1; 82 return 1;
83 }
84 }
82 85
83 return 0; 86 return 0;
84} 87}
@@ -107,24 +110,30 @@ static int friendreq_handlepacket(void *object, const uint8_t *source_pubkey, co
107{ 110{
108 Friend_Requests *fr = object; 111 Friend_Requests *fr = object;
109 112
110 if (length <= 1 + sizeof(fr->nospam) || length > ONION_CLIENT_MAX_DATA_SIZE) 113 if (length <= 1 + sizeof(fr->nospam) || length > ONION_CLIENT_MAX_DATA_SIZE) {
111 return 1; 114 return 1;
115 }
112 116
113 ++packet; 117 ++packet;
114 --length; 118 --length;
115 119
116 if (fr->handle_friendrequest_isset == 0) 120 if (fr->handle_friendrequest_isset == 0) {
117 return 1; 121 return 1;
122 }
118 123
119 if (request_received(fr, source_pubkey)) 124 if (request_received(fr, source_pubkey)) {
120 return 1; 125 return 1;
126 }
121 127
122 if (memcmp(packet, &fr->nospam, sizeof(fr->nospam)) != 0) 128 if (memcmp(packet, &fr->nospam, sizeof(fr->nospam)) != 0) {
123 return 1; 129 return 1;
130 }
124 131
125 if (fr->filter_function) 132 if (fr->filter_function) {
126 if ((*fr->filter_function)(source_pubkey, fr->filter_function_userdata) != 0) 133 if ((*fr->filter_function)(source_pubkey, fr->filter_function_userdata) != 0) {
127 return 1; 134 return 1;
135 }
136 }
128 137
129 addto_receivedlist(fr, source_pubkey); 138 addto_receivedlist(fr, source_pubkey);
130 139
diff --git a/toxcore/group.c b/toxcore/group.c
index b699e867..6d5c6ad4 100644
--- a/toxcore/group.c
+++ b/toxcore/group.c
@@ -33,14 +33,17 @@
33 */ 33 */
34static uint8_t groupnumber_not_valid(const Group_Chats *g_c, int groupnumber) 34static uint8_t groupnumber_not_valid(const Group_Chats *g_c, int groupnumber)
35{ 35{
36 if ((unsigned int)groupnumber >= g_c->num_chats) 36 if ((unsigned int)groupnumber >= g_c->num_chats) {
37 return 1; 37 return 1;
38 }
38 39
39 if (g_c->chats == NULL) 40 if (g_c->chats == NULL) {
40 return 1; 41 return 1;
42 }
41 43
42 if (g_c->chats[groupnumber].status == GROUPCHAT_STATUS_NONE) 44 if (g_c->chats[groupnumber].status == GROUPCHAT_STATUS_NONE) {
43 return 1; 45 return 1;
46 }
44 47
45 return 0; 48 return 0;
46} 49}
@@ -61,8 +64,9 @@ static int realloc_groupchats(Group_Chats *g_c, uint32_t num)
61 64
62 Group_c *newgroup_chats = realloc(g_c->chats, num * sizeof(Group_c)); 65 Group_c *newgroup_chats = realloc(g_c->chats, num * sizeof(Group_c));
63 66
64 if (newgroup_chats == NULL) 67 if (newgroup_chats == NULL) {
65 return -1; 68 return -1;
69 }
66 70
67 g_c->chats = newgroup_chats; 71 g_c->chats = newgroup_chats;
68 return 0; 72 return 0;
@@ -79,8 +83,9 @@ static int create_group_chat(Group_Chats *g_c)
79 uint32_t i; 83 uint32_t i;
80 84
81 for (i = 0; i < g_c->num_chats; ++i) { 85 for (i = 0; i < g_c->num_chats; ++i) {
82 if (g_c->chats[i].status == GROUPCHAT_STATUS_NONE) 86 if (g_c->chats[i].status == GROUPCHAT_STATUS_NONE) {
83 return i; 87 return i;
88 }
84 } 89 }
85 90
86 int id = -1; 91 int id = -1;
@@ -102,15 +107,17 @@ static int create_group_chat(Group_Chats *g_c)
102 */ 107 */
103static int wipe_group_chat(Group_Chats *g_c, int groupnumber) 108static int wipe_group_chat(Group_Chats *g_c, int groupnumber)
104{ 109{
105 if (groupnumber_not_valid(g_c, groupnumber)) 110 if (groupnumber_not_valid(g_c, groupnumber)) {
106 return -1; 111 return -1;
112 }
107 113
108 uint32_t i; 114 uint32_t i;
109 sodium_memzero(&(g_c->chats[groupnumber]), sizeof(Group_c)); 115 sodium_memzero(&(g_c->chats[groupnumber]), sizeof(Group_c));
110 116
111 for (i = g_c->num_chats; i != 0; --i) { 117 for (i = g_c->num_chats; i != 0; --i) {
112 if (g_c->chats[i - 1].status != GROUPCHAT_STATUS_NONE) 118 if (g_c->chats[i - 1].status != GROUPCHAT_STATUS_NONE) {
113 break; 119 break;
120 }
114 } 121 }
115 122
116 if (g_c->num_chats != i) { 123 if (g_c->num_chats != i) {
@@ -123,8 +130,9 @@ static int wipe_group_chat(Group_Chats *g_c, int groupnumber)
123 130
124static Group_c *get_group_c(const Group_Chats *g_c, int groupnumber) 131static Group_c *get_group_c(const Group_Chats *g_c, int groupnumber)
125{ 132{
126 if (groupnumber_not_valid(g_c, groupnumber)) 133 if (groupnumber_not_valid(g_c, groupnumber)) {
127 return 0; 134 return 0;
135 }
128 136
129 return &g_c->chats[groupnumber]; 137 return &g_c->chats[groupnumber];
130} 138}
@@ -142,9 +150,11 @@ static int peer_in_chat(const Group_c *chat, const uint8_t *real_pk)
142{ 150{
143 uint32_t i; 151 uint32_t i;
144 152
145 for (i = 0; i < chat->numpeers; ++i) 153 for (i = 0; i < chat->numpeers; ++i) {
146 if (id_equal(chat->group[i].real_pk, real_pk)) 154 if (id_equal(chat->group[i].real_pk, real_pk)) {
147 return i; 155 return i;
156 }
157 }
148 158
149 return -1; 159 return -1;
150} 160}
@@ -161,9 +171,11 @@ static int get_group_num(const Group_Chats *g_c, const uint8_t *identifier)
161{ 171{
162 uint32_t i; 172 uint32_t i;
163 173
164 for (i = 0; i < g_c->num_chats; ++i) 174 for (i = 0; i < g_c->num_chats; ++i) {
165 if (sodium_memcmp(g_c->chats[i].identifier, identifier, GROUP_IDENTIFIER_LENGTH) == 0) 175 if (sodium_memcmp(g_c->chats[i].identifier, identifier, GROUP_IDENTIFIER_LENGTH) == 0) {
166 return i; 176 return i;
177 }
178 }
167 179
168 return -1; 180 return -1;
169} 181}
@@ -180,9 +192,11 @@ static int get_peer_index(Group_c *g, uint16_t peer_number)
180{ 192{
181 uint32_t i; 193 uint32_t i;
182 194
183 for (i = 0; i < g->numpeers; ++i) 195 for (i = 0; i < g->numpeers; ++i) {
184 if (g->group[i].peer_number == peer_number) 196 if (g->group[i].peer_number == peer_number) {
185 return i; 197 return i;
198 }
199 }
186 200
187 return -1; 201 return -1;
188} 202}
@@ -215,11 +229,13 @@ static int add_to_closest(Group_Chats *g_c, int groupnumber, const uint8_t *real
215{ 229{
216 Group_c *g = get_group_c(g_c, groupnumber); 230 Group_c *g = get_group_c(g_c, groupnumber);
217 231
218 if (!g) 232 if (!g) {
219 return -1; 233 return -1;
234 }
220 235
221 if (public_key_cmp(g->real_pk, real_pk) == 0) 236 if (public_key_cmp(g->real_pk, real_pk) == 0) {
222 return -1; 237 return -1;
238 }
223 239
224 unsigned int i; 240 unsigned int i;
225 unsigned int index = DESIRED_CLOSE_CONNECTIONS; 241 unsigned int index = DESIRED_CLOSE_CONNECTIONS;
@@ -285,8 +301,9 @@ static int add_to_closest(Group_Chats *g_c, int groupnumber, const uint8_t *real
285 add_to_closest(g_c, groupnumber, old_real_pk, old_temp_pk); 301 add_to_closest(g_c, groupnumber, old_real_pk, old_temp_pk);
286 } 302 }
287 303
288 if (!g->changed) 304 if (!g->changed) {
289 g->changed = GROUPCHAT_CLOSEST_ADDED; 305 g->changed = GROUPCHAT_CLOSEST_ADDED;
306 }
290 307
291 return 0; 308 return 0;
292} 309}
@@ -296,11 +313,13 @@ static unsigned int pk_in_closest_peers(Group_c *g, uint8_t *real_pk)
296 unsigned int i; 313 unsigned int i;
297 314
298 for (i = 0; i < DESIRED_CLOSE_CONNECTIONS; ++i) { 315 for (i = 0; i < DESIRED_CLOSE_CONNECTIONS; ++i) {
299 if (!g->closest_peers[i].entry) 316 if (!g->closest_peers[i].entry) {
300 continue; 317 continue;
318 }
301 319
302 if (public_key_cmp(g->closest_peers[i].real_pk, real_pk) == 0) 320 if (public_key_cmp(g->closest_peers[i].real_pk, real_pk) == 0) {
303 return 1; 321 return 1;
322 }
304 323
305 } 324 }
306 325
@@ -313,11 +332,13 @@ static int connect_to_closest(Group_Chats *g_c, int groupnumber)
313{ 332{
314 Group_c *g = get_group_c(g_c, groupnumber); 333 Group_c *g = get_group_c(g_c, groupnumber);
315 334
316 if (!g) 335 if (!g) {
317 return -1; 336 return -1;
337 }
318 338
319 if (!g->changed) 339 if (!g->changed) {
320 return 0; 340 return 0;
341 }
321 342
322 unsigned int i; 343 unsigned int i;
323 344
@@ -328,11 +349,13 @@ static int connect_to_closest(Group_Chats *g_c, int groupnumber)
328 } 349 }
329 350
330 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 351 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
331 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) 352 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) {
332 continue; 353 continue;
354 }
333 355
334 if (!g->close[i].closest) 356 if (!g->close[i].closest) {
335 continue; 357 continue;
358 }
336 359
337 uint8_t real_pk[crypto_box_PUBLICKEYBYTES]; 360 uint8_t real_pk[crypto_box_PUBLICKEYBYTES];
338 uint8_t dht_temp_pk[crypto_box_PUBLICKEYBYTES]; 361 uint8_t dht_temp_pk[crypto_box_PUBLICKEYBYTES];
@@ -345,8 +368,9 @@ static int connect_to_closest(Group_Chats *g_c, int groupnumber)
345 } 368 }
346 369
347 for (i = 0; i < DESIRED_CLOSE_CONNECTIONS; ++i) { 370 for (i = 0; i < DESIRED_CLOSE_CONNECTIONS; ++i) {
348 if (!g->closest_peers[i].entry) 371 if (!g->closest_peers[i].entry) {
349 continue; 372 continue;
373 }
350 374
351 int friendcon_id = getfriend_conn_id_pk(g_c->fr_c, g->closest_peers[i].real_pk); 375 int friendcon_id = getfriend_conn_id_pk(g_c->fr_c, g->closest_peers[i].real_pk);
352 376
@@ -386,8 +410,9 @@ static int addpeer(Group_Chats *g_c, int groupnumber, const uint8_t *real_pk, co
386{ 410{
387 Group_c *g = get_group_c(g_c, groupnumber); 411 Group_c *g = get_group_c(g_c, groupnumber);
388 412
389 if (!g) 413 if (!g) {
390 return -1; 414 return -1;
415 }
391 416
392 //TODO 417 //TODO
393 int peer_index = peer_in_chat(g, real_pk); 418 int peer_index = peer_in_chat(g, real_pk);
@@ -395,22 +420,25 @@ static int addpeer(Group_Chats *g_c, int groupnumber, const uint8_t *real_pk, co
395 if (peer_index != -1) { 420 if (peer_index != -1) {
396 id_copy(g->group[peer_index].temp_pk, temp_pk); 421 id_copy(g->group[peer_index].temp_pk, temp_pk);
397 422
398 if (g->group[peer_index].peer_number != peer_number) 423 if (g->group[peer_index].peer_number != peer_number) {
399 return -1; 424 return -1;
425 }
400 426
401 return peer_index; 427 return peer_index;
402 } 428 }
403 429
404 peer_index = get_peer_index(g, peer_number); 430 peer_index = get_peer_index(g, peer_number);
405 431
406 if (peer_index != -1) 432 if (peer_index != -1) {
407 return -1; 433 return -1;
434 }
408 435
409 Group_Peer *temp; 436 Group_Peer *temp;
410 temp = realloc(g->group, sizeof(Group_Peer) * (g->numpeers + 1)); 437 temp = realloc(g->group, sizeof(Group_Peer) * (g->numpeers + 1));
411 438
412 if (temp == NULL) 439 if (temp == NULL) {
413 return -1; 440 return -1;
441 }
414 442
415 memset(&(temp[g->numpeers]), 0, sizeof(Group_Peer)); 443 memset(&(temp[g->numpeers]), 0, sizeof(Group_Peer));
416 g->group = temp; 444 g->group = temp;
@@ -424,12 +452,14 @@ static int addpeer(Group_Chats *g_c, int groupnumber, const uint8_t *real_pk, co
424 452
425 add_to_closest(g_c, groupnumber, real_pk, temp_pk); 453 add_to_closest(g_c, groupnumber, real_pk, temp_pk);
426 454
427 if (g_c->peer_namelistchange) 455 if (g_c->peer_namelistchange) {
428 g_c->peer_namelistchange(g_c->m, groupnumber, g->numpeers - 1, CHAT_CHANGE_PEER_ADD, 456 g_c->peer_namelistchange(g_c->m, groupnumber, g->numpeers - 1, CHAT_CHANGE_PEER_ADD,
429 g_c->group_namelistchange_userdata); 457 g_c->group_namelistchange_userdata);
458 }
430 459
431 if (g->peer_on_join) 460 if (g->peer_on_join) {
432 g->peer_on_join(g->object, groupnumber, g->numpeers - 1); 461 g->peer_on_join(g->object, groupnumber, g->numpeers - 1);
462 }
433 463
434 return (g->numpeers - 1); 464 return (g->numpeers - 1);
435} 465}
@@ -438,14 +468,16 @@ static int remove_close_conn(Group_Chats *g_c, int groupnumber, int friendcon_id
438{ 468{
439 Group_c *g = get_group_c(g_c, groupnumber); 469 Group_c *g = get_group_c(g_c, groupnumber);
440 470
441 if (!g) 471 if (!g) {
442 return -1; 472 return -1;
473 }
443 474
444 uint32_t i; 475 uint32_t i;
445 476
446 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 477 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
447 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) 478 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) {
448 continue; 479 continue;
480 }
449 481
450 if (g->close[i].number == (unsigned int)friendcon_id) { 482 if (g->close[i].number == (unsigned int)friendcon_id) {
451 g->close[i].type = GROUPCHAT_CLOSE_NONE; 483 g->close[i].type = GROUPCHAT_CLOSE_NONE;
@@ -468,8 +500,9 @@ static int delpeer(Group_Chats *g_c, int groupnumber, int peer_index)
468{ 500{
469 Group_c *g = get_group_c(g_c, groupnumber); 501 Group_c *g = get_group_c(g_c, groupnumber);
470 502
471 if (!g) 503 if (!g) {
472 return -1; 504 return -1;
505 }
473 506
474 uint32_t i; 507 uint32_t i;
475 508
@@ -496,71 +529,85 @@ static int delpeer(Group_Chats *g_c, int groupnumber, int peer_index)
496 free(g->group); 529 free(g->group);
497 g->group = NULL; 530 g->group = NULL;
498 } else { 531 } else {
499 if (g->numpeers != (uint32_t)peer_index) 532 if (g->numpeers != (uint32_t)peer_index) {
500 memcpy(&g->group[peer_index], &g->group[g->numpeers], sizeof(Group_Peer)); 533 memcpy(&g->group[peer_index], &g->group[g->numpeers], sizeof(Group_Peer));
534 }
501 535
502 temp = realloc(g->group, sizeof(Group_Peer) * (g->numpeers)); 536 temp = realloc(g->group, sizeof(Group_Peer) * (g->numpeers));
503 537
504 if (temp == NULL) 538 if (temp == NULL) {
505 return -1; 539 return -1;
540 }
506 541
507 g->group = temp; 542 g->group = temp;
508 } 543 }
509 544
510 if (g_c->peer_namelistchange) 545 if (g_c->peer_namelistchange) {
511 g_c->peer_namelistchange(g_c->m, groupnumber, peer_index, CHAT_CHANGE_PEER_DEL, g_c->group_namelistchange_userdata); 546 g_c->peer_namelistchange(g_c->m, groupnumber, peer_index, CHAT_CHANGE_PEER_DEL, g_c->group_namelistchange_userdata);
547 }
512 548
513 if (g->peer_on_leave) 549 if (g->peer_on_leave) {
514 g->peer_on_leave(g->object, groupnumber, peer_index, peer_object); 550 g->peer_on_leave(g->object, groupnumber, peer_index, peer_object);
551 }
515 552
516 return 0; 553 return 0;
517} 554}
518 555
519static int setnick(Group_Chats *g_c, int groupnumber, int peer_index, const uint8_t *nick, uint16_t nick_len) 556static int setnick(Group_Chats *g_c, int groupnumber, int peer_index, const uint8_t *nick, uint16_t nick_len)
520{ 557{
521 if (nick_len > MAX_NAME_LENGTH) 558 if (nick_len > MAX_NAME_LENGTH) {
522 return -1; 559 return -1;
560 }
523 561
524 Group_c *g = get_group_c(g_c, groupnumber); 562 Group_c *g = get_group_c(g_c, groupnumber);
525 563
526 if (!g) 564 if (!g) {
527 return -1; 565 return -1;
566 }
528 567
529 /* same name as already stored? */ 568 /* same name as already stored? */
530 if (g->group[peer_index].nick_len == nick_len) 569 if (g->group[peer_index].nick_len == nick_len) {
531 if (nick_len == 0 || !memcmp(g->group[peer_index].nick, nick, nick_len)) 570 if (nick_len == 0 || !memcmp(g->group[peer_index].nick, nick, nick_len)) {
532 return 0; 571 return 0;
572 }
573 }
533 574
534 if (nick_len) 575 if (nick_len) {
535 memcpy(g->group[peer_index].nick, nick, nick_len); 576 memcpy(g->group[peer_index].nick, nick, nick_len);
577 }
536 578
537 g->group[peer_index].nick_len = nick_len; 579 g->group[peer_index].nick_len = nick_len;
538 580
539 if (g_c->peer_namelistchange) 581 if (g_c->peer_namelistchange) {
540 g_c->peer_namelistchange(g_c->m, groupnumber, peer_index, CHAT_CHANGE_PEER_NAME, g_c->group_namelistchange_userdata); 582 g_c->peer_namelistchange(g_c->m, groupnumber, peer_index, CHAT_CHANGE_PEER_NAME, g_c->group_namelistchange_userdata);
583 }
541 584
542 return 0; 585 return 0;
543} 586}
544 587
545static int settitle(Group_Chats *g_c, int groupnumber, int peer_index, const uint8_t *title, uint8_t title_len) 588static int settitle(Group_Chats *g_c, int groupnumber, int peer_index, const uint8_t *title, uint8_t title_len)
546{ 589{
547 if (title_len > MAX_NAME_LENGTH || title_len == 0) 590 if (title_len > MAX_NAME_LENGTH || title_len == 0) {
548 return -1; 591 return -1;
592 }
549 593
550 Group_c *g = get_group_c(g_c, groupnumber); 594 Group_c *g = get_group_c(g_c, groupnumber);
551 595
552 if (!g) 596 if (!g) {
553 return -1; 597 return -1;
598 }
554 599
555 /* same as already set? */ 600 /* same as already set? */
556 if (g->title_len == title_len && !memcmp(g->title, title, title_len)) 601 if (g->title_len == title_len && !memcmp(g->title, title, title_len)) {
557 return 0; 602 return 0;
603 }
558 604
559 memcpy(g->title, title, title_len); 605 memcpy(g->title, title, title_len);
560 g->title_len = title_len; 606 g->title_len = title_len;
561 607
562 if (g_c->title_callback) 608 if (g_c->title_callback) {
563 g_c->title_callback(g_c->m, groupnumber, peer_index, title, title_len, g_c->title_callback_userdata); 609 g_c->title_callback(g_c->m, groupnumber, peer_index, title, title_len, g_c->title_callback_userdata);
610 }
564 611
565 return 0; 612 return 0;
566} 613}
@@ -569,17 +616,20 @@ static void set_conns_type_close(Group_Chats *g_c, int groupnumber, int friendco
569{ 616{
570 Group_c *g = get_group_c(g_c, groupnumber); 617 Group_c *g = get_group_c(g_c, groupnumber);
571 618
572 if (!g) 619 if (!g) {
573 return; 620 return;
621 }
574 622
575 uint32_t i; 623 uint32_t i;
576 624
577 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 625 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
578 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) 626 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) {
579 continue; 627 continue;
628 }
580 629
581 if (g->close[i].number != (unsigned int)friendcon_id) 630 if (g->close[i].number != (unsigned int)friendcon_id) {
582 continue; 631 continue;
632 }
583 633
584 if (type == GROUPCHAT_CLOSE_ONLINE) { 634 if (type == GROUPCHAT_CLOSE_ONLINE) {
585 send_packet_online(g_c->fr_c, friendcon_id, groupnumber, g->identifier); 635 send_packet_online(g_c->fr_c, friendcon_id, groupnumber, g->identifier);
@@ -624,8 +674,9 @@ static int add_conn_to_groupchat(Group_Chats *g_c, int friendcon_id, int groupnu
624{ 674{
625 Group_c *g = get_group_c(g_c, groupnumber); 675 Group_c *g = get_group_c(g_c, groupnumber);
626 676
627 if (!g) 677 if (!g) {
628 return -1; 678 return -1;
679 }
629 680
630 uint16_t i, ind = MAX_GROUP_CONNECTIONS; 681 uint16_t i, ind = MAX_GROUP_CONNECTIONS;
631 682
@@ -641,11 +692,13 @@ static int add_conn_to_groupchat(Group_Chats *g_c, int friendcon_id, int groupnu
641 } 692 }
642 } 693 }
643 694
644 if (ind == MAX_GROUP_CONNECTIONS) 695 if (ind == MAX_GROUP_CONNECTIONS) {
645 return -1; 696 return -1;
697 }
646 698
647 if (lock) 699 if (lock) {
648 friend_connection_lock(g_c->fr_c, friendcon_id); 700 friend_connection_lock(g_c->fr_c, friendcon_id);
701 }
649 702
650 g->close[ind].type = GROUPCHAT_CLOSE_CONNECTION; 703 g->close[ind].type = GROUPCHAT_CLOSE_CONNECTION;
651 g->close[ind].number = friendcon_id; 704 g->close[ind].number = friendcon_id;
@@ -668,8 +721,9 @@ int add_groupchat(Group_Chats *g_c, uint8_t type)
668{ 721{
669 int groupnumber = create_group_chat(g_c); 722 int groupnumber = create_group_chat(g_c);
670 723
671 if (groupnumber == -1) 724 if (groupnumber == -1) {
672 return -1; 725 return -1;
726 }
673 727
674 Group_c *g = &g_c->chats[groupnumber]; 728 Group_c *g = &g_c->chats[groupnumber];
675 729
@@ -700,30 +754,34 @@ int del_groupchat(Group_Chats *g_c, int groupnumber)
700{ 754{
701 Group_c *g = get_group_c(g_c, groupnumber); 755 Group_c *g = get_group_c(g_c, groupnumber);
702 756
703 if (!g) 757 if (!g) {
704 return -1; 758 return -1;
759 }
705 760
706 group_kill_peer_send(g_c, groupnumber, g->peer_number); 761 group_kill_peer_send(g_c, groupnumber, g->peer_number);
707 762
708 unsigned int i; 763 unsigned int i;
709 764
710 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 765 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
711 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) 766 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) {
712 continue; 767 continue;
768 }
713 769
714 g->close[i].type = GROUPCHAT_CLOSE_NONE; 770 g->close[i].type = GROUPCHAT_CLOSE_NONE;
715 kill_friend_connection(g_c->fr_c, g->close[i].number); 771 kill_friend_connection(g_c->fr_c, g->close[i].number);
716 } 772 }
717 773
718 for (i = 0; i < g->numpeers; ++i) { 774 for (i = 0; i < g->numpeers; ++i) {
719 if (g->peer_on_leave) 775 if (g->peer_on_leave) {
720 g->peer_on_leave(g->object, groupnumber, i, g->group[i].object); 776 g->peer_on_leave(g->object, groupnumber, i, g->group[i].object);
777 }
721 } 778 }
722 779
723 free(g->group); 780 free(g->group);
724 781
725 if (g->group_on_delete) 782 if (g->group_on_delete) {
726 g->group_on_delete(g->object, groupnumber); 783 g->group_on_delete(g->object, groupnumber);
784 }
727 785
728 return wipe_group_chat(g_c, groupnumber); 786 return wipe_group_chat(g_c, groupnumber);
729} 787}
@@ -738,11 +796,13 @@ int group_peer_pubkey(const Group_Chats *g_c, int groupnumber, int peernumber, u
738{ 796{
739 Group_c *g = get_group_c(g_c, groupnumber); 797 Group_c *g = get_group_c(g_c, groupnumber);
740 798
741 if (!g) 799 if (!g) {
742 return -1; 800 return -1;
801 }
743 802
744 if ((uint32_t)peernumber >= g->numpeers) 803 if ((uint32_t)peernumber >= g->numpeers) {
745 return -1; 804 return -1;
805 }
746 806
747 memcpy(pk, g->group[peernumber].real_pk, crypto_box_PUBLICKEYBYTES); 807 memcpy(pk, g->group[peernumber].real_pk, crypto_box_PUBLICKEYBYTES);
748 return 0; 808 return 0;
@@ -758,11 +818,13 @@ int group_peername(const Group_Chats *g_c, int groupnumber, int peernumber, uint
758{ 818{
759 Group_c *g = get_group_c(g_c, groupnumber); 819 Group_c *g = get_group_c(g_c, groupnumber);
760 820
761 if (!g) 821 if (!g) {
762 return -1; 822 return -1;
823 }
763 824
764 if ((uint32_t)peernumber >= g->numpeers) 825 if ((uint32_t)peernumber >= g->numpeers) {
765 return -1; 826 return -1;
827 }
766 828
767 if (g->group[peernumber].nick_len == 0) { 829 if (g->group[peernumber].nick_len == 0) {
768 memcpy(name, "Tox User", 8); 830 memcpy(name, "Tox User", 8);
@@ -788,8 +850,9 @@ int group_names(const Group_Chats *g_c, int groupnumber, uint8_t names[][MAX_NAM
788{ 850{
789 Group_c *g = get_group_c(g_c, groupnumber); 851 Group_c *g = get_group_c(g_c, groupnumber);
790 852
791 if (!g) 853 if (!g) {
792 return -1; 854 return -1;
855 }
793 856
794 unsigned int i; 857 unsigned int i;
795 858
@@ -807,8 +870,9 @@ int group_number_peers(const Group_Chats *g_c, int groupnumber)
807{ 870{
808 Group_c *g = get_group_c(g_c, groupnumber); 871 Group_c *g = get_group_c(g_c, groupnumber);
809 872
810 if (!g) 873 if (!g) {
811 return -1; 874 return -1;
875 }
812 876
813 return g->numpeers; 877 return g->numpeers;
814} 878}
@@ -820,14 +884,17 @@ unsigned int group_peernumber_is_ours(const Group_Chats *g_c, int groupnumber, i
820{ 884{
821 Group_c *g = get_group_c(g_c, groupnumber); 885 Group_c *g = get_group_c(g_c, groupnumber);
822 886
823 if (!g) 887 if (!g) {
824 return 0; 888 return 0;
889 }
825 890
826 if (g->status != GROUPCHAT_STATUS_CONNECTED) 891 if (g->status != GROUPCHAT_STATUS_CONNECTED) {
827 return 0; 892 return 0;
893 }
828 894
829 if ((uint32_t)peernumber >= g->numpeers) 895 if ((uint32_t)peernumber >= g->numpeers) {
830 return 0; 896 return 0;
897 }
831 898
832 return g->peer_number == g->group[peernumber].peer_number; 899 return g->peer_number == g->group[peernumber].peer_number;
833} 900}
@@ -841,8 +908,9 @@ int group_get_type(const Group_Chats *g_c, int groupnumber)
841{ 908{
842 Group_c *g = get_group_c(g_c, groupnumber); 909 Group_c *g = get_group_c(g_c, groupnumber);
843 910
844 if (!g) 911 if (!g) {
845 return -1; 912 return -1;
913 }
846 914
847 return g->identifier[0]; 915 return g->identifier[0];
848} 916}
@@ -855,8 +923,9 @@ int group_get_type(const Group_Chats *g_c, int groupnumber)
855static unsigned int send_packet_group_peer(Friend_Connections *fr_c, int friendcon_id, uint8_t packet_id, 923static unsigned int send_packet_group_peer(Friend_Connections *fr_c, int friendcon_id, uint8_t packet_id,
856 uint16_t group_num, const uint8_t *data, uint16_t length) 924 uint16_t group_num, const uint8_t *data, uint16_t length)
857{ 925{
858 if (1 + sizeof(uint16_t) + length > MAX_CRYPTO_DATA_SIZE) 926 if (1 + sizeof(uint16_t) + length > MAX_CRYPTO_DATA_SIZE) {
859 return 0; 927 return 0;
928 }
860 929
861 group_num = htons(group_num); 930 group_num = htons(group_num);
862 uint8_t packet[1 + sizeof(uint16_t) + length]; 931 uint8_t packet[1 + sizeof(uint16_t) + length];
@@ -875,8 +944,9 @@ static unsigned int send_packet_group_peer(Friend_Connections *fr_c, int friendc
875static unsigned int send_lossy_group_peer(Friend_Connections *fr_c, int friendcon_id, uint8_t packet_id, 944static unsigned int send_lossy_group_peer(Friend_Connections *fr_c, int friendcon_id, uint8_t packet_id,
876 uint16_t group_num, const uint8_t *data, uint16_t length) 945 uint16_t group_num, const uint8_t *data, uint16_t length)
877{ 946{
878 if (1 + sizeof(uint16_t) + length > MAX_CRYPTO_DATA_SIZE) 947 if (1 + sizeof(uint16_t) + length > MAX_CRYPTO_DATA_SIZE) {
879 return 0; 948 return 0;
949 }
880 950
881 group_num = htons(group_num); 951 group_num = htons(group_num);
882 uint8_t packet[1 + sizeof(uint16_t) + length]; 952 uint8_t packet[1 + sizeof(uint16_t) + length];
@@ -901,8 +971,9 @@ int invite_friend(Group_Chats *g_c, int32_t friendnumber, int groupnumber)
901{ 971{
902 Group_c *g = get_group_c(g_c, groupnumber); 972 Group_c *g = get_group_c(g_c, groupnumber);
903 973
904 if (!g) 974 if (!g) {
905 return -1; 975 return -1;
976 }
906 977
907 uint8_t invite[INVITE_PACKET_SIZE]; 978 uint8_t invite[INVITE_PACKET_SIZE];
908 invite[0] = INVITE_ID; 979 invite[0] = INVITE_ID;
@@ -929,24 +1000,29 @@ static unsigned int send_peer_query(Group_Chats *g_c, int friendcon_id, uint16_t
929 */ 1000 */
930int join_groupchat(Group_Chats *g_c, int32_t friendnumber, uint8_t expected_type, const uint8_t *data, uint16_t length) 1001int join_groupchat(Group_Chats *g_c, int32_t friendnumber, uint8_t expected_type, const uint8_t *data, uint16_t length)
931{ 1002{
932 if (length != sizeof(uint16_t) + GROUP_IDENTIFIER_LENGTH) 1003 if (length != sizeof(uint16_t) + GROUP_IDENTIFIER_LENGTH) {
933 return -1; 1004 return -1;
1005 }
934 1006
935 if (data[sizeof(uint16_t)] != expected_type) 1007 if (data[sizeof(uint16_t)] != expected_type) {
936 return -1; 1008 return -1;
1009 }
937 1010
938 int friendcon_id = getfriendcon_id(g_c->m, friendnumber); 1011 int friendcon_id = getfriendcon_id(g_c->m, friendnumber);
939 1012
940 if (friendcon_id == -1) 1013 if (friendcon_id == -1) {
941 return -1; 1014 return -1;
1015 }
942 1016
943 if (get_group_num(g_c, data + sizeof(uint16_t)) != -1) 1017 if (get_group_num(g_c, data + sizeof(uint16_t)) != -1) {
944 return -1; 1018 return -1;
1019 }
945 1020
946 int groupnumber = create_group_chat(g_c); 1021 int groupnumber = create_group_chat(g_c);
947 1022
948 if (groupnumber == -1) 1023 if (groupnumber == -1) {
949 return -1; 1024 return -1;
1025 }
950 1026
951 Group_c *g = &g_c->chats[groupnumber]; 1027 Group_c *g = &g_c->chats[groupnumber];
952 1028
@@ -1063,8 +1139,9 @@ int callback_groupchat_peer_new(const Group_Chats *g_c, int groupnumber, void (*
1063{ 1139{
1064 Group_c *g = get_group_c(g_c, groupnumber); 1140 Group_c *g = get_group_c(g_c, groupnumber);
1065 1141
1066 if (!g) 1142 if (!g) {
1067 return -1; 1143 return -1;
1144 }
1068 1145
1069 g->peer_on_join = function; 1146 g->peer_on_join = function;
1070 return 0; 1147 return 0;
@@ -1081,8 +1158,9 @@ int callback_groupchat_peer_delete(Group_Chats *g_c, int groupnumber, void (*fun
1081{ 1158{
1082 Group_c *g = get_group_c(g_c, groupnumber); 1159 Group_c *g = get_group_c(g_c, groupnumber);
1083 1160
1084 if (!g) 1161 if (!g) {
1085 return -1; 1162 return -1;
1163 }
1086 1164
1087 g->peer_on_leave = function; 1165 g->peer_on_leave = function;
1088 return 0; 1166 return 0;
@@ -1099,8 +1177,9 @@ int callback_groupchat_delete(Group_Chats *g_c, int groupnumber, void (*function
1099{ 1177{
1100 Group_c *g = get_group_c(g_c, groupnumber); 1178 Group_c *g = get_group_c(g_c, groupnumber);
1101 1179
1102 if (!g) 1180 if (!g) {
1103 return -1; 1181 return -1;
1182 }
1104 1183
1105 g->group_on_delete = function; 1184 g->group_on_delete = function;
1106 return 0; 1185 return 0;
@@ -1171,8 +1250,9 @@ static int group_kill_peer_send(const Group_Chats *g_c, int groupnumber, uint16_
1171 */ 1250 */
1172static int group_name_send(const Group_Chats *g_c, int groupnumber, const uint8_t *nick, uint16_t nick_len) 1251static int group_name_send(const Group_Chats *g_c, int groupnumber, const uint8_t *nick, uint16_t nick_len)
1173{ 1252{
1174 if (nick_len > MAX_NAME_LENGTH) 1253 if (nick_len > MAX_NAME_LENGTH) {
1175 return -1; 1254 return -1;
1255 }
1176 1256
1177 if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_NAME_ID, nick, nick_len)) { 1257 if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_NAME_ID, nick, nick_len)) {
1178 return 0; 1258 return 0;
@@ -1189,28 +1269,33 @@ static int group_name_send(const Group_Chats *g_c, int groupnumber, const uint8_
1189 */ 1269 */
1190int group_title_send(const Group_Chats *g_c, int groupnumber, const uint8_t *title, uint8_t title_len) 1270int group_title_send(const Group_Chats *g_c, int groupnumber, const uint8_t *title, uint8_t title_len)
1191{ 1271{
1192 if (title_len > MAX_NAME_LENGTH || title_len == 0) 1272 if (title_len > MAX_NAME_LENGTH || title_len == 0) {
1193 return -1; 1273 return -1;
1274 }
1194 1275
1195 Group_c *g = get_group_c(g_c, groupnumber); 1276 Group_c *g = get_group_c(g_c, groupnumber);
1196 1277
1197 if (!g) 1278 if (!g) {
1198 return -1; 1279 return -1;
1280 }
1199 1281
1200 /* same as already set? */ 1282 /* same as already set? */
1201 if (g->title_len == title_len && !memcmp(g->title, title, title_len)) 1283 if (g->title_len == title_len && !memcmp(g->title, title, title_len)) {
1202 return 0; 1284 return 0;
1285 }
1203 1286
1204 memcpy(g->title, title, title_len); 1287 memcpy(g->title, title, title_len);
1205 g->title_len = title_len; 1288 g->title_len = title_len;
1206 1289
1207 if (g->numpeers == 1) 1290 if (g->numpeers == 1) {
1208 return 0; 1291 return 0;
1292 }
1209 1293
1210 if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_TITLE_ID, title, title_len)) 1294 if (send_message_group(g_c, groupnumber, GROUP_MESSAGE_TITLE_ID, title, title_len)) {
1211 return 0; 1295 return 0;
1212 else 1296 } else {
1213 return -1; 1297 return -1;
1298 }
1214} 1299}
1215 1300
1216/* Get group title from groupnumber and put it in title. 1301/* Get group title from groupnumber and put it in title.
@@ -1223,14 +1308,17 @@ int group_title_get(const Group_Chats *g_c, int groupnumber, uint8_t *title, uin
1223{ 1308{
1224 Group_c *g = get_group_c(g_c, groupnumber); 1309 Group_c *g = get_group_c(g_c, groupnumber);
1225 1310
1226 if (!g) 1311 if (!g) {
1227 return -1; 1312 return -1;
1313 }
1228 1314
1229 if (g->title_len == 0 || g->title_len > MAX_NAME_LENGTH) 1315 if (g->title_len == 0 || g->title_len > MAX_NAME_LENGTH) {
1230 return -1; 1316 return -1;
1317 }
1231 1318
1232 if (max_length > g->title_len) 1319 if (max_length > g->title_len) {
1233 max_length = g->title_len; 1320 max_length = g->title_len;
1321 }
1234 1322
1235 memcpy(title, g->title, max_length); 1323 memcpy(title, g->title, max_length);
1236 return max_length; 1324 return max_length;
@@ -1240,23 +1328,26 @@ static void handle_friend_invite_packet(Messenger *m, uint32_t friendnumber, con
1240{ 1328{
1241 Group_Chats *g_c = m->group_chat_object; 1329 Group_Chats *g_c = m->group_chat_object;
1242 1330
1243 if (length <= 1) 1331 if (length <= 1) {
1244 return; 1332 return;
1333 }
1245 1334
1246 const uint8_t *invite_data = data + 1; 1335 const uint8_t *invite_data = data + 1;
1247 uint16_t invite_length = length - 1; 1336 uint16_t invite_length = length - 1;
1248 1337
1249 switch (data[0]) { 1338 switch (data[0]) {
1250 case INVITE_ID: { 1339 case INVITE_ID: {
1251 if (length != INVITE_PACKET_SIZE) 1340 if (length != INVITE_PACKET_SIZE) {
1252 return; 1341 return;
1342 }
1253 1343
1254 int groupnumber = get_group_num(g_c, data + 1 + sizeof(uint16_t)); 1344 int groupnumber = get_group_num(g_c, data + 1 + sizeof(uint16_t));
1255 1345
1256 if (groupnumber == -1) { 1346 if (groupnumber == -1) {
1257 if (g_c->invite_callback) 1347 if (g_c->invite_callback) {
1258 g_c->invite_callback(m, friendnumber, *(invite_data + sizeof(uint16_t)), invite_data, invite_length, 1348 g_c->invite_callback(m, friendnumber, *(invite_data + sizeof(uint16_t)), invite_data, invite_length,
1259 g_c->invite_callback_userdata); 1349 g_c->invite_callback_userdata);
1350 }
1260 1351
1261 return; 1352 return;
1262 } 1353 }
@@ -1265,8 +1356,9 @@ static void handle_friend_invite_packet(Messenger *m, uint32_t friendnumber, con
1265 } 1356 }
1266 1357
1267 case INVITE_RESPONSE_ID: { 1358 case INVITE_RESPONSE_ID: {
1268 if (length != INVITE_RESPONSE_PACKET_SIZE) 1359 if (length != INVITE_RESPONSE_PACKET_SIZE) {
1269 return; 1360 return;
1361 }
1270 1362
1271 uint16_t other_groupnum, groupnum; 1363 uint16_t other_groupnum, groupnum;
1272 memcpy(&groupnum, data + 1 + sizeof(uint16_t), sizeof(uint16_t)); 1364 memcpy(&groupnum, data + 1 + sizeof(uint16_t), sizeof(uint16_t));
@@ -1274,11 +1366,13 @@ static void handle_friend_invite_packet(Messenger *m, uint32_t friendnumber, con
1274 1366
1275 Group_c *g = get_group_c(g_c, groupnum); 1367 Group_c *g = get_group_c(g_c, groupnum);
1276 1368
1277 if (!g) 1369 if (!g) {
1278 return; 1370 return;
1371 }
1279 1372
1280 if (sodium_memcmp(data + 1 + sizeof(uint16_t) * 2, g->identifier, GROUP_IDENTIFIER_LENGTH) != 0) 1373 if (sodium_memcmp(data + 1 + sizeof(uint16_t) * 2, g->identifier, GROUP_IDENTIFIER_LENGTH) != 0) {
1281 return; 1374 return;
1375 }
1282 1376
1283 uint16_t peer_number = rand(); /* TODO: what if two people enter the group at the same time and 1377 uint16_t peer_number = rand(); /* TODO: what if two people enter the group at the same time and
1284 are given the same peer_number by different nodes? */ 1378 are given the same peer_number by different nodes? */
@@ -1289,8 +1383,9 @@ static void handle_friend_invite_packet(Messenger *m, uint32_t friendnumber, con
1289 peer_number = rand(); 1383 peer_number = rand();
1290 ++tries; 1384 ++tries;
1291 1385
1292 if (tries > 32) 1386 if (tries > 32) {
1293 return; 1387 return;
1388 }
1294 } 1389 }
1295 1390
1296 memcpy(&other_groupnum, data + 1, sizeof(uint16_t)); 1391 memcpy(&other_groupnum, data + 1, sizeof(uint16_t));
@@ -1327,11 +1422,13 @@ static int friend_in_close(Group_c *g, int friendcon_id)
1327 unsigned int i; 1422 unsigned int i;
1328 1423
1329 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 1424 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
1330 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) 1425 if (g->close[i].type == GROUPCHAT_CLOSE_NONE) {
1331 continue; 1426 continue;
1427 }
1332 1428
1333 if (g->close[i].number != (uint32_t)friendcon_id) 1429 if (g->close[i].number != (uint32_t)friendcon_id) {
1334 continue; 1430 continue;
1431 }
1335 1432
1336 return i; 1433 return i;
1337 } 1434 }
@@ -1371,8 +1468,9 @@ static unsigned int send_peer_kill(Group_Chats *g_c, int friendcon_id, uint16_t
1371 1468
1372static int handle_packet_online(Group_Chats *g_c, int friendcon_id, uint8_t *data, uint16_t length) 1469static int handle_packet_online(Group_Chats *g_c, int friendcon_id, uint8_t *data, uint16_t length)
1373{ 1470{
1374 if (length != ONLINE_PACKET_DATA_SIZE) 1471 if (length != ONLINE_PACKET_DATA_SIZE) {
1375 return -1; 1472 return -1;
1473 }
1376 1474
1377 int groupnumber = get_group_num(g_c, data + sizeof(uint16_t)); 1475 int groupnumber = get_group_num(g_c, data + sizeof(uint16_t));
1378 uint16_t other_groupnum; 1476 uint16_t other_groupnum;
@@ -1381,13 +1479,15 @@ static int handle_packet_online(Group_Chats *g_c, int friendcon_id, uint8_t *dat
1381 1479
1382 Group_c *g = get_group_c(g_c, groupnumber); 1480 Group_c *g = get_group_c(g_c, groupnumber);
1383 1481
1384 if (!g) 1482 if (!g) {
1385 return -1; 1483 return -1;
1484 }
1386 1485
1387 int index = friend_in_close(g, friendcon_id); 1486 int index = friend_in_close(g, friendcon_id);
1388 1487
1389 if (index == -1) 1488 if (index == -1) {
1390 return -1; 1489 return -1;
1490 }
1391 1491
1392 if (g->close[index].type == GROUPCHAT_CLOSE_ONLINE) { 1492 if (g->close[index].type == GROUPCHAT_CLOSE_ONLINE) {
1393 return -1; 1493 return -1;
@@ -1404,8 +1504,9 @@ static int handle_packet_online(Group_Chats *g_c, int friendcon_id, uint8_t *dat
1404 if (g->number_joined != -1 && count_close_connected(g) >= DESIRED_CLOSE_CONNECTIONS) { 1504 if (g->number_joined != -1 && count_close_connected(g) >= DESIRED_CLOSE_CONNECTIONS) {
1405 int fr_close_index = friend_in_close(g, g->number_joined); 1505 int fr_close_index = friend_in_close(g, g->number_joined);
1406 1506
1407 if (fr_close_index == -1) 1507 if (fr_close_index == -1) {
1408 return -1; 1508 return -1;
1509 }
1409 1510
1410 if (!g->close[fr_close_index].closest) { 1511 if (!g->close[fr_close_index].closest) {
1411 g->close[fr_close_index].type = GROUPCHAT_CLOSE_NONE; 1512 g->close[fr_close_index].type = GROUPCHAT_CLOSE_NONE;
@@ -1452,8 +1553,9 @@ static unsigned int send_peers(Group_Chats *g_c, int groupnumber, int friendcon_
1452{ 1553{
1453 Group_c *g = get_group_c(g_c, groupnumber); 1554 Group_c *g = get_group_c(g_c, groupnumber);
1454 1555
1455 if (!g) 1556 if (!g) {
1456 return -1; 1557 return -1;
1558 }
1457 1559
1458 uint8_t packet[MAX_CRYPTO_DATA_SIZE - (1 + sizeof(uint16_t))]; 1560 uint8_t packet[MAX_CRYPTO_DATA_SIZE - (1 + sizeof(uint16_t))];
1459 packet[0] = PEER_RESPONSE_ID; 1561 packet[0] = PEER_RESPONSE_ID;
@@ -1504,13 +1606,15 @@ static unsigned int send_peers(Group_Chats *g_c, int groupnumber, int friendcon_
1504 1606
1505static int handle_send_peers(Group_Chats *g_c, int groupnumber, const uint8_t *data, uint16_t length) 1607static int handle_send_peers(Group_Chats *g_c, int groupnumber, const uint8_t *data, uint16_t length)
1506{ 1608{
1507 if (length == 0) 1609 if (length == 0) {
1508 return -1; 1610 return -1;
1611 }
1509 1612
1510 Group_c *g = get_group_c(g_c, groupnumber); 1613 Group_c *g = get_group_c(g_c, groupnumber);
1511 1614
1512 if (!g) 1615 if (!g) {
1513 return -1; 1616 return -1;
1617 }
1514 1618
1515 const uint8_t *d = data; 1619 const uint8_t *d = data;
1516 1620
@@ -1521,8 +1625,9 @@ static int handle_send_peers(Group_Chats *g_c, int groupnumber, const uint8_t *d
1521 d += sizeof(uint16_t); 1625 d += sizeof(uint16_t);
1522 int peer_index = addpeer(g_c, groupnumber, d, d + crypto_box_PUBLICKEYBYTES, peer_num); 1626 int peer_index = addpeer(g_c, groupnumber, d, d + crypto_box_PUBLICKEYBYTES, peer_num);
1523 1627
1524 if (peer_index == -1) 1628 if (peer_index == -1) {
1525 return -1; 1629 return -1;
1630 }
1526 1631
1527 if (g->status == GROUPCHAT_STATUS_VALID 1632 if (g->status == GROUPCHAT_STATUS_VALID
1528 && public_key_cmp(d, g_c->m->net_crypto->self_public_key) == 0) { 1633 && public_key_cmp(d, g_c->m->net_crypto->self_public_key) == 0) {
@@ -1535,8 +1640,9 @@ static int handle_send_peers(Group_Chats *g_c, int groupnumber, const uint8_t *d
1535 uint8_t name_length = *d; 1640 uint8_t name_length = *d;
1536 d += 1; 1641 d += 1;
1537 1642
1538 if (name_length > (length - (d - data)) || name_length > MAX_NAME_LENGTH) 1643 if (name_length > (length - (d - data)) || name_length > MAX_NAME_LENGTH) {
1539 return -1; 1644 return -1;
1645 }
1540 1646
1541 setnick(g_c, groupnumber, peer_index, d, name_length); 1647 setnick(g_c, groupnumber, peer_index, d, name_length);
1542 d += name_length; 1648 d += name_length;
@@ -1548,15 +1654,17 @@ static int handle_send_peers(Group_Chats *g_c, int groupnumber, const uint8_t *d
1548static void handle_direct_packet(Group_Chats *g_c, int groupnumber, const uint8_t *data, uint16_t length, 1654static void handle_direct_packet(Group_Chats *g_c, int groupnumber, const uint8_t *data, uint16_t length,
1549 int close_index) 1655 int close_index)
1550{ 1656{
1551 if (length == 0) 1657 if (length == 0) {
1552 return; 1658 return;
1659 }
1553 1660
1554 switch (data[0]) { 1661 switch (data[0]) {
1555 case PEER_KILL_ID: { 1662 case PEER_KILL_ID: {
1556 Group_c *g = get_group_c(g_c, groupnumber); 1663 Group_c *g = get_group_c(g_c, groupnumber);
1557 1664
1558 if (!g) 1665 if (!g) {
1559 return; 1666 return;
1667 }
1560 1668
1561 if (!g->close[close_index].closest) { 1669 if (!g->close[close_index].closest) {
1562 g->close[close_index].type = GROUPCHAT_CLOSE_NONE; 1670 g->close[close_index].type = GROUPCHAT_CLOSE_NONE;
@@ -1569,8 +1677,9 @@ static void handle_direct_packet(Group_Chats *g_c, int groupnumber, const uint8_
1569 case PEER_QUERY_ID: { 1677 case PEER_QUERY_ID: {
1570 Group_c *g = get_group_c(g_c, groupnumber); 1678 Group_c *g = get_group_c(g_c, groupnumber);
1571 1679
1572 if (!g) 1680 if (!g) {
1573 return; 1681 return;
1682 }
1574 1683
1575 send_peers(g_c, groupnumber, g->close[close_index].number, g->close[close_index].group_number); 1684 send_peers(g_c, groupnumber, g->close[close_index].number, g->close[close_index].group_number);
1576 } 1685 }
@@ -1603,21 +1712,25 @@ static unsigned int send_message_all_close(const Group_Chats *g_c, int groupnumb
1603{ 1712{
1604 Group_c *g = get_group_c(g_c, groupnumber); 1713 Group_c *g = get_group_c(g_c, groupnumber);
1605 1714
1606 if (!g) 1715 if (!g) {
1607 return 0; 1716 return 0;
1717 }
1608 1718
1609 uint16_t i, sent = 0; 1719 uint16_t i, sent = 0;
1610 1720
1611 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 1721 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
1612 if (g->close[i].type != GROUPCHAT_CLOSE_ONLINE) 1722 if (g->close[i].type != GROUPCHAT_CLOSE_ONLINE) {
1613 continue; 1723 continue;
1724 }
1614 1725
1615 if ((int)i == receiver) 1726 if ((int)i == receiver) {
1616 continue; 1727 continue;
1728 }
1617 1729
1618 if (send_packet_group_peer(g_c->fr_c, g->close[i].number, PACKET_ID_MESSAGE_GROUPCHAT, g->close[i].group_number, data, 1730 if (send_packet_group_peer(g_c->fr_c, g->close[i].number, PACKET_ID_MESSAGE_GROUPCHAT, g->close[i].group_number, data,
1619 length)) 1731 length)) {
1620 ++sent; 1732 ++sent;
1733 }
1621 } 1734 }
1622 1735
1623 return sent; 1736 return sent;
@@ -1633,17 +1746,20 @@ static unsigned int send_lossy_all_close(const Group_Chats *g_c, int groupnumber
1633{ 1746{
1634 Group_c *g = get_group_c(g_c, groupnumber); 1747 Group_c *g = get_group_c(g_c, groupnumber);
1635 1748
1636 if (!g) 1749 if (!g) {
1637 return 0; 1750 return 0;
1751 }
1638 1752
1639 unsigned int i, sent = 0, num_connected_closest = 0, connected_closest[DESIRED_CLOSE_CONNECTIONS]; 1753 unsigned int i, sent = 0, num_connected_closest = 0, connected_closest[DESIRED_CLOSE_CONNECTIONS];
1640 1754
1641 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) { 1755 for (i = 0; i < MAX_GROUP_CONNECTIONS; ++i) {
1642 if (g->close[i].type != GROUPCHAT_CLOSE_ONLINE) 1756 if (g->close[i].type != GROUPCHAT_CLOSE_ONLINE) {
1643 continue; 1757 continue;
1758 }
1644 1759
1645 if ((int)i == receiver) 1760 if ((int)i == receiver) {
1646 continue; 1761 continue;
1762 }
1647 1763
1648 if (g->close[i].closest) { 1764 if (g->close[i].closest) {
1649 connected_closest[num_connected_closest] = i; 1765 connected_closest[num_connected_closest] = i;
@@ -1652,8 +1768,9 @@ static unsigned int send_lossy_all_close(const Group_Chats *g_c, int groupnumber
1652 } 1768 }
1653 1769
1654 if (send_lossy_group_peer(g_c->fr_c, g->close[i].number, PACKET_ID_LOSSY_GROUPCHAT, g->close[i].group_number, data, 1770 if (send_lossy_group_peer(g_c->fr_c, g->close[i].number, PACKET_ID_LOSSY_GROUPCHAT, g->close[i].group_number, data,
1655 length)) 1771 length)) {
1656 ++sent; 1772 ++sent;
1773 }
1657 } 1774 }
1658 1775
1659 if (!num_connected_closest) { 1776 if (!num_connected_closest) {
@@ -1717,16 +1834,19 @@ static unsigned int send_lossy_all_close(const Group_Chats *g_c, int groupnumber
1717static unsigned int send_message_group(const Group_Chats *g_c, int groupnumber, uint8_t message_id, const uint8_t *data, 1834static unsigned int send_message_group(const Group_Chats *g_c, int groupnumber, uint8_t message_id, const uint8_t *data,
1718 uint16_t len) 1835 uint16_t len)
1719{ 1836{
1720 if (len > MAX_GROUP_MESSAGE_DATA_LEN) 1837 if (len > MAX_GROUP_MESSAGE_DATA_LEN) {
1721 return 0; 1838 return 0;
1839 }
1722 1840
1723 Group_c *g = get_group_c(g_c, groupnumber); 1841 Group_c *g = get_group_c(g_c, groupnumber);
1724 1842
1725 if (!g) 1843 if (!g) {
1726 return 0; 1844 return 0;
1845 }
1727 1846
1728 if (g->status != GROUPCHAT_STATUS_CONNECTED) 1847 if (g->status != GROUPCHAT_STATUS_CONNECTED) {
1729 return 0; 1848 return 0;
1849 }
1730 1850
1731 uint8_t packet[sizeof(uint16_t) + sizeof(uint32_t) + 1 + len]; 1851 uint8_t packet[sizeof(uint16_t) + sizeof(uint32_t) + 1 + len];
1732 uint16_t peer_num = htons(g->peer_number); 1852 uint16_t peer_num = htons(g->peer_number);
@@ -1734,16 +1854,18 @@ static unsigned int send_message_group(const Group_Chats *g_c, int groupnumber,
1734 1854
1735 ++g->message_number; 1855 ++g->message_number;
1736 1856
1737 if (!g->message_number) 1857 if (!g->message_number) {
1738 ++g->message_number; 1858 ++g->message_number;
1859 }
1739 1860
1740 uint32_t message_num = htonl(g->message_number); 1861 uint32_t message_num = htonl(g->message_number);
1741 memcpy(packet + sizeof(uint16_t), &message_num, sizeof(message_num)); 1862 memcpy(packet + sizeof(uint16_t), &message_num, sizeof(message_num));
1742 1863
1743 packet[sizeof(uint16_t) + sizeof(uint32_t)] = message_id; 1864 packet[sizeof(uint16_t) + sizeof(uint32_t)] = message_id;
1744 1865
1745 if (len) 1866 if (len) {
1746 memcpy(packet + sizeof(uint16_t) + sizeof(uint32_t) + 1, data, len); 1867 memcpy(packet + sizeof(uint16_t) + sizeof(uint32_t) + 1, data, len);
1868 }
1747 1869
1748 return send_message_all_close(g_c, groupnumber, packet, sizeof(packet), -1); 1870 return send_message_all_close(g_c, groupnumber, packet, sizeof(packet), -1);
1749} 1871}
@@ -1784,8 +1906,9 @@ int send_group_lossy_packet(const Group_Chats *g_c, int groupnumber, const uint8
1784 //TODO: length check here? 1906 //TODO: length check here?
1785 Group_c *g = get_group_c(g_c, groupnumber); 1907 Group_c *g = get_group_c(g_c, groupnumber);
1786 1908
1787 if (!g) 1909 if (!g) {
1788 return -1; 1910 return -1;
1911 }
1789 1912
1790 uint8_t packet[sizeof(uint16_t) * 2 + length]; 1913 uint8_t packet[sizeof(uint16_t) * 2 + length];
1791 uint16_t peer_number = htons(g->peer_number); 1914 uint16_t peer_number = htons(g->peer_number);
@@ -1805,13 +1928,15 @@ int send_group_lossy_packet(const Group_Chats *g_c, int groupnumber, const uint8
1805static void handle_message_packet_group(Group_Chats *g_c, int groupnumber, const uint8_t *data, uint16_t length, 1928static void handle_message_packet_group(Group_Chats *g_c, int groupnumber, const uint8_t *data, uint16_t length,
1806 int close_index) 1929 int close_index)
1807{ 1930{
1808 if (length < sizeof(uint16_t) + sizeof(uint32_t) + 1) 1931 if (length < sizeof(uint16_t) + sizeof(uint32_t) + 1) {
1809 return; 1932 return;
1933 }
1810 1934
1811 Group_c *g = get_group_c(g_c, groupnumber); 1935 Group_c *g = get_group_c(g_c, groupnumber);
1812 1936
1813 if (!g) 1937 if (!g) {
1814 return; 1938 return;
1939 }
1815 1940
1816 uint16_t peer_number; 1941 uint16_t peer_number;
1817 memcpy(&peer_number, data, sizeof(uint16_t)); 1942 memcpy(&peer_number, data, sizeof(uint16_t));
@@ -1845,16 +1970,18 @@ static void handle_message_packet_group(Group_Chats *g_c, int groupnumber, const
1845 1970
1846 switch (message_id) { 1971 switch (message_id) {
1847 case GROUP_MESSAGE_PING_ID: { 1972 case GROUP_MESSAGE_PING_ID: {
1848 if (msg_data_len != 0) 1973 if (msg_data_len != 0) {
1849 return; 1974 return;
1975 }
1850 1976
1851 g->group[index].last_recv = unix_time(); 1977 g->group[index].last_recv = unix_time();
1852 } 1978 }
1853 break; 1979 break;
1854 1980
1855 case GROUP_MESSAGE_NEW_PEER_ID: { 1981 case GROUP_MESSAGE_NEW_PEER_ID: {
1856 if (msg_data_len != GROUP_MESSAGE_NEW_PEER_LENGTH) 1982 if (msg_data_len != GROUP_MESSAGE_NEW_PEER_LENGTH) {
1857 return; 1983 return;
1984 }
1858 1985
1859 uint16_t new_peer_number; 1986 uint16_t new_peer_number;
1860 memcpy(&new_peer_number, msg_data, sizeof(uint16_t)); 1987 memcpy(&new_peer_number, msg_data, sizeof(uint16_t));
@@ -1865,8 +1992,9 @@ static void handle_message_packet_group(Group_Chats *g_c, int groupnumber, const
1865 break; 1992 break;
1866 1993
1867 case GROUP_MESSAGE_KILL_PEER_ID: { 1994 case GROUP_MESSAGE_KILL_PEER_ID: {
1868 if (msg_data_len != GROUP_MESSAGE_KILL_PEER_LENGTH) 1995 if (msg_data_len != GROUP_MESSAGE_KILL_PEER_LENGTH) {
1869 return; 1996 return;
1997 }
1870 1998
1871 uint16_t kill_peer_number; 1999 uint16_t kill_peer_number;
1872 memcpy(&kill_peer_number, msg_data, sizeof(uint16_t)); 2000 memcpy(&kill_peer_number, msg_data, sizeof(uint16_t));
@@ -1882,43 +2010,49 @@ static void handle_message_packet_group(Group_Chats *g_c, int groupnumber, const
1882 break; 2010 break;
1883 2011
1884 case GROUP_MESSAGE_NAME_ID: { 2012 case GROUP_MESSAGE_NAME_ID: {
1885 if (setnick(g_c, groupnumber, index, msg_data, msg_data_len) == -1) 2013 if (setnick(g_c, groupnumber, index, msg_data, msg_data_len) == -1) {
1886 return; 2014 return;
2015 }
1887 } 2016 }
1888 break; 2017 break;
1889 2018
1890 case GROUP_MESSAGE_TITLE_ID: { 2019 case GROUP_MESSAGE_TITLE_ID: {
1891 if (settitle(g_c, groupnumber, index, msg_data, msg_data_len) == -1) 2020 if (settitle(g_c, groupnumber, index, msg_data, msg_data_len) == -1) {
1892 return; 2021 return;
2022 }
1893 } 2023 }
1894 break; 2024 break;
1895 2025
1896 case PACKET_ID_MESSAGE: { 2026 case PACKET_ID_MESSAGE: {
1897 if (msg_data_len == 0) 2027 if (msg_data_len == 0) {
1898 return; 2028 return;
2029 }
1899 2030
1900 uint8_t newmsg[msg_data_len + 1]; 2031 uint8_t newmsg[msg_data_len + 1];
1901 memcpy(newmsg, msg_data, msg_data_len); 2032 memcpy(newmsg, msg_data, msg_data_len);
1902 newmsg[msg_data_len] = 0; 2033 newmsg[msg_data_len] = 0;
1903 2034
1904 //TODO 2035 //TODO
1905 if (g_c->message_callback) 2036 if (g_c->message_callback) {
1906 g_c->message_callback(g_c->m, groupnumber, index, newmsg, msg_data_len, g_c->message_callback_userdata); 2037 g_c->message_callback(g_c->m, groupnumber, index, newmsg, msg_data_len, g_c->message_callback_userdata);
2038 }
1907 2039
1908 break; 2040 break;
1909 } 2041 }
1910 2042
1911 case PACKET_ID_ACTION: { 2043 case PACKET_ID_ACTION: {
1912 if (msg_data_len == 0) 2044 if (msg_data_len == 0) {
1913 return; 2045 return;
2046 }
1914 2047
1915 uint8_t newmsg[msg_data_len + 1]; 2048 uint8_t newmsg[msg_data_len + 1];
1916 memcpy(newmsg, msg_data, msg_data_len); 2049 memcpy(newmsg, msg_data, msg_data_len);
1917 newmsg[msg_data_len] = 0; 2050 newmsg[msg_data_len] = 0;
1918 2051
1919 //TODO 2052 //TODO
1920 if (g_c->action_callback) 2053 if (g_c->action_callback) {
1921 g_c->action_callback(g_c->m, groupnumber, index, newmsg, msg_data_len, g_c->action_callback_userdata); 2054 g_c->action_callback(g_c->m, groupnumber, index, newmsg, msg_data_len, g_c->action_callback_userdata);
2055 }
1922 2056
1923 break; 2057 break;
1924 } 2058 }
@@ -1934,28 +2068,32 @@ static int handle_packet(void *object, int friendcon_id, uint8_t *data, uint16_t
1934{ 2068{
1935 Group_Chats *g_c = object; 2069 Group_Chats *g_c = object;
1936 2070
1937 if (length < 1 + sizeof(uint16_t) + 1) 2071 if (length < 1 + sizeof(uint16_t) + 1) {
1938 return -1; 2072 return -1;
2073 }
1939 2074
1940 if (data[0] == PACKET_ID_ONLINE_PACKET) { 2075 if (data[0] == PACKET_ID_ONLINE_PACKET) {
1941 return handle_packet_online(g_c, friendcon_id, data + 1, length - 1); 2076 return handle_packet_online(g_c, friendcon_id, data + 1, length - 1);
1942 } 2077 }
1943 2078
1944 if (data[0] != PACKET_ID_DIRECT_GROUPCHAT && data[0] != PACKET_ID_MESSAGE_GROUPCHAT) 2079 if (data[0] != PACKET_ID_DIRECT_GROUPCHAT && data[0] != PACKET_ID_MESSAGE_GROUPCHAT) {
1945 return -1; 2080 return -1;
2081 }
1946 2082
1947 uint16_t groupnumber; 2083 uint16_t groupnumber;
1948 memcpy(&groupnumber, data + 1, sizeof(uint16_t)); 2084 memcpy(&groupnumber, data + 1, sizeof(uint16_t));
1949 groupnumber = ntohs(groupnumber); 2085 groupnumber = ntohs(groupnumber);
1950 Group_c *g = get_group_c(g_c, groupnumber); 2086 Group_c *g = get_group_c(g_c, groupnumber);
1951 2087
1952 if (!g) 2088 if (!g) {
1953 return -1; 2089 return -1;
2090 }
1954 2091
1955 int index = friend_in_close(g, friendcon_id); 2092 int index = friend_in_close(g, friendcon_id);
1956 2093
1957 if (index == -1) 2094 if (index == -1) {
1958 return -1; 2095 return -1;
2096 }
1959 2097
1960 switch (data[0]) { 2098 switch (data[0]) {
1961 case PACKET_ID_DIRECT_GROUPCHAT: { 2099 case PACKET_ID_DIRECT_GROUPCHAT: {
@@ -1986,8 +2124,9 @@ static int handle_packet(void *object, int friendcon_id, uint8_t *data, uint16_t
1986 */ 2124 */
1987static unsigned int lossy_packet_not_received(Group_c *g, int peer_index, uint16_t message_number) 2125static unsigned int lossy_packet_not_received(Group_c *g, int peer_index, uint16_t message_number)
1988{ 2126{
1989 if (peer_index == -1) 2127 if (peer_index == -1) {
1990 return -1; 2128 return -1;
2129 }
1991 2130
1992 if (g->group[peer_index].bottom_lossy_number == g->group[peer_index].top_lossy_number) { 2131 if (g->group[peer_index].bottom_lossy_number == g->group[peer_index].top_lossy_number) {
1993 g->group[peer_index].top_lossy_number = message_number; 2132 g->group[peer_index].top_lossy_number = message_number;
@@ -2005,8 +2144,9 @@ static unsigned int lossy_packet_not_received(Group_c *g, int peer_index, uint16
2005 return 0; 2144 return 0;
2006 } 2145 }
2007 2146
2008 if ((uint16_t)(message_number - g->group[peer_index].bottom_lossy_number) > (1 << 15)) 2147 if ((uint16_t)(message_number - g->group[peer_index].bottom_lossy_number) > (1 << 15)) {
2009 return -1; 2148 return -1;
2149 }
2010 2150
2011 uint16_t top_distance = message_number - g->group[peer_index].top_lossy_number; 2151 uint16_t top_distance = message_number - g->group[peer_index].top_lossy_number;
2012 2152
@@ -2039,11 +2179,13 @@ static int handle_lossy(void *object, int friendcon_id, const uint8_t *data, uin
2039{ 2179{
2040 Group_Chats *g_c = object; 2180 Group_Chats *g_c = object;
2041 2181
2042 if (length < 1 + sizeof(uint16_t) * 3 + 1) 2182 if (length < 1 + sizeof(uint16_t) * 3 + 1) {
2043 return -1; 2183 return -1;
2184 }
2044 2185
2045 if (data[0] != PACKET_ID_LOSSY_GROUPCHAT) 2186 if (data[0] != PACKET_ID_LOSSY_GROUPCHAT) {
2046 return -1; 2187 return -1;
2188 }
2047 2189
2048 uint16_t groupnumber, peer_number, message_number; 2190 uint16_t groupnumber, peer_number, message_number;
2049 memcpy(&groupnumber, data + 1, sizeof(uint16_t)); 2191 memcpy(&groupnumber, data + 1, sizeof(uint16_t));
@@ -2055,24 +2197,29 @@ static int handle_lossy(void *object, int friendcon_id, const uint8_t *data, uin
2055 2197
2056 Group_c *g = get_group_c(g_c, groupnumber); 2198 Group_c *g = get_group_c(g_c, groupnumber);
2057 2199
2058 if (!g) 2200 if (!g) {
2059 return -1; 2201 return -1;
2202 }
2060 2203
2061 int index = friend_in_close(g, friendcon_id); 2204 int index = friend_in_close(g, friendcon_id);
2062 2205
2063 if (index == -1) 2206 if (index == -1) {
2064 return -1; 2207 return -1;
2208 }
2065 2209
2066 if (peer_number == g->peer_number) 2210 if (peer_number == g->peer_number) {
2067 return -1; 2211 return -1;
2212 }
2068 2213
2069 int peer_index = get_peer_index(g, peer_number); 2214 int peer_index = get_peer_index(g, peer_number);
2070 2215
2071 if (peer_index == -1) 2216 if (peer_index == -1) {
2072 return -1; 2217 return -1;
2218 }
2073 2219
2074 if (lossy_packet_not_received(g, peer_index, message_number)) 2220 if (lossy_packet_not_received(g, peer_index, message_number)) {
2075 return -1; 2221 return -1;
2222 }
2076 2223
2077 const uint8_t *lossy_data = data + 1 + sizeof(uint16_t) * 3; 2224 const uint8_t *lossy_data = data + 1 + sizeof(uint16_t) * 3;
2078 uint16_t lossy_length = length - (1 + sizeof(uint16_t) * 3); 2225 uint16_t lossy_length = length - (1 + sizeof(uint16_t) * 3);
@@ -2102,8 +2249,9 @@ int group_set_object(const Group_Chats *g_c, int groupnumber, void *object)
2102{ 2249{
2103 Group_c *g = get_group_c(g_c, groupnumber); 2250 Group_c *g = get_group_c(g_c, groupnumber);
2104 2251
2105 if (!g) 2252 if (!g) {
2106 return -1; 2253 return -1;
2254 }
2107 2255
2108 g->object = object; 2256 g->object = object;
2109 return 0; 2257 return 0;
@@ -2118,11 +2266,13 @@ int group_peer_set_object(const Group_Chats *g_c, int groupnumber, int peernumbe
2118{ 2266{
2119 Group_c *g = get_group_c(g_c, groupnumber); 2267 Group_c *g = get_group_c(g_c, groupnumber);
2120 2268
2121 if (!g) 2269 if (!g) {
2122 return -1; 2270 return -1;
2271 }
2123 2272
2124 if ((uint32_t)peernumber >= g->numpeers) 2273 if ((uint32_t)peernumber >= g->numpeers) {
2125 return -1; 2274 return -1;
2275 }
2126 2276
2127 g->group[peernumber].object = object; 2277 g->group[peernumber].object = object;
2128 return 0; 2278 return 0;
@@ -2137,8 +2287,9 @@ void *group_get_object(const Group_Chats *g_c, int groupnumber)
2137{ 2287{
2138 Group_c *g = get_group_c(g_c, groupnumber); 2288 Group_c *g = get_group_c(g_c, groupnumber);
2139 2289
2140 if (!g) 2290 if (!g) {
2141 return NULL; 2291 return NULL;
2292 }
2142 2293
2143 return g->object; 2294 return g->object;
2144} 2295}
@@ -2152,11 +2303,13 @@ void *group_peer_get_object(const Group_Chats *g_c, int groupnumber, int peernum
2152{ 2303{
2153 Group_c *g = get_group_c(g_c, groupnumber); 2304 Group_c *g = get_group_c(g_c, groupnumber);
2154 2305
2155 if (!g) 2306 if (!g) {
2156 return NULL; 2307 return NULL;
2308 }
2157 2309
2158 if ((uint32_t)peernumber >= g->numpeers) 2310 if ((uint32_t)peernumber >= g->numpeers) {
2159 return NULL; 2311 return NULL;
2312 }
2160 2313
2161 return g->group[peernumber].object; 2314 return g->group[peernumber].object;
2162} 2315}
@@ -2168,12 +2321,14 @@ static int ping_groupchat(Group_Chats *g_c, int groupnumber)
2168{ 2321{
2169 Group_c *g = get_group_c(g_c, groupnumber); 2322 Group_c *g = get_group_c(g_c, groupnumber);
2170 2323
2171 if (!g) 2324 if (!g) {
2172 return -1; 2325 return -1;
2326 }
2173 2327
2174 if (is_timeout(g->last_sent_ping, GROUP_PING_INTERVAL)) { 2328 if (is_timeout(g->last_sent_ping, GROUP_PING_INTERVAL)) {
2175 if (group_ping_send(g_c, groupnumber) != -1) /* Ping */ 2329 if (group_ping_send(g_c, groupnumber) != -1) { /* Ping */
2176 g->last_sent_ping = unix_time(); 2330 g->last_sent_ping = unix_time();
2331 }
2177 } 2332 }
2178 2333
2179 return 0; 2334 return 0;
@@ -2183,8 +2338,9 @@ static int groupchat_clear_timedout(Group_Chats *g_c, int groupnumber)
2183{ 2338{
2184 Group_c *g = get_group_c(g_c, groupnumber); 2339 Group_c *g = get_group_c(g_c, groupnumber);
2185 2340
2186 if (!g) 2341 if (!g) {
2187 return -1; 2342 return -1;
2343 }
2188 2344
2189 uint32_t i; 2345 uint32_t i;
2190 2346
@@ -2193,8 +2349,9 @@ static int groupchat_clear_timedout(Group_Chats *g_c, int groupnumber)
2193 delpeer(g_c, groupnumber, i); 2349 delpeer(g_c, groupnumber, i);
2194 } 2350 }
2195 2351
2196 if (g->group == NULL || i >= g->numpeers) 2352 if (g->group == NULL || i >= g->numpeers) {
2197 break; 2353 break;
2354 }
2198 } 2355 }
2199 2356
2200 return 0; 2357 return 0;
@@ -2209,8 +2366,9 @@ void send_name_all_groups(Group_Chats *g_c)
2209 for (i = 0; i < g_c->num_chats; ++i) { 2366 for (i = 0; i < g_c->num_chats; ++i) {
2210 Group_c *g = get_group_c(g_c, i); 2367 Group_c *g = get_group_c(g_c, i);
2211 2368
2212 if (!g) 2369 if (!g) {
2213 continue; 2370 continue;
2371 }
2214 2372
2215 if (g->status == GROUPCHAT_STATUS_CONNECTED) { 2373 if (g->status == GROUPCHAT_STATUS_CONNECTED) {
2216 group_name_send(g_c, i, g_c->m->name, g_c->m->name_length); 2374 group_name_send(g_c, i, g_c->m->name, g_c->m->name_length);
@@ -2221,13 +2379,15 @@ void send_name_all_groups(Group_Chats *g_c)
2221/* Create new groupchat instance. */ 2379/* Create new groupchat instance. */
2222Group_Chats *new_groupchats(Messenger *m) 2380Group_Chats *new_groupchats(Messenger *m)
2223{ 2381{
2224 if (!m) 2382 if (!m) {
2225 return NULL; 2383 return NULL;
2384 }
2226 2385
2227 Group_Chats *temp = calloc(1, sizeof(Group_Chats)); 2386 Group_Chats *temp = calloc(1, sizeof(Group_Chats));
2228 2387
2229 if (temp == NULL) 2388 if (temp == NULL) {
2230 return NULL; 2389 return NULL;
2390 }
2231 2391
2232 temp->m = m; 2392 temp->m = m;
2233 temp->fr_c = m->fr_c; 2393 temp->fr_c = m->fr_c;
@@ -2245,8 +2405,9 @@ void do_groupchats(Group_Chats *g_c)
2245 for (i = 0; i < g_c->num_chats; ++i) { 2405 for (i = 0; i < g_c->num_chats; ++i) {
2246 Group_c *g = get_group_c(g_c, i); 2406 Group_c *g = get_group_c(g_c, i);
2247 2407
2248 if (!g) 2408 if (!g) {
2249 continue; 2409 continue;
2410 }
2250 2411
2251 if (g->status == GROUPCHAT_STATUS_CONNECTED) { 2412 if (g->status == GROUPCHAT_STATUS_CONNECTED) {
2252 connect_to_closest(g_c, i); 2413 connect_to_closest(g_c, i);
diff --git a/toxcore/logger.c b/toxcore/logger.c
index 8e6487c2..c6f4056b 100644
--- a/toxcore/logger.c
+++ b/toxcore/logger.c
@@ -54,8 +54,9 @@ void logger_callback_log(Logger *log, logger_cb *function, void *userdata)
54void logger_write(Logger *log, LOGGER_LEVEL level, const char *file, int line, const char *func, const char *format, 54void logger_write(Logger *log, LOGGER_LEVEL level, const char *file, int line, const char *func, const char *format,
55 ...) 55 ...)
56{ 56{
57 if (!log || !log->callback) 57 if (!log || !log->callback) {
58 return; 58 return;
59 }
59 60
60 /* Format message */ 61 /* Format message */
61 char msg[1024]; 62 char msg[1024];
diff --git a/toxcore/net_crypto.c b/toxcore/net_crypto.c
index 90242b66..8ae8acf8 100644
--- a/toxcore/net_crypto.c
+++ b/toxcore/net_crypto.c
@@ -33,14 +33,17 @@
33 33
34static uint8_t crypt_connection_id_not_valid(const Net_Crypto *c, int crypt_connection_id) 34static uint8_t crypt_connection_id_not_valid(const Net_Crypto *c, int crypt_connection_id)
35{ 35{
36 if ((uint32_t)crypt_connection_id >= c->crypto_connections_length) 36 if ((uint32_t)crypt_connection_id >= c->crypto_connections_length) {
37 return 1; 37 return 1;
38 }
38 39
39 if (c->crypto_connections == NULL) 40 if (c->crypto_connections == NULL) {
40 return 1; 41 return 1;
42 }
41 43
42 if (c->crypto_connections[crypt_connection_id].status == CRYPTO_CONN_NO_CONNECTION) 44 if (c->crypto_connections[crypt_connection_id].status == CRYPTO_CONN_NO_CONNECTION) {
43 return 1; 45 return 1;
46 }
44 47
45 return 0; 48 return 0;
46} 49}
@@ -82,8 +85,9 @@ static int create_cookie_request(const Net_Crypto *c, uint8_t *packet, uint8_t *
82 int len = encrypt_data_symmetric(shared_key, nonce, plain, sizeof(plain), 85 int len = encrypt_data_symmetric(shared_key, nonce, plain, sizeof(plain),
83 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES); 86 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
84 87
85 if (len != COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES) 88 if (len != COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES) {
86 return -1; 89 return -1;
90 }
87 91
88 return (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + len); 92 return (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + len);
89} 93}
@@ -102,8 +106,9 @@ static int create_cookie(uint8_t *cookie, const uint8_t *bytes, const uint8_t *e
102 new_nonce(cookie); 106 new_nonce(cookie);
103 int len = encrypt_data_symmetric(encryption_key, cookie, contents, sizeof(contents), cookie + crypto_box_NONCEBYTES); 107 int len = encrypt_data_symmetric(encryption_key, cookie, contents, sizeof(contents), cookie + crypto_box_NONCEBYTES);
104 108
105 if (len != COOKIE_LENGTH - crypto_box_NONCEBYTES) 109 if (len != COOKIE_LENGTH - crypto_box_NONCEBYTES) {
106 return -1; 110 return -1;
111 }
107 112
108 return 0; 113 return 0;
109} 114}
@@ -119,15 +124,17 @@ static int open_cookie(uint8_t *bytes, const uint8_t *cookie, const uint8_t *enc
119 int len = decrypt_data_symmetric(encryption_key, cookie, cookie + crypto_box_NONCEBYTES, 124 int len = decrypt_data_symmetric(encryption_key, cookie, cookie + crypto_box_NONCEBYTES,
120 COOKIE_LENGTH - crypto_box_NONCEBYTES, contents); 125 COOKIE_LENGTH - crypto_box_NONCEBYTES, contents);
121 126
122 if (len != sizeof(contents)) 127 if (len != sizeof(contents)) {
123 return -1; 128 return -1;
129 }
124 130
125 uint64_t cookie_time; 131 uint64_t cookie_time;
126 memcpy(&cookie_time, contents, sizeof(cookie_time)); 132 memcpy(&cookie_time, contents, sizeof(cookie_time));
127 uint64_t temp_time = unix_time(); 133 uint64_t temp_time = unix_time();
128 134
129 if (cookie_time + COOKIE_TIMEOUT < temp_time || temp_time < cookie_time) 135 if (cookie_time + COOKIE_TIMEOUT < temp_time || temp_time < cookie_time) {
130 return -1; 136 return -1;
137 }
131 138
132 memcpy(bytes, contents + sizeof(cookie_time), COOKIE_DATA_LENGTH); 139 memcpy(bytes, contents + sizeof(cookie_time), COOKIE_DATA_LENGTH);
133 return 0; 140 return 0;
@@ -149,16 +156,18 @@ static int create_cookie_response(const Net_Crypto *c, uint8_t *packet, const ui
149 memcpy(cookie_plain + crypto_box_PUBLICKEYBYTES, dht_public_key, crypto_box_PUBLICKEYBYTES); 156 memcpy(cookie_plain + crypto_box_PUBLICKEYBYTES, dht_public_key, crypto_box_PUBLICKEYBYTES);
150 uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)]; 157 uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
151 158
152 if (create_cookie(plain, cookie_plain, c->secret_symmetric_key) != 0) 159 if (create_cookie(plain, cookie_plain, c->secret_symmetric_key) != 0) {
153 return -1; 160 return -1;
161 }
154 162
155 memcpy(plain + COOKIE_LENGTH, request_plain + COOKIE_DATA_LENGTH, sizeof(uint64_t)); 163 memcpy(plain + COOKIE_LENGTH, request_plain + COOKIE_DATA_LENGTH, sizeof(uint64_t));
156 packet[0] = NET_PACKET_COOKIE_RESPONSE; 164 packet[0] = NET_PACKET_COOKIE_RESPONSE;
157 new_nonce(packet + 1); 165 new_nonce(packet + 1);
158 int len = encrypt_data_symmetric(shared_key, packet + 1, plain, sizeof(plain), packet + 1 + crypto_box_NONCEBYTES); 166 int len = encrypt_data_symmetric(shared_key, packet + 1, plain, sizeof(plain), packet + 1 + crypto_box_NONCEBYTES);
159 167
160 if (len != COOKIE_RESPONSE_LENGTH - (1 + crypto_box_NONCEBYTES)) 168 if (len != COOKIE_RESPONSE_LENGTH - (1 + crypto_box_NONCEBYTES)) {
161 return -1; 169 return -1;
170 }
162 171
163 return COOKIE_RESPONSE_LENGTH; 172 return COOKIE_RESPONSE_LENGTH;
164} 173}
@@ -173,8 +182,9 @@ static int create_cookie_response(const Net_Crypto *c, uint8_t *packet, const ui
173static int handle_cookie_request(const Net_Crypto *c, uint8_t *request_plain, uint8_t *shared_key, 182static int handle_cookie_request(const Net_Crypto *c, uint8_t *request_plain, uint8_t *shared_key,
174 uint8_t *dht_public_key, const uint8_t *packet, uint16_t length) 183 uint8_t *dht_public_key, const uint8_t *packet, uint16_t length)
175{ 184{
176 if (length != COOKIE_REQUEST_LENGTH) 185 if (length != COOKIE_REQUEST_LENGTH) {
177 return -1; 186 return -1;
187 }
178 188
179 memcpy(dht_public_key, packet + 1, crypto_box_PUBLICKEYBYTES); 189 memcpy(dht_public_key, packet + 1, crypto_box_PUBLICKEYBYTES);
180 DHT_get_shared_key_sent(c->dht, shared_key, dht_public_key); 190 DHT_get_shared_key_sent(c->dht, shared_key, dht_public_key);
@@ -182,8 +192,9 @@ static int handle_cookie_request(const Net_Crypto *c, uint8_t *request_plain, ui
182 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES, 192 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, COOKIE_REQUEST_PLAIN_LENGTH + crypto_box_MACBYTES,
183 request_plain); 193 request_plain);
184 194
185 if (len != COOKIE_REQUEST_PLAIN_LENGTH) 195 if (len != COOKIE_REQUEST_PLAIN_LENGTH) {
186 return -1; 196 return -1;
197 }
187 198
188 return 0; 199 return 0;
189} 200}
@@ -198,16 +209,19 @@ static int udp_handle_cookie_request(void *object, IP_Port source, const uint8_t
198 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 209 uint8_t shared_key[crypto_box_BEFORENMBYTES];
199 uint8_t dht_public_key[crypto_box_PUBLICKEYBYTES]; 210 uint8_t dht_public_key[crypto_box_PUBLICKEYBYTES];
200 211
201 if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) 212 if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) {
202 return 1; 213 return 1;
214 }
203 215
204 uint8_t data[COOKIE_RESPONSE_LENGTH]; 216 uint8_t data[COOKIE_RESPONSE_LENGTH];
205 217
206 if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) 218 if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
207 return 1; 219 return 1;
220 }
208 221
209 if ((uint32_t)sendpacket(c->dht->net, source, data, sizeof(data)) != sizeof(data)) 222 if ((uint32_t)sendpacket(c->dht->net, source, data, sizeof(data)) != sizeof(data)) {
210 return 1; 223 return 1;
224 }
211 225
212 return 0; 226 return 0;
213} 227}
@@ -220,13 +234,15 @@ static int tcp_handle_cookie_request(Net_Crypto *c, int connections_number, cons
220 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 234 uint8_t shared_key[crypto_box_BEFORENMBYTES];
221 uint8_t dht_public_key[crypto_box_PUBLICKEYBYTES]; 235 uint8_t dht_public_key[crypto_box_PUBLICKEYBYTES];
222 236
223 if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) 237 if (handle_cookie_request(c, request_plain, shared_key, dht_public_key, packet, length) != 0) {
224 return -1; 238 return -1;
239 }
225 240
226 uint8_t data[COOKIE_RESPONSE_LENGTH]; 241 uint8_t data[COOKIE_RESPONSE_LENGTH];
227 242
228 if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) 243 if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
229 return -1; 244 return -1;
245 }
230 246
231 int ret = send_packet_tcp_connection(c->tcp_c, connections_number, data, sizeof(data)); 247 int ret = send_packet_tcp_connection(c->tcp_c, connections_number, data, sizeof(data));
232 return ret; 248 return ret;
@@ -241,16 +257,19 @@ static int tcp_oob_handle_cookie_request(const Net_Crypto *c, unsigned int tcp_c
241 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 257 uint8_t shared_key[crypto_box_BEFORENMBYTES];
242 uint8_t dht_public_key_temp[crypto_box_PUBLICKEYBYTES]; 258 uint8_t dht_public_key_temp[crypto_box_PUBLICKEYBYTES];
243 259
244 if (handle_cookie_request(c, request_plain, shared_key, dht_public_key_temp, packet, length) != 0) 260 if (handle_cookie_request(c, request_plain, shared_key, dht_public_key_temp, packet, length) != 0) {
245 return -1; 261 return -1;
262 }
246 263
247 if (public_key_cmp(dht_public_key, dht_public_key_temp) != 0) 264 if (public_key_cmp(dht_public_key, dht_public_key_temp) != 0) {
248 return -1; 265 return -1;
266 }
249 267
250 uint8_t data[COOKIE_RESPONSE_LENGTH]; 268 uint8_t data[COOKIE_RESPONSE_LENGTH];
251 269
252 if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) 270 if (create_cookie_response(c, data, request_plain, shared_key, dht_public_key) != sizeof(data)) {
253 return -1; 271 return -1;
272 }
254 273
255 int ret = tcp_send_oob_packet(c->tcp_c, tcp_connections_number, dht_public_key, data, sizeof(data)); 274 int ret = tcp_send_oob_packet(c->tcp_c, tcp_connections_number, dht_public_key, data, sizeof(data));
256 return ret; 275 return ret;
@@ -267,15 +286,17 @@ static int tcp_oob_handle_cookie_request(const Net_Crypto *c, unsigned int tcp_c
267static int handle_cookie_response(uint8_t *cookie, uint64_t *number, const uint8_t *packet, uint16_t length, 286static int handle_cookie_response(uint8_t *cookie, uint64_t *number, const uint8_t *packet, uint16_t length,
268 const uint8_t *shared_key) 287 const uint8_t *shared_key)
269{ 288{
270 if (length != COOKIE_RESPONSE_LENGTH) 289 if (length != COOKIE_RESPONSE_LENGTH) {
271 return -1; 290 return -1;
291 }
272 292
273 uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)]; 293 uint8_t plain[COOKIE_LENGTH + sizeof(uint64_t)];
274 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES, 294 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES,
275 length - (1 + crypto_box_NONCEBYTES), plain); 295 length - (1 + crypto_box_NONCEBYTES), plain);
276 296
277 if (len != sizeof(plain)) 297 if (len != sizeof(plain)) {
278 return -1; 298 return -1;
299 }
279 300
280 memcpy(cookie, plain, COOKIE_LENGTH); 301 memcpy(cookie, plain, COOKIE_LENGTH);
281 memcpy(number, plain + COOKIE_LENGTH, sizeof(uint64_t)); 302 memcpy(number, plain + COOKIE_LENGTH, sizeof(uint64_t));
@@ -303,15 +324,17 @@ static int create_crypto_handshake(const Net_Crypto *c, uint8_t *packet, const u
303 memcpy(cookie_plain + crypto_box_PUBLICKEYBYTES, peer_dht_pubkey, crypto_box_PUBLICKEYBYTES); 324 memcpy(cookie_plain + crypto_box_PUBLICKEYBYTES, peer_dht_pubkey, crypto_box_PUBLICKEYBYTES);
304 325
305 if (create_cookie(plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES, cookie_plain, 326 if (create_cookie(plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_hash_sha512_BYTES, cookie_plain,
306 c->secret_symmetric_key) != 0) 327 c->secret_symmetric_key) != 0) {
307 return -1; 328 return -1;
329 }
308 330
309 new_nonce(packet + 1 + COOKIE_LENGTH); 331 new_nonce(packet + 1 + COOKIE_LENGTH);
310 int len = encrypt_data(peer_real_pk, c->self_secret_key, packet + 1 + COOKIE_LENGTH, plain, sizeof(plain), 332 int len = encrypt_data(peer_real_pk, c->self_secret_key, packet + 1 + COOKIE_LENGTH, plain, sizeof(plain),
311 packet + 1 + COOKIE_LENGTH + crypto_box_NONCEBYTES); 333 packet + 1 + COOKIE_LENGTH + crypto_box_NONCEBYTES);
312 334
313 if (len != HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES)) 335 if (len != HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES)) {
314 return -1; 336 return -1;
337 }
315 338
316 packet[0] = NET_PACKET_CRYPTO_HS; 339 packet[0] = NET_PACKET_CRYPTO_HS;
317 memcpy(packet + 1, cookie, COOKIE_LENGTH); 340 memcpy(packet + 1, cookie, COOKIE_LENGTH);
@@ -340,17 +363,21 @@ static int create_crypto_handshake(const Net_Crypto *c, uint8_t *packet, const u
340static int handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t *session_pk, uint8_t *peer_real_pk, 363static int handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t *session_pk, uint8_t *peer_real_pk,
341 uint8_t *dht_public_key, uint8_t *cookie, const uint8_t *packet, uint16_t length, const uint8_t *expected_real_pk) 364 uint8_t *dht_public_key, uint8_t *cookie, const uint8_t *packet, uint16_t length, const uint8_t *expected_real_pk)
342{ 365{
343 if (length != HANDSHAKE_PACKET_LENGTH) 366 if (length != HANDSHAKE_PACKET_LENGTH) {
344 return -1; 367 return -1;
368 }
345 369
346 uint8_t cookie_plain[COOKIE_DATA_LENGTH]; 370 uint8_t cookie_plain[COOKIE_DATA_LENGTH];
347 371
348 if (open_cookie(cookie_plain, packet + 1, c->secret_symmetric_key) != 0) 372 if (open_cookie(cookie_plain, packet + 1, c->secret_symmetric_key) != 0) {
349 return -1; 373 return -1;
374 }
350 375
351 if (expected_real_pk) 376 if (expected_real_pk) {
352 if (public_key_cmp(cookie_plain, expected_real_pk) != 0) 377 if (public_key_cmp(cookie_plain, expected_real_pk) != 0) {
353 return -1; 378 return -1;
379 }
380 }
354 381
355 uint8_t cookie_hash[crypto_hash_sha512_BYTES]; 382 uint8_t cookie_hash[crypto_hash_sha512_BYTES];
356 crypto_hash_sha512(cookie_hash, packet + 1, COOKIE_LENGTH); 383 crypto_hash_sha512(cookie_hash, packet + 1, COOKIE_LENGTH);
@@ -360,12 +387,14 @@ static int handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t
360 packet + 1 + COOKIE_LENGTH + crypto_box_NONCEBYTES, 387 packet + 1 + COOKIE_LENGTH + crypto_box_NONCEBYTES,
361 HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES), plain); 388 HANDSHAKE_PACKET_LENGTH - (1 + COOKIE_LENGTH + crypto_box_NONCEBYTES), plain);
362 389
363 if (len != sizeof(plain)) 390 if (len != sizeof(plain)) {
364 return -1; 391 return -1;
392 }
365 393
366 if (sodium_memcmp(cookie_hash, plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, 394 if (sodium_memcmp(cookie_hash, plain + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES,
367 crypto_hash_sha512_BYTES) != 0) 395 crypto_hash_sha512_BYTES) != 0) {
368 return -1; 396 return -1;
397 }
369 398
370 memcpy(nonce, plain, crypto_box_NONCEBYTES); 399 memcpy(nonce, plain, crypto_box_NONCEBYTES);
371 memcpy(session_pk, plain + crypto_box_NONCEBYTES, crypto_box_PUBLICKEYBYTES); 400 memcpy(session_pk, plain + crypto_box_NONCEBYTES, crypto_box_PUBLICKEYBYTES);
@@ -378,8 +407,9 @@ static int handle_crypto_handshake(const Net_Crypto *c, uint8_t *nonce, uint8_t
378 407
379static Crypto_Connection *get_crypto_connection(const Net_Crypto *c, int crypt_connection_id) 408static Crypto_Connection *get_crypto_connection(const Net_Crypto *c, int crypt_connection_id)
380{ 409{
381 if (crypt_connection_id_not_valid(c, crypt_connection_id)) 410 if (crypt_connection_id_not_valid(c, crypt_connection_id)) {
382 return 0; 411 return 0;
412 }
383 413
384 return &c->crypto_connections[crypt_connection_id]; 414 return &c->crypto_connections[crypt_connection_id];
385} 415}
@@ -394,13 +424,15 @@ static int add_ip_port_connection(Net_Crypto *c, int crypt_connection_id, IP_Por
394{ 424{
395 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 425 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
396 426
397 if (conn == 0) 427 if (conn == 0) {
398 return -1; 428 return -1;
429 }
399 430
400 if (ip_port.ip.family == AF_INET) { 431 if (ip_port.ip.family == AF_INET) {
401 if (!ipport_equal(&ip_port, &conn->ip_portv4) && LAN_ip(conn->ip_portv4.ip) != 0) { 432 if (!ipport_equal(&ip_port, &conn->ip_portv4) && LAN_ip(conn->ip_portv4.ip) != 0) {
402 if (!bs_list_add(&c->ip_port_list, (uint8_t *)&ip_port, crypt_connection_id)) 433 if (!bs_list_add(&c->ip_port_list, (uint8_t *)&ip_port, crypt_connection_id)) {
403 return -1; 434 return -1;
435 }
404 436
405 bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv4, crypt_connection_id); 437 bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv4, crypt_connection_id);
406 conn->ip_portv4 = ip_port; 438 conn->ip_portv4 = ip_port;
@@ -408,8 +440,9 @@ static int add_ip_port_connection(Net_Crypto *c, int crypt_connection_id, IP_Por
408 } 440 }
409 } else if (ip_port.ip.family == AF_INET6) { 441 } else if (ip_port.ip.family == AF_INET6) {
410 if (!ipport_equal(&ip_port, &conn->ip_portv6)) { 442 if (!ipport_equal(&ip_port, &conn->ip_portv6)) {
411 if (!bs_list_add(&c->ip_port_list, (uint8_t *)&ip_port, crypt_connection_id)) 443 if (!bs_list_add(&c->ip_port_list, (uint8_t *)&ip_port, crypt_connection_id)) {
412 return -1; 444 return -1;
445 }
413 446
414 bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv6, crypt_connection_id); 447 bs_list_remove(&c->ip_port_list, (uint8_t *)&conn->ip_portv6, crypt_connection_id);
415 conn->ip_portv6 = ip_port; 448 conn->ip_portv6 = ip_port;
@@ -432,8 +465,9 @@ IP_Port return_ip_port_connection(Net_Crypto *c, int crypt_connection_id)
432 465
433 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 466 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
434 467
435 if (conn == 0) 468 if (conn == 0) {
436 return empty; 469 return empty;
470 }
437 471
438 uint64_t current_time = unix_time(); 472 uint64_t current_time = unix_time();
439 _Bool v6 = 0, v4 = 0; 473 _Bool v6 = 0, v4 = 0;
@@ -467,8 +501,9 @@ static int send_packet_to(Net_Crypto *c, int crypt_connection_id, const uint8_t
467//TODO TCP, etc... 501//TODO TCP, etc...
468 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 502 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
469 503
470 if (conn == 0) 504 if (conn == 0) {
471 return -1; 505 return -1;
506 }
472 507
473 int direct_send_attempt = 0; 508 int direct_send_attempt = 0;
474 509
@@ -540,24 +575,28 @@ static uint32_t num_packets_array(const Packets_Array *array)
540 */ 575 */
541static int add_data_to_buffer(Packets_Array *array, uint32_t number, const Packet_Data *data) 576static int add_data_to_buffer(Packets_Array *array, uint32_t number, const Packet_Data *data)
542{ 577{
543 if (number - array->buffer_start > CRYPTO_PACKET_BUFFER_SIZE) 578 if (number - array->buffer_start > CRYPTO_PACKET_BUFFER_SIZE) {
544 return -1; 579 return -1;
580 }
545 581
546 uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE; 582 uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
547 583
548 if (array->buffer[num]) 584 if (array->buffer[num]) {
549 return -1; 585 return -1;
586 }
550 587
551 Packet_Data *new_d = malloc(sizeof(Packet_Data)); 588 Packet_Data *new_d = malloc(sizeof(Packet_Data));
552 589
553 if (new_d == NULL) 590 if (new_d == NULL) {
554 return -1; 591 return -1;
592 }
555 593
556 memcpy(new_d, data, sizeof(Packet_Data)); 594 memcpy(new_d, data, sizeof(Packet_Data));
557 array->buffer[num] = new_d; 595 array->buffer[num] = new_d;
558 596
559 if ((number - array->buffer_start) >= (array->buffer_end - array->buffer_start)) 597 if ((number - array->buffer_start) >= (array->buffer_end - array->buffer_start)) {
560 array->buffer_end = number + 1; 598 array->buffer_end = number + 1;
599 }
561 600
562 return 0; 601 return 0;
563} 602}
@@ -572,13 +611,15 @@ static int get_data_pointer(const Packets_Array *array, Packet_Data **data, uint
572{ 611{
573 uint32_t num_spots = array->buffer_end - array->buffer_start; 612 uint32_t num_spots = array->buffer_end - array->buffer_start;
574 613
575 if (array->buffer_end - number > num_spots || number - array->buffer_start >= num_spots) 614 if (array->buffer_end - number > num_spots || number - array->buffer_start >= num_spots) {
576 return -1; 615 return -1;
616 }
577 617
578 uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE; 618 uint32_t num = number % CRYPTO_PACKET_BUFFER_SIZE;
579 619
580 if (!array->buffer[num]) 620 if (!array->buffer[num]) {
581 return 0; 621 return 0;
622 }
582 623
583 *data = array->buffer[num]; 624 *data = array->buffer[num];
584 return 1; 625 return 1;
@@ -591,13 +632,15 @@ static int get_data_pointer(const Packets_Array *array, Packet_Data **data, uint
591 */ 632 */
592static int64_t add_data_end_of_buffer(Packets_Array *array, const Packet_Data *data) 633static int64_t add_data_end_of_buffer(Packets_Array *array, const Packet_Data *data)
593{ 634{
594 if (num_packets_array(array) >= CRYPTO_PACKET_BUFFER_SIZE) 635 if (num_packets_array(array) >= CRYPTO_PACKET_BUFFER_SIZE) {
595 return -1; 636 return -1;
637 }
596 638
597 Packet_Data *new_d = malloc(sizeof(Packet_Data)); 639 Packet_Data *new_d = malloc(sizeof(Packet_Data));
598 640
599 if (new_d == NULL) 641 if (new_d == NULL) {
600 return -1; 642 return -1;
643 }
601 644
602 memcpy(new_d, data, sizeof(Packet_Data)); 645 memcpy(new_d, data, sizeof(Packet_Data));
603 uint32_t id = array->buffer_end; 646 uint32_t id = array->buffer_end;
@@ -613,13 +656,15 @@ static int64_t add_data_end_of_buffer(Packets_Array *array, const Packet_Data *d
613 */ 656 */
614static int64_t read_data_beg_buffer(Packets_Array *array, Packet_Data *data) 657static int64_t read_data_beg_buffer(Packets_Array *array, Packet_Data *data)
615{ 658{
616 if (array->buffer_end == array->buffer_start) 659 if (array->buffer_end == array->buffer_start) {
617 return -1; 660 return -1;
661 }
618 662
619 uint32_t num = array->buffer_start % CRYPTO_PACKET_BUFFER_SIZE; 663 uint32_t num = array->buffer_start % CRYPTO_PACKET_BUFFER_SIZE;
620 664
621 if (!array->buffer[num]) 665 if (!array->buffer[num]) {
622 return -1; 666 return -1;
667 }
623 668
624 memcpy(data, array->buffer[num], sizeof(Packet_Data)); 669 memcpy(data, array->buffer[num], sizeof(Packet_Data));
625 uint32_t id = array->buffer_start; 670 uint32_t id = array->buffer_start;
@@ -638,8 +683,9 @@ static int clear_buffer_until(Packets_Array *array, uint32_t number)
638{ 683{
639 uint32_t num_spots = array->buffer_end - array->buffer_start; 684 uint32_t num_spots = array->buffer_end - array->buffer_start;
640 685
641 if (array->buffer_end - number >= num_spots || number - array->buffer_start > num_spots) 686 if (array->buffer_end - number >= num_spots || number - array->buffer_start > num_spots) {
642 return -1; 687 return -1;
688 }
643 689
644 uint32_t i; 690 uint32_t i;
645 691
@@ -680,11 +726,13 @@ static int clear_buffer(Packets_Array *array)
680 */ 726 */
681static int set_buffer_end(Packets_Array *array, uint32_t number) 727static int set_buffer_end(Packets_Array *array, uint32_t number)
682{ 728{
683 if ((number - array->buffer_start) > CRYPTO_PACKET_BUFFER_SIZE) 729 if ((number - array->buffer_start) > CRYPTO_PACKET_BUFFER_SIZE) {
684 return -1; 730 return -1;
731 }
685 732
686 if ((number - array->buffer_end) > CRYPTO_PACKET_BUFFER_SIZE) 733 if ((number - array->buffer_end) > CRYPTO_PACKET_BUFFER_SIZE) {
687 return -1; 734 return -1;
735 }
688 736
689 array->buffer_end = number; 737 array->buffer_end = number;
690 return 0; 738 return 0;
@@ -698,18 +746,21 @@ static int set_buffer_end(Packets_Array *array, uint32_t number)
698 */ 746 */
699static int generate_request_packet(uint8_t *data, uint16_t length, const Packets_Array *recv_array) 747static int generate_request_packet(uint8_t *data, uint16_t length, const Packets_Array *recv_array)
700{ 748{
701 if (length == 0) 749 if (length == 0) {
702 return -1; 750 return -1;
751 }
703 752
704 data[0] = PACKET_ID_REQUEST; 753 data[0] = PACKET_ID_REQUEST;
705 754
706 uint16_t cur_len = 1; 755 uint16_t cur_len = 1;
707 756
708 if (recv_array->buffer_start == recv_array->buffer_end) 757 if (recv_array->buffer_start == recv_array->buffer_end) {
709 return cur_len; 758 return cur_len;
759 }
710 760
711 if (length <= cur_len) 761 if (length <= cur_len) {
712 return cur_len; 762 return cur_len;
763 }
713 764
714 uint32_t i, n = 1; 765 uint32_t i, n = 1;
715 766
@@ -721,16 +772,18 @@ static int generate_request_packet(uint8_t *data, uint16_t length, const Packets
721 n = 0; 772 n = 0;
722 ++cur_len; 773 ++cur_len;
723 774
724 if (length <= cur_len) 775 if (length <= cur_len) {
725 return cur_len; 776 return cur_len;
777 }
726 778
727 } else if (n == 255) { 779 } else if (n == 255) {
728 data[cur_len] = 0; 780 data[cur_len] = 0;
729 n = 0; 781 n = 0;
730 ++cur_len; 782 ++cur_len;
731 783
732 if (length <= cur_len) 784 if (length <= cur_len) {
733 return cur_len; 785 return cur_len;
786 }
734 } 787 }
735 788
736 ++n; 789 ++n;
@@ -748,14 +801,17 @@ static int generate_request_packet(uint8_t *data, uint16_t length, const Packets
748static int handle_request_packet(Packets_Array *send_array, const uint8_t *data, uint16_t length, 801static int handle_request_packet(Packets_Array *send_array, const uint8_t *data, uint16_t length,
749 uint64_t *latest_send_time, uint64_t rtt_time) 802 uint64_t *latest_send_time, uint64_t rtt_time)
750{ 803{
751 if (length < 1) 804 if (length < 1) {
752 return -1; 805 return -1;
806 }
753 807
754 if (data[0] != PACKET_ID_REQUEST) 808 if (data[0] != PACKET_ID_REQUEST) {
755 return -1; 809 return -1;
810 }
756 811
757 if (length == 1) 812 if (length == 1) {
758 return 0; 813 return 0;
814 }
759 815
760 ++data; 816 ++data;
761 --length; 817 --length;
@@ -767,8 +823,9 @@ static int handle_request_packet(Packets_Array *send_array, const uint8_t *data,
767 uint64_t l_sent_time = ~0; 823 uint64_t l_sent_time = ~0;
768 824
769 for (i = send_array->buffer_start; i != send_array->buffer_end; ++i) { 825 for (i = send_array->buffer_start; i != send_array->buffer_end; ++i) {
770 if (length == 0) 826 if (length == 0) {
771 break; 827 break;
828 }
772 829
773 uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE; 830 uint32_t num = i % CRYPTO_PACKET_BUFFER_SIZE;
774 831
@@ -789,8 +846,9 @@ static int handle_request_packet(Packets_Array *send_array, const uint8_t *data,
789 if (send_array->buffer[num]) { 846 if (send_array->buffer[num]) {
790 uint64_t sent_time = send_array->buffer[num]->sent_time; 847 uint64_t sent_time = send_array->buffer[num]->sent_time;
791 848
792 if (l_sent_time < sent_time) 849 if (l_sent_time < sent_time) {
793 l_sent_time = sent_time; 850 l_sent_time = sent_time;
851 }
794 852
795 free(send_array->buffer[num]); 853 free(send_array->buffer[num]);
796 send_array->buffer[num] = NULL; 854 send_array->buffer[num] = NULL;
@@ -800,8 +858,9 @@ static int handle_request_packet(Packets_Array *send_array, const uint8_t *data,
800 if (n == 255) { 858 if (n == 255) {
801 n = 1; 859 n = 1;
802 860
803 if (data[0] != 0) 861 if (data[0] != 0) {
804 return -1; 862 return -1;
863 }
805 864
806 ++data; 865 ++data;
807 --length; 866 --length;
@@ -810,8 +869,9 @@ static int handle_request_packet(Packets_Array *send_array, const uint8_t *data,
810 } 869 }
811 } 870 }
812 871
813 if (*latest_send_time < l_sent_time) 872 if (*latest_send_time < l_sent_time) {
814 *latest_send_time = l_sent_time; 873 *latest_send_time = l_sent_time;
874 }
815 875
816 return requested; 876 return requested;
817} 877}
@@ -827,13 +887,15 @@ static int handle_request_packet(Packets_Array *send_array, const uint8_t *data,
827 */ 887 */
828static int send_data_packet(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length) 888static int send_data_packet(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length)
829{ 889{
830 if (length == 0 || length + (1 + sizeof(uint16_t) + crypto_box_MACBYTES) > MAX_CRYPTO_PACKET_SIZE) 890 if (length == 0 || length + (1 + sizeof(uint16_t) + crypto_box_MACBYTES) > MAX_CRYPTO_PACKET_SIZE) {
831 return -1; 891 return -1;
892 }
832 893
833 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 894 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
834 895
835 if (conn == 0) 896 if (conn == 0) {
836 return -1; 897 return -1;
898 }
837 899
838 pthread_mutex_lock(&conn->mutex); 900 pthread_mutex_lock(&conn->mutex);
839 uint8_t packet[1 + sizeof(uint16_t) + length + crypto_box_MACBYTES]; 901 uint8_t packet[1 + sizeof(uint16_t) + length + crypto_box_MACBYTES];
@@ -860,8 +922,9 @@ static int send_data_packet(Net_Crypto *c, int crypt_connection_id, const uint8_
860static int send_data_packet_helper(Net_Crypto *c, int crypt_connection_id, uint32_t buffer_start, uint32_t num, 922static int send_data_packet_helper(Net_Crypto *c, int crypt_connection_id, uint32_t buffer_start, uint32_t num,
861 const uint8_t *data, uint16_t length) 923 const uint8_t *data, uint16_t length)
862{ 924{
863 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) 925 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
864 return -1; 926 return -1;
927 }
865 928
866 num = htonl(num); 929 num = htonl(num);
867 buffer_start = htonl(buffer_start); 930 buffer_start = htonl(buffer_start);
@@ -879,8 +942,9 @@ static int reset_max_speed_reached(Net_Crypto *c, int crypt_connection_id)
879{ 942{
880 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 943 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
881 944
882 if (conn == 0) 945 if (conn == 0) {
883 return -1; 946 return -1;
947 }
884 948
885 /* If last packet send failed, try to send packet again. 949 /* If last packet send failed, try to send packet again.
886 If sending it fails we won't be able to send the new packet. */ 950 If sending it fails we won't be able to send the new packet. */
@@ -918,13 +982,15 @@ static int reset_max_speed_reached(Net_Crypto *c, int crypt_connection_id)
918static int64_t send_lossless_packet(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length, 982static int64_t send_lossless_packet(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length,
919 uint8_t congestion_control) 983 uint8_t congestion_control)
920{ 984{
921 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) 985 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
922 return -1; 986 return -1;
987 }
923 988
924 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 989 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
925 990
926 if (conn == 0) 991 if (conn == 0) {
927 return -1; 992 return -1;
993 }
928 994
929 /* If last packet send failed, try to send packet again. 995 /* If last packet send failed, try to send packet again.
930 If sending it fails we won't be able to send the new packet. */ 996 If sending it fails we won't be able to send the new packet. */
@@ -942,8 +1008,9 @@ static int64_t send_lossless_packet(Net_Crypto *c, int crypt_connection_id, cons
942 int64_t packet_num = add_data_end_of_buffer(&conn->send_array, &dt); 1008 int64_t packet_num = add_data_end_of_buffer(&conn->send_array, &dt);
943 pthread_mutex_unlock(&conn->mutex); 1009 pthread_mutex_unlock(&conn->mutex);
944 1010
945 if (packet_num == -1) 1011 if (packet_num == -1) {
946 return -1; 1012 return -1;
1013 }
947 1014
948 if (!congestion_control && conn->maximum_speed_reached) { 1015 if (!congestion_control && conn->maximum_speed_reached) {
949 return packet_num; 1016 return packet_num;
@@ -952,8 +1019,9 @@ static int64_t send_lossless_packet(Net_Crypto *c, int crypt_connection_id, cons
952 if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num, data, length) == 0) { 1019 if (send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, packet_num, data, length) == 0) {
953 Packet_Data *dt1 = NULL; 1020 Packet_Data *dt1 = NULL;
954 1021
955 if (get_data_pointer(&conn->send_array, &dt1, packet_num) == 1) 1022 if (get_data_pointer(&conn->send_array, &dt1, packet_num) == 1) {
956 dt1->sent_time = current_time_monotonic(); 1023 dt1->sent_time = current_time_monotonic();
1024 }
957 } else { 1025 } else {
958 conn->maximum_speed_reached = 1; 1026 conn->maximum_speed_reached = 1;
959 LOGGER_ERROR(c->log, "send_data_packet failed\n"); 1027 LOGGER_ERROR(c->log, "send_data_packet failed\n");
@@ -984,13 +1052,15 @@ static uint16_t get_nonce_uint16(const uint8_t *nonce)
984static int handle_data_packet(const Net_Crypto *c, int crypt_connection_id, uint8_t *data, const uint8_t *packet, 1052static int handle_data_packet(const Net_Crypto *c, int crypt_connection_id, uint8_t *data, const uint8_t *packet,
985 uint16_t length) 1053 uint16_t length)
986{ 1054{
987 if (length <= (1 + sizeof(uint16_t) + crypto_box_MACBYTES) || length > MAX_CRYPTO_PACKET_SIZE) 1055 if (length <= (1 + sizeof(uint16_t) + crypto_box_MACBYTES) || length > MAX_CRYPTO_PACKET_SIZE) {
988 return -1; 1056 return -1;
1057 }
989 1058
990 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1059 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
991 1060
992 if (conn == 0) 1061 if (conn == 0) {
993 return -1; 1062 return -1;
1063 }
994 1064
995 uint8_t nonce[crypto_box_NONCEBYTES]; 1065 uint8_t nonce[crypto_box_NONCEBYTES];
996 memcpy(nonce, conn->recv_nonce, crypto_box_NONCEBYTES); 1066 memcpy(nonce, conn->recv_nonce, crypto_box_NONCEBYTES);
@@ -1003,8 +1073,9 @@ static int handle_data_packet(const Net_Crypto *c, int crypt_connection_id, uint
1003 int len = decrypt_data_symmetric(conn->shared_key, nonce, packet + 1 + sizeof(uint16_t), 1073 int len = decrypt_data_symmetric(conn->shared_key, nonce, packet + 1 + sizeof(uint16_t),
1004 length - (1 + sizeof(uint16_t)), data); 1074 length - (1 + sizeof(uint16_t)), data);
1005 1075
1006 if ((unsigned int)len != length - (1 + sizeof(uint16_t) + crypto_box_MACBYTES)) 1076 if ((unsigned int)len != length - (1 + sizeof(uint16_t) + crypto_box_MACBYTES)) {
1007 return -1; 1077 return -1;
1078 }
1008 1079
1009 if (diff > DATA_NUM_THRESHOLD * 2) { 1080 if (diff > DATA_NUM_THRESHOLD * 2) {
1010 increment_nonce_number(conn->recv_nonce, DATA_NUM_THRESHOLD); 1081 increment_nonce_number(conn->recv_nonce, DATA_NUM_THRESHOLD);
@@ -1022,14 +1093,16 @@ static int send_request_packet(Net_Crypto *c, int crypt_connection_id)
1022{ 1093{
1023 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1094 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1024 1095
1025 if (conn == 0) 1096 if (conn == 0) {
1026 return -1; 1097 return -1;
1098 }
1027 1099
1028 uint8_t data[MAX_CRYPTO_DATA_SIZE]; 1100 uint8_t data[MAX_CRYPTO_DATA_SIZE];
1029 int len = generate_request_packet(data, sizeof(data), &conn->recv_array); 1101 int len = generate_request_packet(data, sizeof(data), &conn->recv_array);
1030 1102
1031 if (len == -1) 1103 if (len == -1) {
1032 return -1; 1104 return -1;
1105 }
1033 1106
1034 return send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, conn->send_array.buffer_end, data, 1107 return send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, conn->send_array.buffer_end, data,
1035 len); 1108 len);
@@ -1042,13 +1115,15 @@ static int send_request_packet(Net_Crypto *c, int crypt_connection_id)
1042 */ 1115 */
1043static int send_requested_packets(Net_Crypto *c, int crypt_connection_id, uint32_t max_num) 1116static int send_requested_packets(Net_Crypto *c, int crypt_connection_id, uint32_t max_num)
1044{ 1117{
1045 if (max_num == 0) 1118 if (max_num == 0) {
1046 return -1; 1119 return -1;
1120 }
1047 1121
1048 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1122 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1049 1123
1050 if (conn == 0) 1124 if (conn == 0) {
1051 return -1; 1125 return -1;
1126 }
1052 1127
1053 uint64_t temp_time = current_time_monotonic(); 1128 uint64_t temp_time = current_time_monotonic();
1054 uint32_t i, num_sent = 0, array_size = num_packets_array(&conn->send_array); 1129 uint32_t i, num_sent = 0, array_size = num_packets_array(&conn->send_array);
@@ -1074,8 +1149,9 @@ static int send_requested_packets(Net_Crypto *c, int crypt_connection_id, uint32
1074 ++num_sent; 1149 ++num_sent;
1075 } 1150 }
1076 1151
1077 if (num_sent >= max_num) 1152 if (num_sent >= max_num) {
1078 break; 1153 break;
1154 }
1079 } 1155 }
1080 1156
1081 return num_sent; 1157 return num_sent;
@@ -1089,21 +1165,25 @@ static int send_requested_packets(Net_Crypto *c, int crypt_connection_id, uint32
1089 */ 1165 */
1090static int new_temp_packet(const Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length) 1166static int new_temp_packet(const Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length)
1091{ 1167{
1092 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) 1168 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
1093 return -1; 1169 return -1;
1170 }
1094 1171
1095 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1172 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1096 1173
1097 if (conn == 0) 1174 if (conn == 0) {
1098 return -1; 1175 return -1;
1176 }
1099 1177
1100 uint8_t *temp_packet = malloc(length); 1178 uint8_t *temp_packet = malloc(length);
1101 1179
1102 if (temp_packet == 0) 1180 if (temp_packet == 0) {
1103 return -1; 1181 return -1;
1182 }
1104 1183
1105 if (conn->temp_packet) 1184 if (conn->temp_packet) {
1106 free(conn->temp_packet); 1185 free(conn->temp_packet);
1186 }
1107 1187
1108 memcpy(temp_packet, packet, length); 1188 memcpy(temp_packet, packet, length);
1109 conn->temp_packet = temp_packet; 1189 conn->temp_packet = temp_packet;
@@ -1122,11 +1202,13 @@ static int clear_temp_packet(const Net_Crypto *c, int crypt_connection_id)
1122{ 1202{
1123 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1203 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1124 1204
1125 if (conn == 0) 1205 if (conn == 0) {
1126 return -1; 1206 return -1;
1207 }
1127 1208
1128 if (conn->temp_packet) 1209 if (conn->temp_packet) {
1129 free(conn->temp_packet); 1210 free(conn->temp_packet);
1211 }
1130 1212
1131 conn->temp_packet = 0; 1213 conn->temp_packet = 0;
1132 conn->temp_packet_length = 0; 1214 conn->temp_packet_length = 0;
@@ -1145,14 +1227,17 @@ static int send_temp_packet(Net_Crypto *c, int crypt_connection_id)
1145{ 1227{
1146 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1228 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1147 1229
1148 if (conn == 0) 1230 if (conn == 0) {
1149 return -1; 1231 return -1;
1232 }
1150 1233
1151 if (!conn->temp_packet) 1234 if (!conn->temp_packet) {
1152 return -1; 1235 return -1;
1236 }
1153 1237
1154 if (send_packet_to(c, crypt_connection_id, conn->temp_packet, conn->temp_packet_length) != 0) 1238 if (send_packet_to(c, crypt_connection_id, conn->temp_packet, conn->temp_packet_length) != 0) {
1155 return -1; 1239 return -1;
1240 }
1156 1241
1157 conn->temp_packet_sent_time = current_time_monotonic(); 1242 conn->temp_packet_sent_time = current_time_monotonic();
1158 ++conn->temp_packet_num_sent; 1243 ++conn->temp_packet_num_sent;
@@ -1170,17 +1255,20 @@ static int create_send_handshake(Net_Crypto *c, int crypt_connection_id, const u
1170{ 1255{
1171 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1256 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1172 1257
1173 if (conn == 0) 1258 if (conn == 0) {
1174 return -1; 1259 return -1;
1260 }
1175 1261
1176 uint8_t handshake_packet[HANDSHAKE_PACKET_LENGTH]; 1262 uint8_t handshake_packet[HANDSHAKE_PACKET_LENGTH];
1177 1263
1178 if (create_crypto_handshake(c, handshake_packet, cookie, conn->sent_nonce, conn->sessionpublic_key, 1264 if (create_crypto_handshake(c, handshake_packet, cookie, conn->sent_nonce, conn->sessionpublic_key,
1179 conn->public_key, dht_public_key) != sizeof(handshake_packet)) 1265 conn->public_key, dht_public_key) != sizeof(handshake_packet)) {
1180 return -1; 1266 return -1;
1267 }
1181 1268
1182 if (new_temp_packet(c, crypt_connection_id, handshake_packet, sizeof(handshake_packet)) != 0) 1269 if (new_temp_packet(c, crypt_connection_id, handshake_packet, sizeof(handshake_packet)) != 0) {
1183 return -1; 1270 return -1;
1271 }
1184 1272
1185 send_temp_packet(c, crypt_connection_id); 1273 send_temp_packet(c, crypt_connection_id);
1186 return 0; 1274 return 0;
@@ -1195,8 +1283,9 @@ static int send_kill_packet(Net_Crypto *c, int crypt_connection_id)
1195{ 1283{
1196 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1284 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1197 1285
1198 if (conn == 0) 1286 if (conn == 0) {
1199 return -1; 1287 return -1;
1288 }
1200 1289
1201 uint8_t kill_packet = PACKET_ID_KILL; 1290 uint8_t kill_packet = PACKET_ID_KILL;
1202 return send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, conn->send_array.buffer_end, 1291 return send_data_packet_helper(c, crypt_connection_id, conn->recv_array.buffer_start, conn->send_array.buffer_end,
@@ -1207,8 +1296,9 @@ static void connection_kill(Net_Crypto *c, int crypt_connection_id)
1207{ 1296{
1208 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1297 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1209 1298
1210 if (conn == 0) 1299 if (conn == 0) {
1211 return; 1300 return;
1301 }
1212 1302
1213 if (conn->connection_status_callback) { 1303 if (conn->connection_status_callback) {
1214 conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 0); 1304 conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 0);
@@ -1225,19 +1315,22 @@ static void connection_kill(Net_Crypto *c, int crypt_connection_id)
1225static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length, 1315static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length,
1226 _Bool udp, void *userdata) 1316 _Bool udp, void *userdata)
1227{ 1317{
1228 if (length > MAX_CRYPTO_PACKET_SIZE || length <= CRYPTO_DATA_PACKET_MIN_SIZE) 1318 if (length > MAX_CRYPTO_PACKET_SIZE || length <= CRYPTO_DATA_PACKET_MIN_SIZE) {
1229 return -1; 1319 return -1;
1320 }
1230 1321
1231 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1322 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1232 1323
1233 if (conn == 0) 1324 if (conn == 0) {
1234 return -1; 1325 return -1;
1326 }
1235 1327
1236 uint8_t data[MAX_DATA_DATA_PACKET_SIZE]; 1328 uint8_t data[MAX_DATA_DATA_PACKET_SIZE];
1237 int len = handle_data_packet(c, crypt_connection_id, data, packet, length); 1329 int len = handle_data_packet(c, crypt_connection_id, data, packet, length);
1238 1330
1239 if (len <= (int)(sizeof(uint32_t) * 2)) 1331 if (len <= (int)(sizeof(uint32_t) * 2)) {
1240 return -1; 1332 return -1;
1333 }
1241 1334
1242 uint32_t buffer_start, num; 1335 uint32_t buffer_start, num;
1243 memcpy(&buffer_start, data, sizeof(uint32_t)); 1336 memcpy(&buffer_start, data, sizeof(uint32_t));
@@ -1266,8 +1359,9 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1266 ++real_data; 1359 ++real_data;
1267 --real_length; 1360 --real_length;
1268 1361
1269 if (real_length == 0) 1362 if (real_length == 0) {
1270 return -1; 1363 return -1;
1364 }
1271 } 1365 }
1272 1366
1273 if (real_data[0] == PACKET_ID_KILL) { 1367 if (real_data[0] == PACKET_ID_KILL) {
@@ -1279,8 +1373,9 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1279 clear_temp_packet(c, crypt_connection_id); 1373 clear_temp_packet(c, crypt_connection_id);
1280 conn->status = CRYPTO_CONN_ESTABLISHED; 1374 conn->status = CRYPTO_CONN_ESTABLISHED;
1281 1375
1282 if (conn->connection_status_callback) 1376 if (conn->connection_status_callback) {
1283 conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 1); 1377 conn->connection_status_callback(conn->connection_status_callback_object, conn->connection_status_callback_id, 1);
1378 }
1284 } 1379 }
1285 1380
1286 if (real_data[0] == PACKET_ID_REQUEST) { 1381 if (real_data[0] == PACKET_ID_REQUEST) {
@@ -1306,8 +1401,9 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1306 dt.length = real_length; 1401 dt.length = real_length;
1307 memcpy(dt.data, real_data, real_length); 1402 memcpy(dt.data, real_data, real_length);
1308 1403
1309 if (add_data_to_buffer(&conn->recv_array, num, &dt) != 0) 1404 if (add_data_to_buffer(&conn->recv_array, num, &dt) != 0) {
1310 return -1; 1405 return -1;
1406 }
1311 1407
1312 1408
1313 while (1) { 1409 while (1) {
@@ -1315,18 +1411,21 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1315 int ret = read_data_beg_buffer(&conn->recv_array, &dt); 1411 int ret = read_data_beg_buffer(&conn->recv_array, &dt);
1316 pthread_mutex_unlock(&conn->mutex); 1412 pthread_mutex_unlock(&conn->mutex);
1317 1413
1318 if (ret == -1) 1414 if (ret == -1) {
1319 break; 1415 break;
1416 }
1320 1417
1321 if (conn->connection_data_callback) 1418 if (conn->connection_data_callback) {
1322 conn->connection_data_callback(conn->connection_data_callback_object, conn->connection_data_callback_id, dt.data, 1419 conn->connection_data_callback(conn->connection_data_callback_object, conn->connection_data_callback_id, dt.data,
1323 dt.length, userdata); 1420 dt.length, userdata);
1421 }
1324 1422
1325 /* conn might get killed in callback. */ 1423 /* conn might get killed in callback. */
1326 conn = get_crypto_connection(c, crypt_connection_id); 1424 conn = get_crypto_connection(c, crypt_connection_id);
1327 1425
1328 if (conn == 0) 1426 if (conn == 0) {
1329 return -1; 1427 return -1;
1428 }
1330 } 1429 }
1331 1430
1332 /* Packet counter. */ 1431 /* Packet counter. */
@@ -1336,9 +1435,10 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1336 1435
1337 set_buffer_end(&conn->recv_array, num); 1436 set_buffer_end(&conn->recv_array, num);
1338 1437
1339 if (conn->connection_lossy_data_callback) 1438 if (conn->connection_lossy_data_callback) {
1340 conn->connection_lossy_data_callback(conn->connection_lossy_data_callback_object, 1439 conn->connection_lossy_data_callback(conn->connection_lossy_data_callback_object,
1341 conn->connection_lossy_data_callback_id, real_data, real_length); 1440 conn->connection_lossy_data_callback_id, real_data, real_length);
1441 }
1342 1442
1343 } else { 1443 } else {
1344 return -1; 1444 return -1;
@@ -1347,8 +1447,9 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1347 if (rtt_calc_time != 0) { 1447 if (rtt_calc_time != 0) {
1348 uint64_t rtt_time = current_time_monotonic() - rtt_calc_time; 1448 uint64_t rtt_time = current_time_monotonic() - rtt_calc_time;
1349 1449
1350 if (rtt_time < conn->rtt_time) 1450 if (rtt_time < conn->rtt_time) {
1351 conn->rtt_time = rtt_time; 1451 conn->rtt_time = rtt_time;
1452 }
1352 } 1453 }
1353 1454
1354 return 0; 1455 return 0;
@@ -1362,30 +1463,36 @@ static int handle_data_packet_helper(Net_Crypto *c, int crypt_connection_id, con
1362static int handle_packet_connection(Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length, 1463static int handle_packet_connection(Net_Crypto *c, int crypt_connection_id, const uint8_t *packet, uint16_t length,
1363 _Bool udp, void *userdata) 1464 _Bool udp, void *userdata)
1364{ 1465{
1365 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) 1466 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
1366 return -1; 1467 return -1;
1468 }
1367 1469
1368 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1470 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1369 1471
1370 if (conn == 0) 1472 if (conn == 0) {
1371 return -1; 1473 return -1;
1474 }
1372 1475
1373 switch (packet[0]) { 1476 switch (packet[0]) {
1374 case NET_PACKET_COOKIE_RESPONSE: { 1477 case NET_PACKET_COOKIE_RESPONSE: {
1375 if (conn->status != CRYPTO_CONN_COOKIE_REQUESTING) 1478 if (conn->status != CRYPTO_CONN_COOKIE_REQUESTING) {
1376 return -1; 1479 return -1;
1480 }
1377 1481
1378 uint8_t cookie[COOKIE_LENGTH]; 1482 uint8_t cookie[COOKIE_LENGTH];
1379 uint64_t number; 1483 uint64_t number;
1380 1484
1381 if (handle_cookie_response(cookie, &number, packet, length, conn->shared_key) != sizeof(cookie)) 1485 if (handle_cookie_response(cookie, &number, packet, length, conn->shared_key) != sizeof(cookie)) {
1382 return -1; 1486 return -1;
1487 }
1383 1488
1384 if (number != conn->cookie_request_number) 1489 if (number != conn->cookie_request_number) {
1385 return -1; 1490 return -1;
1491 }
1386 1492
1387 if (create_send_handshake(c, crypt_connection_id, cookie, conn->dht_public_key) != 0) 1493 if (create_send_handshake(c, crypt_connection_id, cookie, conn->dht_public_key) != 0) {
1388 return -1; 1494 return -1;
1495 }
1389 1496
1390 conn->status = CRYPTO_CONN_HANDSHAKE_SENT; 1497 conn->status = CRYPTO_CONN_HANDSHAKE_SENT;
1391 return 0; 1498 return 0;
@@ -1399,21 +1506,24 @@ static int handle_packet_connection(Net_Crypto *c, int crypt_connection_id, cons
1399 uint8_t cookie[COOKIE_LENGTH]; 1506 uint8_t cookie[COOKIE_LENGTH];
1400 1507
1401 if (handle_crypto_handshake(c, conn->recv_nonce, conn->peersessionpublic_key, peer_real_pk, dht_public_key, cookie, 1508 if (handle_crypto_handshake(c, conn->recv_nonce, conn->peersessionpublic_key, peer_real_pk, dht_public_key, cookie,
1402 packet, length, conn->public_key) != 0) 1509 packet, length, conn->public_key) != 0) {
1403 return -1; 1510 return -1;
1511 }
1404 1512
1405 if (public_key_cmp(dht_public_key, conn->dht_public_key) == 0) { 1513 if (public_key_cmp(dht_public_key, conn->dht_public_key) == 0) {
1406 encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key); 1514 encrypt_precompute(conn->peersessionpublic_key, conn->sessionsecret_key, conn->shared_key);
1407 1515
1408 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING) { 1516 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING) {
1409 if (create_send_handshake(c, crypt_connection_id, cookie, dht_public_key) != 0) 1517 if (create_send_handshake(c, crypt_connection_id, cookie, dht_public_key) != 0) {
1410 return -1; 1518 return -1;
1519 }
1411 } 1520 }
1412 1521
1413 conn->status = CRYPTO_CONN_NOT_CONFIRMED; 1522 conn->status = CRYPTO_CONN_NOT_CONFIRMED;
1414 } else { 1523 } else {
1415 if (conn->dht_pk_callback) 1524 if (conn->dht_pk_callback) {
1416 conn->dht_pk_callback(conn->dht_pk_callback_object, conn->dht_pk_callback_number, dht_public_key); 1525 conn->dht_pk_callback(conn->dht_pk_callback_object, conn->dht_pk_callback_number, dht_public_key);
1526 }
1417 } 1527 }
1418 1528
1419 } else { 1529 } else {
@@ -1456,8 +1566,9 @@ static int realloc_cryptoconnection(Net_Crypto *c, uint32_t num)
1456 1566
1457 Crypto_Connection *newcrypto_connections = realloc(c->crypto_connections, num * sizeof(Crypto_Connection)); 1567 Crypto_Connection *newcrypto_connections = realloc(c->crypto_connections, num * sizeof(Crypto_Connection));
1458 1568
1459 if (newcrypto_connections == NULL) 1569 if (newcrypto_connections == NULL) {
1460 return -1; 1570 return -1;
1571 }
1461 1572
1462 c->crypto_connections = newcrypto_connections; 1573 c->crypto_connections = newcrypto_connections;
1463 return 0; 1574 return 0;
@@ -1474,8 +1585,9 @@ static int create_crypto_connection(Net_Crypto *c)
1474 uint32_t i; 1585 uint32_t i;
1475 1586
1476 for (i = 0; i < c->crypto_connections_length; ++i) { 1587 for (i = 0; i < c->crypto_connections_length; ++i) {
1477 if (c->crypto_connections[i].status == CRYPTO_CONN_NO_CONNECTION) 1588 if (c->crypto_connections[i].status == CRYPTO_CONN_NO_CONNECTION) {
1478 return i; 1589 return i;
1590 }
1479 } 1591 }
1480 1592
1481 while (1) { /* TODO: is this really the best way to do this? */ 1593 while (1) { /* TODO: is this really the best way to do this? */
@@ -1512,8 +1624,9 @@ static int create_crypto_connection(Net_Crypto *c)
1512 */ 1624 */
1513static int wipe_crypto_connection(Net_Crypto *c, int crypt_connection_id) 1625static int wipe_crypto_connection(Net_Crypto *c, int crypt_connection_id)
1514{ 1626{
1515 if (crypt_connection_id_not_valid(c, crypt_connection_id)) 1627 if (crypt_connection_id_not_valid(c, crypt_connection_id)) {
1516 return -1; 1628 return -1;
1629 }
1517 1630
1518 uint32_t i; 1631 uint32_t i;
1519 1632
@@ -1548,9 +1661,11 @@ static int getcryptconnection_id(const Net_Crypto *c, const uint8_t *public_key)
1548 uint32_t i; 1661 uint32_t i;
1549 1662
1550 for (i = 0; i < c->crypto_connections_length; ++i) { 1663 for (i = 0; i < c->crypto_connections_length; ++i) {
1551 if (c->crypto_connections[i].status != CRYPTO_CONN_NO_CONNECTION) 1664 if (c->crypto_connections[i].status != CRYPTO_CONN_NO_CONNECTION) {
1552 if (public_key_cmp(public_key, c->crypto_connections[i].public_key) == 0) 1665 if (public_key_cmp(public_key, c->crypto_connections[i].public_key) == 0) {
1553 return i; 1666 return i;
1667 }
1668 }
1554 } 1669 }
1555 1670
1556 return -1; 1671 return -1;
@@ -1567,12 +1682,14 @@ static int crypto_connection_add_source(Net_Crypto *c, int crypt_connection_id,
1567{ 1682{
1568 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1683 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1569 1684
1570 if (conn == 0) 1685 if (conn == 0) {
1571 return -1; 1686 return -1;
1687 }
1572 1688
1573 if (source.ip.family == AF_INET || source.ip.family == AF_INET6) { 1689 if (source.ip.family == AF_INET || source.ip.family == AF_INET6) {
1574 if (add_ip_port_connection(c, crypt_connection_id, source) != 0) 1690 if (add_ip_port_connection(c, crypt_connection_id, source) != 0) {
1575 return -1; 1691 return -1;
1692 }
1576 1693
1577 if (source.ip.family == AF_INET) { 1694 if (source.ip.family == AF_INET) {
1578 conn->direct_lastrecv_timev4 = unix_time(); 1695 conn->direct_lastrecv_timev4 = unix_time();
@@ -1582,8 +1699,9 @@ static int crypto_connection_add_source(Net_Crypto *c, int crypt_connection_id,
1582 1699
1583 return 0; 1700 return 0;
1584 } else if (source.ip.family == TCP_FAMILY) { 1701 } else if (source.ip.family == TCP_FAMILY) {
1585 if (add_tcp_number_relay_connection(c->tcp_c, conn->connection_number_tcp, source.ip.ip6.uint32[0]) == 0) 1702 if (add_tcp_number_relay_connection(c->tcp_c, conn->connection_number_tcp, source.ip.ip6.uint32[0]) == 0) {
1586 return 1; 1703 return 1;
1704 }
1587 } 1705 }
1588 1706
1589 return -1; 1707 return -1;
@@ -1614,8 +1732,9 @@ static int handle_new_connection_handshake(Net_Crypto *c, IP_Port source, const
1614 New_Connection n_c; 1732 New_Connection n_c;
1615 n_c.cookie = malloc(COOKIE_LENGTH); 1733 n_c.cookie = malloc(COOKIE_LENGTH);
1616 1734
1617 if (n_c.cookie == NULL) 1735 if (n_c.cookie == NULL) {
1618 return -1; 1736 return -1;
1737 }
1619 1738
1620 n_c.source = source; 1739 n_c.source = source;
1621 n_c.cookie_length = COOKIE_LENGTH; 1740 n_c.cookie_length = COOKIE_LENGTH;
@@ -1666,25 +1785,29 @@ static int handle_new_connection_handshake(Net_Crypto *c, IP_Port source, const
1666 */ 1785 */
1667int accept_crypto_connection(Net_Crypto *c, New_Connection *n_c) 1786int accept_crypto_connection(Net_Crypto *c, New_Connection *n_c)
1668{ 1787{
1669 if (getcryptconnection_id(c, n_c->public_key) != -1) 1788 if (getcryptconnection_id(c, n_c->public_key) != -1) {
1670 return -1; 1789 return -1;
1790 }
1671 1791
1672 int crypt_connection_id = create_crypto_connection(c); 1792 int crypt_connection_id = create_crypto_connection(c);
1673 1793
1674 if (crypt_connection_id == -1) 1794 if (crypt_connection_id == -1) {
1675 return -1; 1795 return -1;
1796 }
1676 1797
1677 Crypto_Connection *conn = &c->crypto_connections[crypt_connection_id]; 1798 Crypto_Connection *conn = &c->crypto_connections[crypt_connection_id];
1678 1799
1679 if (n_c->cookie_length != COOKIE_LENGTH) 1800 if (n_c->cookie_length != COOKIE_LENGTH) {
1680 return -1; 1801 return -1;
1802 }
1681 1803
1682 pthread_mutex_lock(&c->tcp_mutex); 1804 pthread_mutex_lock(&c->tcp_mutex);
1683 int connection_number_tcp = new_tcp_connection_to(c->tcp_c, n_c->dht_public_key, crypt_connection_id); 1805 int connection_number_tcp = new_tcp_connection_to(c->tcp_c, n_c->dht_public_key, crypt_connection_id);
1684 pthread_mutex_unlock(&c->tcp_mutex); 1806 pthread_mutex_unlock(&c->tcp_mutex);
1685 1807
1686 if (connection_number_tcp == -1) 1808 if (connection_number_tcp == -1) {
1687 return -1; 1809 return -1;
1810 }
1688 1811
1689 conn->connection_number_tcp = connection_number_tcp; 1812 conn->connection_number_tcp = connection_number_tcp;
1690 memcpy(conn->public_key, n_c->public_key, crypto_box_PUBLICKEYBYTES); 1813 memcpy(conn->public_key, n_c->public_key, crypto_box_PUBLICKEYBYTES);
@@ -1722,25 +1845,29 @@ int new_crypto_connection(Net_Crypto *c, const uint8_t *real_public_key, const u
1722{ 1845{
1723 int crypt_connection_id = getcryptconnection_id(c, real_public_key); 1846 int crypt_connection_id = getcryptconnection_id(c, real_public_key);
1724 1847
1725 if (crypt_connection_id != -1) 1848 if (crypt_connection_id != -1) {
1726 return crypt_connection_id; 1849 return crypt_connection_id;
1850 }
1727 1851
1728 crypt_connection_id = create_crypto_connection(c); 1852 crypt_connection_id = create_crypto_connection(c);
1729 1853
1730 if (crypt_connection_id == -1) 1854 if (crypt_connection_id == -1) {
1731 return -1; 1855 return -1;
1856 }
1732 1857
1733 Crypto_Connection *conn = &c->crypto_connections[crypt_connection_id]; 1858 Crypto_Connection *conn = &c->crypto_connections[crypt_connection_id];
1734 1859
1735 if (conn == 0) 1860 if (conn == 0) {
1736 return -1; 1861 return -1;
1862 }
1737 1863
1738 pthread_mutex_lock(&c->tcp_mutex); 1864 pthread_mutex_lock(&c->tcp_mutex);
1739 int connection_number_tcp = new_tcp_connection_to(c->tcp_c, dht_public_key, crypt_connection_id); 1865 int connection_number_tcp = new_tcp_connection_to(c->tcp_c, dht_public_key, crypt_connection_id);
1740 pthread_mutex_unlock(&c->tcp_mutex); 1866 pthread_mutex_unlock(&c->tcp_mutex);
1741 1867
1742 if (connection_number_tcp == -1) 1868 if (connection_number_tcp == -1) {
1743 return -1; 1869 return -1;
1870 }
1744 1871
1745 conn->connection_number_tcp = connection_number_tcp; 1872 conn->connection_number_tcp = connection_number_tcp;
1746 memcpy(conn->public_key, real_public_key, crypto_box_PUBLICKEYBYTES); 1873 memcpy(conn->public_key, real_public_key, crypto_box_PUBLICKEYBYTES);
@@ -1780,8 +1907,9 @@ int set_direct_ip_port(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port,
1780{ 1907{
1781 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 1908 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1782 1909
1783 if (conn == 0) 1910 if (conn == 0) {
1784 return -1; 1911 return -1;
1912 }
1785 1913
1786 if (add_ip_port_connection(c, crypt_connection_id, ip_port) == 0) { 1914 if (add_ip_port_connection(c, crypt_connection_id, ip_port) == 0) {
1787 if (connected) { 1915 if (connected) {
@@ -1807,15 +1935,17 @@ int set_direct_ip_port(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port,
1807 1935
1808static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t length, void *userdata) 1936static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t length, void *userdata)
1809{ 1937{
1810 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) 1938 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
1811 return -1; 1939 return -1;
1940 }
1812 1941
1813 Net_Crypto *c = object; 1942 Net_Crypto *c = object;
1814 1943
1815 Crypto_Connection *conn = get_crypto_connection(c, id); 1944 Crypto_Connection *conn = get_crypto_connection(c, id);
1816 1945
1817 if (conn == 0) 1946 if (conn == 0) {
1818 return -1; 1947 return -1;
1948 }
1819 1949
1820 if (data[0] == NET_PACKET_COOKIE_REQUEST) { 1950 if (data[0] == NET_PACKET_COOKIE_REQUEST) {
1821 return tcp_handle_cookie_request(c, conn->connection_number_tcp, data, length); 1951 return tcp_handle_cookie_request(c, conn->connection_number_tcp, data, length);
@@ -1825,8 +1955,9 @@ static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t
1825 int ret = handle_packet_connection(c, id, data, length, 0, userdata); 1955 int ret = handle_packet_connection(c, id, data, length, 0, userdata);
1826 pthread_mutex_lock(&c->tcp_mutex); 1956 pthread_mutex_lock(&c->tcp_mutex);
1827 1957
1828 if (ret != 0) 1958 if (ret != 0) {
1829 return -1; 1959 return -1;
1960 }
1830 1961
1831 //TODO detect and kill bad TCP connections. 1962 //TODO detect and kill bad TCP connections.
1832 return 0; 1963 return 0;
@@ -1835,8 +1966,9 @@ static int tcp_data_callback(void *object, int id, const uint8_t *data, uint16_t
1835static int tcp_oob_callback(void *object, const uint8_t *public_key, unsigned int tcp_connections_number, 1966static int tcp_oob_callback(void *object, const uint8_t *public_key, unsigned int tcp_connections_number,
1836 const uint8_t *data, uint16_t length) 1967 const uint8_t *data, uint16_t length)
1837{ 1968{
1838 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) 1969 if (length == 0 || length > MAX_CRYPTO_PACKET_SIZE) {
1839 return -1; 1970 return -1;
1971 }
1840 1972
1841 Net_Crypto *c = object; 1973 Net_Crypto *c = object;
1842 1974
@@ -1848,8 +1980,9 @@ static int tcp_oob_callback(void *object, const uint8_t *public_key, unsigned in
1848 source.ip.family = TCP_FAMILY; 1980 source.ip.family = TCP_FAMILY;
1849 source.ip.ip6.uint32[0] = tcp_connections_number; 1981 source.ip.ip6.uint32[0] = tcp_connections_number;
1850 1982
1851 if (handle_new_connection_handshake(c, source, data, length) != 0) 1983 if (handle_new_connection_handshake(c, source, data, length) != 0) {
1852 return -1; 1984 return -1;
1985 }
1853 1986
1854 return 0; 1987 return 0;
1855 } else { 1988 } else {
@@ -1866,8 +1999,9 @@ int add_tcp_relay_peer(Net_Crypto *c, int crypt_connection_id, IP_Port ip_port,
1866{ 1999{
1867 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2000 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1868 2001
1869 if (conn == 0) 2002 if (conn == 0) {
1870 return -1; 2003 return -1;
2004 }
1871 2005
1872 pthread_mutex_lock(&c->tcp_mutex); 2006 pthread_mutex_lock(&c->tcp_mutex);
1873 int ret = add_tcp_relay_connection(c->tcp_c, conn->connection_number_tcp, ip_port, public_key); 2007 int ret = add_tcp_relay_connection(c->tcp_c, conn->connection_number_tcp, ip_port, public_key);
@@ -1927,8 +2061,9 @@ int send_tcp_onion_request(Net_Crypto *c, unsigned int tcp_connections_number, c
1927 */ 2061 */
1928unsigned int copy_connected_tcp_relays(Net_Crypto *c, Node_format *tcp_relays, uint16_t num) 2062unsigned int copy_connected_tcp_relays(Net_Crypto *c, Node_format *tcp_relays, uint16_t num)
1929{ 2063{
1930 if (num == 0) 2064 if (num == 0) {
1931 return 0; 2065 return 0;
2066 }
1932 2067
1933 pthread_mutex_lock(&c->tcp_mutex); 2068 pthread_mutex_lock(&c->tcp_mutex);
1934 unsigned int ret = tcp_copy_connected_relays(c->tcp_c, tcp_relays, num); 2069 unsigned int ret = tcp_copy_connected_relays(c->tcp_c, tcp_relays, num);
@@ -1948,8 +2083,9 @@ static void do_tcp(Net_Crypto *c, void *userdata)
1948 for (i = 0; i < c->crypto_connections_length; ++i) { 2083 for (i = 0; i < c->crypto_connections_length; ++i) {
1949 Crypto_Connection *conn = get_crypto_connection(c, i); 2084 Crypto_Connection *conn = get_crypto_connection(c, i);
1950 2085
1951 if (conn == 0) 2086 if (conn == 0) {
1952 return; 2087 return;
2088 }
1953 2089
1954 if (conn->status == CRYPTO_CONN_ESTABLISHED) { 2090 if (conn->status == CRYPTO_CONN_ESTABLISHED) {
1955 _Bool direct_connected = 0; 2091 _Bool direct_connected = 0;
@@ -1983,8 +2119,9 @@ int connection_status_handler(const Net_Crypto *c, int crypt_connection_id,
1983{ 2119{
1984 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2120 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
1985 2121
1986 if (conn == 0) 2122 if (conn == 0) {
1987 return -1; 2123 return -1;
2124 }
1988 2125
1989 conn->connection_status_callback = connection_status_callback; 2126 conn->connection_status_callback = connection_status_callback;
1990 conn->connection_status_callback_object = object; 2127 conn->connection_status_callback_object = object;
@@ -2005,8 +2142,9 @@ int connection_data_handler(const Net_Crypto *c, int crypt_connection_id, int (*
2005{ 2142{
2006 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2143 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2007 2144
2008 if (conn == 0) 2145 if (conn == 0) {
2009 return -1; 2146 return -1;
2147 }
2010 2148
2011 conn->connection_data_callback = connection_data_callback; 2149 conn->connection_data_callback = connection_data_callback;
2012 conn->connection_data_callback_object = object; 2150 conn->connection_data_callback_object = object;
@@ -2027,8 +2165,9 @@ int connection_lossy_data_handler(Net_Crypto *c, int crypt_connection_id,
2027{ 2165{
2028 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2166 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2029 2167
2030 if (conn == 0) 2168 if (conn == 0) {
2031 return -1; 2169 return -1;
2170 }
2032 2171
2033 conn->connection_lossy_data_callback = connection_lossy_data_callback; 2172 conn->connection_lossy_data_callback = connection_lossy_data_callback;
2034 conn->connection_lossy_data_callback_object = object; 2173 conn->connection_lossy_data_callback_object = object;
@@ -2052,8 +2191,9 @@ int nc_dht_pk_callback(Net_Crypto *c, int crypt_connection_id, void (*function)(
2052{ 2191{
2053 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2192 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2054 2193
2055 if (conn == 0) 2194 if (conn == 0) {
2056 return -1; 2195 return -1;
2196 }
2057 2197
2058 conn->dht_pk_callback = function; 2198 conn->dht_pk_callback = function;
2059 conn->dht_pk_callback_object = object; 2199 conn->dht_pk_callback_object = object;
@@ -2083,29 +2223,34 @@ static int crypto_id_ip_port(const Net_Crypto *c, IP_Port ip_port)
2083 */ 2223 */
2084static int udp_handle_packet(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata) 2224static int udp_handle_packet(void *object, IP_Port source, const uint8_t *packet, uint16_t length, void *userdata)
2085{ 2225{
2086 if (length <= CRYPTO_MIN_PACKET_SIZE || length > MAX_CRYPTO_PACKET_SIZE) 2226 if (length <= CRYPTO_MIN_PACKET_SIZE || length > MAX_CRYPTO_PACKET_SIZE) {
2087 return 1; 2227 return 1;
2228 }
2088 2229
2089 Net_Crypto *c = object; 2230 Net_Crypto *c = object;
2090 int crypt_connection_id = crypto_id_ip_port(c, source); 2231 int crypt_connection_id = crypto_id_ip_port(c, source);
2091 2232
2092 if (crypt_connection_id == -1) { 2233 if (crypt_connection_id == -1) {
2093 if (packet[0] != NET_PACKET_CRYPTO_HS) 2234 if (packet[0] != NET_PACKET_CRYPTO_HS) {
2094 return 1; 2235 return 1;
2236 }
2095 2237
2096 if (handle_new_connection_handshake(c, source, packet, length) != 0) 2238 if (handle_new_connection_handshake(c, source, packet, length) != 0) {
2097 return 1; 2239 return 1;
2240 }
2098 2241
2099 return 0; 2242 return 0;
2100 } 2243 }
2101 2244
2102 if (handle_packet_connection(c, crypt_connection_id, packet, length, 1, userdata) != 0) 2245 if (handle_packet_connection(c, crypt_connection_id, packet, length, 1, userdata) != 0) {
2103 return 1; 2246 return 1;
2247 }
2104 2248
2105 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2249 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2106 2250
2107 if (conn == 0) 2251 if (conn == 0) {
2108 return -1; 2252 return -1;
2253 }
2109 2254
2110 pthread_mutex_lock(&conn->mutex); 2255 pthread_mutex_lock(&conn->mutex);
2111 2256
@@ -2147,8 +2292,9 @@ static void send_crypto_packets(Net_Crypto *c)
2147 for (i = 0; i < c->crypto_connections_length; ++i) { 2292 for (i = 0; i < c->crypto_connections_length; ++i) {
2148 Crypto_Connection *conn = get_crypto_connection(c, i); 2293 Crypto_Connection *conn = get_crypto_connection(c, i);
2149 2294
2150 if (conn == 0) 2295 if (conn == 0) {
2151 return; 2296 return;
2297 }
2152 2298
2153 if (CRYPTO_SEND_PACKET_INTERVAL + conn->temp_packet_sent_time < temp_time) { 2299 if (CRYPTO_SEND_PACKET_INTERVAL + conn->temp_packet_sent_time < temp_time) {
2154 send_temp_packet(c, i); 2300 send_temp_packet(c, i);
@@ -2170,14 +2316,17 @@ static void send_crypto_packets(Net_Crypto *c)
2170 double request_packet_interval2 = ((CRYPTO_PACKET_MIN_RATE / conn->packet_recv_rate) * 2316 double request_packet_interval2 = ((CRYPTO_PACKET_MIN_RATE / conn->packet_recv_rate) *
2171 (double)CRYPTO_SEND_PACKET_INTERVAL) + (double)PACKET_COUNTER_AVERAGE_INTERVAL; 2317 (double)CRYPTO_SEND_PACKET_INTERVAL) + (double)PACKET_COUNTER_AVERAGE_INTERVAL;
2172 2318
2173 if (request_packet_interval2 < request_packet_interval) 2319 if (request_packet_interval2 < request_packet_interval) {
2174 request_packet_interval = request_packet_interval2; 2320 request_packet_interval = request_packet_interval2;
2321 }
2175 2322
2176 if (request_packet_interval < PACKET_COUNTER_AVERAGE_INTERVAL) 2323 if (request_packet_interval < PACKET_COUNTER_AVERAGE_INTERVAL) {
2177 request_packet_interval = PACKET_COUNTER_AVERAGE_INTERVAL; 2324 request_packet_interval = PACKET_COUNTER_AVERAGE_INTERVAL;
2325 }
2178 2326
2179 if (request_packet_interval > CRYPTO_SEND_PACKET_INTERVAL) 2327 if (request_packet_interval > CRYPTO_SEND_PACKET_INTERVAL) {
2180 request_packet_interval = CRYPTO_SEND_PACKET_INTERVAL; 2328 request_packet_interval = CRYPTO_SEND_PACKET_INTERVAL;
2329 }
2181 2330
2182 if (temp_time - conn->last_request_packet_sent > (uint64_t)request_packet_interval) { 2331 if (temp_time - conn->last_request_packet_sent > (uint64_t)request_packet_interval) {
2183 if (send_request_packet(c, i) == 0) { 2332 if (send_request_packet(c, i) == 0) {
@@ -2246,8 +2395,9 @@ static void send_crypto_packets(Net_Crypto *c)
2246 if (sum > 0) { 2395 if (sum > 0) {
2247 total_sent -= sum; 2396 total_sent -= sum;
2248 } else { 2397 } else {
2249 if (total_resent > -sum) 2398 if (total_resent > -sum) {
2250 total_resent = -sum; 2399 total_resent = -sum;
2400 }
2251 } 2401 }
2252 2402
2253 /* if queue is too big only allow resending packets. */ 2403 /* if queue is too big only allow resending packets. */
@@ -2258,8 +2408,9 @@ static void send_crypto_packets(Net_Crypto *c)
2258 double min_speed_request = 1000.0 * (((double)(total_sent + total_resent)) / ((double)( 2408 double min_speed_request = 1000.0 * (((double)(total_sent + total_resent)) / ((double)(
2259 CONGESTION_QUEUE_ARRAY_SIZE) * PACKET_COUNTER_AVERAGE_INTERVAL)); 2409 CONGESTION_QUEUE_ARRAY_SIZE) * PACKET_COUNTER_AVERAGE_INTERVAL));
2260 2410
2261 if (min_speed < CRYPTO_PACKET_MIN_RATE) 2411 if (min_speed < CRYPTO_PACKET_MIN_RATE) {
2262 min_speed = CRYPTO_PACKET_MIN_RATE; 2412 min_speed = CRYPTO_PACKET_MIN_RATE;
2413 }
2263 2414
2264 double send_array_ratio = (((double)npackets) / min_speed); 2415 double send_array_ratio = (((double)npackets) / min_speed);
2265 2416
@@ -2320,8 +2471,9 @@ static void send_crypto_packets(Net_Crypto *c)
2320 conn->last_packets_left_requested_rem = rem; 2471 conn->last_packets_left_requested_rem = rem;
2321 } 2472 }
2322 2473
2323 if (conn->packets_left > conn->packets_left_requested) 2474 if (conn->packets_left > conn->packets_left_requested) {
2324 conn->packets_left_requested = conn->packets_left; 2475 conn->packets_left_requested = conn->packets_left;
2476 }
2325 } 2477 }
2326 2478
2327 int ret = send_requested_packets(c, i, conn->packets_left_requested); 2479 int ret = send_requested_packets(c, i, conn->packets_left_requested);
@@ -2381,8 +2533,9 @@ uint32_t crypto_num_free_sendqueue_slots(const Net_Crypto *c, int crypt_connecti
2381{ 2533{
2382 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2534 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2383 2535
2384 if (conn == 0) 2536 if (conn == 0) {
2385 return 0; 2537 return 0;
2538 }
2386 2539
2387 uint32_t max_packets = CRYPTO_PACKET_BUFFER_SIZE - num_packets_array(&conn->send_array); 2540 uint32_t max_packets = CRYPTO_PACKET_BUFFER_SIZE - num_packets_array(&conn->send_array);
2388 2541
@@ -2403,30 +2556,37 @@ uint32_t crypto_num_free_sendqueue_slots(const Net_Crypto *c, int crypt_connecti
2403int64_t write_cryptpacket(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length, 2556int64_t write_cryptpacket(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length,
2404 uint8_t congestion_control) 2557 uint8_t congestion_control)
2405{ 2558{
2406 if (length == 0) 2559 if (length == 0) {
2407 return -1; 2560 return -1;
2561 }
2408 2562
2409 if (data[0] < CRYPTO_RESERVED_PACKETS) 2563 if (data[0] < CRYPTO_RESERVED_PACKETS) {
2410 return -1; 2564 return -1;
2565 }
2411 2566
2412 if (data[0] >= PACKET_ID_LOSSY_RANGE_START) 2567 if (data[0] >= PACKET_ID_LOSSY_RANGE_START) {
2413 return -1; 2568 return -1;
2569 }
2414 2570
2415 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2571 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2416 2572
2417 if (conn == 0) 2573 if (conn == 0) {
2418 return -1; 2574 return -1;
2575 }
2419 2576
2420 if (conn->status != CRYPTO_CONN_ESTABLISHED) 2577 if (conn->status != CRYPTO_CONN_ESTABLISHED) {
2421 return -1; 2578 return -1;
2579 }
2422 2580
2423 if (congestion_control && conn->packets_left == 0) 2581 if (congestion_control && conn->packets_left == 0) {
2424 return -1; 2582 return -1;
2583 }
2425 2584
2426 int64_t ret = send_lossless_packet(c, crypt_connection_id, data, length, congestion_control); 2585 int64_t ret = send_lossless_packet(c, crypt_connection_id, data, length, congestion_control);
2427 2586
2428 if (ret == -1) 2587 if (ret == -1) {
2429 return -1; 2588 return -1;
2589 }
2430 2590
2431 if (congestion_control) { 2591 if (congestion_control) {
2432 --conn->packets_left; 2592 --conn->packets_left;
@@ -2448,8 +2608,9 @@ int cryptpacket_received(Net_Crypto *c, int crypt_connection_id, uint32_t packet
2448{ 2608{
2449 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2609 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2450 2610
2451 if (conn == 0) 2611 if (conn == 0) {
2452 return -1; 2612 return -1;
2613 }
2453 2614
2454 uint32_t num = conn->send_array.buffer_end - conn->send_array.buffer_start; 2615 uint32_t num = conn->send_array.buffer_end - conn->send_array.buffer_start;
2455 uint32_t num1 = packet_number - conn->send_array.buffer_start; 2616 uint32_t num1 = packet_number - conn->send_array.buffer_start;
@@ -2468,14 +2629,17 @@ int cryptpacket_received(Net_Crypto *c, int crypt_connection_id, uint32_t packet
2468 */ 2629 */
2469int send_lossy_cryptpacket(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length) 2630int send_lossy_cryptpacket(Net_Crypto *c, int crypt_connection_id, const uint8_t *data, uint16_t length)
2470{ 2631{
2471 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) 2632 if (length == 0 || length > MAX_CRYPTO_DATA_SIZE) {
2472 return -1; 2633 return -1;
2634 }
2473 2635
2474 if (data[0] < PACKET_ID_LOSSY_RANGE_START) 2636 if (data[0] < PACKET_ID_LOSSY_RANGE_START) {
2475 return -1; 2637 return -1;
2638 }
2476 2639
2477 if (data[0] >= (PACKET_ID_LOSSY_RANGE_START + PACKET_ID_LOSSY_RANGE_SIZE)) 2640 if (data[0] >= (PACKET_ID_LOSSY_RANGE_START + PACKET_ID_LOSSY_RANGE_SIZE)) {
2478 return -1; 2641 return -1;
2642 }
2479 2643
2480 pthread_mutex_lock(&c->connections_mutex); 2644 pthread_mutex_lock(&c->connections_mutex);
2481 ++c->connection_use_counter; 2645 ++c->connection_use_counter;
@@ -2522,8 +2686,9 @@ int crypto_kill(Net_Crypto *c, int crypt_connection_id)
2522 int ret = -1; 2686 int ret = -1;
2523 2687
2524 if (conn) { 2688 if (conn) {
2525 if (conn->status == CRYPTO_CONN_ESTABLISHED) 2689 if (conn->status == CRYPTO_CONN_ESTABLISHED) {
2526 send_kill_packet(c, crypt_connection_id); 2690 send_kill_packet(c, crypt_connection_id);
2691 }
2527 2692
2528 pthread_mutex_lock(&c->tcp_mutex); 2693 pthread_mutex_lock(&c->tcp_mutex);
2529 kill_tcp_connection_to(c->tcp_c, conn->connection_number_tcp); 2694 kill_tcp_connection_to(c->tcp_c, conn->connection_number_tcp);
@@ -2552,19 +2717,22 @@ unsigned int crypto_connection_status(const Net_Crypto *c, int crypt_connection_
2552{ 2717{
2553 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id); 2718 Crypto_Connection *conn = get_crypto_connection(c, crypt_connection_id);
2554 2719
2555 if (conn == 0) 2720 if (conn == 0) {
2556 return CRYPTO_CONN_NO_CONNECTION; 2721 return CRYPTO_CONN_NO_CONNECTION;
2722 }
2557 2723
2558 if (direct_connected) { 2724 if (direct_connected) {
2559 *direct_connected = 0; 2725 *direct_connected = 0;
2560 2726
2561 uint64_t current_time = unix_time(); 2727 uint64_t current_time = unix_time();
2562 2728
2563 if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev4) > current_time) 2729 if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev4) > current_time) {
2564 *direct_connected = 1; 2730 *direct_connected = 1;
2731 }
2565 2732
2566 if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev6) > current_time) 2733 if ((UDP_DIRECT_TIMEOUT + conn->direct_lastrecv_timev6) > current_time) {
2567 *direct_connected = 1; 2734 *direct_connected = 1;
2735 }
2568 } 2736 }
2569 2737
2570 if (online_tcp_relays) { 2738 if (online_tcp_relays) {
@@ -2606,13 +2774,15 @@ Net_Crypto *new_net_crypto(Logger *log, DHT *dht, TCP_Proxy_Info *proxy_info)
2606{ 2774{
2607 unix_time_update(); 2775 unix_time_update();
2608 2776
2609 if (dht == NULL) 2777 if (dht == NULL) {
2610 return NULL; 2778 return NULL;
2779 }
2611 2780
2612 Net_Crypto *temp = calloc(1, sizeof(Net_Crypto)); 2781 Net_Crypto *temp = calloc(1, sizeof(Net_Crypto));
2613 2782
2614 if (temp == NULL) 2783 if (temp == NULL) {
2615 return NULL; 2784 return NULL;
2785 }
2616 2786
2617 temp->log = log; 2787 temp->log = log;
2618 2788
@@ -2658,16 +2828,19 @@ static void kill_timedout(Net_Crypto *c)
2658 for (i = 0; i < c->crypto_connections_length; ++i) { 2828 for (i = 0; i < c->crypto_connections_length; ++i) {
2659 Crypto_Connection *conn = get_crypto_connection(c, i); 2829 Crypto_Connection *conn = get_crypto_connection(c, i);
2660 2830
2661 if (conn == 0) 2831 if (conn == 0) {
2662 return; 2832 return;
2833 }
2663 2834
2664 if (conn->status == CRYPTO_CONN_NO_CONNECTION) 2835 if (conn->status == CRYPTO_CONN_NO_CONNECTION) {
2665 continue; 2836 continue;
2837 }
2666 2838
2667 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING || conn->status == CRYPTO_CONN_HANDSHAKE_SENT 2839 if (conn->status == CRYPTO_CONN_COOKIE_REQUESTING || conn->status == CRYPTO_CONN_HANDSHAKE_SENT
2668 || conn->status == CRYPTO_CONN_NOT_CONFIRMED) { 2840 || conn->status == CRYPTO_CONN_NOT_CONFIRMED) {
2669 if (conn->temp_packet_num_sent < MAX_NUM_SENDPACKET_TRIES) 2841 if (conn->temp_packet_num_sent < MAX_NUM_SENDPACKET_TRIES) {
2670 continue; 2842 continue;
2843 }
2671 2844
2672 connection_kill(c, i); 2845 connection_kill(c, i);
2673 } 2846 }
diff --git a/toxcore/network.c b/toxcore/network.c
index 734c8bd2..a0b09028 100644
--- a/toxcore/network.c
+++ b/toxcore/network.c
@@ -194,8 +194,9 @@ int set_socket_dualstack(sock_t sock)
194 socklen_t optsize = sizeof(ipv6only); 194 socklen_t optsize = sizeof(ipv6only);
195 int res = getsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, &optsize); 195 int res = getsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, &optsize);
196 196
197 if ((res == 0) && (ipv6only == 0)) 197 if ((res == 0) && (ipv6only == 0)) {
198 return 1; 198 return 1;
199 }
199 200
200 ipv6only = 0; 201 ipv6only = 0;
201 return (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, sizeof(ipv6only)) == 0); 202 return (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&ipv6only, sizeof(ipv6only)) == 0);
@@ -277,21 +278,22 @@ static uint32_t data_1(uint16_t buflen, const uint8_t *buffer)
277static void loglogdata(Logger *log, const char *message, const uint8_t *buffer, 278static void loglogdata(Logger *log, const char *message, const uint8_t *buffer,
278 uint16_t buflen, IP_Port ip_port, int res) 279 uint16_t buflen, IP_Port ip_port, int res)
279{ 280{
280 if (res < 0) /* Windows doesn't necessarily know %zu */ 281 if (res < 0) { /* Windows doesn't necessarily know %zu */
281 LOGGER_TRACE(log, "[%2u] %s %3hu%c %s:%hu (%u: %s) | %04x%04x", 282 LOGGER_TRACE(log, "[%2u] %s %3hu%c %s:%hu (%u: %s) | %04x%04x",
282 buffer[0], message, (buflen < 999 ? (uint16_t)buflen : 999), 'E', 283 buffer[0], message, (buflen < 999 ? (uint16_t)buflen : 999), 'E',
283 ip_ntoa(&ip_port.ip), ntohs(ip_port.port), errno, strerror(errno), data_0(buflen, buffer), 284 ip_ntoa(&ip_port.ip), ntohs(ip_port.port), errno, strerror(errno), data_0(buflen, buffer),
284 data_1(buflen, buffer)); 285 data_1(buflen, buffer));
285 else if ((res > 0) && ((size_t)res <= buflen)) 286 } else if ((res > 0) && ((size_t)res <= buflen)) {
286 LOGGER_TRACE(log, "[%2u] %s %3zu%c %s:%hu (%u: %s) | %04x%04x", 287 LOGGER_TRACE(log, "[%2u] %s %3zu%c %s:%hu (%u: %s) | %04x%04x",
287 buffer[0], message, (res < 999 ? (size_t)res : 999), ((size_t)res < buflen ? '<' : '='), 288 buffer[0], message, (res < 999 ? (size_t)res : 999), ((size_t)res < buflen ? '<' : '='),
288 ip_ntoa(&ip_port.ip), ntohs(ip_port.port), 0, "OK", data_0(buflen, buffer), data_1(buflen, 289 ip_ntoa(&ip_port.ip), ntohs(ip_port.port), 0, "OK", data_0(buflen, buffer), data_1(buflen,
289 buffer)); 290 buffer));
290 else /* empty or overwrite */ 291 } else { /* empty or overwrite */
291 LOGGER_TRACE(log, "[%2u] %s %zu%c%zu %s:%hu (%u: %s) | %04x%04x", 292 LOGGER_TRACE(log, "[%2u] %s %zu%c%zu %s:%hu (%u: %s) | %04x%04x",
292 buffer[0], message, (size_t)res, (!res ? '!' : '>'), buflen, 293 buffer[0], message, (size_t)res, (!res ? '!' : '>'), buflen,
293 ip_ntoa(&ip_port.ip), ntohs(ip_port.port), 0, "OK", data_0(buflen, buffer), data_1(buflen, 294 ip_ntoa(&ip_port.ip), ntohs(ip_port.port), 0, "OK", data_0(buflen, buffer), data_1(buflen,
294 buffer)); 295 buffer));
296 }
295} 297}
296 298
297 299
@@ -300,12 +302,14 @@ static void loglogdata(Logger *log, const char *message, const uint8_t *buffer,
300 */ 302 */
301int sendpacket(Networking_Core *net, IP_Port ip_port, const uint8_t *data, uint16_t length) 303int sendpacket(Networking_Core *net, IP_Port ip_port, const uint8_t *data, uint16_t length)
302{ 304{
303 if (net->family == 0) /* Socket not initialized */ 305 if (net->family == 0) { /* Socket not initialized */
304 return -1; 306 return -1;
307 }
305 308
306 /* socket AF_INET, but target IP NOT: can't send */ 309 /* socket AF_INET, but target IP NOT: can't send */
307 if ((net->family == AF_INET) && (ip_port.ip.family != AF_INET)) 310 if ((net->family == AF_INET) && (ip_port.ip.family != AF_INET)) {
308 return -1; 311 return -1;
312 }
309 313
310 struct sockaddr_storage addr; 314 struct sockaddr_storage addr;
311 size_t addrsize = 0; 315 size_t addrsize = 0;
@@ -405,8 +409,9 @@ static int receivepacket(Logger *log, sock_t sock, IP_Port *ip_port, uint8_t *da
405 ip_port->ip.family = AF_INET; 409 ip_port->ip.family = AF_INET;
406 ip_port->ip.ip4.uint32 = ip_port->ip.ip6.uint32[3]; 410 ip_port->ip.ip4.uint32 = ip_port->ip.ip6.uint32[3];
407 } 411 }
408 } else 412 } else {
409 return -1; 413 return -1;
414 }
410 415
411 loglogdata(log, "=>O", data, MAX_UDP_PACKET_SIZE, *ip_port, *length); 416 loglogdata(log, "=>O", data, MAX_UDP_PACKET_SIZE, *ip_port, *length);
412 417
@@ -421,8 +426,9 @@ void networking_registerhandler(Networking_Core *net, uint8_t byte, packet_handl
421 426
422void networking_poll(Networking_Core *net, void *userdata) 427void networking_poll(Networking_Core *net, void *userdata)
423{ 428{
424 if (net->family == 0) /* Socket not initialized */ 429 if (net->family == 0) { /* Socket not initialized */
425 return; 430 return;
431 }
426 432
427 unix_time_update(); 433 unix_time_update();
428 434
@@ -431,7 +437,9 @@ void networking_poll(Networking_Core *net, void *userdata)
431 uint32_t length; 437 uint32_t length;
432 438
433 while (receivepacket(net->log, net->sock, &ip_port, data, &length) != -1) { 439 while (receivepacket(net->log, net->sock, &ip_port, data, &length) != -1) {
434 if (length < 1) continue; 440 if (length < 1) {
441 continue;
442 }
435 443
436 if (!(net->packethandlers[data[0]].function)) { 444 if (!(net->packethandlers[data[0]].function)) {
437 LOGGER_WARNING(net->log, "[%02u] -- Packet has no handler", data[0]); 445 LOGGER_WARNING(net->log, "[%02u] -- Packet has no handler", data[0]);
@@ -450,8 +458,9 @@ void networking_poll(Networking_Core *net, void *userdata)
450uint8_t at_startup_ran = 0; 458uint8_t at_startup_ran = 0;
451int networking_at_startup(void) 459int networking_at_startup(void)
452{ 460{
453 if (at_startup_ran != 0) 461 if (at_startup_ran != 0) {
454 return 0; 462 return 0;
463 }
455 464
456#ifndef VANILLA_NACL 465#ifndef VANILLA_NACL
457 466
@@ -459,8 +468,9 @@ int networking_at_startup(void)
459 randombytes_stir(); 468 randombytes_stir();
460#else 469#else
461 470
462 if (sodium_init() == -1) 471 if (sodium_init() == -1) {
463 return -1; 472 return -1;
473 }
464 474
465#endif /*USE_RANDOMBYTES_STIR*/ 475#endif /*USE_RANDOMBYTES_STIR*/
466 476
@@ -524,8 +534,9 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
524 port_to = temp; 534 port_to = temp;
525 } 535 }
526 536
527 if (error) 537 if (error) {
528 *error = 2; 538 *error = 2;
539 }
529 540
530 /* maybe check for invalid IPs like 224+.x.y.z? if there is any IP set ever */ 541 /* maybe check for invalid IPs like 224+.x.y.z? if there is any IP set ever */
531 if (ip.family != AF_INET && ip.family != AF_INET6) { 542 if (ip.family != AF_INET && ip.family != AF_INET6) {
@@ -535,13 +546,15 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
535 return NULL; 546 return NULL;
536 } 547 }
537 548
538 if (networking_at_startup() != 0) 549 if (networking_at_startup() != 0) {
539 return NULL; 550 return NULL;
551 }
540 552
541 Networking_Core *temp = calloc(1, sizeof(Networking_Core)); 553 Networking_Core *temp = calloc(1, sizeof(Networking_Core));
542 554
543 if (temp == NULL) 555 if (temp == NULL) {
544 return NULL; 556 return NULL;
557 }
545 558
546 temp->log = log; 559 temp->log = log;
547 temp->family = ip.family; 560 temp->family = ip.family;
@@ -558,8 +571,9 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
558#endif 571#endif
559 free(temp); 572 free(temp);
560 573
561 if (error) 574 if (error) {
562 *error = 1; 575 *error = 1;
576 }
563 577
564 return NULL; 578 return NULL;
565 } 579 }
@@ -578,8 +592,9 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
578 if (!set_socket_nosigpipe(temp->sock)) { 592 if (!set_socket_nosigpipe(temp->sock)) {
579 kill_networking(temp); 593 kill_networking(temp);
580 594
581 if (error) 595 if (error) {
582 *error = 1; 596 *error = 1;
597 }
583 598
584 return NULL; 599 return NULL;
585 } 600 }
@@ -588,8 +603,9 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
588 if (!set_socket_nonblock(temp->sock)) { 603 if (!set_socket_nonblock(temp->sock)) {
589 kill_networking(temp); 604 kill_networking(temp);
590 605
591 if (error) 606 if (error) {
592 *error = 1; 607 *error = 1;
608 }
593 609
594 return NULL; 610 return NULL;
595 } 611 }
@@ -673,19 +689,22 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
673 /* errno isn't reset on success, only set on failure, the failed 689 /* errno isn't reset on success, only set on failure, the failed
674 * binds with parallel clients yield a -EPERM to the outside if 690 * binds with parallel clients yield a -EPERM to the outside if
675 * errno isn't cleared here */ 691 * errno isn't cleared here */
676 if (tries > 0) 692 if (tries > 0) {
677 errno = 0; 693 errno = 0;
694 }
678 695
679 if (error) 696 if (error) {
680 *error = 0; 697 *error = 0;
698 }
681 699
682 return temp; 700 return temp;
683 } 701 }
684 702
685 port_to_try++; 703 port_to_try++;
686 704
687 if (port_to_try > port_to) 705 if (port_to_try > port_to) {
688 port_to_try = port_from; 706 port_to_try = port_from;
707 }
689 708
690 *portptr = htons(port_to_try); 709 *portptr = htons(port_to_try);
691 } 710 }
@@ -695,8 +714,9 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
695 714
696 kill_networking(temp); 715 kill_networking(temp);
697 716
698 if (error) 717 if (error) {
699 *error = 1; 718 *error = 1;
719 }
700 720
701 return NULL; 721 return NULL;
702} 722}
@@ -704,11 +724,13 @@ Networking_Core *new_networking_ex(Logger *log, IP ip, uint16_t port_from, uint1
704/* Function to cleanup networking stuff. */ 724/* Function to cleanup networking stuff. */
705void kill_networking(Networking_Core *net) 725void kill_networking(Networking_Core *net)
706{ 726{
707 if (!net) 727 if (!net) {
708 return; 728 return;
729 }
709 730
710 if (net->family != 0) /* Socket not initialized */ 731 if (net->family != 0) { /* Socket not initialized */
711 kill_sock(net->sock); 732 kill_sock(net->sock);
733 }
712 734
713 free(net); 735 free(net);
714 return; 736 return;
@@ -723,26 +745,30 @@ void kill_networking(Networking_Core *net)
723 */ 745 */
724int ip_equal(const IP *a, const IP *b) 746int ip_equal(const IP *a, const IP *b)
725{ 747{
726 if (!a || !b) 748 if (!a || !b) {
727 return 0; 749 return 0;
750 }
728 751
729 /* same family */ 752 /* same family */
730 if (a->family == b->family) { 753 if (a->family == b->family) {
731 if (a->family == AF_INET) 754 if (a->family == AF_INET) {
732 return (a->ip4.in_addr.s_addr == b->ip4.in_addr.s_addr); 755 return (a->ip4.in_addr.s_addr == b->ip4.in_addr.s_addr);
733 else if (a->family == AF_INET6) 756 } else if (a->family == AF_INET6) {
734 return a->ip6.uint64[0] == b->ip6.uint64[0] && a->ip6.uint64[1] == b->ip6.uint64[1]; 757 return a->ip6.uint64[0] == b->ip6.uint64[0] && a->ip6.uint64[1] == b->ip6.uint64[1];
735 else 758 } else {
736 return 0; 759 return 0;
760 }
737 } 761 }
738 762
739 /* different family: check on the IPv6 one if it is the IPv4 one embedded */ 763 /* different family: check on the IPv6 one if it is the IPv4 one embedded */
740 if ((a->family == AF_INET) && (b->family == AF_INET6)) { 764 if ((a->family == AF_INET) && (b->family == AF_INET6)) {
741 if (IPV6_IPV4_IN_V6(b->ip6)) 765 if (IPV6_IPV4_IN_V6(b->ip6)) {
742 return (a->ip4.in_addr.s_addr == b->ip6.uint32[3]); 766 return (a->ip4.in_addr.s_addr == b->ip6.uint32[3]);
767 }
743 } else if ((a->family == AF_INET6) && (b->family == AF_INET)) { 768 } else if ((a->family == AF_INET6) && (b->family == AF_INET)) {
744 if (IPV6_IPV4_IN_V6(a->ip6)) 769 if (IPV6_IPV4_IN_V6(a->ip6)) {
745 return (a->ip6.uint32[3] == b->ip4.in_addr.s_addr); 770 return (a->ip6.uint32[3] == b->ip4.in_addr.s_addr);
771 }
746 } 772 }
747 773
748 return 0; 774 return 0;
@@ -756,11 +782,13 @@ int ip_equal(const IP *a, const IP *b)
756 */ 782 */
757int ipport_equal(const IP_Port *a, const IP_Port *b) 783int ipport_equal(const IP_Port *a, const IP_Port *b)
758{ 784{
759 if (!a || !b) 785 if (!a || !b) {
760 return 0; 786 return 0;
787 }
761 788
762 if (!a->port || (a->port != b->port)) 789 if (!a->port || (a->port != b->port)) {
763 return 0; 790 return 0;
791 }
764 792
765 return ip_equal(&a->ip, &b->ip); 793 return ip_equal(&a->ip, &b->ip);
766} 794}
@@ -768,8 +796,9 @@ int ipport_equal(const IP_Port *a, const IP_Port *b)
768/* nulls out ip */ 796/* nulls out ip */
769void ip_reset(IP *ip) 797void ip_reset(IP *ip)
770{ 798{
771 if (!ip) 799 if (!ip) {
772 return; 800 return;
801 }
773 802
774 memset(ip, 0, sizeof(IP)); 803 memset(ip, 0, sizeof(IP));
775} 804}
@@ -777,8 +806,9 @@ void ip_reset(IP *ip)
777/* nulls out ip, sets family according to flag */ 806/* nulls out ip, sets family according to flag */
778void ip_init(IP *ip, uint8_t ipv6enabled) 807void ip_init(IP *ip, uint8_t ipv6enabled)
779{ 808{
780 if (!ip) 809 if (!ip) {
781 return; 810 return;
811 }
782 812
783 memset(ip, 0, sizeof(IP)); 813 memset(ip, 0, sizeof(IP));
784 ip->family = ipv6enabled ? AF_INET6 : AF_INET; 814 ip->family = ipv6enabled ? AF_INET6 : AF_INET;
@@ -787,8 +817,9 @@ void ip_init(IP *ip, uint8_t ipv6enabled)
787/* checks if ip is valid */ 817/* checks if ip is valid */
788int ip_isset(const IP *ip) 818int ip_isset(const IP *ip)
789{ 819{
790 if (!ip) 820 if (!ip) {
791 return 0; 821 return 0;
822 }
792 823
793 return (ip->family != 0); 824 return (ip->family != 0);
794} 825}
@@ -796,11 +827,13 @@ int ip_isset(const IP *ip)
796/* checks if ip is valid */ 827/* checks if ip is valid */
797int ipport_isset(const IP_Port *ipport) 828int ipport_isset(const IP_Port *ipport)
798{ 829{
799 if (!ipport) 830 if (!ipport) {
800 return 0; 831 return 0;
832 }
801 833
802 if (!ipport->port) 834 if (!ipport->port) {
803 return 0; 835 return 0;
836 }
804 837
805 return ip_isset(&ipport->ip); 838 return ip_isset(&ipport->ip);
806} 839}
@@ -808,8 +841,9 @@ int ipport_isset(const IP_Port *ipport)
808/* copies an ip structure (careful about direction!) */ 841/* copies an ip structure (careful about direction!) */
809void ip_copy(IP *target, const IP *source) 842void ip_copy(IP *target, const IP *source)
810{ 843{
811 if (!source || !target) 844 if (!source || !target) {
812 return; 845 return;
846 }
813 847
814 memcpy(target, source, sizeof(IP)); 848 memcpy(target, source, sizeof(IP));
815} 849}
@@ -817,8 +851,9 @@ void ip_copy(IP *target, const IP *source)
817/* copies an ip_port structure (careful about direction!) */ 851/* copies an ip_port structure (careful about direction!) */
818void ipport_copy(IP_Port *target, const IP_Port *source) 852void ipport_copy(IP_Port *target, const IP_Port *source)
819{ 853{
820 if (!source || !target) 854 if (!source || !target) {
821 return; 855 return;
856 }
822 857
823 memcpy(target, source, sizeof(IP_Port)); 858 memcpy(target, source, sizeof(IP_Port));
824} 859}
@@ -850,10 +885,12 @@ const char *ip_ntoa(const IP *ip)
850 size_t len = strlen(addresstext); 885 size_t len = strlen(addresstext);
851 addresstext[len] = ']'; 886 addresstext[len] = ']';
852 addresstext[len + 1] = 0; 887 addresstext[len + 1] = 0;
853 } else 888 } else {
854 snprintf(addresstext, sizeof(addresstext), "(IP invalid, family %u)", ip->family); 889 snprintf(addresstext, sizeof(addresstext), "(IP invalid, family %u)", ip->family);
855 } else 890 }
891 } else {
856 snprintf(addresstext, sizeof(addresstext), "(IP invalid: NULL)"); 892 snprintf(addresstext, sizeof(addresstext), "(IP invalid: NULL)");
893 }
857 894
858 /* brute force protection against lacking termination */ 895 /* brute force protection against lacking termination */
859 addresstext[sizeof(addresstext) - 1] = 0; 896 addresstext[sizeof(addresstext) - 1] = 0;
@@ -907,8 +944,9 @@ int ip_parse_addr(const IP *ip, char *address, size_t length)
907 */ 944 */
908int addr_parse_ip(const char *address, IP *to) 945int addr_parse_ip(const char *address, IP *to)
909{ 946{
910 if (!address || !to) 947 if (!address || !to) {
911 return 0; 948 return 0;
949 }
912 950
913 struct in_addr addr4; 951 struct in_addr addr4;
914 952
@@ -948,8 +986,9 @@ int addr_parse_ip(const char *address, IP *to)
948 */ 986 */
949int addr_resolve(const char *address, IP *to, IP *extra) 987int addr_resolve(const char *address, IP *to, IP *extra)
950{ 988{
951 if (!address || !to) 989 if (!address || !to) {
952 return 0; 990 return 0;
991 }
953 992
954 sa_family_t family = to->family; 993 sa_family_t family = to->family;
955 994
@@ -964,8 +1003,9 @@ int addr_resolve(const char *address, IP *to, IP *extra)
964 hints.ai_family = family; 1003 hints.ai_family = family;
965 hints.ai_socktype = SOCK_DGRAM; // type of socket Tox uses. 1004 hints.ai_socktype = SOCK_DGRAM; // type of socket Tox uses.
966 1005
967 if (networking_at_startup() != 0) 1006 if (networking_at_startup() != 0) {
968 return 0; 1007 return 0;
1008 }
969 1009
970 rc = getaddrinfo(address, NULL, &hints, &server); 1010 rc = getaddrinfo(address, NULL, &hints, &server);
971 1011
@@ -1050,9 +1090,11 @@ int addr_resolve(const char *address, IP *to, IP *extra)
1050 */ 1090 */
1051int addr_resolve_or_parse_ip(const char *address, IP *to, IP *extra) 1091int addr_resolve_or_parse_ip(const char *address, IP *to, IP *extra)
1052{ 1092{
1053 if (!addr_resolve(address, to, extra)) 1093 if (!addr_resolve(address, to, extra)) {
1054 if (!addr_parse_ip(address, to)) 1094 if (!addr_parse_ip(address, to)) {
1055 return 0; 1095 return 0;
1096 }
1097 }
1056 1098
1057 return 1; 1099 return 1;
1058} 1100}
diff --git a/toxcore/onion.c b/toxcore/onion.c
index f0e3eed4..d3512780 100644
--- a/toxcore/onion.c
+++ b/toxcore/onion.c
@@ -63,8 +63,9 @@ static void ip_pack(uint8_t *data, IP source)
63/* return 0 on success, -1 on failure. */ 63/* return 0 on success, -1 on failure. */
64static int ip_unpack(IP *target, const uint8_t *data, unsigned int data_size, _Bool disable_family_check) 64static int ip_unpack(IP *target, const uint8_t *data, unsigned int data_size, _Bool disable_family_check)
65{ 65{
66 if (data_size < (1 + SIZE_IP6)) 66 if (data_size < (1 + SIZE_IP6)) {
67 return -1; 67 return -1;
68 }
68 69
69 target->family = data[0]; 70 target->family = data[0];
70 71
@@ -91,11 +92,13 @@ static void ipport_pack(uint8_t *data, const IP_Port *source)
91/* return 0 on success, -1 on failure. */ 92/* return 0 on success, -1 on failure. */
92static int ipport_unpack(IP_Port *target, const uint8_t *data, unsigned int data_size, _Bool disable_family_check) 93static int ipport_unpack(IP_Port *target, const uint8_t *data, unsigned int data_size, _Bool disable_family_check)
93{ 94{
94 if (data_size < (SIZE_IP + SIZE_PORT)) 95 if (data_size < (SIZE_IP + SIZE_PORT)) {
95 return -1; 96 return -1;
97 }
96 98
97 if (ip_unpack(&target->ip, data, data_size, disable_family_check) == -1) 99 if (ip_unpack(&target->ip, data, data_size, disable_family_check) == -1) {
98 return -1; 100 return -1;
101 }
99 102
100 memcpy(&target->port, data + SIZE_IP, SIZE_PORT); 103 memcpy(&target->port, data + SIZE_IP, SIZE_PORT);
101 return 0; 104 return 0;
@@ -113,8 +116,9 @@ static int ipport_unpack(IP_Port *target, const uint8_t *data, unsigned int data
113 */ 116 */
114int create_onion_path(const DHT *dht, Onion_Path *new_path, const Node_format *nodes) 117int create_onion_path(const DHT *dht, Onion_Path *new_path, const Node_format *nodes)
115{ 118{
116 if (!new_path || !nodes) 119 if (!new_path || !nodes) {
117 return -1; 120 return -1;
121 }
118 122
119 encrypt_precompute(nodes[0].public_key, dht->self_secret_key, new_path->shared_key1); 123 encrypt_precompute(nodes[0].public_key, dht->self_secret_key, new_path->shared_key1);
120 memcpy(new_path->public_key1, dht->self_public_key, crypto_box_PUBLICKEYBYTES); 124 memcpy(new_path->public_key1, dht->self_public_key, crypto_box_PUBLICKEYBYTES);
@@ -148,8 +152,9 @@ int create_onion_path(const DHT *dht, Onion_Path *new_path, const Node_format *n
148 */ 152 */
149int onion_path_to_nodes(Node_format *nodes, unsigned int num_nodes, const Onion_Path *path) 153int onion_path_to_nodes(Node_format *nodes, unsigned int num_nodes, const Onion_Path *path)
150{ 154{
151 if (num_nodes < ONION_PATH_LENGTH) 155 if (num_nodes < ONION_PATH_LENGTH) {
152 return -1; 156 return -1;
157 }
153 158
154 nodes[0].ip_port = path->ip_port1; 159 nodes[0].ip_port = path->ip_port1;
155 nodes[1].ip_port = path->ip_port2; 160 nodes[1].ip_port = path->ip_port2;
@@ -173,8 +178,9 @@ int onion_path_to_nodes(Node_format *nodes, unsigned int num_nodes, const Onion_
173int create_onion_packet(uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, IP_Port dest, 178int create_onion_packet(uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, IP_Port dest,
174 const uint8_t *data, uint16_t length) 179 const uint8_t *data, uint16_t length)
175{ 180{
176 if (1 + length + SEND_1 > max_packet_length || length == 0) 181 if (1 + length + SEND_1 > max_packet_length || length == 0) {
177 return -1; 182 return -1;
183 }
178 184
179 uint8_t step1[SIZE_IPPORT + length]; 185 uint8_t step1[SIZE_IPPORT + length];
180 186
@@ -191,8 +197,9 @@ int create_onion_packet(uint8_t *packet, uint16_t max_packet_length, const Onion
191 int len = encrypt_data_symmetric(path->shared_key3, nonce, step1, sizeof(step1), 197 int len = encrypt_data_symmetric(path->shared_key3, nonce, step1, sizeof(step1),
192 step2 + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES); 198 step2 + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES);
193 199
194 if (len != SIZE_IPPORT + length + crypto_box_MACBYTES) 200 if (len != SIZE_IPPORT + length + crypto_box_MACBYTES) {
195 return -1; 201 return -1;
202 }
196 203
197 uint8_t step3[SIZE_IPPORT + SEND_BASE * 2 + length]; 204 uint8_t step3[SIZE_IPPORT + SEND_BASE * 2 + length];
198 ipport_pack(step3, &path->ip_port2); 205 ipport_pack(step3, &path->ip_port2);
@@ -200,8 +207,9 @@ int create_onion_packet(uint8_t *packet, uint16_t max_packet_length, const Onion
200 len = encrypt_data_symmetric(path->shared_key2, nonce, step2, sizeof(step2), 207 len = encrypt_data_symmetric(path->shared_key2, nonce, step2, sizeof(step2),
201 step3 + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES); 208 step3 + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES);
202 209
203 if (len != SIZE_IPPORT + SEND_BASE + length + crypto_box_MACBYTES) 210 if (len != SIZE_IPPORT + SEND_BASE + length + crypto_box_MACBYTES) {
204 return -1; 211 return -1;
212 }
205 213
206 packet[0] = NET_PACKET_ONION_SEND_INITIAL; 214 packet[0] = NET_PACKET_ONION_SEND_INITIAL;
207 memcpy(packet + 1, nonce, crypto_box_NONCEBYTES); 215 memcpy(packet + 1, nonce, crypto_box_NONCEBYTES);
@@ -210,8 +218,9 @@ int create_onion_packet(uint8_t *packet, uint16_t max_packet_length, const Onion
210 len = encrypt_data_symmetric(path->shared_key1, nonce, step3, sizeof(step3), 218 len = encrypt_data_symmetric(path->shared_key1, nonce, step3, sizeof(step3),
211 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES); 219 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES);
212 220
213 if (len != SIZE_IPPORT + SEND_BASE * 2 + length + crypto_box_MACBYTES) 221 if (len != SIZE_IPPORT + SEND_BASE * 2 + length + crypto_box_MACBYTES) {
214 return -1; 222 return -1;
223 }
215 224
216 return 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + len; 225 return 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + len;
217} 226}
@@ -228,8 +237,9 @@ int create_onion_packet(uint8_t *packet, uint16_t max_packet_length, const Onion
228int create_onion_packet_tcp(uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, IP_Port dest, 237int create_onion_packet_tcp(uint8_t *packet, uint16_t max_packet_length, const Onion_Path *path, IP_Port dest,
229 const uint8_t *data, uint16_t length) 238 const uint8_t *data, uint16_t length)
230{ 239{
231 if (crypto_box_NONCEBYTES + SIZE_IPPORT + SEND_BASE * 2 + length > max_packet_length || length == 0) 240 if (crypto_box_NONCEBYTES + SIZE_IPPORT + SEND_BASE * 2 + length > max_packet_length || length == 0) {
232 return -1; 241 return -1;
242 }
233 243
234 uint8_t step1[SIZE_IPPORT + length]; 244 uint8_t step1[SIZE_IPPORT + length];
235 245
@@ -246,16 +256,18 @@ int create_onion_packet_tcp(uint8_t *packet, uint16_t max_packet_length, const O
246 int len = encrypt_data_symmetric(path->shared_key3, nonce, step1, sizeof(step1), 256 int len = encrypt_data_symmetric(path->shared_key3, nonce, step1, sizeof(step1),
247 step2 + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES); 257 step2 + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES);
248 258
249 if (len != SIZE_IPPORT + length + crypto_box_MACBYTES) 259 if (len != SIZE_IPPORT + length + crypto_box_MACBYTES) {
250 return -1; 260 return -1;
261 }
251 262
252 ipport_pack(packet + crypto_box_NONCEBYTES, &path->ip_port2); 263 ipport_pack(packet + crypto_box_NONCEBYTES, &path->ip_port2);
253 memcpy(packet + crypto_box_NONCEBYTES + SIZE_IPPORT, path->public_key2, crypto_box_PUBLICKEYBYTES); 264 memcpy(packet + crypto_box_NONCEBYTES + SIZE_IPPORT, path->public_key2, crypto_box_PUBLICKEYBYTES);
254 len = encrypt_data_symmetric(path->shared_key2, nonce, step2, sizeof(step2), 265 len = encrypt_data_symmetric(path->shared_key2, nonce, step2, sizeof(step2),
255 packet + crypto_box_NONCEBYTES + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES); 266 packet + crypto_box_NONCEBYTES + SIZE_IPPORT + crypto_box_PUBLICKEYBYTES);
256 267
257 if (len != SIZE_IPPORT + SEND_BASE + length + crypto_box_MACBYTES) 268 if (len != SIZE_IPPORT + SEND_BASE + length + crypto_box_MACBYTES) {
258 return -1; 269 return -1;
270 }
259 271
260 memcpy(packet, nonce, crypto_box_NONCEBYTES); 272 memcpy(packet, nonce, crypto_box_NONCEBYTES);
261 273
@@ -275,11 +287,13 @@ int send_onion_packet(Networking_Core *net, const Onion_Path *path, IP_Port dest
275 uint8_t packet[ONION_MAX_PACKET_SIZE]; 287 uint8_t packet[ONION_MAX_PACKET_SIZE];
276 int len = create_onion_packet(packet, sizeof(packet), path, dest, data, length); 288 int len = create_onion_packet(packet, sizeof(packet), path, dest, data, length);
277 289
278 if (len == -1) 290 if (len == -1) {
279 return -1; 291 return -1;
292 }
280 293
281 if (sendpacket(net, path->ip_port1, packet, len) != len) 294 if (sendpacket(net, path->ip_port1, packet, len) != len) {
282 return -1; 295 return -1;
296 }
283 297
284 return 0; 298 return 0;
285} 299}
@@ -292,16 +306,18 @@ int send_onion_packet(Networking_Core *net, const Onion_Path *path, IP_Port dest
292 */ 306 */
293int send_onion_response(Networking_Core *net, IP_Port dest, const uint8_t *data, uint16_t length, const uint8_t *ret) 307int send_onion_response(Networking_Core *net, IP_Port dest, const uint8_t *data, uint16_t length, const uint8_t *ret)
294{ 308{
295 if (length > ONION_RESPONSE_MAX_DATA_SIZE || length == 0) 309 if (length > ONION_RESPONSE_MAX_DATA_SIZE || length == 0) {
296 return -1; 310 return -1;
311 }
297 312
298 uint8_t packet[1 + RETURN_3 + length]; 313 uint8_t packet[1 + RETURN_3 + length];
299 packet[0] = NET_PACKET_ONION_RECV_3; 314 packet[0] = NET_PACKET_ONION_RECV_3;
300 memcpy(packet + 1, ret, RETURN_3); 315 memcpy(packet + 1, ret, RETURN_3);
301 memcpy(packet + 1 + RETURN_3, data, length); 316 memcpy(packet + 1 + RETURN_3, data, length);
302 317
303 if ((uint32_t)sendpacket(net, dest, packet, sizeof(packet)) != sizeof(packet)) 318 if ((uint32_t)sendpacket(net, dest, packet, sizeof(packet)) != sizeof(packet)) {
304 return -1; 319 return -1;
320 }
305 321
306 return 0; 322 return 0;
307} 323}
@@ -310,11 +326,13 @@ static int handle_send_initial(void *object, IP_Port source, const uint8_t *pack
310{ 326{
311 Onion *onion = object; 327 Onion *onion = object;
312 328
313 if (length > ONION_MAX_PACKET_SIZE) 329 if (length > ONION_MAX_PACKET_SIZE) {
314 return 1; 330 return 1;
331 }
315 332
316 if (length <= 1 + SEND_1) 333 if (length <= 1 + SEND_1) {
317 return 1; 334 return 1;
335 }
318 336
319 change_symmetric_key(onion); 337 change_symmetric_key(onion);
320 338
@@ -324,24 +342,28 @@ static int handle_send_initial(void *object, IP_Port source, const uint8_t *pack
324 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, 342 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES,
325 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES), plain); 343 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES), plain);
326 344
327 if (len != length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_box_MACBYTES)) 345 if (len != length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + crypto_box_MACBYTES)) {
328 return 1; 346 return 1;
347 }
329 348
330 return onion_send_1(onion, plain, len, source, packet + 1); 349 return onion_send_1(onion, plain, len, source, packet + 1);
331} 350}
332 351
333int onion_send_1(const Onion *onion, const uint8_t *plain, uint16_t len, IP_Port source, const uint8_t *nonce) 352int onion_send_1(const Onion *onion, const uint8_t *plain, uint16_t len, IP_Port source, const uint8_t *nonce)
334{ 353{
335 if (len > ONION_MAX_PACKET_SIZE + SIZE_IPPORT - (1 + crypto_box_NONCEBYTES + ONION_RETURN_1)) 354 if (len > ONION_MAX_PACKET_SIZE + SIZE_IPPORT - (1 + crypto_box_NONCEBYTES + ONION_RETURN_1)) {
336 return 1; 355 return 1;
356 }
337 357
338 if (len <= SIZE_IPPORT + SEND_BASE * 2) 358 if (len <= SIZE_IPPORT + SEND_BASE * 2) {
339 return 1; 359 return 1;
360 }
340 361
341 IP_Port send_to; 362 IP_Port send_to;
342 363
343 if (ipport_unpack(&send_to, plain, len, 0) == -1) 364 if (ipport_unpack(&send_to, plain, len, 0) == -1) {
344 return 1; 365 return 1;
366 }
345 367
346 uint8_t ip_port[SIZE_IPPORT]; 368 uint8_t ip_port[SIZE_IPPORT];
347 ipport_pack(ip_port, &source); 369 ipport_pack(ip_port, &source);
@@ -356,13 +378,15 @@ int onion_send_1(const Onion *onion, const uint8_t *plain, uint16_t len, IP_Port
356 len = encrypt_data_symmetric(onion->secret_symmetric_key, ret_part, ip_port, SIZE_IPPORT, 378 len = encrypt_data_symmetric(onion->secret_symmetric_key, ret_part, ip_port, SIZE_IPPORT,
357 ret_part + crypto_box_NONCEBYTES); 379 ret_part + crypto_box_NONCEBYTES);
358 380
359 if (len != SIZE_IPPORT + crypto_box_MACBYTES) 381 if (len != SIZE_IPPORT + crypto_box_MACBYTES) {
360 return 1; 382 return 1;
383 }
361 384
362 data_len += crypto_box_NONCEBYTES + len; 385 data_len += crypto_box_NONCEBYTES + len;
363 386
364 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) 387 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) {
365 return 1; 388 return 1;
389 }
366 390
367 return 0; 391 return 0;
368} 392}
@@ -371,11 +395,13 @@ static int handle_send_1(void *object, IP_Port source, const uint8_t *packet, ui
371{ 395{
372 Onion *onion = object; 396 Onion *onion = object;
373 397
374 if (length > ONION_MAX_PACKET_SIZE) 398 if (length > ONION_MAX_PACKET_SIZE) {
375 return 1; 399 return 1;
400 }
376 401
377 if (length <= 1 + SEND_2) 402 if (length <= 1 + SEND_2) {
378 return 1; 403 return 1;
404 }
379 405
380 change_symmetric_key(onion); 406 change_symmetric_key(onion);
381 407
@@ -385,13 +411,15 @@ static int handle_send_1(void *object, IP_Port source, const uint8_t *packet, ui
385 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, 411 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES,
386 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_1), plain); 412 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_1), plain);
387 413
388 if (len != length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_1 + crypto_box_MACBYTES)) 414 if (len != length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_1 + crypto_box_MACBYTES)) {
389 return 1; 415 return 1;
416 }
390 417
391 IP_Port send_to; 418 IP_Port send_to;
392 419
393 if (ipport_unpack(&send_to, plain, len, 0) == -1) 420 if (ipport_unpack(&send_to, plain, len, 0) == -1) {
394 return 1; 421 return 1;
422 }
395 423
396 uint8_t data[ONION_MAX_PACKET_SIZE]; 424 uint8_t data[ONION_MAX_PACKET_SIZE];
397 data[0] = NET_PACKET_ONION_SEND_2; 425 data[0] = NET_PACKET_ONION_SEND_2;
@@ -406,13 +434,15 @@ static int handle_send_1(void *object, IP_Port source, const uint8_t *packet, ui
406 len = encrypt_data_symmetric(onion->secret_symmetric_key, ret_part, ret_data, sizeof(ret_data), 434 len = encrypt_data_symmetric(onion->secret_symmetric_key, ret_part, ret_data, sizeof(ret_data),
407 ret_part + crypto_box_NONCEBYTES); 435 ret_part + crypto_box_NONCEBYTES);
408 436
409 if (len != RETURN_2 - crypto_box_NONCEBYTES) 437 if (len != RETURN_2 - crypto_box_NONCEBYTES) {
410 return 1; 438 return 1;
439 }
411 440
412 data_len += crypto_box_NONCEBYTES + len; 441 data_len += crypto_box_NONCEBYTES + len;
413 442
414 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) 443 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) {
415 return 1; 444 return 1;
445 }
416 446
417 return 0; 447 return 0;
418} 448}
@@ -421,11 +451,13 @@ static int handle_send_2(void *object, IP_Port source, const uint8_t *packet, ui
421{ 451{
422 Onion *onion = object; 452 Onion *onion = object;
423 453
424 if (length > ONION_MAX_PACKET_SIZE) 454 if (length > ONION_MAX_PACKET_SIZE) {
425 return 1; 455 return 1;
456 }
426 457
427 if (length <= 1 + SEND_3) 458 if (length <= 1 + SEND_3) {
428 return 1; 459 return 1;
460 }
429 461
430 change_symmetric_key(onion); 462 change_symmetric_key(onion);
431 463
@@ -435,13 +467,15 @@ static int handle_send_2(void *object, IP_Port source, const uint8_t *packet, ui
435 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, 467 int len = decrypt_data_symmetric(shared_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES,
436 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_2), plain); 468 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_2), plain);
437 469
438 if (len != length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_2 + crypto_box_MACBYTES)) 470 if (len != length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + RETURN_2 + crypto_box_MACBYTES)) {
439 return 1; 471 return 1;
472 }
440 473
441 IP_Port send_to; 474 IP_Port send_to;
442 475
443 if (ipport_unpack(&send_to, plain, len, 0) == -1) 476 if (ipport_unpack(&send_to, plain, len, 0) == -1) {
444 return 1; 477 return 1;
478 }
445 479
446 uint8_t data[ONION_MAX_PACKET_SIZE]; 480 uint8_t data[ONION_MAX_PACKET_SIZE];
447 memcpy(data, plain + SIZE_IPPORT, len - SIZE_IPPORT); 481 memcpy(data, plain + SIZE_IPPORT, len - SIZE_IPPORT);
@@ -454,13 +488,15 @@ static int handle_send_2(void *object, IP_Port source, const uint8_t *packet, ui
454 len = encrypt_data_symmetric(onion->secret_symmetric_key, ret_part, ret_data, sizeof(ret_data), 488 len = encrypt_data_symmetric(onion->secret_symmetric_key, ret_part, ret_data, sizeof(ret_data),
455 ret_part + crypto_box_NONCEBYTES); 489 ret_part + crypto_box_NONCEBYTES);
456 490
457 if (len != RETURN_3 - crypto_box_NONCEBYTES) 491 if (len != RETURN_3 - crypto_box_NONCEBYTES) {
458 return 1; 492 return 1;
493 }
459 494
460 data_len += RETURN_3; 495 data_len += RETURN_3;
461 496
462 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) 497 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) {
463 return 1; 498 return 1;
499 }
464 500
465 return 0; 501 return 0;
466} 502}
@@ -470,11 +506,13 @@ static int handle_recv_3(void *object, IP_Port source, const uint8_t *packet, ui
470{ 506{
471 Onion *onion = object; 507 Onion *onion = object;
472 508
473 if (length > ONION_MAX_PACKET_SIZE) 509 if (length > ONION_MAX_PACKET_SIZE) {
474 return 1; 510 return 1;
511 }
475 512
476 if (length <= 1 + RETURN_3) 513 if (length <= 1 + RETURN_3) {
477 return 1; 514 return 1;
515 }
478 516
479 change_symmetric_key(onion); 517 change_symmetric_key(onion);
480 518
@@ -482,13 +520,15 @@ static int handle_recv_3(void *object, IP_Port source, const uint8_t *packet, ui
482 int len = decrypt_data_symmetric(onion->secret_symmetric_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES, 520 int len = decrypt_data_symmetric(onion->secret_symmetric_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES,
483 SIZE_IPPORT + RETURN_2 + crypto_box_MACBYTES, plain); 521 SIZE_IPPORT + RETURN_2 + crypto_box_MACBYTES, plain);
484 522
485 if ((uint32_t)len != sizeof(plain)) 523 if ((uint32_t)len != sizeof(plain)) {
486 return 1; 524 return 1;
525 }
487 526
488 IP_Port send_to; 527 IP_Port send_to;
489 528
490 if (ipport_unpack(&send_to, plain, len, 0) == -1) 529 if (ipport_unpack(&send_to, plain, len, 0) == -1) {
491 return 1; 530 return 1;
531 }
492 532
493 uint8_t data[ONION_MAX_PACKET_SIZE]; 533 uint8_t data[ONION_MAX_PACKET_SIZE];
494 data[0] = NET_PACKET_ONION_RECV_2; 534 data[0] = NET_PACKET_ONION_RECV_2;
@@ -496,8 +536,9 @@ static int handle_recv_3(void *object, IP_Port source, const uint8_t *packet, ui
496 memcpy(data + 1 + RETURN_2, packet + 1 + RETURN_3, length - (1 + RETURN_3)); 536 memcpy(data + 1 + RETURN_2, packet + 1 + RETURN_3, length - (1 + RETURN_3));
497 uint16_t data_len = 1 + RETURN_2 + (length - (1 + RETURN_3)); 537 uint16_t data_len = 1 + RETURN_2 + (length - (1 + RETURN_3));
498 538
499 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) 539 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) {
500 return 1; 540 return 1;
541 }
501 542
502 return 0; 543 return 0;
503} 544}
@@ -506,11 +547,13 @@ static int handle_recv_2(void *object, IP_Port source, const uint8_t *packet, ui
506{ 547{
507 Onion *onion = object; 548 Onion *onion = object;
508 549
509 if (length > ONION_MAX_PACKET_SIZE) 550 if (length > ONION_MAX_PACKET_SIZE) {
510 return 1; 551 return 1;
552 }
511 553
512 if (length <= 1 + RETURN_2) 554 if (length <= 1 + RETURN_2) {
513 return 1; 555 return 1;
556 }
514 557
515 change_symmetric_key(onion); 558 change_symmetric_key(onion);
516 559
@@ -518,13 +561,15 @@ static int handle_recv_2(void *object, IP_Port source, const uint8_t *packet, ui
518 int len = decrypt_data_symmetric(onion->secret_symmetric_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES, 561 int len = decrypt_data_symmetric(onion->secret_symmetric_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES,
519 SIZE_IPPORT + RETURN_1 + crypto_box_MACBYTES, plain); 562 SIZE_IPPORT + RETURN_1 + crypto_box_MACBYTES, plain);
520 563
521 if ((uint32_t)len != sizeof(plain)) 564 if ((uint32_t)len != sizeof(plain)) {
522 return 1; 565 return 1;
566 }
523 567
524 IP_Port send_to; 568 IP_Port send_to;
525 569
526 if (ipport_unpack(&send_to, plain, len, 0) == -1) 570 if (ipport_unpack(&send_to, plain, len, 0) == -1) {
527 return 1; 571 return 1;
572 }
528 573
529 uint8_t data[ONION_MAX_PACKET_SIZE]; 574 uint8_t data[ONION_MAX_PACKET_SIZE];
530 data[0] = NET_PACKET_ONION_RECV_1; 575 data[0] = NET_PACKET_ONION_RECV_1;
@@ -532,8 +577,9 @@ static int handle_recv_2(void *object, IP_Port source, const uint8_t *packet, ui
532 memcpy(data + 1 + RETURN_1, packet + 1 + RETURN_2, length - (1 + RETURN_2)); 577 memcpy(data + 1 + RETURN_1, packet + 1 + RETURN_2, length - (1 + RETURN_2));
533 uint16_t data_len = 1 + RETURN_1 + (length - (1 + RETURN_2)); 578 uint16_t data_len = 1 + RETURN_1 + (length - (1 + RETURN_2));
534 579
535 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) 580 if ((uint32_t)sendpacket(onion->net, send_to, data, data_len) != data_len) {
536 return 1; 581 return 1;
582 }
537 583
538 return 0; 584 return 0;
539} 585}
@@ -542,11 +588,13 @@ static int handle_recv_1(void *object, IP_Port source, const uint8_t *packet, ui
542{ 588{
543 Onion *onion = object; 589 Onion *onion = object;
544 590
545 if (length > ONION_MAX_PACKET_SIZE) 591 if (length > ONION_MAX_PACKET_SIZE) {
546 return 1; 592 return 1;
593 }
547 594
548 if (length <= 1 + RETURN_1) 595 if (length <= 1 + RETURN_1) {
549 return 1; 596 return 1;
597 }
550 598
551 change_symmetric_key(onion); 599 change_symmetric_key(onion);
552 600
@@ -554,21 +602,25 @@ static int handle_recv_1(void *object, IP_Port source, const uint8_t *packet, ui
554 int len = decrypt_data_symmetric(onion->secret_symmetric_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES, 602 int len = decrypt_data_symmetric(onion->secret_symmetric_key, packet + 1, packet + 1 + crypto_box_NONCEBYTES,
555 SIZE_IPPORT + crypto_box_MACBYTES, plain); 603 SIZE_IPPORT + crypto_box_MACBYTES, plain);
556 604
557 if ((uint32_t)len != SIZE_IPPORT) 605 if ((uint32_t)len != SIZE_IPPORT) {
558 return 1; 606 return 1;
607 }
559 608
560 IP_Port send_to; 609 IP_Port send_to;
561 610
562 if (ipport_unpack(&send_to, plain, len, 1) == -1) 611 if (ipport_unpack(&send_to, plain, len, 1) == -1) {
563 return 1; 612 return 1;
613 }
564 614
565 uint16_t data_len = length - (1 + RETURN_1); 615 uint16_t data_len = length - (1 + RETURN_1);
566 616
567 if (onion->recv_1_function && send_to.ip.family != AF_INET && send_to.ip.family != AF_INET6) 617 if (onion->recv_1_function && send_to.ip.family != AF_INET && send_to.ip.family != AF_INET6) {
568 return onion->recv_1_function(onion->callback_object, send_to, packet + (1 + RETURN_1), data_len); 618 return onion->recv_1_function(onion->callback_object, send_to, packet + (1 + RETURN_1), data_len);
619 }
569 620
570 if ((uint32_t)sendpacket(onion->net, send_to, packet + (1 + RETURN_1), data_len) != data_len) 621 if ((uint32_t)sendpacket(onion->net, send_to, packet + (1 + RETURN_1), data_len) != data_len) {
571 return 1; 622 return 1;
623 }
572 624
573 return 0; 625 return 0;
574} 626}
@@ -581,13 +633,15 @@ void set_callback_handle_recv_1(Onion *onion, int (*function)(void *, IP_Port, c
581 633
582Onion *new_onion(DHT *dht) 634Onion *new_onion(DHT *dht)
583{ 635{
584 if (dht == NULL) 636 if (dht == NULL) {
585 return NULL; 637 return NULL;
638 }
586 639
587 Onion *onion = calloc(1, sizeof(Onion)); 640 Onion *onion = calloc(1, sizeof(Onion));
588 641
589 if (onion == NULL) 642 if (onion == NULL) {
590 return NULL; 643 return NULL;
644 }
591 645
592 onion->dht = dht; 646 onion->dht = dht;
593 onion->net = dht->net; 647 onion->net = dht->net;
@@ -607,8 +661,9 @@ Onion *new_onion(DHT *dht)
607 661
608void kill_onion(Onion *onion) 662void kill_onion(Onion *onion)
609{ 663{
610 if (onion == NULL) 664 if (onion == NULL) {
611 return; 665 return;
666 }
612 667
613 networking_registerhandler(onion->net, NET_PACKET_ONION_SEND_INITIAL, NULL, NULL); 668 networking_registerhandler(onion->net, NET_PACKET_ONION_SEND_INITIAL, NULL, NULL);
614 networking_registerhandler(onion->net, NET_PACKET_ONION_SEND_1, NULL, NULL); 669 networking_registerhandler(onion->net, NET_PACKET_ONION_SEND_1, NULL, NULL);
diff --git a/toxcore/onion_announce.c b/toxcore/onion_announce.c
index f6a00f67..08492bb9 100644
--- a/toxcore/onion_announce.c
+++ b/toxcore/onion_announce.c
@@ -51,8 +51,9 @@ int create_announce_request(uint8_t *packet, uint16_t max_packet_length, const u
51 const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id, 51 const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id,
52 const uint8_t *data_public_key, uint64_t sendback_data) 52 const uint8_t *data_public_key, uint64_t sendback_data)
53{ 53{
54 if (max_packet_length < ONION_ANNOUNCE_REQUEST_SIZE) 54 if (max_packet_length < ONION_ANNOUNCE_REQUEST_SIZE) {
55 return -1; 55 return -1;
56 }
56 57
57 uint8_t plain[ONION_PING_ID_SIZE + crypto_box_PUBLICKEYBYTES + crypto_box_PUBLICKEYBYTES + 58 uint8_t plain[ONION_PING_ID_SIZE + crypto_box_PUBLICKEYBYTES + crypto_box_PUBLICKEYBYTES +
58 ONION_ANNOUNCE_SENDBACK_DATA_LENGTH]; 59 ONION_ANNOUNCE_SENDBACK_DATA_LENGTH];
@@ -68,8 +69,9 @@ int create_announce_request(uint8_t *packet, uint16_t max_packet_length, const u
68 int len = encrypt_data(dest_client_id, secret_key, packet + 1, plain, sizeof(plain), 69 int len = encrypt_data(dest_client_id, secret_key, packet + 1, plain, sizeof(plain),
69 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES); 70 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES);
70 71
71 if ((uint32_t)len + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES != ONION_ANNOUNCE_REQUEST_SIZE) 72 if ((uint32_t)len + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES != ONION_ANNOUNCE_REQUEST_SIZE) {
72 return -1; 73 return -1;
74 }
73 75
74 memcpy(packet + 1 + crypto_box_NONCEBYTES, public_key, crypto_box_PUBLICKEYBYTES); 76 memcpy(packet + 1 + crypto_box_NONCEBYTES, public_key, crypto_box_PUBLICKEYBYTES);
75 77
@@ -89,11 +91,13 @@ int create_announce_request(uint8_t *packet, uint16_t max_packet_length, const u
89int create_data_request(uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key, 91int create_data_request(uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key,
90 const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length) 92 const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length)
91{ 93{
92 if (DATA_REQUEST_MIN_SIZE + length > max_packet_length) 94 if (DATA_REQUEST_MIN_SIZE + length > max_packet_length) {
93 return -1; 95 return -1;
96 }
94 97
95 if ((unsigned int)DATA_REQUEST_MIN_SIZE + length > ONION_MAX_DATA_SIZE) 98 if ((unsigned int)DATA_REQUEST_MIN_SIZE + length > ONION_MAX_DATA_SIZE) {
96 return -1; 99 return -1;
100 }
97 101
98 packet[0] = NET_PACKET_ONION_DATA_REQUEST; 102 packet[0] = NET_PACKET_ONION_DATA_REQUEST;
99 memcpy(packet + 1, public_key, crypto_box_PUBLICKEYBYTES); 103 memcpy(packet + 1, public_key, crypto_box_PUBLICKEYBYTES);
@@ -109,8 +113,9 @@ int create_data_request(uint8_t *packet, uint16_t max_packet_length, const uint8
109 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES); 113 packet + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES);
110 114
111 if (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + len != DATA_REQUEST_MIN_SIZE + 115 if (1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES + len != DATA_REQUEST_MIN_SIZE +
112 length) 116 length) {
113 return -1; 117 return -1;
118 }
114 119
115 return DATA_REQUEST_MIN_SIZE + length; 120 return DATA_REQUEST_MIN_SIZE + length;
116} 121}
@@ -137,17 +142,20 @@ int send_announce_request(Networking_Core *net, const Onion_Path *path, Node_for
137 int len = create_announce_request(request, sizeof(request), dest.public_key, public_key, secret_key, ping_id, client_id, 142 int len = create_announce_request(request, sizeof(request), dest.public_key, public_key, secret_key, ping_id, client_id,
138 data_public_key, sendback_data); 143 data_public_key, sendback_data);
139 144
140 if (len != sizeof(request)) 145 if (len != sizeof(request)) {
141 return -1; 146 return -1;
147 }
142 148
143 uint8_t packet[ONION_MAX_PACKET_SIZE]; 149 uint8_t packet[ONION_MAX_PACKET_SIZE];
144 len = create_onion_packet(packet, sizeof(packet), path, dest.ip_port, request, sizeof(request)); 150 len = create_onion_packet(packet, sizeof(packet), path, dest.ip_port, request, sizeof(request));
145 151
146 if (len == -1) 152 if (len == -1) {
147 return -1; 153 return -1;
154 }
148 155
149 if (sendpacket(net, path->ip_port1, packet, len) != len) 156 if (sendpacket(net, path->ip_port1, packet, len) != len) {
150 return -1; 157 return -1;
158 }
151 159
152 return 0; 160 return 0;
153} 161}
@@ -172,17 +180,20 @@ int send_data_request(Networking_Core *net, const Onion_Path *path, IP_Port dest
172 uint8_t request[ONION_MAX_DATA_SIZE]; 180 uint8_t request[ONION_MAX_DATA_SIZE];
173 int len = create_data_request(request, sizeof(request), public_key, encrypt_public_key, nonce, data, length); 181 int len = create_data_request(request, sizeof(request), public_key, encrypt_public_key, nonce, data, length);
174 182
175 if (len == -1) 183 if (len == -1) {
176 return -1; 184 return -1;
185 }
177 186
178 uint8_t packet[ONION_MAX_PACKET_SIZE]; 187 uint8_t packet[ONION_MAX_PACKET_SIZE];
179 len = create_onion_packet(packet, sizeof(packet), path, dest, request, len); 188 len = create_onion_packet(packet, sizeof(packet), path, dest, request, len);
180 189
181 if (len == -1) 190 if (len == -1) {
182 return -1; 191 return -1;
192 }
183 193
184 if (sendpacket(net, path->ip_port1, packet, len) != len) 194 if (sendpacket(net, path->ip_port1, packet, len) != len) {
185 return -1; 195 return -1;
196 }
186 197
187 return 0; 198 return 0;
188} 199}
@@ -211,8 +222,9 @@ static int in_entries(const Onion_Announce *onion_a, const uint8_t *public_key)
211 222
212 for (i = 0; i < ONION_ANNOUNCE_MAX_ENTRIES; ++i) { 223 for (i = 0; i < ONION_ANNOUNCE_MAX_ENTRIES; ++i) {
213 if (!is_timeout(onion_a->entries[i].time, ONION_ANNOUNCE_TIMEOUT) 224 if (!is_timeout(onion_a->entries[i].time, ONION_ANNOUNCE_TIMEOUT)
214 && public_key_cmp(onion_a->entries[i].public_key, public_key) == 0) 225 && public_key_cmp(onion_a->entries[i].public_key, public_key) == 0) {
215 return i; 226 return i;
227 }
216 } 228 }
217 229
218 return -1; 230 return -1;
@@ -227,22 +239,27 @@ static int cmp_entry(const void *a, const void *b)
227 int t1 = is_timeout(entry1.time, ONION_ANNOUNCE_TIMEOUT); 239 int t1 = is_timeout(entry1.time, ONION_ANNOUNCE_TIMEOUT);
228 int t2 = is_timeout(entry2.time, ONION_ANNOUNCE_TIMEOUT); 240 int t2 = is_timeout(entry2.time, ONION_ANNOUNCE_TIMEOUT);
229 241
230 if (t1 && t2) 242 if (t1 && t2) {
231 return 0; 243 return 0;
244 }
232 245
233 if (t1) 246 if (t1) {
234 return -1; 247 return -1;
248 }
235 249
236 if (t2) 250 if (t2) {
237 return 1; 251 return 1;
252 }
238 253
239 int close = id_closest(cmp_public_key, entry1.public_key, entry2.public_key); 254 int close = id_closest(cmp_public_key, entry1.public_key, entry2.public_key);
240 255
241 if (close == 1) 256 if (close == 1) {
242 return 1; 257 return 1;
258 }
243 259
244 if (close == 2) 260 if (close == 2) {
245 return -1; 261 return -1;
262 }
246 263
247 return 0; 264 return 0;
248} 265}
@@ -262,18 +279,21 @@ static int add_to_entries(Onion_Announce *onion_a, IP_Port ret_ip_port, const ui
262 279
263 if (pos == -1) { 280 if (pos == -1) {
264 for (i = 0; i < ONION_ANNOUNCE_MAX_ENTRIES; ++i) { 281 for (i = 0; i < ONION_ANNOUNCE_MAX_ENTRIES; ++i) {
265 if (is_timeout(onion_a->entries[i].time, ONION_ANNOUNCE_TIMEOUT)) 282 if (is_timeout(onion_a->entries[i].time, ONION_ANNOUNCE_TIMEOUT)) {
266 pos = i; 283 pos = i;
284 }
267 } 285 }
268 } 286 }
269 287
270 if (pos == -1) { 288 if (pos == -1) {
271 if (id_closest(onion_a->dht->self_public_key, public_key, onion_a->entries[0].public_key) == 1) 289 if (id_closest(onion_a->dht->self_public_key, public_key, onion_a->entries[0].public_key) == 1) {
272 pos = 0; 290 pos = 0;
291 }
273 } 292 }
274 293
275 if (pos == -1) 294 if (pos == -1) {
276 return -1; 295 return -1;
296 }
277 297
278 memcpy(onion_a->entries[pos].public_key, public_key, crypto_box_PUBLICKEYBYTES); 298 memcpy(onion_a->entries[pos].public_key, public_key, crypto_box_PUBLICKEYBYTES);
279 onion_a->entries[pos].ret_ip_port = ret_ip_port; 299 onion_a->entries[pos].ret_ip_port = ret_ip_port;
@@ -290,8 +310,9 @@ static int handle_announce_request(void *object, IP_Port source, const uint8_t *
290{ 310{
291 Onion_Announce *onion_a = object; 311 Onion_Announce *onion_a = object;
292 312
293 if (length != ANNOUNCE_REQUEST_SIZE_RECV) 313 if (length != ANNOUNCE_REQUEST_SIZE_RECV) {
294 return 1; 314 return 1;
315 }
295 316
296 const uint8_t *packet_public_key = packet + 1 + crypto_box_NONCEBYTES; 317 const uint8_t *packet_public_key = packet + 1 + crypto_box_NONCEBYTES;
297 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 318 uint8_t shared_key[crypto_box_BEFORENMBYTES];
@@ -303,8 +324,9 @@ static int handle_announce_request(void *object, IP_Port source, const uint8_t *
303 ONION_PING_ID_SIZE + crypto_box_PUBLICKEYBYTES + crypto_box_PUBLICKEYBYTES + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + 324 ONION_PING_ID_SIZE + crypto_box_PUBLICKEYBYTES + crypto_box_PUBLICKEYBYTES + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH +
304 crypto_box_MACBYTES, plain); 325 crypto_box_MACBYTES, plain);
305 326
306 if ((uint32_t)len != sizeof(plain)) 327 if ((uint32_t)len != sizeof(plain)) {
307 return 1; 328 return 1;
329 }
308 330
309 uint8_t ping_id1[ONION_PING_ID_SIZE]; 331 uint8_t ping_id1[ONION_PING_ID_SIZE];
310 generate_ping_id(onion_a, unix_time(), packet_public_key, source, ping_id1); 332 generate_ping_id(onion_a, unix_time(), packet_public_key, source, ping_id1);
@@ -356,16 +378,18 @@ static int handle_announce_request(void *object, IP_Port source, const uint8_t *
356 if (num_nodes != 0) { 378 if (num_nodes != 0) {
357 nodes_length = pack_nodes(pl + 1 + ONION_PING_ID_SIZE, sizeof(nodes_list), nodes_list, num_nodes); 379 nodes_length = pack_nodes(pl + 1 + ONION_PING_ID_SIZE, sizeof(nodes_list), nodes_list, num_nodes);
358 380
359 if (nodes_length <= 0) 381 if (nodes_length <= 0) {
360 return 1; 382 return 1;
383 }
361 } 384 }
362 385
363 uint8_t data[ONION_ANNOUNCE_RESPONSE_MAX_SIZE]; 386 uint8_t data[ONION_ANNOUNCE_RESPONSE_MAX_SIZE];
364 len = encrypt_data_symmetric(shared_key, nonce, pl, 1 + ONION_PING_ID_SIZE + nodes_length, 387 len = encrypt_data_symmetric(shared_key, nonce, pl, 1 + ONION_PING_ID_SIZE + nodes_length,
365 data + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES); 388 data + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES);
366 389
367 if (len != 1 + ONION_PING_ID_SIZE + nodes_length + crypto_box_MACBYTES) 390 if (len != 1 + ONION_PING_ID_SIZE + nodes_length + crypto_box_MACBYTES) {
368 return 1; 391 return 1;
392 }
369 393
370 data[0] = NET_PACKET_ANNOUNCE_RESPONSE; 394 data[0] = NET_PACKET_ANNOUNCE_RESPONSE;
371 memcpy(data + 1, plain + ONION_PING_ID_SIZE + crypto_box_PUBLICKEYBYTES + crypto_box_PUBLICKEYBYTES, 395 memcpy(data + 1, plain + ONION_PING_ID_SIZE + crypto_box_PUBLICKEYBYTES + crypto_box_PUBLICKEYBYTES,
@@ -374,8 +398,9 @@ static int handle_announce_request(void *object, IP_Port source, const uint8_t *
374 398
375 if (send_onion_response(onion_a->net, source, data, 399 if (send_onion_response(onion_a->net, source, data,
376 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES + len, 400 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES + len,
377 packet + (ANNOUNCE_REQUEST_SIZE_RECV - ONION_RETURN_3)) == -1) 401 packet + (ANNOUNCE_REQUEST_SIZE_RECV - ONION_RETURN_3)) == -1) {
378 return 1; 402 return 1;
403 }
379 404
380 return 0; 405 return 0;
381} 406}
@@ -384,37 +409,43 @@ static int handle_data_request(void *object, IP_Port source, const uint8_t *pack
384{ 409{
385 Onion_Announce *onion_a = object; 410 Onion_Announce *onion_a = object;
386 411
387 if (length <= DATA_REQUEST_MIN_SIZE_RECV) 412 if (length <= DATA_REQUEST_MIN_SIZE_RECV) {
388 return 1; 413 return 1;
414 }
389 415
390 if (length > ONION_MAX_PACKET_SIZE) 416 if (length > ONION_MAX_PACKET_SIZE) {
391 return 1; 417 return 1;
418 }
392 419
393 int index = in_entries(onion_a, packet + 1); 420 int index = in_entries(onion_a, packet + 1);
394 421
395 if (index == -1) 422 if (index == -1) {
396 return 1; 423 return 1;
424 }
397 425
398 uint8_t data[length - (crypto_box_PUBLICKEYBYTES + ONION_RETURN_3)]; 426 uint8_t data[length - (crypto_box_PUBLICKEYBYTES + ONION_RETURN_3)];
399 data[0] = NET_PACKET_ONION_DATA_RESPONSE; 427 data[0] = NET_PACKET_ONION_DATA_RESPONSE;
400 memcpy(data + 1, packet + 1 + crypto_box_PUBLICKEYBYTES, length - (1 + crypto_box_PUBLICKEYBYTES + ONION_RETURN_3)); 428 memcpy(data + 1, packet + 1 + crypto_box_PUBLICKEYBYTES, length - (1 + crypto_box_PUBLICKEYBYTES + ONION_RETURN_3));
401 429
402 if (send_onion_response(onion_a->net, onion_a->entries[index].ret_ip_port, data, sizeof(data), 430 if (send_onion_response(onion_a->net, onion_a->entries[index].ret_ip_port, data, sizeof(data),
403 onion_a->entries[index].ret) == -1) 431 onion_a->entries[index].ret) == -1) {
404 return 1; 432 return 1;
433 }
405 434
406 return 0; 435 return 0;
407} 436}
408 437
409Onion_Announce *new_onion_announce(DHT *dht) 438Onion_Announce *new_onion_announce(DHT *dht)
410{ 439{
411 if (dht == NULL) 440 if (dht == NULL) {
412 return NULL; 441 return NULL;
442 }
413 443
414 Onion_Announce *onion_a = calloc(1, sizeof(Onion_Announce)); 444 Onion_Announce *onion_a = calloc(1, sizeof(Onion_Announce));
415 445
416 if (onion_a == NULL) 446 if (onion_a == NULL) {
417 return NULL; 447 return NULL;
448 }
418 449
419 onion_a->dht = dht; 450 onion_a->dht = dht;
420 onion_a->net = dht->net; 451 onion_a->net = dht->net;
@@ -428,8 +459,9 @@ Onion_Announce *new_onion_announce(DHT *dht)
428 459
429void kill_onion_announce(Onion_Announce *onion_a) 460void kill_onion_announce(Onion_Announce *onion_a)
430{ 461{
431 if (onion_a == NULL) 462 if (onion_a == NULL) {
432 return; 463 return;
464 }
433 465
434 networking_registerhandler(onion_a->net, NET_PACKET_ANNOUNCE_REQUEST, NULL, NULL); 466 networking_registerhandler(onion_a->net, NET_PACKET_ANNOUNCE_REQUEST, NULL, NULL);
435 networking_registerhandler(onion_a->net, NET_PACKET_ONION_DATA_REQUEST, NULL, NULL); 467 networking_registerhandler(onion_a->net, NET_PACKET_ONION_DATA_REQUEST, NULL, NULL);
diff --git a/toxcore/onion_client.c b/toxcore/onion_client.c
index 717737ad..c6528c97 100644
--- a/toxcore/onion_client.c
+++ b/toxcore/onion_client.c
@@ -40,14 +40,16 @@
40 */ 40 */
41int onion_add_bs_path_node(Onion_Client *onion_c, IP_Port ip_port, const uint8_t *public_key) 41int onion_add_bs_path_node(Onion_Client *onion_c, IP_Port ip_port, const uint8_t *public_key)
42{ 42{
43 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) 43 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) {
44 return -1; 44 return -1;
45 }
45 46
46 unsigned int i; 47 unsigned int i;
47 48
48 for (i = 0; i < MAX_PATH_NODES; ++i) { 49 for (i = 0; i < MAX_PATH_NODES; ++i) {
49 if (public_key_cmp(public_key, onion_c->path_nodes_bs[i].public_key) == 0) 50 if (public_key_cmp(public_key, onion_c->path_nodes_bs[i].public_key) == 0) {
50 return -1; 51 return -1;
52 }
51 } 53 }
52 54
53 onion_c->path_nodes_bs[onion_c->path_nodes_index_bs % MAX_PATH_NODES].ip_port = ip_port; 55 onion_c->path_nodes_bs[onion_c->path_nodes_index_bs % MAX_PATH_NODES].ip_port = ip_port;
@@ -57,8 +59,9 @@ int onion_add_bs_path_node(Onion_Client *onion_c, IP_Port ip_port, const uint8_t
57 uint16_t last = onion_c->path_nodes_index_bs; 59 uint16_t last = onion_c->path_nodes_index_bs;
58 ++onion_c->path_nodes_index_bs; 60 ++onion_c->path_nodes_index_bs;
59 61
60 if (onion_c->path_nodes_index_bs < last) 62 if (onion_c->path_nodes_index_bs < last) {
61 onion_c->path_nodes_index_bs = MAX_PATH_NODES + 1; 63 onion_c->path_nodes_index_bs = MAX_PATH_NODES + 1;
64 }
62 65
63 return 0; 66 return 0;
64} 67}
@@ -70,14 +73,16 @@ int onion_add_bs_path_node(Onion_Client *onion_c, IP_Port ip_port, const uint8_t
70 */ 73 */
71static int onion_add_path_node(Onion_Client *onion_c, IP_Port ip_port, const uint8_t *public_key) 74static int onion_add_path_node(Onion_Client *onion_c, IP_Port ip_port, const uint8_t *public_key)
72{ 75{
73 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) 76 if (ip_port.ip.family != AF_INET && ip_port.ip.family != AF_INET6) {
74 return -1; 77 return -1;
78 }
75 79
76 unsigned int i; 80 unsigned int i;
77 81
78 for (i = 0; i < MAX_PATH_NODES; ++i) { 82 for (i = 0; i < MAX_PATH_NODES; ++i) {
79 if (public_key_cmp(public_key, onion_c->path_nodes[i].public_key) == 0) 83 if (public_key_cmp(public_key, onion_c->path_nodes[i].public_key) == 0) {
80 return -1; 84 return -1;
85 }
81 } 86 }
82 87
83 onion_c->path_nodes[onion_c->path_nodes_index % MAX_PATH_NODES].ip_port = ip_port; 88 onion_c->path_nodes[onion_c->path_nodes_index % MAX_PATH_NODES].ip_port = ip_port;
@@ -87,8 +92,9 @@ static int onion_add_path_node(Onion_Client *onion_c, IP_Port ip_port, const uin
87 uint16_t last = onion_c->path_nodes_index; 92 uint16_t last = onion_c->path_nodes_index;
88 ++onion_c->path_nodes_index; 93 ++onion_c->path_nodes_index;
89 94
90 if (onion_c->path_nodes_index < last) 95 if (onion_c->path_nodes_index < last) {
91 onion_c->path_nodes_index = MAX_PATH_NODES + 1; 96 onion_c->path_nodes_index = MAX_PATH_NODES + 1;
97 }
92 98
93 return 0; 99 return 0;
94} 100}
@@ -101,16 +107,19 @@ uint16_t onion_backup_nodes(const Onion_Client *onion_c, Node_format *nodes, uin
101{ 107{
102 unsigned int i; 108 unsigned int i;
103 109
104 if (!max_num) 110 if (!max_num) {
105 return 0; 111 return 0;
112 }
106 113
107 unsigned int num_nodes = (onion_c->path_nodes_index < MAX_PATH_NODES) ? onion_c->path_nodes_index : MAX_PATH_NODES; 114 unsigned int num_nodes = (onion_c->path_nodes_index < MAX_PATH_NODES) ? onion_c->path_nodes_index : MAX_PATH_NODES;
108 115
109 if (num_nodes == 0) 116 if (num_nodes == 0) {
110 return 0; 117 return 0;
118 }
111 119
112 if (num_nodes < max_num) 120 if (num_nodes < max_num) {
113 max_num = num_nodes; 121 max_num = num_nodes;
122 }
114 123
115 for (i = 0; i < max_num; ++i) { 124 for (i = 0; i < max_num; ++i) {
116 nodes[i] = onion_c->path_nodes[(onion_c->path_nodes_index - (1 + i)) % num_nodes]; 125 nodes[i] = onion_c->path_nodes[(onion_c->path_nodes_index - (1 + i)) % num_nodes];
@@ -127,15 +136,17 @@ static uint16_t random_nodes_path_onion(const Onion_Client *onion_c, Node_format
127{ 136{
128 unsigned int i; 137 unsigned int i;
129 138
130 if (!max_num) 139 if (!max_num) {
131 return 0; 140 return 0;
141 }
132 142
133 unsigned int num_nodes = (onion_c->path_nodes_index < MAX_PATH_NODES) ? onion_c->path_nodes_index : MAX_PATH_NODES; 143 unsigned int num_nodes = (onion_c->path_nodes_index < MAX_PATH_NODES) ? onion_c->path_nodes_index : MAX_PATH_NODES;
134 144
135 //if (DHT_non_lan_connected(onion_c->dht)) { 145 //if (DHT_non_lan_connected(onion_c->dht)) {
136 if (DHT_isconnected(onion_c->dht)) { 146 if (DHT_isconnected(onion_c->dht)) {
137 if (num_nodes == 0) 147 if (num_nodes == 0) {
138 return 0; 148 return 0;
149 }
139 150
140 for (i = 0; i < max_num; ++i) { 151 for (i = 0; i < max_num; ++i) {
141 nodes[i] = onion_c->path_nodes[rand() % num_nodes]; 152 nodes[i] = onion_c->path_nodes[rand() % num_nodes];
@@ -158,8 +169,9 @@ static uint16_t random_nodes_path_onion(const Onion_Client *onion_c, Node_format
158 unsigned int num_nodes_bs = (onion_c->path_nodes_index_bs < MAX_PATH_NODES) ? onion_c->path_nodes_index_bs : 169 unsigned int num_nodes_bs = (onion_c->path_nodes_index_bs < MAX_PATH_NODES) ? onion_c->path_nodes_index_bs :
159 MAX_PATH_NODES; 170 MAX_PATH_NODES;
160 171
161 if (num_nodes_bs == 0) 172 if (num_nodes_bs == 0) {
162 return 0; 173 return 0;
174 }
163 175
164 nodes[0].ip_port.ip.family = TCP_FAMILY; 176 nodes[0].ip_port.ip.family = TCP_FAMILY;
165 nodes[0].ip_port.ip.ip4.uint32 = random_tcp; 177 nodes[0].ip_port.ip.ip4.uint32 = random_tcp;
@@ -229,14 +241,16 @@ static int random_path(const Onion_Client *onion_c, Onion_Client_Paths *onion_pa
229 if (path_timed_out(onion_paths, pathnum)) { 241 if (path_timed_out(onion_paths, pathnum)) {
230 Node_format nodes[ONION_PATH_LENGTH]; 242 Node_format nodes[ONION_PATH_LENGTH];
231 243
232 if (random_nodes_path_onion(onion_c, nodes, ONION_PATH_LENGTH) != ONION_PATH_LENGTH) 244 if (random_nodes_path_onion(onion_c, nodes, ONION_PATH_LENGTH) != ONION_PATH_LENGTH) {
233 return -1; 245 return -1;
246 }
234 247
235 int n = is_path_used(onion_paths, nodes); 248 int n = is_path_used(onion_paths, nodes);
236 249
237 if (n == -1) { 250 if (n == -1) {
238 if (create_onion_path(onion_c->dht, &onion_paths->paths[pathnum], nodes) == -1) 251 if (create_onion_path(onion_c->dht, &onion_paths->paths[pathnum], nodes) == -1) {
239 return -1; 252 return -1;
253 }
240 254
241 onion_paths->last_path_success[pathnum] = unix_time() + ONION_PATH_FIRST_TIMEOUT - ONION_PATH_TIMEOUT; 255 onion_paths->last_path_success[pathnum] = unix_time() + ONION_PATH_FIRST_TIMEOUT - ONION_PATH_TIMEOUT;
242 onion_paths->path_creation_time[pathnum] = unix_time(); 256 onion_paths->path_creation_time[pathnum] = unix_time();
@@ -262,8 +276,9 @@ static int random_path(const Onion_Client *onion_c, Onion_Client_Paths *onion_pa
262/* Does path with path_num exist. */ 276/* Does path with path_num exist. */
263static _Bool path_exists(Onion_Client_Paths *onion_paths, uint32_t path_num) 277static _Bool path_exists(Onion_Client_Paths *onion_paths, uint32_t path_num)
264{ 278{
265 if (path_timed_out(onion_paths, path_num)) 279 if (path_timed_out(onion_paths, path_num)) {
266 return 0; 280 return 0;
281 }
267 282
268 return onion_paths->paths[path_num % NUMBER_ONION_PATHS].path_num == path_num; 283 return onion_paths->paths[path_num % NUMBER_ONION_PATHS].path_num == path_num;
269} 284}
@@ -273,8 +288,9 @@ static _Bool path_exists(Onion_Client_Paths *onion_paths, uint32_t path_num)
273 */ 288 */
274static uint32_t set_path_timeouts(Onion_Client *onion_c, uint32_t num, uint32_t path_num) 289static uint32_t set_path_timeouts(Onion_Client *onion_c, uint32_t num, uint32_t path_num)
275{ 290{
276 if (num > onion_c->num_friends) 291 if (num > onion_c->num_friends) {
277 return -1; 292 return -1;
293 }
278 294
279 Onion_Client_Paths *onion_paths; 295 Onion_Client_Paths *onion_paths;
280 296
@@ -316,19 +332,22 @@ static int send_onion_packet_tcp_udp(const Onion_Client *onion_c, const Onion_Pa
316 uint8_t packet[ONION_MAX_PACKET_SIZE]; 332 uint8_t packet[ONION_MAX_PACKET_SIZE];
317 int len = create_onion_packet(packet, sizeof(packet), path, dest, data, length); 333 int len = create_onion_packet(packet, sizeof(packet), path, dest, data, length);
318 334
319 if (len == -1) 335 if (len == -1) {
320 return -1; 336 return -1;
337 }
321 338
322 if (sendpacket(onion_c->net, path->ip_port1, packet, len) != len) 339 if (sendpacket(onion_c->net, path->ip_port1, packet, len) != len) {
323 return -1; 340 return -1;
341 }
324 342
325 return 0; 343 return 0;
326 } else if (path->ip_port1.ip.family == TCP_FAMILY) { 344 } else if (path->ip_port1.ip.family == TCP_FAMILY) {
327 uint8_t packet[ONION_MAX_PACKET_SIZE]; 345 uint8_t packet[ONION_MAX_PACKET_SIZE];
328 int len = create_onion_packet_tcp(packet, sizeof(packet), path, dest, data, length); 346 int len = create_onion_packet_tcp(packet, sizeof(packet), path, dest, data, length);
329 347
330 if (len == -1) 348 if (len == -1) {
331 return -1; 349 return -1;
350 }
332 351
333 return send_tcp_onion_request(onion_c->c, path->ip_port1.ip.ip4.uint32, packet, len); 352 return send_tcp_onion_request(onion_c->c, path->ip_port1.ip.ip4.uint32, packet, len);
334 } else { 353 } else {
@@ -361,8 +380,9 @@ static int new_sendback(Onion_Client *onion_c, uint32_t num, const uint8_t *publ
361 memcpy(data + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES + sizeof(IP_Port), &path_num, sizeof(uint32_t)); 380 memcpy(data + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES + sizeof(IP_Port), &path_num, sizeof(uint32_t));
362 *sendback = ping_array_add(&onion_c->announce_ping_array, data, sizeof(data)); 381 *sendback = ping_array_add(&onion_c->announce_ping_array, data, sizeof(data));
363 382
364 if (*sendback == 0) 383 if (*sendback == 0) {
365 return -1; 384 return -1;
385 }
366 386
367 return 0; 387 return 0;
368} 388}
@@ -384,8 +404,9 @@ static uint32_t check_sendback(Onion_Client *onion_c, const uint8_t *sendback, u
384 memcpy(&sback, sendback, sizeof(uint64_t)); 404 memcpy(&sback, sendback, sizeof(uint64_t));
385 uint8_t data[sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES + sizeof(IP_Port) + sizeof(uint32_t)]; 405 uint8_t data[sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES + sizeof(IP_Port) + sizeof(uint32_t)];
386 406
387 if (ping_array_check(data, sizeof(data), &onion_c->announce_ping_array, sback) != sizeof(data)) 407 if (ping_array_check(data, sizeof(data), &onion_c->announce_ping_array, sback) != sizeof(data)) {
388 return ~0; 408 return ~0;
409 }
389 410
390 memcpy(ret_pubkey, data + sizeof(uint32_t), crypto_box_PUBLICKEYBYTES); 411 memcpy(ret_pubkey, data + sizeof(uint32_t), crypto_box_PUBLICKEYBYTES);
391 memcpy(ret_ip_port, data + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES, sizeof(IP_Port)); 412 memcpy(ret_ip_port, data + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES, sizeof(IP_Port));
@@ -399,27 +420,32 @@ static uint32_t check_sendback(Onion_Client *onion_c, const uint8_t *sendback, u
399static int client_send_announce_request(Onion_Client *onion_c, uint32_t num, IP_Port dest, const uint8_t *dest_pubkey, 420static int client_send_announce_request(Onion_Client *onion_c, uint32_t num, IP_Port dest, const uint8_t *dest_pubkey,
400 const uint8_t *ping_id, uint32_t pathnum) 421 const uint8_t *ping_id, uint32_t pathnum)
401{ 422{
402 if (num > onion_c->num_friends) 423 if (num > onion_c->num_friends) {
403 return -1; 424 return -1;
425 }
404 426
405 uint64_t sendback; 427 uint64_t sendback;
406 Onion_Path path; 428 Onion_Path path;
407 429
408 if (num == 0) { 430 if (num == 0) {
409 if (random_path(onion_c, &onion_c->onion_paths_self, pathnum, &path) == -1) 431 if (random_path(onion_c, &onion_c->onion_paths_self, pathnum, &path) == -1) {
410 return -1; 432 return -1;
433 }
411 } else { 434 } else {
412 if (random_path(onion_c, &onion_c->onion_paths_friends, pathnum, &path) == -1) 435 if (random_path(onion_c, &onion_c->onion_paths_friends, pathnum, &path) == -1) {
413 return -1; 436 return -1;
437 }
414 } 438 }
415 439
416 if (new_sendback(onion_c, num, dest_pubkey, dest, path.path_num, &sendback) == -1) 440 if (new_sendback(onion_c, num, dest_pubkey, dest, path.path_num, &sendback) == -1) {
417 return -1; 441 return -1;
442 }
418 443
419 uint8_t zero_ping_id[ONION_PING_ID_SIZE] = {0}; 444 uint8_t zero_ping_id[ONION_PING_ID_SIZE] = {0};
420 445
421 if (ping_id == NULL) 446 if (ping_id == NULL) {
422 ping_id = zero_ping_id; 447 ping_id = zero_ping_id;
448 }
423 449
424 uint8_t request[ONION_ANNOUNCE_REQUEST_SIZE]; 450 uint8_t request[ONION_ANNOUNCE_REQUEST_SIZE];
425 int len; 451 int len;
@@ -450,22 +476,27 @@ static int cmp_entry(const void *a, const void *b)
450 int t1 = is_timeout(entry1.timestamp, ONION_NODE_TIMEOUT); 476 int t1 = is_timeout(entry1.timestamp, ONION_NODE_TIMEOUT);
451 int t2 = is_timeout(entry2.timestamp, ONION_NODE_TIMEOUT); 477 int t2 = is_timeout(entry2.timestamp, ONION_NODE_TIMEOUT);
452 478
453 if (t1 && t2) 479 if (t1 && t2) {
454 return 0; 480 return 0;
481 }
455 482
456 if (t1) 483 if (t1) {
457 return -1; 484 return -1;
485 }
458 486
459 if (t2) 487 if (t2) {
460 return 1; 488 return 1;
489 }
461 490
462 int close = id_closest(cmp_public_key, entry1.public_key, entry2.public_key); 491 int close = id_closest(cmp_public_key, entry1.public_key, entry2.public_key);
463 492
464 if (close == 1) 493 if (close == 1) {
465 return 1; 494 return 1;
495 }
466 496
467 if (close == 2) 497 if (close == 2) {
468 return -1; 498 return -1;
499 }
469 500
470 return 0; 501 return 0;
471} 502}
@@ -473,8 +504,9 @@ static int cmp_entry(const void *a, const void *b)
473static int client_add_to_list(Onion_Client *onion_c, uint32_t num, const uint8_t *public_key, IP_Port ip_port, 504static int client_add_to_list(Onion_Client *onion_c, uint32_t num, const uint8_t *public_key, IP_Port ip_port,
474 uint8_t is_stored, const uint8_t *pingid_or_key, uint32_t path_num) 505 uint8_t is_stored, const uint8_t *pingid_or_key, uint32_t path_num)
475{ 506{
476 if (num > onion_c->num_friends) 507 if (num > onion_c->num_friends) {
477 return -1; 508 return -1;
509 }
478 510
479 Onion_Node *list_nodes = NULL; 511 Onion_Node *list_nodes = NULL;
480 uint8_t *reference_id = NULL; 512 uint8_t *reference_id = NULL;
@@ -490,8 +522,9 @@ static int client_add_to_list(Onion_Client *onion_c, uint32_t num, const uint8_t
490 } 522 }
491 523
492 } else { 524 } else {
493 if (is_stored >= 2) 525 if (is_stored >= 2) {
494 return -1; 526 return -1;
527 }
495 528
496 list_nodes = onion_c->friends_list[num - 1].clients_list; 529 list_nodes = onion_c->friends_list[num - 1].clients_list;
497 reference_id = onion_c->friends_list[num - 1].real_public_key; 530 reference_id = onion_c->friends_list[num - 1].real_public_key;
@@ -517,8 +550,9 @@ static int client_add_to_list(Onion_Client *onion_c, uint32_t num, const uint8_t
517 } 550 }
518 } 551 }
519 552
520 if (index == -1) 553 if (index == -1) {
521 return 0; 554 return 0;
555 }
522 556
523 memcpy(list_nodes[index].public_key, public_key, crypto_box_PUBLICKEYBYTES); 557 memcpy(list_nodes[index].public_key, public_key, crypto_box_PUBLICKEYBYTES);
524 list_nodes[index].ip_port = ip_port; 558 list_nodes[index].ip_port = ip_port;
@@ -535,8 +569,9 @@ static int client_add_to_list(Onion_Client *onion_c, uint32_t num, const uint8_t
535 list_nodes[index].is_stored = is_stored; 569 list_nodes[index].is_stored = is_stored;
536 list_nodes[index].timestamp = unix_time(); 570 list_nodes[index].timestamp = unix_time();
537 571
538 if (!stored) 572 if (!stored) {
539 list_nodes[index].last_pinged = 0; 573 list_nodes[index].last_pinged = 0;
574 }
540 575
541 list_nodes[index].path_used = set_path_timeouts(onion_c, num, path_num); 576 list_nodes[index].path_used = set_path_timeouts(onion_c, num, path_num);
542 return 0; 577 return 0;
@@ -547,9 +582,11 @@ static int good_to_ping(Last_Pinged *last_pinged, uint8_t *last_pinged_index, co
547 unsigned int i; 582 unsigned int i;
548 583
549 for (i = 0; i < MAX_STORED_PINGED_NODES; ++i) { 584 for (i = 0; i < MAX_STORED_PINGED_NODES; ++i) {
550 if (!is_timeout(last_pinged[i].timestamp, MIN_NODE_PING_TIME)) 585 if (!is_timeout(last_pinged[i].timestamp, MIN_NODE_PING_TIME)) {
551 if (public_key_cmp(last_pinged[i].public_key, public_key) == 0) 586 if (public_key_cmp(last_pinged[i].public_key, public_key) == 0) {
552 return 0; 587 return 0;
588 }
589 }
553 } 590 }
554 591
555 memcpy(last_pinged[*last_pinged_index % MAX_STORED_PINGED_NODES].public_key, public_key, crypto_box_PUBLICKEYBYTES); 592 memcpy(last_pinged[*last_pinged_index % MAX_STORED_PINGED_NODES].public_key, public_key, crypto_box_PUBLICKEYBYTES);
@@ -561,11 +598,13 @@ static int good_to_ping(Last_Pinged *last_pinged, uint8_t *last_pinged_index, co
561static int client_ping_nodes(Onion_Client *onion_c, uint32_t num, const Node_format *nodes, uint16_t num_nodes, 598static int client_ping_nodes(Onion_Client *onion_c, uint32_t num, const Node_format *nodes, uint16_t num_nodes,
562 IP_Port source) 599 IP_Port source)
563{ 600{
564 if (num > onion_c->num_friends) 601 if (num > onion_c->num_friends) {
565 return -1; 602 return -1;
603 }
566 604
567 if (num_nodes == 0) 605 if (num_nodes == 0) {
568 return 0; 606 return 0;
607 }
569 608
570 Onion_Node *list_nodes = NULL; 609 Onion_Node *list_nodes = NULL;
571 uint8_t *reference_id = NULL; 610 uint8_t *reference_id = NULL;
@@ -593,9 +632,11 @@ static int client_ping_nodes(Onion_Client *onion_c, uint32_t num, const Node_for
593 632
594 for (i = 0; i < num_nodes; ++i) { 633 for (i = 0; i < num_nodes; ++i) {
595 634
596 if (!lan_ips_accepted) 635 if (!lan_ips_accepted) {
597 if (LAN_ip(nodes[i].ip_port.ip) == 0) 636 if (LAN_ip(nodes[i].ip_port.ip) == 0) {
598 continue; 637 continue;
638 }
639 }
599 640
600 if (is_timeout(list_nodes[0].timestamp, ONION_NODE_TIMEOUT) 641 if (is_timeout(list_nodes[0].timestamp, ONION_NODE_TIMEOUT)
601 || id_closest(reference_id, list_nodes[0].public_key, nodes[i].public_key) == 2 642 || id_closest(reference_id, list_nodes[0].public_key, nodes[i].public_key) == 2
@@ -622,8 +663,9 @@ static int handle_announce_response(void *object, IP_Port source, const uint8_t
622{ 663{
623 Onion_Client *onion_c = object; 664 Onion_Client *onion_c = object;
624 665
625 if (length < ONION_ANNOUNCE_RESPONSE_MIN_SIZE || length > ONION_ANNOUNCE_RESPONSE_MAX_SIZE) 666 if (length < ONION_ANNOUNCE_RESPONSE_MIN_SIZE || length > ONION_ANNOUNCE_RESPONSE_MAX_SIZE) {
626 return 1; 667 return 1;
668 }
627 669
628 uint16_t len_nodes = length - ONION_ANNOUNCE_RESPONSE_MIN_SIZE; 670 uint16_t len_nodes = length - ONION_ANNOUNCE_RESPONSE_MIN_SIZE;
629 671
@@ -632,8 +674,9 @@ static int handle_announce_response(void *object, IP_Port source, const uint8_t
632 uint32_t path_num; 674 uint32_t path_num;
633 uint32_t num = check_sendback(onion_c, packet + 1, public_key, &ip_port, &path_num); 675 uint32_t num = check_sendback(onion_c, packet + 1, public_key, &ip_port, &path_num);
634 676
635 if (num > onion_c->num_friends) 677 if (num > onion_c->num_friends) {
636 return 1; 678 return 1;
679 }
637 680
638 uint8_t plain[1 + ONION_PING_ID_SIZE + len_nodes]; 681 uint8_t plain[1 + ONION_PING_ID_SIZE + len_nodes];
639 int len = -1; 682 int len = -1;
@@ -643,8 +686,9 @@ static int handle_announce_response(void *object, IP_Port source, const uint8_t
643 packet + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES, 686 packet + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES,
644 length - (1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES), plain); 687 length - (1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES), plain);
645 } else { 688 } else {
646 if (onion_c->friends_list[num - 1].status == 0) 689 if (onion_c->friends_list[num - 1].status == 0) {
647 return 1; 690 return 1;
691 }
648 692
649 len = decrypt_data(public_key, onion_c->friends_list[num - 1].temp_secret_key, 693 len = decrypt_data(public_key, onion_c->friends_list[num - 1].temp_secret_key,
650 packet + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH, 694 packet + 1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH,
@@ -652,21 +696,25 @@ static int handle_announce_response(void *object, IP_Port source, const uint8_t
652 length - (1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES), plain); 696 length - (1 + ONION_ANNOUNCE_SENDBACK_DATA_LENGTH + crypto_box_NONCEBYTES), plain);
653 } 697 }
654 698
655 if ((uint32_t)len != sizeof(plain)) 699 if ((uint32_t)len != sizeof(plain)) {
656 return 1; 700 return 1;
701 }
657 702
658 if (client_add_to_list(onion_c, num, public_key, ip_port, plain[0], plain + 1, path_num) == -1) 703 if (client_add_to_list(onion_c, num, public_key, ip_port, plain[0], plain + 1, path_num) == -1) {
659 return 1; 704 return 1;
705 }
660 706
661 if (len_nodes != 0) { 707 if (len_nodes != 0) {
662 Node_format nodes[MAX_SENT_NODES]; 708 Node_format nodes[MAX_SENT_NODES];
663 int num_nodes = unpack_nodes(nodes, MAX_SENT_NODES, 0, plain + 1 + ONION_PING_ID_SIZE, len_nodes, 0); 709 int num_nodes = unpack_nodes(nodes, MAX_SENT_NODES, 0, plain + 1 + ONION_PING_ID_SIZE, len_nodes, 0);
664 710
665 if (num_nodes <= 0) 711 if (num_nodes <= 0) {
666 return 1; 712 return 1;
713 }
667 714
668 if (client_ping_nodes(onion_c, num, nodes, num_nodes, source) == -1) 715 if (client_ping_nodes(onion_c, num, nodes, num_nodes, source) == -1) {
669 return 1; 716 return 1;
717 }
670 } 718 }
671 719
672 //TODO: LAN vs non LAN ips?, if we are connected only to LAN, are we offline? 720 //TODO: LAN vs non LAN ips?, if we are connected only to LAN, are we offline?
@@ -680,29 +728,34 @@ static int handle_data_response(void *object, IP_Port source, const uint8_t *pac
680{ 728{
681 Onion_Client *onion_c = object; 729 Onion_Client *onion_c = object;
682 730
683 if (length <= (ONION_DATA_RESPONSE_MIN_SIZE + DATA_IN_RESPONSE_MIN_SIZE)) 731 if (length <= (ONION_DATA_RESPONSE_MIN_SIZE + DATA_IN_RESPONSE_MIN_SIZE)) {
684 return 1; 732 return 1;
733 }
685 734
686 if (length > MAX_DATA_REQUEST_SIZE) 735 if (length > MAX_DATA_REQUEST_SIZE) {
687 return 1; 736 return 1;
737 }
688 738
689 uint8_t temp_plain[length - ONION_DATA_RESPONSE_MIN_SIZE]; 739 uint8_t temp_plain[length - ONION_DATA_RESPONSE_MIN_SIZE];
690 int len = decrypt_data(packet + 1 + crypto_box_NONCEBYTES, onion_c->temp_secret_key, packet + 1, 740 int len = decrypt_data(packet + 1 + crypto_box_NONCEBYTES, onion_c->temp_secret_key, packet + 1,
691 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES, 741 packet + 1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES,
692 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES), temp_plain); 742 length - (1 + crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES), temp_plain);
693 743
694 if ((uint32_t)len != sizeof(temp_plain)) 744 if ((uint32_t)len != sizeof(temp_plain)) {
695 return 1; 745 return 1;
746 }
696 747
697 uint8_t plain[sizeof(temp_plain) - DATA_IN_RESPONSE_MIN_SIZE]; 748 uint8_t plain[sizeof(temp_plain) - DATA_IN_RESPONSE_MIN_SIZE];
698 len = decrypt_data(temp_plain, onion_c->c->self_secret_key, packet + 1, temp_plain + crypto_box_PUBLICKEYBYTES, 749 len = decrypt_data(temp_plain, onion_c->c->self_secret_key, packet + 1, temp_plain + crypto_box_PUBLICKEYBYTES,
699 sizeof(temp_plain) - crypto_box_PUBLICKEYBYTES, plain); 750 sizeof(temp_plain) - crypto_box_PUBLICKEYBYTES, plain);
700 751
701 if ((uint32_t)len != sizeof(plain)) 752 if ((uint32_t)len != sizeof(plain)) {
702 return 1; 753 return 1;
754 }
703 755
704 if (!onion_c->Onion_Data_Handlers[plain[0]].function) 756 if (!onion_c->Onion_Data_Handlers[plain[0]].function) {
705 return 1; 757 return 1;
758 }
706 759
707 return onion_c->Onion_Data_Handlers[plain[0]].function(onion_c->Onion_Data_Handlers[plain[0]].object, temp_plain, plain, 760 return onion_c->Onion_Data_Handlers[plain[0]].function(onion_c->Onion_Data_Handlers[plain[0]].object, temp_plain, plain,
708 sizeof(plain)); 761 sizeof(plain));
@@ -714,29 +767,34 @@ static int handle_dhtpk_announce(void *object, const uint8_t *source_pubkey, con
714{ 767{
715 Onion_Client *onion_c = object; 768 Onion_Client *onion_c = object;
716 769
717 if (length < DHTPK_DATA_MIN_LENGTH) 770 if (length < DHTPK_DATA_MIN_LENGTH) {
718 return 1; 771 return 1;
772 }
719 773
720 if (length > DHTPK_DATA_MAX_LENGTH) 774 if (length > DHTPK_DATA_MAX_LENGTH) {
721 return 1; 775 return 1;
776 }
722 777
723 int friend_num = onion_friend_num(onion_c, source_pubkey); 778 int friend_num = onion_friend_num(onion_c, source_pubkey);
724 779
725 if (friend_num == -1) 780 if (friend_num == -1) {
726 return 1; 781 return 1;
782 }
727 783
728 uint64_t no_replay; 784 uint64_t no_replay;
729 memcpy(&no_replay, data + 1, sizeof(uint64_t)); 785 memcpy(&no_replay, data + 1, sizeof(uint64_t));
730 net_to_host((uint8_t *) &no_replay, sizeof(no_replay)); 786 net_to_host((uint8_t *) &no_replay, sizeof(no_replay));
731 787
732 if (no_replay <= onion_c->friends_list[friend_num].last_noreplay) 788 if (no_replay <= onion_c->friends_list[friend_num].last_noreplay) {
733 return 1; 789 return 1;
790 }
734 791
735 onion_c->friends_list[friend_num].last_noreplay = no_replay; 792 onion_c->friends_list[friend_num].last_noreplay = no_replay;
736 793
737 if (onion_c->friends_list[friend_num].dht_pk_callback) 794 if (onion_c->friends_list[friend_num].dht_pk_callback) {
738 onion_c->friends_list[friend_num].dht_pk_callback(onion_c->friends_list[friend_num].dht_pk_callback_object, 795 onion_c->friends_list[friend_num].dht_pk_callback(onion_c->friends_list[friend_num].dht_pk_callback_object,
739 onion_c->friends_list[friend_num].dht_pk_callback_number, data + 1 + sizeof(uint64_t)); 796 onion_c->friends_list[friend_num].dht_pk_callback_number, data + 1 + sizeof(uint64_t));
797 }
740 798
741 onion_set_friend_DHT_pubkey(onion_c, friend_num, data + 1 + sizeof(uint64_t)); 799 onion_set_friend_DHT_pubkey(onion_c, friend_num, data + 1 + sizeof(uint64_t));
742 onion_c->friends_list[friend_num].last_seen = unix_time(); 800 onion_c->friends_list[friend_num].last_seen = unix_time();
@@ -748,8 +806,9 @@ static int handle_dhtpk_announce(void *object, const uint8_t *source_pubkey, con
748 int num_nodes = unpack_nodes(nodes, MAX_SENT_NODES, 0, data + 1 + sizeof(uint64_t) + crypto_box_PUBLICKEYBYTES, 806 int num_nodes = unpack_nodes(nodes, MAX_SENT_NODES, 0, data + 1 + sizeof(uint64_t) + crypto_box_PUBLICKEYBYTES,
749 len_nodes, 1); 807 len_nodes, 1);
750 808
751 if (num_nodes <= 0) 809 if (num_nodes <= 0) {
752 return 1; 810 return 1;
811 }
753 812
754 int i; 813 int i;
755 814
@@ -773,8 +832,9 @@ static int handle_dhtpk_announce(void *object, const uint8_t *source_pubkey, con
773 832
774static int handle_tcp_onion(void *object, const uint8_t *data, uint16_t length, void *userdata) 833static int handle_tcp_onion(void *object, const uint8_t *data, uint16_t length, void *userdata)
775{ 834{
776 if (length == 0) 835 if (length == 0) {
777 return 1; 836 return 1;
837 }
778 838
779 IP_Port ip_port = {{0}}; 839 IP_Port ip_port = {{0}};
780 ip_port.ip.family = TCP_FAMILY; 840 ip_port.ip.family = TCP_FAMILY;
@@ -798,21 +858,25 @@ static int handle_tcp_onion(void *object, const uint8_t *data, uint16_t length,
798 */ 858 */
799int send_onion_data(Onion_Client *onion_c, int friend_num, const uint8_t *data, uint16_t length) 859int send_onion_data(Onion_Client *onion_c, int friend_num, const uint8_t *data, uint16_t length)
800{ 860{
801 if ((uint32_t)friend_num >= onion_c->num_friends) 861 if ((uint32_t)friend_num >= onion_c->num_friends) {
802 return -1; 862 return -1;
863 }
803 864
804 if (length + DATA_IN_RESPONSE_MIN_SIZE > MAX_DATA_REQUEST_SIZE) 865 if (length + DATA_IN_RESPONSE_MIN_SIZE > MAX_DATA_REQUEST_SIZE) {
805 return -1; 866 return -1;
867 }
806 868
807 if (length == 0) 869 if (length == 0) {
808 return -1; 870 return -1;
871 }
809 872
810 unsigned int i, good_nodes[MAX_ONION_CLIENTS], num_good = 0, num_nodes = 0; 873 unsigned int i, good_nodes[MAX_ONION_CLIENTS], num_good = 0, num_nodes = 0;
811 Onion_Node *list_nodes = onion_c->friends_list[friend_num].clients_list; 874 Onion_Node *list_nodes = onion_c->friends_list[friend_num].clients_list;
812 875
813 for (i = 0; i < MAX_ONION_CLIENTS; ++i) { 876 for (i = 0; i < MAX_ONION_CLIENTS; ++i) {
814 if (is_timeout(list_nodes[i].timestamp, ONION_NODE_TIMEOUT)) 877 if (is_timeout(list_nodes[i].timestamp, ONION_NODE_TIMEOUT)) {
815 continue; 878 continue;
879 }
816 880
817 ++num_nodes; 881 ++num_nodes;
818 882
@@ -822,8 +886,9 @@ int send_onion_data(Onion_Client *onion_c, int friend_num, const uint8_t *data,
822 } 886 }
823 } 887 }
824 888
825 if (num_good < (num_nodes / 4) + 1) 889 if (num_good < (num_nodes / 4) + 1) {
826 return -1; 890 return -1;
891 }
827 892
828 uint8_t nonce[crypto_box_NONCEBYTES]; 893 uint8_t nonce[crypto_box_NONCEBYTES];
829 random_nonce(nonce); 894 random_nonce(nonce);
@@ -833,26 +898,30 @@ int send_onion_data(Onion_Client *onion_c, int friend_num, const uint8_t *data,
833 int len = encrypt_data(onion_c->friends_list[friend_num].real_public_key, onion_c->c->self_secret_key, nonce, data, 898 int len = encrypt_data(onion_c->friends_list[friend_num].real_public_key, onion_c->c->self_secret_key, nonce, data,
834 length, packet + crypto_box_PUBLICKEYBYTES); 899 length, packet + crypto_box_PUBLICKEYBYTES);
835 900
836 if ((uint32_t)len + crypto_box_PUBLICKEYBYTES != sizeof(packet)) 901 if ((uint32_t)len + crypto_box_PUBLICKEYBYTES != sizeof(packet)) {
837 return -1; 902 return -1;
903 }
838 904
839 unsigned int good = 0; 905 unsigned int good = 0;
840 906
841 for (i = 0; i < num_good; ++i) { 907 for (i = 0; i < num_good; ++i) {
842 Onion_Path path; 908 Onion_Path path;
843 909
844 if (random_path(onion_c, &onion_c->onion_paths_friends, ~0, &path) == -1) 910 if (random_path(onion_c, &onion_c->onion_paths_friends, ~0, &path) == -1) {
845 continue; 911 continue;
912 }
846 913
847 uint8_t o_packet[ONION_MAX_PACKET_SIZE]; 914 uint8_t o_packet[ONION_MAX_PACKET_SIZE];
848 len = create_data_request(o_packet, sizeof(o_packet), onion_c->friends_list[friend_num].real_public_key, 915 len = create_data_request(o_packet, sizeof(o_packet), onion_c->friends_list[friend_num].real_public_key,
849 list_nodes[good_nodes[i]].data_public_key, nonce, packet, sizeof(packet)); 916 list_nodes[good_nodes[i]].data_public_key, nonce, packet, sizeof(packet));
850 917
851 if (len == -1) 918 if (len == -1) {
852 continue; 919 continue;
920 }
853 921
854 if (send_onion_packet_tcp_udp(onion_c, &path, list_nodes[good_nodes[i]].ip_port, o_packet, len) == 0) 922 if (send_onion_packet_tcp_udp(onion_c, &path, list_nodes[good_nodes[i]].ip_port, o_packet, len) == 0) {
855 ++good; 923 ++good;
924 }
856 } 925 }
857 926
858 return good; 927 return good;
@@ -867,11 +936,13 @@ int send_onion_data(Onion_Client *onion_c, int friend_num, const uint8_t *data,
867 */ 936 */
868static int send_dht_dhtpk(const Onion_Client *onion_c, int friend_num, const uint8_t *data, uint16_t length) 937static int send_dht_dhtpk(const Onion_Client *onion_c, int friend_num, const uint8_t *data, uint16_t length)
869{ 938{
870 if ((uint32_t)friend_num >= onion_c->num_friends) 939 if ((uint32_t)friend_num >= onion_c->num_friends) {
871 return -1; 940 return -1;
941 }
872 942
873 if (!onion_c->friends_list[friend_num].know_dht_public_key) 943 if (!onion_c->friends_list[friend_num].know_dht_public_key) {
874 return -1; 944 return -1;
945 }
875 946
876 uint8_t nonce[crypto_box_NONCEBYTES]; 947 uint8_t nonce[crypto_box_NONCEBYTES];
877 new_nonce(nonce); 948 new_nonce(nonce);
@@ -882,15 +953,17 @@ static int send_dht_dhtpk(const Onion_Client *onion_c, int friend_num, const uin
882 int len = encrypt_data(onion_c->friends_list[friend_num].real_public_key, onion_c->c->self_secret_key, nonce, data, 953 int len = encrypt_data(onion_c->friends_list[friend_num].real_public_key, onion_c->c->self_secret_key, nonce, data,
883 length, temp + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES); 954 length, temp + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
884 955
885 if ((uint32_t)len + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES != sizeof(temp)) 956 if ((uint32_t)len + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES != sizeof(temp)) {
886 return -1; 957 return -1;
958 }
887 959
888 uint8_t packet[MAX_CRYPTO_REQUEST_SIZE]; 960 uint8_t packet[MAX_CRYPTO_REQUEST_SIZE];
889 len = create_request(onion_c->dht->self_public_key, onion_c->dht->self_secret_key, packet, 961 len = create_request(onion_c->dht->self_public_key, onion_c->dht->self_secret_key, packet,
890 onion_c->friends_list[friend_num].dht_public_key, temp, sizeof(temp), CRYPTO_PACKET_DHTPK); 962 onion_c->friends_list[friend_num].dht_public_key, temp, sizeof(temp), CRYPTO_PACKET_DHTPK);
891 963
892 if (len == -1) 964 if (len == -1) {
893 return -1; 965 return -1;
966 }
894 967
895 return route_tofriend(onion_c->dht, onion_c->friends_list[friend_num].dht_public_key, packet, len); 968 return route_tofriend(onion_c->dht, onion_c->friends_list[friend_num].dht_public_key, packet, len);
896} 969}
@@ -900,22 +973,26 @@ static int handle_dht_dhtpk(void *object, IP_Port source, const uint8_t *source_
900{ 973{
901 Onion_Client *onion_c = object; 974 Onion_Client *onion_c = object;
902 975
903 if (length < DHTPK_DATA_MIN_LENGTH + DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES) 976 if (length < DHTPK_DATA_MIN_LENGTH + DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES) {
904 return 1; 977 return 1;
978 }
905 979
906 if (length > DHTPK_DATA_MAX_LENGTH + DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES) 980 if (length > DHTPK_DATA_MAX_LENGTH + DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES) {
907 return 1; 981 return 1;
982 }
908 983
909 uint8_t plain[DHTPK_DATA_MAX_LENGTH]; 984 uint8_t plain[DHTPK_DATA_MAX_LENGTH];
910 int len = decrypt_data(packet, onion_c->c->self_secret_key, packet + crypto_box_PUBLICKEYBYTES, 985 int len = decrypt_data(packet, onion_c->c->self_secret_key, packet + crypto_box_PUBLICKEYBYTES,
911 packet + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES, 986 packet + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES,
912 length - (crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES), plain); 987 length - (crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES), plain);
913 988
914 if (len != length - (DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES)) 989 if (len != length - (DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES)) {
915 return 1; 990 return 1;
991 }
916 992
917 if (public_key_cmp(source_pubkey, plain + 1 + sizeof(uint64_t)) != 0) 993 if (public_key_cmp(source_pubkey, plain + 1 + sizeof(uint64_t)) != 0) {
918 return 1; 994 return 1;
995 }
919 996
920 return handle_dhtpk_announce(onion_c, packet, plain, len); 997 return handle_dhtpk_announce(onion_c, packet, plain, len);
921} 998}
@@ -930,8 +1007,9 @@ static int handle_dht_dhtpk(void *object, IP_Port source, const uint8_t *source_
930 */ 1007 */
931static int send_dhtpk_announce(Onion_Client *onion_c, uint16_t friend_num, uint8_t onion_dht_both) 1008static int send_dhtpk_announce(Onion_Client *onion_c, uint16_t friend_num, uint8_t onion_dht_both)
932{ 1009{
933 if (friend_num >= onion_c->num_friends) 1010 if (friend_num >= onion_c->num_friends) {
934 return -1; 1011 return -1;
1012 }
935 1013
936 uint8_t data[DHTPK_DATA_MAX_LENGTH]; 1014 uint8_t data[DHTPK_DATA_MAX_LENGTH];
937 data[0] = ONION_DATA_DHTPK; 1015 data[0] = ONION_DATA_DHTPK;
@@ -949,23 +1027,28 @@ static int send_dhtpk_announce(Onion_Client *onion_c, uint16_t friend_num, uint8
949 nodes_len = pack_nodes(data + DHTPK_DATA_MIN_LENGTH, DHTPK_DATA_MAX_LENGTH - DHTPK_DATA_MIN_LENGTH, nodes, 1027 nodes_len = pack_nodes(data + DHTPK_DATA_MIN_LENGTH, DHTPK_DATA_MAX_LENGTH - DHTPK_DATA_MIN_LENGTH, nodes,
950 num_nodes); 1028 num_nodes);
951 1029
952 if (nodes_len <= 0) 1030 if (nodes_len <= 0) {
953 return -1; 1031 return -1;
1032 }
954 } 1033 }
955 1034
956 int num1 = -1, num2 = -1; 1035 int num1 = -1, num2 = -1;
957 1036
958 if (onion_dht_both != 1) 1037 if (onion_dht_both != 1) {
959 num1 = send_onion_data(onion_c, friend_num, data, DHTPK_DATA_MIN_LENGTH + nodes_len); 1038 num1 = send_onion_data(onion_c, friend_num, data, DHTPK_DATA_MIN_LENGTH + nodes_len);
1039 }
960 1040
961 if (onion_dht_both != 0) 1041 if (onion_dht_both != 0) {
962 num2 = send_dht_dhtpk(onion_c, friend_num, data, DHTPK_DATA_MIN_LENGTH + nodes_len); 1042 num2 = send_dht_dhtpk(onion_c, friend_num, data, DHTPK_DATA_MIN_LENGTH + nodes_len);
1043 }
963 1044
964 if (num1 == -1) 1045 if (num1 == -1) {
965 return num2; 1046 return num2;
1047 }
966 1048
967 if (num2 == -1) 1049 if (num2 == -1) {
968 return num1; 1050 return num1;
1051 }
969 1052
970 return num1 + num2; 1053 return num1 + num2;
971} 1054}
@@ -980,11 +1063,13 @@ int onion_friend_num(const Onion_Client *onion_c, const uint8_t *public_key)
980 unsigned int i; 1063 unsigned int i;
981 1064
982 for (i = 0; i < onion_c->num_friends; ++i) { 1065 for (i = 0; i < onion_c->num_friends; ++i) {
983 if (onion_c->friends_list[i].status == 0) 1066 if (onion_c->friends_list[i].status == 0) {
984 continue; 1067 continue;
1068 }
985 1069
986 if (public_key_cmp(public_key, onion_c->friends_list[i].real_public_key) == 0) 1070 if (public_key_cmp(public_key, onion_c->friends_list[i].real_public_key) == 0) {
987 return i; 1071 return i;
1072 }
988 } 1073 }
989 1074
990 return -1; 1075 return -1;
@@ -1005,8 +1090,9 @@ static int realloc_onion_friends(Onion_Client *onion_c, uint32_t num)
1005 1090
1006 Onion_Friend *newonion_friends = realloc(onion_c->friends_list, num * sizeof(Onion_Friend)); 1091 Onion_Friend *newonion_friends = realloc(onion_c->friends_list, num * sizeof(Onion_Friend));
1007 1092
1008 if (newonion_friends == NULL) 1093 if (newonion_friends == NULL) {
1009 return -1; 1094 return -1;
1095 }
1010 1096
1011 onion_c->friends_list = newonion_friends; 1097 onion_c->friends_list = newonion_friends;
1012 return 0; 1098 return 0;
@@ -1021,8 +1107,9 @@ int onion_addfriend(Onion_Client *onion_c, const uint8_t *public_key)
1021{ 1107{
1022 int num = onion_friend_num(onion_c, public_key); 1108 int num = onion_friend_num(onion_c, public_key);
1023 1109
1024 if (num != -1) 1110 if (num != -1) {
1025 return num; 1111 return num;
1112 }
1026 1113
1027 unsigned int i, index = ~0; 1114 unsigned int i, index = ~0;
1028 1115
@@ -1034,8 +1121,9 @@ int onion_addfriend(Onion_Client *onion_c, const uint8_t *public_key)
1034 } 1121 }
1035 1122
1036 if (index == (uint32_t)~0) { 1123 if (index == (uint32_t)~0) {
1037 if (realloc_onion_friends(onion_c, onion_c->num_friends + 1) == -1) 1124 if (realloc_onion_friends(onion_c, onion_c->num_friends + 1) == -1) {
1038 return -1; 1125 return -1;
1126 }
1039 1127
1040 index = onion_c->num_friends; 1128 index = onion_c->num_friends;
1041 memset(&(onion_c->friends_list[onion_c->num_friends]), 0, sizeof(Onion_Friend)); 1129 memset(&(onion_c->friends_list[onion_c->num_friends]), 0, sizeof(Onion_Friend));
@@ -1055,8 +1143,9 @@ int onion_addfriend(Onion_Client *onion_c, const uint8_t *public_key)
1055 */ 1143 */
1056int onion_delfriend(Onion_Client *onion_c, int friend_num) 1144int onion_delfriend(Onion_Client *onion_c, int friend_num)
1057{ 1145{
1058 if ((uint32_t)friend_num >= onion_c->num_friends) 1146 if ((uint32_t)friend_num >= onion_c->num_friends) {
1059 return -1; 1147 return -1;
1148 }
1060 1149
1061 //if (onion_c->friends_list[friend_num].know_dht_public_key) 1150 //if (onion_c->friends_list[friend_num].know_dht_public_key)
1062 // DHT_delfriend(onion_c->dht, onion_c->friends_list[friend_num].dht_public_key, 0); 1151 // DHT_delfriend(onion_c->dht, onion_c->friends_list[friend_num].dht_public_key, 0);
@@ -1065,8 +1154,9 @@ int onion_delfriend(Onion_Client *onion_c, int friend_num)
1065 unsigned int i; 1154 unsigned int i;
1066 1155
1067 for (i = onion_c->num_friends; i != 0; --i) { 1156 for (i = onion_c->num_friends; i != 0; --i) {
1068 if (onion_c->friends_list[i - 1].status != 0) 1157 if (onion_c->friends_list[i - 1].status != 0) {
1069 break; 1158 break;
1159 }
1070 } 1160 }
1071 1161
1072 if (onion_c->num_friends != i) { 1162 if (onion_c->num_friends != i) {
@@ -1088,8 +1178,9 @@ int onion_delfriend(Onion_Client *onion_c, int friend_num)
1088int recv_tcp_relay_handler(Onion_Client *onion_c, int friend_num, int (*tcp_relay_node_callback)(void *object, 1178int recv_tcp_relay_handler(Onion_Client *onion_c, int friend_num, int (*tcp_relay_node_callback)(void *object,
1089 uint32_t number, IP_Port ip_port, const uint8_t *public_key), void *object, uint32_t number) 1179 uint32_t number, IP_Port ip_port, const uint8_t *public_key), void *object, uint32_t number)
1090{ 1180{
1091 if ((uint32_t)friend_num >= onion_c->num_friends) 1181 if ((uint32_t)friend_num >= onion_c->num_friends) {
1092 return -1; 1182 return -1;
1183 }
1093 1184
1094 onion_c->friends_list[friend_num].tcp_relay_node_callback = tcp_relay_node_callback; 1185 onion_c->friends_list[friend_num].tcp_relay_node_callback = tcp_relay_node_callback;
1095 onion_c->friends_list[friend_num].tcp_relay_node_callback_object = object; 1186 onion_c->friends_list[friend_num].tcp_relay_node_callback_object = object;
@@ -1108,8 +1199,9 @@ int recv_tcp_relay_handler(Onion_Client *onion_c, int friend_num, int (*tcp_rela
1108int onion_dht_pk_callback(Onion_Client *onion_c, int friend_num, void (*function)(void *data, int32_t number, 1199int onion_dht_pk_callback(Onion_Client *onion_c, int friend_num, void (*function)(void *data, int32_t number,
1109 const uint8_t *dht_public_key), void *object, uint32_t number) 1200 const uint8_t *dht_public_key), void *object, uint32_t number)
1110{ 1201{
1111 if ((uint32_t)friend_num >= onion_c->num_friends) 1202 if ((uint32_t)friend_num >= onion_c->num_friends) {
1112 return -1; 1203 return -1;
1204 }
1113 1205
1114 onion_c->friends_list[friend_num].dht_pk_callback = function; 1206 onion_c->friends_list[friend_num].dht_pk_callback = function;
1115 onion_c->friends_list[friend_num].dht_pk_callback_object = object; 1207 onion_c->friends_list[friend_num].dht_pk_callback_object = object;
@@ -1124,11 +1216,13 @@ int onion_dht_pk_callback(Onion_Client *onion_c, int friend_num, void (*function
1124 */ 1216 */
1125int onion_set_friend_DHT_pubkey(Onion_Client *onion_c, int friend_num, const uint8_t *dht_key) 1217int onion_set_friend_DHT_pubkey(Onion_Client *onion_c, int friend_num, const uint8_t *dht_key)
1126{ 1218{
1127 if ((uint32_t)friend_num >= onion_c->num_friends) 1219 if ((uint32_t)friend_num >= onion_c->num_friends) {
1128 return -1; 1220 return -1;
1221 }
1129 1222
1130 if (onion_c->friends_list[friend_num].status == 0) 1223 if (onion_c->friends_list[friend_num].status == 0) {
1131 return -1; 1224 return -1;
1225 }
1132 1226
1133 if (onion_c->friends_list[friend_num].know_dht_public_key) { 1227 if (onion_c->friends_list[friend_num].know_dht_public_key) {
1134 if (public_key_cmp(dht_key, onion_c->friends_list[friend_num].dht_public_key) == 0) { 1228 if (public_key_cmp(dht_key, onion_c->friends_list[friend_num].dht_public_key) == 0) {
@@ -1152,14 +1246,17 @@ int onion_set_friend_DHT_pubkey(Onion_Client *onion_c, int friend_num, const uin
1152 */ 1246 */
1153unsigned int onion_getfriend_DHT_pubkey(const Onion_Client *onion_c, int friend_num, uint8_t *dht_key) 1247unsigned int onion_getfriend_DHT_pubkey(const Onion_Client *onion_c, int friend_num, uint8_t *dht_key)
1154{ 1248{
1155 if ((uint32_t)friend_num >= onion_c->num_friends) 1249 if ((uint32_t)friend_num >= onion_c->num_friends) {
1156 return 0; 1250 return 0;
1251 }
1157 1252
1158 if (onion_c->friends_list[friend_num].status == 0) 1253 if (onion_c->friends_list[friend_num].status == 0) {
1159 return 0; 1254 return 0;
1255 }
1160 1256
1161 if (!onion_c->friends_list[friend_num].know_dht_public_key) 1257 if (!onion_c->friends_list[friend_num].know_dht_public_key) {
1162 return 0; 1258 return 0;
1259 }
1163 1260
1164 memcpy(dht_key, onion_c->friends_list[friend_num].dht_public_key, crypto_box_PUBLICKEYBYTES); 1261 memcpy(dht_key, onion_c->friends_list[friend_num].dht_public_key, crypto_box_PUBLICKEYBYTES);
1165 return 1; 1262 return 1;
@@ -1176,8 +1273,9 @@ int onion_getfriendip(const Onion_Client *onion_c, int friend_num, IP_Port *ip_p
1176{ 1273{
1177 uint8_t dht_public_key[crypto_box_PUBLICKEYBYTES]; 1274 uint8_t dht_public_key[crypto_box_PUBLICKEYBYTES];
1178 1275
1179 if (onion_getfriend_DHT_pubkey(onion_c, friend_num, dht_public_key) == 0) 1276 if (onion_getfriend_DHT_pubkey(onion_c, friend_num, dht_public_key) == 0) {
1180 return -1; 1277 return -1;
1278 }
1181 1279
1182 return DHT_getfriendip(onion_c->dht, dht_public_key, ip_port); 1280 return DHT_getfriendip(onion_c->dht, dht_public_key, ip_port);
1183} 1281}
@@ -1194,11 +1292,13 @@ int onion_getfriendip(const Onion_Client *onion_c, int friend_num, IP_Port *ip_p
1194 */ 1292 */
1195int onion_set_friend_online(Onion_Client *onion_c, int friend_num, uint8_t is_online) 1293int onion_set_friend_online(Onion_Client *onion_c, int friend_num, uint8_t is_online)
1196{ 1294{
1197 if ((uint32_t)friend_num >= onion_c->num_friends) 1295 if ((uint32_t)friend_num >= onion_c->num_friends) {
1198 return -1; 1296 return -1;
1297 }
1199 1298
1200 if (is_online == 0 && onion_c->friends_list[friend_num].is_online == 1) 1299 if (is_online == 0 && onion_c->friends_list[friend_num].is_online == 1) {
1201 onion_c->friends_list[friend_num].last_seen = unix_time(); 1300 onion_c->friends_list[friend_num].last_seen = unix_time();
1301 }
1202 1302
1203 onion_c->friends_list[friend_num].is_online = is_online; 1303 onion_c->friends_list[friend_num].is_online = is_online;
1204 1304
@@ -1244,24 +1344,28 @@ static void populate_path_nodes_tcp(Onion_Client *onion_c)
1244 1344
1245static void do_friend(Onion_Client *onion_c, uint16_t friendnum) 1345static void do_friend(Onion_Client *onion_c, uint16_t friendnum)
1246{ 1346{
1247 if (friendnum >= onion_c->num_friends) 1347 if (friendnum >= onion_c->num_friends) {
1248 return; 1348 return;
1349 }
1249 1350
1250 if (onion_c->friends_list[friendnum].status == 0) 1351 if (onion_c->friends_list[friendnum].status == 0) {
1251 return; 1352 return;
1353 }
1252 1354
1253 unsigned int interval = ANNOUNCE_FRIEND; 1355 unsigned int interval = ANNOUNCE_FRIEND;
1254 1356
1255 if (onion_c->friends_list[friendnum].run_count < RUN_COUNT_FRIEND_ANNOUNCE_BEGINNING) 1357 if (onion_c->friends_list[friendnum].run_count < RUN_COUNT_FRIEND_ANNOUNCE_BEGINNING) {
1256 interval = ANNOUNCE_FRIEND_BEGINNING; 1358 interval = ANNOUNCE_FRIEND_BEGINNING;
1359 }
1257 1360
1258 unsigned int i, count = 0; 1361 unsigned int i, count = 0;
1259 Onion_Node *list_nodes = onion_c->friends_list[friendnum].clients_list; 1362 Onion_Node *list_nodes = onion_c->friends_list[friendnum].clients_list;
1260 1363
1261 if (!onion_c->friends_list[friendnum].is_online) { 1364 if (!onion_c->friends_list[friendnum].is_online) {
1262 for (i = 0; i < MAX_ONION_CLIENTS; ++i) { 1365 for (i = 0; i < MAX_ONION_CLIENTS; ++i) {
1263 if (is_timeout(list_nodes[i].timestamp, FRIEND_ONION_NODE_TIMEOUT)) 1366 if (is_timeout(list_nodes[i].timestamp, FRIEND_ONION_NODE_TIMEOUT)) {
1264 continue; 1367 continue;
1368 }
1265 1369
1266 ++count; 1370 ++count;
1267 1371
@@ -1283,8 +1387,9 @@ static void do_friend(Onion_Client *onion_c, uint16_t friendnum)
1283 1387
1284 unsigned int n = num_nodes; 1388 unsigned int n = num_nodes;
1285 1389
1286 if (num_nodes > (MAX_ONION_CLIENTS / 2)) 1390 if (num_nodes > (MAX_ONION_CLIENTS / 2)) {
1287 n = (MAX_ONION_CLIENTS / 2); 1391 n = (MAX_ONION_CLIENTS / 2);
1392 }
1288 1393
1289 if (num_nodes != 0) { 1394 if (num_nodes != 0) {
1290 unsigned int j; 1395 unsigned int j;
@@ -1302,13 +1407,17 @@ static void do_friend(Onion_Client *onion_c, uint16_t friendnum)
1302 } 1407 }
1303 1408
1304 /* send packets to friend telling them our DHT public key. */ 1409 /* send packets to friend telling them our DHT public key. */
1305 if (is_timeout(onion_c->friends_list[friendnum].last_dht_pk_onion_sent, ONION_DHTPK_SEND_INTERVAL)) 1410 if (is_timeout(onion_c->friends_list[friendnum].last_dht_pk_onion_sent, ONION_DHTPK_SEND_INTERVAL)) {
1306 if (send_dhtpk_announce(onion_c, friendnum, 0) >= 1) 1411 if (send_dhtpk_announce(onion_c, friendnum, 0) >= 1) {
1307 onion_c->friends_list[friendnum].last_dht_pk_onion_sent = unix_time(); 1412 onion_c->friends_list[friendnum].last_dht_pk_onion_sent = unix_time();
1413 }
1414 }
1308 1415
1309 if (is_timeout(onion_c->friends_list[friendnum].last_dht_pk_dht_sent, DHT_DHTPK_SEND_INTERVAL)) 1416 if (is_timeout(onion_c->friends_list[friendnum].last_dht_pk_dht_sent, DHT_DHTPK_SEND_INTERVAL)) {
1310 if (send_dhtpk_announce(onion_c, friendnum, 1) >= 1) 1417 if (send_dhtpk_announce(onion_c, friendnum, 1) >= 1) {
1311 onion_c->friends_list[friendnum].last_dht_pk_dht_sent = unix_time(); 1418 onion_c->friends_list[friendnum].last_dht_pk_dht_sent = unix_time();
1419 }
1420 }
1312 1421
1313 } 1422 }
1314} 1423}
@@ -1330,8 +1439,9 @@ static void do_announce(Onion_Client *onion_c)
1330 Onion_Node *list_nodes = onion_c->clients_announce_list; 1439 Onion_Node *list_nodes = onion_c->clients_announce_list;
1331 1440
1332 for (i = 0; i < MAX_ONION_CLIENTS_ANNOUNCE; ++i) { 1441 for (i = 0; i < MAX_ONION_CLIENTS_ANNOUNCE; ++i) {
1333 if (is_timeout(list_nodes[i].timestamp, ONION_NODE_TIMEOUT)) 1442 if (is_timeout(list_nodes[i].timestamp, ONION_NODE_TIMEOUT)) {
1334 continue; 1443 continue;
1444 }
1335 1445
1336 ++count; 1446 ++count;
1337 1447
@@ -1385,11 +1495,13 @@ static int onion_isconnected(const Onion_Client *onion_c)
1385{ 1495{
1386 unsigned int i, num = 0, announced = 0; 1496 unsigned int i, num = 0, announced = 0;
1387 1497
1388 if (is_timeout(onion_c->last_packet_recv, ONION_OFFLINE_TIMEOUT)) 1498 if (is_timeout(onion_c->last_packet_recv, ONION_OFFLINE_TIMEOUT)) {
1389 return 0; 1499 return 0;
1500 }
1390 1501
1391 if (onion_c->path_nodes_index == 0) 1502 if (onion_c->path_nodes_index == 0) {
1392 return 0; 1503 return 0;
1504 }
1393 1505
1394 for (i = 0; i < MAX_ONION_CLIENTS_ANNOUNCE; ++i) { 1506 for (i = 0; i < MAX_ONION_CLIENTS_ANNOUNCE; ++i) {
1395 if (!is_timeout(onion_c->clients_announce_list[i].timestamp, ONION_NODE_TIMEOUT)) { 1507 if (!is_timeout(onion_c->clients_announce_list[i].timestamp, ONION_NODE_TIMEOUT)) {
@@ -1410,8 +1522,9 @@ static int onion_isconnected(const Onion_Client *onion_c)
1410 /* Consider ourselves online if we are announced to half or more nodes 1522 /* Consider ourselves online if we are announced to half or more nodes
1411 we are connected to */ 1523 we are connected to */
1412 if (num && announced) { 1524 if (num && announced) {
1413 if ((num / 2) <= announced && (pnodes / 2) <= num) 1525 if ((num / 2) <= announced && (pnodes / 2) <= num) {
1414 return 1; 1526 return 1;
1527 }
1415 } 1528 }
1416 1529
1417 return 0; 1530 return 0;
@@ -1440,8 +1553,9 @@ void do_onion_client(Onion_Client *onion_c)
1440{ 1553{
1441 unsigned int i; 1554 unsigned int i;
1442 1555
1443 if (onion_c->last_run == unix_time()) 1556 if (onion_c->last_run == unix_time()) {
1444 return; 1557 return;
1558 }
1445 1559
1446 if (is_timeout(onion_c->first_run, ONION_CONNECTION_SECONDS)) { 1560 if (is_timeout(onion_c->first_run, ONION_CONNECTION_SECONDS)) {
1447 populate_path_nodes(onion_c); 1561 populate_path_nodes(onion_c);
@@ -1485,13 +1599,15 @@ void do_onion_client(Onion_Client *onion_c)
1485 1599
1486Onion_Client *new_onion_client(Net_Crypto *c) 1600Onion_Client *new_onion_client(Net_Crypto *c)
1487{ 1601{
1488 if (c == NULL) 1602 if (c == NULL) {
1489 return NULL; 1603 return NULL;
1604 }
1490 1605
1491 Onion_Client *onion_c = calloc(1, sizeof(Onion_Client)); 1606 Onion_Client *onion_c = calloc(1, sizeof(Onion_Client));
1492 1607
1493 if (onion_c == NULL) 1608 if (onion_c == NULL) {
1494 return NULL; 1609 return NULL;
1610 }
1495 1611
1496 if (ping_array_init(&onion_c->announce_ping_array, ANNOUNCE_ARRAY_SIZE, ANNOUNCE_TIMEOUT) != 0) { 1612 if (ping_array_init(&onion_c->announce_ping_array, ANNOUNCE_ARRAY_SIZE, ANNOUNCE_TIMEOUT) != 0) {
1497 free(onion_c); 1613 free(onion_c);
@@ -1514,8 +1630,9 @@ Onion_Client *new_onion_client(Net_Crypto *c)
1514 1630
1515void kill_onion_client(Onion_Client *onion_c) 1631void kill_onion_client(Onion_Client *onion_c)
1516{ 1632{
1517 if (onion_c == NULL) 1633 if (onion_c == NULL) {
1518 return; 1634 return;
1635 }
1519 1636
1520 ping_array_free_all(&onion_c->announce_ping_array); 1637 ping_array_free_all(&onion_c->announce_ping_array);
1521 realloc_onion_friends(onion_c, 0); 1638 realloc_onion_friends(onion_c, 0);
diff --git a/toxcore/ping.c b/toxcore/ping.c
index dc0a01f3..8993c6b2 100644
--- a/toxcore/ping.c
+++ b/toxcore/ping.c
@@ -64,8 +64,9 @@ int send_ping_request(PING *ping, IP_Port ipp, const uint8_t *public_key)
64 int rc; 64 int rc;
65 uint64_t ping_id; 65 uint64_t ping_id;
66 66
67 if (id_equal(public_key, ping->dht->self_public_key)) 67 if (id_equal(public_key, ping->dht->self_public_key)) {
68 return 1; 68 return 1;
69 }
69 70
70 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 71 uint8_t shared_key[crypto_box_BEFORENMBYTES];
71 72
@@ -77,8 +78,9 @@ int send_ping_request(PING *ping, IP_Port ipp, const uint8_t *public_key)
77 memcpy(data + crypto_box_PUBLICKEYBYTES, &ipp, sizeof(IP_Port)); 78 memcpy(data + crypto_box_PUBLICKEYBYTES, &ipp, sizeof(IP_Port));
78 ping_id = ping_array_add(&ping->ping_array, data, sizeof(data)); 79 ping_id = ping_array_add(&ping->ping_array, data, sizeof(data));
79 80
80 if (ping_id == 0) 81 if (ping_id == 0) {
81 return 1; 82 return 1;
83 }
82 84
83 uint8_t ping_plain[PING_PLAIN_SIZE]; 85 uint8_t ping_plain[PING_PLAIN_SIZE];
84 ping_plain[0] = NET_PACKET_PING_REQUEST; 86 ping_plain[0] = NET_PACKET_PING_REQUEST;
@@ -94,8 +96,9 @@ int send_ping_request(PING *ping, IP_Port ipp, const uint8_t *public_key)
94 ping_plain, sizeof(ping_plain), 96 ping_plain, sizeof(ping_plain),
95 pk + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES); 97 pk + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
96 98
97 if (rc != PING_PLAIN_SIZE + crypto_box_MACBYTES) 99 if (rc != PING_PLAIN_SIZE + crypto_box_MACBYTES) {
98 return 1; 100 return 1;
101 }
99 102
100 return sendpacket(ping->dht->net, ipp, pk, sizeof(pk)); 103 return sendpacket(ping->dht->net, ipp, pk, sizeof(pk));
101} 104}
@@ -106,8 +109,9 @@ static int send_ping_response(PING *ping, IP_Port ipp, const uint8_t *public_key
106 uint8_t pk[DHT_PING_SIZE]; 109 uint8_t pk[DHT_PING_SIZE];
107 int rc; 110 int rc;
108 111
109 if (id_equal(public_key, ping->dht->self_public_key)) 112 if (id_equal(public_key, ping->dht->self_public_key)) {
110 return 1; 113 return 1;
114 }
111 115
112 uint8_t ping_plain[PING_PLAIN_SIZE]; 116 uint8_t ping_plain[PING_PLAIN_SIZE];
113 ping_plain[0] = NET_PACKET_PING_RESPONSE; 117 ping_plain[0] = NET_PACKET_PING_RESPONSE;
@@ -123,8 +127,9 @@ static int send_ping_response(PING *ping, IP_Port ipp, const uint8_t *public_key
123 ping_plain, sizeof(ping_plain), 127 ping_plain, sizeof(ping_plain),
124 pk + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES ); 128 pk + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES );
125 129
126 if (rc != PING_PLAIN_SIZE + crypto_box_MACBYTES) 130 if (rc != PING_PLAIN_SIZE + crypto_box_MACBYTES) {
127 return 1; 131 return 1;
132 }
128 133
129 return sendpacket(ping->dht->net, ipp, pk, sizeof(pk)); 134 return sendpacket(ping->dht->net, ipp, pk, sizeof(pk));
130} 135}
@@ -134,13 +139,15 @@ static int handle_ping_request(void *_dht, IP_Port source, const uint8_t *packet
134 DHT *dht = _dht; 139 DHT *dht = _dht;
135 int rc; 140 int rc;
136 141
137 if (length != DHT_PING_SIZE) 142 if (length != DHT_PING_SIZE) {
138 return 1; 143 return 1;
144 }
139 145
140 PING *ping = dht->ping; 146 PING *ping = dht->ping;
141 147
142 if (id_equal(packet + 1, ping->dht->self_public_key)) 148 if (id_equal(packet + 1, ping->dht->self_public_key)) {
143 return 1; 149 return 1;
150 }
144 151
145 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 152 uint8_t shared_key[crypto_box_BEFORENMBYTES];
146 153
@@ -153,11 +160,13 @@ static int handle_ping_request(void *_dht, IP_Port source, const uint8_t *packet
153 PING_PLAIN_SIZE + crypto_box_MACBYTES, 160 PING_PLAIN_SIZE + crypto_box_MACBYTES,
154 ping_plain ); 161 ping_plain );
155 162
156 if (rc != sizeof(ping_plain)) 163 if (rc != sizeof(ping_plain)) {
157 return 1; 164 return 1;
165 }
158 166
159 if (ping_plain[0] != NET_PACKET_PING_REQUEST) 167 if (ping_plain[0] != NET_PACKET_PING_REQUEST) {
160 return 1; 168 return 1;
169 }
161 170
162 uint64_t ping_id; 171 uint64_t ping_id;
163 memcpy(&ping_id, ping_plain + 1, sizeof(ping_id)); 172 memcpy(&ping_id, ping_plain + 1, sizeof(ping_id));
@@ -173,13 +182,15 @@ static int handle_ping_response(void *_dht, IP_Port source, const uint8_t *packe
173 DHT *dht = _dht; 182 DHT *dht = _dht;
174 int rc; 183 int rc;
175 184
176 if (length != DHT_PING_SIZE) 185 if (length != DHT_PING_SIZE) {
177 return 1; 186 return 1;
187 }
178 188
179 PING *ping = dht->ping; 189 PING *ping = dht->ping;
180 190
181 if (id_equal(packet + 1, ping->dht->self_public_key)) 191 if (id_equal(packet + 1, ping->dht->self_public_key)) {
182 return 1; 192 return 1;
193 }
183 194
184 uint8_t shared_key[crypto_box_BEFORENMBYTES]; 195 uint8_t shared_key[crypto_box_BEFORENMBYTES];
185 196
@@ -194,27 +205,32 @@ static int handle_ping_response(void *_dht, IP_Port source, const uint8_t *packe
194 PING_PLAIN_SIZE + crypto_box_MACBYTES, 205 PING_PLAIN_SIZE + crypto_box_MACBYTES,
195 ping_plain); 206 ping_plain);
196 207
197 if (rc != sizeof(ping_plain)) 208 if (rc != sizeof(ping_plain)) {
198 return 1; 209 return 1;
210 }
199 211
200 if (ping_plain[0] != NET_PACKET_PING_RESPONSE) 212 if (ping_plain[0] != NET_PACKET_PING_RESPONSE) {
201 return 1; 213 return 1;
214 }
202 215
203 uint64_t ping_id; 216 uint64_t ping_id;
204 memcpy(&ping_id, ping_plain + 1, sizeof(ping_id)); 217 memcpy(&ping_id, ping_plain + 1, sizeof(ping_id));
205 uint8_t data[PING_DATA_SIZE]; 218 uint8_t data[PING_DATA_SIZE];
206 219
207 if (ping_array_check(data, sizeof(data), &ping->ping_array, ping_id) != sizeof(data)) 220 if (ping_array_check(data, sizeof(data), &ping->ping_array, ping_id) != sizeof(data)) {
208 return 1; 221 return 1;
222 }
209 223
210 if (!id_equal(packet + 1, data)) 224 if (!id_equal(packet + 1, data)) {
211 return 1; 225 return 1;
226 }
212 227
213 IP_Port ipp; 228 IP_Port ipp;
214 memcpy(&ipp, data + crypto_box_PUBLICKEYBYTES, sizeof(IP_Port)); 229 memcpy(&ipp, data + crypto_box_PUBLICKEYBYTES, sizeof(IP_Port));
215 230
216 if (!ipport_equal(&ipp, &source)) 231 if (!ipport_equal(&ipp, &source)) {
217 return 1; 232 return 1;
233 }
218 234
219 addto_lists(dht, source, packet + 1); 235 addto_lists(dht, source, packet + 1);
220 return 0; 236 return 0;
@@ -239,8 +255,9 @@ static int in_list(const Client_data *list, uint16_t length, const uint8_t *publ
239 ipptp = &list[i].assoc6; 255 ipptp = &list[i].assoc6;
240 } 256 }
241 257
242 if (!is_timeout(ipptp->timestamp, BAD_NODE_TIMEOUT) && ipport_equal(&ipptp->ip_port, &ip_port)) 258 if (!is_timeout(ipptp->timestamp, BAD_NODE_TIMEOUT) && ipport_equal(&ipptp->ip_port, &ip_port)) {
243 return 1; 259 return 1;
260 }
244 } 261 }
245 } 262 }
246 263
@@ -259,14 +276,17 @@ static int in_list(const Client_data *list, uint16_t length, const uint8_t *publ
259 */ 276 */
260int add_to_ping(PING *ping, const uint8_t *public_key, IP_Port ip_port) 277int add_to_ping(PING *ping, const uint8_t *public_key, IP_Port ip_port)
261{ 278{
262 if (!ip_isset(&ip_port.ip)) 279 if (!ip_isset(&ip_port.ip)) {
263 return -1; 280 return -1;
281 }
264 282
265 if (!node_addable_to_close_list(ping->dht, public_key, ip_port)) 283 if (!node_addable_to_close_list(ping->dht, public_key, ip_port)) {
266 return -1; 284 return -1;
285 }
267 286
268 if (in_list(ping->dht->close_clientlist, LCLIENT_LIST, public_key, ip_port)) 287 if (in_list(ping->dht->close_clientlist, LCLIENT_LIST, public_key, ip_port)) {
269 return -1; 288 return -1;
289 }
270 290
271 IP_Port temp; 291 IP_Port temp;
272 292
@@ -289,8 +309,9 @@ int add_to_ping(PING *ping, const uint8_t *public_key, IP_Port ip_port)
289 } 309 }
290 } 310 }
291 311
292 if (add_to_list(ping->to_ping, MAX_TO_PING, public_key, ip_port, ping->dht->self_public_key)) 312 if (add_to_list(ping->to_ping, MAX_TO_PING, public_key, ip_port, ping->dht->self_public_key)) {
293 return 0; 313 return 0;
314 }
294 315
295 return -1; 316 return -1;
296} 317}
@@ -301,27 +322,32 @@ int add_to_ping(PING *ping, const uint8_t *public_key, IP_Port ip_port)
301 */ 322 */
302void do_to_ping(PING *ping) 323void do_to_ping(PING *ping)
303{ 324{
304 if (!is_timeout(ping->last_to_ping, TIME_TO_PING)) 325 if (!is_timeout(ping->last_to_ping, TIME_TO_PING)) {
305 return; 326 return;
327 }
306 328
307 if (!ip_isset(&ping->to_ping[0].ip_port.ip)) 329 if (!ip_isset(&ping->to_ping[0].ip_port.ip)) {
308 return; 330 return;
331 }
309 332
310 unsigned int i; 333 unsigned int i;
311 334
312 for (i = 0; i < MAX_TO_PING; ++i) { 335 for (i = 0; i < MAX_TO_PING; ++i) {
313 if (!ip_isset(&ping->to_ping[i].ip_port.ip)) 336 if (!ip_isset(&ping->to_ping[i].ip_port.ip)) {
314 break; 337 break;
338 }
315 339
316 if (!node_addable_to_close_list(ping->dht, ping->to_ping[i].public_key, ping->to_ping[i].ip_port)) 340 if (!node_addable_to_close_list(ping->dht, ping->to_ping[i].public_key, ping->to_ping[i].ip_port)) {
317 continue; 341 continue;
342 }
318 343
319 send_ping_request(ping, ping->to_ping[i].ip_port, ping->to_ping[i].public_key); 344 send_ping_request(ping, ping->to_ping[i].ip_port, ping->to_ping[i].public_key);
320 ip_reset(&ping->to_ping[i].ip_port.ip); 345 ip_reset(&ping->to_ping[i].ip_port.ip);
321 } 346 }
322 347
323 if (i != 0) 348 if (i != 0) {
324 ping->last_to_ping = unix_time(); 349 ping->last_to_ping = unix_time();
350 }
325} 351}
326 352
327 353
@@ -329,8 +355,9 @@ PING *new_ping(DHT *dht)
329{ 355{
330 PING *ping = calloc(1, sizeof(PING)); 356 PING *ping = calloc(1, sizeof(PING));
331 357
332 if (ping == NULL) 358 if (ping == NULL) {
333 return NULL; 359 return NULL;
360 }
334 361
335 if (ping_array_init(&ping->ping_array, PING_NUM_MAX, PING_TIMEOUT) != 0) { 362 if (ping_array_init(&ping->ping_array, PING_NUM_MAX, PING_TIMEOUT) != 0) {
336 free(ping); 363 free(ping);
diff --git a/toxcore/ping_array.c b/toxcore/ping_array.c
index 93dade05..59eb7018 100644
--- a/toxcore/ping_array.c
+++ b/toxcore/ping_array.c
@@ -46,8 +46,9 @@ static void ping_array_clear_timedout(Ping_Array *array)
46 while (array->last_deleted != array->last_added) { 46 while (array->last_deleted != array->last_added) {
47 uint32_t index = array->last_deleted % array->total_size; 47 uint32_t index = array->last_deleted % array->total_size;
48 48
49 if (!is_timeout(array->entries[index].time, array->timeout)) 49 if (!is_timeout(array->entries[index].time, array->timeout)) {
50 break; 50 break;
51 }
51 52
52 clear_entry(array, index); 53 clear_entry(array, index);
53 ++array->last_deleted; 54 ++array->last_deleted;
@@ -71,8 +72,9 @@ uint64_t ping_array_add(Ping_Array *array, const uint8_t *data, uint32_t length)
71 72
72 array->entries[index].data = malloc(length); 73 array->entries[index].data = malloc(length);
73 74
74 if (array->entries[index].data == NULL) 75 if (array->entries[index].data == NULL) {
75 return 0; 76 return 0;
77 }
76 78
77 memcpy(array->entries[index].data, data, length); 79 memcpy(array->entries[index].data, data, length);
78 array->entries[index].length = length; 80 array->entries[index].length = length;
@@ -83,8 +85,9 @@ uint64_t ping_array_add(Ping_Array *array, const uint8_t *data, uint32_t length)
83 ping_id *= array->total_size; 85 ping_id *= array->total_size;
84 ping_id += index; 86 ping_id += index;
85 87
86 if (ping_id == 0) 88 if (ping_id == 0) {
87 ping_id += array->total_size; 89 ping_id += array->total_size;
90 }
88 91
89 array->entries[index].ping_id = ping_id; 92 array->entries[index].ping_id = ping_id;
90 return ping_id; 93 return ping_id;
@@ -100,22 +103,27 @@ uint64_t ping_array_add(Ping_Array *array, const uint8_t *data, uint32_t length)
100 */ 103 */
101int ping_array_check(uint8_t *data, uint32_t length, Ping_Array *array, uint64_t ping_id) 104int ping_array_check(uint8_t *data, uint32_t length, Ping_Array *array, uint64_t ping_id)
102{ 105{
103 if (ping_id == 0) 106 if (ping_id == 0) {
104 return -1; 107 return -1;
108 }
105 109
106 uint32_t index = ping_id % array->total_size; 110 uint32_t index = ping_id % array->total_size;
107 111
108 if (array->entries[index].ping_id != ping_id) 112 if (array->entries[index].ping_id != ping_id) {
109 return -1; 113 return -1;
114 }
110 115
111 if (is_timeout(array->entries[index].time, array->timeout)) 116 if (is_timeout(array->entries[index].time, array->timeout)) {
112 return -1; 117 return -1;
118 }
113 119
114 if (array->entries[index].length > length) 120 if (array->entries[index].length > length) {
115 return -1; 121 return -1;
122 }
116 123
117 if (array->entries[index].data == NULL) 124 if (array->entries[index].data == NULL) {
118 return -1; 125 return -1;
126 }
119 127
120 memcpy(data, array->entries[index].data, array->entries[index].length); 128 memcpy(data, array->entries[index].data, array->entries[index].length);
121 uint32_t len = array->entries[index].length; 129 uint32_t len = array->entries[index].length;
@@ -132,13 +140,15 @@ int ping_array_check(uint8_t *data, uint32_t length, Ping_Array *array, uint64_t
132 */ 140 */
133int ping_array_init(Ping_Array *empty_array, uint32_t size, uint32_t timeout) 141int ping_array_init(Ping_Array *empty_array, uint32_t size, uint32_t timeout)
134{ 142{
135 if (size == 0 || timeout == 0 || empty_array == NULL) 143 if (size == 0 || timeout == 0 || empty_array == NULL) {
136 return -1; 144 return -1;
145 }
137 146
138 empty_array->entries = calloc(size, sizeof(Ping_Array_Entry)); 147 empty_array->entries = calloc(size, sizeof(Ping_Array_Entry));
139 148
140 if (empty_array->entries == NULL) 149 if (empty_array->entries == NULL) {
141 return -1; 150 return -1;
151 }
142 152
143 empty_array->last_deleted = empty_array->last_added = 0; 153 empty_array->last_deleted = empty_array->last_added = 0;
144 empty_array->total_size = size; 154 empty_array->total_size = size;
diff --git a/toxcore/tox.c b/toxcore/tox.c
index a98e8aa7..960fb618 100644
--- a/toxcore/tox.c
+++ b/toxcore/tox.c
@@ -251,8 +251,9 @@ Tox *tox_new(const struct Tox_Options *options, TOX_ERR_NEW *error)
251 251
252 ip_init(&m_options.proxy_info.ip_port.ip, m_options.ipv6enabled); 252 ip_init(&m_options.proxy_info.ip_port.ip, m_options.ipv6enabled);
253 253
254 if (m_options.ipv6enabled) 254 if (m_options.ipv6enabled) {
255 m_options.proxy_info.ip_port.ip.family = AF_UNSPEC; 255 m_options.proxy_info.ip_port.ip.family = AF_UNSPEC;
256 }
256 257
257 if (!addr_resolve_or_parse_ip(options->proxy_host, &m_options.proxy_info.ip_port.ip, NULL)) { 258 if (!addr_resolve_or_parse_ip(options->proxy_host, &m_options.proxy_info.ip_port.ip, NULL)) {
258 SET_ERROR_PARAMETER(error, TOX_ERR_NEW_PROXY_BAD_HOST); 259 SET_ERROR_PARAMETER(error, TOX_ERR_NEW_PROXY_BAD_HOST);
@@ -499,16 +500,18 @@ void tox_self_get_public_key(const Tox *tox, uint8_t *public_key)
499{ 500{
500 const Messenger *m = tox; 501 const Messenger *m = tox;
501 502
502 if (public_key) 503 if (public_key) {
503 memcpy(public_key, m->net_crypto->self_public_key, crypto_box_PUBLICKEYBYTES); 504 memcpy(public_key, m->net_crypto->self_public_key, crypto_box_PUBLICKEYBYTES);
505 }
504} 506}
505 507
506void tox_self_get_secret_key(const Tox *tox, uint8_t *secret_key) 508void tox_self_get_secret_key(const Tox *tox, uint8_t *secret_key)
507{ 509{
508 const Messenger *m = tox; 510 const Messenger *m = tox;
509 511
510 if (secret_key) 512 if (secret_key) {
511 memcpy(secret_key, m->net_crypto->self_secret_key, crypto_box_SECRETKEYBYTES); 513 memcpy(secret_key, m->net_crypto->self_secret_key, crypto_box_SECRETKEYBYTES);
514 }
512} 515}
513 516
514bool tox_self_set_name(Tox *tox, const uint8_t *name, size_t length, TOX_ERR_SET_INFO *error) 517bool tox_self_set_name(Tox *tox, const uint8_t *name, size_t length, TOX_ERR_SET_INFO *error)
diff --git a/toxcore/util.c b/toxcore/util.c
index 7b715990..efb35ef2 100644
--- a/toxcore/util.c
+++ b/toxcore/util.c
@@ -40,8 +40,9 @@ static uint64_t unix_base_time_value;
40 40
41void unix_time_update() 41void unix_time_update()
42{ 42{
43 if (unix_base_time_value == 0) 43 if (unix_base_time_value == 0) {
44 unix_base_time_value = ((uint64_t)time(NULL) - (current_time_monotonic() / 1000ULL)); 44 unix_base_time_value = ((uint64_t)time(NULL) - (current_time_monotonic() / 1000ULL));
45 }
45 46
46 unix_time_value = (current_time_monotonic() / 1000ULL) + unix_base_time_value; 47 unix_time_value = (current_time_monotonic() / 1000ULL) + unix_base_time_value;
47} 48}
@@ -160,8 +161,9 @@ int load_state(load_state_callback_func load_state_callback, void *outer,
160 } 161 }
161 162
162 /* -2 means end of save. */ 163 /* -2 means end of save. */
163 if (ret == -2) 164 if (ret == -2) {
164 return 0; 165 return 0;
166 }
165 167
166 data += length_sub; 168 data += length_sub;
167 length -= length_sub; 169 length -= length_sub;
@@ -174,8 +176,9 @@ int create_recursive_mutex(pthread_mutex_t *mutex)
174{ 176{
175 pthread_mutexattr_t attr; 177 pthread_mutexattr_t attr;
176 178
177 if (pthread_mutexattr_init(&attr) != 0) 179 if (pthread_mutexattr_init(&attr) != 0) {
178 return -1; 180 return -1;
181 }
179 182
180 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) { 183 if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
181 pthread_mutexattr_destroy(&attr); 184 pthread_mutexattr_destroy(&attr);
@@ -213,14 +216,16 @@ void *rb_write(RingBuffer *b, void *p)
213{ 216{
214 void *rc = NULL; 217 void *rc = NULL;
215 218
216 if ((b->end + 1) % b->size == b->start) /* full */ 219 if ((b->end + 1) % b->size == b->start) { /* full */
217 rc = b->data[b->start]; 220 rc = b->data[b->start];
221 }
218 222
219 b->data[b->end] = p; 223 b->data[b->end] = p;
220 b->end = (b->end + 1) % b->size; 224 b->end = (b->end + 1) % b->size;
221 225
222 if (b->end == b->start) 226 if (b->end == b->start) {
223 b->start = (b->start + 1) % b->size; 227 b->start = (b->start + 1) % b->size;
228 }
224 229
225 return rc; 230 return rc;
226} 231}
@@ -239,7 +244,9 @@ RingBuffer *rb_new(int size)
239{ 244{
240 RingBuffer *buf = calloc(sizeof(RingBuffer), 1); 245 RingBuffer *buf = calloc(sizeof(RingBuffer), 1);
241 246
242 if (!buf) return NULL; 247 if (!buf) {
248 return NULL;
249 }
243 250
244 buf->size = size + 1; /* include empty elem */ 251 buf->size = size + 1; /* include empty elem */
245 252
@@ -259,8 +266,9 @@ void rb_kill(RingBuffer *b)
259} 266}
260uint16_t rb_size(const RingBuffer *b) 267uint16_t rb_size(const RingBuffer *b)
261{ 268{
262 if (rb_empty(b)) 269 if (rb_empty(b)) {
263 return 0; 270 return 0;
271 }
264 272
265 return 273 return
266 b->end > b->start ? 274 b->end > b->start ?
@@ -271,8 +279,9 @@ uint16_t rb_data(const RingBuffer *b, void **dest)
271{ 279{
272 uint16_t i = 0; 280 uint16_t i = 0;
273 281
274 for (; i < rb_size(b); i++) 282 for (; i < rb_size(b); i++) {
275 dest[i] = b->data[(b->start + i) % b->size]; 283 dest[i] = b->data[(b->start + i) % b->size];
284 }
276 285
277 return i; 286 return i;
278} 287}
diff --git a/toxdns/toxdns.c b/toxdns/toxdns.c
index 7b07fa16..65da4908 100644
--- a/toxdns/toxdns.c
+++ b/toxdns/toxdns.c
@@ -70,8 +70,9 @@ void *tox_dns3_new(uint8_t *server_public_key)
70{ 70{
71 DNS_Object *d = malloc(sizeof(DNS_Object)); 71 DNS_Object *d = malloc(sizeof(DNS_Object));
72 72
73 if (d == NULL) 73 if (d == NULL) {
74 return NULL; 74 return NULL;
75 }
75 76
76 memcpy(d->server_public_key, server_public_key, crypto_box_PUBLICKEYBYTES); 77 memcpy(d->server_public_key, server_public_key, crypto_box_PUBLICKEYBYTES);
77 dns_new_temp_keys(d); 78 dns_new_temp_keys(d);
@@ -106,8 +107,9 @@ int tox_generate_dns3_string(void *dns3_object, uint8_t *string, uint16_t string
106 int end_len = ((base * 8) / 5) + (base / DOT_INTERVAL) + !!(base % 5); 107 int end_len = ((base * 8) / 5) + (base / DOT_INTERVAL) + !!(base % 5);
107 end_len -= !(base % DOT_INTERVAL); 108 end_len -= !(base % DOT_INTERVAL);
108 109
109 if (end_len > string_max_len) 110 if (end_len > string_max_len) {
110 return -1; 111 return -1;
112 }
111 113
112 DNS_Object *d = dns3_object; 114 DNS_Object *d = dns3_object;
113 uint8_t buffer[1024]; 115 uint8_t buffer[1024];
@@ -118,8 +120,9 @@ int tox_generate_dns3_string(void *dns3_object, uint8_t *string, uint16_t string
118 int len = encrypt_data_symmetric(d->shared_key, nonce, name, name_len, 120 int len = encrypt_data_symmetric(d->shared_key, nonce, name, name_len,
119 buffer + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES); 121 buffer + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES);
120 122
121 if (len == -1) 123 if (len == -1) {
122 return -1; 124 return -1;
125 }
123 126
124 int total_len = len + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES; 127 int total_len = len + sizeof(uint32_t) + crypto_box_PUBLICKEYBYTES;
125 uint8_t *buff = buffer, *old_str = string; 128 uint8_t *buff = buffer, *old_str = string;
@@ -201,8 +204,9 @@ int tox_decrypt_dns3_TXT(void *dns3_object, uint8_t *tox_id, uint8_t *id_record,
201{ 204{
202 DNS_Object *d = dns3_object; 205 DNS_Object *d = dns3_object;
203 206
204 if (id_record_len != 87) 207 if (id_record_len != 87) {
205 return -1; 208 return -1;
209 }
206 210
207 /*if (id_record_len > 255 || id_record_len <= (sizeof(uint32_t) + crypto_box_MACBYTES)) 211 /*if (id_record_len > 255 || id_record_len <= (sizeof(uint32_t) + crypto_box_MACBYTES))
208 return -1;*/ 212 return -1;*/
@@ -213,16 +217,18 @@ int tox_decrypt_dns3_TXT(void *dns3_object, uint8_t *tox_id, uint8_t *id_record,
213 uint8_t data[id_record_len]; 217 uint8_t data[id_record_len];
214 int length = decode(data, id_record_null); 218 int length = decode(data, id_record_null);
215 219
216 if (length == -1) 220 if (length == -1) {
217 return -1; 221 return -1;
222 }
218 223
219 uint8_t nonce[crypto_box_NONCEBYTES] = {0}; 224 uint8_t nonce[crypto_box_NONCEBYTES] = {0};
220 memcpy(nonce, &request_id, sizeof(uint32_t)); 225 memcpy(nonce, &request_id, sizeof(uint32_t));
221 nonce[sizeof(uint32_t)] = 1; 226 nonce[sizeof(uint32_t)] = 1;
222 int len = decrypt_data_symmetric(d->shared_key, nonce, data, length, tox_id); 227 int len = decrypt_data_symmetric(d->shared_key, nonce, data, length, tox_id);
223 228
224 if (len != FRIEND_ADDRESS_SIZE) 229 if (len != FRIEND_ADDRESS_SIZE) {
225 return -1; 230 return -1;
231 }
226 232
227 return 0; 233 return 0;
228} 234}
diff --git a/toxencryptsave/toxencryptsave.c b/toxencryptsave/toxencryptsave.c
index 267bd813..e62e2283 100644
--- a/toxencryptsave/toxencryptsave.c
+++ b/toxencryptsave/toxencryptsave.c
@@ -86,8 +86,9 @@ bool toxes_version_is_compatible(uint32_t major, uint32_t minor, uint32_t patch)
86 */ 86 */
87bool tox_get_salt(const uint8_t *data, uint8_t *salt) 87bool tox_get_salt(const uint8_t *data, uint8_t *salt)
88{ 88{
89 if (memcmp(data, TOX_ENC_SAVE_MAGIC_NUMBER, TOX_ENC_SAVE_MAGIC_LENGTH) != 0) 89 if (memcmp(data, TOX_ENC_SAVE_MAGIC_NUMBER, TOX_ENC_SAVE_MAGIC_LENGTH) != 0) {
90 return 0; 90 return 0;
91 }
91 92
92 data += TOX_ENC_SAVE_MAGIC_LENGTH; 93 data += TOX_ENC_SAVE_MAGIC_LENGTH;
93 memcpy(salt, data, crypto_pwhash_scryptsalsa208sha256_SALTBYTES); 94 memcpy(salt, data, crypto_pwhash_scryptsalsa208sha256_SALTBYTES);
@@ -312,8 +313,9 @@ bool tox_pass_decrypt(const uint8_t *data, size_t length, const uint8_t *passphr
312 */ 313 */
313bool tox_is_data_encrypted(const uint8_t *data) 314bool tox_is_data_encrypted(const uint8_t *data)
314{ 315{
315 if (memcmp(data, TOX_ENC_SAVE_MAGIC_NUMBER, TOX_ENC_SAVE_MAGIC_LENGTH) == 0) 316 if (memcmp(data, TOX_ENC_SAVE_MAGIC_NUMBER, TOX_ENC_SAVE_MAGIC_LENGTH) == 0) {
316 return 1; 317 return 1;
317 else 318 } else {
318 return 0; 319 return 0;
320 }
319} 321}