stream_writer

Module provides TelnetWriter and TelnetWriterUnicode.

class TelnetWriter(transport, protocol, *, client=False, server=False, reader=None)[source]

Telnet IAC Interpreter implementing the telnet protocol.

A copy of asyncio.StreamWriter with IAC interpretation.

Initialize TelnetWriter.

Almost all negotiation actions are performed through the writer interface, as any action requires writing bytes to the underling stream. This class implements feed_byte(), which acts as a Telnet Is-A-Command (IAC) interpreter.

The significance of the last byte passed to this method is tested by instance attribute is_oob, following the call to feed_byte() to determine whether the given byte is in or out of band.

A minimal Telnet Protocol method, asyncio.Protocol.data_received(), should forward each byte to feed_byte(), which returns True to indicate the given byte should be forwarded to a Protocol reader method.

Parameters:
  • client (bool) – Whether the IAC interpreter should react from the client point of view.

  • server (bool) – Whether the IAC interpreter should react from the server point of view.

byte_count = 0

Total bytes sent to feed_byte()

lflow = True

Whether flow control is enabled.

xon_any = False

Whether flow control enabled by Transmit-Off (XOFF) (Ctrl-s), should re-enable Transmit-On (XON) only on receipt of XON (Ctrl-q). When False, any keypress from client re-enables transmission.

iac_received = None

Whether the last byte received by feed_byte() is the beginning of an IAC command.

cmd_received: bytes | tuple[bytes, bytes] | bool | None = None

Whether the last byte received by feed_byte() begins an IAC command sequence.

slc_received = None

Whether the last byte received by feed_byte() is a matching special line character value, if negotiated.

slc_simulated = True

SLC function values and callbacks are fired for clients in Kludge mode not otherwise capable of negotiating LINEMODE, providing transport remote editing function callbacks for dumb clients.

default_linemode = <b'\x10': lit_echo:True, soft_tab:False, ack:False, trapsig:False, remote:True, local:False>

Initial line mode requested by server if client supports LINEMODE negotiation (remote line editing and literal echo of control chars)

pending_option

Dictionary of telnet option byte(s) that follow an IAC-DO or IAC-DONT command, and contains a value of True until IAC-WILL or IAC-WONT has been received by remote end.

local_option

Dictionary of telnet option byte(s) that follow an IAC-WILL or IAC-WONT command, sent by our end, indicating state of local capabilities.

remote_option

Dictionary of telnet option byte(s) that follow an IAC-WILL or IAC-WONT command received by remote end, indicating state of remote capabilities.

environ_encoding: str

Encoding used for NEW_ENVIRON variable names and values. Default "ascii" per RFC 1572; set to "cp037" for EBCDIC hosts such as IBM OS/400.

always_will: set[bytes]

Set of option byte(s) for which the client always sends WILL (even when not natively supported). Overrides the default WONT rejection in handle_do().

always_do: set[bytes]

Set of option byte(s) for which the client always sends DO (even when not natively supported). Overrides the default DONT rejection in handle_will().

always_wont: set[bytes]

Set of option byte(s) for which the client always sends WONT in response to DO, refusing the option even when natively supported. Overrides the default WILL in handle_do().

always_dont: set[bytes]

Set of option byte(s) for which the client always sends DONT in response to WILL, refusing the option even when natively supported. Overrides the default DO in handle_will().

passive_do: set[bytes]

Set of option byte(s) for which the client sends DO only in response to a server WILL (passive negotiation).

ctx: TelnetSessionContext

Per-connection session context. Applications may replace this with a subclass of TelnetSessionContext to carry additional state (e.g. MUD client macros, room graphs).

rejected_will: set[bytes]

Set of option byte(s) for WILL received from remote end that were rejected with DONT (unhandled options).

rejected_do: set[bytes]

Set of option byte(s) for DO received from remote end that were rejected with WONT (unsupported options).

directional_refusals: set[bytes]

Set of option byte(s) refused due to directional mismatch (e.g. WILL NAWS on client end, DO TTYPE on server end).

environ_send_raw: bytes | None

Raw bytes of the last NEW_ENVIRON SEND payload, captured for fingerprinting. None if no SEND was received.

mssp_data: dict[str, str | list[str]] | None

Decoded MSSP variables received via subnegotiation. None until a SB MSSP payload is received and decoded.

