server

The main function here is wired to the command line tool by name telnetlib3-server. If this server’s PID receives the SIGTERM signal, it attempts to shutdown gracefully.

The TelnetServer class negotiates a character-at-a-time (WILL-SGA, WILL-ECHO) session with support for negotiation about window size, environment variables, terminal type name, and to automatically close connections clients after an idle period.

class TelnetServer(term='unknown', cols=80, rows=25, timeout=300, *args, **kwargs)[source]

Bases: telnetlib3.server_base.BaseServer

Telnet Server protocol performing common negotiation.

TTYPE_LOOPMAX = 8

Maximum number of cycles to seek for all terminal types. We are seeking the repeat or cycle of a terminal table, choosing the first – but when negotiated by MUD clients, we chose the must Unix TERM appropriate,

connection_made(transport)[source]

Called when a connection is made.

Sets attributes _transport, _when_connected, _last_received, reader and writer.

Ensure super().connection_made(transport) is called when derived.

data_received(data)[source]

Process bytes received by transport.

begin_negotiation()[source]

Begin on-connect negotiation.

A Telnet server is expected to demand preferred session options immediately after connection. Deriving implementations should always call super().begin_negotiation().

begin_advanced_negotiation()[source]

Begin advanced negotiation.

Callback method further requests advanced telnet options. Called once on receipt of any DO or WILL acknowledgments received, indicating that the remote end is capable of negotiating further.

Only called if sub-classing begin_negotiation() causes at least one negotiation option to be affirmatively acknowledged.

check_negotiation(final=False)[source]

Callback, return whether negotiation is complete.

Parameters:final (bool) – Whether this is the final time this callback will be requested to answer regarding protocol negotiation.
Returns:Whether negotiation is over (server end is satisfied).
Return type:bool

Method is called on each new command byte processed until negotiation is considered final, or after connect_maxwait has elapsed, setting attribute _waiter_connected to value self when complete.

Ensure super().check_negotiation() is called and conditionally combined when derived.

encoding(outgoing=None, incoming=None)[source]

Return encoding for the given stream direction.

Parameters:
  • outgoing (bool) – Whether the return value is suitable for encoding bytes for transmission to client end.
  • incoming (bool) – Whether the return value is suitable for decoding bytes received from the client.
Raises:

TypeError – when a direction argument, either outgoing or incoming, was not set True.

Returns:

'US-ASCII' for the directions indicated, unless BINARY RFC 856 has been negotiated for the direction indicated or :attr`force_binary` is set True.

Return type:

str

set_timeout(duration=-1)[source]

Restart or unset timeout for client.

Parameters:duration (int) – When specified as a positive integer, schedules Future for callback of on_timeout(). When -1, the value of self.get_extra_info('timeout') is used. When non-True, it is canceled.
on_timeout()[source]

Callback received on session timeout.

Default implementation writes “Timeout.” bound by CRLF and closes.

This can be disabled by calling set_timeout() with :paramref:`~.set_timeout.duration` value of 0 or value of the same for keyword argument timeout.

on_naws(rows, cols)[source]

Callback receives NAWS response, RFC 1073.

Parameters:
  • rows (int) – screen size, by number of cells in height.
  • cols (int) – screen size, by number of cells in width.
on_request_environ()[source]

Definition for NEW_ENVIRON request of client, RFC 1572.

This method is a callback from request_environ(), first entered on receipt of (WILL, NEW_ENVIRON) by server. The return value defines the request made to the client for environment values.

Rtype list:

a list of unicode character strings of US-ASCII characters, indicating the environment keys the server requests of the client. If this list contains the special byte constants, USERVAR or VAR, the client is allowed to volunteer any other additional user or system values.

Any empty return value indicates that no request should be made.

The default return value is:

['LANG', 'TERM', 'COLUMNS', 'LINES', 'DISPLAY', 'COLORTERM',
 VAR, USERVAR, 'COLORTERM']
on_environ(mapping)[source]

Callback receives NEW_ENVIRON response, RFC 1572.

on_request_charset()[source]

Definition for CHARSET request by client, RFC 2066.

This method is a callback from request_charset(), first entered on receipt of (WILL, CHARSET) by server. The return value defines the request made to the client for encodings.

Rtype list:

a list of unicode character strings of US-ASCII characters, indicating the encodings offered by the server in its preferred order.

Any empty return value indicates that no encodings are offered.

The default return value begins:

['UTF-8', 'UTF-16', 'LATIN1', 'US-ASCII', 'BIG5', 'GBK', ...]
on_charset(charset)[source]

Callback for CHARSET response, RFC 2066.

on_tspeed(rx, tx)[source]

