autobahn.websocket.protocol

Classes

WebSocketClientFactory

A protocol factory for WebSocket clients.

WebSocketClientProtocol

Protocol base class for WebSocket clients.

WebSocketFactory

Mixin for

WebSocketProtocol

Protocol base class for WebSocket.

WebSocketServerFactory

A protocol factory for WebSocket servers.

WebSocketServerProtocol

Protocol base class for WebSocket servers.

Module Contents

class 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()

_batched_timer[source]
isServer = False[source]

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

logFrames = False[source]
logOctets = False[source]
protocol[source]

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

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

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

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

trackTimings = False[source]
class WebSocketClientProtocol[source]

Bases: WebSocketProtocol

Protocol base class for WebSocket clients.

CONFIG_ATTRS = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask',...[source]
_actuallyStartHandshake(request_options)[source]

Internal helper.

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

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

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

failHandshake(reason)[source]

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

failProxyConnect(reason)[source]

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

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.

onConnecting(transport_details: autobahn.wamp.types.TransportDetails) autobahn.websocket.types.ConnectingRequest | None[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).

processHandshake()[source]

Process WebSocket opening handshake response from server.

processProxyConnect()[source]

Process HTTP/CONNECT response from server.

startHandshake()[source]

Start WebSocket opening handshake.

startProxyConnect()[source]

Connect to explicit proxy.

class 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:

An instance of autobahn.websocket.protocol.PreparedMessage.

class WebSocketProtocol[source]

Bases: autobahn.util.ObservableMixin

Protocol base class for WebSocket.

This class implements:

CLOSE_STATUS_CODES_ALLOWED[source]

Status codes allowed to send in close.

CLOSE_STATUS_CODE_ABNORMAL_CLOSE = 1006[source]

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

CLOSE_STATUS_CODE_GOING_AWAY = 1001[source]

Going away.

CLOSE_STATUS_CODE_INTERNAL_ERROR = 1011[source]

The peer encountered an unexpected condition or internal error.

CLOSE_STATUS_CODE_INVALID_PAYLOAD = 1007[source]

Invalid frame payload data.

CLOSE_STATUS_CODE_MANDATORY_EXTENSION = 1010[source]

Mandatory extension.

CLOSE_STATUS_CODE_MESSAGE_TOO_BIG = 1009[source]

Message too big.

CLOSE_STATUS_CODE_NORMAL = 1000[source]

Normal close of connection.

CLOSE_STATUS_CODE_NULL = 1005[source]

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

CLOSE_STATUS_CODE_POLICY_VIOLATION = 1008[source]

Policy violation.

CLOSE_STATUS_CODE_PROTOCOL_ERROR = 1002[source]

Protocol error.

CLOSE_STATUS_CODE_RESERVED1 = 1004[source]

RESERVED

CLOSE_STATUS_CODE_SERVICE_RESTART = 1012[source]

Service restart.

CLOSE_STATUS_CODE_TLS_HANDSHAKE_FAILED = 1015[source]

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

CLOSE_STATUS_CODE_TRY_AGAIN_LATER = 1013[source]

Try again later.

CLOSE_STATUS_CODE_UNASSIGNED1 = 1014[source]

Unassiged.

CLOSE_STATUS_CODE_UNSUPPORTED_DATA = 1003[source]

Unsupported data.

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

Configuration attributes specific to clients.

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

Configuration attributes common to servers and clients.

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

Configuration attributes specific to servers.

DEFAULT_SPEC_VERSION = 18[source]

final RFC6455.

Type:

Default WebSocket protocol spec version this implementation speaks

MESSAGE_TYPE_BINARY = 2[source]

WebSocket binary message type (arbitrary binary payload).

MESSAGE_TYPE_TEXT = 1[source]

WebSocket text message type (UTF-8 payload).

PROTOCOL_TO_SPEC_VERSION[source]

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