zmp_data: list[list[str]]

Accumulated ZMP messages (list of [command, arg, …] lists). Empty until SB ZMP payloads are received and decoded.

atcp_data: list[tuple[str, str]]

Accumulated ATCP messages (list of (package, value) tuples). Empty until SB ATCP payloads are received and decoded.

aardwolf_data: list[dict[str, Any]]

Accumulated Aardwolf messages (list of decoded dicts). Empty until SB AARDWOLF payloads are received and decoded.

mxp_data: list[bytes]

Accumulated MXP subnegotiation payloads (list of raw bytes). Empty until SB MXP payloads are received. An empty payload (b"") signals MXP mode activation.

comport_data: dict[str, Any] | None

COM-PORT-OPTION (RFC 2217) data received via subnegotiation. None until an SB COM-PORT-OPTION payload is received.

compression: bool | None

Compression policy: None = passively accept (default), True = actively request, False = reject.

mccp2_active: bool

Whether MCCP2 compression is currently active (server→client).

mccp3_active: bool

Whether MCCP3 compression is currently active (client→server).

slctab

SLC Tab (SLC Functions and their support level, and ascii value)

property connection_closed: bool

Return True if connection has been closed.

property transport: BaseTransport | None

Return the underlying transport.

close()[source]

Close the connection and release resources.

Return type:

None

is_closing()[source]

Return True if the connection is closing or already closed.

Return type:

bool

async wait_closed()[source]

Wait until the underlying connection has completed closing.

This method returns when the underlying connection has been closed. It can be used to wait for the connection to be fully closed after calling close().

Return type:

None

async wait_for(*, remote=None, local=None, pending=None)[source]

Wait for negotiation state conditions to be met.

Parameters:
Return type:

bool

Returns:

True when all conditions are met.

Raises:

Example:

# Wait for TTYPE and NAWS negotiation to complete
await writer.wait_for(remote={"TTYPE": True, "NAWS": True})

# Wait for pending options to clear
await writer.wait_for(pending={"TTYPE": False})
async wait_for_condition(predicate)[source]

Wait for a custom condition to be met.

Parameters:

predicate (Callable[[TelnetWriter], bool]) – Callable taking TelnetWriter, returning bool.

Return type:

bool

Returns:

True when predicate returns True.

Raises:

asyncio.CancelledError – If connection closes while waiting.

Example:

await writer.wait_for_condition(lambda w: w.mode == "kludge")
write(data)[source]

Write a bytes object to the protocol transport.

Return type:

None

writelines(lines)[source]

Write unicode strings to transport.

Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.

Return type:

None

write_eof()[source]

Write EOF to the transport.

Return type:

None

can_write_eof()[source]

Return True if the transport supports write_eof().

Return type:

bool

async drain()[source]

Flush the write buffer.

The intended use is to write

w.write(data) await w.drain()

Return type:

None

feed_byte(byte)[source]

Feed a single byte into Telnet option state machine.

Parameters:

byte (bytes) – an 8-bit byte value as integer (0-255), or a bytes array. When a bytes array, it must be of length 1.

Return type:

bool

Returns:

Whether the given byte is “in band”, that is, should be duplicated to a connected terminal or device. False is returned for an IAC command for each byte until its completion.

Raises:

ValueError – When an illegal IAC command is received.

get_extra_info(name, default=None)[source]

Get optional server protocol information.

Return type:

Any

property protocol: Any

The (Telnet) protocol attached to this stream.

property server: bool

Whether this stream is of the server’s point of view.

property client: bool

Whether this stream is of the client’s point of view.

property inbinary: bool

Whether binary data is expected to be received on reader, RFC 856.

property outbinary: bool

Whether binary data may be written to the writer, RFC 856.

echo(data)[source]

Conditionally write data to transport when “remote echo” enabled.

Parameters:

data (bytes) – bytes received as input, conditionally written. The default implementation depends on telnet negotiation willingness for local echo, only an RFC- compliant telnet client will correctly set or unset echo accordingly by demand.

Return type:

None

property will_echo: bool

Whether Server end is expected to echo back input sent by client.

From server perspective: the server should echo (duplicate) client input back over the wire, the client is awaiting this data to indicate their input has been received.

From client perspective: the server will not echo our input, we should choose to duplicate our input to standard out ourselves.

