-
Notifications
You must be signed in to change notification settings - Fork 58
/
realm.go
1321 lines (1200 loc) · 37.1 KB
/
realm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package router
import (
"errors"
"fmt"
"strconv"
"sync"
"github.com/gammazero/nexus/v3/router/auth"
"github.com/gammazero/nexus/v3/stdlog"
"github.com/gammazero/nexus/v3/transport"
"github.com/gammazero/nexus/v3/wamp"
)
// Special ID for meta session.
const metaID = wamp.ID(1)
type testament struct {
topic wamp.URI
args wamp.List
kwargs wamp.Dict
options wamp.Dict
}
type testamentBucket struct {
detached []testament
destroyed []testament
}
// A Realm is a WAMP routing and administrative domain, optionally protected by
// authentication and authorization. WAMP messages are only routed within a
// Realm.
type realm struct {
broker *broker
dealer *dealer
authorizer Authorizer
// authmethod -> Authenticator
authenticators map[string]auth.Authenticator
// session ID -> Session
clients map[wamp.ID]*wamp.Session
// session ID -> testament
testaments map[wamp.ID]testamentBucket
metaPeer wamp.Peer
metaSess *wamp.Session
metaIDGen *wamp.IDGen
actionChan chan func()
stopped chan struct{}
// Used by close() to wait for sessions to exit.
waitHandlers sync.WaitGroup
// Session meta-procedure registration ID -> handler map.
metaProcMap map[wamp.ID]func(*wamp.Invocation) wamp.Message
metaDone chan struct{}
closed bool
closeLock sync.Mutex
log stdlog.StdLog
debug bool
localAuth bool
localAuthz bool
metaStrict bool
metaIncDetails []string
enableMetaKill bool
enableMetaModify bool
}
var (
shutdownGoodbye = &wamp.Goodbye{
Reason: wamp.ErrSystemShutdown,
Details: wamp.Dict{},
}
)
// newRealm creates a new realm with the given RealmConfig, broker and dealer.
func newRealm(config *RealmConfig, broker *broker, dealer *dealer, logger stdlog.StdLog, debug bool) (*realm, error) {
if !config.URI.ValidURI(config.StrictURI, "") {
return nil, fmt.Errorf(
"invalid realm URI %v (URI strict checking %v)", config.URI, config.StrictURI)
}
r := &realm{
broker: broker,
dealer: dealer,
authorizer: config.Authorizer,
clients: map[wamp.ID]*wamp.Session{},
testaments: map[wamp.ID]testamentBucket{},
actionChan: make(chan func()),
stopped: make(chan struct{}),
metaIDGen: new(wamp.IDGen),
metaDone: make(chan struct{}),
metaProcMap: make(map[wamp.ID]func(*wamp.Invocation) wamp.Message, 9),
log: logger,
debug: debug,
localAuth: config.RequireLocalAuth,
localAuthz: config.RequireLocalAuthz,
metaStrict: config.MetaStrict,
enableMetaKill: config.EnableMetaKill,
enableMetaModify: config.EnableMetaModify,
}
if debug {
if r.enableMetaKill {
r.log.Println("Session meta kill procedures enabled")
}
if r.enableMetaKill {
r.log.Println("Session meta modify_details procedure enabled")
}
}
if r.metaStrict && len(config.MetaIncludeSessionDetails) != 0 {
r.metaIncDetails = make([]string, len(config.MetaIncludeSessionDetails))
copy(r.metaIncDetails, config.MetaIncludeSessionDetails)
}
r.authenticators = map[string]auth.Authenticator{}
for _, auth := range config.Authenticators {
r.authenticators[auth.AuthMethod()] = auth
}
// If allowing anonymous authentication, then install an anonymous
// authenticator if one has not already been provided in the config.
if config.AnonymousAuth {
if _, ok := r.authenticators["anonymous"]; !ok {
r.authenticators["anonymous"] = &auth.AnonymousAuth{
AuthRole: "anonymous",
}
}
}
r.setupMetaProcedures()
go r.metaProcedureHandler()
go r.run()
return r, nil
}
func (r *realm) run() {
for action := range r.actionChan {
action()
}
close(r.stopped)
}
// close performs an orderly shutdown of the realm.
//
// First a lock is acquired that prevents any new clients from joining the
// realm and makes sure any clients already in the process of joining finish
// joining.
//
// Next, each client session is killed, removing it from the broker and dealer,
// triggering a GOODBYE message to the client, and causing the session's
// message handler to exit. This ensures there are no messages remaining to be
// sent to the router.
//
// After that, the meta client session is killed. This ensures there are no
// more meta messages to sent to the router.
//
// At this point the broker and dealer are shutdown since they cannot receive
// any more messages to route, and have no clients to route messages to.
//
// Finally, the realm's action channel is closed and its goroutine is stopped.
func (r *realm) close() {
// The lock is held in mutual exclusion with the router starting any new
// session handlers for this realm. This prevents the router from starting
// any new session handlers, allowing the realm can safely close after
// waiting for all existing session handlers to exit.
r.closeLock.Lock()
defer r.closeLock.Unlock()
if r.closed {
// This realm is already closed.
return
}
r.closed = true
// Kick all clients off. Sending shutdownGoodbye causes client message
// handlers to exit without sending meta events.
ch := make(chan struct{})
r.actionChan <- func() {
for _, c := range r.clients {
c.EndRecv(shutdownGoodbye)
}
close(ch)
}
<-ch
// Wait until each client's handleInboundMessages() has exited. No new
// messages can be generated once sessions are closed.
r.waitHandlers.Wait()
// All normal handlers have exited, so now stop the meta session. When
// the meta client receives GOODBYE from the meta session, the meta
// session is done and will not try to publish anything more to the
// broker, and it is finally safe to exit and close the broker.
r.metaSess.EndRecv(shutdownGoodbye)
<-r.metaDone
// handleInboundMessages() and metaProcedureHandler() are the only things
// than can submit request to the broker and dealer, so now that these are
// finished there can be no more messages to broker and dealer.
// No new messages, so safe to close dealer and broker.
r.dealer.close()
r.broker.close()
// Finally close realm's action channel.
close(r.actionChan)
<-r.stopped
}
func (r *realm) setupMetaProcedures() {
// Create a local client for publishing meta events.
r.createMetaSession()
// Register to handle session meta procedures.
r.registerMetaProcedure(wamp.MetaProcSessionCount, r.sessionCount)
r.registerMetaProcedure(wamp.MetaProcSessionList, r.sessionList)
r.registerMetaProcedure(wamp.MetaProcSessionGet, r.sessionGet)
if r.enableMetaKill {
r.registerMetaProcedure(wamp.MetaProcSessionKill, r.sessionKill)
r.registerMetaProcedure(wamp.MetaProcSessionKillByAuthid, r.sessionKillByAuthid)
r.registerMetaProcedure(wamp.MetaProcSessionKillByAuthrole, r.sessionKillByAuthrole)
r.registerMetaProcedure(wamp.MetaProcSessionKillAll, r.sessionKillAll)
}
if r.enableMetaModify {
r.registerMetaProcedure(wamp.MetaProcSessionModifyDetails, r.sessionModifyDetails)
}
// Register to handle registration meta procedures.
r.registerMetaProcedure(wamp.MetaProcRegList, r.dealer.regList)
r.registerMetaProcedure(wamp.MetaProcRegLookup, r.dealer.regLookup)
r.registerMetaProcedure(wamp.MetaProcRegMatch, r.dealer.regMatch)
r.registerMetaProcedure(wamp.MetaProcRegGet, r.dealer.regGet)
r.registerMetaProcedure(wamp.MetaProcRegListCallees, r.dealer.regListCallees)
r.registerMetaProcedure(wamp.MetaProcRegCountCallees, r.dealer.regCountCallees)
// Register to handle subscription meta procedures.
r.registerMetaProcedure(wamp.MetaProcSubList, r.broker.subList)
r.registerMetaProcedure(wamp.MetaProcSubLookup, r.broker.subLookup)
r.registerMetaProcedure(wamp.MetaProcSubMatch, r.broker.subMatch)
r.registerMetaProcedure(wamp.MetaProcSubGet, r.broker.subGet)
r.registerMetaProcedure(wamp.MetaProcSubListSubscribers, r.broker.subListSubscribers)
r.registerMetaProcedure(wamp.MetaProcSubCountSubscribers, r.broker.subCountSubscribers)
r.registerMetaProcedure(wamp.MetaProcEventHistory, r.broker.subEventHistory)
// Register to handle testament meta procedures.
r.registerMetaProcedure(wamp.MetaProcSessionAddTestament, r.testamentAdd)
r.registerMetaProcedure(wamp.MetaProcSessionFlushTestaments, r.testamentFlush)
}
// createMetaSession creates and starts a session that runs in this realm, and
// bridges two peers. One peer, the r.metaSess, is associated with the router
// and handles meta session requests. The other, r.metaPeer, is the remote
// (client) side of the router uplink and is used as the interface to send meta
// session messages to. Sending a PUBLISH message to it will result in the
// router publishing the event to any subscribers.
func (r *realm) createMetaSession() {
cli, rtr := transport.LinkedPeers()
r.metaPeer = cli
r.dealer.setMetaPeer(cli)
// This session is the local leg of the router uplink.
r.metaSess = wamp.NewSession(rtr, metaID, wamp.Dict{"authrole": "trusted"}, nil)
// Run the handler for messages from the meta session.
go r.handleInboundMessages(r.metaSess)
if r.debug {
r.log.Println("Started meta-session", r.metaSess)
}
}
// onJoin is called when a non-meta session joins this realm. The session is
// stored in the realm's clients and a meta event is published.
//
// Note: onJoin() is called from handleSession, not handleInboundMessages, so
// that it is not called for the meta client.
func (r *realm) onJoin(sess *wamp.Session) {
sync := make(chan struct{})
r.actionChan <- func() {
r.clients[sess.ID] = sess
close(sync)
}
<-sync
// Session Meta Events MUST be dispatched by the Router to the same realm
// as the WAMP session which triggered the event.
//
// WAMP spec only specifies publishing "session", "authid", "authrole",
// "authmethod", "authprovider", "transport". This implementation
// publishes all details except transport.auth.
sess.Lock()
output := r.cleanSessionDetails(sess.Details)
sess.Unlock()
r.metaPeer.Send() <- &wamp.Publish{
Request: wamp.GlobalID(),
Topic: wamp.MetaEventSessionOnJoin,
Arguments: wamp.List{output},
}
}
// onLeave is called when a non-meta session leaves this realm. The session is
// removed from the realm's clients and a meta event is published.
//
// If the session handler exited due to realm shutdown, then remove the session
// from broker, dealer, and realm without generating meta events. If not
// shutdown, then remove the session and generate meta events as appropriate.
//
// There is no point to generating meta events at realm shutdown since those
// events would only be received by meta event subscribers that had not been
// removed yet, and clients are removed in any order.
//
// Note: onLeave() must be called from outside handleInboundMessages so that it
// is not called for the meta client.
func (r *realm) onLeave(sess *wamp.Session, shutdown, killAll bool) {
var testaments testamentBucket
var hasTstm bool
sync := make(chan struct{})
r.actionChan <- func() {
delete(r.clients, sess.ID)
testaments, hasTstm = r.testaments[sess.ID]
if hasTstm {
delete(r.testaments, sess.ID)
}
// If realm is shutdown, do not bother to remove session from broker
// and dealer. They will be closed after sessions are closed.
if !shutdown {
r.dealer.removeSession(sess)
r.broker.removeSession(sess)
}
close(sync)
}
<-sync
if shutdown || killAll {
return
}
if hasTstm {
sendTestaments := func(testaments []testament) {
for i := range testaments {
r.metaPeer.Send() <- &wamp.Publish{
Request: wamp.GlobalID(),
Topic: testaments[i].topic,
Arguments: testaments[i].args,
ArgumentsKw: testaments[i].kwargs,
Options: testaments[i].options,
}
}
}
sendTestaments(testaments.detached)
sendTestaments(testaments.destroyed)
}
r.metaPeer.Send() <- &wamp.Publish{
Request: wamp.GlobalID(),
Topic: wamp.MetaEventSessionOnLeave,
Arguments: wamp.List{
sess.ID,
sess.Details["authid"],
sess.Details["authrole"]},
}
}
// HandleSession starts a session attached to this realm.
//
// Routing occurs only between WAMP Sessions that have joined the same Realm.
func (r *realm) handleSession(sess *wamp.Session) error {
// The lock is held in mutual exclusion with the closing of the realm.
// This ensures that no new session handler can start once the realm is
// closing, during which the realm waits for all existing session handlers
// to exit.
r.closeLock.Lock()
if r.closed {
r.closeLock.Unlock()
err := errors.New("realm closed")
return err
}
r.waitHandlers.Add(1)
// Ensure session is capable of receiving exit signal before releasing lock
r.onJoin(sess)
r.closeLock.Unlock()
if r.debug {
r.log.Println("Handling messages for session", sess)
}
go func() {
shutdown, killAll, err := r.handleInboundMessages(sess)
if err != nil {
abortMsg := wamp.Abort{
Reason: wamp.ErrProtocolViolation,
Details: wamp.Dict{wamp.OptMessage: err.Error()},
}
r.log.Println("Aborting session", sess, ":", err)
select {
case sess.Send() <- &abortMsg:
default:
}
}
r.onLeave(sess, shutdown, killAll)
sess.Close()
r.waitHandlers.Done()
}()
return nil
}
// handleInboundMessages handles the messages sent from a client session to
// the router.
func (r *realm) handleInboundMessages(sess *wamp.Session) (bool, bool, error) {
if r.debug {
defer r.log.Println("Ended session", sess)
}
recv := sess.Recv()
recvDone := sess.RecvDone()
for {
var msg wamp.Message
var open bool
select {
case msg, open = <-recv:
if !open {
r.log.Println("Lost", sess)
return false, false, nil
}
case <-recvDone:
goodbye := sess.Goodbye()
switch goodbye {
case shutdownGoodbye, wamp.NoGoodbye:
if r.debug {
r.log.Printf("Stop session %s: system shutdown", sess)
}
select {
case sess.Send() <- goodbye:
default:
}
return true, false, nil
}
if r.debug {
r.log.Printf("Kill session %s: %s", sess, goodbye.Reason)
}
var killAll bool
if _, ok := goodbye.Details["all"]; ok {
killAll = true
}
select {
case sess.Send() <- goodbye:
default:
}
return false, killAll, nil
}
if r.debug {
r.log.Printf("Session %s submitting %s: %+v", sess,
msg.MessageType(), msg)
}
// Note: meta session is always authorized
if r.authorizer != nil && sess != r.metaSess && !r.authzMessage(sess, msg) {
// Not authorized; error response sent; do not process message.
continue
}
switch msg := msg.(type) {
case *wamp.Publish:
r.broker.publish(sess, msg)
case *wamp.Subscribe:
r.broker.subscribe(sess, msg)
case *wamp.Unsubscribe:
r.broker.unsubscribe(sess, msg)
case *wamp.Register:
r.dealer.register(sess, msg)
case *wamp.Unregister:
r.dealer.unregister(sess, msg)
case *wamp.Call:
r.dealer.call(sess, msg)
case *wamp.Yield:
r.dealer.yield(sess, msg)
case *wamp.Cancel:
r.dealer.cancel(sess, msg)
case *wamp.Error:
// An INVOCATION error is the only type of ERROR message the
// router should receive.
if msg.Type != wamp.INVOCATION {
return false, false, fmt.Errorf("invalid ERROR received: %v", msg)
}
r.dealer.error(msg)
case *wamp.Goodbye:
// Handle client leaving realm.
gmMsg := &wamp.Goodbye{
Reason: wamp.ErrGoodbyeAndOut,
Details: wamp.Dict{},
}
select {
case sess.Send() <- gmMsg:
default:
}
if r.debug {
r.log.Println("GOODBYE from session", sess, "reason:",
msg.Reason)
}
return false, false, nil
default:
// Received unrecognized message type.
return false, false, fmt.Errorf("unexpected %v", msg.MessageType())
}
}
}
// authzMessage checks if the session is authorized to send the message. If
// authorization fails or if the session is not authorized, then an error
// response is returned to the client, and this method returns false.
func (r *realm) authzMessage(sess *wamp.Session, msg wamp.Message) bool {
// If the client is local, then do not check authorization, unless
// requested in config.
if sess.Peer.IsLocal() && !r.localAuthz {
return true
}
// Create a safe session to prevent access to the session.Peer.
safeSession := &wamp.Session{
ID: sess.ID,
Details: sess.Details,
}
// Write-lock the session, because there is no telling what the Authorizer
// will do to the session details.
sess.Lock()
isAuthz, err := r.authorizer.Authorize(safeSession, msg)
sess.Unlock()
if !isAuthz {
skipResponse := false
errRsp := &wamp.Error{Type: msg.MessageType(), Details: wamp.Dict{}}
// Get the Request from request types of messages.
switch msg := msg.(type) {
case *wamp.Publish:
// a publish error should only be sent when OptAcknowledge is set.
if pubAck, _ := msg.Options[wamp.OptAcknowledge].(bool); !pubAck {
skipResponse = true
}
errRsp.Request = msg.Request
case *wamp.Subscribe:
errRsp.Request = msg.Request
case *wamp.Unsubscribe:
errRsp.Request = msg.Request
case *wamp.Register:
errRsp.Request = msg.Request
case *wamp.Unregister:
errRsp.Request = msg.Request
case *wamp.Call:
errRsp.Request = msg.Request
case *wamp.Cancel:
errRsp.Request = msg.Request
case *wamp.Yield:
errRsp.Request = msg.Request
}
if err != nil {
// Error trying to authorize. Include error message.
errRsp.Error = wamp.ErrAuthorizationFailed
errRsp.Arguments = wamp.List{err.Error()}
r.log.Println("Client", sess, "authorization failed:", err)
} else {
// Session not authorized. The inability to return a message is
// intentional, so as not to encourage returning information that
// could disclose any clues about authorization to an attacker.
errRsp.Error = wamp.ErrNotAuthorized
r.log.Println("Client", sess, msg.MessageType(), "not authorized")
}
if !skipResponse {
select {
case sess.Send() <- errRsp:
default:
r.log.Println("!!! client blocked, could not send authz error")
}
}
return false
}
return true
}
// authClient authenticates the client according to the authmethods in the
// HELLO message details and the authenticators available for this realm.
func (r *realm) authClient(sid wamp.ID, client wamp.Peer, details wamp.Dict) (*wamp.Welcome, error) {
// If the client is local, then no authentication is required.
if client.IsLocal() && !r.localAuth {
// Create welcome details for local client.
authid, _ := wamp.AsString(details["authid"])
if authid == "" {
authid = strconv.FormatInt(int64(wamp.GlobalID()), 16)
}
details = wamp.Dict{
"authid": authid,
"authrole": "trusted",
"authmethod": "local",
"authprovider": "static",
"roles": wamp.Dict{
wamp.RoleBroker: r.broker.role(),
wamp.RoleDealer: r.dealer.role(),
},
}
return &wamp.Welcome{Details: details}, nil
}
// The default authentication method is "WAMP-Anonymous" if client does not
// specify otherwise.
_authmethods, _ := wamp.AsList(details["authmethods"])
if len(_authmethods) == 0 {
_authmethods = append(_authmethods, "anonymous")
}
var authmethods []string
for _, val := range _authmethods {
am, ok := wamp.AsString(val)
if !ok {
r.log.Println("!! Could not convert authmethod:", val)
continue
}
if am == "" {
continue
}
authmethods = append(authmethods, am)
}
if len(authmethods) == 0 {
return nil, errors.New("no authentication supplied")
}
authr, method := r.getAuthenticator(authmethods)
if authr == nil {
return nil, errors.New("could not authenticate with any method")
}
// Return welcome message or error.
welcome, err := authr.Authenticate(sid, details, client)
if err != nil {
return nil, err
}
welcome.Details["authmethod"] = method
welcome.Details["roles"] = wamp.Dict{
wamp.RoleBroker: r.broker.role(),
wamp.RoleDealer: r.dealer.role(),
}
return welcome, nil
}
// getAuthenticator finds the first authenticator registered for the methods.
func (r *realm) getAuthenticator(methods []string) (auth auth.Authenticator, authMethod string) {
sync := make(chan struct{})
r.actionChan <- func() {
// Iterate through the methods and see if there is an Authenticator for
// the method.
if len(r.authenticators) != 0 {
for _, method := range methods {
if a, ok := r.authenticators[method]; ok {
auth = a
authMethod = method
break
}
}
}
close(sync)
}
<-sync
return
}
func (r *realm) registerMetaProcedure(procedure wamp.URI, f func(*wamp.Invocation) wamp.Message) {
// Register the meta procedure. The "disclose_caller" option must be
// enabled for the testament API and the meta session API.
r.metaPeer.Send() <- &wamp.Register{
Request: r.metaIDGen.Next(),
Options: wamp.Dict{
"disclose_caller": true,
},
Procedure: procedure,
}
msg := <-r.metaPeer.Recv()
if msg == nil {
// This would only happen if the meta client was closed before or
// during meta procedure registration at realm startup. Safety first.
return
}
reg, ok := msg.(*wamp.Registered)
if !ok {
err, ok := msg.(*wamp.Error)
if !ok {
if _, ok = msg.(*wamp.Goodbye); ok {
r.log.Println("Shutdown during meta procedure registration")
return
}
r.log.Println("PANIC! Received unexpected", msg.MessageType())
panic("cannot register meta procedure")
}
errMsg := fmt.Sprintf(
"PANIC! Failed to register session meta procedure: %v", err.Error)
if len(err.Arguments) != 0 {
errMsg += fmt.Sprint(": ", err.Arguments[0])
}
r.log.Print(errMsg)
panic(errMsg)
}
r.metaProcMap[reg.Registration] = f
}
func (r *realm) metaProcedureHandler() {
defer close(r.metaDone)
var rsp wamp.Message
for msg := range r.metaPeer.Recv() {
switch msg := msg.(type) {
case *wamp.Invocation:
metaProcHandler, ok := r.metaProcMap[msg.Registration]
if !ok {
r.metaPeer.Send() <- &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrNoSuchProcedure,
}
continue
}
rsp = metaProcHandler(msg)
case *wamp.Goodbye:
if r.debug {
r.log.Print("Session meta procedure handler exiting GOODBYE")
}
return
default:
r.log.Println("Meta procedure received unexpected", msg.MessageType())
}
r.metaPeer.Send() <- rsp
}
}
// sessionCount is a session meta procedure that obtains the number of sessions
// currently attached to the realm.
func (r *realm) sessionCount(msg *wamp.Invocation) wamp.Message {
var filter []string
if len(msg.Arguments) != 0 {
filterList, ok := wamp.AsList(msg.Arguments[0])
if !ok {
return &wamp.Error{
Type: wamp.INVOCATION,
Error: wamp.ErrInvalidArgument,
Request: msg.Request,
Details: wamp.Dict{},
}
}
filter, ok = wamp.ListToStrings(filterList)
if !ok {
return &wamp.Error{
Type: wamp.INVOCATION,
Error: wamp.ErrInvalidArgument,
Request: msg.Request,
Details: wamp.Dict{},
}
}
}
retChan := make(chan int)
if len(filter) == 0 {
r.actionChan <- func() {
retChan <- len(r.clients)
}
} else {
r.actionChan <- func() {
var nclients int
for _, sess := range r.clients {
sess.Lock()
authrole, _ := wamp.AsString(sess.Details["authrole"])
sess.Unlock()
for j := range filter {
if filter[j] == authrole {
nclients++
break
}
}
}
retChan <- nclients
}
}
nclients := <-retChan
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{nclients},
}
}
// sessionList is a session meta procedure that retrieves a list of the session
// IDs for all sessions currently attached to the realm.
func (r *realm) sessionList(msg *wamp.Invocation) wamp.Message {
var filter []string
if len(msg.Arguments) != 0 {
filterList, ok := wamp.AsList(msg.Arguments[0])
if !ok {
return &wamp.Error{
Type: wamp.INVOCATION,
Error: wamp.ErrInvalidArgument,
Request: msg.Request,
Details: wamp.Dict{},
}
}
filter, ok = wamp.ListToStrings(filterList)
if !ok {
return &wamp.Error{
Type: wamp.INVOCATION,
Error: wamp.ErrInvalidArgument,
Request: msg.Request,
Details: wamp.Dict{},
}
}
}
retChan := make(chan []wamp.ID)
if len(filter) == 0 {
r.actionChan <- func() {
ids := make([]wamp.ID, len(r.clients))
count := 0
for sid := range r.clients {
ids[count] = sid
count++
}
retChan <- ids
}
} else {
r.actionChan <- func() {
var ids []wamp.ID
for sid, sess := range r.clients {
sess.Lock()
authrole, _ := wamp.AsString(sess.Details["authrole"])
sess.Unlock()
for j := range filter {
if filter[j] == authrole {
ids = append(ids, sid)
break
}
}
}
retChan <- ids
}
}
list := <-retChan
return &wamp.Yield{Request: msg.Request, Arguments: wamp.List{list}}
}
// sessionGet is the session meta procedure that retrieves information on a
// specific session.
func (r *realm) sessionGet(msg *wamp.Invocation) wamp.Message {
if len(msg.Arguments) == 0 {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
sid, ok := wamp.AsID(msg.Arguments[0])
if !ok {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
retChan := make(chan *wamp.Session)
r.actionChan <- func() {
sess := r.clients[sid]
retChan <- sess
}
sess := <-retChan
if sess == nil {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
// WAMP spec only specifies returning "session", "authid", "authrole",
// "authmethod", "authprovider", and "transport". All details are returned
// in this implementation, except transport.auth, unless Config.MetaStrict
// is set to true.
sess.Lock()
output := r.cleanSessionDetails(sess.Details)
sess.Unlock()
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{output},
}
}
// sessionKill is a session meta procedure that closes a single session
// identified by session ID.
//
// The caller of this meta procedure may only specify session IDs other than
// its own session. Specifying the caller's own session will result in a
// wamp.error.no_such_session since no other session with that ID exists.
func (r *realm) sessionKill(msg *wamp.Invocation) wamp.Message {
if len(msg.Arguments) == 0 {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
sid, ok := wamp.AsID(msg.Arguments[0])
if !ok {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
caller, _ := wamp.AsID(msg.Details["caller"])
if caller == sid {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
reason, _ := wamp.AsURI(msg.ArgumentsKw["reason"])
if reason != "" && !reason.ValidURI(false, "") {
return makeError(msg.Request, wamp.ErrInvalidURI)
}
message, _ := wamp.AsString(msg.ArgumentsKw["message"])
err := r.killSession(sid, reason, message)
if err != nil {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
return &wamp.Yield{
Request: msg.Request,
}
}
// sessionKillByAuthid is a session meta procedure that closes all currently
// connected sessions that have the specified authid. If the caller's own
// session has the specified authid, the caller's session is excluded from the
// closed sessions.
func (r *realm) sessionKillByAuthid(msg *wamp.Invocation) wamp.Message {
if len(msg.Arguments) == 0 {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
authid, ok := wamp.AsString(msg.Arguments[0])
if !ok {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
reason, _ := wamp.AsURI(msg.ArgumentsKw["reason"])
if reason != "" && !reason.ValidURI(false, "") {
return makeError(msg.Request, wamp.ErrInvalidURI)
}
message, _ := wamp.AsString(msg.ArgumentsKw["message"])
caller, _ := wamp.AsID(msg.Details["caller"])
count := r.killSessionsByDetail("authid", authid, reason, message, caller)
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{count},
}
}
// sessionKillByAuthrole is a session meta procedure that closes all currently
// connected sessions that have the specified authrole. If the caller's own
// session has the specified authrole, the caller's session is excluded from
// the closed sessions.
func (r *realm) sessionKillByAuthrole(msg *wamp.Invocation) wamp.Message {
if len(msg.Arguments) == 0 {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
authrole, ok := wamp.AsString(msg.Arguments[0])
if !ok {
return makeError(msg.Request, wamp.ErrNoSuchSession)
}
reason, _ := wamp.AsURI(msg.ArgumentsKw["reason"])
if reason != "" && !reason.ValidURI(false, "") {
return makeError(msg.Request, wamp.ErrInvalidURI)
}
message, _ := wamp.AsString(msg.ArgumentsKw["message"])
caller, _ := wamp.AsID(msg.Details["caller"])
count := r.killSessionsByDetail("authrole", authrole, reason, message, caller)
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{count},
}
}
// sessionKillAll is a session meta procedure that closes all currently
// connected sessions in the caller's realm. The caller's own session is
// excluded from the closed sessions.
func (r *realm) sessionKillAll(msg *wamp.Invocation) wamp.Message {
reason, _ := wamp.AsURI(msg.ArgumentsKw["reason"])
if reason != "" && !reason.ValidURI(false, "") {
return makeError(msg.Request, wamp.ErrInvalidURI)
}
message, _ := wamp.AsString(msg.ArgumentsKw["message"])
caller, _ := wamp.AsID(msg.Details["caller"])
count := r.killAllSessions(reason, message, caller)
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{count},
}