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.excl...
':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.i...
'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'forc...
':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 call...
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) == s...
':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...
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 =...
':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: callab...
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: ...
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: boo...
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 * 1...
'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 s...
'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._p...
'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 :r...
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 * 10000...
'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.CL...
'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(WebSocke...
'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,...
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)): ...
'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.wasServerConnectionDropT...
'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 ...
'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.wasCloseHandshakeTim...
'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={ab...
'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 ...
'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 ...
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__ ...
'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.serverConnectionDropTimeoutCa...
'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.opcod...
'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...
'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...
'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...
'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 ...
'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 fragm...
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....
'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_opco...
'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 ...
'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)) payl...
'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.log...
'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): reasonRa...
'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...
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 /...
'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) ...
'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) ...
'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.st...
'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 c...
'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...
'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.sen...
'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): ...
'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)...
'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._perMes...
'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:]: ...
'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 doNotCompr...
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 =...
'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 th...
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....
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_...