property mode: str

String describing NVT mode.

One of:

kludge: Client acknowledges WILL-ECHO, WILL-SGA. Character-at-

a-time and remote line editing may be provided.

local: Default NVT half-duplex mode, client performs line

editing and transmits only after pressing send (usually CR).

remote: Client supports advanced remote line editing, using

mixed-mode local line buffering (optionally, echoing) until send, but also transmits buffer up to and including special line characters (SLCs).

property is_oob: bool

The previous byte should not be received by the API stream.

property linemode: Linemode

Linemode instance for stream.

Note

value is meaningful after successful LINEMODE negotiation, otherwise does not represent the linemode state of the stream.

Attributes of the stream’s active linemode may be tested using boolean instance attributes, edit, trapsig, soft_tab, lit_echo, remote, local.

send_iac(buf)[source]

Send a command starting with IAC (base 10 byte value 255).

No transformations of bytes are performed. Normally, if the byte value 255 is sent, it is escaped as IAC + IAC. This method ensures it is not escaped.

Return type:

None

iac(cmd, opt=b'')[source]

Send Is-A-Command 3-byte negotiation command.

Returns True if command was sent. Not all commands are legal in the context of client, server, or pending negotiation state, emitting a relevant debug warning to the log handler if not sent.

Raises:

ValueError – When cmd is not DO, DONT, WILL, or WONT.

Return type:

bool

send_ga()[source]

Transmit IAC GA (Go-Ahead).

Returns True if sent. If IAC-DO-SGA has been received, then False is returned and IAC-GA is not transmitted.

Return type:

bool

send_eor()[source]

Transmit IAC CMD_EOR (End-of-Record), RFC 885.

Returns True if sent. If IAC-DO-EOR has not been received, False is returned and IAC-CMD_EOR is not transmitted.

Return type:

bool

send_gmcp(package, data=None)[source]

Transmit a GMCP message via subnegotiation.

Parameters:
  • package (str) – GMCP package name (e.g., "Char.Vitals")

  • data (Any) – Optional data to encode as JSON

Return type:

None

send_msdp(variables)[source]

Transmit MSDP variables via subnegotiation.

Parameters:

variables (dict[str, Any]) – Dictionary of variable names to values

Return type:

None

send_mssp(variables)[source]

Transmit MSSP variables via subnegotiation.

Parameters:

variables (dict[str, str | list[str]]) – Dictionary of variable names to values

Return type:

None

request_status()[source]

Send IAC-SB-STATUS-SEND sub-negotiation (RFC 859).

This method may only be called after IAC-WILL-STATUS has been received. Returns True if status request was sent.

Return type:

bool

request_comport_signature()[source]

Send IAC SB COM-PORT-OPTION SIGNATURE IAC SE, RFC 2217.

Requests the server’s COM-PORT-OPTION signature string. Returns True if the request was sent.

Return type:

bool

request_tspeed()[source]

Send IAC-SB-TSPEED-SEND sub-negotiation, RFC 1079.

This method may only be called after IAC-WILL-TSPEED has been received. Returns True if TSPEED request was sent.

Return type:

bool

request_charset()[source]

Request sub-negotiation CHARSET, RFC 2066.

Returns True if request is valid for telnet state, and was sent.

The sender requests that all text sent to and by it be encoded in one of character sets specified by string list codepages, which is determined by function value returned by callback registered using set_ext_send_callback() with value CHARSET.

Return type:

bool

request_environ()[source]

Request sub-negotiation NEW_ENVIRON, RFC 1572.

Returns True if request is valid for telnet state, and was sent. When the request list exceeds the subnegotiation buffer limit of many telnet clients (256 bytes for GNU inetutils), the request is automatically split into multiple SB frames.

Return type:

bool

request_xdisploc()[source]

Send XDISPLOC, SEND sub-negotiation, RFC 1086.

Returns True if request is valid for telnet state, and was sent.

Return type:

bool

request_ttype()[source]

Send TTYPE SEND sub-negotiation, RFC 930.

Returns True if request is valid for telnet state, and was sent.

Return type:

bool

request_forwardmask(fmask=None)[source]

Request the client forward their terminal control characters.

Characters are indicated in the Forwardmask instance fmask. When fmask is None, a forwardmask is generated for the SLC characters registered by slctab.

