forked from irungentoo/toxcore
-
Notifications
You must be signed in to change notification settings - Fork 291
/
Copy pathgroup_chats.c
8526 lines (6674 loc) · 248 KB
/
group_chats.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: GPL-3.0-or-later
* Copyright © 2016-2020 The TokTok team.
* Copyright © 2015 Tox project.
*/
/**
* An implementation of massive text only group chats.
*/
#include "group_chats.h"
#include <sodium.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "DHT.h"
#include "Messenger.h"
#include "TCP_connection.h"
#include "attributes.h"
#include "bin_pack.h"
#include "bin_unpack.h"
#include "ccompat.h"
#include "crypto_core.h"
#include "friend_connection.h"
#include "group_announce.h"
#include "group_common.h"
#include "group_connection.h"
#include "group_moderation.h"
#include "group_pack.h"
#include "logger.h"
#include "mono_time.h"
#include "net_crypto.h"
#include "network.h"
#include "onion_announce.h"
#include "onion_client.h"
#include "util.h"
/* The minimum size of a plaintext group handshake packet */
#define GC_MIN_HS_PACKET_PAYLOAD_SIZE (1 + ENC_PUBLIC_KEY_SIZE + SIG_PUBLIC_KEY_SIZE + 1 + 1)
/* The minimum size of an encrypted group handshake packet. */
#define GC_MIN_ENCRYPTED_HS_PAYLOAD_SIZE (1 + ENC_PUBLIC_KEY_SIZE + ENC_PUBLIC_KEY_SIZE +\
GC_MIN_HS_PACKET_PAYLOAD_SIZE + CRYPTO_NONCE_SIZE + CRYPTO_MAC_SIZE)
/* Size of a group's shared state in packed format */
#define GC_PACKED_SHARED_STATE_SIZE (EXT_PUBLIC_KEY_SIZE + sizeof(uint16_t) + MAX_GC_GROUP_NAME_SIZE +\
sizeof(uint16_t) + 1 + sizeof(uint16_t) + MAX_GC_PASSWORD_SIZE +\
MOD_MODERATION_HASH_SIZE + sizeof(uint32_t) + sizeof(uint32_t) + 1)
/* Minimum size of a topic packet; includes topic length, public signature key, topic version and checksum */
#define GC_MIN_PACKED_TOPIC_INFO_SIZE (sizeof(uint16_t) + SIG_PUBLIC_KEY_SIZE + sizeof(uint32_t) + sizeof(uint16_t))
#define GC_SHARED_STATE_ENC_PACKET_SIZE (SIGNATURE_SIZE + GC_PACKED_SHARED_STATE_SIZE)
/* Header information attached to all broadcast messages: broadcast_type */
#define GC_BROADCAST_ENC_HEADER_SIZE 1
/* Size of a group packet message ID */
#define GC_MESSAGE_ID_BYTES sizeof(uint64_t)
/* Size of a lossless ack packet */
#define GC_LOSSLESS_ACK_PACKET_SIZE (GC_MESSAGE_ID_BYTES + 1)
/* Smallest possible size of an encrypted lossless payload.
*
* Data includes the message_id, group packet type, and the nonce and MAC for decryption.
*/
#define GC_MIN_LOSSLESS_PAYLOAD_SIZE (GC_MESSAGE_ID_BYTES + CRYPTO_NONCE_SIZE + 1 + CRYPTO_MAC_SIZE)
/* Smallest possible size of a lossy group packet */
#define GC_MIN_LOSSY_PAYLOAD_SIZE (GC_MIN_LOSSLESS_PAYLOAD_SIZE - GC_MESSAGE_ID_BYTES)
/* Maximum number of bytes to pad packets with.
*
* Packets are padded with a random number of zero bytes between zero and this value in order to hide
* the true length of the message, which reduces the amount of metadata leaked through packet analysis.
*
* Note: This behaviour was copied from the toxcore encryption implementation in net_crypto.c.
*/
#define GC_MAX_PACKET_PADDING 8
/* Minimum size of a ping packet, which contains the peer count, peer list checksum, shared state version,
* sanctions list version, sanctions list checksum, topic version, and topic checksum
*/
#define GC_PING_PACKET_MIN_DATA_SIZE ((sizeof(uint16_t) * 4) + (sizeof(uint32_t) * 3))
/* How often in seconds we can send a group sync request packet */
#define GC_SYNC_REQUEST_LIMIT (GC_PING_TIMEOUT + 1)
/* How often in seconds we can send the peer list to any peer in the group in a sync response */
#define GC_SYNC_RESPONSE_PEER_LIST_LIMIT 3
/* How often in seconds we try to handshake with an unconfirmed peer */
#define GC_SEND_HANDSHAKE_INTERVAL 3
/* How often in seconds we rotate session encryption keys with a peer */
#define GC_KEY_ROTATION_TIMEOUT (5 * 60)
/* How often in seconds we try to reconnect to peers that recently timed out */
#define GC_TIMED_OUT_RECONN_TIMEOUT (GC_UNCONFIRMED_PEER_TIMEOUT * 3)
/* How long in seconds before we stop trying to reconnect with a timed out peer */
#define GC_TIMED_OUT_STALE_TIMEOUT (60 * 15)
/* The value the topic lock is set to when the topic lock is enabled. */
#define GC_TOPIC_LOCK_ENABLED 0
static_assert(GCC_BUFFER_SIZE <= UINT16_MAX,
"GCC_BUFFER_SIZE must be <= UINT16_MAX)");
static_assert(MAX_GC_PACKET_CHUNK_SIZE < MAX_GC_PACKET_SIZE,
"MAX_GC_PACKET_CHUNK_SIZE must be < MAX_GC_PACKET_SIZE");
static_assert(MAX_GC_PACKET_INCOMING_CHUNK_SIZE < MAX_GC_PACKET_SIZE,
"MAX_GC_PACKET_INCOMING_CHUNK_SIZE must be < MAX_GC_PACKET_SIZE");
static_assert(MAX_GC_PACKET_INCOMING_CHUNK_SIZE >= MAX_GC_PACKET_CHUNK_SIZE,
"MAX_GC_PACKET_INCOMING_CHUNK_SIZE must be >= MAX_GC_PACKET_CHUNK_SIZE");
// size of a lossless handshake packet - lossless packets can't/shouldn't be split up
static_assert(MAX_GC_PACKET_CHUNK_SIZE >= 171,
"MAX_GC_PACKET_CHUNK_SIZE must be >= 171");
static_assert(MAX_GC_PACKET_INCOMING_CHUNK_SIZE >= 171,
"MAX_GC_PACKET_INCOMING_CHUNK_SIZE must be >= 171");
// group_moderation constants assume this is the max packet size.
static_assert(MAX_GC_PACKET_SIZE >= 50000,
"MAX_GC_PACKET_SIZE doesn't match constants in group_moderation.h");
static_assert(MAX_GC_PACKET_SIZE <= UINT16_MAX - MAX_GC_PACKET_CHUNK_SIZE,
"MAX_GC_PACKET_SIZE must be <= UINT16_MAX - MAX_GC_PACKET_CHUNK_SIZE");
static_assert(MAX_GC_PACKET_SIZE <= UINT16_MAX - MAX_GC_PACKET_INCOMING_CHUNK_SIZE,
"MAX_GC_PACKET_SIZE must be <= UINT16_MAX - MAX_GC_PACKET_INCOMING_CHUNK_SIZE");
/** Types of broadcast messages. */
typedef enum Group_Message_Type {
GC_MESSAGE_TYPE_NORMAL = 0x00,
GC_MESSAGE_TYPE_ACTION = 0x01,
} Group_Message_Type;
/** Types of handshake request packets. */
typedef enum Group_Handshake_Packet_Type {
GH_REQUEST = 0x00, // Requests a handshake
GH_RESPONSE = 0x01, // Responds to a handshake request
} Group_Handshake_Packet_Type;
/** Types of handshake requests (within a handshake request packet). */
typedef enum Group_Handshake_Request_Type {
HS_INVITE_REQUEST = 0x00, // Requests an invite to the group
HS_PEER_INFO_EXCHANGE = 0x01, // Requests a peer info exchange
} Group_Handshake_Request_Type;
/** These bitmasks determine what group state info a peer is requesting in a sync request */
typedef enum Group_Sync_Flags {
GF_PEERS = (1 << 0), // 1
GF_TOPIC = (1 << 1), // 2
GF_STATE = (1 << 2), // 4
} Group_Sync_Flags;
non_null() static bool self_gc_is_founder(const GC_Chat *chat);
non_null() static bool group_number_valid(const GC_Session *c, int group_number);
non_null() static int peer_update(const GC_Chat *chat, const GC_Peer *peer, uint32_t peer_number);
non_null() static void group_delete(GC_Session *c, GC_Chat *chat);
non_null() static void group_cleanup(const GC_Session *c, GC_Chat *chat);
non_null() static bool group_exists(const GC_Session *c, const uint8_t *chat_id);
non_null() static void add_tcp_relays_to_chat(const GC_Session *c, GC_Chat *chat);
non_null(1, 2) nullable(4)
static bool peer_delete(const GC_Session *c, GC_Chat *chat, uint32_t peer_number, void *userdata);
non_null() static void create_gc_session_keypair(const Logger *log, const Random *rng, uint8_t *public_key,
uint8_t *secret_key);
non_null() static size_t load_gc_peers(GC_Chat *chat, const GC_SavedPeerInfo *addrs, uint16_t num_addrs);
non_null() static bool saved_peer_is_valid(const GC_SavedPeerInfo *saved_peer);
static const GC_Chat empty_gc_chat = {nullptr};
non_null()
static void kill_group_friend_connection(const GC_Session *c, const GC_Chat *chat)
{
if (chat->friend_connection_id != -1) {
m_kill_group_connection(c->messenger, chat);
}
}
uint16_t gc_get_wrapped_packet_size(uint16_t length, Net_Packet_Type packet_type)
{
assert(length <= (packet_type == NET_PACKET_GC_LOSSY ? MAX_GC_CUSTOM_LOSSY_PACKET_SIZE : MAX_GC_PACKET_CHUNK_SIZE));
const uint16_t min_header_size = packet_type == NET_PACKET_GC_LOSSY
? GC_MIN_LOSSY_PAYLOAD_SIZE
: GC_MIN_LOSSLESS_PAYLOAD_SIZE;
const uint16_t header_size = ENC_PUBLIC_KEY_SIZE + GC_MAX_PACKET_PADDING + min_header_size;
assert(length <= UINT16_MAX - header_size);
return length + header_size;
}
/** Return true if `peer_number` is our own. */
static bool peer_number_is_self(int peer_number)
{
return peer_number == 0;
}
bool gc_peer_number_is_valid(const GC_Chat *chat, int peer_number)
{
return peer_number >= 0 && peer_number < (int)chat->numpeers;
}
non_null()
static GC_Peer *get_gc_peer(const GC_Chat *chat, int peer_number)
{
if (!gc_peer_number_is_valid(chat, peer_number)) {
return nullptr;
}
return &chat->group[peer_number];
}
GC_Connection *get_gc_connection(const GC_Chat *chat, int peer_number)
{
GC_Peer *peer = get_gc_peer(chat, peer_number);
if (peer == nullptr) {
return nullptr;
}
return &peer->gconn;
}
/** Returns the max packet size, not wrapped */
static uint16_t group_packet_max_packet_size(Net_Packet_Type net_packet_type)
{
if (net_packet_type == NET_PACKET_GC_LOSSY) {
return MAX_GC_CUSTOM_LOSSY_PACKET_SIZE;
} else {
return MAX_GC_PACKET_CHUNK_SIZE;
}
}
/** Returns the amount of empty padding a packet of designated length should have. */
static uint16_t group_packet_padding_length(uint16_t length, uint16_t max_length)
{
return (max_length - length) % GC_MAX_PACKET_PADDING;
}
void gc_get_self_nick(const GC_Chat *chat, uint8_t *nick)
{
if (nick != nullptr) {
const GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
assert(peer->nick_length > 0);
memcpy(nick, peer->nick, peer->nick_length);
}
}
uint16_t gc_get_self_nick_size(const GC_Chat *chat)
{
const GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
return peer->nick_length;
}
/** @brief Sets self nick to `nick`.
*
* Returns false if `nick` is null or `length` is greater than MAX_GC_NICK_SIZE.
*/
non_null()
static bool self_gc_set_nick(const GC_Chat *chat, const uint8_t *nick, uint16_t length)
{
if (nick == nullptr || length > MAX_GC_NICK_SIZE) {
return false;
}
GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
memcpy(peer->nick, nick, length);
peer->nick_length = length;
return true;
}
Group_Role gc_get_self_role(const GC_Chat *chat)
{
const GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
return peer->role;
}
/** Sets self role. If role is invalid this function has no effect. */
non_null()
static void self_gc_set_role(const GC_Chat *chat, Group_Role role)
{
if (role <= GR_OBSERVER) {
GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
peer->role = role;
}
}
uint8_t gc_get_self_status(const GC_Chat *chat)
{
const GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
return peer->status;
}
/** Sets self status. If status is invalid this function has no effect. */
non_null()
static void self_gc_set_status(const GC_Chat *chat, Group_Peer_Status status)
{
if (status == GS_NONE || status == GS_AWAY || status == GS_BUSY) {
GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
peer->status = status;
return;
}
LOGGER_WARNING(chat->log, "Attempting to set user status with invalid status: %u", (uint8_t)status);
}
uint32_t gc_get_self_peer_id(const GC_Chat *chat)
{
const GC_Peer *peer = get_gc_peer(chat, 0);
assert(peer != nullptr);
return peer->peer_id;
}
/** Sets self confirmed status. */
non_null()
static void self_gc_set_confirmed(const GC_Chat *chat, bool confirmed)
{
GC_Connection *gconn = get_gc_connection(chat, 0);
assert(gconn != nullptr);
gconn->confirmed = confirmed;
}
/** Returns true if self has the founder role */
non_null()
static bool self_gc_is_founder(const GC_Chat *chat)
{
return gc_get_self_role(chat) == GR_FOUNDER;
}
void gc_get_self_public_key(const GC_Chat *chat, uint8_t *public_key)
{
if (public_key != nullptr) {
memcpy(public_key, chat->self_public_key, ENC_PUBLIC_KEY_SIZE);
}
}
/** @brief Sets self extended public key to `ext_public_key`.
*
* If `ext_public_key` is null this function has no effect.
*/
non_null()
static void self_gc_set_ext_public_key(const GC_Chat *chat, const uint8_t *ext_public_key)
{
if (ext_public_key != nullptr) {
GC_Connection *gconn = get_gc_connection(chat, 0);
assert(gconn != nullptr);
memcpy(gconn->addr.public_key, ext_public_key, EXT_PUBLIC_KEY_SIZE);
}
}
/**
* Return true if `peer` has permission to speak according to the `voice_state`.
*/
non_null()
static bool peer_has_voice(const GC_Peer *peer, Group_Voice_State voice_state)
{
const Group_Role role = peer->role;
switch (voice_state) {
case GV_ALL:
return role <= GR_USER;
case GV_MODS:
return role <= GR_MODERATOR;
case GV_FOUNDER:
return role == GR_FOUNDER;
default:
return false;
}
}
int pack_gc_saved_peers(const GC_Chat *chat, uint8_t *data, uint16_t length, uint16_t *processed)
{
uint16_t packed_len = 0;
uint16_t count = 0;
for (uint32_t i = 0; i < GC_MAX_SAVED_PEERS; ++i) {
const GC_SavedPeerInfo *saved_peer = &chat->saved_peers[i];
if (!saved_peer_is_valid(saved_peer)) {
continue;
}
int packed_ipp_len = 0;
int packed_tcp_len = 0;
if (ipport_isset(&saved_peer->ip_port)) {
if (packed_len > length) {
return -1;
}
packed_ipp_len = pack_ip_port(chat->log, data + packed_len, length - packed_len, &saved_peer->ip_port);
if (packed_ipp_len > 0) {
packed_len += packed_ipp_len;
}
}
if (ipport_isset(&saved_peer->tcp_relay.ip_port)) {
if (packed_len > length) {
return -1;
}
packed_tcp_len = pack_nodes(chat->log, data + packed_len, length - packed_len, &saved_peer->tcp_relay, 1);
if (packed_tcp_len > 0) {
packed_len += packed_tcp_len;
}
}
if (packed_len + ENC_PUBLIC_KEY_SIZE > length) {
return -1;
}
if (packed_tcp_len > 0 || packed_ipp_len > 0) {
memcpy(data + packed_len, chat->saved_peers[i].public_key, ENC_PUBLIC_KEY_SIZE);
packed_len += ENC_PUBLIC_KEY_SIZE;
++count;
} else {
LOGGER_WARNING(chat->log, "Failed to pack saved peer");
}
}
if (processed != nullptr) {
*processed = packed_len;
}
return count;
}
int unpack_gc_saved_peers(GC_Chat *chat, const uint8_t *data, uint16_t length)
{
uint16_t count = 0;
uint16_t unpacked_len = 0;
for (size_t i = 0; unpacked_len < length; ++i) {
GC_SavedPeerInfo *saved_peer = &chat->saved_peers[i];
const int ipp_len = unpack_ip_port(&saved_peer->ip_port, data + unpacked_len, length - unpacked_len, false);
if (ipp_len > 0) {
unpacked_len += ipp_len;
}
if (unpacked_len > length) {
return -1;
}
uint16_t tcp_len_processed = 0;
const int tcp_len = unpack_nodes(&saved_peer->tcp_relay, 1, &tcp_len_processed, data + unpacked_len,
length - unpacked_len, true);
if (tcp_len == 1 && tcp_len_processed > 0) {
unpacked_len += tcp_len_processed;
} else if (ipp_len <= 0) {
LOGGER_WARNING(chat->log, "Failed to unpack saved peer: Invalid connection info.");
return -1;
}
if (unpacked_len + ENC_PUBLIC_KEY_SIZE > length) {
return -1;
}
if (tcp_len > 0 || ipp_len > 0) {
memcpy(saved_peer->public_key, data + unpacked_len, ENC_PUBLIC_KEY_SIZE);
unpacked_len += ENC_PUBLIC_KEY_SIZE;
++count;
} else {
LOGGER_ERROR(chat->log, "Unpacked peer with bad connection info");
return -1;
}
}
return count;
}
/** Returns true if chat privacy state is set to public. */
non_null()
static bool is_public_chat(const GC_Chat *chat)
{
return chat->shared_state.privacy_state == GI_PUBLIC;
}
/** Returns true if group is password protected */
non_null()
static bool chat_is_password_protected(const GC_Chat *chat)
{
return chat->shared_state.password_length > 0;
}
/** Returns true if `password` matches the current group password. */
non_null()
static bool validate_password(const GC_Chat *chat, const uint8_t *password, uint16_t length)
{
if (length > MAX_GC_PASSWORD_SIZE) {
return false;
}
if (length != chat->shared_state.password_length) {
return false;
}
return memcmp(chat->shared_state.password, password, length) == 0;
}
/** @brief Returns the chat object that contains a peer with a public key equal to `id`.
*
* `id` must be at least ENC_PUBLIC_KEY_SIZE bytes in length.
*/
non_null()
static GC_Chat *get_chat_by_id(const GC_Session *c, const uint8_t *id)
{
if (c == nullptr) {
return nullptr;
}
for (uint32_t i = 0; i < c->chats_index; ++i) {
GC_Chat *chat = &c->chats[i];
if (chat->connection_state == CS_NONE) {
continue;
}
if (memcmp(id, chat->self_public_key, ENC_PUBLIC_KEY_SIZE) == 0) {
return chat;
}
if (get_peer_number_of_enc_pk(chat, id, false) != -1) {
return chat;
}
}
return nullptr;
}
/** @brief Returns the jenkins hash of a 32 byte public encryption key. */
uint32_t gc_get_pk_jenkins_hash(const uint8_t *public_key)
{
return jenkins_one_at_a_time_hash(public_key, ENC_PUBLIC_KEY_SIZE);
}
/** @brief Sets the sum of the public_key_hash of all confirmed peers.
*
* Must be called every time a peer is confirmed or deleted.
*/
non_null()
static void set_gc_peerlist_checksum(GC_Chat *chat)
{
uint16_t sum = 0;
for (uint32_t i = 0; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
assert(gconn != nullptr);
if (gconn->confirmed) {
sum += gconn->public_key_hash;
}
}
chat->peers_checksum = sum;
}
/** Returns a checksum of the topic currently set in `topic_info`. */
non_null()
static uint16_t get_gc_topic_checksum(const GC_TopicInfo *topic_info)
{
return data_checksum(topic_info->topic, topic_info->length);
}
int get_peer_number_of_enc_pk(const GC_Chat *chat, const uint8_t *public_enc_key, bool confirmed)
{
for (uint32_t i = 0; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
assert(gconn != nullptr);
if (gconn->pending_delete) {
continue;
}
if (confirmed && !gconn->confirmed) {
continue;
}
if (memcmp(gconn->addr.public_key, public_enc_key, ENC_PUBLIC_KEY_SIZE) == 0) {
return i;
}
}
return -1;
}
/** @brief Check if peer associated with `public_sig_key` is in peer list.
*
* Returns the peer number if peer is in the peer list.
* Returns -1 if peer is not in the peer list.
*/
non_null()
static int get_peer_number_of_sig_pk(const GC_Chat *chat, const uint8_t *public_sig_key)
{
for (uint32_t i = 0; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
assert(gconn != nullptr);
if (memcmp(get_sig_pk(gconn->addr.public_key), public_sig_key, SIG_PUBLIC_KEY_SIZE) == 0) {
return i;
}
}
return -1;
}
non_null()
static bool gc_get_enc_pk_from_sig_pk(const GC_Chat *chat, uint8_t *public_key, const uint8_t *public_sig_key)
{
for (uint32_t i = 0; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
assert(gconn != nullptr);
const uint8_t *full_pk = gconn->addr.public_key;
if (memcmp(public_sig_key, get_sig_pk(full_pk), SIG_PUBLIC_KEY_SIZE) == 0) {
memcpy(public_key, get_enc_key(full_pk), ENC_PUBLIC_KEY_SIZE);
return true;
}
}
return false;
}
non_null()
static GC_Connection *random_gc_connection(const GC_Chat *chat)
{
if (chat->numpeers <= 1) {
return nullptr;
}
const uint32_t base = random_range_u32(chat->rng, chat->numpeers - 1);
for (uint32_t i = 0; i < chat->numpeers - 1; ++i) {
const uint32_t index = 1 + (base + i) % (chat->numpeers - 1);
GC_Connection *rand_gconn = get_gc_connection(chat, index);
if (rand_gconn == nullptr) {
return nullptr;
}
if (!rand_gconn->pending_delete && rand_gconn->confirmed) {
return rand_gconn;
}
}
return nullptr;
}
/** @brief Returns the peer number associated with peer_id.
* Returns -1 if peer_id is invalid.
*/
non_null()
static int get_peer_number_of_peer_id(const GC_Chat *chat, uint32_t peer_id)
{
for (uint32_t i = 0; i < chat->numpeers; ++i) {
if (chat->group[i].peer_id == peer_id) {
return i;
}
}
return -1;
}
/** @brief Returns a unique peer ID.
* Returns UINT32_MAX if all possible peer ID's are taken.
*
* These ID's are permanently assigned to a peer when they join the group and should be
* considered arbitrary values.
*/
non_null()
static uint32_t get_new_peer_id(const GC_Chat *chat)
{
for (uint32_t i = 0; i < UINT32_MAX - 1; ++i) {
if (get_peer_number_of_peer_id(chat, i) == -1) {
return i;
}
}
return UINT32_MAX;
}
/** @brief Sets the password for the group (locally only).
*
* Return true on success.
*/
non_null(1) nullable(2)
static bool set_gc_password_local(GC_Chat *chat, const uint8_t *passwd, uint16_t length)
{
if (length > MAX_GC_PASSWORD_SIZE) {
return false;
}
if (passwd == nullptr || length == 0) {
chat->shared_state.password_length = 0;
memzero(chat->shared_state.password, MAX_GC_PASSWORD_SIZE);
} else {
chat->shared_state.password_length = length;
crypto_memlock(chat->shared_state.password, sizeof(chat->shared_state.password));
memcpy(chat->shared_state.password, passwd, length);
}
return true;
}
/** @brief Sets the local shared state to `version`.
*
* This should always be called instead of setting the variables manually.
*/
non_null()
static void set_gc_shared_state_version(GC_Chat *chat, uint32_t version)
{
chat->shared_state.version = version;
chat->moderation.shared_state_version = version;
}
/** @brief Expands the chat_id into the extended chat public key (encryption key + signature key).
*
* @param dest must have room for EXT_PUBLIC_KEY_SIZE bytes.
*
* Return true on success.
*/
non_null()
static bool expand_chat_id(uint8_t *dest, const uint8_t *chat_id)
{
assert(dest != nullptr);
const int ret = crypto_sign_ed25519_pk_to_curve25519(dest, chat_id);
memcpy(dest + ENC_PUBLIC_KEY_SIZE, chat_id, SIG_PUBLIC_KEY_SIZE);
return ret != -1;
}
/** Copies peer connect info from `gconn` to `addr`. */
non_null()
static void copy_gc_saved_peer(const Random *rng, const GC_Connection *gconn, GC_SavedPeerInfo *addr)
{
if (!gcc_copy_tcp_relay(rng, &addr->tcp_relay, gconn)) {
addr->tcp_relay = (Node_format) {
0
};
}
addr->ip_port = gconn->addr.ip_port;
memcpy(addr->public_key, gconn->addr.public_key, ENC_PUBLIC_KEY_SIZE);
}
/** Return true if `saved_peer` has either a valid IP_Port or a valid TCP relay. */
non_null()
static bool saved_peer_is_valid(const GC_SavedPeerInfo *saved_peer)
{
return ipport_isset(&saved_peer->ip_port) || ipport_isset(&saved_peer->tcp_relay.ip_port);
}
/** @brief Returns the index of the saved peers entry for `public_key`.
* Returns -1 if key is not found.
*/
non_null()
static int saved_peer_index(const GC_Chat *chat, const uint8_t *public_key)
{
for (uint16_t i = 0; i < GC_MAX_SAVED_PEERS; ++i) {
const GC_SavedPeerInfo *saved_peer = &chat->saved_peers[i];
if (memcmp(saved_peer->public_key, public_key, ENC_PUBLIC_KEY_SIZE) == 0) {
return i;
}
}
return -1;
}
/** @brief Returns the index of the first vacant entry in saved peers list.
*
* If `public_key` is non-null and already exists in the list, its index will be returned.
*
* A vacant entry is an entry that does not have either an IP_port or tcp relay set (invalid),
* or an entry containing info on a peer that is not presently online (offline).
*
* Invalid entries are given priority over offline entries.
*
* Returns -1 if there are no vacant indices.
*/
non_null(1) nullable(2)
static int saved_peers_get_new_index(const GC_Chat *chat, const uint8_t *public_key)
{
if (public_key != nullptr) {
const int idx = saved_peer_index(chat, public_key);
if (idx != -1) {
return idx;
}
}
// first check for invalid spots
for (uint16_t i = 0; i < GC_MAX_SAVED_PEERS; ++i) {
const GC_SavedPeerInfo *saved_peer = &chat->saved_peers[i];
if (!saved_peer_is_valid(saved_peer)) {
return i;
}
}
// now look for entries with offline peers
for (uint16_t i = 0; i < GC_MAX_SAVED_PEERS; ++i) {
const GC_SavedPeerInfo *saved_peer = &chat->saved_peers[i];
const int peernumber = get_peer_number_of_enc_pk(chat, saved_peer->public_key, true);
if (peernumber < 0) {
return i;
}
}
return -1;
}
/** @brief Attempts to add `gconn` to the saved peer list.
*
* If an entry already exists it will be updated.
*
* Older peers will only be overwritten if the peer is no longer
* present in the chat. This gives priority to more stable connections.
*
* This function should be called every time a new peer joins the group.
*/
non_null()
static void add_gc_saved_peers(GC_Chat *chat, const GC_Connection *gconn)
{
const int idx = saved_peers_get_new_index(chat, gconn->addr.public_key);
if (idx == -1) {
return;
}
GC_SavedPeerInfo *saved_peer = &chat->saved_peers[idx];
copy_gc_saved_peer(chat->rng, gconn, saved_peer);
}
/** @brief Finds the first vacant spot in the saved peers list and fills it with a present
* peer who isn't already in the list.
*
* This function should be called after a confirmed peer exits the group.
*/
non_null()
static void refresh_gc_saved_peers(GC_Chat *chat)
{
const int idx = saved_peers_get_new_index(chat, nullptr);
if (idx == -1) {
return;
}
for (uint32_t i = 1; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
if (gconn == nullptr) {
continue;
}
if (!gconn->confirmed) {
continue;
}
if (saved_peer_index(chat, gconn->addr.public_key) == -1) {
GC_SavedPeerInfo *saved_peer = &chat->saved_peers[idx];
copy_gc_saved_peer(chat->rng, gconn, saved_peer);
return;
}
}
}
/** Returns the number of confirmed peers in peerlist. */
non_null()
static uint16_t get_gc_confirmed_numpeers(const GC_Chat *chat)
{
uint16_t count = 0;
for (uint32_t i = 0; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
assert(gconn != nullptr);
if (gconn->confirmed) {
++count;
}
}
return count;
}
non_null() static bool sign_gc_shared_state(GC_Chat *chat);
non_null() static bool broadcast_gc_mod_list(const GC_Chat *chat);
non_null() static bool broadcast_gc_shared_state(const GC_Chat *chat);
non_null() static bool update_gc_sanctions_list(GC_Chat *chat, const uint8_t *public_sig_key);
non_null() static bool update_gc_topic(GC_Chat *chat, const uint8_t *public_sig_key);
non_null() static bool send_gc_set_observer(const GC_Chat *chat, const uint8_t *target_ext_pk,
const uint8_t *sanction_data, uint16_t length, bool add_obs);
/** Returns true if peer designated by `peer_number` is in the sanctions list as an observer. */
non_null()
static bool peer_is_observer(const GC_Chat *chat, uint32_t peer_number)
{
const GC_Connection *gconn = get_gc_connection(chat, peer_number);
if (gconn == nullptr) {
return false;
}
return sanctions_list_is_observer(&chat->moderation, get_enc_key(gconn->addr.public_key));
}
/** Returns true if peer designated by `peer_number` is the group founder. */
non_null()
static bool peer_is_founder(const GC_Chat *chat, uint32_t peer_number)
{
const GC_Connection *gconn = get_gc_connection(chat, peer_number);
if (gconn == nullptr) {
return false;
}
return memcmp(chat->shared_state.founder_public_key, gconn->addr.public_key, ENC_PUBLIC_KEY_SIZE) == 0;
}
/** Returns true if peer designated by `peer_number` is in the moderator list or is the founder. */
non_null()
static bool peer_is_moderator(const GC_Chat *chat, uint32_t peer_number)
{
const GC_Connection *gconn = get_gc_connection(chat, peer_number);
if (gconn == nullptr) {
return false;
}
if (peer_is_founder(chat, peer_number)) {
return false;
}
return mod_list_verify_sig_pk(&chat->moderation, get_sig_pk(gconn->addr.public_key));
}
/** @brief Iterates through the peerlist and updates group roles according to the
* current group state.
*
* Also updates the roles checksum. If any role conflicts exist the shared state
* version is set to zero in order to force a sync update.
*
* This should be called every time the moderator list or sanctions list changes,
* and after a new peer is marked as confirmed.
*/
non_null()
static void update_gc_peer_roles(GC_Chat *chat)
{
chat->roles_checksum = 0;
bool conflicts = false;
for (uint32_t i = 0; i < chat->numpeers; ++i) {
const GC_Connection *gconn = get_gc_connection(chat, i);
if (gconn == nullptr) {
continue;