autobahn.websocket.protocol


Module Contents

Classes

WebSocketProtocol

Protocol base class for WebSocket.

WebSocketFactory

Mixin for

WebSocketServerProtocol

Protocol base class for WebSocket servers.

WebSocketServerFactory

A protocol factory for WebSocket servers.

WebSocketClientProtocol

Protocol base class for WebSocket clients.

WebSocketClientFactory

A protocol factory for WebSocket clients.

class autobahn.websocket.protocol.WebSocketProtocol[source]

Bases: autobahn.util.ObservableMixin

Protocol base class for WebSocket.

This class implements:

property transport_details: Optional[autobahn.wamp.types.TransportDetails]

Implements autobahn.wamp.interfaces.ITransport.transport_details.

peer = <never connected>
SUPPORTED_SPEC_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18]

WebSocket protocol spec (draft) versions supported by this implementation. Use of version 18 indicates RFC6455. Use of versions < 18 indicate actual draft spec versions (Hybi-Drafts).

SUPPORTED_PROTOCOL_VERSIONS = [8, 13]

WebSocket protocol versions supported by this implementation.

SPEC_TO_PROTOCOL_VERSION

Mapping from protocol spec (draft) version to protocol version.

PROTOCOL_TO_SPEC_VERSION

Mapping from protocol version to the latest protocol spec (draft) version using that protocol version.

DEFAULT_SPEC_VERSION = 18

Default WebSocket protocol spec version this implementation speaks: final RFC6455.

_WS_MAGIC = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