Return type:

bool

send_lineflow_mode()[source]

Send LFLOW mode sub-negotiation, RFC 1372.

Returns True if request is valid for telnet state, and was sent.

Return type:

Optional[bool]

send_linemode(linemode=None)[source]

Set and Inform other end to agree to change to linemode, linemode.

An instance of the Linemode class, or self.linemode when unset.

Raises:

AssertionError – When LINEMODE not negotiated.

Return type:

None

request_linemode_change(edit=None, trapsig=None, soft_tab=None, lit_echo=None)[source]

Request a LINEMODE mode change.

Server-side only. Each keyword arg, if not None, enables or disables the corresponding bit in the LINEMODE MODE mask.

Parameters:
Return type:

None

set_iac_callback(cmd, func)[source]

Register callable func as callback for IAC cmd.

BRK, IP, AO, AYT, EC, EL, CMD_EOR, EOF, SUSP, ABORT, and NOP.

These callbacks receive a single argument, the IAC cmd which triggered it.

Return type:

None

handle_nop(cmd)[source]

Handle IAC No-Operation (NOP).

Return type:

None

handle_ga(cmd)[source]

Handle IAC Go-Ahead (GA).

Return type:

None

handle_dm(cmd)[source]

Handle IAC Data-Mark (DM).

Return type:

None

handle_el(_byte)[source]

Handle IAC Erase Line (EL, SLC_EL).

Provides a function which discards all the data ready on current line of input. The prompt should be re-displayed.

Return type:

None

handle_eor(_byte)[source]

Handle IAC End of Record (CMD_EOR, SLC_EOR).

Return type:

None

handle_abort(_byte)[source]

Handle IAC Abort (ABORT, SLC_ABORT).

Similar to Interrupt Process (IP), but means only to abort or terminate the process to which the NVT is connected.

Return type:

None

handle_eof(_byte)[source]

Handle IAC End of Record (EOF, SLC_EOF).

Return type:

None

handle_susp(_byte)[source]

Handle IAC Suspend Process (SUSP, SLC_SUSP).

Suspends the execution of the current process attached to the NVT in such a way that another process will take over control of the NVT, and the suspended process can be resumed at a later time.

If the receiving system does not support this functionality, it should be ignored.

Return type:

None

handle_brk(_byte)[source]

Handle IAC Break (BRK, SLC_BRK).

Sent by clients to indicate BREAK keypress. This is not the same as IP (^c), but a means to map system-dependent break key such as found on an IBM Systems.

Return type:

None

handle_ayt(_byte)[source]

Handle IAC Are You There (AYT, SLC_AYT).

Provides the user with some visible (e.g., printable) evidence that the system is still up and running.

Return type:

None

handle_ip(_byte)[source]

Handle IAC Interrupt Process (IP, SLC_IP).

Return type:

None

handle_ao(_byte)[source]

Handle IAC Abort Output (AO) or SLC_AO.

Discards any remaining output on the transport buffer.

[…] a reasonable implementation would be to suppress the remainder of the text string, but transmit the prompt character and the preceding <CR><LF>.

Return type:

None

handle_ec(_byte)[source]

Handle IAC Erase Character (EC, SLC_EC).

Provides a function which deletes the last preceding undeleted character from data ready on current line of input.

Return type:

None

handle_tm(cmd)[source]

Handle IAC (WILL, WONT, DO, DONT) Timing Mark (TM).

TM is essentially a NOP that any IAC interpreter must answer, if at least it answers WONT to unknown options (required), it may still be used as a means to accurately measure the “ping” time.

Return type:

None

set_slc_callback(slc_byte, func)[source]

Register func as callable for receipt of slc_byte.

Parameters:
  • slc_byte (bytes) – any of SLC_SYNCH, SLC_BRK, SLC_IP, SLC_AO, SLC_AYT, SLC_EOR, SLC_ABORT, SLC_EOF, SLC_SUSP, SLC_EC, SLC_EL, SLC_EW, SLC_RP, SLC_XON, SLC_XOFF …

  • func (Callable[..., Any]) – Callback receiving a single argument: the SLC function byte that fired it. Some SLC and IAC functions are intermixed; which signaling mechanism used by client can be tested by evaluating this argument.

Return type:

None

handle_ew(_slc)[source]

