desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns options dict as sent within WAMP messages.'
def message_attr(self):
options = {} if (self.acknowledge is not None): options[u'acknowledge'] = self.acknowledge if (self.exclude_me is not None): options[u'exclude_me'] = self.exclude_me if (self.exclude is not None): options[u'exclude'] = (self.exclude if (type(self.exclude) == list) else [self.exclude]) if (self.exclude_authid is not None): options[u'exclude_authid'] = (self.exclude_authid if (type(self.exclude_authid) == list) else [self.exclude_authid]) if (self.exclude_authrole is not None): options[u'exclude_authrole'] = (self.exclude_authrole if (type(self.exclude_authrole) == list) else [self.exclude_authrole]) if (self.eligible is not None): options[u'eligible'] = (self.eligible if (type(self.eligible) == list) else [self.eligible]) if (self.eligible_authid is not None): options[u'eligible_authid'] = (self.eligible_authid if (type(self.eligible_authid) == list) else [self.eligible_authid]) if (self.eligible_authrole is not None): options[u'eligible_authrole'] = (self.eligible_authrole if (type(self.eligible_authrole) == list) else [self.eligible_authrole]) if (self.retain is not None): options[u'retain'] = self.retain return options
':param details_arg: When invoking the endpoint, provide call details in this keyword argument to the callable. :type details_arg: str'
def __init__(self, match=None, invoke=None, concurrency=None, details_arg=None, force_reregister=None):
assert ((match is None) or ((type(match) == six.text_type) and (match in [u'exact', u'prefix', u'wildcard']))) assert ((invoke is None) or ((type(invoke) == six.text_type) and (invoke in [u'single', u'first', u'last', u'roundrobin', u'random']))) assert ((concurrency is None) or ((type(concurrency) in six.integer_types) and (concurrency > 0))) assert ((details_arg is None) or (type(details_arg) == str)) assert (force_reregister in [None, True, False]) self.match = match self.invoke = invoke self.concurrency = concurrency self.details_arg = details_arg self.force_reregister = force_reregister
'Returns options dict as sent within WAMP messages.'
def message_attr(self):
options = {} if (self.match is not None): options[u'match'] = self.match if (self.invoke is not None): options[u'invoke'] = self.invoke if (self.concurrency is not None): options[u'concurrency'] = self.concurrency if (self.force_reregister is not None): options[u'force_reregister'] = self.force_reregister return options
':param registration: The (client side) registration object this invocation is delivered on. :type registration: instance of :class:`autobahn.wamp.request.Registration` :param progress: A callable that will receive progressive call results. :type progress: callable or None :param caller: The WAMP session ID of the caller, if the latter is disclosed. Only filled when caller is disclosed. :type caller: int or None :param caller_authid: The WAMP authid of the original caller of this event. Only filled when caller is disclosed. :type caller_authid: str or None :param caller_authrole: The WAMP authrole of the original caller of this event. Only filled when caller is disclosed. :type caller_authrole: str or None :param procedure: For pattern-based registrations, the actual procedure URI being called. :type procedure: str or None :param enc_algo: Payload encryption algorithm that was in use (currently, either `None` or `"cryptobox"`). :type enc_algo: str or None'
def __init__(self, registration, progress=None, caller=None, caller_authid=None, caller_authrole=None, procedure=None, enc_algo=None):
assert isinstance(registration, Registration) assert ((progress is None) or callable(progress)) assert ((caller is None) or (type(caller) in six.integer_types)) assert ((caller_authid is None) or (type(caller_authid) == six.text_type)) assert ((caller_authrole is None) or (type(caller_authrole) == six.text_type)) assert ((procedure is None) or (type(procedure) == six.text_type)) assert ((enc_algo is None) or (type(enc_algo) == six.text_type)) self.registration = registration self.progress = progress self.caller = caller self.caller_authid = caller_authid self.caller_authrole = caller_authrole self.procedure = procedure self.enc_algo = enc_algo
':param on_progress: A callback that will be called when the remote endpoint called yields interim call progress results. :type on_progress: callable :param timeout: Time in seconds after which the call should be automatically canceled. :type timeout: float'
def __init__(self, on_progress=None, timeout=None):
assert ((on_progress is None) or callable(on_progress)) assert ((timeout is None) or ((type(timeout) in (list(six.integer_types) + [float])) and (timeout > 0))) self.on_progress = on_progress self.timeout = timeout
'Returns options dict as sent within WAMP messages.'
def message_attr(self):
options = {} if (self.timeout is not None): options[u'timeout'] = self.timeout if (self.on_progress is not None): options[u'receive_progress'] = True return options
':param results: The positional result values. :type results: list :param kwresults: The keyword result values. :type kwresults: dict'
def __init__(self, *results, **kwresults):
enc_algo = kwresults.pop('enc_algo', None) assert ((enc_algo is None) or (type(enc_algo) == six.text_type)) self.enc_algo = enc_algo self.results = results self.kwresults = kwresults
':param payload: The encoded application payload. :type payload: bytes :param enc_algo: The payload transparency algorithm identifier to check. :type enc_algo: str :param enc_serializer: The payload transparency serializer identifier to check. :type enc_serializer: str :param enc_key: If using payload transparency with an encryption algorithm, the payload encryption key. :type enc_key: str or None'
def __init__(self, payload, enc_algo, enc_serializer=None, enc_key=None):
assert (type(payload) == six.binary_type) assert (type(enc_algo) == six.text_type) assert ((enc_serializer is None) or (type(enc_serializer) == six.text_type)) assert ((enc_key is None) or (type(enc_key) == six.text_type)) self.payload = payload self.enc_algo = enc_algo self.enc_serializer = enc_serializer self.enc_key = enc_key
':param publication_id: The publication ID of the published event. :type publication_id: int :param was_encrypted: Flag indicating whether the app payload was encrypted. :type was_encrypted: bool'
def __init__(self, publication_id, was_encrypted):
self.id = publication_id self.was_encrypted = was_encrypted
':param subscription_id: The subscription ID. :type subscription_id: int :param topic: The subscription URI or URI pattern. :type topic: str :param session: The ApplicationSession this subscription is living on. :type session: instance of ApplicationSession :param handler: The user event callback. :type handler: callable'
def __init__(self, subscription_id, topic, session, handler):
self.id = subscription_id self.topic = topic self.active = True self.session = session self.handler = handler
'Unsubscribe this subscription.'
def unsubscribe(self):
if self.active: return self.session._unsubscribe(self) else: raise Exception('subscription no longer active')
':param fn: The event handler function to be called. :type fn: callable :param obj: The (optional) object upon which to call the function. :type obj: obj or None :param details_arg: The keyword argument under which event details should be provided. :type details_arg: str or None'
def __init__(self, fn, obj=None, details_arg=None):
self.fn = fn self.obj = obj self.details_arg = details_arg
':param id: The registration ID. :type id: int :param active: Flag indicating whether this registration is active. :type active: bool :param procedure: The procedure URI or URI pattern. :type procedure: callable :param endpoint: The user callback. :type endpoint: callable'
def __init__(self, session, registration_id, procedure, endpoint):
self.id = registration_id self.active = True self.session = session self.procedure = procedure self.endpoint = endpoint
''
def unregister(self):
if self.active: return self.session._unregister(self) else: raise Exception('registration no longer active')
':param fn: The endpoint procedure to be called. :type fn: callable :param obj: The (optional) object upon which to call the function. :type obj: obj or None :param details_arg: The keyword argument under which call details should be provided. :type details_arg: str or None'
def __init__(self, fn, obj=None, details_arg=None):
self.fn = fn self.obj = obj self.details_arg = details_arg
':param request_id: The WAMP request ID. :type request_id: int :param on_reply: The Deferred/Future to be fired when the request returns. :type on_reply: Deferred/Future'
def __init__(self, request_id, on_reply):
self.request_id = request_id self.on_reply = on_reply
':param request_id: The WAMP request ID. :type request_id: int :param on_reply: The Deferred/Future to be fired when the request returns. :type on_reply: Deferred/Future :param was_encrypted: Flag indicating whether the app payload was encrypted. :type was_encrypted: bool'
def __init__(self, request_id, on_reply, was_encrypted):
Request.__init__(self, request_id, on_reply) self.was_encrypted = was_encrypted
':param request_id: The WAMP request ID. :type request_id: int :param topic: The topic URI being subscribed to. :type topic: unicode :param on_reply: The Deferred/Future to be fired when the request returns. :type on_reply: Deferred/Future :param handler: WAMP call options that are in use for this call. :type handler: callable'
def __init__(self, request_id, topic, on_reply, handler):
Request.__init__(self, request_id, on_reply) self.topic = topic self.handler = handler
''
def __init__(self, request_id, on_reply, subscription_id):
Request.__init__(self, request_id, on_reply) self.subscription_id = subscription_id
':param request_id: The WAMP request ID. :type request_id: int :param on_reply: The Deferred/Future to be fired when the request returns. :type on_reply: Deferred/Future :param options: WAMP call options that are in use for this call. :type options: dict'
def __init__(self, request_id, procedure, on_reply, options):
Request.__init__(self, request_id, on_reply) self.procedure = procedure self.options = options
''
def __init__(self, request_id, on_reply, procedure, endpoint):
Request.__init__(self, request_id, on_reply) self.procedure = procedure self.endpoint = endpoint
''
def __init__(self, request_id, on_reply, registration_id):
Request.__init__(self, request_id, on_reply) self.registration_id = registration_id
'Returns next ID. :returns: The next ID. :rtype: int'
def next(self):
self._next += 1 if (self._next > 9007199254740992): self._next = 1 return self._next
':param start: If ``True``, immediately start the stopwatch. :type start: bool'
def __init__(self, start=True):
self._elapsed = 0 if start: self._started = rtime() self._running = True else: self._started = None self._running = False
'Return total time elapsed in seconds during which the stopwatch was running. :returns: The elapsed time in seconds. :rtype: float'
def elapsed(self):
if self._running: now = rtime() return (self._elapsed + (now - self._started)) else: return self._elapsed
'Pauses the stopwatch and returns total time elapsed in seconds during which the stopwatch was running. :returns: The elapsed time in seconds. :rtype: float'
def pause(self):
if self._running: now = rtime() self._elapsed += (now - self._started) self._running = False return self._elapsed else: return self._elapsed
'Resumes a paused stopwatch and returns total elapsed time in seconds during which the stopwatch was running. :returns: The elapsed time in seconds. :rtype: float'
def resume(self):
if (not self._running): self._started = rtime() self._running = True return self._elapsed else: now = rtime() return (self._elapsed + (now - self._started))
'Stops the stopwatch and returns total time elapsed in seconds during which the stopwatch was (previously) running. :returns: The elapsed time in seconds. :rtype: float'
def stop(self):
elapsed = self.pause() self._elapsed = 0 self._started = None self._running = False return elapsed
''
def __init__(self, tracker, tracked):
self.tracker = tracker self.tracked = tracked self._timings = {} self._offset = rtime() self._dt_offset = datetime.utcnow()
'Track elapsed for key. :param key: Key under which to track the timing. :type key: str'
def track(self, key):
self._timings[key] = rtime()
'Get elapsed difference between two previously tracked keys. :param start_key: First key for interval (older timestamp). :type start_key: str :param end_key: Second key for interval (younger timestamp). :type end_key: str :param formatted: If ``True``, format computed time period and return string. :type formatted: bool :returns: Computed time period in seconds (or formatted string). :rtype: float or str'
def diff(self, start_key, end_key, formatted=True):
if ((end_key in self._timings) and (start_key in self._timings)): d = (self._timings[end_key] - self._timings[start_key]) if formatted: if (d < 1e-05): s = ('%d ns' % round((d * 1000000000.0))) elif (d < 0.01): s = ('%d us' % round((d * 1000000.0))) elif (d < 10): s = ('%d ms' % round((d * 1000.0))) else: s = ('%d s' % round(d)) return s.rjust(8) else: return d elif formatted: return 'n.a.'.rjust(8) else: return None
'Return the UTC wall-clock time at which a tracked event occurred. :param key: The key :type key: str :returns: Timezone-naive datetime. :rtype: instance of :py:class:`datetime.datetime`'
def absolute(self, key):
elapsed = self[key] if (elapsed is None): raise KeyError(('No such key "%s".' % elapsed)) return (self._dt_offset + timedelta(seconds=elapsed))
'Compare this object to another object for equality. :param other: The other object to compare with. :type other: obj :returns: ``True`` iff the objects are equal. :rtype: bool'
def __eq__(self, other):
if (not isinstance(other, self.__class__)): return False for k in self.__dict__: if (not k.startswith('_')): if (not (self.__dict__[k] == other.__dict__[k])): return False return True
'Compare this object to another object for inequality. :param other: The other object to compare with. :type other: obj :returns: ``True`` iff the objects are not equal. :rtype: bool'
def __ne__(self, other):
return (not self.__eq__(other))
':param valid_events: if non-None, .on() or .fire() with an event not listed in valid_events raises an exception.'
def set_valid_events(self, valid_events=None):
self._valid_events = list(valid_events)
'Internal helper. Throws RuntimeError if we have a valid_events list, and the given event isnt\' in it. Does nothing otherwise.'
def _check_event(self, event):
if (self._valid_events and (event not in self._valid_events)): raise RuntimeError("Invalid event '{event}'. Expected one of: {events}".format(event=event, events=', '.join(self._valid_events)))
'Add a handler for an event. :param event: the name of the event :param handler: a callable thats invoked when .fire() is called for this events. Arguments will be whatever are given to .fire()'
def on(self, event, handler):
self._check_event(event) if (self._listeners is None): self._listeners = dict() if (event not in self._listeners): self._listeners[event] = [] self._listeners[event].append(handler)
'Stop listening for a single event, or all events. :param event: if None, remove all listeners. Otherwise, remove listeners for the single named event. :param handler: if None, remove all handlers for the named event; otherwise remove just the given handler.'
def off(self, event=None, handler=None):
if (event is None): if (handler is not None): raise RuntimeError("Can't specificy a specific handler without an event") self._listeners = dict() else: if (self._listeners is None): return self._check_event(event) if (event in self._listeners): if (handler is None): del self._listeners[event] else: self._listeners[event].discard(handler)
'Fire a particular event. :param event: the event to fire. All other args and kwargs are passed on to the handler(s) for the event. :return: a Deferred/Future gathering all async results from all handlers and/or parent handlers.'
def fire(self, event, *args, **kwargs):
if (self._listeners is None): return txaio.create_future(result=[]) self._check_event(event) res = [] for handler in self._listeners.get(event, []): future = txaio.as_future(handler, *args, **kwargs) res.append(future) if (self._parent is not None): res.append(self._parent.fire(event, *args, **kwargs)) return txaio.gather(res, consume_exceptions=False)
'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'
def __init__(self, opcode, fin, rsv, length, mask):
self.opcode = opcode self.fin = fin self.rsv = rsv self.length = length self.mask = mask
'Track elapsed for key. :param key: Key under which to track the timing. :type key: str'
def track(self, key):
self._timings[key] = self._stopwatch.elapsed()
'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).'
def diff(self, startKey, endKey, formatted=True):
if ((endKey in self._timings) and (startKey in self._timings)): d = (self._timings[endKey] - self._timings[startKey]) if formatted: if (d < 1e-05): s = ('%d ns' % round((d * 1000000000.0))) elif (d < 0.01): s = ('%d us' % round((d * 1000000.0))) elif (d < 10): s = ('%d ms' % round((d * 1000.0))) else: s = ('%d s' % round(d)) return s.rjust(8) else: return d elif formatted: return 'n.a.'.rjust(8) else: return None
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onOpen`'
def onOpen(self):
self.log.debug('WebSocketProtocol.onOpen')
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageBegin`'
def onMessageBegin(self, isBinary):
self.message_is_binary = isBinary self.message_data = [] self.message_data_total_length = 0
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameBegin`'
def onMessageFrameBegin(self, length):
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._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_MESSAGE_TOO_BIG, u'message exceeds payload limit of {} octets'.format(self.maxMessagePayloadSize)) elif (0 < self.maxFramePayloadSize < length): self.wasMaxFramePayloadSizeExceeded = True self._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_POLICY_VIOLATION, u'frame exceeds payload limit of {} octets'.format(self.maxFramePayloadSize))
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameData`'
def onMessageFrameData(self, payload):
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._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_MESSAGE_TOO_BIG, u'message exceeds payload limit of {} octets'.format(self.maxMessagePayloadSize)) self.message_data.append(payload) else: self.frame_data.append(payload)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameEnd`'
def onMessageFrameEnd(self):
if (not self.failedByMe): self._onMessageFrame(self.frame_data) self.frame_data = None
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrame`'
def onMessageFrame(self, payload):
if (not self.failedByMe): self.message_data.extend(payload)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessageEnd`'
def onMessageEnd(self):
if (not self.failedByMe): payload = ''.join(self.message_data) if self.trackedTimings: self.trackedTimings.track('onMessage') self._onMessage(payload, self.message_is_binary) self.message_data = None
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessage`'
def onMessage(self, payload, isBinary):
self.log.debug('WebSocketProtocol.onMessage(payload=<{payload_len} bytes)>, isBinary={isBinary}', payload_len=(len(payload) if payload else 0), isBinary=isBinary)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onPing`'
def onPing(self, payload):
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)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onPong`'
def onPong(self, payload):
self.log.debug('WebSocketProtocol.onPong(payload=<{payload_len} bytes>)', payload_len=(len(payload) if payload else 0))
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.onClose`'
def onClose(self, wasClean, code, reason):
self.log.debug('WebSocketProtocol.onClose(wasClean={wasClean}, code={code}, reason={reason})', wasClean=wasClean, code=code, reason=reason)
'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'
def onCloseFrame(self, code, reasonRaw):
self.remoteCloseCode = None self.remoteCloseReason = None 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(u'invalid close code {}'.format(code)): return True else: self.remoteCloseCode = WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL else: self.remoteCloseCode = code if (reasonRaw is not None): u = Utf8Validator() val = u.validate(reasonRaw) if (not (val[0] and val[1])): if self._invalid_payload(u'invalid close reason (non-UTF8 payload)'): return True else: self.remoteCloseReason = reasonRaw.decode('utf8') if (self.state == WebSocketProtocol.STATE_CLOSING): 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: self.dropConnection(abort=True) elif (self.serverConnectionDropTimeout > 0): self.serverConnectionDropTimeoutCall = txaio.call_later(self.serverConnectionDropTimeout, self.onServerConnectionDropTimeout) elif (self.state == WebSocketProtocol.STATE_OPEN): self.wasClean = True if (self.websocket_version == 0): self.sendCloseFrame(isReply=True) elif 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: self.dropConnection(abort=False) else: pass elif (self.state == WebSocketProtocol.STATE_CLOSED): self.wasClean = False else: raise Exception('logic error')
'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.'
def onServerConnectionDropTimeout(self):
self.serverConnectionDropTimeoutCall = None if (self.state != WebSocketProtocol.STATE_CLOSED): self.wasClean = False self.wasNotCleanReason = u'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')
'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.'
def onOpenHandshakeTimeout(self):
self.openHandshakeTimeoutCall = None if (self.state in [WebSocketProtocol.STATE_CONNECTING, WebSocketProtocol.STATE_PROXY_CONNECTING]): self.wasClean = False self.wasNotCleanReason = u'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: raise Exception('logic error')
'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.'
def onCloseHandshakeTimeout(self):
self.closeHandshakeTimeoutCall = None if (self.state != WebSocketProtocol.STATE_CLOSED): self.wasClean = False self.wasNotCleanReason = u'WebSocket closing handshake timeout (peer did not finish the opening handshake in time)' self.wasCloseHandshakeTimeout = True self.dropConnection(abort=True) else: self.log.debug('skipping closing handshake timeout: WebSocket connection is already closed')
'When doing automatic ping/pongs to detect broken connection, the peer did not reply in time to our ping. We drop the connection.'
def onAutoPingTimeout(self):
self.wasClean = False self.wasNotCleanReason = u'WebSocket ping timeout (peer did not respond with pong in time)' self.autoPingTimeoutCall = None self.dropConnection(abort=True)
'Drop the underlying TCP connection.'
def dropConnection(self, abort=False):
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 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)
'Fails the WebSocket connection.'
def _fail_connection(self, code=CLOSE_STATUS_CODE_GOING_AWAY, reason=u'going away'):
if (self.state != WebSocketProtocol.STATE_CLOSED): self.log.debug('failing connection: {code}: {reason}', code=code, reason=reason) self.failedByMe = True if self.failByDrop: self.wasClean = False self.wasNotCleanReason = u'I dropped the WebSocket TCP connection: {0}'.format(reason) self.dropConnection(abort=True) elif (self.state != WebSocketProtocol.STATE_CLOSING): self.sendCloseFrame(code=code, reasonUtf8=encode_truncate(reason, 123), isReply=False) else: self.dropConnection(abort=False) else: self.log.debug('skip failing of connection since connection is already closed')
'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.'
def _protocol_violation(self, reason):
self.log.debug('Protocol violation: {reason}', reason=reason) self._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, reason) if self.failByDrop: return True else: return False
'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.'
def _invalid_payload(self, reason):
self.log.debug('Invalid payload: {reason}', reason=reason) self._fail_connection(WebSocketProtocol.CLOSE_STATUS_CODE_INVALID_PAYLOAD, reason) if self.failByDrop: return True else: return False
'Enable/disable tracking of detailed timings. :param enable: Turn time tracking on/off. :type enable: bool'
def setTrackTimings(self, enable):
if ((not hasattr(self, 'trackTimings')) or (self.trackTimings != enable)): self.trackTimings = enable if self.trackTimings: self.trackedTimings = Timings() else: self.trackedTimings = None
'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).'
def _connectionMade(self):
configAttrLog = [] for configAttr in self.CONFIG_ATTRS: if (not hasattr(self, configAttr)): setattr(self, configAttr, getattr(self.factory, configAttr)) configAttrSource = self.factory.__class__.__name__ else: configAttrSource = self.__class__.__name__ configAttrLog.append((configAttr, getattr(self, configAttr), configAttrSource)) self.log.debug('\n{attrs}', attrs=pformat(configAttrLog)) self._perMessageCompress = None self.trackedTimings = None self.setTrackTimings(self.trackTimings) self.trafficStats = TrafficStats() if ((not self.factory.isServer) and (self.factory.proxy is not None)): self.state = WebSocketProtocol.STATE_PROXY_CONNECTING else: self.state = WebSocketProtocol.STATE_CONNECTING self.send_state = WebSocketProtocol.SEND_STATE_GROUND self.data = '' self.send_queue = deque() self.triggered = False self.utf8validator = Utf8Validator() self.wasMaxFramePayloadSizeExceeded = False self.wasMaxMessagePayloadSizeExceeded = False self.closedByMe = False self.failedByMe = False self.droppedByMe = False self.wasClean = False self.wasNotCleanReason = None self.wasServerConnectionDropTimeout = False self.wasOpenHandshakeTimeout = False self.wasCloseHandshakeTimeout = False self.wasServingFlashSocketPolicyFile = False self.localCloseCode = None self.localCloseReason = None self.remoteCloseCode = None self.remoteCloseReason = None if (not self.factory.isServer): self.serverConnectionDropTimeoutCall = None self.openHandshakeTimeoutCall = None self.closeHandshakeTimeoutCall = None self.autoPingTimeoutCall = None self.autoPingPending = None self.autoPingPendingCall = None if (self.openHandshakeTimeout > 0): self.openHandshakeTimeoutCall = self.factory._batched_timer.call_later(self.openHandshakeTimeout, self.onOpenHandshakeTimeout)
'This is called by network framework when a transport connection was lost.'
def _connectionLost(self, reason):
self.log.debug('_connectionLost: {reason}', reason=reason) if ((not self.factory.isServer) and (self.serverConnectionDropTimeoutCall is not None)): self.log.debug('serverConnectionDropTimeoutCall.cancel') self.serverConnectionDropTimeoutCall.cancel() self.serverConnectionDropTimeoutCall = None if self.autoPingPendingCall: self.log.debug('Auto ping/pong: canceling autoPingPendingCall upon lost connection') self.autoPingPendingCall.cancel() self.autoPingPendingCall = None if self.autoPingTimeoutCall: self.log.debug('Auto ping/pong: canceling autoPingTimeoutCall upon lost connection') self.autoPingTimeoutCall.cancel() self.autoPingTimeoutCall = None if (self.state != WebSocketProtocol.STATE_CLOSED): self.state = WebSocketProtocol.STATE_CLOSED txaio.resolve(self.is_closed, self) if self.wasServingFlashSocketPolicyFile: self.log.debug('connection dropped after serving Flash Socket Policy File') elif (not self.wasClean): if ((not self.droppedByMe) and (self.wasNotCleanReason is None)): self.wasNotCleanReason = u'peer dropped the TCP connection without previous WebSocket closing handshake' self._onClose(self.wasClean, WebSocketProtocol.CLOSE_STATUS_CODE_ABNORMAL_CLOSE, ('connection was closed uncleanly (%s)' % self.wasNotCleanReason)) else: self._onClose(self.wasClean, self.remoteCloseCode, self.remoteCloseReason)
'Hook fired right after raw octets have been received, but only when self.logOctets == True.'
def logRxOctets(self, data):
self.log.debug('RX Octets from {peer} : octets = {octets}', peer=self.peer, octets=_LazyHexFormatter(data))
'Hook fired right after raw octets have been sent, but only when self.logOctets == True.'
def logTxOctets(self, data, sync):
self.log.debug('TX Octets to {peer} : sync = {sync}, octets = {octets}', peer=self.peer, sync=sync, octets=_LazyHexFormatter(data))
'Hook fired right after WebSocket frame has been received and decoded, but only when self.logFrames == True.'
def logRxFrame(self, frameHeader, payload):
data = ''.join(payload) self.log.debug('RX Frame from {peer} : fin = {fin}, rsv = {rsv}, opcode = {opcode}, mask = {mask}, length = {length}, payload = {payload}', peer=self.peer, fin=frameHeader.fin, rsv=frameHeader.rsv, opcode=frameHeader.opcode, mask=(binascii.b2a_hex(frameHeader.mask) if frameHeader.mask else '-'), length=frameHeader.length, payload=(repr(data) if (frameHeader.opcode == 1) else _LazyHexFormatter(data)))
'Hook fired right after WebSocket frame has been encoded and sent, but only when self.logFrames == True.'
def logTxFrame(self, frameHeader, payload, repeatLength, chopsize, sync):
self.log.debug('TX Frame to {peer} : fin = {fin}, rsv = {rsv}, opcode = {opcode}, mask = {mask}, length = {length}, repeat_length = {repeat_length}, chopsize = {chopsize}, sync = {sync}, payload = {payload}', peer=self.peer, fin=frameHeader.fin, rsv=frameHeader.rsv, opcode=frameHeader.opcode, mask=(binascii.b2a_hex(frameHeader.mask) if frameHeader.mask else '-'), length=frameHeader.length, repeat_length=repeatLength, chopsize=chopsize, sync=sync, payload=(repr(payload) if (frameHeader.opcode == 1) else _LazyHexFormatter(payload)))
'This is called by network framework upon receiving data on transport connection.'
def _dataReceived(self, data):
if (self.state == WebSocketProtocol.STATE_OPEN): self.trafficStats.incomingOctetsWireLevel += len(data) elif ((self.state == WebSocketProtocol.STATE_CONNECTING) or (self.state == WebSocketProtocol.STATE_PROXY_CONNECTING)): self.trafficStats.preopenIncomingOctetsWireLevel += len(data) if self.logOctets: self.logRxOctets(data) self.data += data self.consumeData()
'Consume buffered (incoming) data.'
def consumeData(self):
if ((self.state == WebSocketProtocol.STATE_OPEN) or (self.state == WebSocketProtocol.STATE_CLOSING)): while (self.processData() and (self.state != WebSocketProtocol.STATE_CLOSED)): pass elif (self.state == WebSocketProtocol.STATE_PROXY_CONNECTING): self.processProxyConnect() elif (self.state == WebSocketProtocol.STATE_CONNECTING): self.processHandshake() elif (self.state == WebSocketProtocol.STATE_CLOSED): self.log.debug('received data in STATE_CLOSED') else: raise Exception('invalid state')
'Process proxy connect.'
def processProxyConnect(self):
raise Exception('must implement proxy connect (client or server) in derived class')
'Process WebSocket handshake.'
def processHandshake(self):
raise Exception('must implement handshake (client or server) in derived class')
'Trigger sending stuff from send queue (which is only used for chopped/synched writes).'
def _trigger(self):
if (not self.triggered): self.triggered = True self._send()
'Send out stuff from send queue. For details how this works, see test/trickling in the repo.'
def _send(self):
if (len(self.send_queue) > 0): e = self.send_queue.popleft() if (self.state != WebSocketProtocol.STATE_CLOSED): self.transport.write(e[0]) if (self.state == WebSocketProtocol.STATE_OPEN): self.trafficStats.outgoingOctetsWireLevel += len(e[0]) elif ((self.state == WebSocketProtocol.STATE_CONNECTING) or (self.state == WebSocketProtocol.STATE_PROXY_CONNECTING)): self.trafficStats.preopenOutgoingOctetsWireLevel += len(e[0]) if self.logOctets: self.logTxOctets(e[0], e[1]) else: self.log.debug('skipped delayed write, since connection is closed') txaio.call_later(WebSocketProtocol._QUEUED_WRITE_DELAY, self._send) else: self.triggered = False
'Wrapper for self.transport.write which allows to give a chopsize. When asked to chop up writing to TCP stream, we write only chopsize octets and then give up control to select() in underlying reactor so that bytes get onto wire immediately. Note that this is different from and unrelated to WebSocket data message fragmentation. Note that this is also different from the TcpNoDelay option which can be set on the socket.'
def sendData(self, data, sync=False, chopsize=None):
if (chopsize and (chopsize > 0)): i = 0 n = len(data) done = False while (not done): j = (i + chopsize) if (j >= n): done = True j = n self.send_queue.append((data[i:j], True)) i += chopsize self._trigger() elif (sync or (len(self.send_queue) > 0)): self.send_queue.append((data, sync)) self._trigger() else: self.transport.write(data) if (self.state == WebSocketProtocol.STATE_OPEN): self.trafficStats.outgoingOctetsWireLevel += len(data) elif ((self.state == WebSocketProtocol.STATE_CONNECTING) or (self.state == WebSocketProtocol.STATE_PROXY_CONNECTING)): self.trafficStats.preopenOutgoingOctetsWireLevel += len(data) if self.logOctets: self.logTxOctets(data, False)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendPreparedMessage`'
def sendPreparedMessage(self, preparedMsg):
if ((self._perMessageCompress is None) or preparedMsg.doNotCompress): self.sendData(preparedMsg.payloadHybi) else: self.sendMessage(preparedMsg.payload, preparedMsg.binary)
'After WebSocket handshake has been completed, this procedure will do all subsequent processing of incoming bytes.'
def processData(self):
buffered_len = len(self.data) if (self.current_frame is None): if (buffered_len >= 2): if six.PY3: b = self.data[0] else: b = ord(self.data[0]) frame_fin = ((b & 128) != 0) frame_rsv = ((b & 112) >> 4) frame_opcode = (b & 15) if six.PY3: b = self.data[1] else: b = ord(self.data[1]) frame_masked = ((b & 128) != 0) frame_payload_len1 = (b & 127) if (frame_rsv != 0): if ((self._perMessageCompress is not None) and (frame_rsv == 4)): pass elif self._protocol_violation(u'RSV = {} and no extension negotiated'.format(frame_rsv)): return False if (self.factory.isServer and self.requireMaskedClientFrames and (not frame_masked)): if self._protocol_violation(u'unmasked client-to-server frame'): return False if ((not self.factory.isServer) and (not self.acceptMaskedServerFrames) and frame_masked): if self._protocol_violation(u'masked server-to-client frame'): return False if (frame_opcode > 7): if (not frame_fin): if self._protocol_violation(u'fragmented control frame'): return False if (frame_payload_len1 > 125): if self._protocol_violation(u'control frame with payload length > 125 octets'): return False if (frame_opcode not in [8, 9, 10]): if self._protocol_violation(u'control frame using reserved opcode {}'.format(frame_opcode)): return False if ((frame_opcode == 8) and (frame_payload_len1 == 1)): if self._protocol_violation(u'received close control frame with payload len 1'): return False if ((self._perMessageCompress is not None) and (frame_rsv == 4)): if self._protocol_violation(u'received compressed control frame [{}]'.format(self._perMessageCompress.EXTENSION_NAME)): return False else: if (frame_opcode not in [0, 1, 2]): if self._protocol_violation(u'data frame using reserved opcode {}'.format(frame_opcode)): return False if ((not self.inside_message) and (frame_opcode == 0)): if self._protocol_violation(u'received continuation data frame outside fragmented message'): return False if (self.inside_message and (frame_opcode != 0)): if self._protocol_violation(u'received non-continuation data frame while inside fragmented message'): return False if ((self._perMessageCompress is not None) and (frame_rsv == 4) and self.inside_message): if self._protocol_violation(u'received continuation data frame with compress bit set [{}]'.format(self._perMessageCompress.EXTENSION_NAME)): return False if frame_masked: mask_len = 4 else: mask_len = 0 if (frame_payload_len1 < 126): frame_header_len = (2 + mask_len) elif (frame_payload_len1 == 126): frame_header_len = ((2 + 2) + mask_len) elif (frame_payload_len1 == 127): frame_header_len = ((2 + 8) + mask_len) else: raise Exception('logic error') if (buffered_len >= frame_header_len): i = 2 if (frame_payload_len1 == 126): frame_payload_len = struct.unpack('!H', self.data[i:(i + 2)])[0] if (frame_payload_len < 126): if self._protocol_violation(u'invalid data frame length (not using minimal length encoding)'): return False i += 2 elif (frame_payload_len1 == 127): frame_payload_len = struct.unpack('!Q', self.data[i:(i + 8)])[0] if (frame_payload_len > 9223372036854775807): if self._protocol_violation(u'invalid data frame length (>2^63)'): return False if (frame_payload_len < 65536): if self._protocol_violation(u'invalid data frame length (not using minimal length encoding)'): return False i += 8 else: frame_payload_len = frame_payload_len1 frame_mask = None if frame_masked: frame_mask = self.data[i:(i + 4)] i += 4 if (frame_masked and (frame_payload_len > 0) and self.applyMask): self.current_frame_masker = create_xor_masker(frame_mask, frame_payload_len) else: self.current_frame_masker = XorMaskerNull() self.data = self.data[i:] self.current_frame = FrameHeader(frame_opcode, frame_fin, frame_rsv, frame_payload_len, frame_mask) self.onFrameBegin() return ((frame_payload_len == 0) or (len(self.data) > 0)) else: return False else: return False else: rest = (self.current_frame.length - self.current_frame_masker.pointer()) if (buffered_len >= rest): data = self.data[:rest] length = rest self.data = self.data[rest:] else: data = self.data length = buffered_len self.data = '' if (length > 0): payload = self.current_frame_masker.process(data) else: payload = '' fr = self.onFrameData(payload) if (fr is False): return False if (self.current_frame_masker.pointer() == self.current_frame.length): fr = self.onFrameEnd() if (fr is False): return False return (len(self.data) > 0)
'Begin of receive new frame.'
def onFrameBegin(self):
if (self.current_frame.opcode > 7): self.control_frame_data = [] else: if (not self.inside_message): self.inside_message = True if ((self._perMessageCompress is not None) and (self.current_frame.rsv == 4)): self._isMessageCompressed = True self._perMessageCompress.start_decompress_message() else: self._isMessageCompressed = False if ((self.current_frame.opcode == WebSocketProtocol.MESSAGE_TYPE_TEXT) and self.utf8validateIncoming): self.utf8validator.reset() self.utf8validateIncomingCurrentMessage = True self.utf8validateLast = (True, True, 0, 0) else: self.utf8validateIncomingCurrentMessage = False if self.trackedTimings: self.trackedTimings.track('onMessageBegin') self._onMessageBegin((self.current_frame.opcode == WebSocketProtocol.MESSAGE_TYPE_BINARY)) self._onMessageFrameBegin(self.current_frame.length)
'New data received within frame.'
def onFrameData(self, payload):
if (self.current_frame.opcode > 7): self.control_frame_data.append(payload) else: if self._isMessageCompressed: compressedLen = len(payload) self.log.debug('RX compressed [length]: octets', legnth=compressedLen, octets=_LazyHexFormatter(payload)) payload = self._perMessageCompress.decompress_message_data(payload) uncompressedLen = len(payload) else: l = len(payload) compressedLen = l uncompressedLen = l if (self.state == WebSocketProtocol.STATE_OPEN): self.trafficStats.incomingOctetsWebSocketLevel += compressedLen self.trafficStats.incomingOctetsAppLevel += uncompressedLen if self.utf8validateIncomingCurrentMessage: self.utf8validateLast = self.utf8validator.validate(payload) if (not self.utf8validateLast[0]): if self._invalid_payload(u'encountered invalid UTF-8 while processing text message at payload octet index {}'.format(self.utf8validateLast[3])): return False self._onMessageFrameData(payload)
'End of frame received.'
def onFrameEnd(self):
if (self.current_frame.opcode > 7): if self.logFrames: self.logRxFrame(self.current_frame, self.control_frame_data) self.processControlFrame() else: if (self.state == WebSocketProtocol.STATE_OPEN): self.trafficStats.incomingWebSocketFrames += 1 if self.logFrames: self.logRxFrame(self.current_frame, self.frame_data) self._onMessageFrameEnd() if self.current_frame.fin: if self._isMessageCompressed: self._perMessageCompress.end_decompress_message() if self.utf8validateIncomingCurrentMessage: if (not self.utf8validateLast[1]): if self._invalid_payload(u'UTF-8 text message payload ended within Unicode code point at payload octet index {}'.format(self.utf8validateLast[3])): return False if (self.state == WebSocketProtocol.STATE_OPEN): self.trafficStats.incomingWebSocketMessages += 1 self._onMessageEnd() self.inside_message = False self.current_frame = None
'Process a completely received control frame.'
def processControlFrame(self):
payload = ''.join(self.control_frame_data) self.control_frame_data = None if (self.current_frame.opcode == 8): code = None reasonRaw = None ll = len(payload) if (ll > 1): code = struct.unpack('!H', payload[0:2])[0] if (ll > 2): reasonRaw = payload[2:] if self.onCloseFrame(code, reasonRaw): return False elif (self.current_frame.opcode == 9): self._onPing(payload) elif (self.current_frame.opcode == 10): if self.autoPingPending: try: if (payload == self.autoPingPending): self.log.debug('Auto ping/pong: received pending pong for auto-ping/pong') if self.autoPingTimeoutCall: self.autoPingTimeoutCall.cancel() self.autoPingPending = None self.autoPingTimeoutCall = None if self.autoPingInterval: self.autoPingPendingCall = self.factory._batched_timer.call_later(self.autoPingInterval, self._sendAutoPing) else: self.log.debug('Auto ping/pong: received non-pending pong') except: self.log.debug('Auto ping/pong: received non-pending pong') self._onPong(payload) else: pass return True
'Send out frame. Normally only used internally via sendMessage(), sendPing(), sendPong() and sendClose(). This method deliberately allows to send invalid frames (that is frames invalid per-se, or frames invalid because of protocol state). Other than in fuzzing servers, calling methods will ensure that no invalid frames are sent. In addition, this method supports explicit specification of payload length. When payload_len is given, it will always write that many octets to the stream. It\'ll wrap within payload, resending parts of that when more octets were requested The use case is again for fuzzing server which want to sent increasing amounts of payload data to peers without having to construct potentially large messages themselves.'
def sendFrame(self, opcode, payload='', fin=True, rsv=0, mask=None, payload_len=None, chopsize=None, sync=False):
if (payload_len is not None): if (len(payload) < 1): raise Exception(('cannot construct repeated payload with length %d from payload of length %d' % (payload_len, len(payload)))) l = payload_len pl = (''.join([payload for _ in range((payload_len / len(payload)))]) + payload[:(payload_len % len(payload))]) else: l = len(payload) pl = payload b0 = 0 if fin: b0 |= (1 << 7) b0 |= ((rsv % 8) << 4) b0 |= (opcode % 128) b1 = 0 if (mask or ((not self.factory.isServer) and self.maskClientFrames) or (self.factory.isServer and self.maskServerFrames)): b1 |= (1 << 7) if (not mask): mask = struct.pack('!I', random.getrandbits(32)) mv = mask else: mv = '' if ((l > 0) and self.applyMask): masker = create_xor_masker(mask, l) plm = masker.process(pl) else: plm = pl else: mv = '' plm = pl el = '' if (l <= 125): b1 |= l elif (l <= 65535): b1 |= 126 el = struct.pack('!H', l) elif (l <= 9223372036854775807): b1 |= 127 el = struct.pack('!Q', l) else: raise Exception('invalid payload length') if six.PY3: raw = ''.join([b0.to_bytes(1, 'big'), b1.to_bytes(1, 'big'), el, mv, plm]) else: raw = ''.join([chr(b0), chr(b1), el, mv, plm]) if (opcode in [0, 1, 2]): self.trafficStats.outgoingWebSocketFrames += 1 if self.logFrames: frameHeader = FrameHeader(opcode, fin, rsv, l, mask) self.logTxFrame(frameHeader, payload, payload_len, chopsize, sync) self.sendData(raw, sync, chopsize)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendPing`'
def sendPing(self, payload=None):
if (self.state != WebSocketProtocol.STATE_OPEN): return if payload: l = len(payload) if (l > 125): raise Exception(('invalid payload for PING (payload length must be <= 125, was %d)' % l)) self.sendFrame(opcode=9, payload=payload) else: self.sendFrame(opcode=9)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendPong`'
def sendPong(self, payload=None):
if (self.state != WebSocketProtocol.STATE_OPEN): return if payload: l = len(payload) if (l > 125): raise Exception(('invalid payload for PONG (payload length must be <= 125, was %d)' % l)) self.sendFrame(opcode=10, payload=payload) else: self.sendFrame(opcode=10)
'Send a close frame and update protocol state. Note, that this is an internal method which deliberately allows not send close frame with invalid payload.'
def sendCloseFrame(self, code=None, reasonUtf8=None, isReply=False):
if (self.state == WebSocketProtocol.STATE_CLOSING): self.log.debug('ignoring sendCloseFrame since connection is closing') elif (self.state == WebSocketProtocol.STATE_CLOSED): self.log.debug('ignoring sendCloseFrame since connection already closed') elif (self.state in [WebSocketProtocol.STATE_PROXY_CONNECTING, WebSocketProtocol.STATE_CONNECTING]): raise Exception('cannot close a connection not yet connected') elif (self.state == WebSocketProtocol.STATE_OPEN): payload = '' if (code is not None): payload += struct.pack('!H', code) if (reasonUtf8 is not None): payload += reasonUtf8 self.sendFrame(opcode=8, payload=payload) self.state = WebSocketProtocol.STATE_CLOSING self.closedByMe = (not isReply) self.localCloseCode = code self.localCloseReason = reasonUtf8 if (self.closedByMe and (self.closeHandshakeTimeout > 0)): self.closeHandshakeTimeoutCall = self.factory._batched_timer.call_later(self.closeHandshakeTimeout, self.onCloseHandshakeTimeout) else: raise Exception('logic error')
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendClose`'
def sendClose(self, code=None, reason=None):
if (code is not None): if (type(code) not in six.integer_types): raise Exception("invalid type '{}' for close code (must be an integer)".format(type(code))) if ((code != 1000) and (not (3000 <= code <= 4999))): raise Exception('invalid close code {} (must be 1000 or from [3000, 4999])'.format(code)) if (reason is not None): if (code is None): raise Exception('close reason without close code') if (type(reason) != six.text_type): raise Exception("reason must be of type unicode (was '{}')".format(type(reason))) reasonUtf8 = encode_truncate(reason, 123) else: reasonUtf8 = None self.sendCloseFrame(code=code, reasonUtf8=reasonUtf8, isReply=False)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.beginMessage`'
def beginMessage(self, isBinary=False, doNotCompress=False):
if (self.state != WebSocketProtocol.STATE_OPEN): return if (self.send_state != WebSocketProtocol.SEND_STATE_GROUND): raise Exception('WebSocketProtocol.beginMessage invalid in current sending state') self.send_message_opcode = (WebSocketProtocol.MESSAGE_TYPE_BINARY if isBinary else WebSocketProtocol.MESSAGE_TYPE_TEXT) self.send_state = WebSocketProtocol.SEND_STATE_MESSAGE_BEGIN if ((self._perMessageCompress is not None) and (not doNotCompress)): self.send_compressed = True self._perMessageCompress.start_compress_message() else: self.send_compressed = False self.trafficStats.outgoingWebSocketMessages += 1
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.beginMessageFrame`'
def beginMessageFrame(self, length):
if (self.state != WebSocketProtocol.STATE_OPEN): return if (self.send_state not in [WebSocketProtocol.SEND_STATE_MESSAGE_BEGIN, WebSocketProtocol.SEND_STATE_INSIDE_MESSAGE]): raise Exception(('WebSocketProtocol.beginMessageFrame invalid in current sending state [%d]' % self.send_state)) if ((type(length) != int) or (length < 0) or (length > 9223372036854775807)): raise Exception('invalid value for message frame length') self.send_message_frame_length = length self.trafficStats.outgoingWebSocketFrames += 1 if (((not self.factory.isServer) and self.maskClientFrames) or (self.factory.isServer and self.maskServerFrames)): self.send_message_frame_mask = struct.pack('!I', random.getrandbits(32)) else: self.send_message_frame_mask = None if (self.send_message_frame_mask and (length > 0) and self.applyMask): self.send_message_frame_masker = create_xor_masker(self.send_message_frame_mask, length) else: self.send_message_frame_masker = XorMaskerNull() b0 = 0 if (self.send_state == WebSocketProtocol.SEND_STATE_MESSAGE_BEGIN): b0 |= (self.send_message_opcode % 128) if self.send_compressed: b0 |= ((4 % 8) << 4) self.send_state = WebSocketProtocol.SEND_STATE_INSIDE_MESSAGE else: pass b1 = 0 if self.send_message_frame_mask: b1 |= (1 << 7) mv = self.send_message_frame_mask else: mv = '' el = '' if (length <= 125): b1 |= length elif (length <= 65535): b1 |= 126 el = struct.pack('!H', length) elif (length <= 9223372036854775807): b1 |= 127 el = struct.pack('!Q', length) else: raise Exception('invalid payload length') if six.PY3: header = ''.join([b0.to_bytes(1, 'big'), b1.to_bytes(1, 'big'), el, mv]) else: header = ''.join([chr(b0), chr(b1), el, mv]) self.sendData(header) self.send_state = WebSocketProtocol.SEND_STATE_INSIDE_MESSAGE_FRAME
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendMessageFrameData`'
def sendMessageFrameData(self, payload, sync=False):
if (self.state != WebSocketProtocol.STATE_OPEN): return if (not self.send_compressed): self.trafficStats.outgoingOctetsAppLevel += len(payload) self.trafficStats.outgoingOctetsWebSocketLevel += len(payload) if (self.send_state != WebSocketProtocol.SEND_STATE_INSIDE_MESSAGE_FRAME): raise Exception('WebSocketProtocol.sendMessageFrameData invalid in current sending state') rl = len(payload) if ((self.send_message_frame_masker.pointer() + rl) > self.send_message_frame_length): l = (self.send_message_frame_length - self.send_message_frame_masker.pointer()) rest = (- (rl - l)) pl = payload[:l] else: l = rl rest = ((self.send_message_frame_length - self.send_message_frame_masker.pointer()) - l) pl = payload plm = self.send_message_frame_masker.process(pl) self.sendData(plm, sync=sync) if (self.send_message_frame_masker.pointer() >= self.send_message_frame_length): self.send_state = WebSocketProtocol.SEND_STATE_INSIDE_MESSAGE return rest
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.endMessage`'
def endMessage(self):
if (self.state != WebSocketProtocol.STATE_OPEN): return if self.send_compressed: payload = self._perMessageCompress.end_compress_message() self.trafficStats.outgoingOctetsWebSocketLevel += len(payload) else: payload = '' self.sendFrame(opcode=0, payload=payload, fin=True) self.send_state = WebSocketProtocol.SEND_STATE_GROUND
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendMessageFrame`'
def sendMessageFrame(self, payload, sync=False):
if (self.state != WebSocketProtocol.STATE_OPEN): return if self.send_compressed: self.trafficStats.outgoingOctetsAppLevel += len(payload) payload = self._perMessageCompress.compress_message_data(payload) self.beginMessageFrame(len(payload)) self.sendMessageFrameData(payload, sync)
'Implements :func:`autobahn.websocket.interfaces.IWebSocketChannel.sendMessage`'
def sendMessage(self, payload, isBinary=False, fragmentSize=None, sync=False, doNotCompress=False):
assert (type(payload) == bytes) if (self.state != WebSocketProtocol.STATE_OPEN): return if self.trackedTimings: self.trackedTimings.track('sendMessage') if isBinary: opcode = 2 else: opcode = 1 self.trafficStats.outgoingWebSocketMessages += 1 if ((self._perMessageCompress is not None) and (not doNotCompress)): sendCompressed = True self._perMessageCompress.start_compress_message() self.trafficStats.outgoingOctetsAppLevel += len(payload) payload1 = self._perMessageCompress.compress_message_data(payload) payload2 = self._perMessageCompress.end_compress_message() payload = ''.join([payload1, payload2]) self.trafficStats.outgoingOctetsWebSocketLevel += len(payload) else: sendCompressed = False l = len(payload) self.trafficStats.outgoingOctetsAppLevel += l self.trafficStats.outgoingOctetsWebSocketLevel += l if (fragmentSize is not None): pfs = fragmentSize elif (self.autoFragmentSize > 0): pfs = self.autoFragmentSize else: pfs = None if ((pfs is None) or (len(payload) <= pfs)): self.sendFrame(opcode=opcode, payload=payload, sync=sync, rsv=(4 if sendCompressed else 0)) else: if (pfs < 1): raise Exception(('payload fragment size must be at least 1 (was %d)' % pfs)) n = len(payload) i = 0 done = False first = True while (not done): j = (i + pfs) if (j > n): done = True j = n if first: self.sendFrame(opcode=opcode, payload=payload[i:j], fin=done, sync=sync, rsv=(4 if sendCompressed else 0)) first = False else: self.sendFrame(opcode=0, payload=payload[i:j], fin=done, sync=sync) i += pfs
'Parse the Sec-WebSocket-Extensions header.'
def _parseExtensionsHeader(self, header, removeQuotes=True):
extensions = [] exts = [str(x.strip()) for x in header.split(',')] for e in exts: if (e != ''): ext = [x.strip() for x in e.split(';')] if (len(ext) > 0): extension = ext[0].lower() params = {} for p in ext[1:]: p = [x.strip() for x in p.split('=')] key = p[0].lower() if (len(p) > 1): value = '='.join(p[1:]) if removeQuotes: if ((len(value) > 0) and (value[0] == '"')): value = value[1:] if ((len(value) > 0) and (value[(-1)] == '"')): value = value[:(-1)] else: value = True if (key not in params): params[key] = [] params[key].append(value) extensions.append((extension, params)) else: pass return extensions
'Ctor for a prepared message. :param payload: The message payload. :type payload: str :param isBinary: Provide `True` for binary payload. :type isBinary: bool :param applyMask: Provide `True` if WebSocket message is to be masked (required for client to server WebSocket messages). :type applyMask: bool :param doNotCompress: Iff `True`, never compress this message. This only applies when WebSocket compression has been negotiated on the WebSocket connection. Use when you know the payload incompressible (e.g. encrypted or already compressed). :type doNotCompress: bool'
def __init__(self, payload, isBinary, applyMask, doNotCompress):
if (not doNotCompress): self.payload = payload self.binary = isBinary self.doNotCompress = doNotCompress l = len(payload) b0 = (((1 << 7) | 2) if isBinary else ((1 << 7) | 1)) if applyMask: b1 = (1 << 7) mask = struct.pack('!I', random.getrandbits(32)) if (l == 0): plm = payload else: plm = create_xor_masker(mask, l).process(payload) else: b1 = 0 mask = '' plm = payload el = '' if (l <= 125): b1 |= l elif (l <= 65535): b1 |= 126 el = struct.pack('!H', l) elif (l <= 9223372036854775807): b1 |= 127 el = struct.pack('!Q', l) else: raise Exception('invalid payload length') if six.PY3: self.payloadHybi = ''.join([b0.to_bytes(1, 'big'), b1.to_bytes(1, 'big'), el, mask, plm]) else: self.payloadHybi = ''.join([chr(b0), chr(b1), el, mask, plm])
'Prepare a WebSocket message. This can be later sent on multiple instances of :class:`autobahn.websocket.WebSocketProtocol` using :meth:`autobahn.websocket.WebSocketProtocol.sendPreparedMessage`. By doing so, you can avoid the (small) overhead of framing the *same* payload into WebSocket messages multiple times when that same payload is to be sent out on multiple connections. :param payload: The message payload. :type payload: bytes :param isBinary: `True` iff payload is binary, else the payload must be UTF-8 encoded text. :type isBinary: bool :param doNotCompress: Iff `True`, never compress this message. This only applies when WebSocket compression has been negotiated on the WebSocket connection. Use when you know the payload incompressible (e.g. encrypted or already compressed). :type doNotCompress: bool :returns: obj -- An instance of :class:`autobahn.websocket.protocol.PreparedMessage`.'
def prepareMessage(self, payload, isBinary=False, doNotCompress=False):
applyMask = (not self.isServer) return PreparedMessage(payload, isBinary, applyMask, doNotCompress)
'Callback fired during WebSocket opening handshake when new WebSocket client connection is about to be established. When you want to accept the connection, return the accepted protocol from list of WebSocket (sub)protocols provided by client or `None` to speak no specific one or when the client protocol list was empty. You may also return a pair of `(protocol, headers)` to send additional HTTP headers, with `headers` being a dictionary of key-values. Throw :class:`autobahn.websocket.types.ConnectionDeny` when you don\'t want to accept the WebSocket connection request. :param request: WebSocket connection request information. :type request: instance of :class:`autobahn.websocket.protocol.ConnectionRequest`'
def onConnect(self, request):
return None
'Called by network framework when new transport connection from client was accepted. Default implementation will prepare for initial WebSocket opening handshake. When overriding in derived class, make sure to call this base class implementation *before* your code.'
def _connectionMade(self):
WebSocketProtocol._connectionMade(self) self.factory.countConnections += 1 self.log.debug('connection accepted from peer {peer}', peer=self.peer)
'Called by network framework when established transport connection from client was lost. Default implementation will tear down all state properly. When overriding in derived class, make sure to call this base class implementation *after* your code.'
def _connectionLost(self, reason):
WebSocketProtocol._connectionLost(self, reason) self.factory.countConnections -= 1
'Process WebSocket opening handshake request from client.'
def processHandshake(self):
end_of_header = self.data.find('\r\n\r\n') if (end_of_header >= 0): self.http_request_data = self.data[:(end_of_header + 4)] self.log.debug('received HTTP request:\n\n{data}\n\n', data=self.http_request_data) try: (self.http_status_line, self.http_headers, http_headers_cnt) = parseHttpHeader(self.http_request_data) except Exception as e: return self.failHandshake('Error during parsing of HTTP status line / request headers : {0}'.format(e)) if (('x-forwarded-for' in self.http_headers) and self.trustXForwardedFor): addresses = [x.strip() for x in self.http_headers['x-forwarded-for'].split(',')] trusted_addresses = addresses[(- self.trustXForwardedFor):] self.peer = trusted_addresses[0] self.log.debug('received HTTP status line in opening handshake : {status}', status=self.http_status_line) self.log.debug('received HTTP headers in opening handshake : {headers}', headers=self.http_headers) rl = self.http_status_line.split() if (len(rl) != 3): return self.failHandshake(("Bad HTTP request status line '%s'" % self.http_status_line)) if (rl[0].strip() != 'GET'): return self.failHandshake(("HTTP method '%s' not allowed" % rl[0]), 405) vs = rl[2].strip().split('/') if ((len(vs) != 2) or (vs[0] != 'HTTP') or (vs[1] not in ['1.1'])): return self.failHandshake(("Unsupported HTTP version '%s'" % rl[2]), 505) self.http_request_uri = rl[1].strip() try: (scheme, netloc, path, params, query, fragment) = urllib.parse.urlparse(self.http_request_uri) if ((scheme != '') or (netloc != '')): pass if (fragment != ''): return self.failHandshake(("HTTP requested resource contains a fragment identifier '%s'" % fragment)) self.http_request_path = path self.http_request_params = urllib.parse.parse_qs(query) except: return self.failHandshake(("Bad HTTP request resource - could not parse '%s'" % rl[1].strip())) if ('host' not in self.http_headers): return self.failHandshake('HTTP Host header missing in opening handshake request') if (http_headers_cnt['host'] > 1): return self.failHandshake('HTTP Host header appears more than once in opening handshake request') self.http_request_host = self.http_headers['host'].strip() if ((self.http_request_host.find(':') >= 0) and (not self.http_request_host.endswith(']'))): (h, p) = self.http_request_host.rsplit(':', 1) try: port = int(str(p.strip())) except ValueError: return self.failHandshake(("invalid port '%s' in HTTP Host header '%s'" % (str(p.strip()), str(self.http_request_host)))) if self.factory.externalPort: if (port != self.factory.externalPort): return self.failHandshake(("port %d in HTTP Host header '%s' does not match server listening port %s" % (port, str(self.http_request_host), self.factory.externalPort))) else: self.log.debug('skipping opening handshake port checking - neither WS URL nor external port set') self.http_request_host = h elif self.factory.externalPort: if (not ((self.factory.isSecure and (self.factory.externalPort == 443)) or ((not self.factory.isSecure) and (self.factory.externalPort == 80)))): return self.failHandshake(("missing port in HTTP Host header '%s' and server runs on non-standard port %d (wss = %s)" % (str(self.http_request_host), self.factory.externalPort, self.factory.isSecure))) else: self.log.debug('skipping opening handshake port checking - neither WS URL nor external port set') if ('upgrade' not in self.http_headers): if self.webStatus: if (('redirect' in self.http_request_params) and (len(self.http_request_params['redirect']) > 0)): url = self.http_request_params['redirect'][0] if (('after' in self.http_request_params) and (len(self.http_request_params['after']) > 0)): after = int(self.http_request_params['after'][0]) self.log.debug('HTTP Upgrade header missing : render server status page and meta-refresh-redirecting to {url} after {duration} seconds', url=url, duration=after) self.sendServerStatus(url, after) else: self.log.debug('HTTP Upgrade header missing : 303-redirecting to {url}', url=url) self.sendRedirect(url) else: self.log.debug('HTTP Upgrade header missing : render server status page') self.sendServerStatus() self.dropConnection(abort=False) return else: return self.failHandshake('HTTP Upgrade header missing', 426) upgradeWebSocket = False for u in self.http_headers['upgrade'].split(','): if (u.strip().lower() == 'websocket'): upgradeWebSocket = True break if (not upgradeWebSocket): return self.failHandshake(("HTTP Upgrade headers do not include 'websocket' value (case-insensitive) : %s" % self.http_headers['upgrade'])) if ('connection' not in self.http_headers): return self.failHandshake('HTTP Connection header missing') connectionUpgrade = False for c in self.http_headers['connection'].split(','): if (c.strip().lower() == 'upgrade'): connectionUpgrade = True break if (not connectionUpgrade): return self.failHandshake(("HTTP Connection headers do not include 'upgrade' value (case-insensitive) : %s" % self.http_headers['connection'])) if ('sec-websocket-version' not in self.http_headers): self.log.debug('Hixie76 protocol detected') return self.failHandshake('WebSocket connection denied - Hixie76 protocol not supported.') else: self.log.debug('Hybi protocol detected') if (http_headers_cnt['sec-websocket-version'] > 1): return self.failHandshake('HTTP Sec-WebSocket-Version header appears more than once in opening handshake request') try: version = int(self.http_headers['sec-websocket-version']) except ValueError: return self.failHandshake(("could not parse HTTP Sec-WebSocket-Version header '%s' in opening handshake request" % self.http_headers['sec-websocket-version'])) if (version not in self.versions): sv = sorted(self.versions) sv.reverse() svs = ','.join([str(x) for x in sv]) return self.failHandshake(('WebSocket version %d not supported (supported versions: %s)' % (version, svs)), 400, [('Sec-WebSocket-Version', svs)]) else: self.websocket_version = version if ('sec-websocket-protocol' in self.http_headers): protocols = [str(x.strip()) for x in self.http_headers['sec-websocket-protocol'].split(',')] pp = {} for p in protocols: if (p in pp): return self.failHandshake(("duplicate protocol '%s' specified in HTTP Sec-WebSocket-Protocol header" % p)) else: pp[p] = 1 self.websocket_protocols = protocols else: self.websocket_protocols = [] if (self.websocket_version < 13): websocket_origin_header_key = 'sec-websocket-origin' else: websocket_origin_header_key = 'origin' self.websocket_origin = '' if (websocket_origin_header_key in self.http_headers): if (http_headers_cnt[websocket_origin_header_key] > 1): return self.failHandshake('HTTP Origin header appears more than once in opening handshake request') self.websocket_origin = self.http_headers[websocket_origin_header_key].strip() try: origin_tuple = _url_to_origin(self.websocket_origin) except ValueError as e: return self.failHandshake('HTTP Origin header invalid: {}'.format(e)) have_origin = True else: have_origin = False if have_origin: if ((origin_tuple == 'null') and self.factory.allowNullOrigin): origin_is_allowed = True else: origin_is_allowed = _is_same_origin(origin_tuple, ('https' if self.factory.isSecure else 'http'), (self.factory.externalPort or self.factory.port), self.allowedOriginsPatterns) if (not origin_is_allowed): return self.failHandshake("WebSocket connection denied: origin '{0}' not allowed".format(self.websocket_origin)) if ('sec-websocket-key' not in self.http_headers): return self.failHandshake('HTTP Sec-WebSocket-Key header missing') if (http_headers_cnt['sec-websocket-key'] > 1): return self.failHandshake('HTTP Sec-WebSocket-Key header appears more than once in opening handshake request') key = self.http_headers['sec-websocket-key'].strip() if (len(key) != 24): return self.failHandshake(("bad Sec-WebSocket-Key (length must be 24 ASCII chars) '%s'" % key)) if (key[(-2):] != '=='): return self.failHandshake(("bad Sec-WebSocket-Key (invalid base64 encoding) '%s'" % key)) for c in key[:(-2)]: if (c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/'): return self.failHandshake(("bad character '%s' in Sec-WebSocket-Key (invalid base64 encoding) '%s'" % (c, key))) self.websocket_extensions = [] if ('sec-websocket-extensions' in self.http_headers): if (http_headers_cnt['sec-websocket-extensions'] > 1): return self.failHandshake('HTTP Sec-WebSocket-Extensions header appears more than once in opening handshake request') else: self.websocket_extensions = self._parseExtensionsHeader(self.http_headers['sec-websocket-extensions']) self.data = self.data[(end_of_header + 4):] self._wskey = key if ((self.maxConnections > 0) and (self.factory.countConnections > self.maxConnections)): self.failHandshake('maximum number of connections reached', code=503) else: request = ConnectionRequest(self.peer, self.http_headers, self.http_request_host, self.http_request_path, self.http_request_params, self.websocket_version, self.websocket_origin, self.websocket_protocols, self.websocket_extensions) f = txaio.as_future(self.onConnect, request) def forward_error(err): if isinstance(err.value, ConnectionDeny): self.failHandshake(err.value.reason, err.value.code) else: self.log.warn("Unexpected exception in onConnect ['{err.value}']", err=err) self.log.warn('{tb}', tb=txaio.failure_format_traceback(err)) return self.failHandshake('Internal server error: {}'.format(err.value), ConnectionDeny.INTERNAL_SERVER_ERROR) txaio.add_callbacks(f, self.succeedHandshake, forward_error) elif self.serveFlashSocketPolicy: flash_policy_file_request = self.data.find('<policy-file-request/>\x00') if (flash_policy_file_request >= 0): self.log.debug('received Flash Socket Policy File request') if self.serveFlashSocketPolicy: self.log.debug('sending Flash Socket Policy File :\n{policy}', policy=self.flashSocketPolicy) self.sendData(self.flashSocketPolicy.encode('utf8')) self.wasServingFlashSocketPolicyFile = True self.dropConnection() else: self.log.debug('No Flash Policy File served. You might want to serve a Flask Socket Policy file on the destination port since you received a request for it. See WebSocketServerFactory.serveFlashSocketPolicy and WebSocketServerFactory.flashSocketPolicy')