/
message.py
5949 lines (4662 loc) · 207 KB
/
message.py
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
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
import re
import binascii
import autobahn
from autobahn.wamp.exception import ProtocolError, InvalidUriError
from autobahn.wamp.role import ROLE_NAME_TO_CLASS
try:
import cbor
import flatbuffers
from autobahn.wamp import message_fbs
except ImportError:
_HAS_WAMP_FLATBUFFERS = False
else:
_HAS_WAMP_FLATBUFFERS = True
__all__ = ('Message',
'Hello',
'Welcome',
'Abort',
'Challenge',
'Authenticate',
'Goodbye',
'Error',
'Publish',
'Published',
'Subscribe',
'Subscribed',
'Unsubscribe',
'Unsubscribed',
'Event',
'Call',
'Cancel',
'Result',
'Register',
'Registered',
'Unregister',
'Unregistered',
'Invocation',
'Interrupt',
'Yield',
'check_or_raise_uri',
'check_or_raise_id',
'is_valid_enc_algo',
'is_valid_enc_serializer',
'PAYLOAD_ENC_CRYPTO_BOX',
'PAYLOAD_ENC_MQTT',
'PAYLOAD_ENC_STANDARD_IDENTIFIERS')
# strict URI check allowing empty URI components
_URI_PAT_STRICT_EMPTY = re.compile(r"^(([0-9a-z_]+\.)|\.)*([0-9a-z_]+)?$")
# loose URI check allowing empty URI components
_URI_PAT_LOOSE_EMPTY = re.compile(r"^(([^\s\.#]+\.)|\.)*([^\s\.#]+)?$")
# strict URI check disallowing empty URI components
_URI_PAT_STRICT_NON_EMPTY = re.compile(r"^([0-9a-z_]+\.)*([0-9a-z_]+)$")
# loose URI check disallowing empty URI components
_URI_PAT_LOOSE_NON_EMPTY = re.compile(r"^([^\s\.#]+\.)*([^\s\.#]+)$")
# strict URI check disallowing empty URI components in all but the last component
_URI_PAT_STRICT_LAST_EMPTY = re.compile(r"^([0-9a-z_]+\.)*([0-9a-z_]*)$")
# loose URI check disallowing empty URI components in all but the last component
_URI_PAT_LOOSE_LAST_EMPTY = re.compile(r"^([^\s\.#]+\.)*([^\s\.#]*)$")
# custom (=implementation specific) WAMP attributes (used in WAMP message details/options)
_CUSTOM_ATTRIBUTE = re.compile(r"^x_([a-z][0-9a-z_]+)?$")
# Value for algo attribute in end-to-end encrypted messages using cryptobox, which
# is a scheme based on Curve25519, SHA512, Salsa20 and Poly1305.
# See: http://cr.yp.to/highspeed/coolnacl-20120725.pdf
PAYLOAD_ENC_CRYPTO_BOX = 'cryptobox'
# Payload transparency identifier for MQTT payloads (which are arbitrary binary).
PAYLOAD_ENC_MQTT = 'mqtt'
# Payload transparency identifier for XBR payloads
PAYLOAD_ENC_XBR = 'xbr'
# Payload transparency algorithm identifiers from the WAMP spec.
PAYLOAD_ENC_STANDARD_IDENTIFIERS = [PAYLOAD_ENC_CRYPTO_BOX, PAYLOAD_ENC_MQTT, PAYLOAD_ENC_XBR]
# Payload transparency serializer identifiers from the WAMP spec.
PAYLOAD_ENC_STANDARD_SERIALIZERS = ['json', 'msgpack', 'cbor', 'ubjson', 'flatbuffers']
ENC_ALGO_NONE = 0
ENC_ALGO_CRYPTOBOX = 1
ENC_ALGO_MQTT = 2
ENC_ALGO_XBR = 3
ENC_ALGOS = {
ENC_ALGO_NONE: 'null',
ENC_ALGO_CRYPTOBOX: 'cryptobox',
ENC_ALGO_MQTT: 'mqtt',
ENC_ALGO_XBR: 'xbr',
}
ENC_ALGOS_FROMSTR = {key: value for value, key in ENC_ALGOS.items()}
ENC_SER_NONE = 0
ENC_SER_JSON = 1
ENC_SER_MSGPACK = 2
ENC_SER_CBOR = 3
ENC_SER_UBJSON = 4
ENC_SER_OPAQUE = 5
ENC_SER_FLATBUFFERS = 6
ENC_SERS = {
ENC_SER_NONE: 'null',
ENC_SER_JSON: 'json',
ENC_SER_MSGPACK: 'msgpack',
ENC_SER_CBOR: 'cbor',
ENC_SER_UBJSON: 'ubjson',
ENC_SER_OPAQUE: 'opaque',
ENC_SER_FLATBUFFERS: 'flatbuffers',
}
ENC_SERS_FROMSTR = {key: value for value, key in ENC_SERS.items()}
def is_valid_enc_algo(enc_algo):
"""
For WAMP payload transparency mode, check if the provided ``enc_algo``
identifier in the WAMP message is a valid one.
Currently defined standard identifiers are:
* ``"cryptobox"``
* ``"mqtt"``
* ``"xbr"``
Users can select arbitrary identifiers too, but these MUST start with ``"x_"``.
:param enc_algo: The payload transparency algorithm identifier to check.
:type enc_algo: str
:returns: Returns ``True`` if and only if the payload transparency
algorithm identifier is valid.
:rtype: bool
"""
return type(enc_algo) == str and (enc_algo in PAYLOAD_ENC_STANDARD_IDENTIFIERS or _CUSTOM_ATTRIBUTE.match(enc_algo))
def is_valid_enc_serializer(enc_serializer):
"""
For WAMP payload transparency mode, check if the provided ``enc_serializer``
identifier in the WAMP message is a valid one.
Currently, the only standard defined identifier are
* ``"json"``
* ``"msgpack"``
* ``"cbor"``
* ``"ubjson"``
* ``"flatbuffers"``
Users can select arbitrary identifiers too, but these MUST start with ``"x_"``.
:param enc_serializer: The payload transparency serializer identifier to check.
:type enc_serializer: str
:returns: Returns ``True`` if and only if the payload transparency
serializer identifier is valid.
:rtype: bool
"""
return type(enc_serializer) == str and (enc_serializer in PAYLOAD_ENC_STANDARD_SERIALIZERS or _CUSTOM_ATTRIBUTE.match(enc_serializer))
def b2a(data, max_len=40):
if type(data) == str:
s = data
elif type(data) == bytes:
s = binascii.b2a_hex(data).decode('ascii')
elif data is None:
s = '-'
else:
s = '{}'.format(data)
if len(s) > max_len:
return s[:max_len] + '..'
else:
return s
def check_or_raise_uri(value, message="WAMP message invalid", strict=False, allow_empty_components=False, allow_last_empty=False, allow_none=False):
"""
Check a value for being a valid WAMP URI.
If the value is not a valid WAMP URI is invalid, raises :class:`autobahn.wamp.exception.ProtocolError`.
Otherwise return the value.
:param value: The value to check.
:type value: str or None
:param message: Prefix for message in exception raised when value is invalid.
:type message: str
:param strict: If ``True``, do a strict check on the URI (the WAMP spec SHOULD behavior).
:type strict: bool
:param allow_empty_components: If ``True``, allow empty URI components (for pattern based
subscriptions and registrations).
:type allow_empty_components: bool
:param allow_none: If ``True``, allow ``None`` for URIs.
:type allow_none: bool
:returns: The URI value (if valid).
:rtype: str
:raises: instance of :class:`autobahn.wamp.exception.ProtocolError`
"""
if value is None:
if allow_none:
return
else:
raise InvalidUriError("{0}: URI cannot be null".format(message))
if type(value) != str:
if not (value is None and allow_none):
raise InvalidUriError("{0}: invalid type {1} for URI".format(message, type(value)))
if strict:
if allow_last_empty:
pat = _URI_PAT_STRICT_LAST_EMPTY
elif allow_empty_components:
pat = _URI_PAT_STRICT_EMPTY
else:
pat = _URI_PAT_STRICT_NON_EMPTY
else:
if allow_last_empty:
pat = _URI_PAT_LOOSE_LAST_EMPTY
elif allow_empty_components:
pat = _URI_PAT_LOOSE_EMPTY
else:
pat = _URI_PAT_LOOSE_NON_EMPTY
if not pat.match(value):
raise InvalidUriError('{0}: invalid value "{1}" for URI (did not match pattern "{2}" with options strict={3}, allow_empty_components={4}, allow_last_empty={5}, allow_none={6})'.format(message, value, pat.pattern, strict, allow_empty_components, allow_last_empty, allow_none))
else:
return value
def check_or_raise_id(value, message="WAMP message invalid"):
"""
Check a value for being a valid WAMP ID.
If the value is not a valid WAMP ID, raises :class:`autobahn.wamp.exception.ProtocolError`.
Otherwise return the value.
:param value: The value to check.
:type value: int
:param message: Prefix for message in exception raised when value is invalid.
:type message: str
:returns: The ID value (if valid).
:rtype: int
:raises: instance of :class:`autobahn.wamp.exception.ProtocolError`
"""
if type(value) != int:
raise ProtocolError("{0}: invalid type {1} for ID".format(message, type(value)))
# the value 0 for WAMP IDs is possible in certain WAMP messages, e.g. UNREGISTERED with
# router revocation signaling!
if value < 0 or value > 9007199254740992: # 2**53
raise ProtocolError("{0}: invalid value {1} for ID".format(message, value))
return value
def check_or_raise_extra(value, message="WAMP message invalid"):
"""
Check a value for being a valid WAMP extra dictionary.
If the value is not a valid WAMP extra dictionary, raises :class:`autobahn.wamp.exception.ProtocolError`.
Otherwise return the value.
:param value: The value to check.
:type value: dict
:param message: Prefix for message in exception raised when value is invalid.
:type message: str
:returns: The extra dictionary (if valid).
:rtype: dict
:raises: instance of :class:`autobahn.wamp.exception.ProtocolError`
"""
if type(value) != dict:
raise ProtocolError("{0}: invalid type {1} for WAMP extra".format(message, type(value)))
for k in value.keys():
if not isinstance(k, str):
raise ProtocolError("{0}: invalid type {1} for key in WAMP extra ('{2}')".format(message, type(k), k))
return value
def _validate_kwargs(kwargs, message="WAMP message invalid"):
"""
Check a value for being a valid WAMP kwargs dictionary.
If the value is not a valid WAMP kwargs dictionary,
raises :class:`autobahn.wamp.exception.ProtocolError`.
Otherwise return the kwargs.
The WAMP spec requires that the keys in kwargs are proper
strings (unicode), not bytes. Note that the WAMP spec
says nothing about keys in application payload. Key in the
latter can be potentially of other type (if that is really
wanted).
:param kwargs: The keyword arguments to check.
:type kwargs: dict
:param message: Prefix for message in exception raised when
value is invalid.
:type message: str
:returns: The kwargs dictionary (if valid).
:rtype: dict
:raises: instance of
:class:`autobahn.wamp.exception.ProtocolError`
"""
if kwargs is not None:
if type(kwargs) != dict:
raise ProtocolError("{0}: invalid type {1} for WAMP kwargs".format(message, type(kwargs)))
for k in kwargs.keys():
if not isinstance(k, str):
raise ProtocolError("{0}: invalid type {1} for key in WAMP kwargs ('{2}')".format(message, type(k), k))
return kwargs
class Message(object):
"""
WAMP message base class.
.. note:: This is not supposed to be instantiated, but subclassed only.
"""
MESSAGE_TYPE = None
"""
WAMP message type code.
"""
__slots__ = (
'_from_fbs',
'_serialized',
'_correlation_id',
'_correlation_uri',
'_correlation_is_anchor',
'_correlation_is_last',
'_router_internal',
)
def __init__(self, from_fbs=None):
# only filled in case this object has flatbuffers underlying
self._from_fbs = from_fbs
# serialization cache: mapping from ISerializer instances to serialized bytes
self._serialized = {}
# user attributes for message correlation (mainly for message tracing)
self._correlation_id = None
self._correlation_uri = None
self._correlation_is_anchor = None
self._correlation_is_last = None
# non-serialized 'internal' attributes (used by Crossbar router)
self._router_internal = None
@property
def correlation_id(self):
return self._correlation_id
@correlation_id.setter
def correlation_id(self, value):
assert(value is None or type(value) == str)
self._correlation_id = value
@property
def correlation_uri(self):
return self._correlation_uri
@correlation_uri.setter
def correlation_uri(self, value):
assert(value is None or type(value) == str)
self._correlation_uri = value
@property
def correlation_is_anchor(self):
return self._correlation_is_anchor
@correlation_is_anchor.setter
def correlation_is_anchor(self, value):
assert(value is None or type(value) == bool)
self._correlation_is_anchor = value
@property
def correlation_is_last(self):
return self._correlation_is_last
@correlation_is_last.setter
def correlation_is_last(self, value):
assert(value is None or type(value) == bool)
self._correlation_is_last = value
def __eq__(self, other):
"""
Compare this message to another message for equality.
:param other: The other message to compare with.
:type other: obj
:returns: ``True`` iff the messages are equal.
:rtype: bool
"""
if not isinstance(other, self.__class__):
return False
# we only want the actual message data attributes (not eg _serialize)
for k in self.__slots__:
if k not in ['_serialized',
'_correlation_id',
'_correlation_uri',
'_correlation_is_anchor',
'_correlation_is_last'] and not k.startswith('_'):
if not getattr(self, k) == getattr(other, k):
return False
return True
def __ne__(self, other):
"""
Compare this message to another message for inequality.
:param other: The other message to compare with.
:type other: obj
:returns: ``True`` iff the messages are not equal.
:rtype: bool
"""
return not self.__eq__(other)
@staticmethod
def parse(wmsg):
"""
Factory method that parses a unserialized raw message (as returned byte
:func:`autobahn.interfaces.ISerializer.unserialize`) into an instance
of this class.
:returns: An instance of this class.
:rtype: obj
"""
raise NotImplementedError()
def marshal(self):
raise NotImplementedError()
@staticmethod
def cast(buf):
raise NotImplementedError()
def build(self, builder):
raise NotImplementedError()
def uncache(self):
"""
Resets the serialization cache.
"""
self._serialized = {}
def serialize(self, serializer):
"""
Serialize this object into a wire level bytes representation and cache
the resulting bytes. If the cache already contains an entry for the given
serializer, return the cached representation directly.
:param serializer: The wire level serializer to use.
:type serializer: An instance that implements :class:`autobahn.interfaces.ISerializer`
:returns: The serialized bytes.
:rtype: bytes
"""
# only serialize if not cached ..
if serializer not in self._serialized:
if serializer.NAME == 'flatbuffers':
# flatbuffers get special treatment ..
builder = flatbuffers.Builder(1024)
# this is the core method writing out this message (self) to a (new) flatbuffer
# FIXME: implement this method for all classes derived from Message
obj = self.build(builder)
builder.Finish(obj)
buf = builder.Output()
self._serialized[serializer] = bytes(buf)
else:
# all other serializers first marshal() the object and then serialize the latter
self._serialized[serializer] = serializer.serialize(self.marshal())
# cache is filled now: return serialized, cached bytes
return self._serialized[serializer]
class Hello(Message):
"""
A WAMP ``HELLO`` message.
Format: ``[HELLO, Realm|uri, Details|dict]``
"""
MESSAGE_TYPE = 1
"""
The WAMP message code for this type of message.
"""
__slots__ = (
'realm',
'roles',
'authmethods',
'authid',
'authrole',
'authextra',
'resumable',
'resume_session',
'resume_token',
)
def __init__(self,
realm,
roles,
authmethods=None,
authid=None,
authrole=None,
authextra=None,
resumable=None,
resume_session=None,
resume_token=None):
"""
:param realm: The URI of the WAMP realm to join.
:type realm: str
:param roles: The WAMP session roles and features to announce.
:type roles: dict of :class:`autobahn.wamp.role.RoleFeatures`
:param authmethods: The authentication methods to announce.
:type authmethods: list of str or None
:param authid: The authentication ID to announce.
:type authid: str or None
:param authrole: The authentication role to announce.
:type authrole: str or None
:param authextra: Application-specific "extra data" to be forwarded to the client.
:type authextra: dict or None
:param resumable: Whether the client wants this to be a session that can be later resumed.
:type resumable: bool or None
:param resume_session: The session the client would like to resume.
:type resume_session: int or None
:param resume_token: The secure authorisation token to resume the session.
:type resume_token: str or None
"""
assert(realm is None or isinstance(realm, str))
assert(type(roles) == dict)
assert(len(roles) > 0)
for role in roles:
assert(role in ['subscriber', 'publisher', 'caller', 'callee'])
assert(isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role]))
if authmethods:
assert(type(authmethods) == list)
for authmethod in authmethods:
assert(type(authmethod) == str)
assert(authid is None or type(authid) == str)
assert(authrole is None or type(authrole) == str)
assert(authextra is None or type(authextra) == dict)
assert(resumable is None or type(resumable) == bool)
assert(resume_session is None or type(resume_session) == int)
assert(resume_token is None or type(resume_token) == str)
Message.__init__(self)
self.realm = realm
self.roles = roles
self.authmethods = authmethods
self.authid = authid
self.authrole = authrole
self.authextra = authextra
self.resumable = resumable
self.resume_session = resume_session
self.resume_token = resume_token
@staticmethod
def parse(wmsg):
"""
Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.
"""
# this should already be verified by WampSerializer.unserialize
assert(len(wmsg) > 0 and wmsg[0] == Hello.MESSAGE_TYPE)
if len(wmsg) != 3:
raise ProtocolError("invalid message length {0} for HELLO".format(len(wmsg)))
realm = check_or_raise_uri(wmsg[1], "'realm' in HELLO", allow_none=True)
details = check_or_raise_extra(wmsg[2], "'details' in HELLO")
roles = {}
if 'roles' not in details:
raise ProtocolError("missing mandatory roles attribute in options in HELLO")
details_roles = check_or_raise_extra(details['roles'], "'roles' in 'details' in HELLO")
if len(details_roles) == 0:
raise ProtocolError("empty 'roles' in 'details' in HELLO")
for role in details_roles:
if role not in ['subscriber', 'publisher', 'caller', 'callee']:
raise ProtocolError("invalid role '{0}' in 'roles' in 'details' in HELLO".format(role))
role_cls = ROLE_NAME_TO_CLASS[role]
details_role = check_or_raise_extra(details_roles[role], "role '{0}' in 'roles' in 'details' in HELLO".format(role))
if 'features' in details_role:
check_or_raise_extra(details_role['features'], "'features' in role '{0}' in 'roles' in 'details' in HELLO".format(role))
role_features = role_cls(**details_role['features'])
else:
role_features = role_cls()
roles[role] = role_features
authmethods = None
if 'authmethods' in details:
details_authmethods = details['authmethods']
if type(details_authmethods) != list:
raise ProtocolError("invalid type {0} for 'authmethods' detail in HELLO".format(type(details_authmethods)))
for auth_method in details_authmethods:
if type(auth_method) != str:
raise ProtocolError("invalid type {0} for item in 'authmethods' detail in HELLO".format(type(auth_method)))
authmethods = details_authmethods
authid = None
if 'authid' in details:
details_authid = details['authid']
if type(details_authid) != str:
raise ProtocolError("invalid type {0} for 'authid' detail in HELLO".format(type(details_authid)))
authid = details_authid
authrole = None
if 'authrole' in details:
details_authrole = details['authrole']
if type(details_authrole) != str:
raise ProtocolError("invalid type {0} for 'authrole' detail in HELLO".format(type(details_authrole)))
authrole = details_authrole
authextra = None
if 'authextra' in details:
details_authextra = details['authextra']
if type(details_authextra) != dict:
raise ProtocolError("invalid type {0} for 'authextra' detail in HELLO".format(type(details_authextra)))
authextra = details_authextra
resumable = None
if 'resumable' in details:
resumable = details['resumable']
if type(resumable) != bool:
raise ProtocolError("invalid type {0} for 'resumable' detail in HELLO".format(type(resumable)))
resume_session = None
if 'resume-session' in details:
resume_session = details['resume-session']
if type(resume_session) != int:
raise ProtocolError("invalid type {0} for 'resume-session' detail in HELLO".format(type(resume_session)))
resume_token = None
if 'resume-token' in details:
resume_token = details['resume-token']
if type(resume_token) != str:
raise ProtocolError("invalid type {0} for 'resume-token' detail in HELLO".format(type(resume_token)))
else:
if resume_session:
raise ProtocolError("resume-token must be provided if resume-session is provided in HELLO")
obj = Hello(realm, roles, authmethods, authid, authrole, authextra, resumable, resume_session, resume_token)
return obj
def marshal(self):
"""
Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list
"""
details = {'roles': {}}
for role in self.roles.values():
details['roles'][role.ROLE] = {}
for feature in role.__dict__:
if not feature.startswith('_') and feature != 'ROLE' and getattr(role, feature) is not None:
if 'features' not in details['roles'][role.ROLE]:
details['roles'][role.ROLE] = {'features': {}}
details['roles'][role.ROLE]['features'][feature] = getattr(role, feature)
if self.authmethods is not None:
details['authmethods'] = self.authmethods
if self.authid is not None:
details['authid'] = self.authid
if self.authrole is not None:
details['authrole'] = self.authrole
if self.authextra is not None:
details['authextra'] = self.authextra
if self.resumable is not None:
details['resumable'] = self.resumable
if self.resume_session is not None:
details['resume-session'] = self.resume_session
if self.resume_token is not None:
details['resume-token'] = self.resume_token
return [Hello.MESSAGE_TYPE, self.realm, details]
def __str__(self):
"""
Return a string representation of this message.
"""
return "Hello(realm={}, roles={}, authmethods={}, authid={}, authrole={}, authextra={}, resumable={}, resume_session={}, resume_token={})".format(self.realm, self.roles, self.authmethods, self.authid, self.authrole, self.authextra, self.resumable, self.resume_session, self.resume_token)
class Welcome(Message):
"""
A WAMP ``WELCOME`` message.
Format: ``[WELCOME, Session|id, Details|dict]``
"""
MESSAGE_TYPE = 2
"""
The WAMP message code for this type of message.
"""
__slots__ = (
'session',
'roles',
'realm',
'authid',
'authrole',
'authmethod',
'authprovider',
'authextra',
'resumed',
'resumable',
'resume_token',
'custom',
)
def __init__(self,
session,
roles,
realm=None,
authid=None,
authrole=None,
authmethod=None,
authprovider=None,
authextra=None,
resumed=None,
resumable=None,
resume_token=None,
custom=None):
"""
:param session: The WAMP session ID the other peer is assigned.
:type session: int
:param roles: The WAMP roles to announce.
:type roles: dict of :class:`autobahn.wamp.role.RoleFeatures`
:param realm: The effective realm the session is joined on.
:type realm: str or None
:param authid: The authentication ID assigned.
:type authid: str or None
:param authrole: The authentication role assigned.
:type authrole: str or None
:param authmethod: The authentication method in use.
:type authmethod: str or None
:param authprovider: The authentication provided in use.
:type authprovider: str or None
:param authextra: Application-specific "extra data" to be forwarded to the client.
:type authextra: arbitrary or None
:param resumed: Whether the session is a resumed one.
:type resumed: bool or None
:param resumable: Whether this session can be resumed later.
:type resumable: bool or None
:param resume_token: The secure authorisation token to resume the session.
:type resume_token: str or None
:param custom: Implementation-specific "custom attributes" (`x_my_impl_attribute`) to be set.
:type custom: dict or None
"""
assert(type(session) == int)
assert(type(roles) == dict)
assert(len(roles) > 0)
for role in roles:
assert(role in ['broker', 'dealer'])
assert(isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role]))
assert(realm is None or type(realm) == str)
assert(authid is None or type(authid) == str)
assert(authrole is None or type(authrole) == str)
assert(authmethod is None or type(authmethod) == str)
assert(authprovider is None or type(authprovider) == str)
assert(authextra is None or type(authextra) == dict)
assert(resumed is None or type(resumed) == bool)
assert(resumable is None or type(resumable) == bool)
assert(resume_token is None or type(resume_token) == str)
assert(custom is None or type(custom) == dict)
if custom:
for k in custom:
assert(_CUSTOM_ATTRIBUTE.match(k))
Message.__init__(self)
self.session = session
self.roles = roles
self.realm = realm
self.authid = authid
self.authrole = authrole
self.authmethod = authmethod
self.authprovider = authprovider
self.authextra = authextra
self.resumed = resumed
self.resumable = resumable
self.resume_token = resume_token
self.custom = custom or {}
@staticmethod
def parse(wmsg):
"""
Verifies and parses an unserialized raw message into an actual WAMP message instance.
:param wmsg: The unserialized raw message.
:type wmsg: list
:returns: An instance of this class.
"""
# this should already be verified by WampSerializer.unserialize
assert(len(wmsg) > 0 and wmsg[0] == Welcome.MESSAGE_TYPE)
if len(wmsg) != 3:
raise ProtocolError("invalid message length {0} for WELCOME".format(len(wmsg)))
session = check_or_raise_id(wmsg[1], "'session' in WELCOME")
details = check_or_raise_extra(wmsg[2], "'details' in WELCOME")
# FIXME: tigher value checking (types, URIs etc)
realm = details.get('realm', None)
authid = details.get('authid', None)
authrole = details.get('authrole', None)
authmethod = details.get('authmethod', None)
authprovider = details.get('authprovider', None)
authextra = details.get('authextra', None)
resumed = None
if 'resumed' in details:
resumed = details['resumed']
if not type(resumed) == bool:
raise ProtocolError("invalid type {0} for 'resumed' detail in WELCOME".format(type(resumed)))
resumable = None
if 'resumable' in details:
resumable = details['resumable']
if not type(resumable) == bool:
raise ProtocolError("invalid type {0} for 'resumable' detail in WELCOME".format(type(resumable)))
resume_token = None
if 'resume_token' in details:
resume_token = details['resume_token']
if not type(resume_token) == str:
raise ProtocolError("invalid type {0} for 'resume_token' detail in WELCOME".format(type(resume_token)))
elif resumable:
raise ProtocolError("resume_token required when resumable is given in WELCOME")
roles = {}
if 'roles' not in details:
raise ProtocolError("missing mandatory roles attribute in options in WELCOME")
details_roles = check_or_raise_extra(details['roles'], "'roles' in 'details' in WELCOME")
if len(details_roles) == 0:
raise ProtocolError("empty 'roles' in 'details' in WELCOME")
for role in details_roles:
if role not in ['broker', 'dealer']:
raise ProtocolError("invalid role '{0}' in 'roles' in 'details' in WELCOME".format(role))
role_cls = ROLE_NAME_TO_CLASS[role]
details_role = check_or_raise_extra(details_roles[role], "role '{0}' in 'roles' in 'details' in WELCOME".format(role))
if 'features' in details_role:
check_or_raise_extra(details_role['features'], "'features' in role '{0}' in 'roles' in 'details' in WELCOME".format(role))
role_features = role_cls(**details_roles[role]['features'])
else:
role_features = role_cls()
roles[role] = role_features
custom = {}
for k in details:
if _CUSTOM_ATTRIBUTE.match(k):
custom[k] = details[k]
obj = Welcome(session, roles, realm, authid, authrole, authmethod, authprovider, authextra, resumed, resumable, resume_token, custom)
return obj
def marshal(self):
"""
Marshal this object into a raw message for subsequent serialization to bytes.
:returns: The serialized raw message.
:rtype: list
"""
details = {}
details.update(self.custom)
if self.realm:
details['realm'] = self.realm
if self.authid:
details['authid'] = self.authid
if self.authrole:
details['authrole'] = self.authrole
if self.authrole:
details['authmethod'] = self.authmethod
if self.authprovider:
details['authprovider'] = self.authprovider
if self.authextra:
details['authextra'] = self.authextra