Handle SLC_EW (Erase Word).

Provides a function which deletes the last preceding undeleted character, and any subsequent bytes until next whitespace character from data ready on current line of input.

Return type:

None

handle_rp(_slc)[source]

Handle SLC Repaint (RP).

Return type:

None

handle_lnext(_slc)[source]

Handle SLC Literal Next (LNEXT) (Next character is received raw).

Return type:

None

handle_xon(_byte)[source]

Handle SLC Transmit-On (XON).

Return type:

None

handle_xoff(_byte)[source]

Handle SLC Transmit-Off (XOFF).

Return type:

None

set_ext_send_callback(cmd, func)[source]

Register callback for inquiries of sub-negotiation of cmd.

Parameters:
  • func (Callable[..., Any]) – A callable function for the given cmd byte. Note that the return type must match those documented.

  • cmd (bytes) –

    These callbacks must return any number of arguments, for each registered cmd byte, respectively:

    • SNDLOC: for clients, returning one argument: the string describing client location, such as b'ROOM 641-A', RFC 779.

    • NAWS: for clients, returning two integer arguments (width, height), such as (80, 24), RFC 1073.

    • TSPEED: for clients, returning two integer arguments (rx, tx) such as (57600, 57600), RFC 1079.

    • TTYPE: for clients, returning one string, usually the terminfo(5) database capability name, such as ‘xterm’, RFC 1091.

    • XDISPLOC: for clients, returning one string, the DISPLAY host value, in form of <host>:<dispnum>[.<screennum>], RFC 1096.

    • NEW_ENVIRON: for clients, returning a dictionary of (key, val) pairs of environment item values, RFC 1408.

    • CHARSET: for clients, receiving iterable of strings of character sets requested by server, callback must return one of those strings given, RFC 2066.

Return type:

None

set_ext_offer_callback(cmd, func)[source]

Register callback for building outgoing sub-negotiation requests.

Unlike set_ext_send_callback() (which responds to received requests), this callback is invoked with no arguments and must return a list describing what to offer or request.

Parameters:
  • cmd (bytes) – Telnet option byte.

  • func (Callable[..., Any]) –

    Callable returning a list:

    • CHARSET: return a list of charset name strings to offer in an outgoing SB CHARSET REQUEST, RFC 2066.

    • NEW_ENVIRON: return a list of environment variable name strings (or the special VAR/USERVAR bytes) to request in an outgoing SB NEW_ENVIRON SEND, RFC 1572.

Return type:

None

set_ext_callback(cmd, func)[source]

Register func as callback for receipt of cmd negotiation.

Parameters:

cmd (bytes) – One of the following listed bytes:

Return type:

None

  • LOGOUT: for servers and clients, receiving one argument. Server end may receive DO or DONT as argument cmd, indicating client’s wish to disconnect, or a response to WILL, LOGOUT, indicating its wish not to be automatically disconnected. Client end may receive WILL or WONT, indicating server’s wish to disconnect, or acknowledgment that the client will not be disconnected.

  • SNDLOC: for servers, receiving one argument: the string describing the client location, such as 'ROOM 641-A', RFC 779.

  • NAWS: for servers, receiving two integer arguments (width, height), such as (80, 24), RFC 1073.

  • TSPEED: for servers, receiving two integer arguments (rx, tx) such as (57600, 57600), RFC 1079.

  • TTYPE: for servers, receiving one string, usually the terminfo(5) database capability name, such as ‘xterm’, RFC 1091.

  • XDISPLOC: for servers, receiving one string, the DISPLAY host value, in form of <host>:<dispnum>[.<screennum>], RFC 1096.

  • NEW_ENVIRON: for servers, receiving a dictionary of (key, val) pairs of remote client environment item values, RFC 1408.

  • CHARSET: for servers, receiving one string, the character set negotiated by client. RFC 2066.

  • GMCP: receiving two arguments (package, data), the GMCP package name as string and decoded JSON data (or None).

  • MSDP: receiving one argument, a dict of MSDP variable names to values (strings, lists, or nested dicts).

  • MSSP: receiving one argument, a dict of MSSP variable names to string values (or list of strings for multi-valued).

Parameters:

func (Callable[..., Any]) – The callback function to register.

handle_xdisploc(xdisploc)[source]

Receive XDISPLAY value xdisploc, RFC 1096.