Callback for TSPEED response, RFC 1079.

on_ttype(ttype)[source]

Callback for TTYPE response, RFC 930.

on_xdisploc(xdisploc)[source]

Callback for XDISPLOC response, RFC 1096.

begin_shell(result)
connection_lost(exc)

Called when the connection is lost or closed.

Parameters:exc (Exception) – exception. None indicates close by EOF.
duration

Time elapsed since client connected, in seconds as float.

eof_received()

Called when the other end calls write_eof() or equivalent.

This callback may be exercised by the nc(1) client argument -z.

get_extra_info(name, default=None)

Get optional server protocol or transport information.

idle

Time elapsed since data last received, in seconds as float.

negotiation_should_advance()

Whether advanced negotiation should commence.

Return type:bool
Returns:True if advanced negotiation should be permitted.

The base implementation returns True if any negotiation options were affirmatively acknowledged by client, more than likely options requested in callback begin_negotiation().

pause_writing()

Called when the transport’s buffer goes over the high-water mark.

Pause and resume calls are paired – pause_writing() is called once when the buffer goes strictly over the high-water mark (even if subsequent writes increases the buffer size even more), and eventually resume_writing() is called once when the buffer size reaches the low-water mark.

Note that if the buffer size equals the high-water mark, pause_writing() is not called – it must go strictly over. Conversely, resume_writing() is called when the buffer size is equal or lower than the low-water mark. These end conditions are important to ensure that things go as expected when either mark is zero.

NOTE: This is the only Protocol callback that is not called through EventLoop.call_soon() – if it were, it would have no effect when it’s most needed (when the app keeps writing without yielding until pause_writing() is called).

resume_writing()

Called when the transport’s buffer drains below the low-water mark.

See pause_writing() for details.

timeout_connection()
parse_server_args()[source]
create_server(host=None, port=23, protocol_factory=<class 'telnetlib3.server.TelnetServer'>, **kwds)[source]

Create a TCP Telnet server.

Parameters:
  • host (str) – The host parameter can be a string, in that case the TCP server is bound to host and port. The host parameter can also be a sequence of strings, and in that case the TCP server is bound to all hosts of the sequence.
  • port (int) – listen port for TCP Server.
  • protocol_factory (server_base.BaseServer) – An alternate protocol factory for the server, when unspecified, TelnetServer is used.
  • shell (Callable) – A asyncio.coroutine() that is called after negotiation completes, receiving arguments (reader, writer). The reader is a TelnetReader instance, the writer is a TelnetWriter instance.
  • encoding (str) –

    The default assumed encoding, or False to disable unicode support. Encoding may be negotiation to another value by the client through NEW_ENVIRON RFC 1572 by sending environment value of LANG, or by any legal value for CHARSET RFC 2066 negotiation.

    The server’s attached reader, writer streams accept and return unicode, unless this value explicitly set False. In that case, the attached streams interfaces are bytes-only.

  • encoding_errors (str) – Same meaning as codecs.Codec.encode(). Default value is strict.
  • force_binary (bool) – When True, the encoding specified is used for both directions even when BINARY mode, RFC 856, is not negotiated for the direction specified. This parameter has no effect when encoding=False.
  • term (str) – Value returned for writer.get_extra_info('term') until negotiated by TTYPE RFC 930, or NAWS RFC 1572. Default value is 'unknown'.
  • cols (int) – Value returned for writer.get_extra_info('cols') until negotiated by NAWS RFC 1572. Default value is 80 columns.
  • rows (int) – Value returned for writer.get_extra_info('rows') until negotiated by NAWS RFC 1572. Default value is 25 rows.
  • timeout (int) – Causes clients to disconnect if idle for this duration, in seconds. This ensures resources are freed on busy servers. When explicitly set to False, clients will not be disconnected for timeout. Default value is 300 seconds (5 minutes).
  • connect_maxwait (float) – If the remote end is not complaint, or otherwise confused by our demands, the shell continues anyway after the greater of this value has elapsed. A client that is not answering option negotiation will delay the start of the shell by this amount.
  • limit (int) – The buffer limit for the reader stream.
Return asyncio.Server:
 

The return value is the same as asyncio.loop.create_server(), An object which can be used to stop the service.

This function is a coroutine().

run_server(host='localhost', port=6023, loglevel='info', logfile=None, logfmt='%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(message)s', shell=<function telnet_server_shell>, encoding='utf8', force_binary=False, timeout=300, connect_maxwait=4.0)[source]

Program entry point for server daemon.

This function configures a logger and creates a telnet server for the given keyword arguments, serving forever, completing only upon receipt of SIGTERM.