forked from tinode/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopic.go
2862 lines (2469 loc) · 87.8 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 (
"container/list"
"errors"
"log"
"sort"
"sync/atomic"
"time"
"github.com/tinode/chat/server/auth"
"github.com/tinode/chat/server/push"
"github.com/tinode/chat/server/store"
"github.com/tinode/chat/server/store/types"
)
// Time between subscription of a background session and when the notifications are sent.
// If session unsubscribes in this time frame notifications are not sent at all.
const deferredNotificationsTimeout = time.Second * 5
// 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
// TODO(gene): currently unused
// 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
// 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
// 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
// Queue of delayed presence updates from successful service (background) subscriptions.
defrNotif *list.List
// Inbound {data} and {pres} messages from sessions or other topics, already converted to SCM. 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
// Track the most active sessions to report User Agent changes. Buffered = 32
uaChange chan string
// Channel to terminate topic -- either the topic is deleted or system is being shut down. Buffered = 1.
exit chan *shutDown
// 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.
uid types.Uid
// Reference to a list bucket with deferred notification or nil if no notifications are deferred.
ref *list.Element
}
// 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
}
var nilPresParams = &presParams{}
var nilPresFilters = &presFilters{}
func (t *Topic) run(hub *Hub) {
// Kills topic after a period of inactivity.
keepAlive := idleTopicTimeout
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 sreg := <-t.reg:
// Request to add a connection to this topic
if t.isInactive() {
asUid := types.ParseUserId(sreg.pkt.from)
sreg.sess.queueOut(ErrLocked(sreg.pkt.id, t.original(asUid), 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, sreg); err == nil {
if sreg.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, sreg.sess.sid)
}
}
case leave := <-t.unreg:
// Remove connection from topic; session may continue to function
now := types.TimeNow()
// userId.IsZero() == true when the entire session is being dropped.
asUid := leave.userId
if t.isInactive() {
if !asUid.IsZero() && leave.id != "" {
leave.sess.queueOut(ErrLocked(leave.id, t.original(asUid), now))
}
continue
} else if leave.unsub {
// User wants to leave and unsubscribe.
// asUid must not be Zero.
if err := t.replyLeaveUnsub(hub, leave.sess, asUid, leave.id); err != nil {
log.Println("failed to unsub", err, leave.sess.sid)
continue
}
} else if pssd := t.remSession(leave.sess, asUid); pssd != nil {
// Just leaving the topic without unsubscribing if user is subscribed.
pud := t.perUser[pssd.uid]
if pssd.ref == nil {
pud.online--
}
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.uaChange <- mrs.userAgent:
default:
}
}
// Update user's last online timestamp & user agent
if err := store.Users.UpdateLastSeen(asUid, mrs.userAgent, now); err != nil {
log.Println(err)
}
case types.TopicCatFnd:
// Remove ephemeral query.
t.fndRemovePublic(leave.sess)
case types.TopicCatGrp:
if pud.online == 0 {
// User is going offline: notify online subscribers on 'me'
t.presSubsOnline("off", asUid.UserId(), nilPresParams,
&presFilters{filterIn: types.ModeRead}, "")
}
}
t.perUser[pssd.uid] = pud
if leave.id != "" {
leave.sess.queueOut(NoErr(leave.id, t.original(asUid), now))
}
}
// 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
var pushRcpt *push.Receipt
asUid := types.ParseUserId(msg.from)
if msg.Data != nil {
if t.isInactive() {
msg.sess.queueOut(ErrLocked(msg.id, t.original(asUid), msg.timestamp))
continue
}
if t.isReadOnly() {
msg.sess.queueOut(ErrPermissionDenied(msg.id, t.original(asUid), msg.timestamp))
continue
}
from := types.ParseUserId(msg.Data.From)
userData, userFound := t.perUser[from]
// 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))
continue
}
}
if err := store.Messages.Save(&types.Message{
ObjHeader: types.ObjHeader{CreatedAt: msg.Data.Timestamp},
SeqId: t.lastID + 1,
Topic: t.name,
From: from.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))
continue
}
t.lastID++
t.touched = msg.Data.Timestamp
msg.Data.SeqId = t.lastID
if userFound {
userData.readID = t.lastID
userData.readID = t.lastID
t.perUser[from] = userData
}
if msg.id != "" {
reply := NoErrAccepted(msg.id, t.original(asUid), msg.timestamp)
reply.Ctrl.Params = map[string]int{"seq": t.lastID}
msg.sess.queueOut(reply)
}
pushRcpt = t.pushForData(from, 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}, "", true)
// Tell the plugins that a message was accepted for delivery
pluginMessage(msg.Data, plgActCreate)
} else if msg.Pres != nil {
if t.isInactive() {
// Ignore presence update - topic is paused or being deleted
continue
}
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
continue
}
// "what" may have changed, i.e. unset or "+command" removed ("on+en" -> "on")
msg.Pres.What = what
} else if msg.Info != nil {
if t.isInactive() {
// Ignore info messages - topic is paused or being deleted
continue
}
if msg.Info.SeqId > t.lastID {
// Drop bogus read notification
continue
}
from := types.ParseUserId(msg.Info.From)
pud := t.perUser[from]
// Filter out "kp" from users with no 'W' permission (or people without a subscription)
if msg.Info.What == "kp" && (!(pud.modeGiven & pud.modeWant).IsWriter() || t.isReadOnly()) {
continue
}
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 !(pud.modeGiven & pud.modeWant).IsReader() {
continue
}
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
continue
}
} else if msg.Info.What == "recv" {
if msg.Info.SeqId > pud.recvID {
pud.recvID = msg.Info.SeqId
recv = pud.recvID
} else {
continue
}
}
if pud.readID > pud.recvID {
pud.recvID = pud.readID
recv = pud.recvID
}
if err := store.Subs.Update(t.name, from,
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)
continue
}
// Read/recv updated: notify user's other sessions of the change
t.presPubMessageCount(from, recv, read, msg.skipSid)
// Update cached count of unread messages
usersUpdateUnread(from, unread, true)
t.perUser[from] = pud
}
}
// Broadcast the message. Only {data}, {pres}, {info} are broadcastable.
// {meta} and {ctrl} are sent to the session only
if msg.Data != nil || msg.Pres != nil || msg.Info != nil {
for sess, pssd := range t.sessions {
if sess.sid == msg.skipSid {
continue
}
if msg.Pres != nil {
// Skip notifying - already notified on topic.
if msg.Pres.SkipTopic != "" && sess.getSub(msg.Pres.SkipTopic) != nil {
continue
}
// Notification addressed to a single user only
if msg.Pres.SingleUser != "" && pssd.uid.UserId() != msg.Pres.SingleUser {
continue
}
// Check presence filters
pud := t.perUser[pssd.uid]
// Send "gone" and "acs" notifications even if the topic is muted.
if (!(pud.modeGiven & pud.modeWant).IsPresencer() && msg.Pres.What != "gone" && msg.Pres.What != "acs") ||
(msg.Pres.FilterIn != 0 && int(pud.modeGiven&pud.modeWant)&msg.Pres.FilterIn == 0) ||
(msg.Pres.FilterOut != 0 && int(pud.modeGiven&pud.modeWant)&msg.Pres.FilterOut != 0) {
continue
}
} else {
// Check if the user has Read permission
pud := t.perUser[pssd.uid]
if !(pud.modeGiven & pud.modeWant).IsReader() {
continue
}
// Don't send key presses from one user's session to the other sessions of the same user.
if msg.Info != nil && msg.Info.What == "kp" && msg.Info.From == pssd.uid.UserId() {
continue
}
}
if t.cat == types.TopicCatP2P {
// For p2p topics topic name is dependent on receiver
switch {
case msg.Data != nil:
msg.Data.Topic = t.original(pssd.uid)
case msg.Pres != nil:
msg.Pres.Topic = t.original(pssd.uid)
case msg.Info != nil:
msg.Info.Topic = t.original(pssd.uid)
}
}
if sess.queueOut(msg) {
// Update device map with the device ID which should NOT receive the notification.
if pushRcpt != nil {
if addr, ok := pushRcpt.To[pssd.uid]; ok {
if pssd.ref == nil {
// Count foreground sessions only, background sessions are automated
// and should not affect pushes to other devices.
addr.Delivered++
}
if sess.deviceID != "" {
// List of device IDs which already received the message. Push should
// skip them.
// The same device ID may appear twice.
addr.Devices = append(addr.Devices, sess.deviceID)
}
pushRcpt.To[pssd.uid] = addr
}
}
} else {
log.Printf("topic[%s]: connection stuck, detaching", t.name)
// The whole session is being dropped, so sessionLeave.userId is not set.
t.unreg <- &sessionLeave{sess: sess}
}
}
if pushRcpt != nil {
// usersPush will update unread message count and send push notification.
usersPush(pushRcpt)
}
} else {
// TODO(gene): remove this
log.Panic("topic: wrong message type for broadcasting", t.name)
}
case meta := <-t.meta:
// Request to get/set topic metadata
asUid := types.ParseUserId(meta.pkt.from)
authLevel := auth.Level(meta.pkt.authLvl)
switch {
case meta.pkt.Get != nil:
// Get request
if meta.what&constMsgMetaDesc != 0 {
if err := t.replyGetDesc(meta.sess, asUid, meta.pkt.Get.Id, meta.pkt.Get.Desc); err != nil {
log.Printf("topic[%s] meta.Get.Desc failed: %s", t.name, err)
}
}
if meta.what&constMsgMetaSub != 0 {
if err := t.replyGetSub(meta.sess, asUid, authLevel, meta.pkt.Get.Id, meta.pkt.Get.Sub); err != nil {
log.Printf("topic[%s] meta.Get.Sub failed: %s", t.name, err)
}
}
if meta.what&constMsgMetaData != 0 {
if err := t.replyGetData(meta.sess, asUid, meta.pkt.Get.Id, meta.pkt.Get.Data); err != nil {
log.Printf("topic[%s] meta.Get.Data failed: %s", t.name, err)
}
}
if meta.what&constMsgMetaDel != 0 {
if err := t.replyGetDel(meta.sess, asUid, meta.pkt.Get.Id, meta.pkt.Get.Del); err != nil {
log.Printf("topic[%s] meta.Get.Del failed: %s", t.name, err)
}
}
if meta.what&constMsgMetaTags != 0 {
if err := t.replyGetTags(meta.sess, asUid, meta.pkt.Get.Id); err != nil {
log.Printf("topic[%s] meta.Get.Tags failed: %s", t.name, err)
}
}
if meta.what&constMsgMetaCred != 0 {
log.Printf("topic[%s] handle getCred", t.name)
if err := t.replyGetCreds(meta.sess, asUid, meta.pkt.Get.Id); err != nil {
log.Printf("topic[%s] meta.Get.Creds failed: %s", t.name, err)
}
}
case meta.pkt.Set != nil:
// Set request
if meta.what&constMsgMetaDesc != 0 {
if err := t.replySetDesc(meta.sess, asUid, meta.pkt.Set); 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.what&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.what&constMsgMetaTags != 0 {
if err := t.replySetTags(meta.sess, asUid, meta.pkt.Set); err != nil {
log.Printf("topic[%s] meta.Set.Tags failed: %v", t.name, err)
}
}
if meta.what&constMsgMetaCred != 0 {
if err := t.replySetCred(meta.sess, asUid, authLevel, meta.pkt.Set); 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.what {
case constMsgDelMsg:
err = t.replyDelMsg(meta.sess, asUid, meta.pkt.Del)
case constMsgDelSub:
err = t.replyDelSub(hub, meta.sess, asUid, meta.pkt.Del)
case constMsgDelTopic:
err = t.replyDelTopic(hub, meta.sess, asUid, meta.pkt.Del)
case constMsgDelCred:
err = t.replyDelCred(hub, meta.sess, asUid, authLevel, meta.pkt.Del)
}
if err != nil {
log.Printf("topic[%s] meta.Del failed: %v", t.name, err)
}
}
case ua := <-t.uaChange:
// Process an update to user agent from one of the sessions
currentUA = ua
uaTimer.Reset(uaTimerDelay)
case <-defrNotifTimer.C:
// Handle deferred presence notifications from a successful service (background) subscription.
if t.isInactive() {
continue
}
// Process events older than this timestamp.
expiration := time.Now().Add(-deferredNotificationsTimeout)
// Iterate through the list until all sufficiently old events are processed.
for elem := t.defrNotif.Back(); elem != nil; elem = t.defrNotif.Back() {
sreg := elem.Value.(*sessionJoin)
if expiration.Before(sreg.pkt.timestamp) {
// All done. Remaining events are newer.
break
}
t.defrNotif.Remove(elem)
if pssd, ok := t.sessions[sreg.sess]; ok {
userData := t.perUser[pssd.uid]
userData.online++
t.perUser[pssd.uid] = userData
pssd.ref = nil
t.sessions[sreg.sess] = pssd
}
t.sendSubNotifications(types.ParseUserId(sreg.pkt.from), sreg)
}
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{topic: 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, "", 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, "", 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")
}
// 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.detach <- 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, sreg *sessionJoin) error {
asUid := types.ParseUserId(sreg.pkt.from)
authLevel := auth.Level(sreg.pkt.authLvl)
msgsub := sreg.pkt.Sub
getWhat := 0
if msgsub.Get != nil {
getWhat = parseMsgClientMeta(msgsub.Get.What)
}
if err := t.subCommonReply(h, sreg); err != nil {
return err
}
// Send notifications.
// Some notifications are always sent immediately.
t.sendImmediateSubNotifications(asUid, sreg)
pssd, ok := t.sessions[sreg.sess]
if msgsub.Background && ok {
// Notifications are delayed.
pssd.ref = t.defrNotif.PushFront(sreg)
t.sessions[sreg.sess] = pssd
} else {
// Remaining notifications are also sent immediately.
t.sendSubNotifications(asUid, sreg)
}
if getWhat&constMsgMetaDesc != 0 {
// Send get.desc as a {meta} packet.
if err := t.replyGetDesc(sreg.sess, asUid, sreg.pkt.id, msgsub.Get.Desc); err != nil {
log.Printf("topic[%s] handleSubscription Get.Desc failed: %v sid=%s", t.name, err, sreg.sess.sid)
}
}
if getWhat&constMsgMetaSub != 0 {
// Send get.sub response as a separate {meta} packet
if err := t.replyGetSub(sreg.sess, asUid, authLevel, sreg.pkt.id, msgsub.Get.Sub); err != nil {
log.Printf("topic[%s] handleSubscription Get.Sub failed: %v sid=%s", t.name, err, sreg.sess.sid)
}
}
if getWhat&constMsgMetaTags != 0 {
// Send get.tags response as a separate {meta} packet
if err := t.replyGetTags(sreg.sess, asUid, sreg.pkt.id); err != nil {
log.Printf("topic[%s] handleSubscription Get.Tags failed: %v sid=%s", t.name, err, sreg.sess.sid)
}
}
if getWhat&constMsgMetaCred != 0 {
// Send get.tags response as a separate {meta} packet
if err := t.replyGetCreds(sreg.sess, asUid, sreg.pkt.id); err != nil {
log.Printf("topic[%s] handleSubscription Get.Cred failed: %v sid=%s", t.name, err, sreg.sess.sid)
}
}
if getWhat&constMsgMetaData != 0 {
// Send get.data response as {data} packets
if err := t.replyGetData(sreg.sess, asUid, sreg.pkt.id, msgsub.Get.Data); err != nil {
log.Printf("topic[%s] handleSubscription Get.Data failed: %v sid=%s", t.name, err, sreg.sess.sid)
}
}
if getWhat&constMsgMetaDel != 0 {
// Send get.del response as a separate {meta} packet
if err := t.replyGetDel(sreg.sess, asUid, sreg.pkt.id, msgsub.Get.Del); err != nil {
log.Printf("topic[%s] handleSubscription Get.Del failed: %v sid=%s", t.name, err, sreg.sess.sid)
}
}
return nil
}
// Send immediate presence notification in response to a subscription.
// These notifications are always sent immediately even if background is requested.
func (t *Topic) sendImmediateSubNotifications(asUid types.Uid, sreg *sessionJoin) {
pud := t.perUser[asUid]
if t.cat == types.TopicCatP2P {
uid2 := t.p2pOtherUser(asUid)
pud2 := t.perUser[uid2]
// Inform the other user that the topic was just created.
if sreg.created {
t.presSingleUserOffline(uid2, "acs", &presParams{
dWant: pud2.modeWant.String(),
dGiven: pud2.modeGiven.String(),
actor: asUid.UserId()}, "", false)
}
if sreg.newsub {
// Notify current user's 'me' topic to accept notifications from user2
t.presSingleUserOffline(asUid, "?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 (pud2.modeGiven & pud2.modeWant).IsPresencer() {
// If user2 should receive notifications, enable it.
status += "+en"
}
t.presSingleUserOffline(uid2, status, nilPresParams, "", false)
}
}
// newsub could be true only for p2p and group topics, no need to check topic category explicitly.
if sreg.newsub {
// Notify creator's other sessions that the subscription (or the entire topic) was created.
t.presSingleUserOffline(asUid, "acs",
&presParams{
dWant: pud.modeWant.String(),
dGiven: pud.modeGiven.String(),
actor: asUid.UserId()},
sreg.sess.sid, false)
}
}
// Send immediate or deferred presence notification in response to a subscription.
func (t *Topic) sendSubNotifications(asUid types.Uid, sreg *sessionJoin) {
pud := t.perUser[asUid]
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", sreg.sess.userAgent)
}
case types.TopicCatGrp:
// 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, "", 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}, sreg.sess.sid)
}
}
}
// subCommonReply generates a response to a subscription request
func (t *Topic) subCommonReply(h *Hub, sreg *sessionJoin) error {
// The topic is already initialized by the Hub
var now time.Time
// For newly created topics report topic creation time.
if sreg.created {
now = t.updated
} else {
now = types.TimeNow()
}
msgsub := sreg.pkt.Sub
asUid := types.ParseUserId(sreg.pkt.from)
asLvl := auth.Level(sreg.pkt.authLvl)
toriginal := t.original(asUid)
if !sreg.newsub && (t.cat == types.TopicCatP2P || t.cat == types.TopicCatGrp || t.cat == types.TopicCatSys) {
// Check if this is a new subscription.
_, found := t.perUser[asUid]
sreg.newsub = !found
}
var private interface{}
var mode string
if msgsub.Set != nil {
if msgsub.Set.Sub != nil {
if msgsub.Set.Sub.User != "" {
sreg.sess.queueOut(ErrMalformed(sreg.pkt.id, toriginal, now))
return errors.New("user id must not be specified")
}
mode = msgsub.Set.Sub.Mode
}
if msgsub.Set.Desc != nil {
private = msgsub.Set.Desc.Private
}
}
var err error
var changed bool
// Create new subscription or modify an existing one.
if changed, err = t.requestSub(h, sreg.sess, asUid, asLvl, sreg.pkt.id, mode, private, msgsub.Background); err != nil {
return err
}
params := map[string]interface{}{}
if changed {
pud := t.perUser[asUid]
// Report back the assigned access mode.
params["acs"] = &MsgAccessMode{
Given: pud.modeGiven.String(),
Want: pud.modeWant.String(),
Mode: (pud.modeGiven & pud.modeWant).String()}
}
// When a group topic is created, it's given a temporary name by the client.
// Then this name changes. Report back the original name here.
if sreg.created && sreg.pkt.topic != toriginal {
params["tmpname"] = sreg.pkt.topic
}
if len(params) == 0 {
// Don't send empty params '{}'
params = nil
}
sreg.sess.queueOut(NoErrParams(sreg.pkt.id, toriginal, now, params))
return nil
}
// User requests or updates a self-subscription to a topic. Called as a
// result of {sub} or {meta set=sub}.
// Returns changed == true if user's accessmode has changed.
//
// h - hub
// sess - originating session
// asUid - id of the user making the request
// asLvl - access level of the user making the request
// pktID - id of {sub} or {set} packet
// want - requested access mode
// private - private value to assign to the subscription
// background - presence notifications are deferred
//
// Handle these cases:
// A. User is trying to subscribe for the first time (no subscription)
// B. User is already subscribed, just joining without changing anything
// C. User is responding to an earlier invite (modeWant was "N" in subscription)
// D. User is already subscribed, changing modeWant
// E. User is accepting ownership transfer (requesting ownership transfer is not permitted)
func (t *Topic) requestSub(h *Hub, sess *Session, asUid types.Uid, asLvl auth.Level,
pktID, want string, private interface{}, background bool) (bool, error) {
now := types.TimeNow()
toriginal := t.original(asUid)
var changed bool
// Access mode values as they were before this request was processed.
oldWant := types.ModeNone
oldGiven := types.ModeNone
// Parse access mode requested by the user
modeWant := types.ModeUnset
if want != "" {
if err := modeWant.UnmarshalText([]byte(want)); err != nil {
sess.queueOut(ErrMalformed(pktID, toriginal, now))
return changed, err
}
}
// Check if it's an attempt at a new subscription to the topic.
// It could be an actual subscription (IsJoiner() == true) or a ban (IsJoiner() == false)
userData, existingSub := t.perUser[asUid]
if !existingSub || userData.deleted {
// Check if the max number of subscriptions is already reached.
if t.cat == types.TopicCatGrp && t.subsCount() >= globals.maxSubscriberCount {
sess.queueOut(ErrPolicy(pktID, toriginal, now))
return changed, errors.New("max subscription count exceeded")
}
if t.cat == types.TopicCatP2P {
// P2P could be here only if it was previously deleted. I.e. existingSub is always true for P2P.
if modeWant != types.ModeUnset {
userData.modeWant = modeWant
}
// If no modeWant is provided, leave existing one unchanged.
// Make sure the user is not asking for unreasonable permissions
userData.modeWant = (userData.modeWant & types.ModeCP2P) | types.ModeApprove
} else if t.cat == types.TopicCatSys {
if asLvl != auth.LevelRoot {
sess.queueOut(ErrPermissionDenied(pktID, toriginal, now))
return changed, errors.New("subscription to 'sys' topic requires root access level")
}
// Assign default access levels
userData.modeWant = types.ModeCSys
userData.modeGiven = types.ModeCSys
if modeWant != types.ModeUnset {
userData.modeWant = (modeWant & types.ModeCSys) | types.ModeWrite
}
} else {
// For non-p2p & non-sys topics access is given as default access
userData.modeGiven = t.accessFor(asLvl)
if modeWant == types.ModeUnset {
// User wants default access mode.
userData.modeWant = userData.modeGiven
} else {
userData.modeWant = modeWant
}