Return type:

None

handle_send_xdisploc()[source]

Send XDISPLAY value xdisploc, RFC 1096.

Return type:

str

handle_sndloc(location)[source]

Receive LOCATION value location, RFC 779.

Return type:

None

handle_send_sndloc()[source]

Send LOCATION value location, RFC 779.

Return type:

str

handle_ttype(ttype)[source]

Receive TTYPE value ttype, RFC 1091.

A string value that represents client’s emulation capability.

Some example values: VT220, VT100, ANSITERM, ANSI, TTY, and 5250.

Return type:

None

handle_send_ttype()[source]

Send TTYPE value ttype, RFC 1091.

Return type:

str

handle_naws(width, height)[source]

Receive window size width and height, RFC 1073.

Return type:

None

handle_send_naws()[source]

Send window size width and height, RFC 1073.

Return type:

tuple[int, int]

handle_environ(env)[source]

Receive environment variables as dict, RFC 1572.

Return type:

None

handle_send_client_environ(_keys)[source]

Send environment variables as dict, RFC 1572.

If argument keys is empty, then all available values should be sent. Otherwise, keys is a set of environment keys explicitly requested.

Return type:

dict[str, str]

handle_send_server_environ()[source]

Server requests environment variables as list, RFC 1572.

Return type:

list[str]

handle_tspeed(rx, tx)[source]

Receive terminal speed from TSPEED as int, RFC 1079.

Return type:

None

handle_send_tspeed()[source]

Send terminal speed from TSPEED as int, RFC 1079.

Return type:

tuple[int, int]

handle_charset(charset)[source]

Receive character set as string, RFC 2066.

Return type:

None

handle_gmcp(package, data)[source]

Receive GMCP message with package name and data.

Parameters:
  • package (str) – GMCP package name (e.g., "Char.Vitals").

  • data (Any) – Decoded JSON value – may be any JSON type (str, int, float, bool, None, list, or dict).

Return type:

None

handle_msdp(variables)[source]

Receive MSDP variables as dict.

Parameters:

variables (dict[str, Any]) – Mapping of variable names to values. Values may be str, dict[str, Any] (MSDP table), or list[Any] (MSDP array) per the MSDP wire format.

Return type:

None

handle_mssp(variables)[source]

Receive MSSP variables as dict.

Return type:

None

handle_msp(data)[source]

Receive MUD Sound Protocol subnegotiation data.

Return type:

None

handle_mxp(data)[source]

Receive MUD eXtension Protocol subnegotiation data.

Return type:

None

handle_zmp(parts)[source]

Receive decoded ZMP message as list of [command, arg, ...].

Return type:

None

handle_aardwolf(data)[source]

Receive decoded Aardwolf message as dict.

Return type:

None

handle_atcp(package, value)[source]

Receive decoded ATCP message as (package, value).

Return type:

None

handle_send_client_charset(_charsets)[source]

Send character set selection as string, RFC 2066.

Given the available encodings presented by the server, select and return only one. Returning an empty string indicates that no selection is made (request is ignored).

Return type:

str

handle_send_server_charset()[source]

Send character set (encodings) offered to client, RFC 2066.

Return type:

list[str]

handle_logout(cmd)[source]

Handle (IAC, (DO | DONT | WILL | WONT), LOGOUT), RFC 727.

Only the server end may receive (DO, DONT). Only the client end may receive (WILL, WONT).

Return type:

None

handle_do(opt)[source]

Process byte 3 of series (IAC, DO, opt) received by remote end.

This method can be derived to change or extend protocol capabilities, for most cases, simply returning True if supported, False otherwise.

In special cases of various RFC statutes, state is stored and answered in willing affirmative, with the exception of:

  • DO TM is always answered WILL TM, even if it was already replied to. No state is stored (“Timing Mark”), and the IAC callback registered by set_ext_callback() for cmd TM is called with argument byte DO.

  • DO LOGOUT executes extended callback registered by cmd LOGOUT with argument DO (indicating a request for voluntary logoff).

  • DO STATUS sends state of all local, remote, and pending options.

Raises:

ValueError – When opt is invalid for the current endpoint role (server/client).

Return type:

bool

handle_dont(opt)[source]

Process byte 3 of series (IAC, DONT, opt) received by remote end.

