-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
session.go
1383 lines (1213 loc) · 39 KB
/
session.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 :
*
* Handling of user sessions/connections. One user may have multiple sesions.
* Each session may handle multiple topics
*
*****************************************************************************/
package main
import (
"container/list"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/tinode/chat/pbx"
"github.com/tinode/chat/server/auth"
"github.com/tinode/chat/server/logs"
"github.com/tinode/chat/server/store"
"github.com/tinode/chat/server/store/types"
"golang.org/x/text/language"
)
// Maximum number of queued messages before session is considered stale and dropped.
const sendQueueLimit = 128
// Time given to a background session to terminate to avoid tiggering presence notifications.
// If session terminates (or unsubscribes from topic) in this time frame notifications are not sent at all.
const deferredNotificationsTimeout = time.Second * 5
var minSupportedVersionValue = parseVersion(minSupportedVersion)
// SessionProto is the type of the wire transport.
type SessionProto int
// Constants defining individual types of wire transports.
const (
// NONE is undefined/not set.
NONE SessionProto = iota
// WEBSOCK represents websocket connection.
WEBSOCK
// LPOLL represents a long polling connection.
LPOLL
// GRPC is a gRPC connection
GRPC
// PROXY is temporary session used as a proxy at master node.
PROXY
// MULTIPLEX is a multiplexing session reprsenting a connection from proxy topic to master.
MULTIPLEX
)
// Session represents a single WS connection or a long polling session. A user may have multiple
// sessions.
type Session struct {
// protocol - NONE (unset), WEBSOCK, LPOLL, GRPC, PROXY, MULTIPLEX
proto SessionProto
// Session ID
sid string
// Websocket. Set only for websocket sessions.
ws *websocket.Conn
// Pointer to session's record in sessionStore. Set only for Long Poll sessions.
lpTracker *list.Element
// gRPC handle. Set only for gRPC clients.
grpcnode pbx.Node_MessageLoopServer
// Reference to the cluster node where the session has originated. Set only for cluster RPC sessions.
clnode *ClusterNode
// Reference to multiplexing session. Set only for proxy sessions.
multi *Session
proxiedTopic string
// IP address of the client. For long polling this is the IP of the last poll.
remoteAddr string
// User agent, a string provived by an authenticated client in {login} packet.
userAgent string
// Protocol version of the client: ((major & 0xff) << 8) | (minor & 0xff).
ver int
// Device ID of the client
deviceID string
// Platform: web, ios, android
platf string
// Human language of the client
lang string
// Country code of the client
countryCode string
// ID of the current user. Could be zero if session is not authenticated
// or for multiplexing sessions.
uid types.Uid
// Authentication level - NONE (unset), ANON, AUTH, ROOT.
authLvl auth.Level
// Time when the long polling session was last refreshed
lastTouched time.Time
// Time when the session received any packer from client
lastAction int64
// Timer which triggers after some seconds to mark background session as foreground.
bkgTimer *time.Timer
// Number of subscribe/unsubscribe requests in flight.
inflightReqs *boundedWaitGroup
// Synchronizes access to session store in cluster mode:
// subscribe/unsubscribe replies are asynchronous.
sessionStoreLock sync.Mutex
// Indicates that the session is terminating.
// After this flag's been flipped to true, there must not be any more writes
// into the session's send channel.
// Read/written atomically.
// 0 = false
// 1 = true
terminating int32
// Background session: subscription presence notifications and online status are delayed.
background bool
// Outbound mesages, buffered.
// The content must be serialized in format suitable for the session.
send chan any
// Channel for shutting down the session, buffer 1.
// Content in the same format as for 'send'
stop chan any
// detach - channel for detaching session from topic, buffered.
// Content is topic name to detach from.
detach chan string
// Map of topic subscriptions, indexed by topic name.
// Don't access directly. Use getters/setters.
subs map[string]*Subscription
// Mutex for subs access: both topic go routines and network go routines access
// subs concurrently.
subsLock sync.RWMutex
// Needed for long polling and grpc.
lock sync.Mutex
// Field used only in cluster mode by topic master node.
// Type of proxy to master request being handled.
proxyReq ProxyReqType
}
// Subscription is a mapper of sessions to topics.
type Subscription struct {
// Channel to communicate with the topic, copy of Topic.clientMsg
broadcast chan<- *ClientComMessage
// Session sends a signal to Topic when this session is unsubscribed
// This is a copy of Topic.unreg
done chan<- *ClientComMessage
// Channel to send {meta} requests, copy of Topic.meta
meta chan<- *ClientComMessage
// Channel to ping topic with session's updates, copy of Topic.supd
supd chan<- *sessionUpdate
}
func (s *Session) addSub(topic string, sub *Subscription) {
if s.multi != nil {
s.multi.addSub(topic, sub)
return
}
s.subsLock.Lock()
// Sessions that serve as an interface between proxy topics and their masters (proxy sessions)
// may have only one subscription, that is, to its master topic.
// Normal sessions may be subscribed to multiple topics.
if !s.isMultiplex() || s.countSub() == 0 {
s.subs[topic] = sub
}
s.subsLock.Unlock()
}
func (s *Session) getSub(topic string) *Subscription {
// Don't check s.multi here. Let it panic if called for proxy session.
s.subsLock.RLock()
defer s.subsLock.RUnlock()
return s.subs[topic]
}
func (s *Session) delSub(topic string) {
if s.multi != nil {
s.multi.delSub(topic)
return
}
s.subsLock.Lock()
delete(s.subs, topic)
s.subsLock.Unlock()
}
func (s *Session) countSub() int {
if s.multi != nil {
return s.multi.countSub()
}
return len(s.subs)
}
// Inform topics that the session is being terminated.
// No need to check for s.multi because it's not called for PROXY sessions.
func (s *Session) unsubAll() {
s.subsLock.RLock()
defer s.subsLock.RUnlock()
for _, sub := range s.subs {
// sub.done is the same as topic.unreg
// The whole session is being dropped; ClientComMessage is a wrapper for session, ClientComMessage.init is false.
// keep redundant init: false so it can be searched for.
sub.done <- &ClientComMessage{sess: s, init: false}
}
}
// Indicates whether this session is a local interface for a remote proxy topic.
// It multiplexes multiple sessions.
func (s *Session) isMultiplex() bool {
return s.proto == MULTIPLEX
}
// Indicates whether this session is a short-lived proxy for a remote session.
func (s *Session) isProxy() bool {
return s.proto == PROXY
}
// Cluster session: either a proxy or a multiplexing session.
func (s *Session) isCluster() bool {
return s.isProxy() || s.isMultiplex()
}
func (s *Session) scheduleClusterWriteLoop() {
if globals.cluster != nil && globals.cluster.proxyEventQueue != nil {
globals.cluster.proxyEventQueue.Schedule(
func() { s.clusterWriteLoop(s.proxiedTopic) })
}
}
func (s *Session) supportsMessageBatching() bool {
switch s.proto {
case WEBSOCK:
return true
case GRPC:
return true
default:
return false
}
}
// queueOut attempts to send a list of ServerComMessages to a session write loop;
// it fails if the send buffer is full.
func (s *Session) queueOutBatch(msgs []*ServerComMessage) bool {
if s == nil {
return true
}
if atomic.LoadInt32(&s.terminating) > 0 {
return true
}
if s.multi != nil {
// In case of a cluster we need to pass a copy of the actual session.
for i := range msgs {
msgs[i].sess = s
}
if s.multi.queueOutBatch(msgs) {
s.multi.scheduleClusterWriteLoop()
return true
}
return false
}
if s.supportsMessageBatching() {
select {
case s.send <- msgs:
default:
// Never block here since it may also block the topic's run() goroutine.
logs.Err.Println("s.queueOut: session's send queue2 full", s.sid)
return false
}
if s.isMultiplex() {
s.scheduleClusterWriteLoop()
}
} else {
for _, msg := range msgs {
s.queueOut(msg)
}
}
return true
}
// queueOut attempts to send a ServerComMessage to a session write loop;
// it fails, if the send buffer is full.
func (s *Session) queueOut(msg *ServerComMessage) bool {
if s == nil {
return true
}
if atomic.LoadInt32(&s.terminating) > 0 {
return true
}
if s.multi != nil {
// In case of a cluster we need to pass a copy of the actual session.
msg.sess = s
if s.multi.queueOut(msg) {
s.multi.scheduleClusterWriteLoop()
return true
}
return false
}
// Record latency only on {ctrl} messages and end-user sessions.
if msg.Ctrl != nil && msg.Id != "" {
if !msg.Ctrl.Timestamp.IsZero() && !s.isCluster() {
duration := time.Since(msg.Ctrl.Timestamp).Milliseconds()
statsAddHistSample("RequestLatency", float64(duration))
}
if 200 <= msg.Ctrl.Code && msg.Ctrl.Code < 600 {
statsInc(fmt.Sprintf("CtrlCodesTotal%dxx", msg.Ctrl.Code/100), 1)
} else {
logs.Warn.Println("Invalid response code: ", msg.Ctrl.Code)
}
}
select {
case s.send <- msg:
default:
// Never block here since it may also block the topic's run() goroutine.
logs.Err.Println("s.queueOut: session's send queue full", s.sid)
return false
}
if s.isMultiplex() {
s.scheduleClusterWriteLoop()
}
return true
}
// queueOutBytes attempts to send a ServerComMessage already serialized to []byte.
// If the send buffer is full, it fails.
func (s *Session) queueOutBytes(data []byte) bool {
if s == nil || atomic.LoadInt32(&s.terminating) > 0 {
return true
}
select {
case s.send <- data:
default:
logs.Err.Println("s.queueOutBytes: session's send queue full", s.sid)
return false
}
if s.isMultiplex() {
s.scheduleClusterWriteLoop()
}
return true
}
func (s *Session) maybeScheduleClusterWriteLoop() {
if s.multi != nil {
s.multi.scheduleClusterWriteLoop()
return
}
if s.isMultiplex() {
s.scheduleClusterWriteLoop()
}
}
func (s *Session) detachSession(fromTopic string) {
if atomic.LoadInt32(&s.terminating) == 0 {
s.detach <- fromTopic
s.maybeScheduleClusterWriteLoop()
}
}
func (s *Session) stopSession(data any) {
s.stop <- data
s.maybeScheduleClusterWriteLoop()
}
func (s *Session) purgeChannels() {
for len(s.send) > 0 {
<-s.send
}
for len(s.stop) > 0 {
<-s.stop
}
for len(s.detach) > 0 {
<-s.detach
}
}
// cleanUp is called when the session is terminated to perform resource cleanup.
func (s *Session) cleanUp(expired bool) {
atomic.StoreInt32(&s.terminating, 1)
s.purgeChannels()
s.inflightReqs.Wait()
s.inflightReqs = nil
if !expired {
s.sessionStoreLock.Lock()
globals.sessionStore.Delete(s)
s.sessionStoreLock.Unlock()
}
s.background = false
s.bkgTimer.Stop()
s.unsubAll()
// Stop the write loop.
s.stopSession(nil)
}
// Message received, convert bytes to ClientComMessage and dispatch
func (s *Session) dispatchRaw(raw []byte) {
now := types.TimeNow()
var msg ClientComMessage
if atomic.LoadInt32(&s.terminating) > 0 {
logs.Warn.Println("s.dispatch: message received on a terminating session", s.sid)
s.queueOut(ErrLocked("", "", now))
return
}
if len(raw) == 1 && raw[0] == 0x31 {
// 0x31 == '1'. This is a network probe message. Respond with a '0':
s.queueOutBytes([]byte{0x30})
return
}
toLog := raw
truncated := ""
if len(raw) > 512 {
toLog = raw[:512]
truncated = "<...>"
}
logs.Info.Printf("in: '%s%s' sid='%s' uid='%s'", toLog, truncated, s.sid, s.uid)
if err := json.Unmarshal(raw, &msg); err != nil {
// Malformed message
logs.Warn.Println("s.dispatch", err, s.sid)
s.queueOut(ErrMalformed("", "", now))
return
}
s.dispatch(&msg)
}
func (s *Session) dispatch(msg *ClientComMessage) {
now := types.TimeNow()
atomic.StoreInt64(&s.lastAction, now.UnixNano())
// This should be the first block here, before any other checks.
var resp *ServerComMessage
if msg, resp = pluginFireHose(s, msg); resp != nil {
// Plugin provided a response. No further processing is needed.
s.queueOut(resp)
return
} else if msg == nil {
// Plugin requested to silently drop the request.
return
}
if msg.Extra == nil || msg.Extra.AsUser == "" {
// Use current user's ID and auth level.
msg.AsUser = s.uid.UserId()
msg.AuthLvl = int(s.authLvl)
} else if s.authLvl != auth.LevelRoot {
// Only root user can set alternative user ID and auth level values.
s.queueOut(ErrPermissionDenied("", "", now))
logs.Warn.Println("s.dispatch: non-root asigned msg.from", s.sid)
return
} else if fromUid := types.ParseUserId(msg.Extra.AsUser); fromUid.IsZero() {
// Invalid msg.Extra.AsUser.
s.queueOut(ErrMalformed("", "", now))
logs.Warn.Println("s.dispatch: malformed msg.from: ", msg.Extra.AsUser, s.sid)
return
} else {
// Use provided msg.Extra.AsUser
msg.AsUser = msg.Extra.AsUser
// Assign auth level, if one is provided. Ignore invalid strings.
if authLvl := auth.ParseAuthLevel(msg.Extra.AuthLevel); authLvl == auth.LevelNone {
// AuthLvl is not set by the caller, assign default LevelAuth.
msg.AuthLvl = int(auth.LevelAuth)
} else {
msg.AuthLvl = int(authLvl)
}
}
msg.Timestamp = now
var handler func(*ClientComMessage)
var uaRefresh bool
// Check if s.ver is defined
checkVers := func(handler func(*ClientComMessage)) func(*ClientComMessage) {
return func(m *ClientComMessage) {
if s.ver == 0 {
logs.Warn.Println("s.dispatch: {hi} is missing", s.sid)
s.queueOut(ErrCommandOutOfSequence(m.Id, m.Original, msg.Timestamp))
return
}
handler(m)
}
}
// Check if user is logged in
checkUser := func(handler func(*ClientComMessage)) func(*ClientComMessage) {
return func(m *ClientComMessage) {
if msg.AsUser == "" {
logs.Warn.Println("s.dispatch: authentication required", s.sid)
s.queueOut(ErrAuthRequiredReply(m, m.Timestamp))
return
}
handler(m)
}
}
switch {
case msg.Pub != nil:
handler = checkVers(checkUser(s.publish))
msg.Id = msg.Pub.Id
msg.Original = msg.Pub.Topic
uaRefresh = true
case msg.Sub != nil:
handler = checkVers(checkUser(s.subscribe))
msg.Id = msg.Sub.Id
msg.Original = msg.Sub.Topic
uaRefresh = true
case msg.Leave != nil:
handler = checkVers(checkUser(s.leave))
msg.Id = msg.Leave.Id
msg.Original = msg.Leave.Topic
case msg.Hi != nil:
handler = s.hello
msg.Id = msg.Hi.Id
case msg.Login != nil:
handler = checkVers(s.login)
msg.Id = msg.Login.Id
case msg.Get != nil:
handler = checkVers(checkUser(s.get))
msg.Id = msg.Get.Id
msg.Original = msg.Get.Topic
uaRefresh = true
case msg.Set != nil:
handler = checkVers(checkUser(s.set))
msg.Id = msg.Set.Id
msg.Original = msg.Set.Topic
uaRefresh = true
case msg.Del != nil:
handler = checkVers(checkUser(s.del))
msg.Id = msg.Del.Id
msg.Original = msg.Del.Topic
case msg.Acc != nil:
handler = checkVers(s.acc)
msg.Id = msg.Acc.Id
case msg.Note != nil:
// If user is not authenticated or version not set the {note} is silently ignored.
handler = s.note
msg.Original = msg.Note.Topic
uaRefresh = true
default:
// Unknown message
s.queueOut(ErrMalformed("", "", msg.Timestamp))
logs.Warn.Println("s.dispatch: unknown message", s.sid)
return
}
if globals.cluster.isPartitioned() {
// The cluster is partitioned due to network or other failure and this node is a part of the smaller partition.
// In order to avoid data inconsistency across the cluster we must reject all requests.
s.queueOut(ErrClusterUnreachableReply(msg, msg.Timestamp))
return
}
msg.sess = s
msg.init = true
handler(msg)
// Notify 'me' topic that this session is currently active.
if uaRefresh && msg.AsUser != "" && s.userAgent != "" {
if sub := s.getSub(msg.AsUser); sub != nil {
// The chan is buffered. If the buffer is exhaused, the session will wait for 'me' to become available
sub.supd <- &sessionUpdate{userAgent: s.userAgent}
}
}
}
// Request to subscribe to a topic.
func (s *Session) subscribe(msg *ClientComMessage) {
if strings.HasPrefix(msg.Original, "new") || strings.HasPrefix(msg.Original, "nch") {
// Request to create a new group/channel topic.
// If we are in a cluster, make sure the new topic belongs to the current node.
msg.RcptTo = globals.cluster.genLocalTopicName()
} else {
var resp *ServerComMessage
msg.RcptTo, resp = s.expandTopicName(msg)
if resp != nil {
s.queueOut(resp)
return
}
}
s.inflightReqs.Add(1)
// Session can subscribe to topic on behalf of a single user at a time.
if sub := s.getSub(msg.RcptTo); sub != nil {
s.queueOut(InfoAlreadySubscribed(msg.Id, msg.Original, msg.Timestamp))
s.inflightReqs.Done()
} else {
select {
case globals.hub.join <- msg:
default:
// Reply with a 503 to the user.
s.queueOut(ErrServiceUnavailableReply(msg, msg.Timestamp))
s.inflightReqs.Done()
logs.Err.Println("s.subscribe: hub.join queue full, topic ", msg.RcptTo, s.sid)
}
// Hub will send Ctrl success/failure packets back to session
}
}
// Leave/Unsubscribe a topic
func (s *Session) leave(msg *ClientComMessage) {
// Expand topic name
var resp *ServerComMessage
msg.RcptTo, resp = s.expandTopicName(msg)
if resp != nil {
s.queueOut(resp)
return
}
s.inflightReqs.Add(1)
if sub := s.getSub(msg.RcptTo); sub != nil {
// Session is attached to the topic.
if (msg.Original == "me" || msg.Original == "fnd") && msg.Leave.Unsub {
// User should not unsubscribe from 'me' or 'find'. Just leaving is fine.
s.queueOut(ErrPermissionDeniedReply(msg, msg.Timestamp))
s.inflightReqs.Done()
} else {
// Unlink from topic, topic will send a reply.
sub.done <- msg
}
return
}
s.inflightReqs.Done()
if !msg.Leave.Unsub {
// Session is not attached to the topic, wants to leave - fine, no change
s.queueOut(InfoNotJoined(msg.Id, msg.Original, msg.Timestamp))
} else {
// Session wants to unsubscribe from the topic it did not join
// TODO(gene): allow topic to unsubscribe without joining first; send to hub to unsub
logs.Warn.Println("s.leave:", "must attach first", s.sid)
s.queueOut(ErrAttachFirst(msg, msg.Timestamp))
}
}
// Broadcast a message to all topic subscribers
func (s *Session) publish(msg *ClientComMessage) {
// TODO(gene): Check for repeated messages with the same ID
var resp *ServerComMessage
msg.RcptTo, resp = s.expandTopicName(msg)
if resp != nil {
s.queueOut(resp)
return
}
// Add "sender" header if the message is sent on behalf of another user.
if msg.AsUser != s.uid.UserId() {
if msg.Pub.Head == nil {
msg.Pub.Head = make(map[string]any)
}
msg.Pub.Head["sender"] = s.uid.UserId()
} else if msg.Pub.Head != nil {
// Clear potentially false "sender" field.
delete(msg.Pub.Head, "sender")
if len(msg.Pub.Head) == 0 {
msg.Pub.Head = nil
}
}
if sub := s.getSub(msg.RcptTo); sub != nil {
// This is a post to a subscribed topic. The message is sent to the topic only
select {
case sub.broadcast <- msg:
default:
// Reply with a 503 to the user.
s.queueOut(ErrServiceUnavailableReply(msg, msg.Timestamp))
logs.Err.Println("s.publish: sub.broadcast channel full, topic ", msg.RcptTo, s.sid)
}
} else if msg.RcptTo == "sys" {
// Publishing to "sys" topic requires no subscription.
select {
case globals.hub.routeCli <- msg:
default:
// Reply with a 503 to the user.
s.queueOut(ErrServiceUnavailableReply(msg, msg.Timestamp))
logs.Err.Println("s.publish: hub.route channel full", s.sid)
}
} else {
// Publish request received without attaching to topic first.
s.queueOut(ErrAttachFirst(msg, msg.Timestamp))
logs.Warn.Printf("s.publish[%s]: must attach first %s", msg.RcptTo, s.sid)
}
}
// Client metadata
func (s *Session) hello(msg *ClientComMessage) {
var params map[string]any
var deviceIDUpdate bool
if s.ver == 0 {
s.ver = parseVersion(msg.Hi.Version)
if s.ver == 0 {
logs.Warn.Println("s.hello:", "failed to parse version", s.sid)
s.queueOut(ErrMalformed(msg.Id, "", msg.Timestamp))
return
}
// Check version compatibility
if versionCompare(s.ver, minSupportedVersionValue) < 0 {
s.ver = 0
s.queueOut(ErrVersionNotSupported(msg.Id, msg.Timestamp))
logs.Warn.Println("s.hello:", "unsupported version", s.sid)
return
}
params = map[string]any{
"ver": currentVersion,
"build": store.Store.GetAdapterName() + ":" + buildstamp,
"maxMessageSize": globals.maxMessageSize,
"maxSubscriberCount": globals.maxSubscriberCount,
"minTagLength": minTagLength,
"maxTagLength": maxTagLength,
"maxTagCount": globals.maxTagCount,
"maxFileUploadSize": globals.maxFileUploadSize,
"reqCred": globals.validatorClientConfig,
}
if len(globals.iceServers) > 0 {
params["iceServers"] = globals.iceServers
}
if globals.callEstablishmentTimeout > 0 {
params["callTimeout"] = globals.callEstablishmentTimeout
}
if s.proto == GRPC {
// gRPC client may need server address to be able to fetch large files over http(s).
// TODO: add support for fetching files over gRPC, then remove this parameter.
params["servingAt"] = globals.servingAt
// Report cluster size.
if globals.cluster != nil {
params["clusterSize"] = len(globals.cluster.nodes) + 1
} else {
params["clusterSize"] = 1
}
}
// Set ua & platform in the beginning of the session.
// Don't change them later.
s.userAgent = msg.Hi.UserAgent
s.platf = msg.Hi.Platform
if s.platf == "" {
s.platf = platformFromUA(msg.Hi.UserAgent)
}
// This is a background session. Start a timer.
if msg.Hi.Background {
s.bkgTimer.Reset(deferredNotificationsTimeout)
}
} else if msg.Hi.Version == "" || parseVersion(msg.Hi.Version) == s.ver {
// Save changed device ID+Lang or delete earlier specified device ID.
// Platform cannot be changed.
if !s.uid.IsZero() {
var err error
if msg.Hi.DeviceID == types.NullValue {
deviceIDUpdate = true
err = store.Devices.Delete(s.uid, s.deviceID)
} else if msg.Hi.DeviceID != "" && s.deviceID != msg.Hi.DeviceID {
deviceIDUpdate = true
err = store.Devices.Update(s.uid, s.deviceID, &types.DeviceDef{
DeviceId: msg.Hi.DeviceID,
Platform: s.platf,
LastSeen: msg.Timestamp,
Lang: msg.Hi.Lang,
})
userChannelsSubUnsub(s.uid, msg.Hi.DeviceID, true)
}
if err != nil {
logs.Warn.Println("s.hello:", "device ID", err, s.sid)
s.queueOut(ErrUnknown(msg.Id, "", msg.Timestamp))
return
}
}
} else {
// Version cannot be changed mid-session.
s.queueOut(ErrCommandOutOfSequence(msg.Id, "", msg.Timestamp))
logs.Warn.Println("s.hello:", "version cannot be changed", s.sid)
return
}
if msg.Hi.DeviceID == types.NullValue {
msg.Hi.DeviceID = ""
}
s.deviceID = msg.Hi.DeviceID
s.lang = msg.Hi.Lang
// Try to deduce the country from the locale.
// Tag may be well-defined even if err != nil. For example, for 'zh_CN_#Hans'
// the tag is 'zh-CN' exact but the err is 'tag is not well-formed'.
if tag, _ := language.Parse(s.lang); tag != language.Und {
if region, conf := tag.Region(); region.IsCountry() && conf >= language.High {
s.countryCode = region.String()
}
}
if s.countryCode == "" {
if len(s.lang) > 2 {
// Logging strings longer than 2 b/c language.Parse(XX) always succeeds
// returning confidence Low.
logs.Warn.Println("s.hello:", "could not parse locale ", s.lang)
}
s.countryCode = globals.defaultCountryCode
}
var httpStatus int
var httpStatusText string
if s.proto == LPOLL || deviceIDUpdate {
// In case of long polling StatusCreated was reported earlier.
// In case of deviceID update just report success.
httpStatus = http.StatusOK
httpStatusText = "ok"
} else {
httpStatus = http.StatusCreated
httpStatusText = "created"
}
ctrl := &MsgServerCtrl{Id: msg.Id, Code: httpStatus, Text: httpStatusText, Timestamp: msg.Timestamp}
if len(params) > 0 {
ctrl.Params = params
}
s.queueOut(&ServerComMessage{Ctrl: ctrl})
}
// Account creation
func (s *Session) acc(msg *ClientComMessage) {
newAcc := strings.HasPrefix(msg.Acc.User, "new")
// If temporary auth parameters are provided, get the user ID from them.
var rec *auth.Rec
if !newAcc && msg.Acc.TmpScheme != "" {
if !s.uid.IsZero() {
s.queueOut(ErrAlreadyAuthenticated(msg.Acc.Id, "", msg.Timestamp))
logs.Warn.Println("s.acc: got temp auth while already authenticated", s.sid)
return
}
authHdl := store.Store.GetLogicalAuthHandler(msg.Acc.TmpScheme)
if authHdl == nil {
logs.Warn.Println("s.acc: unknown authentication scheme", msg.Acc.TmpScheme, s.sid)
s.queueOut(ErrAuthUnknownScheme(msg.Id, "", msg.Timestamp))
}
var err error
rec, _, err = authHdl.Authenticate(msg.Acc.TmpSecret, s.remoteAddr)
if err != nil {
s.queueOut(decodeStoreError(err, msg.Acc.Id, msg.Timestamp,
map[string]any{"what": "auth"}))
logs.Warn.Println("s.acc: invalid temp auth", err, s.sid)
return
}
}
if newAcc {
// New account
replyCreateUser(s, msg, rec)
} else {
// Existing account.
replyUpdateUser(s, msg, rec)
}
}
// Authenticate
func (s *Session) login(msg *ClientComMessage) {
// msg.from is ignored here
if msg.Login.Scheme == "reset" {
if err := s.authSecretReset(msg.Login.Secret); err != nil {
s.queueOut(decodeStoreError(err, msg.Id, msg.Timestamp, nil))
} else {
s.queueOut(InfoAuthReset(msg.Id, msg.Timestamp))
}
return
}
if !s.uid.IsZero() {
// TODO: change error to notice InfoNoChange and return current user ID & auth level
// params := map[string]interface{}{"user": s.uid.UserId(), "authlvl": s.authLevel.String()}
s.queueOut(ErrAlreadyAuthenticated(msg.Id, "", msg.Timestamp))
return
}
handler := store.Store.GetLogicalAuthHandler(msg.Login.Scheme)
if handler == nil {
logs.Warn.Println("s.login: unknown authentication scheme", msg.Login.Scheme, s.sid)
s.queueOut(ErrAuthUnknownScheme(msg.Id, "", msg.Timestamp))
return
}
rec, challenge, err := handler.Authenticate(msg.Login.Secret, s.remoteAddr)
if err != nil {
resp := decodeStoreError(err, msg.Id, msg.Timestamp, nil)
if resp.Ctrl.Code >= 500 {
// Log internal errors
logs.Warn.Println("s.login: internal", err, s.sid)
}
s.queueOut(resp)
return
}
// If authenticator did not check user state, it returns state "undef". If so, check user state here.
if rec.State == types.StateUndefined {
rec.State, err = userGetState(rec.Uid)
}
if err == nil && rec.State != types.StateOK {
err = types.ErrPermissionDenied
}
if err != nil {
logs.Warn.Println("s.login: user state check failed", rec.Uid, err, s.sid)
s.queueOut(decodeStoreError(err, msg.Id, msg.Timestamp, nil))
return
}
if challenge != nil {
// Multi-stage authentication. Issue challenge to the client.
s.queueOut(InfoChallenge(msg.Id, msg.Timestamp, challenge))
return
}
var missing []string
if rec.Features&auth.FeatureValidated == 0 && len(globals.authValidators[rec.AuthLevel]) > 0 {
var validated []string
// Check responses. Ignore invalid responses, just keep cred unvalidated.
if validated, _, err = validatedCreds(rec.Uid, rec.AuthLevel, msg.Login.Cred, false); err == nil {
// Get a list of credentials which have not been validated.
_, missing, _ = stringSliceDelta(globals.authValidators[rec.AuthLevel], validated)
}
}
if err != nil {
logs.Warn.Println("s.login: failed to validate credentials:", err, s.sid)
s.queueOut(decodeStoreError(err, msg.Id, msg.Timestamp, nil))
} else {
s.queueOut(s.onLogin(msg.Id, msg.Timestamp, rec, missing))
}
}
// authSecretReset resets an authentication secret;
// params: "auth-method-to-reset:credential-method:credential-value",
// for example: "basic:email:[email protected]".
func (s *Session) authSecretReset(params []byte) error {
var authScheme, credMethod, credValue string
if parts := strings.Split(string(params), ":"); len(parts) >= 3 {
authScheme, credMethod, credValue = parts[0], parts[1], parts[2]
} else {
return types.ErrMalformed
}
// Technically we don't need to check it here, but we are going to mail the 'authScheme' string to the user.
// We have to make sure it does not contain any exploits. This is the simplest check.
auther := store.Store.GetLogicalAuthHandler(authScheme)
if auther == nil {
return types.ErrUnsupported
}
validator := store.Store.GetValidator(credMethod)