forked from tinode/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopic.go
3558 lines (3115 loc) · 109 KB
/
topic.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
/******************************************************************************
*
* Description :
* An isolated communication channel (chat room, 1:1 conversation) for
* usually multiple users. There is no communication across topics.
*
*****************************************************************************/
package main
import (
"errors"
"log"
"reflect"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/tinode/chat/server/auth"
"github.com/tinode/chat/server/concurrency"
"github.com/tinode/chat/server/push"
"github.com/tinode/chat/server/store"
"github.com/tinode/chat/server/store/types"
)
// Topic is an isolated communication channel
type Topic struct {
// Еxpanded/unique name of the topic.
name string
// For single-user topics session-specific topic name, such as 'me',
// otherwise the same as 'name'.
xoriginal string
// Topic category
cat types.TopicCat
// Channel functionality is enabled for the group topic.
isChan bool
// If isProxy == true, the actual topic is hosted by another cluster member.
// The topic should:
// 1. forward all messages to master
// 2. route replies from the master to sessions.
// 3. disconnect sessions at master's request.
// 4. shut down the topic at master's request.
// 5. aggregate access permissions on behalf of attached sessions.
isProxy bool
// Name of the master node for this topic if isProxy is true.
masterNode string
// Topic runs a goroutine (clusterWriteLoop) that reads events from all proxy
// multiplexing sessions.
// List of proxied sessions.
proxiedSessions []*Session
// Proxied sessions' channels for the use in the topic's clusterWriteLoop:
// i-th session's channels (proxiedSessions[i]) are found at:
// proxiedChannels[i * 3 + 1] - send
// proxiedChannels[i * 3 + 2] - stop
// proxiedChannels[i * 3 + 3] - detach
//
// proxiedChannels[0] is a special-purpose channel necessary for interrupting
// clusterWriteLoop when sessions are added or removed.
proxiedChannels []reflect.SelectCase
// Guards proxiedSessions and proxiedTopics (not using sync.Mutex here
// since we need TryLock functionality).
proxiedLock concurrency.SimpleMutex
// Time when the topic was first created.
created time.Time
// Time when the topic was last updated.
updated time.Time
// Time of the last outgoing message.
touched time.Time
// Server-side ID of the last data message
lastID int
// ID of the deletion operation. Not an ID of the message.
delID int
// Last published userAgent ('me' topic only)
userAgent string
// User ID of the topic owner/creator. Could be zero.
owner types.Uid
// Default access mode
accessAuth types.AccessMode
accessAnon types.AccessMode
// Topic discovery tags
tags []string
// Topic's public data
public interface{}
// Topic's per-subscriber data
perUser map[types.Uid]perUserData
// Union of permissions across all users (used by proxy sessions with uid = 0).
// These are used by master topics only (in the proxy-master topic context)
// as a coarse-grained attempt to perform acs checks since proxy sessions "impersonate"
// multiple normal sessions (uids) which may have different uids.
modeWantUnion types.AccessMode
modeGivenUnion types.AccessMode
// User's contact list (not nil for 'me' topic only).
// The map keys are UserIds for P2P topics and grpXXX for group topics.
perSubs map[string]perSubsData
// Sessions attached to this topic. The UID kept here may not match Session.uid if session is
// subscribed on behalf of another user.
sessions map[*Session]perSessionData
// Requests to broadcast messages from sessions or other topics. Buffered = 256
broadcast chan *ServerComMessage
// Channel for receiving {get}/{set} requests, buffered = 32
meta chan *metaReq
// Subscribe requests from sessions, buffered = 32
reg chan *sessionJoin
// Unsubscribe requests from sessions, buffered = 32
unreg chan *sessionLeave
// Session updates: background sessions coming online, User Agent changes. Buffered = 32
supd chan *sessionUpdate
// Channel to terminate topic -- either the topic is deleted or system is being shut down. Buffered = 1.
exit chan *shutDown
// Channel to receive topic master responses (used only by proxy topics).
proxy chan *ClusterResp
// Channel to receive topic proxy service requests, e.g. sending deferred notifications.
master chan *ClusterSessUpdate
// Flag which tells topic lifecycle status: new, ready, paused, marked for deletion.
status int32
}
// perUserData holds topic's cache of per-subscriber data
type perUserData struct {
// Timestamps when the subscription was created and updated
created time.Time
updated time.Time
// Count of subscription online and announced (presence not deferred).
online int
// Last t.lastId reported by user through {pres} as received or read
recvID int
readID int
// ID of the latest Delete operation
delID int
private interface{}
modeWant types.AccessMode
modeGiven types.AccessMode
// P2P only:
public interface{}
topicName string
deleted bool
}
// perSubsData holds user's (on 'me' topic) cache of subscription data
type perSubsData struct {
// The other user's/topic's online status as seen by this user.
online bool
// True if we care about the updates from the other user/topic: (want&given).IsPresencer().
// Does not affect sending notifications from this user to other users.
enabled bool
}
// Data related to a subscription of a session to a topic.
type perSessionData struct {
// ID of the subscribed user (asUid); not necessarily the session owner.
// Could be zero for multiplexed sessions in cluster.
uid types.Uid
// This is a channel subscription
isChanSub bool
// IDs of subscribed users in a multiplexing session.
muids []types.Uid
}
// Reasons why topic is being shut down.
const (
// StopNone no reason given/default.
StopNone = iota
// StopShutdown terminated due to system shutdown.
StopShutdown
// StopDeleted terminated due to being deleted.
StopDeleted
// StopRehashing terminated due to cluster rehashing (moved to a different node).
StopRehashing
)
// Topic shutdown
type shutDown struct {
// Channel to report back completion of topic shutdown. Could be nil
done chan<- bool
// Topic is being deleted as opposite to total system shutdown
reason int
}
// Session update: user agent change or background session becoming normal.
// If sess is nil then user agent change, otherwise bg to fg update.
type sessionUpdate struct {
sess *Session
userAgent string
}
var nilPresParams = &presParams{}
var nilPresFilters = &presFilters{}
func (t *Topic) run(hub *Hub) {
if !t.isProxy {
t.runLocal(hub)
} else {
t.runProxy(hub)
}
}
// getPerUserAcs returns `want` and `given` permissions for the given user id.
func (t *Topic) getPerUserAcs(uid types.Uid) (types.AccessMode, types.AccessMode) {
if uid.IsZero() {
// For zero uids (typically for proxy sessions), return the union of all permissions.
return t.modeWantUnion, t.modeGivenUnion
}
pud := t.perUser[uid]
return pud.modeWant, pud.modeGiven
}
// passesPresenceFilters applies presence filters to `msg`
// depending on per-user want and given acls for the provided `uid`.
func (t *Topic) passesPresenceFilters(pres *MsgServerPres, uid types.Uid) bool {
modeWant, modeGiven := t.getPerUserAcs(uid)
// "gone" and "acs" notifications are sent even if the topic is muted.
return ((modeGiven & modeWant).IsPresencer() || pres.What == "gone" || pres.What == "acs") &&
(pres.FilterIn == 0 || int(modeGiven&modeWant)&pres.FilterIn != 0) &&
(pres.FilterOut == 0 || int(modeGiven&modeWant)&pres.FilterOut == 0)
}
// userIsReader returns true if the user (specified by `uid`) may read the given topic.
func (t *Topic) userIsReader(uid types.Uid) bool {
modeWant, modeGiven := t.getPerUserAcs(uid)
return (modeGiven & modeWant).IsReader()
}
// maybeFixTopicName sets the topic field in `msg` depending on the uid.
func (t *Topic) maybeFixTopicName(msg *ServerComMessage, uid types.Uid) {
// For zero uids we don't know the proper topic name.
if uid.IsZero() {
return
}
if t.cat == types.TopicCatP2P || (t.cat == types.TopicCatGrp && t.isChan) {
// For p2p topics topic name is dependent on receiver.
// Channel topics may be presented as grpXXX or chnXXX.
switch {
case msg.Data != nil:
msg.Data.Topic = t.original(uid)
case msg.Pres != nil:
msg.Pres.Topic = t.original(uid)
case msg.Info != nil:
msg.Info.Topic = t.original(uid)
}
}
}
// computePerUserAcsUnion computes want and given permissions unions over all topic's subscribers.
func (t *Topic) computePerUserAcsUnion() {
wantUnion := types.ModeNone
givenUnion := types.ModeNone
for _, pud := range t.perUser {
wantUnion = wantUnion | pud.modeWant
givenUnion = givenUnion | pud.modeGiven
}
t.modeWantUnion = wantUnion
t.modeGivenUnion = givenUnion
}
// fixUpUserCounts decrements online counts for the provided user ids.
func (t *Topic) fixUpUserCounts(userCounts map[types.Uid]int) {
for uid, decrementBy := range userCounts {
if pud, ok := t.perUser[uid]; ok {
pud.online -= decrementBy
t.perUser[uid] = pud
if pud.online < 0 {
log.Printf("topic[%s]: invalid online count for user %s", t.name, uid)
}
}
}
}
func (t *Topic) runLocal(hub *Hub) {
// Kills topic after a period of inactivity.
keepAlive := idleMasterTopicTimeout
killTimer := time.NewTimer(time.Hour)
killTimer.Stop()
// Notifies about user agent change. 'me' only
uaTimer := time.NewTimer(time.Minute)
var currentUA string
uaTimer.Stop()
// Ticker for deferred presence notifications.
defrNotifTimer := time.NewTimer(time.Millisecond * 500)
for {
select {
case join := <-t.reg:
// Request to add a connection to this topic
if t.isInactive() {
join.sess.queueOut(ErrLockedReply(join.pkt, types.TimeNow()))
} else {
// The topic is alive, so stop the kill timer, if it's ticking. We don't want the topic to die
// while processing the call
killTimer.Stop()
if err := t.handleSubscription(hub, join); err == nil {
if join.pkt.Sub.Created {
// Call plugins with the new topic
pluginTopic(t, plgActCreate)
}
} else {
if len(t.sessions) == 0 && t.cat != types.TopicCatSys {
// Failed to subscribe, the topic is still inactive
killTimer.Reset(keepAlive)
}
log.Printf("topic[%s] subscription failed %v, sid=%s", t.name, err, join.sess.sid)
}
}
if join.sess.inflightReqs != nil {
join.sess.inflightReqs.Done()
}
case leave := <-t.unreg:
t.handleLeaveRequest(hub, leave)
if leave.pkt != nil && leave.sess.inflightReqs != nil {
// If it's a client initiated request.
leave.sess.inflightReqs.Done()
}
// If there are no more subscriptions to this topic, start a kill timer
if len(t.sessions) == 0 && t.cat != types.TopicCatSys {
killTimer.Reset(keepAlive)
}
case msg := <-t.broadcast:
// Content message intended for broadcasting to recipients
t.handleBroadcast(msg)
case meta := <-t.meta:
// Request to get/set topic metadata
asUid := types.ParseUserId(meta.pkt.AsUser)
authLevel := auth.Level(meta.pkt.AuthLvl)
switch {
case meta.pkt.Get != nil:
// Get request
if meta.pkt.MetaWhat&constMsgMetaDesc != 0 {
if err := t.replyGetDesc(meta.sess, asUid, meta.pkt.Get.Desc, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Get.Desc failed: %s", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaSub != 0 {
if err := t.replyGetSub(meta.sess, asUid, authLevel, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Get.Sub failed: %s", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaData != 0 {
if err := t.replyGetData(meta.sess, asUid, meta.pkt.Get.Data, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Get.Data failed: %s", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaDel != 0 {
if err := t.replyGetDel(meta.sess, asUid, meta.pkt.Get.Del, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Get.Del failed: %s", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaTags != 0 {
if err := t.replyGetTags(meta.sess, asUid, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Get.Tags failed: %s", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaCred != 0 {
log.Printf("topic[%s] handle getCred", t.name)
if err := t.replyGetCreds(meta.sess, asUid, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Get.Creds failed: %s", t.name, err)
}
}
case meta.pkt.Set != nil:
// Set request
if meta.pkt.MetaWhat&constMsgMetaDesc != 0 {
if err := t.replySetDesc(meta.sess, asUid, meta.pkt); err == nil {
// Notify plugins of the update
pluginTopic(t, plgActUpd)
} else {
log.Printf("topic[%s] meta.Set.Desc failed: %v", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaSub != 0 {
if err := t.replySetSub(hub, meta.sess, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Set.Sub failed: %v", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaTags != 0 {
if err := t.replySetTags(meta.sess, asUid, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Set.Tags failed: %v", t.name, err)
}
}
if meta.pkt.MetaWhat&constMsgMetaCred != 0 {
if err := t.replySetCred(meta.sess, asUid, authLevel, meta.pkt); err != nil {
log.Printf("topic[%s] meta.Set.Cred failed: %v", t.name, err)
}
}
case meta.pkt.Del != nil:
// Del request
var err error
switch meta.pkt.MetaWhat {
case constMsgDelMsg:
err = t.replyDelMsg(meta.sess, asUid, meta.pkt)
case constMsgDelSub:
err = t.replyDelSub(hub, meta.sess, asUid, meta.pkt)
case constMsgDelTopic:
err = t.replyDelTopic(hub, meta.sess, asUid, meta.pkt)
case constMsgDelCred:
err = t.replyDelCred(hub, meta.sess, asUid, authLevel, meta.pkt)
}
if err != nil {
log.Printf("topic[%s] meta.Del failed: %v", t.name, err)
}
}
case upd := <-t.supd:
if upd.sess != nil {
// 'me' & 'grp' only. Background session timed out and came online.
t.sessToForeground(upd.sess)
} else if currentUA != upd.userAgent {
if t.cat != types.TopicCatMe {
log.Panicln("invalid topic category in UA update", t.name)
}
// 'me' only. Process an update to user agent from one of the sessions.
currentUA = upd.userAgent
uaTimer.Reset(uaTimerDelay)
}
case <-uaTimer.C:
// Publish user agent changes after a delay
if currentUA == "" || currentUA == t.userAgent {
continue
}
t.userAgent = currentUA
t.presUsersOfInterest("ua", t.userAgent)
case <-killTimer.C:
// Topic timeout
hub.unreg <- &topicUnreg{rcptTo: t.name}
defrNotifTimer.Stop()
if t.cat == types.TopicCatMe {
uaTimer.Stop()
t.presUsersOfInterest("off", currentUA)
} else if t.cat == types.TopicCatGrp {
t.presSubsOffline("off", nilPresParams, nilPresFilters, nilPresFilters, "", false)
}
case sd := <-t.exit:
// Handle four cases:
// 1. Topic is shutting down by timer due to inactivity (reason == StopNone)
// 2. Topic is being deleted (reason == StopDeleted)
// 3. System shutdown (reason == StopShutdown, done != nil).
// 4. Cluster rehashing (reason == StopRehashing)
if sd.reason == StopDeleted {
if t.cat == types.TopicCatGrp {
t.presSubsOffline("gone", nilPresParams, nilPresFilters, nilPresFilters, "", false)
}
// P2P users get "off+remove" earlier in the process
// Inform plugins that the topic is deleted
pluginTopic(t, plgActDel)
} else if sd.reason == StopRehashing {
// Must send individual messages to sessions because normal sending through the topic's
// broadcast channel won't work - it will be shut down too soon.
t.presSubsOnlineDirect("term", nilPresParams, nilPresFilters, "")
}
// In case of a system shutdown don't bother with notifications. They won't be delivered anyway.
// Tell sessions to remove the topic
for s := range t.sessions {
s.detachSession(t.name)
}
usersRegisterTopic(t, false)
// Report completion back to sender, if 'done' is not nil.
if sd.done != nil {
sd.done <- true
}
return
}
}
}
// Session subscribed to a topic, created == true if topic was just created and {pres} needs to be announced
func (t *Topic) handleSubscription(h *Hub, join *sessionJoin) error {
asUid := types.ParseUserId(join.pkt.AsUser)
authLevel := auth.Level(join.pkt.AuthLvl)
asChan := isChannel(join.pkt.Original)
msgsub := join.pkt.Sub
getWhat := 0
if msgsub.Get != nil {
getWhat = parseMsgClientMeta(msgsub.Get.What)
}
if err := t.subscriptionReply(h, asChan, join); err != nil {
return err
}
if getWhat&constMsgMetaDesc != 0 {
// Send get.desc as a {meta} packet.
if err := t.replyGetDesc(join.sess, asUid, msgsub.Get.Desc, join.pkt); err != nil {
log.Printf("topic[%s] handleSubscription Get.Desc failed: %v sid=%s", t.name, err, join.sess.sid)
}
}
if getWhat&constMsgMetaSub != 0 {
// Send get.sub response as a separate {meta} packet
if err := t.replyGetSub(join.sess, asUid, authLevel, join.pkt); err != nil {
log.Printf("topic[%s] handleSubscription Get.Sub failed: %v sid=%s", t.name, err, join.sess.sid)
}
}
if getWhat&constMsgMetaTags != 0 {
// Send get.tags response as a separate {meta} packet
if err := t.replyGetTags(join.sess, asUid, join.pkt); err != nil {
log.Printf("topic[%s] handleSubscription Get.Tags failed: %v sid=%s", t.name, err, join.sess.sid)
}
}
if getWhat&constMsgMetaCred != 0 {
// Send get.tags response as a separate {meta} packet
if err := t.replyGetCreds(join.sess, asUid, join.pkt); err != nil {
log.Printf("topic[%s] handleSubscription Get.Cred failed: %v sid=%s", t.name, err, join.sess.sid)
}
}
if getWhat&constMsgMetaData != 0 {
// Send get.data response as {data} packets
if err := t.replyGetData(join.sess, asUid, msgsub.Get.Data, join.pkt); err != nil {
log.Printf("topic[%s] handleSubscription Get.Data failed: %v sid=%s", t.name, err, join.sess.sid)
}
}
if getWhat&constMsgMetaDel != 0 {
// Send get.del response as a separate {meta} packet
if err := t.replyGetDel(join.sess, asUid, msgsub.Get.Del, join.pkt); err != nil {
log.Printf("topic[%s] handleSubscription Get.Del failed: %v sid=%s", t.name, err, join.sess.sid)
}
}
return nil
}
// handleLeaveRequest processes a session leave request.
func (t *Topic) handleLeaveRequest(hub *Hub, leave *sessionLeave) {
// Remove connection from topic; session may continue to function
now := types.TimeNow()
// userId.IsZero() == true when the entire session is being dropped.
var asUid types.Uid
var asChan bool
if leave.pkt != nil {
asUid = types.ParseUserId(leave.pkt.AsUser)
var err error
asChan, err = t.verifyChannelAccess(leave.pkt.Original)
if err != nil {
// Group topic cannot be addressed as channel unless channel functionality is enabled.
leave.sess.queueOut(ErrNotFoundReply(leave.pkt, now))
}
}
if t.isInactive() {
if !asUid.IsZero() && leave.pkt != nil {
leave.sess.queueOut(ErrLockedReply(leave.pkt, now))
}
return
} else if asChan && !t.isChan {
if leave.pkt != nil {
// Group topic cannot be addressed as channel unless channel functionality is enabled.
leave.sess.queueOut(ErrNotFoundReply(leave.pkt, now))
}
return
} else if leave.pkt != nil && leave.pkt.Leave.Unsub {
// User wants to leave and unsubscribe.
// asUid must not be Zero.
if err := t.replyLeaveUnsub(hub, leave.sess, leave.pkt, asUid); err != nil {
log.Println("failed to unsub", err, leave.sess.sid)
return
}
} else if pssd, _ := t.remSession(leave.sess, asUid); pssd != nil {
if pssd.isChanSub && asChan {
if leave.pkt != nil {
leave.sess.queueOut(NoErr(leave.pkt.Id, leave.pkt.Original, now))
}
return
}
if pssd.isChanSub != asChan {
// Cannot address non-channel subscription as channel and vice versa.
if leave.pkt != nil {
// Group topic cannot be addressed as channel unless channel functionality is enabled.
leave.sess.queueOut(ErrNotFoundReply(leave.pkt, now))
}
return
}
var uid types.Uid
if leave.sess.isProxy() {
// Multiplexing session, multiple UIDs.
uid = asUid
} else {
// Simple session, single UID.
uid = pssd.uid
}
var pud perUserData
// uid may be zero when a proxy session is trying to terminate (it called unsubAll).
if !uid.IsZero() {
// UID not zero: one user removed.
pud = t.perUser[uid]
if !leave.sess.background {
pud.online--
}
} else if len(pssd.muids) > 0 {
// UID is zero: multiplexing session is dropped altogether.
// Using new 'uid' and 'pud' variables.
for _, uid := range pssd.muids {
pud := t.perUser[uid]
pud.online--
t.perUser[uid] = pud
}
} else if !leave.sess.isCluster() {
log.Panic("cannot determine uid: leave req=", leave)
}
switch t.cat {
case types.TopicCatMe:
mrs := t.mostRecentSession()
if mrs == nil {
// Last session
mrs = leave.sess
} else {
// Change UA to the most recent live session and announce it. Don't block.
select {
case t.supd <- &sessionUpdate{userAgent: mrs.userAgent}:
default:
}
}
meUid := uid
if meUid.IsZero() && len(pssd.muids) > 0 {
// The entire multiplexing session is being dropped. Need to find owner's UID.
// len(pssd.muids) could be zero if the session was a background session.
meUid = pssd.muids[0]
}
if !meUid.IsZero() {
// Update user's last online timestamp & user agent. Only one user can be subscribed to 'me' topic.
if err := store.Users.UpdateLastSeen(meUid, mrs.userAgent, now); err != nil {
log.Println(err)
}
}
case types.TopicCatFnd:
// FIXME: this does not work correctly in case of a multiplexing query.
// Remove ephemeral query.
t.fndRemovePublic(leave.sess)
case types.TopicCatGrp:
// Topic is going offline: notify online subscribers on 'me'.
readFilter := &presFilters{filterIn: types.ModeRead}
if !uid.IsZero() {
if pud.online == 0 {
t.presSubsOnline("off", uid.UserId(), nilPresParams, readFilter, "")
}
} else if len(pssd.muids) > 0 {
for _, uid := range pssd.muids {
if t.perUser[uid].online == 0 {
t.presSubsOnline("off", uid.UserId(), nilPresParams, readFilter, "")
}
}
}
}
if !uid.IsZero() {
t.perUser[uid] = pud
// Respond if contains an id.
if leave.pkt != nil {
leave.sess.queueOut(NoErrReply(leave.pkt, now))
}
}
}
}
// sessToForeground updates perUser online status accounting and fires due
// deferred notifications for the provided session.
func (t *Topic) sessToForeground(sess *Session) {
s := sess
if s.multi != nil {
s = s.multi
}
if pssd, ok := t.sessions[s]; ok && !pssd.isChanSub {
uid := pssd.uid
if s.isMultiplex() {
// If 's' is a multiplexing session, then sess is a proxy and it contains correct UID.
// Add UID to the list of online users.
uid := sess.uid
pssd.muids = append(pssd.muids, uid)
}
// Mark user as online
pud := t.perUser[uid]
pud.online++
t.perUser[uid] = pud
t.sendSubNotifications(uid, sess.sid, sess.userAgent)
}
}
// Subscribe or unsubscribe user to/from FCM topic (channel).
func (t *Topic) channelSubUnsub(uid types.Uid, sub bool) {
push.ChannelSub(&push.ChannelReq{
Uid: uid,
Channel: types.GrpToChn(t.name),
Unsub: !sub})
}
// Send immediate presence notification in response to a subscription.
// Send push notification to the P2P counterpart.
// In case of a new channel subscription subscribe user to an FCM topic.
// These notifications are always sent immediately even if background is requested.
func (t *Topic) sendImmediateSubNotifications(asUid types.Uid, acs *MsgAccessMode, sreg *sessionJoin) {
modeWant, _ := types.ParseAcs([]byte(acs.Want))
modeGiven, _ := types.ParseAcs([]byte(acs.Given))
mode := modeWant & modeGiven
if t.cat == types.TopicCatP2P {
uid2 := t.p2pOtherUser(asUid)
pud2 := t.perUser[uid2]
mode2 := pud2.modeGiven & pud2.modeWant
if pud2.deleted {
mode2 = types.ModeInvalid
}
// Inform the other user that the topic was just created.
if sreg.pkt.Sub.Created {
t.presSingleUserOffline(uid2, mode2, "acs", &presParams{
dWant: pud2.modeWant.String(),
dGiven: pud2.modeGiven.String(),
actor: asUid.UserId()}, "", false)
}
if sreg.pkt.Sub.Newsub {
// Notify current user's 'me' topic to accept notifications from user2
t.presSingleUserOffline(asUid, mode, "?none+en", nilPresParams, "", false)
// Initiate exchange of 'online' status with the other user.
// We don't know if the current user is online in the 'me' topic,
// so sending an '?unkn' status to user2. His 'me' topic
// will reply with user2's status and request an actual status from user1.
status := "?unkn"
if mode2.IsPresencer() {
// If user2 should receive notifications, enable it.
status += "+en"
}
t.presSingleUserOffline(uid2, mode2, status, nilPresParams, "", false)
// Also send a push notification to the other user.
if pushRcpt := t.pushForSub(asUid, uid2, pud2.modeWant, pud2.modeGiven, types.TimeNow()); pushRcpt != nil {
usersPush(pushRcpt)
}
}
}
// newsub could be true only for p2p and group topics, no need to check topic category explicitly.
if sreg.pkt.Sub.Newsub {
// Notify creator's other sessions that the subscription (or the entire topic) was created.
t.presSingleUserOffline(asUid, mode, "acs",
&presParams{
dWant: acs.Want,
dGiven: acs.Given,
actor: asUid.UserId()},
sreg.sess.sid, false)
if t.isChan && isChannel(sreg.pkt.Original) {
t.channelSubUnsub(asUid, true)
}
}
}
// Send immediate or deferred presence notification in response to a subscription.
// Not used by channels.
func (t *Topic) sendSubNotifications(asUid types.Uid, sid, userAgent string) {
switch t.cat {
case types.TopicCatMe:
// Notify user's contact that the given user is online now.
if !t.isLoaded() {
t.markLoaded()
if err := t.loadContacts(asUid); err != nil {
log.Println("topic: failed to load contacts", t.name, err.Error())
}
// User online: notify users of interest without forcing response (no +en here).
t.presUsersOfInterest("on", userAgent)
}
case types.TopicCatGrp:
pud := t.perUser[asUid]
// Enable notifications for a new group topic, if appropriate.
if !t.isLoaded() {
t.markLoaded()
status := "on"
if (pud.modeGiven & pud.modeWant).IsPresencer() {
status += "+en"
}
// Notify topic subscribers that the topic is online now.
t.presSubsOffline(status, nilPresParams, nilPresFilters, nilPresFilters, "", false)
} else if pud.online == 1 {
// If this is the first session of the user in the topic.
// Notify other online group members that the user is online now.
t.presSubsOnline("on", asUid.UserId(), nilPresParams,
&presFilters{filterIn: types.ModeRead}, sid)
}
}
}
// handleBroadcast fans out broadcastable messages to recipients in topic and proxy_topic.
func (t *Topic) handleBroadcast(msg *ServerComMessage) {
asUid := types.ParseUserId(msg.AsUser)
if t.isInactive() {
// Ignore broadcast - topic is paused or being deleted.
if msg.Data != nil {
msg.sess.queueOut(ErrLocked(msg.Id, t.original(asUid), msg.Timestamp))
}
return
}
var pushRcpt *push.Receipt
if msg.Data != nil {
if t.isReadOnly() {
msg.sess.queueOut(ErrPermissionDenied(msg.Id, t.original(asUid), msg.Timestamp))
return
}
asUser := types.ParseUserId(msg.Data.From)
userData, userFound := t.perUser[asUser]
// Anyone is allowed to post to 'sys' topic.
if t.cat != types.TopicCatSys {
// If it's not 'sys' check write permission.
if !(userData.modeWant & userData.modeGiven).IsWriter() {
msg.sess.queueOut(ErrPermissionDenied(msg.Id, t.original(asUid), msg.Timestamp))
return
}
}
if t.isProxy {
t.lastID = msg.Data.SeqId
} else {
// Save to DB at master topic.
if err := store.Messages.Save(&types.Message{
ObjHeader: types.ObjHeader{CreatedAt: msg.Data.Timestamp},
SeqId: t.lastID + 1,
Topic: t.name,
From: asUser.String(),
Head: msg.Data.Head,
Content: msg.Data.Content}, (userData.modeGiven & userData.modeWant).IsReader()); err != nil {
log.Printf("topic[%s]: failed to save message: %v", t.name, err)
msg.sess.queueOut(ErrUnknown(msg.Id, t.original(asUid), msg.Timestamp))
return
}
t.lastID++
t.touched = msg.Data.Timestamp
msg.Data.SeqId = t.lastID
}
if userFound {
userData.readID = t.lastID
userData.readID = t.lastID
t.perUser[asUser] = userData
}
if msg.Id != "" && msg.sess != nil {
reply := NoErrAccepted(msg.Id, t.original(asUid), msg.Timestamp)
reply.Ctrl.Params = map[string]int{"seq": t.lastID}
msg.sess.queueOut(reply)
}
if !t.isProxy {
pushRcpt = t.pushForData(asUser, msg.Data)
// Message sent: notify offline 'R' subscrbers on 'me'.
t.presSubsOffline("msg", &presParams{seqID: t.lastID, actor: msg.Data.From},
&presFilters{filterIn: types.ModeRead}, nilPresFilters, "", true)
// Tell the plugins that a message was accepted for delivery
pluginMessage(msg.Data, plgActCreate)
}
} else if msg.Pres != nil {
what := t.presProcReq(msg.Pres.Src, msg.Pres.What, msg.Pres.WantReply)
if t.xoriginal != msg.Pres.Topic || what == "" {
// This is just a request for status, don't forward it to sessions
return
}
// "what" may have changed, i.e. unset or "+command" removed ("on+en" -> "on")
msg.Pres.What = what
} else if msg.Info != nil {
if msg.Info.SeqId > t.lastID {
// Drop bogus read notification
return
}
asUser := types.ParseUserId(msg.Info.From)
pud := t.perUser[asUser]
mode := pud.modeGiven & pud.modeWant
if pud.deleted {
mode = types.ModeInvalid
}
// Filter out "kp" from users with no 'W' permission (or people without a subscription)
if msg.Info.What == "kp" && (!mode.IsWriter() || t.isReadOnly()) {
return
}
if msg.Info.What == "read" || msg.Info.What == "recv" {
// Filter out "read/recv" from users with no 'R' permission (or people without a subscription)
if !mode.IsReader() {
return
}
var read, recv, unread int
if msg.Info.What == "read" {
if msg.Info.SeqId > pud.readID {
// The number of unread messages has decreased, negative value
unread = pud.readID - msg.Info.SeqId
pud.readID = msg.Info.SeqId
read = pud.readID
} else {
// No need to report stale or bogus read status
return
}
} else if msg.Info.What == "recv" {
if msg.Info.SeqId > pud.recvID {
pud.recvID = msg.Info.SeqId
recv = pud.recvID
} else {
return
}
}
if pud.readID > pud.recvID {
pud.recvID = pud.readID
recv = pud.recvID
}
if !t.isProxy {
if err := store.Subs.Update(t.name, asUser,
map[string]interface{}{
"RecvSeqId": pud.recvID,
"ReadSeqId": pud.readID},
false); err != nil {
log.Printf("topic[%s]: failed to update SeqRead/Recv counter: %v", t.name, err)
return
}
// Read/recv updated: notify user's other sessions of the change
t.presPubMessageCount(asUser, mode, recv, read, msg.SkipSid)
// Update cached count of unread messages
usersUpdateUnread(asUser, unread, true)
}
t.perUser[asUser] = pud
}
} else {
// TODO(gene): remove this
log.Panic("topic: wrong message type for broadcasting", t.name)
}
// Broadcast the message. Only {data}, {pres}, {info} are broadcastable.
// {meta} and {ctrl} are sent to the session only
for sess, pssd := range t.sessions {
// Send all messages to multiplexing session.
if !sess.isMultiplex() {
if sess.sid == msg.SkipSid {
continue
}
if msg.Pres != nil {
// Skip notifying - already notified on topic.