/
client_groupchat.go
1694 lines (1470 loc) · 44.8 KB
/
client_groupchat.go
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
package client
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/companyzero/bisonrelay/client/clientdb"
"github.com/companyzero/bisonrelay/client/clientintf"
"github.com/companyzero/bisonrelay/rpc"
"github.com/companyzero/bisonrelay/zkidentity"
"golang.org/x/exp/slices"
)
const (
// {min,max}SupportedGCVersion tracks the mininum and maximum versions
// the client code handles for GCs.
minSupportedGCVersion = 0
maxSupportedGCVersion = 1
// newGCVersion is the version of newly created GCs.
newGCVersion = 1
)
// The group chat flow is:
//
// Alice Bob
// ------- -----
//
// NewGroupChat()
// InviteToGroupChat()
// \---------> RMGroupInvite -->
//
// handleGCInvite()
// AcceptGroupChatInvite()
// <-- RMGroupJoin -------------/
//
// handleGCJoin()
// \---------> RMGroupList -->
// handleGroupList()
//
// setGCAlias sets the new group chat alias cache.
func (c *Client) setGCAlias(aliasMap map[string]zkidentity.ShortID) {
c.gcAliasMtx.Lock()
c.gcAliasMap = aliasMap
c.gcAliasMtx.Unlock()
}
// AliasGC replaces the local alias of a GC for a new one.
func (c *Client) AliasGC(gcID zkidentity.ShortID, newAlias string) error {
newAlias = strings.TrimSpace(newAlias)
if newAlias == "" {
return fmt.Errorf("new GC alias acnnot be empty")
}
return c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
// Ensure gc exists.
if _, err := c.db.GetGC(tx, gcID); err != nil {
return err
}
if aliasMap, err := c.db.SetGCAlias(tx, gcID, newAlias); err != nil {
return err
} else {
c.setGCAlias(aliasMap)
}
return nil
})
}
// GetGCAlias returns the local alias for the specified GC.
func (c *Client) GetGCAlias(gcID zkidentity.ShortID) (string, error) {
var alias string
c.gcAliasMtx.Lock()
for v, id := range c.gcAliasMap {
if id == gcID {
alias = v
break
}
}
c.gcAliasMtx.Unlock()
if alias == "" {
return "", fmt.Errorf("gc %s not found", gcID)
}
return alias, nil
}
// GCIDByName returns the GC ID of the local GC with the given name. The name can
// be either a local GC alias or a full hex GC ID.
func (c *Client) GCIDByName(name string) (zkidentity.ShortID, error) {
var id zkidentity.ShortID
// Check if it's a full hex ID.
if err := id.FromString(name); err == nil {
return id, nil
}
// Check alias cache.
c.gcAliasMtx.Lock()
id, ok := c.gcAliasMap[name]
c.gcAliasMtx.Unlock()
if !ok {
return id, fmt.Errorf("gc %q not found", name)
}
return id, nil
}
// GCsWithPrefix returns a list of GC aliases that have the specified prefix.
func (c *Client) GCsWithPrefix(prefix string) []string {
var res []string
c.gcAliasMtx.Lock()
for alias := range c.gcAliasMap {
if strings.HasPrefix(alias, prefix) {
res = append(res, alias)
}
}
c.gcAliasMtx.Unlock()
return res
}
// GCsWithMember returns a list of GCs that have the specified UID as a member.
func (c *Client) GCsWithMember(uid UserID) ([]zkidentity.ShortID, error) {
var res []zkidentity.ShortID
err := c.dbView(func(tx clientdb.ReadTx) error {
var err error
res, err = c.db.ListGCsWithMember(tx, uid)
return err
})
return res, err
}
// NewGroupChatVersion creates a new gc with the local user as admin and the
// specified version.
func (c *Client) NewGroupChatVersion(name string, version uint8) (zkidentity.ShortID, error) {
var id zkidentity.ShortID
// Ensure we're not trying to duplicate the name.
if _, err := c.GCIDByName(name); err == nil {
return id, fmt.Errorf("gc named %q already exists", name)
}
if _, err := rand.Read(id[:]); err != nil {
return id, err
}
err := c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
// Ensure it doesn't exist.
_, err := c.db.GetGC(tx, id)
if !errors.Is(err, clientdb.ErrNotFound) {
if err == nil {
err = fmt.Errorf("can't create gc %q (%s): %w",
name, id.String(), errAlreadyExists)
}
return err
}
gc := rpc.RMGroupList{
ID: id,
Name: name,
Generation: 1,
Version: version,
Timestamp: time.Now().Unix(),
Members: []zkidentity.ShortID{
c.PublicID(),
},
}
if err = c.db.SaveGC(tx, gc); err != nil {
return fmt.Errorf("can't save gc %q (%s): %v", name, id.String(), err)
}
if aliasMap, err := c.db.SetGCAlias(tx, id, name); err != nil {
c.log.Errorf("can't set name %s for gc %s: %v", name, id.String(), err)
} else {
c.setGCAlias(aliasMap)
}
c.log.Infof("Created new gc %q (%s)", name, id.String())
return nil
})
return id, err
}
// NewGroupChat creates a group chat with the local client as admin.
func (c *Client) NewGroupChat(name string) (zkidentity.ShortID, error) {
return c.NewGroupChatVersion(name, newGCVersion)
}
// uidHasGCPerm returns true whether the given UID has permission to modify the
// given GC. This takes into account the GC version.
func (c *Client) uidHasGCPerm(gc rpc.RMGroupList, uid clientintf.UserID) error {
if gc.Version == 0 {
// Version 0 GCs only have admin as Members[0].
if len(gc.Members) > 0 && gc.Members[0].ConstantTimeEq(&uid) {
return nil
}
return fmt.Errorf("user %s not version 0 GC admin", uid)
}
if gc.Version == 1 {
if len(gc.Members) > 0 && gc.Members[0].ConstantTimeEq(&uid) {
// Update from admin. Accept.
return nil
}
if slices.Contains(gc.ExtraAdmins, uid) {
// Additional admin.
return nil
}
return fmt.Errorf("user %s not version 1 GC admin", uid)
}
return fmt.Errorf("unsupported GC version %d", gc.Version)
}
// InviteToGroupChat invites the given user to the given gc. The local user
// must be the admin of the group and the remote user must have been KX'd with.
func (c *Client) InviteToGroupChat(gcID zkidentity.ShortID, user UserID) error {
ru, err := c.rul.byID(user)
if err != nil {
return err
}
invite := rpc.RMGroupInvite{
ID: gcID,
Expires: time.Now().Add(time.Hour * 24).Unix(),
}
err = c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
// Ensure gc exists and we're the admin.
gc, err := c.db.GetGC(tx, gcID)
if err != nil {
return err
}
if err := c.uidHasGCPerm(gc, c.PublicID()); err != nil {
return fmt.Errorf("not permitted to send send invite: %v", err)
}
invite.Name = gc.Name
invite.Version = gc.Version
// Generate an unused token.
for {
// The % 1000000 is to generate a shorter token and
// maintain compat to old client.
invite.Token = c.mustRandomUint64() % 1000000
_, _, _, err := c.db.FindGCInvite(tx, gcID, invite.Token)
if errors.Is(err, clientdb.ErrNotFound) {
break
} else if err != nil {
return err
}
}
// Add to db.
_, err = c.db.AddGCInvite(tx, user, invite)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
// Send the invite.
c.log.Infof("Inviting %s to gc %q (%s)", ru, invite.Name, gcID)
payEvent := fmt.Sprintf("gc.%s.sendinvite", gcID.ShortLogID())
return ru.sendRM(invite, payEvent)
}
// handleGCInvite handles a message where a remote user is inviting us to join
// a gc.
func (c *Client) handleGCInvite(ru *RemoteUser, invite rpc.RMGroupInvite) error {
if invite.ID.IsEmpty() {
return fmt.Errorf("cannot accept gc invite: gc id is empty")
}
invite.Name = strings.TrimSpace(invite.Name)
if invite.Name == "" {
invite.Name = hex.EncodeToString(invite.ID[:8])
}
if invite.Version < minSupportedGCVersion || invite.Version > maxSupportedGCVersion {
return fmt.Errorf("invited to GC %s (%q) with unsupported version %d",
invite.ID, invite.Name, invite.Version)
}
if invite.ID.IsEmpty() {
return fmt.Errorf("GC id is empty")
}
// Add this invite to the DB.
var iid uint64
err := c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
var err error
_, err = c.db.GetGC(tx, invite.ID)
if !errors.Is(err, clientdb.ErrNotFound) {
if err == nil {
err = fmt.Errorf("can't accept gc invite: gc %q already exists",
invite.ID.String())
}
return err
}
iid, err = c.db.AddGCInvite(tx, ru.ID(), invite)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
// Let user know about it.
c.log.Infof("Received invitation to gc %q from user %s", invite.ID.String(), ru)
c.ntfns.notifyInvitedToGC(ru, iid, invite)
return nil
}
// AcceptGroupChatInvite accepts the given invitation, previously received from
// some user.
func (c *Client) AcceptGroupChatInvite(iid uint64) error {
var invite rpc.RMGroupInvite
var uid UserID
err := c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
var err error
invite, uid, err = c.db.GetGCInvite(tx, iid)
if err != nil {
return err
}
if err := c.db.MarkGCInviteAccepted(tx, iid); err != nil {
return err
}
return err
})
if err != nil {
return err
}
ru, err := c.rul.byID(uid)
if err != nil {
return err
}
join := rpc.RMGroupJoin{
ID: invite.ID,
Token: invite.Token,
}
c.log.Infof("Accepting invitation to gc %q (%s) from %s", invite.Name, invite.ID.String(), ru)
payEvent := fmt.Sprintf("gc.%s.acceptinvite", invite.ID.ShortLogID())
return ru.sendRM(join, payEvent)
}
// ListGCInvitesFor returns all GC invites. If gcid is specified, only invites
// for the specified GC are returned.
func (c *Client) ListGCInvitesFor(gcid *zkidentity.ShortID) ([]*clientdb.GCInvite, error) {
var invites []*clientdb.GCInvite
err := c.dbView(func(tx clientdb.ReadTx) error {
var err error
invites, err = c.db.ListGCInvites(tx, gcid)
return err
})
return invites, err
}
// sendToGCMembers sends the given message to all GC members of the given slice
// (unless that is the local client).
func (c *Client) sendToGCMembers(gcID zkidentity.ShortID,
members []zkidentity.ShortID, payType string, msg interface{},
progressChan chan SendProgress) error {
localID := c.PublicID()
payEvent := fmt.Sprintf("gc.%s.%s", gcID.ShortLogID(), payType)
// missingKXInfo will be used to track information about members that
// the local client hasn't KXd with yet.
type missingKXInfo struct {
uid clientintf.UserID
hasKX bool
hasMI bool
medID *clientintf.UserID
miCount uint32
skipWarn bool
skipMI bool
}
var missingKX []missingKXInfo
// Add the set of outbound messages to the sendq.
ids := make([]clientintf.UserID, 0, len(members)-1)
for _, uid := range members {
if uid == localID {
continue
}
// If the user isn't KX'd with, and they haven't been warned
// recently, add to the missingKX list to perform some actions
// later on.
_, err := c.rul.byID(uid)
if err != nil {
c.unkxdWarningsMtx.Lock()
if t := c.unkxdWarnings[uid]; time.Since(t) > c.cfg.UnkxdWarningTimeout {
missingKX = append(missingKX, missingKXInfo{uid: uid})
}
c.unkxdWarningsMtx.Unlock()
continue
}
ids = append(ids, uid)
}
sqid, err := c.addToSendQ(payEvent, msg, priorityGC, ids...)
if err != nil {
return fmt.Errorf("Unable to add gc msg to send queue: %v", err)
}
// These will be used to track the sending progress.
var progressMtx sync.Mutex
var sent, total int
// Start the sending process for each member.
for _, id := range members {
if id == localID {
continue
}
ru, err := c.rul.byID(id)
if err != nil {
continue
}
progressMtx.Lock() // Unlikely, but could race with the result.
total += 1
progressMtx.Unlock()
// Send as a goroutine to fulfill for all users concurrently.
go func() {
err := ru.sendRMPriority(msg, payEvent, priorityGC)
if errors.Is(err, clientintf.ErrSubsysExiting) {
return
}
// Remove from sendq independently of error.
c.removeFromSendQ(sqid, ru.ID())
if err != nil {
c.log.Errorf("Unable to send %T on gc %q to user %s: %v",
msg, gcID.String(), ru, err)
return
}
// Alert about progress.
if progressChan != nil {
progressMtx.Lock()
sent += 1
progressChan <- SendProgress{
Sent: sent,
Total: total,
Err: err,
}
progressMtx.Unlock()
}
}()
}
// Early return if there are no members that are missing kx.
if len(missingKX) == 0 {
return nil
}
// Handle GC members for which we don't have KX. Determine if there
// is a KX/MediateID attempt for them, start a new one if needed and
// warn the UI about it.
//
// First: go through the DB to see if they are being KX'd with.
err = c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
var localID, gcOwner clientintf.UserID
var gotGCInfo bool
for i := range missingKX {
target := missingKX[i].uid
// Check if already KXing.
kxs, err := c.db.HasKXWithUser(tx, target)
if err != nil {
return err
}
missingKX[i].hasKX = len(kxs) > 0
// Check if already has MediateID requests.
hasRecent, err := c.db.HasAnyRecentMediateID(tx, target,
c.cfg.RecentMediateIDThreshold)
if err != nil {
return err
}
missingKX[i].hasMI = hasRecent
// Check if the attempts to KX with the target crossed
// a max attempt count limit or if we're expecting a
// KX request from them (because _they_ joined the
// GC).
if unkx, err := c.db.ReadUnxkdUserInfo(tx, target); err == nil {
missingKX[i].miCount = unkx.MIRequests
if unkx.MIRequests >= uint32(c.cfg.MaxAutoKXMediateIDRequests) {
c.log.Debugf("Skipping autoKX with GC's %s member %s "+
"due to MI requests %d >= max %d",
gcID, target, unkx.MIRequests,
c.cfg.MaxAutoKXMediateIDRequests)
missingKX[i].skipMI = true
missingKX[i].skipWarn = unkx.MIRequests > uint32(c.cfg.MaxAutoKXMediateIDRequests)
if !missingKX[i].skipWarn {
// Add one to MIRequests to avoid warning again.
unkx.MIRequests += 1
err := c.db.StoreUnkxdUserInfo(tx, unkx)
if err != nil {
return err
}
}
} else if unkx.AddedToGCTime != nil && time.Since(*unkx.AddedToGCTime) < c.cfg.RecentMediateIDThreshold {
c.log.Debugf("Skipping autoKX with GC's %s member %s "+
"due to interval from GC add %s < recent "+
"MI threshold %s", gcID, target,
time.Since(*unkx.AddedToGCTime),
c.cfg.RecentMediateIDThreshold)
missingKX[i].skipMI = true
}
if unkx.AddedToGCTime != nil && time.Since(*unkx.AddedToGCTime) < c.cfg.UnkxdWarningTimeout {
missingKX[i].skipWarn = true
}
}
if missingKX[i].skipMI || missingKX[i].hasMI {
continue
}
// Fetch the group list if needed.
if !gotGCInfo {
gcl, err := c.db.GetGC(tx, gcID)
if err != nil {
return err
}
localID = c.PublicID()
gcOwner = gcl.Members[0]
gotGCInfo = true
}
// Determine if we can ask the GC's owner for a mediate
// ID request.
if gcOwner != localID {
missingKX[i].medID = &gcOwner
}
}
return nil
})
if err != nil {
return err
}
// Next, log a warning and send a ntfn to the UI about each user's
// situation.
c.unkxdWarningsMtx.Lock()
now := time.Now()
for _, mkx := range missingKX {
if mkx.skipWarn {
continue
}
if t := c.unkxdWarnings[mkx.uid]; now.Sub(t) < c.cfg.UnkxdWarningTimeout {
// Already warned.
continue
}
c.unkxdWarnings[mkx.uid] = now
c.log.Warnf("Unable to send %T to unKXd member %s in GC %s",
msg, mkx.uid, gcID)
c.ntfns.notifyGCWithUnxkdMember(gcID, mkx.uid, mkx.hasKX, mkx.hasMI,
mkx.miCount, mkx.medID)
}
c.unkxdWarningsMtx.Unlock()
// Next, start the mediate id requests that are needed.
for _, mkx := range missingKX {
if mkx.hasKX || mkx.hasMI || mkx.medID == nil || mkx.skipMI {
continue
}
err := c.maybeRequestMediateID(*mkx.medID, mkx.uid)
if err != nil && !errors.Is(err, clientintf.ErrSubsysExiting) {
c.log.Errorf("Unable to request mediate ID of target %s "+
"to mediator %s: %v", mkx.uid, mkx.medID, err)
}
}
return nil
}
// maybeNotifyGCVersionWarning checks whether a notification for a GC version
// mismatch is needed for a received GC list, and triggers the notification.
func (c *Client) maybeNotifyGCVersionWarning(ru *RemoteUser, gcid zkidentity.ShortID, gcl rpc.RMGroupList) {
notifyVersionWarning := (gcl.Version < minSupportedGCVersion || gcl.Version > maxSupportedGCVersion) && !c.gcWarnedVersions.Set(gcid)
if notifyVersionWarning {
c.log.Warnf("Received GCList for GC %s with version "+
"%d which is not between the supported versions %d to %d",
gcid, gcl.Version, minSupportedGCVersion, maxSupportedGCVersion)
c.ntfns.notifyOnGCVersionWarning(ru, gcl, minSupportedGCVersion,
maxSupportedGCVersion)
}
}
// maybeUpdateGCFunc verifies that the given gcid exists, calls f() with the
// existing GC definition, then updates the DB with the modified value. It
// returns both the old and new GC definitions.
//
// Checks are performed to ensure the new GC definitions are sane and allowed
// by the given remote user. If ru is nil, then the update is assumed to be
// made by the local client.
//
// f is called within a DB tx.
func (c *Client) maybeUpdateGCFunc(ru *RemoteUser, gcid zkidentity.ShortID, f func(*rpc.RMGroupList) error) (oldGC, newGC rpc.RMGroupList, err error) {
var checkVersionWarning bool
var updaterID clientintf.UserID
localID := c.PublicID()
if ru != nil {
updaterID = ru.ID()
} else {
updaterID = localID
}
err = c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
// Fetch GC.
var err error
oldGC, err = c.db.GetGC(tx, gcid)
if err != nil {
return err
}
if len(oldGC.Members) == 0 {
return fmt.Errorf("old GC %s has zero members", gcid)
}
// Produce the new GC. Deep copy the old GC so f() can mutate
// everything.
newGC = oldGC
newGC.Members = slices.Clone(oldGC.Members)
newGC.ExtraAdmins = slices.Clone(oldGC.ExtraAdmins)
if err := f(&newGC); err != nil {
return err
}
// Ensure no backtrack on generation.
if newGC.Generation < oldGC.Generation {
return fmt.Errorf("cannot backtrack GC generation on "+
"GC %s (%d < %d)", gcid, oldGC.Generation,
newGC.Generation)
}
// Ensure no downgrade in version.
if newGC.Version < oldGC.Version {
return fmt.Errorf("cannot downgrade GC version on "+
"GC %s (%d < %d)", gcid, oldGC.Generation,
newGC.Generation)
}
// Special case changing the owner: only the owner itself
// can do it.
if len(oldGC.Members) == 0 || len(newGC.Members) == 0 {
return fmt.Errorf("gc has no members")
}
if oldGC.Members[0] != newGC.Members[0] && oldGC.Members[0] != updaterID {
return fmt.Errorf("only previous GC owner %s may change "+
"GC's %s owner", oldGC.Members[0], gcid)
}
// This check is done before checking for permission because a
// future version might have different rules for checking
// permission.
checkVersionWarning = ru != nil
if err := c.uidHasGCPerm(oldGC, updaterID); err != nil {
return err
}
// Handle case where the local client was removed from GC.
stillMember := slices.Contains(newGC.Members, c.PublicID())
if !stillMember {
if err := c.db.DeleteGC(tx, oldGC.ID); err != nil {
return err
}
if aliasMap, err := c.db.SetGCAlias(tx, oldGC.ID, ""); err != nil {
return err
} else {
c.setGCAlias(aliasMap)
}
return nil
}
// This is an update, so any new members added to the GC that
// we haven't KX'd with are expected to send a MI to the GC
// owner/admin (because _they_ are the ones joining). So add
// info to prevent us attempting a crossed MI with them for
// some time.
if ru != nil && stillMember {
for _, uid := range newGC.Members {
if uid == localID {
continue
}
if c.db.AddressBookEntryExists(tx, uid) {
continue
}
unkx, err := c.db.ReadUnxkdUserInfo(tx, uid)
if err != nil {
if !errors.Is(err, clientdb.ErrNotFound) {
return err
}
unkx.UID = uid
}
if unkx.AddedToGCTime != nil {
continue
}
now := time.Now()
unkx.AddedToGCTime = &now
if err := c.db.StoreUnkxdUserInfo(tx, unkx); err != nil {
return err
}
}
}
return c.db.SaveGC(tx, newGC)
})
if checkVersionWarning {
c.maybeNotifyGCVersionWarning(ru, newGC.ID, newGC)
}
return
}
// maybeUpdateGC updates the given GC definitions for the specified one.
func (c *Client) maybeUpdateGC(ru *RemoteUser, newGC rpc.RMGroupList) (oldGC rpc.RMGroupList, err error) {
cb := func(ngc *rpc.RMGroupList) error {
*ngc = newGC
return nil
}
oldGC, _, err = c.maybeUpdateGCFunc(ru, newGC.ID, cb)
return
}
// handleGCJoin handles a msg when a remote user is asking to join a GC we
// administer (that is, responding to an invite previously sent by us).
func (c *Client) handleGCJoin(ru *RemoteUser, invite rpc.RMGroupJoin) error {
var gc rpc.RMGroupList
updated := false
err := c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
var err error
_, uid, iid, err := c.db.FindGCInvite(tx,
invite.ID, invite.Token)
if err != nil {
return err
}
// Ensure we received this join from the same user we sent it
// to.
if uid != ru.ID() {
return fmt.Errorf("received GCJoin from user %s when "+
"it was sent to user %s", ru.ID(), uid)
}
// Ensure we have permission to add people to GC.
gc, err = c.db.GetGC(tx, invite.ID)
if err != nil {
return err
}
if err := c.uidHasGCPerm(gc, c.PublicID()); err != nil {
return fmt.Errorf("local user does not have permission "+
"to add gc member: %v", err)
}
// This invitation is fulfilled.
if err = c.db.DelGCInvite(tx, iid); err != nil {
return err
}
// Ensure user is not on gc yet.
if slices.Contains(gc.Members, uid) {
return fmt.Errorf("user %s already part of gc %q",
uid, gc.ID.String())
}
if invite.Error == "" {
// Add the new member, increment generation, save the
// new gc group.
gc.Members = append(gc.Members, uid)
gc.Generation += 1
gc.Timestamp = time.Now().Unix()
if err = c.db.SaveGC(tx, gc); err != nil {
return err
}
updated = true
} else {
c.log.Infof("User %s rejected invitation to %q: %q",
ru, gc.ID.String(), invite.Error)
}
return nil
})
if err != nil || !updated {
return err
}
c.log.Infof("User %s joined gc %s (%q)", ru, gc.ID, gc.Name)
// Join fulfilled. Send new group list to every member except admin
// (us).
err = c.sendToGCMembers(gc.ID, gc.Members, "sendlist", gc, nil)
if err != nil {
return err
}
c.ntfns.notifyGCInviteAccepted(ru, gc)
return nil
}
// notifyUpdatedGC determines what changed between two GC definitions and
// notifies the user about it.
func (c *Client) notifyUpdatedGC(ru *RemoteUser, oldGC, newGC rpc.RMGroupList) {
if oldGC.Version != newGC.Version {
c.ntfns.notifyOnGCUpgraded(newGC, oldGC.Version)
}
memberChanges := sliceDiff(oldGC.Members, newGC.Members)
if len(memberChanges.added) > 0 {
c.ntfns.notifyOnAddedGCMembers(newGC, memberChanges.added)
}
if len(memberChanges.removed) > 0 {
c.ntfns.notifyOnRemovedGCMembers(newGC, memberChanges.removed)
}
adminChanges := sliceDiff(oldGC.ExtraAdmins, newGC.ExtraAdmins)
// Also check if the "owner" (Members[0] admin) changed.
if oldGC.Members[0] != newGC.Members[0] {
adminChanges.added = append(memberChanges.added, newGC.Members[0])
adminChanges.removed = append(memberChanges.removed, oldGC.Members[0])
}
if len(adminChanges.removed) > 0 || len(adminChanges.added) > 0 {
c.ntfns.notifyGCAdminsChanged(ru, newGC, adminChanges.added, adminChanges.removed)
}
}
// saveJoinedGC is called when the local client receives the first RMGroupList
// after requesting to join the GC with the GC admin.
//
// Returns the new GC name.
func (c *Client) saveJoinedGC(ru *RemoteUser, gl rpc.RMGroupList) (string, error) {
var checkVersionWarning bool
var gcName string
err := c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
// Double check GC does not exist yet.
_, err := c.db.GetGC(tx, gl.ID)
if err == nil {
return fmt.Errorf("GC %s already exists when attempting "+
"to save after joining", gl.ID)
}
// This must have been an invite we accepted. Ensure
// this came from the expected user.
invite, _, err := c.db.FindAcceptedGCInvite(tx, gl.ID, ru.ID())
if err != nil {
return fmt.Errorf("unable to list gc invites: %v", err)
}
// This is set to true before the perm check because future
// versions might change the permissions about who can send the
// list.
checkVersionWarning = true
// Ensure we received this from someone that can add
// members.
if err := c.uidHasGCPerm(gl, ru.ID()); err != nil {
return err
}
// Remove all invites received to this GC.
if err := c.db.DelAllInvitesToGC(tx, gl.ID); err != nil {
return fmt.Errorf("unable to del gc invite: %v", err)
}
// Figure out the GC name.
gcName = invite.Name
_, err = c.GCIDByName(gcName)
for i := 1; err == nil; i += 1 {
gcName = fmt.Sprintf("%s_%d", invite.Name, i)
_, err = c.GCIDByName(gcName)
}
if aliasMap, err := c.db.SetGCAlias(tx, gl.ID, gcName); err != nil {
c.log.Errorf("can't set name %s for gc %s: %v", gcName, gl.ID.String(), err)
} else {
c.setGCAlias(aliasMap)
}
// All is well. Update the local gc data.
if err := c.db.SaveGC(tx, gl); err != nil {
return fmt.Errorf("unable to save gc: %v", err)
}
return nil
})
if checkVersionWarning {
c.maybeNotifyGCVersionWarning(ru, gl.ID, gl)
}
return gcName, err
}
// handleGCList handles updates to a GC metadata. The sending user must have
// been the admin, otherwise this update is rejected.
func (c *Client) handleGCList(ru *RemoteUser, gl rpc.RMGroupList) error {
var gcName string
// Check if GC exists to determine if it's the first GC list.
_, err := c.GetGC(gl.ID)
isNewGC := err != nil && errors.Is(err, clientdb.ErrNotFound)
if err != nil && !isNewGC {
return err
}
if !isNewGC {
// Existing GC update. Do the update, then return.
oldGC, err := c.maybeUpdateGC(ru, gl)
if err != nil {
return err
}
gcName, _ = c.GetGCAlias(gl.ID)
c.log.Infof("Received updated GC list %s (%q) from %s", gl.ID, gcName, ru)
c.notifyUpdatedGC(ru, oldGC, gl)
return nil
}
// First GC list from a GC we just joined.
gcName, err = c.saveJoinedGC(ru, gl)
if err != nil {
return err
}
c.log.Infof("Received first GC list of %s (%q) from %s", gl.ID, gcName, ru)
c.ntfns.notifyOnJoinedGC(gl)
// Start kx with unknown members. They are relying on us performing
// transitive KX via an admin.
me := c.PublicID()
for _, v := range gl.Members {
v := v
if v == me {
continue
}
_, err := c.rul.byID(v)
if !errors.Is(err, userNotFoundError{}) {
continue
}
err = c.maybeRequestMediateID(ru.ID(), v)
if err != nil && !errors.Is(err, clientintf.ErrSubsysExiting) {
c.log.Errorf("Unable to autokx with %s via %s: %v",
v, ru, err)
}
}
return nil
}
// handleDelayedGCMessages is called by the gc message cacher when it's time
// to let external callers know about new messages.
func (c *Client) handleDelayedGCMessages(msg clientintf.ReceivedGCMsg) {
user, err := c.UserByID(msg.UID)
if err != nil {
// Should only happen if we blocked the user
// during the gcm cacher delay.
c.log.Warnf("Delayed GC message with unknown user %s", msg.UID)
return
}
// Log the message and remove the cached GCM from the db.
err = c.dbUpdate(func(tx clientdb.ReadWriteTx) error {
if err := c.db.RemoveCachedRGCM(tx, msg); err != nil {
c.log.Warnf("Unable to remove cached RGCM: %v", err)
}
gcAlias, _ := c.GetGCAlias(msg.GCM.ID)
err := c.db.LogGCMsg(tx, gcAlias, msg.GCM.ID, false, user.Nick(),
msg.GCM.Message, msg.TS)
if err != nil {