Protocol defined magic used during WebSocket handshake (used in Hybi-drafts and final RFC6455.

_QUEUED_WRITE_DELAY = 1e-05

For synched/chopped writes, this is the reactor reentry delay in seconds.

MESSAGE_TYPE_TEXT = 1

WebSocket text message type (UTF-8 payload).

MESSAGE_TYPE_BINARY = 2

WebSocket binary message type (arbitrary binary payload).

STATE_CLOSED = 0
STATE_CONNECTING = 1
STATE_CLOSING = 2
STATE_OPEN = 3
STATE_PROXY_CONNECTING = 4
SEND_STATE_GROUND = 0
SEND_STATE_MESSAGE_BEGIN = 1
SEND_STATE_INSIDE_MESSAGE = 2
SEND_STATE_INSIDE_MESSAGE_FRAME = 3
CLOSE_STATUS_CODE_NORMAL = 1000

Normal close of connection.

CLOSE_STATUS_CODE_GOING_AWAY = 1001

Going away.

CLOSE_STATUS_CODE_PROTOCOL_ERROR = 1002

Protocol error.

CLOSE_STATUS_CODE_UNSUPPORTED_DATA = 1003

Unsupported data.

CLOSE_STATUS_CODE_RESERVED1 = 1004

RESERVED

CLOSE_STATUS_CODE_NULL = 1005

No status received. (MUST NOT be used as status code when sending a close).

CLOSE_STATUS_CODE_ABNORMAL_CLOSE = 1006

Abnormal close of connection. (MUST NOT be used as status code when sending a close).

CLOSE_STATUS_CODE_INVALID_PAYLOAD = 1007

Invalid frame payload data.

CLOSE_STATUS_CODE_POLICY_VIOLATION = 1008

Policy violation.

CLOSE_STATUS_CODE_MESSAGE_TOO_BIG = 1009

Message too big.

CLOSE_STATUS_CODE_MANDATORY_EXTENSION = 1010

Mandatory extension.

CLOSE_STATUS_CODE_INTERNAL_ERROR = 1011

The peer encountered an unexpected condition or internal error.

CLOSE_STATUS_CODE_SERVICE_RESTART = 1012

Service restart.

CLOSE_STATUS_CODE_TRY_AGAIN_LATER = 1013

Try again later.

CLOSE_STATUS_CODE_UNASSIGNED1 = 1014

Unassiged.

CLOSE_STATUS_CODE_TLS_HANDSHAKE_FAILED = 1015

TLS handshake failed, i.e. server certificate could not be verified. (MUST NOT be used as status code when sending a close).

CLOSE_STATUS_CODES_ALLOWED

Status codes allowed to send in close.

CONFIG_ATTRS_COMMON = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask',...

Configuration attributes common to servers and clients.

CONFIG_ATTRS_SERVER = ['versions', 'webStatus', 'requireMaskedClientFrames', 'maskServerFrames',...

Configuration attributes specific to servers.

CONFIG_ATTRS_CLIENT = ['version', 'acceptMaskedServerFrames', 'maskClientFrames', 'serverConnectionDropTimeout',...

Configuration attributes specific to clients.

onOpen()[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onOpen()

onMessageBegin(isBinary)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessageBegin()

onMessageFrameBegin(length)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameBegin()

onMessageFrameData(payload)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameData()

onMessageFrameEnd()[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrameEnd()

onMessageFrame(payload)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessageFrame()

onMessageEnd()[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessageEnd()

onMessage(payload, isBinary)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onMessage()

onPing(payload)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onPing()

onPong(payload)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onPong()

onClose(wasClean, code, reason)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.onClose()

onCloseFrame(code, reasonRaw)[source]

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).

Parameters
  • code (int) – Close status code, if there was one (WebSocketProtocol.CLOSE_STATUS_CODE_*).

  • reasonRaw (bytes) – Close reason (when present, a status code MUST have been also be present).

onServerConnectionDropTimeout()[source]

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.

onOpenHandshakeTimeout()[source]

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.

onCloseHandshakeTimeout()[source]

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.

onAutoPong(ping_sent, ping_seq, pong_received, pong_rtt, payload)[source]

When doing automatic ping/pongs, this is called upon a successful pong.

Parameters
  • ping_sent – Posix time in ns when ping was sent.

  • ping_seq – Sequence number of ping that was sent.

  • pong_received – Posix time in ns when pong was received.

  • pong_rtt – Pong roundtrip-time in ms measured.

  • payload – The complete WebSocket ping/pong message payload (ping_sent 8 bytes big-endian | ping_seq 4 bytes big endian | max. 113 optional random bytes).

onAutoPingTimeout()[source]

When doing automatic ping/pongs to detect broken connection, the peer did not reply in time to our ping. We drop the connection.

dropConnection(abort=False)[source]

Drop the underlying TCP connection.

_max_message_size_exceeded(msg_size, max_msg_size, reason)[source]
_fail_connection(code=CLOSE_STATUS_CODE_GOING_AWAY, reason='going away')[source]

Fails the WebSocket connection.

_protocol_violation(reason)[source]

Fired when a WebSocket protocol violation/error occurs.

Parameters

reason (str) – Protocol violation that was encountered (human readable).

Returns

bool – True, when any further processing should be discontinued.

_invalid_payload(reason)[source]

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.

Parameters

reason (str) – What was invalid for the payload (human readable).

Returns

bool – True, when any further processing should be discontinued.

setTrackTimings(enable)[source]

Enable/disable tracking of detailed timings.

Parameters

enable (bool) – Turn time tracking on/off.

_connectionMade()[source]

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).

_connectionLost(reason)[source]

This is called by network framework when a transport connection was lost.

logRxOctets(data)[source]

Hook fired right after raw octets have been received, but only when self.logOctets == True.

logTxOctets(data, sync)[source]

Hook fired right after raw octets have been sent, but only when self.logOctets == True.

logRxFrame(frameHeader, payload)[source]

Hook fired right after WebSocket frame has been received and decoded, but only when self.logFrames == True.

logTxFrame(frameHeader, payload, repeatLength, chopsize, sync)[source]

Hook fired right after WebSocket frame has been encoded and sent, but only when self.logFrames == True.

_dataReceived(data)[source]

This is called by network framework upon receiving data on transport connection.

consumeData()[source]

Consume buffered (incoming) data.

processProxyConnect()[source]

Process proxy connect.

processHandshake()[source]

Process WebSocket handshake.

_trigger()[source]

Trigger sending stuff from send queue (which is only used for chopped/synched writes).

_send()[source]

Send out stuff from send queue. For details how this works, see test/trickling in the repo.

sendData(data, sync=False, chopsize=None)[source]

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.

sendPreparedMessage(preparedMsg)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendPreparedMessage()

processData()[source]

After WebSocket handshake has been completed, this procedure will do all subsequent processing of incoming bytes.

onFrameBegin()[source]

Begin of receive new frame.

onFrameData(payload)[source]

New data received within frame.

onFrameEnd()[source]

End of frame received.

processControlFrame()[source]

Process a completely received control frame.

sendFrame(opcode, payload=b'', fin=True, rsv=0, mask=None, payload_len=None, chopsize=None, sync=False)[source]

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.

sendPing(payload=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendPing()

_sendAutoPing()[source]
_cancelAutoPingTimeoutCall()[source]

When data is received from client, use it in leu of timely PONG response - cancel pending timeout call that will drop connection. See https://github.com/crossbario/autobahn-python/issues/1327

sendPong(payload=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendPong()

sendCloseFrame(code=None, reasonUtf8=None, isReply=False)[source]

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.

sendClose(code=None, reason=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendClose()

beginMessage(isBinary=False, doNotCompress=False)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.beginMessage()

beginMessageFrame(length)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.beginMessageFrame()

sendMessageFrameData(payload, sync=False)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendMessageFrameData()

endMessage()[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.endMessage()

sendMessageFrame(payload, sync=False)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendMessageFrame()

sendMessage(payload, isBinary=False, fragmentSize=None, sync=False, doNotCompress=False)[source]

Implements autobahn.websocket.interfaces.IWebSocketChannel.sendMessage()

_parseExtensionsHeader(header, removeQuotes=True)[source]

Parse the Sec-WebSocket-Extensions header.

class autobahn.websocket.protocol.WebSocketFactory[source]

Bases: object

Mixin for autobahn.websocket.protocol.WebSocketClientFactory and autobahn.websocket.protocol.WebSocketServerFactory.

prepareMessage(payload, isBinary=False, doNotCompress=False)[source]

Prepare a WebSocket message. This can be later sent on multiple instances of autobahn.websocket.WebSocketProtocol using 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.

Parameters
  • payload (bytes) – The message payload.

  • isBinary (bool) – True iff payload is binary, else the payload must be UTF-8 encoded text.

  • doNotCompress (bool) – 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).

Returns

obj – An instance of autobahn.websocket.protocol.PreparedMessage.

class autobahn.websocket.protocol.WebSocketServerProtocol[source]

Bases: WebSocketProtocol

Protocol base class for WebSocket servers.

CONFIG_ATTRS
onConnect(request: autobahn.websocket.types.ConnectionRequest) Union[Optional[str], Tuple[Optional[str], Dict[str, str]]][source]

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 autobahn.websocket.types.ConnectionDeny when you don’t want to accept the WebSocket connection request.

Parameters

request – WebSocket connection request information.

Returns

You may return one of:
  • None: the connection is accepted with no specific WebSocket subprotocol,

  • str: the connection is accepted with the returned name as the WebSocket subprotocol, or

  • (str, dict): a pair of subprotocol accepted and HTTP headers to send to the client.

You can also return a Deferred/Future that resolves/rejects to the above.

_connectionMade()[source]

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.

_connectionLost(reason)[source]

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.

processProxyConnect()[source]

Process proxy connect.

processHandshake()[source]

Process WebSocket opening handshake request from client.

succeedHandshake(res)[source]

Callback after onConnect() returns successfully. Generates the response for the handshake.

failHandshake(reason, code=400, responseHeaders=None)[source]

During opening handshake the client request was invalid, we send a HTTP error response and then drop the connection.

sendHttpErrorResponse(code, reason, responseHeaders=None)[source]

Send out HTTP error response.

sendHtml(html)[source]

Send HTML page HTTP response.

sendRedirect(url)[source]

Send HTTP Redirect (303) response.

sendServerStatus(redirectUrl=None, redirectAfter=0)[source]

Used to send out server status/version upon receiving a HTTP/GET without upgrade to WebSocket header (and option serverStatus is True).

class autobahn.websocket.protocol.WebSocketServerFactory(url=None, protocols=None, server='AutobahnPython/{}'.format(__version__), headers=None, externalPort=None)[source]

Bases: WebSocketFactory

A protocol factory for WebSocket servers.

Implements autobahn.websocket.interfaces.IWebSocketServerChannelFactory()

protocol

The protocol to be spoken. Must be derived from autobahn.websocket.protocol.WebSocketServerProtocol.

isServer = True

Flag indicating if this factory is client- or server-side.

setSessionParameters(url=None, protocols=None, server=None, headers=None, externalPort=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketServerChannelFactory.setSessionParameters()

resetProtocolOptions()[source]

Implements autobahn.websocket.interfaces.IWebSocketServerChannelFactory.resetProtocolOptions()

setProtocolOptions(versions=None, webStatus=None, utf8validateIncoming=None, maskServerFrames=None, requireMaskedClientFrames=None, applyMask=None, maxFramePayloadSize=None, maxMessagePayloadSize=None, autoFragmentSize=None, failByDrop=None, echoCloseCodeReason=None, openHandshakeTimeout=None, closeHandshakeTimeout=None, tcpNoDelay=None, perMessageCompressionAccept=None, autoPingInterval=None, autoPingTimeout=None, autoPingSize=None, autoPingRestartOnAnyTraffic=None, serveFlashSocketPolicy=None, flashSocketPolicy=None, allowedOrigins=None, allowNullOrigin=False, maxConnections=None, trustXForwardedFor=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketServerChannelFactory.setProtocolOptions()

getConnectionCount()[source]

Get number of currently connected clients.

Returns

int – Number of currently connected clients.

class autobahn.websocket.protocol.WebSocketClientProtocol[source]

Bases: WebSocketProtocol

Protocol base class for WebSocket clients.

CONFIG_ATTRS
onConnecting(transport_details: autobahn.wamp.types.TransportDetails) Optional[autobahn.websocket.types.ConnectingRequest][source]

Callback fired after the connection is established, but before the handshake has started. This may return a autobahn.websocket.types.ConnectingRequest instance (or a future which resolves to one) to control aspects of the handshake (or None for defaults)

Parameters

transport_details – Details of the transport underlying the WebSocket connection being established.

Returns

A autobahn.websocket.types.ConnectingRequest instance is returned to indicate which options should be used for this connection. If you wish to use the default behavior, None may be returned (this is the default).

onConnect(response: autobahn.websocket.types.ConnectionResponse) NoneType[source]

Callback fired directly after WebSocket opening handshake when new WebSocket connection was established from the client to a server.

Parameters

response – WebSocket connection response information sent by server.

_connectionMade()[source]

Called by network framework when new transport connection to server was established. Default implementation will start the initial WebSocket opening handshake (or proxy connect). When overriding in derived class, make sure to call this base class implementation _before_ your code.

_connectionLost(reason)[source]

Called by network framework when established transport connection to server 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.

startProxyConnect()[source]

Connect to explicit proxy.

processProxyConnect()[source]

Process HTTP/CONNECT response from server.

failProxyConnect(reason)[source]

During initial explicit proxy connect, the server response indicates some failure and we drop the connection.

startHandshake()[source]

Start WebSocket opening handshake.

_actuallyStartHandshake(request_options)[source]

Internal helper.

Actually send the WebSocket opening handshake after receiving valid request options.

processHandshake()[source]

Process WebSocket opening handshake response from server.

failHandshake(reason)[source]

During opening handshake the server response is invalid and we drop the connection.

class autobahn.websocket.protocol.WebSocketClientFactory(url=None, origin=None, protocols=None, useragent='AutobahnPython/{}'.format(__version__), headers=None, proxy=None)[source]

Bases: WebSocketFactory

A protocol factory for WebSocket clients.

Implements autobahn.websocket.interfaces.IWebSocketClientChannelFactory()

protocol

The protocol to be spoken. Must be derived from autobahn.websocket.protocol.WebSocketClientProtocol.

isServer = False

Flag indicating if this factory is client- or server-side.

setSessionParameters(url=None, origin=None, protocols=None, useragent=None, headers=None, proxy=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketClientChannelFactory.setSessionParameters()

resetProtocolOptions()[source]

Implements autobahn.websocket.interfaces.IWebSocketClientChannelFactory.resetProtocolOptions()

setProtocolOptions(version=None, utf8validateIncoming=None, acceptMaskedServerFrames=None, maskClientFrames=None, applyMask=None, maxFramePayloadSize=None, maxMessagePayloadSize=None, autoFragmentSize=None, failByDrop=None, echoCloseCodeReason=None, serverConnectionDropTimeout=None, openHandshakeTimeout=None, closeHandshakeTimeout=None, tcpNoDelay=None, perMessageCompressionOffers=None, perMessageCompressionAccept=None, autoPingInterval=None, autoPingTimeout=None, autoPingSize=None, autoPingRestartOnAnyTraffic=None)[source]

Implements autobahn.websocket.interfaces.IWebSocketClientChannelFactory.setProtocolOptions()