-
Notifications
You must be signed in to change notification settings - Fork 763
/
protocol.py
executable file
·4140 lines (3464 loc) · 163 KB
/
protocol.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 binascii
import hashlib
import base64
import struct
import random
import os
import pickle
import copy
import json
import time
from typing import Optional, Union, Tuple, Dict
from pprint import pformat
from collections import deque
from urllib import parse
from autobahn import __version__
from autobahn.websocket.interfaces import IWebSocketChannel, \
IWebSocketChannelFrameApi, \
IWebSocketChannelStreamingApi
from autobahn.websocket.types import ConnectingRequest, ConnectionRequest, ConnectionResponse, ConnectionDeny
from autobahn.wamp.types import TransportDetails
from autobahn.util import Stopwatch, wildcards2patterns, encode_truncate, hltype
from autobahn.util import _LazyHexFormatter
from autobahn.util import ObservableMixin
from autobahn.websocket.utf8validator import Utf8Validator
from autobahn.websocket.xormasker import XorMaskerNull, create_xor_masker
from autobahn.websocket.compress import PERMESSAGE_COMPRESSION_EXTENSION
from autobahn.websocket.util import parse_url
from autobahn.exception import PayloadExceededError, Disconnected
from autobahn.util import _maybe_tls_reason
import txaio
import hyperlink
# https://stackoverflow.com/a/15844751/884770
# from types import NoneType
NoneType = type(None)
__all__ = ("WebSocketProtocol",
"WebSocketFactory",
"WebSocketServerProtocol",
"WebSocketServerFactory",
"WebSocketClientProtocol",
"WebSocketClientFactory")
def _url_to_origin(url):
"""
Given an RFC6455 Origin URL, this returns the (scheme, host, port)
triple. If there's no port, and the scheme isn't http or https
then port will be None
"""
if url.lower() == 'null':
return 'null'
res = parse.urlsplit(url)
scheme = res.scheme.lower()
if scheme == 'file':
# when browsing local files, Chrome sends file:// URLs,
# Firefox sends 'null'
return 'null'
host = res.hostname
port = res.port
if port is None:
try:
port = {'https': 443, 'http': 80}[scheme]
except KeyError:
port = None
if not host:
raise ValueError("No host part in Origin '{}'".format(url))
return scheme, host, port
def _is_same_origin(websocket_origin, host_scheme, host_port, host_policy):
"""
Internal helper. Returns True if the provided websocket_origin
triple should be considered valid given the provided policy and
expected host_port.
Currently, the policy is just the list of allowedOriginsPatterns
from the WebSocketProtocol instance. Schemes and ports are matched
first, and only if there is not a mismatch do we compare each
allowed-origin pattern against the host.
"""
if websocket_origin == 'null':
# nothing is the same as the null origin
return False
if not isinstance(websocket_origin, tuple) or not len(websocket_origin) == 3:
raise ValueError("'websocket_origin' must be a 3-tuple")
(origin_scheme, origin_host, origin_port) = websocket_origin
# so, theoretically we should match on the 3-tuple of (scheme,
# origin, port) to follow the RFC. However, the existing API just
# allows you to pass a list of regular expressions that match
# against the Origin header -- so to keep that API working, we
# just match a reconstituted/sanitized Origin line against the
# regular expressions. We *do* explicitly match the scheme first,
# however!
# therefore, the default of "*" will still match everything (even
# if things are on weird ports). To be "actually secure" and pass
# explicit ports, you can put it in your matcher
# (e.g. "https://*.example.com:1234")
template = '{scheme}://{host}:{port}'
origin_header = template.format(
scheme=origin_scheme,
host=origin_host,
port=origin_port,
)
# so, this will be matching against e.g. "http://example.com:8080"
for origin_pattern in host_policy:
if origin_pattern.match(origin_header):
return True
return False
class TrafficStats(object):
def __init__(self):
self.reset()
def reset(self):
# all of the following only tracks data messages, not control frames, not handshaking
#
self.outgoingOctetsWireLevel = 0
self.outgoingOctetsWebSocketLevel = 0
self.outgoingOctetsAppLevel = 0
self.outgoingWebSocketFrames = 0
self.outgoingWebSocketMessages = 0
self.incomingOctetsWireLevel = 0
self.incomingOctetsWebSocketLevel = 0
self.incomingOctetsAppLevel = 0
self.incomingWebSocketFrames = 0
self.incomingWebSocketMessages = 0
# the following track any traffic before the WebSocket connection
# reaches STATE_OPEN (this includes WebSocket opening handshake
# proxy handling and such)
self.preopenOutgoingOctetsWireLevel = 0
self.preopenIncomingOctetsWireLevel = 0
def __json__(self):
# compression ratio = compressed size / uncompressed size
#
if self.outgoingOctetsAppLevel > 0:
outgoingCompressionRatio = float(self.outgoingOctetsWebSocketLevel) / float(self.outgoingOctetsAppLevel)
else:
outgoingCompressionRatio = None
if self.incomingOctetsAppLevel > 0:
incomingCompressionRatio = float(self.incomingOctetsWebSocketLevel) / float(self.incomingOctetsAppLevel)
else:
incomingCompressionRatio = None
# protocol overhead = non-payload size / payload size
#
if self.outgoingOctetsWebSocketLevel > 0:
outgoingWebSocketOverhead = float(self.outgoingOctetsWireLevel - self.outgoingOctetsWebSocketLevel) / float(self.outgoingOctetsWebSocketLevel)
else:
outgoingWebSocketOverhead = None
if self.incomingOctetsWebSocketLevel > 0:
incomingWebSocketOverhead = float(self.incomingOctetsWireLevel - self.incomingOctetsWebSocketLevel) / float(self.incomingOctetsWebSocketLevel)
else:
incomingWebSocketOverhead = None
return {'outgoingOctetsWireLevel': self.outgoingOctetsWireLevel,
'outgoingOctetsWebSocketLevel': self.outgoingOctetsWebSocketLevel,
'outgoingOctetsAppLevel': self.outgoingOctetsAppLevel,
'outgoingCompressionRatio': outgoingCompressionRatio,
'outgoingWebSocketOverhead': outgoingWebSocketOverhead,
'outgoingWebSocketFrames': self.outgoingWebSocketFrames,
'outgoingWebSocketMessages': self.outgoingWebSocketMessages,
'preopenOutgoingOctetsWireLevel': self.preopenOutgoingOctetsWireLevel,
'incomingOctetsWireLevel': self.incomingOctetsWireLevel,
'incomingOctetsWebSocketLevel': self.incomingOctetsWebSocketLevel,
'incomingOctetsAppLevel': self.incomingOctetsAppLevel,
'incomingCompressionRatio': incomingCompressionRatio,
'incomingWebSocketOverhead': incomingWebSocketOverhead,
'incomingWebSocketFrames': self.incomingWebSocketFrames,
'incomingWebSocketMessages': self.incomingWebSocketMessages,
'preopenIncomingOctetsWireLevel': self.preopenIncomingOctetsWireLevel}
def __str__(self):
return json.dumps(self.__json__())
class FrameHeader(object):
"""
Thin-wrapper for storing WebSocket frame metadata.
FOR INTERNAL USE ONLY!
"""
def __init__(self, opcode, fin, rsv, length, mask):
"""
Constructor.
:param opcode: Frame opcode (0-15).
:type opcode: int
:param fin: Frame FIN flag.
:type fin: bool
:param rsv: Frame reserved flags (0-7).
:type rsv: int
:param length: Frame payload length.
:type length: int
:param mask: Frame mask (binary string) or None.
:type mask: str
"""
self.opcode = opcode
self.fin = fin
self.rsv = rsv
self.length = length
self.mask = mask
def parseHttpHeader(data):
"""
Parses the beginning of a HTTP request header (the data up to the \n\n line) into a pair
of status line and HTTP headers dictionary.
Header keys are normalized to all-lower-case.
FOR INTERNAL USE ONLY!
:param data: The HTTP header data up to the \n\n line.
:type data: bytes
:returns: tuple -- Tuple of HTTP status line, headers and headers count.
"""
# By default, message header field parameters in Hypertext Transfer
# Protocol (HTTP) messages cannot carry characters outside the ISO-
# 8859-1 character set.
#
# See:
# - http://tools.ietf.org/html/rfc5987
# - https://github.com/crossbario/autobahn-python/issues/533
#
raw = data.decode('iso-8859-1').splitlines()
http_status_line = raw[0].strip()
http_headers = {}
http_headers_cnt = {}
for h in raw[1:]:
i = h.find(":")
if i > 0:
# HTTP header keys are case-insensitive
key = h[:i].strip().lower()
value = h[i + 1:].strip()
# handle HTTP headers split across multiple lines
if key in http_headers:
http_headers[key] += ', {}'.format(value)
http_headers_cnt[key] += 1
else:
http_headers[key] = value
http_headers_cnt[key] = 1
else:
# skip bad HTTP header
pass
return http_status_line, http_headers, http_headers_cnt
class Timings(object):
"""
Helper class to track timings by key. This class also supports item access,
iteration and conversion to string.
"""
def __init__(self):
self._stopwatch = Stopwatch()
self._timings = {}
def track(self, key):
"""
Track elapsed for key.
:param key: Key under which to track the timing.
:type key: str
"""
self._timings[key] = self._stopwatch.elapsed()
def diff(self, startKey, endKey, formatted=True):
"""
Get elapsed difference between two previously tracked keys.
:param startKey: First key for interval (older timestamp).
:type startKey: str
:param endKey: Second key for interval (younger timestamp).
:type endKey: str
:param formatted: If ``True``, format computed time period and return string.
:type formatted: bool
:returns: float or str -- Computed time period in seconds (or formatted string).
"""
if endKey in self._timings and startKey in self._timings:
d = self._timings[endKey] - self._timings[startKey]
if formatted:
if d < 0.00001: # 10us
s = "{} ns".format(round(d * 1000000000.))
elif d < 0.01: # 10ms
s = "{} us".format(round(d * 1000000.))
elif d < 10: # 10s
s = "{} ms".format(round(d * 1000.))
else:
s = "{} s".format(round(d))
return s.rjust(8)
else:
return d
else:
if formatted:
return "n.a.".rjust(8)
else:
return None
def __getitem__(self, key):
return self._timings.get(key, None)
def __iter__(self):
return self._timings.__iter__()
def __str__(self):
return pformat(self._timings)
class WebSocketProtocol(ObservableMixin):
"""
Protocol base class for WebSocket.
This class implements:
* :class:`autobahn.websocket.interfaces.IWebSocketChannel`
* :class:`autobahn.websocket.interfaces.IWebSocketChannelFrameApi`
* :class:`autobahn.websocket.interfaces.IWebSocketChannelStreamingApi`
"""
peer = '<never connected>'
SUPPORTED_SPEC_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18]
"""
WebSocket protocol spec (draft) versions supported by this implementation.
Use of version 18 indicates RFC6455. Use of versions < 18 indicate actual
draft spec versions (Hybi-Drafts).
"""
SUPPORTED_PROTOCOL_VERSIONS = [8, 13]
"""
WebSocket protocol versions supported by this implementation.
"""
SPEC_TO_PROTOCOL_VERSION = {10: 8, 11: 8, 12: 8, 13: 13, 14: 13, 15: 13, 16: 13, 17: 13, 18: 13}
"""
Mapping from protocol spec (draft) version to protocol version.
"""
PROTOCOL_TO_SPEC_VERSION = {8: 12, 13: 18}
"""
Mapping from protocol version to the latest protocol spec (draft) version
using that protocol version.
"""
DEFAULT_SPEC_VERSION = 18
"""
Default WebSocket protocol spec version this implementation speaks: final
RFC6455.
"""
_WS_MAGIC = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
"""
Protocol defined magic used during WebSocket handshake (used in Hybi-drafts
and final RFC6455.
"""
_QUEUED_WRITE_DELAY = 0.00001
"""
For synched/chopped writes, this is the reactor reentry delay in seconds.
"""
MESSAGE_TYPE_TEXT = 1
"""
WebSocket text message type (UTF-8 payload).
"""
MESSAGE_TYPE_BINARY = 2
"""
WebSocket binary message type (arbitrary binary payload).
"""
# WebSocket protocol state:
# (STATE_PROXY_CONNECTING) => STATE_CONNECTING => STATE_OPEN => STATE_CLOSING => STATE_CLOSED
#
STATE_CLOSED = 0
STATE_CONNECTING = 1
STATE_CLOSING = 2
STATE_OPEN = 3
STATE_PROXY_CONNECTING = 4
# Streaming Send State
SEND_STATE_GROUND = 0
SEND_STATE_MESSAGE_BEGIN = 1
SEND_STATE_INSIDE_MESSAGE = 2
SEND_STATE_INSIDE_MESSAGE_FRAME = 3
# WebSocket protocol close codes
# See:https://www.iana.org/assignments/websocket/websocket.xml#close-code-number-rules
#
CLOSE_STATUS_CODE_NORMAL = 1000
"""Normal close of connection."""
CLOSE_STATUS_CODE_GOING_AWAY = 1001
"""Going away."""
CLOSE_STATUS_CODE_PROTOCOL_ERROR = 1002
"""Protocol error."""
CLOSE_STATUS_CODE_UNSUPPORTED_DATA = 1003
"""Unsupported data."""
CLOSE_STATUS_CODE_RESERVED1 = 1004
"""RESERVED"""
CLOSE_STATUS_CODE_NULL = 1005 # MUST NOT be set in close frame!
"""No status received. (MUST NOT be used as status code when sending a close)."""
CLOSE_STATUS_CODE_ABNORMAL_CLOSE = 1006 # MUST NOT be set in close frame!
"""Abnormal close of connection. (MUST NOT be used as status code when sending a close)."""
CLOSE_STATUS_CODE_INVALID_PAYLOAD = 1007
"""Invalid frame payload data."""
CLOSE_STATUS_CODE_POLICY_VIOLATION = 1008
"""Policy violation."""
CLOSE_STATUS_CODE_MESSAGE_TOO_BIG = 1009
"""Message too big."""
CLOSE_STATUS_CODE_MANDATORY_EXTENSION = 1010
"""Mandatory extension."""
CLOSE_STATUS_CODE_INTERNAL_ERROR = 1011
"""The peer encountered an unexpected condition or internal error."""
CLOSE_STATUS_CODE_SERVICE_RESTART = 1012
"""Service restart."""
CLOSE_STATUS_CODE_TRY_AGAIN_LATER = 1013
"""Try again later."""
CLOSE_STATUS_CODE_UNASSIGNED1 = 1014
"""Unassiged."""
CLOSE_STATUS_CODE_TLS_HANDSHAKE_FAILED = 1015 # MUST NOT be set in close frame!
"""TLS handshake failed, i.e. server certificate could not be verified. (MUST NOT be used as status code when sending a close)."""
CLOSE_STATUS_CODES_ALLOWED = [CLOSE_STATUS_CODE_NORMAL,
CLOSE_STATUS_CODE_GOING_AWAY,
CLOSE_STATUS_CODE_PROTOCOL_ERROR,
CLOSE_STATUS_CODE_UNSUPPORTED_DATA,
CLOSE_STATUS_CODE_INVALID_PAYLOAD,
CLOSE_STATUS_CODE_POLICY_VIOLATION,
CLOSE_STATUS_CODE_MESSAGE_TOO_BIG,
CLOSE_STATUS_CODE_MANDATORY_EXTENSION,
CLOSE_STATUS_CODE_INTERNAL_ERROR,
CLOSE_STATUS_CODE_SERVICE_RESTART,
CLOSE_STATUS_CODE_TRY_AGAIN_LATER]
"""Status codes allowed to send in close."""
CONFIG_ATTRS_COMMON = ['logOctets',
'logFrames',
'trackTimings',
'utf8validateIncoming',
'applyMask',
'maxFramePayloadSize',
'maxMessagePayloadSize',
'autoFragmentSize',
'failByDrop',
'echoCloseCodeReason',
'openHandshakeTimeout',
'closeHandshakeTimeout',
'tcpNoDelay',
'autoPingInterval',
'autoPingTimeout',
'autoPingSize',
'autoPingRestartOnAnyTraffic']
"""
Configuration attributes common to servers and clients.
"""
CONFIG_ATTRS_SERVER = ['versions',
'webStatus',
'requireMaskedClientFrames',
'maskServerFrames',
'perMessageCompressionAccept',
'serveFlashSocketPolicy',
'flashSocketPolicy',
'allowedOrigins',
'allowedOriginsPatterns',
'allowNullOrigin',
'maxConnections',
'trustXForwardedFor']
"""
Configuration attributes specific to servers.
"""
CONFIG_ATTRS_CLIENT = ['version',
'acceptMaskedServerFrames',
'maskClientFrames',
'serverConnectionDropTimeout',
'perMessageCompressionOffers',
'perMessageCompressionAccept']
"""
Configuration attributes specific to clients.
"""
def __init__(self):
#: a Future/Deferred that fires when we hit STATE_CLOSED
self.is_closed = txaio.create_future()
self.is_open = txaio.create_future()
# XXX should we have open/close here too, or do you HAVE to use is_closed future?
# XXX what about when_open() and when_closed() as well/instead?
self.set_valid_events([
"message", # like onMessage (takes: payload, is_binary=)
])
self._transport_details = None
@property
def transport_details(self) -> Optional[TransportDetails]:
return self._transport_details
def onOpen(self):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onOpen`
"""
self.log.debug("WebSocketProtocol.onOpen")
def onMessageBegin(self, isBinary):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageBegin`
"""
self.message_is_binary = isBinary
self.message_data = []
self.message_data_total_length = 0
def onMessageFrameBegin(self, length):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameBegin`
"""
self.frame_length = length
self.frame_data = []
self.message_data_total_length += length
if not self.failedByMe:
if 0 < self.maxMessagePayloadSize < self.message_data_total_length:
self.wasMaxMessagePayloadSizeExceeded = True
self._max_message_size_exceeded(self.message_data_total_length,
self.maxMessagePayloadSize,
'received WebSocket message size {} exceeds payload limit of {} octets'.format(self.message_data_total_length, self.maxMessagePayloadSize))
elif 0 < self.maxFramePayloadSize < length:
self.wasMaxFramePayloadSizeExceeded = True
self._max_message_size_exceeded(length,
self.maxFramePayloadSize,
'received WebSocket frame size {} exceeds payload limit of {} octets'.format(length, self.maxFramePayloadSize))
def onMessageFrameData(self, payload):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameData`
"""
if not self.failedByMe:
if self.websocket_version == 0:
self.message_data_total_length += len(payload)
if 0 < self.maxMessagePayloadSize < self.message_data_total_length:
self.wasMaxMessagePayloadSizeExceeded = True
self._max_message_size_exceeded(self.message_data_total_length,
self.maxMessagePayloadSize,
'received (partial) WebSocket message size {} (already) exceeds payload limit of {} octets'.format(self.message_data_total_length, self.maxMessagePayloadSize))
self.message_data.append(payload)
else:
self.frame_data.append(payload)
def onMessageFrameEnd(self):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameEnd`
"""
if not self.failedByMe:
self._onMessageFrame(self.frame_data)
self.frame_data = None
def onMessageFrame(self, payload):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrame`
"""
if not self.failedByMe:
self.message_data.extend(payload)
def onMessageEnd(self):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageEnd`
"""
if not self.failedByMe:
payload = b''.join(self.message_data)
if self.trackedTimings:
self.trackedTimings.track("onMessage")
self._onMessage(payload, self.message_is_binary)
# notify any listeners about this message
f = self.fire("message", payload, is_binary=self.message_is_binary)
def error(f):
self.log.error(
"Firing signal 'message' failed: {fail}",
fail=f,
)
# all we can really do here is log; user code error
txaio.add_callbacks(f, None, error)
self.message_data = None
def onMessage(self, payload, isBinary):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onMessage`
"""
self.log.debug(
"WebSocketProtocol.onMessage(payload=<{payload_len} bytes)>, isBinary={isBinary}",
payload_len=(len(payload) if payload else 0),
isBinary=isBinary,
)
def onPing(self, payload):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onPing`
"""
self.log.debug(
"WebSocketProtocol.onPing(payload=<{payload_len} bytes>)",
payload_len=(len(payload) if payload else 0),
)
if self.state == WebSocketProtocol.STATE_OPEN:
self.sendPong(payload)
def onPong(self, payload):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onPong`
"""
self.log.debug(
"WebSocketProtocol.onPong(payload=<{payload_len} bytes>)",
payload_len=(len(payload) if payload else 0),
)
def onClose(self, wasClean, code, reason):
"""
Implements :meth:`autobahn.websocket.interfaces.IWebSocketChannel.onClose`
"""
self.log.debug(
"WebSocketProtocol.onClose(wasClean={wasClean}, code={code}, reason={reason})",
wasClean=wasClean,
code=code,
reason=reason,
)
def onCloseFrame(self, code, reasonRaw):
"""
Callback when a Close frame was received. The default implementation answers by
sending a Close when no Close was sent before. Otherwise it drops
the TCP connection either immediately (when we are a server) or after a timeout
(when we are a client and expect the server to drop the TCP).
:param code: Close status code, if there was one (:class:`WebSocketProtocol`.CLOSE_STATUS_CODE_*).
:type code: int
:param reasonRaw: Close reason (when present, a status code MUST have been also be present).
:type reasonRaw: bytes
"""
self.remoteCloseCode = None
self.remoteCloseReason = None
# reserved close codes: 0-999, 1004, 1005, 1006, 1011-2999, >= 5000
#
if code is not None and (code < 1000 or (1000 <= code <= 2999 and code not in WebSocketProtocol.CLOSE_STATUS_CODES_ALLOWED) or code >= 5000):
if self._protocol_violation('invalid close code {}'.format(code)):
return True
else:
self.remoteCloseCode = WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL
else:
self.remoteCloseCode = code
# closing reason
#
if reasonRaw is not None:
# we use our own UTF-8 validator to get consistent and fully conformant
# UTF-8 validation behavior
u = Utf8Validator()
val = u.validate(reasonRaw)
# the UTF8 must be valid _and_ end on a Unicode code point
if not (val[0] and val[1]):
if self._invalid_payload('invalid close reason (non-UTF8 payload)'):
return True
else:
self.remoteCloseReason = reasonRaw.decode('utf8')
# handle receive of close frame depending on protocol state
#
if self.state == WebSocketProtocol.STATE_CLOSING:
# We already initiated the closing handshake, so this
# is the peer's reply to our close frame.
# cancel any closing HS timer if present
#
if self.closeHandshakeTimeoutCall is not None:
self.log.debug("connection closed properly: canceling closing handshake timeout")
self.closeHandshakeTimeoutCall.cancel()
self.closeHandshakeTimeoutCall = None
self.wasClean = True
if self.factory.isServer:
# When we are a server, we immediately drop the TCP.
self.dropConnection(abort=True)
else:
# When we are a client, the server should drop the TCP
# If that doesn't happen, we do. And that will set wasClean = False.
if self.serverConnectionDropTimeout > 0:
self.serverConnectionDropTimeoutCall = txaio.call_later(
self.serverConnectionDropTimeout,
self.onServerConnectionDropTimeout,
)
elif self.state == WebSocketProtocol.STATE_OPEN:
# The peer initiates a closing handshake, so we reply
# by sending close frame.
self.wasClean = True
if self.websocket_version == 0:
self.sendCloseFrame(isReply=True)
else:
# Either reply with same code/reason, or code == NORMAL/reason=None
if self.echoCloseCodeReason:
self.sendCloseFrame(code=self.remoteCloseCode, reasonUtf8=encode_truncate(self.remoteCloseReason, 123), isReply=True)
else:
self.sendCloseFrame(code=WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL, isReply=True)
if self.factory.isServer:
# When we are a server, we immediately drop the TCP.
self.dropConnection(abort=False)
else:
# When we are a client, we expect the server to drop the TCP,
# and when the server fails to do so, a timeout in sendCloseFrame()
# will set wasClean = False back again.
pass
elif self.state == WebSocketProtocol.STATE_CLOSED:
# The peer initiated a closing handshake but dropped the TCP immediately.
self.wasClean = False
else:
# STATE_PROXY_CONNECTING, STATE_CONNECTING
raise Exception("logic error")
def onServerConnectionDropTimeout(self):
"""
We (a client) expected the peer (a server) to drop the connection,
but it didn't (in time self.serverConnectionDropTimeout).
So we drop the connection, but set self.wasClean = False.
"""
self.serverConnectionDropTimeoutCall = None
if self.state != WebSocketProtocol.STATE_CLOSED:
self.wasClean = False
self.wasNotCleanReason = 'WebSocket closing handshake timeout (server did not drop TCP connection in time)'
self.wasServerConnectionDropTimeout = True
self.dropConnection(abort=True)
else:
self.log.debug("skipping closing handshake timeout: server did indeed drop the connection in time")
def onOpenHandshakeTimeout(self):
"""
We expected the peer to complete the opening handshake with to us.
It didn't do so (in time self.openHandshakeTimeout).
So we drop the connection, but set self.wasClean = False.
"""
self.openHandshakeTimeoutCall = None
if self.state in [WebSocketProtocol.STATE_CONNECTING, WebSocketProtocol.STATE_PROXY_CONNECTING]:
self.wasClean = False
self.wasNotCleanReason = 'WebSocket opening handshake timeout (peer did not finish the opening handshake in time)'
self.wasOpenHandshakeTimeout = True
self.dropConnection(abort=True)
elif self.state == WebSocketProtocol.STATE_OPEN:
self.log.debug("skipping opening handshake timeout: WebSocket connection is open (opening handshake already finished)")
elif self.state == WebSocketProtocol.STATE_CLOSING:
self.log.debug("skipping opening handshake timeout: WebSocket connection is already closing ..")
elif self.state == WebSocketProtocol.STATE_CLOSED:
self.log.debug("skipping opening handshake timeout: WebSocket connection is already closed")
else:
# should not arrive here
raise Exception("logic error")
def onCloseHandshakeTimeout(self):
"""
We expected the peer to respond to us initiating a close handshake. It didn't
respond (in time self.closeHandshakeTimeout) with a close response frame though.
So we drop the connection, but set self.wasClean = False.
"""
self.closeHandshakeTimeoutCall = None
if self.state != WebSocketProtocol.STATE_CLOSED:
self.wasClean = False
self.wasNotCleanReason = 'WebSocket closing handshake timeout (peer did not finish the closing handshake in time)'
self.wasCloseHandshakeTimeout = True
self.dropConnection(abort=True)
else:
self.log.debug('skipping closing handshake timeout: WebSocket connection is already closed')
def onAutoPong(self, ping_sent, ping_seq, pong_received, pong_rtt, payload):
"""
When doing automatic ping/pongs, this is called upon a successful pong.
:param ping_sent: Posix time in ns when ping was sent.
:param ping_seq: Sequence number of ping that was sent.
:param pong_received: Posix time in ns when pong was received.
:param pong_rtt: Pong roundtrip-time in ms measured.
:param payload: The complete WebSocket ping/pong message payload
(ping_sent 8 bytes big-endian | ping_seq 4 bytes big endian | max. 113 optional random bytes).
"""
self.log.debug(
"Auto ping/pong: received pending pong (size={size}) for auto-ping (sent={sent}, seq={seq}, received={received}) in RTT of {rtt} ms",
size=len(payload), sent=ping_sent, seq=ping_seq, received=pong_received, rtt=pong_rtt)
def onAutoPingTimeout(self):
"""
When doing automatic ping/pongs to detect broken connection, the peer
did not reply in time to our ping. We drop the connection.
"""
self.wasClean = False
self.wasNotCleanReason = 'WebSocket ping timeout (peer did not respond with pong in time)'
self.autoPingTimeoutCall = None
self.dropConnection(abort=True)
def dropConnection(self, abort=False):
"""
Drop the underlying TCP connection.
"""
self.unregisterProducer()
if self.state != WebSocketProtocol.STATE_CLOSED:
if self.wasClean:
self.log.debug('dropping connection to peer {peer} with abort={abort}', peer=self.peer, abort=abort)
else:
self.log.warn('dropping connection to peer {peer} with abort={abort}: {reason}', peer=self.peer, abort=abort, reason=self.wasNotCleanReason)
self.droppedByMe = True
# this code-path will be hit (*without* hitting
# _connectionLost) in some timeout scenarios (unit-tests
# cover these). However, sometimes we hit both.
self.state = WebSocketProtocol.STATE_CLOSED
txaio.resolve(self.is_closed, self)
self._closeConnection(abort)
else:
self.log.debug('dropping connection to peer {peer} skipped - connection already closed', peer=self.peer)
def _max_message_size_exceeded(self, msg_size, max_msg_size, reason):
# hook that is fired when a message is (to be) received that is larger than what is configured to be handled
if True:
self._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_MESSAGE_TOO_BIG, reason)
else:
raise PayloadExceededError(reason)
def _fail_connection(self, code=CLOSE_STATUS_CODE_GOING_AWAY, reason='going away'):
"""
Fails the WebSocket connection.
"""
if self.state != WebSocketProtocol.STATE_CLOSED:
self.log.warn('failing WebSocket connection (code={code}): "{reason}"', code=code, reason=reason)
self.failedByMe = True
if self.failByDrop:
# brutally drop the TCP connection
self.wasClean = False
self.wasNotCleanReason = 'I dropped the WebSocket TCP connection: {0}'.format(reason)
self.dropConnection(abort=True)
else:
if self.state != WebSocketProtocol.STATE_CLOSING:
# perform WebSocket closing handshake
self.sendCloseFrame(code=code, reasonUtf8=encode_truncate(reason, 123), isReply=False)
else:
# already performing closing handshake .. we now drop the TCP
# (this can happen e.g. if we encounter a 2nd protocol violation during closing HS)
self.dropConnection(abort=False)
else:
self.log.debug("skip failing of connection since connection is already closed")
def _protocol_violation(self, reason):
"""
Fired when a WebSocket protocol violation/error occurs.
:param reason: Protocol violation that was encountered (human readable).
:type reason: str
:returns: bool -- True, when any further processing should be discontinued.
"""
self.log.debug("Protocol violation: {reason}", reason=reason)
self._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, reason)
if self.failByDrop:
return True
else:
# if we don't immediately drop the TCP, we need to skip the invalid frame
# to continue to later receive the closing handshake reply
return False
def _invalid_payload(self, reason):
"""
Fired when invalid payload is encountered. Currently, this only happens
for text message when payload is invalid UTF-8 or close frames with
close reason that is invalid UTF-8.
:param reason: What was invalid for the payload (human readable).
:type reason: str
:returns: bool -- True, when any further processing should be discontinued.
"""
self.log.debug("Invalid payload: {reason}", reason=reason)
self._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_INVALID_PAYLOAD, reason)
if self.failByDrop:
return True
else:
# if we don't immediately drop the TCP, we need to skip the invalid frame
# to continue to later receive the closing handshake reply
return False
def setTrackTimings(self, enable):
"""
Enable/disable tracking of detailed timings.
:param enable: Turn time tracking on/off.
:type enable: bool
"""
if not hasattr(self, 'trackTimings') or self.trackTimings != enable:
self.trackTimings = enable
if self.trackTimings:
self.trackedTimings = Timings()
else:
self.trackedTimings = None
def _connectionMade(self):
"""
This is called by network framework when a new TCP connection has been established
and handed over to a Protocol instance (an instance of this class).
"""
# copy default options from factory (so we are not affected by changed on
# those), but only copy if not already set on protocol instance (allow
# to set configuration individually)
#
configAttrLog = []
for configAttr in self.CONFIG_ATTRS: