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.StreamWriterwith 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 tofeed_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 tofeed_byte(), which returns True to indicate the given byte should be forwarded to a Protocol reader method.- Parameters:
- 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
Trueuntil 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
TelnetSessionContextto 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.
Noneif no SEND was received.
- mssp_data: dict[str, str | list[str]] | None
Decoded MSSP variables received via subnegotiation.
Noneuntil aSB MSSPpayload is received and decoded.
- zmp_data: list[list[str]]
Accumulated ZMP messages (list of [command, arg, …] lists). Empty until
SB ZMPpayloads are received and decoded.
- atcp_data: list[tuple[str, str]]
Accumulated ATCP messages (list of (package, value) tuples). Empty until
SB ATCPpayloads are received and decoded.
- aardwolf_data: list[dict[str, Any]]
Accumulated Aardwolf messages (list of decoded dicts). Empty until
SB AARDWOLFpayloads are received and decoded.
- mxp_data: list[bytes]
Accumulated MXP subnegotiation payloads (list of raw bytes). Empty until
SB MXPpayloads 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.
Noneuntil anSB COM-PORT-OPTIONpayload is received.
- compression: bool | None
Compression policy:
None= passively accept (default),True= actively request,False= reject.
- slctab
SLC Tab (SLC Functions and their support level, and ascii value)
- 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:
- async wait_for(*, remote=None, local=None, pending=None)[source]
Wait for negotiation state conditions to be met.
- Parameters:
- Return type:
- Returns:
True when all conditions are met.
- Raises:
KeyError – If an option name is not recognized.
asyncio.CancelledError – If connection closes while waiting.
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:
- 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")
- 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:
- async drain()[source]
Flush the write buffer.
The intended use is to write
w.write(data) await w.drain()
- Return type:
- 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:
- Returns:
Whether the given
byteis “in band”, that is, should be duplicated to a connected terminal or device.Falseis returned for anIACcommand for each byte until its completion.- Raises:
ValueError – When an illegal IAC command is received.
- 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 lineediting and transmits only after pressing send (usually CR).
remote: Client supports advanced remote line editing, usingmixed-mode local line buffering (optionally, echoing) until send, but also transmits buffer up to and including special line characters (SLCs).
- 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:
- 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:
- 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:
- 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:
- request_status()[source]
Send
IAC-SB-STATUS-SENDsub-negotiation (RFC 859).This method may only be called after
IAC-WILL-STATUShas been received. Returns True if status request was sent.- Return type:
- 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:
- request_tspeed()[source]
Send IAC-SB-TSPEED-SEND sub-negotiation, RFC 1079.
This method may only be called after
IAC-WILL-TSPEEDhas been received. Returns True if TSPEED request was sent.- Return type:
- 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 usingset_ext_send_callback()with valueCHARSET.- Return type:
- 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:
- request_xdisploc()[source]
Send XDISPLOC, SEND sub-negotiation, RFC 1086.
Returns True if request is valid for telnet state, and was sent.
- Return type:
- request_ttype()[source]
Send TTYPE SEND sub-negotiation, RFC 930.
Returns True if request is valid for telnet state, and was sent.
- Return type:
- 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 byslctab.- Return type:
- send_lineflow_mode()[source]
Send LFLOW mode sub-negotiation, RFC 1372.
Returns True if request is valid for telnet state, and was sent.
- 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:
- 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.
- set_iac_callback(cmd, func)[source]
Register callable
funcas callback for IACcmd.BRK, IP, AO, AYT, EC, EL, CMD_EOR, EOF, SUSP, ABORT, and NOP.
These callbacks receive a single argument, the IAC
cmdwhich triggered it.- Return type:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- 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:
- set_slc_callback(slc_byte, func)[source]
Register
funcas callable for receipt ofslc_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:
- 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:
- handle_lnext(_slc)[source]
Handle SLC Literal Next (LNEXT) (Next character is received raw).
- Return type:
- 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 givencmdbyte. Note that the return type must match those documented.cmd (
bytes) –These callbacks must return any number of arguments, for each registered
cmdbyte, 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:
- 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.Callable returning a list:
- Return type:
- set_ext_callback(cmd, func)[source]
Register
funcas callback for receipt ofcmdnegotiation.LOGOUT: for servers and clients, receiving one argument. Server end may receive DO or DONT as argumentcmd, 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).
- 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:
- handle_send_client_environ(_keys)[source]
Send environment variables as dict, RFC 1572.
If argument
keysis empty, then all available values should be sent. Otherwise,keysis a set of environment keys explicitly requested.
- 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:
- 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:
- 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 byteDO.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:
- 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 toFalse, with the exception of (IAC, DONT, LOGOUT), which only signals a callback tohandle_logout(DONT).- Return type:
- 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]ofTrue. For unsupported capabilities, RFC specifies a response of (IAC, DONT, opt). Similarly, setself.remote_option[opt]toFalse.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:
- 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 performopt.- Raises:
ValueError – When WONT TM is received without prior DO TM.
- Return type:
- 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:
- 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,
TelnetWriterfor details.Requires the
fn_encodingcallback, receiving mutually boolean keyword argumentoutgoing=Trueto 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
LANGenvironment variables by NEW_ENVIRON, RFC 1572.Initialize TelnetWriterUnicode with encoding callback.
- encode(string, errors=None)[source]
Encode
stringusing protocol-preferred encoding.- Parameters:
string (
str) – unicode string to encode.errors (
Optional[str]) – same as meaning incodecs.Codec.encode(), whenNone(default), value of class initializer keyword argument,encoding_errors.
- Return type:
Note
Though a unicode interface, when
outbinarymode has not been protocol negotiated,fn_encodingstrictly 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 protocolencodingkeyword is explicitly set toFalse, the given string should be only rawb'bytes'.errors (
Optional[str]) – same as meaning incodecs.Codec.encode(), whenNone(default), value of class initializer keyword argument,encoding_errors.
- Return type:
- 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:
- echo(string, errors=None)[source]
Conditionally write
stringto transport when “remote echo” enabled.- Parameters:
string (
str) – string received as input, conditionally written.errors (
Optional[str]) – same as meaning incodecs.Codec.encode().
- Return type:
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.