This only results in self.local_option[opt] set to False, with the exception of (IAC, DONT, LOGOUT), which only signals a callback to handle_logout(DONT).

Return type:

None

handle_will(opt)[source]

Process byte 3 of series (IAC, WILL, opt) received by remote end.

The remote end requests we perform any number of capabilities. Most implementations require an answer in the affirmative with DO, unless DO has meaning specific for only client or server end, and dissenting with DONT.

WILL ECHO may only be received for clients, answered with DO. WILL NAWS may only be received for servers, answered with DO. BINARY and SGA are answered with DO. STATUS, NEW_ENVIRON, XDISPLOC, and TTYPE is answered with sub-negotiation SEND. The env variables requested in response to WILL NEW_ENVIRON is “SEND ANY”. All others are replied with DONT.

The result of a supported capability is a response of (IAC, DO, opt) and the setting of self.remote_option[opt] of True. For unsupported capabilities, RFC specifies a response of (IAC, DONT, opt). Similarly, set self.remote_option[opt] to False.

Options received in the wrong direction (e.g. WILL NAWS on client end) are gracefully refused with DONT per Postel’s law (RFC 1123).

Raises:

ValueError – When WILL ECHO is received on server end, or when WILL TM is received without prior DO TM.

Return type:

None

handle_wont(opt)[source]

Process byte 3 of series (IAC, WONT, opt) received by remote end.

(IAC, WONT, opt) is a negative acknowledgment of (IAC, DO, opt) sent.

The remote end requests we do not perform a telnet capability.

It is not possible to decline a WONT. T.remote_option[opt] is set False to indicate the remote end’s refusal to perform opt.

Raises:

ValueError – When WONT TM is received without prior DO TM.

Return type:

None

handle_subnegotiation(buf)[source]

Callback for end of sub-negotiation buffer.

SB options handled here are TTYPE, XDISPLOC, NEW_ENVIRON, NAWS, and STATUS, and are delegated to their handle_ equivalent methods. Implementers of additional SB options should extend this method.

Raises:

ValueError – When the sub-negotiation buffer is empty, starts with NUL, is too short, or contains an unhandled command.

Return type:

None

handle_mccp2(activated)[source]

Default ext_callback for MCCP2 activation.

Return type:

None

property forwardmask: Forwardmask | None

Received LINEMODE FORWARDMASK, or None.

class TelnetWriterUnicode(transport, protocol, fn_encoding, *, encoding_errors='strict', client=False, server=False, reader=None)[source]

A Unicode StreamWriter interface for Telnet protocol.

See ancestor class, TelnetWriter for details.

Requires the fn_encoding callback, receiving mutually boolean keyword argument outgoing=True to determine what encoding should be used to decode the value in the direction specified.

The encoding may be conditionally negotiated by CHARSET, RFC 2066, or discovered by LANG environment variables by NEW_ENVIRON, RFC 1572.

Initialize TelnetWriterUnicode with encoding callback.

encode(string, errors=None)[source]

Encode string using protocol-preferred encoding.

Parameters:
  • string (str) – unicode string to encode.

  • errors (Optional[str]) – same as meaning in codecs.Codec.encode(), when None (default), value of class initializer keyword argument, encoding_errors.

Return type:

bytes

Note

Though a unicode interface, when outbinary mode has not been protocol negotiated, fn_encoding strictly enforces 7-bit ASCII range (ordinal byte values less than 128), as a strict compliance of the telnet RFC.

write(string, errors=None)[source]

Write unicode string to transport, using protocol-preferred encoding.

If the connection is closed, nothing is done.

Parameters:
  • string (str) – unicode string text to write to endpoint using the protocol’s preferred encoding. When the protocol encoding keyword is explicitly set to False, the given string should be only raw b'bytes'.

  • errors (Optional[str]) – same as meaning in codecs.Codec.encode(), when None (default), value of class initializer keyword argument, encoding_errors.

Return type:

None

writelines(lines, errors=None)[source]

Write unicode strings to transport.

Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.

Return type:

None

echo(string, errors=None)[source]

Conditionally write string to transport when “remote echo” enabled.

Parameters:
Return type:

None

This method may only be called from the server perspective. The default implementation depends on telnet negotiation willingness for local echo: only an RFC-compliant telnet client will correctly set or unset echo accordingly by demand.