SEND_STATE_GROUND = 0[source]
SEND_STATE_INSIDE_MESSAGE = 2[source]
SEND_STATE_INSIDE_MESSAGE_FRAME = 3[source]
SEND_STATE_MESSAGE_BEGIN = 1[source]
SPEC_TO_PROTOCOL_VERSION[source]

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

STATE_CLOSED = 0[source]
STATE_CLOSING = 2[source]
STATE_CONNECTING = 1[source]
STATE_OPEN = 3[source]
STATE_PROXY_CONNECTING = 4[source]
SUPPORTED_PROTOCOL_VERSIONS = [8, 13][source]

WebSocket protocol versions supported by this implementation.

SUPPORTED_SPEC_VERSIONS = [10, 11, 12, 13, 14, 15, 16, 17, 18][source]

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

_QUEUED_WRITE_DELAY = 1e-05[source]

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

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

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

_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

_connectionLost(reason)[source]

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

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

_dataReceived(data)[source]

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

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

Fails the WebSocket connection.

_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:

True, when any further processing should be discontinued.

_max_message_size_exceeded(msg_size, max_msg_size, reason)[source]
_parseExtensionsHeader(header, removeQuotes=True)[source]

Parse the Sec-WebSocket-Extensions header.

_protocol_violation(reason)[source]

Fired when a WebSocket protocol violation/error occurs.

Parameters:

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

Returns:

True, when any further processing should be discontinued.

_send()[source]

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

_sendAutoPing()[source]
_transport_details: autobahn.wamp.types.TransportDetails | None[source]
_trigger()[source]

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

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

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

beginMessageFrame(length)[source]

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

consumeData()[source]

Consume buffered (incoming) data.

dropConnection(abort=False)[source]

Drop the underlying TCP connection.

endMessage()[source]

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

is_closed[source]
is_open[source]
logRxFrame(frameHeader, payload)[source]

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

logRxOctets(data)[source]

Hook fired right after raw octets have been received, but only when self.logOctets == 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.

logTxOctets(data, sync)[source]

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

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.

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

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

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.

onFrameBegin()[source]

Begin of receive new frame.

onFrameData(payload)[source]

New data received within frame.

onFrameEnd()[source]

End of frame received.

onMessage(payload, isBinary)[source]

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

onMessageBegin(isBinary)[source]

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

onMessageEnd()[source]

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

onMessageFrame(payload)[source]

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

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

onOpen()[source]

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

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.

onPing(payload)[source]

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

onPong(payload)[source]

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

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.

peer = '<never connected>'[source]
processControlFrame()[source]

Process a completely received control frame.

processData()[source]

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

processHandshake()[source]

Process WebSocket handshake.

processProxyConnect()[source]

Process proxy connect.

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

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

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.

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.

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.

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

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

sendMessageFrame(payload, sync=False)[source]

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

sendMessageFrameData(payload, sync=False)[source]

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

sendPing(payload=None)[source]

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

sendPong(payload=None)[source]

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

sendPreparedMessage(preparedMsg)[source]

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

setTrackTimings(enable)[source]

Enable/disable tracking of detailed timings.

Parameters:

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

property transport_details: autobahn.wamp.types.TransportDetails | None[source]

Implements autobahn.wamp.interfaces.ITransport.transport_details.

class 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()

_batched_timer[source]
countConnections = 0[source]
getConnectionCount()[source]

Get number of currently connected clients.

Returns:

Number of currently connected clients.

isServer = True[source]

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

logFrames = False[source]
logOctets = False[source]
protocol[source]

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

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

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

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

trackTimings = False[source]
class WebSocketServerProtocol[source]

Bases: WebSocketProtocol

Protocol base class for WebSocket servers.

CONFIG_ATTRS = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask',...[source]
_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.

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

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.

onConnect(request: autobahn.websocket.types.ConnectionRequest) str | None | Tuple[str | None, 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.

processHandshake()[source]

Process WebSocket opening handshake request from client.

processProxyConnect()[source]

Process proxy connect.

sendHtml(html)[source]

Send HTML page HTTP response.

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

Send out HTTP error 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).

succeedHandshake(res)[source]

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