nmmo.render.websocket module#

class nmmo.render.websocket.Application(realm)#

Bases: object

kill()#
update(packet)#
class nmmo.render.websocket.GodswordServerProtocol#

Bases: WebSocketServerProtocol

CLOSE_STATUS_CODES_ALLOWED = [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013]#

Status codes allowed to send in 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_GOING_AWAY = 1001#

Going away.

CLOSE_STATUS_CODE_INTERNAL_ERROR = 1011#

The peer encountered an unexpected condition or internal error.

CLOSE_STATUS_CODE_INVALID_PAYLOAD = 1007#

Invalid frame payload data.

CLOSE_STATUS_CODE_MANDATORY_EXTENSION = 1010#

Mandatory extension.

CLOSE_STATUS_CODE_MESSAGE_TOO_BIG = 1009#

Message too big.

CLOSE_STATUS_CODE_NORMAL = 1000#

Normal close of connection.

CLOSE_STATUS_CODE_NULL = 1005#

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

CLOSE_STATUS_CODE_POLICY_VIOLATION = 1008#

Policy violation.

CLOSE_STATUS_CODE_PROTOCOL_ERROR = 1002#

Protocol error.

CLOSE_STATUS_CODE_RESERVED1 = 1004#

RESERVED

CLOSE_STATUS_CODE_SERVICE_RESTART = 1012#

Service restart.

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_CODE_TRY_AGAIN_LATER = 1013#

Try again later.

CLOSE_STATUS_CODE_UNASSIGNED1 = 1014#

Unassiged.

CLOSE_STATUS_CODE_UNSUPPORTED_DATA = 1003#

Unsupported data.

CONFIG_ATTRS = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask', 'maxFramePayloadSize', 'maxMessagePayloadSize', 'autoFragmentSize', 'failByDrop', 'echoCloseCodeReason', 'openHandshakeTimeout', 'closeHandshakeTimeout', 'tcpNoDelay', 'autoPingInterval', 'autoPingTimeout', 'autoPingSize', 'versions', 'webStatus', 'requireMaskedClientFrames', 'maskServerFrames', 'perMessageCompressionAccept', 'serveFlashSocketPolicy', 'flashSocketPolicy', 'allowedOrigins', 'allowedOriginsPatterns', 'allowNullOrigin', 'maxConnections', 'trustXForwardedFor']#
CONFIG_ATTRS_CLIENT = ['version', 'acceptMaskedServerFrames', 'maskClientFrames', 'serverConnectionDropTimeout', 'perMessageCompressionOffers', 'perMessageCompressionAccept']#

Configuration attributes specific to clients.

CONFIG_ATTRS_COMMON = ['logOctets', 'logFrames', 'trackTimings', 'utf8validateIncoming', 'applyMask', 'maxFramePayloadSize', 'maxMessagePayloadSize', 'autoFragmentSize', 'failByDrop', 'echoCloseCodeReason', 'openHandshakeTimeout', 'closeHandshakeTimeout', 'tcpNoDelay', 'autoPingInterval', 'autoPingTimeout', 'autoPingSize']#

Configuration attributes common to servers and clients.

CONFIG_ATTRS_SERVER = ['versions', 'webStatus', 'requireMaskedClientFrames', 'maskServerFrames', 'perMessageCompressionAccept', 'serveFlashSocketPolicy', 'flashSocketPolicy', 'allowedOrigins', 'allowedOriginsPatterns', 'allowNullOrigin', 'maxConnections', 'trustXForwardedFor']#

Configuration attributes specific to servers.

DEFAULT_SPEC_VERSION = 18#

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

MESSAGE_TYPE_BINARY = 2#

WebSocket binary message type (arbitrary binary payload).

MESSAGE_TYPE_TEXT = 1#

WebSocket text message type (UTF-8 payload).

PROTOCOL_TO_SPEC_VERSION = {8: 12, 13: 18}#

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

SEND_STATE_GROUND = 0#
SEND_STATE_INSIDE_MESSAGE = 2#
SEND_STATE_INSIDE_MESSAGE_FRAME = 3#
SEND_STATE_MESSAGE_BEGIN = 1#
SPEC_TO_PROTOCOL_VERSION = {10: 8, 11: 8, 12: 8, 13: 13, 14: 13, 15: 13, 16: 13, 17: 13, 18: 13}#

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

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

WebSocket protocol versions supported by this implementation.

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

beginMessage(isBinary=False, doNotCompress=False)#

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

beginMessageFrame(length)#

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

connected = 0#
connectionLost(reason)#

Called when the connection is shut down.

Clear any circular references here, and any external references to this Protocol. The connection has been closed.

@type reason: L{twisted.python.failure.Failure}

connectionMade()#

Called when a connection is made.

This may be considered the initializer of the protocol, because it is called when the connection is completed. For clients, this is called once the connection to the server has been established; for servers, this is called after an accept() call stops blocking and a socket has been received. If you need to send any greeting or initial message, do it here.

consumeData()#

Consume buffered (incoming) data.

dataReceived(data)#

Called whenever data is received.

Use this method to translate to a higher-level message. Usually, some callback will be made upon the receipt of each complete protocol message.

@param data: a string of indeterminate length. Please keep in mind

that you will probably need to buffer some data, as partial (or multiple) protocol messages may be received! I recommend that unit tests for protocols call through to this method with differing chunk sizes, down to one byte at a time.

dropConnection(abort=False)#

Drop the underlying TCP connection.

endMessage()#

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

failHandshake(reason, code=400, responseHeaders=None)#

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

get_channel_id(channel_id_type='tls-unique')#

Implements autobahn.wamp.interfaces.ITransport.get_channel_id()

is_closed#

a Future/Deferred that fires when we hit STATE_CLOSED

log#
logPrefix()#

Return a prefix matching the class name, to identify log messages related to this protocol instance.

logRxFrame(frameHeader, payload)#

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

logRxOctets(data)#

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

logTxFrame(frameHeader, payload, repeatLength, chopsize, sync)#

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

logTxOctets(data, sync)#

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

makeConnection(transport)#

Make a connection to a transport and a server.

This sets the ‘transport’ attribute of this Protocol, and calls the connectionMade() callback.

onAutoPingTimeout()#

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

onClose(wasClean, code=None, reason=None)#

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

onCloseFrame(code, reasonRaw)#

Callback when a Close frame was received. The default implementation answers by sending a Close when no Close was sent before. Otherwise it drops the TCP connection either immediately (when we are a server) or after a timeout (when we are a client and expect the server to drop the TCP).

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

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.

onConnect(request)#

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 (instance of autobahn.websocket.protocol.ConnectionRequest) – WebSocket connection request information.

onFrameBegin()#

Begin of receive new frame.

onFrameData(payload)#

New data received within frame.

onFrameEnd()#

End of frame received.

onMessage(packet, isBinary)#

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

onMessageBegin(isBinary)#

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

onMessageEnd()#

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

onMessageFrame(payload)#

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

onMessageFrameBegin(length)#

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

onMessageFrameData(payload)#

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

onMessageFrameEnd()#

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

onOpen()#

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

onOpenHandshakeTimeout()#

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

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

onPong(payload)#

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

onServerConnectionDropTimeout()#

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>'#
processControlFrame()#

Process a completely received control frame.

processData()#

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

processHandshake()#

Process WebSocket opening handshake request from client.

processProxyConnect()#

Process proxy connect.

registerProducer(producer, streaming)#

Register a Twisted producer with this protocol.

Parameters:
  • producer (object) – A Twisted push or pull producer.

  • streaming (bool) – Producer type.

sendClose(code=None, reason=None)#

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

sendCloseFrame(code=None, reasonUtf8=None, isReply=False)#

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

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

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.

sendHtml(html)#

Send HTML page HTTP response.

sendHttpErrorResponse(code, reason, responseHeaders=None)#

Send out HTTP error response.

sendMessage(payload, isBinary=False, fragmentSize=None, sync=False, doNotCompress=False)#

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

sendMessageFrame(payload, sync=False)#

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

sendMessageFrameData(payload, sync=False)#

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

sendPing(payload=None)#

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

sendPong(payload=None)#

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

sendPreparedMessage(preparedMsg)#

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

sendRedirect(url)#

Send HTTP Redirect (303) response.

sendServerStatus(redirectUrl=None, redirectAfter=0)#

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

sendUpdate(data)#
serverPacket()#
setTrackTimings(enable)#

Enable/disable tracking of detailed timings.

Parameters:

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

succeedHandshake(res)#

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

transport = None#
unregisterProducer()#

Unregister Twisted producer with this protocol.

class nmmo.render.websocket.WSServerFactory(ip, realm)#

Bases: WebSocketServerFactory

buildProtocol(addr)#

Create an instance of a subclass of Protocol.

The returned instance will handle input on an incoming server connection, and an attribute “factory” pointing to the creating factory.

Alternatively, L{None} may be returned to immediately close the new connection.

Override this method to alter how Protocol instances get created.

@param addr: an object implementing L{twisted.internet.interfaces.IAddress}

clientConnectionLost(client)#
clientConnectionMade(client)#
doStart()#

Make sure startFactory is called.

Users should not call this function themselves!

doStop()#

Make sure stopFactory is called.

Users should not call this function themselves!

classmethod forProtocol(protocol, *args, **kwargs)#

Create a factory for the given protocol.

It sets the C{protocol} attribute and returns the constructed factory instance.

@param protocol: A L{Protocol} subclass

@param args: Positional arguments for the factory.

@param kwargs: Keyword arguments for the factory.

@return: A L{Factory} instance wired up to C{protocol}.

getConnectionCount()#

Get number of currently connected clients.

Returns:

int – Number of currently connected clients.

isServer = True#

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

log#
logPrefix()#

Describe this factory for log messages.

noisy = True#
numPorts = 0#
prepareMessage(payload, isBinary=False, doNotCompress=False)#

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.

protocol#

alias of WebSocketServerProtocol

resetProtocolOptions()#

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, serveFlashSocketPolicy=None, flashSocketPolicy=None, allowedOrigins=None, allowNullOrigin=False, maxConnections=None, trustXForwardedFor=None)#

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

setSessionParameters(url=None, protocols=None, server=None, headers=None, externalPort=None)#

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

startFactory()#

This will be called before I begin listening on a Port or Connector.

It will only be called once, even if the factory is connected to multiple ports.

This can be used to perform ‘unserialization’ tasks that are best put off until things are actually running, such as connecting to a database, opening files, etcetera.

stopFactory()#

This will be called before I stop listening on all Ports/Connectors.

This can be overridden to perform ‘shutdown’ tasks such as disconnecting database connections, closing files, etc.

It will be called, for example, before an application shuts down, if it was connected to a port. User code should not call this function directly.

update(packet)#