blob: 14ca1b19041d44fa87b1cca1c3e152d08fb99d8a [file] [log] [blame]
Hye-Shik Change029da02005-09-07 07:40:05 +00001r"""TELNET client class.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +00002
3Based on RFC 854: TELNET Protocol Specification, by J. Postel and
4J. Reynolds
5
6Example:
7
8>>> from telnetlib import Telnet
9>>> tn = Telnet('www.python.org', 79) # connect to finger port
Benjamin Peterson3de7fb82008-10-15 20:54:24 +000010>>> tn.write(b'guido\r\n')
Guido van Rossum7131f842007-02-09 20:13:25 +000011>>> print(tn.read_all())
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000012Login Name TTY Idle When Where
13guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
Tim Petersb90f89a2001-01-15 03:26:36 +000014
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000015>>>
16
17Note that read_all() won't read until eof -- it just reads some data
18-- but it guarantees to read at least one byte unless EOF is hit.
19
20It is possible to pass a Telnet object to select.select() in order to
21wait until more data is available. Note that in this case,
Benjamin Peterson3de7fb82008-10-15 20:54:24 +000022read_eager() may return b'' even if there was data on the socket,
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000023because the protocol negotiation may have eaten the data. This is why
24EOFError is needed in some cases to distinguish between "no data" and
25"connection closed" (since the socket also appears ready for reading
26when it is closed).
27
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000028To do:
29- option negotiation
Guido van Rossumccb5ec61997-12-24 22:24:19 +000030- timeout should be intrinsic to the connection object instead of an
31 option on one of the read calls only
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000032
33"""
34
35
36# Imported modules
Gregory P. Smithdad57112012-07-15 23:42:26 -070037import errno
Guido van Rossumccb5ec61997-12-24 22:24:19 +000038import sys
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000039import socket
40import select
Victor Stinner2ff68dd2013-10-26 09:16:29 +020041try:
42 from time import monotonic as _time
43except ImportError:
44 from time import time as _time
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000045
Skip Montanaro40fc1602001-03-01 04:27:19 +000046__all__ = ["Telnet"]
47
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000048# Tunable parameters
49DEBUGLEVEL = 0
50
51# Telnet protocol defaults
52TELNET_PORT = 23
53
54# Telnet protocol characters (don't change)
Jack Diederich1c8f38c2009-04-10 05:33:26 +000055IAC = bytes([255]) # "Interpret As Command"
56DONT = bytes([254])
57DO = bytes([253])
58WONT = bytes([252])
59WILL = bytes([251])
60theNULL = bytes([0])
Martin v. Löwis574deae2002-11-04 17:34:07 +000061
Jack Diederich1c8f38c2009-04-10 05:33:26 +000062SE = bytes([240]) # Subnegotiation End
63NOP = bytes([241]) # No Operation
64DM = bytes([242]) # Data Mark
65BRK = bytes([243]) # Break
66IP = bytes([244]) # Interrupt process
67AO = bytes([245]) # Abort output
68AYT = bytes([246]) # Are You There
69EC = bytes([247]) # Erase Character
70EL = bytes([248]) # Erase Line
71GA = bytes([249]) # Go Ahead
72SB = bytes([250]) # Subnegotiation Begin
Martin v. Löwis574deae2002-11-04 17:34:07 +000073
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000074
Martin v. Löwisb0162f92001-09-06 08:51:38 +000075# Telnet protocol options code (don't change)
76# These ones all come from arpa/telnet.h
Jack Diederich1c8f38c2009-04-10 05:33:26 +000077BINARY = bytes([0]) # 8-bit data path
78ECHO = bytes([1]) # echo
79RCP = bytes([2]) # prepare to reconnect
80SGA = bytes([3]) # suppress go ahead
81NAMS = bytes([4]) # approximate message size
82STATUS = bytes([5]) # give status
83TM = bytes([6]) # timing mark
84RCTE = bytes([7]) # remote controlled transmission and echo
85NAOL = bytes([8]) # negotiate about output line width
86NAOP = bytes([9]) # negotiate about output page size
87NAOCRD = bytes([10]) # negotiate about CR disposition
88NAOHTS = bytes([11]) # negotiate about horizontal tabstops
89NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
90NAOFFD = bytes([13]) # negotiate about formfeed disposition
91NAOVTS = bytes([14]) # negotiate about vertical tab stops
92NAOVTD = bytes([15]) # negotiate about vertical tab disposition
93NAOLFD = bytes([16]) # negotiate about output LF disposition
94XASCII = bytes([17]) # extended ascii character set
95LOGOUT = bytes([18]) # force logout
96BM = bytes([19]) # byte macro
97DET = bytes([20]) # data entry terminal
98SUPDUP = bytes([21]) # supdup protocol
99SUPDUPOUTPUT = bytes([22]) # supdup output
100SNDLOC = bytes([23]) # send location
101TTYPE = bytes([24]) # terminal type
102EOR = bytes([25]) # end or record
103TUID = bytes([26]) # TACACS user identification
104OUTMRK = bytes([27]) # output marking
105TTYLOC = bytes([28]) # terminal location number
106VT3270REGIME = bytes([29]) # 3270 regime
107X3PAD = bytes([30]) # X.3 PAD
108NAWS = bytes([31]) # window size
109TSPEED = bytes([32]) # terminal speed
110LFLOW = bytes([33]) # remote flow control
111LINEMODE = bytes([34]) # Linemode option
112XDISPLOC = bytes([35]) # X Display Location
113OLD_ENVIRON = bytes([36]) # Old - Environment variables
114AUTHENTICATION = bytes([37]) # Authenticate
115ENCRYPT = bytes([38]) # Encryption option
116NEW_ENVIRON = bytes([39]) # New - Environment variables
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000117# the following ones come from
118# http://www.iana.org/assignments/telnet-options
119# Unfortunately, that document does not assign identifiers
120# to all of them, so we are making them up
Jack Diederich1c8f38c2009-04-10 05:33:26 +0000121TN3270E = bytes([40]) # TN3270E
122XAUTH = bytes([41]) # XAUTH
123CHARSET = bytes([42]) # CHARSET
124RSP = bytes([43]) # Telnet Remote Serial Port
125COM_PORT_OPTION = bytes([44]) # Com Port Control Option
126SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
127TLS = bytes([46]) # Telnet Start TLS
128KERMIT = bytes([47]) # KERMIT
129SEND_URL = bytes([48]) # SEND-URL
130FORWARD_X = bytes([49]) # FORWARD_X
131PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
132SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
133PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
134EXOPL = bytes([255]) # Extended-Options-List
135NOOPT = bytes([0])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000136
137class Telnet:
138
139 """Telnet interface class.
140
141 An instance of this class represents a connection to a telnet
142 server. The instance is initially not connected; the open()
143 method must be used to establish a connection. Alternatively, the
144 host name and optional port number can be passed to the
145 constructor, too.
146
147 Don't try to reopen an already connected instance.
148
149 This class has many read_*() methods. Note that some of them
150 raise EOFError when the end of the connection is read, because
151 they can return an empty string for other reasons. See the
152 individual doc strings.
153
154 read_until(expected, [timeout])
155 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000157
158 read_all()
159 Read all data until EOF; may block.
160
161 read_some()
162 Read at least one byte or EOF; may block.
163
164 read_very_eager()
165 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000167
168 read_eager()
169 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000171
172 read_lazy()
173 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000175
176 read_very_lazy()
177 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000179
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000180 read_sb_data()
181 Reads available data between SB ... SE sequence. Don't block.
182
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000183 set_option_negotiation_callback(callback)
184 Each time a telnet option is read on the input flow, this callback
185 (if set) is called with the following parameters :
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000186 callback(telnet socket, command, option)
187 option will be chr(0) when there is no option.
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000188 No other action is done afterwards by telnetlib.
189
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000190 """
191
Georg Brandlf78e02b2008-06-10 17:40:04 +0000192 def __init__(self, host=None, port=0,
193 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000195
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 When called without arguments, create an unconnected instance.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000197 With a hostname argument, it connects the instance; port number
198 and timeout are optional.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 """
200 self.debuglevel = DEBUGLEVEL
201 self.host = host
202 self.port = port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 self.sock = None
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000205 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 self.irawq = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000207 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 self.eof = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000209 self.iacseq = b'' # Buffer for IAC sequence.
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000210 self.sb = 0 # flag for SB and SE sequence.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000211 self.sbdataq = b''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000212 self.option_callback = None
Gregory P. Smithdad57112012-07-15 23:42:26 -0700213 self._has_poll = hasattr(select, 'poll')
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000214 if host is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000216
Georg Brandlf78e02b2008-06-10 17:40:04 +0000217 def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000219
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 The optional second argument is the port number, which
221 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000222
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 Don't try to reopen an already connected instance.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 """
225 self.eof = 0
226 if not port:
227 port = TELNET_PORT
228 self.host = host
229 self.port = port
Georg Brandlf78e02b2008-06-10 17:40:04 +0000230 self.timeout = timeout
231 self.sock = socket.create_connection((host, port), timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000232
233 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 """Destructor -- close the connection."""
235 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000236
237 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000238 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000239
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 If extra arguments are present, they are substituted in the
241 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000242
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 """
244 if self.debuglevel > 0:
R. David Murray32ef70c2010-12-14 14:16:20 +0000245 print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(msg % args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(msg)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000250
251 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000253
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000255
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 """
257 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000258
259 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 """Close the connection."""
261 if self.sock:
262 self.sock.close()
263 self.sock = 0
264 self.eof = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000265 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000266 self.sb = 0
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000267
268 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 """Return the socket object used internally."""
270 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000271
272 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 """Return the fileno() of the socket object used internally."""
274 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000275
276 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000277 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000278
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 Can block if the connection is blocked. May raise
280 socket.error if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000281
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000282 """
283 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000284 buffer = buffer.replace(IAC, IAC+IAC)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000285 self.msg("send %r", buffer)
Martin v. Löwise12454f2002-02-16 23:06:19 +0000286 self.sock.sendall(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000287
288 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000289 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000290
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000291 When no match is found, return whatever is available instead,
292 possibly the empty string. Raise EOFError if the connection
293 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000294
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 """
Gregory P. Smithdad57112012-07-15 23:42:26 -0700296 if self._has_poll:
297 return self._read_until_with_poll(match, timeout)
298 else:
299 return self._read_until_with_select(match, timeout)
300
301 def _read_until_with_poll(self, match, timeout):
302 """Read until a given string is encountered or until timeout.
303
304 This method uses select.poll() to implement the timeout.
305 """
306 n = len(match)
307 call_timeout = timeout
308 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200309 time_start = _time()
Gregory P. Smithdad57112012-07-15 23:42:26 -0700310 self.process_rawq()
311 i = self.cookedq.find(match)
312 if i < 0:
313 poller = select.poll()
314 poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
315 poller.register(self, poll_in_or_priority_flags)
316 while i < 0 and not self.eof:
317 try:
318 ready = poller.poll(call_timeout)
319 except select.error as e:
320 if e.errno == errno.EINTR:
321 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200322 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700323 call_timeout = timeout-elapsed
324 continue
325 raise
326 for fd, mode in ready:
327 if mode & poll_in_or_priority_flags:
328 i = max(0, len(self.cookedq)-n)
329 self.fill_rawq()
330 self.process_rawq()
331 i = self.cookedq.find(match, i)
332 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200333 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700334 if elapsed >= timeout:
335 break
336 call_timeout = timeout-elapsed
337 poller.unregister(self)
338 if i >= 0:
339 i = i + n
340 buf = self.cookedq[:i]
341 self.cookedq = self.cookedq[i:]
342 return buf
343 return self.read_very_lazy()
344
345 def _read_until_with_select(self, match, timeout=None):
346 """Read until a given string is encountered or until timeout.
347
348 The timeout is implemented using select.select().
349 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000350 n = len(match)
351 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000352 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000353 if i >= 0:
354 i = i+n
355 buf = self.cookedq[:i]
356 self.cookedq = self.cookedq[i:]
357 return buf
358 s_reply = ([self], [], [])
359 s_args = s_reply
360 if timeout is not None:
361 s_args = s_args + (timeout,)
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200362 time_start = _time()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000363 while not self.eof and select.select(*s_args) == s_reply:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 i = max(0, len(self.cookedq)-n)
365 self.fill_rawq()
366 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000367 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000368 if i >= 0:
369 i = i+n
370 buf = self.cookedq[:i]
371 self.cookedq = self.cookedq[i:]
372 return buf
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000373 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200374 elapsed = _time() - time_start
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000375 if elapsed >= timeout:
376 break
377 s_args = s_reply + (timeout-elapsed,)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000378 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000379
380 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 """Read all data until EOF; block until connection closed."""
382 self.process_rawq()
383 while not self.eof:
384 self.fill_rawq()
385 self.process_rawq()
386 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000387 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000388 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000389
390 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000392
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000393 Return b'' if EOF is hit. Block if no data is immediately
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000395
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 """
397 self.process_rawq()
398 while not self.cookedq and not self.eof:
399 self.fill_rawq()
400 self.process_rawq()
401 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000402 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000403 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000404
405 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000407
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000409 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000411
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000412 """
413 self.process_rawq()
414 while not self.eof and self.sock_avail():
415 self.fill_rawq()
416 self.process_rawq()
417 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000418
419 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000421
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000423 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000424 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000425
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 """
427 self.process_rawq()
428 while not self.cookedq and not self.eof and self.sock_avail():
429 self.fill_rawq()
430 self.process_rawq()
431 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000432
433 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000434 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000435
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000437 Return b'' if no cooked data available otherwise. Don't block
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000438 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000439
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000440 """
441 self.process_rawq()
442 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000443
444 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000446
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000447 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000448 Return b'' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000449
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 """
451 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000452 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000453 if not buf and self.eof and not self.rawq:
Collin Winterce36ad82007-08-30 01:19:48 +0000454 raise EOFError('telnet connection closed')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000455 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000456
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000457 def read_sb_data(self):
458 """Return any data available in the SB ... SE queue.
459
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000460 Return b'' if no SB ... SE available. Should only be called
Tim Peters230a60c2002-11-09 05:08:07 +0000461 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000462 found, old unread SB data will be discarded. Don't block.
463
464 """
465 buf = self.sbdataq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000466 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000467 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000468
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000469 def set_option_negotiation_callback(self, callback):
470 """Provide a callback function called after each receipt of a telnet option."""
471 self.option_callback = callback
472
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000473 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000474 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000475
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000476 Set self.eof when connection is closed. Don't block unless in
477 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000478
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000479 """
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000480 buf = [b'', b'']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000481 try:
482 while self.rawq:
483 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000484 if not self.iacseq:
485 if c == theNULL:
486 continue
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000487 if c == b"\021":
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000488 continue
489 if c != IAC:
490 buf[self.sb] = buf[self.sb] + c
491 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000492 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000493 self.iacseq += c
494 elif len(self.iacseq) == 1:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000495 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000496 if c in (DO, DONT, WILL, WONT):
497 self.iacseq += c
498 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000499
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000500 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000501 if c == IAC:
502 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000503 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000504 if c == SB: # SB ... SE start.
505 self.sb = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000506 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000507 elif c == SE:
508 self.sb = 0
509 self.sbdataq = self.sbdataq + buf[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000510 buf[1] = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000511 if self.option_callback:
512 # Callback is supposed to look into
513 # the sbdataq
514 self.option_callback(self.sock, c, NOOPT)
515 else:
516 # We can't offer automatic processing of
517 # suboptions. Alas, we should not get any
518 # unless we did a WILL/DO before.
519 self.msg('IAC %d not recognized' % ord(c))
520 elif len(self.iacseq) == 2:
Jack Diederich36596a32009-07-26 22:23:04 +0000521 cmd = self.iacseq[1:2]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000522 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000523 opt = c
524 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000525 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000526 cmd == DO and 'DO' or 'DONT', ord(opt))
527 if self.option_callback:
528 self.option_callback(self.sock, cmd, opt)
529 else:
530 self.sock.sendall(IAC + WONT + opt)
531 elif cmd in (WILL, WONT):
532 self.msg('IAC %s %d',
533 cmd == WILL and 'WILL' or 'WONT', ord(opt))
534 if self.option_callback:
535 self.option_callback(self.sock, cmd, opt)
536 else:
537 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000538 except EOFError: # raised by self.rawq_getchar()
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000539 self.iacseq = b'' # Reset on EOF
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000540 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000541 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000542 self.cookedq = self.cookedq + buf[0]
543 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000544
545 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000546 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000547
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000548 Block if no data is immediately available. Raise EOFError
549 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000550
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000551 """
552 if not self.rawq:
553 self.fill_rawq()
554 if self.eof:
555 raise EOFError
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000556 c = self.rawq[self.irawq:self.irawq+1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000557 self.irawq = self.irawq + 1
558 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000559 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000560 self.irawq = 0
561 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000562
563 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000564 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000565
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000566 Block if no data is immediately available. Set self.eof when
567 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000568
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000569 """
570 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000571 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000572 self.irawq = 0
573 # The buffer size should be fairly small so as to avoid quadratic
574 # behavior in process_rawq() above
575 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000576 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000577 self.eof = (not buf)
578 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000579
580 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000581 """Test whether data is available on the socket."""
582 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000583
584 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000585 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000586 if sys.platform == "win32":
587 self.mt_interact()
588 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000589 while 1:
590 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
591 if self in rfd:
592 try:
593 text = self.read_eager()
594 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000595 print('*** Connection closed by remote host ***')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000596 break
597 if text:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000598 sys.stdout.write(text.decode('ascii'))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000599 sys.stdout.flush()
600 if sys.stdin in rfd:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000601 line = sys.stdin.readline().encode('ascii')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000602 if not line:
603 break
604 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000605
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000606 def mt_interact(self):
607 """Multithreaded version of interact()."""
Georg Brandl2067bfd2008-05-25 13:05:15 +0000608 import _thread
609 _thread.start_new_thread(self.listener, ())
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000610 while 1:
611 line = sys.stdin.readline()
612 if not line:
613 break
R. David Murrayba488d12010-10-26 12:42:24 +0000614 self.write(line.encode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000615
616 def listener(self):
617 """Helper for mt_interact() -- this executes in the other thread."""
618 while 1:
619 try:
620 data = self.read_eager()
621 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000622 print('*** Connection closed by remote host ***')
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000623 return
624 if data:
R. David Murrayba488d12010-10-26 12:42:24 +0000625 sys.stdout.write(data.decode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000626 else:
627 sys.stdout.flush()
628
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000629 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000630 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000631
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000632 The first argument is a list of regular expressions, either
633 compiled (re.RegexObject instances) or uncompiled (strings).
634 The optional second argument is a timeout, in seconds; default
635 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000636
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000637 Return a tuple of three items: the index in the list of the
638 first regular expression that matches; the match object
639 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000640
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000641 If EOF is read and no text was read, raise EOFError.
642 Otherwise, when nothing matches, return (-1, None, text) where
643 text is the text received so far (may be the empty string if a
644 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000645
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000646 If a regular expression ends with a greedy match (e.g. '.*')
647 or if more than one expression can match the same input, the
648 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000649
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 """
Gregory P. Smithdad57112012-07-15 23:42:26 -0700651 if self._has_poll:
652 return self._expect_with_poll(list, timeout)
653 else:
654 return self._expect_with_select(list, timeout)
655
656 def _expect_with_poll(self, expect_list, timeout=None):
657 """Read until one from a list of a regular expressions matches.
658
659 This method uses select.poll() to implement the timeout.
660 """
661 re = None
662 expect_list = expect_list[:]
663 indices = range(len(expect_list))
664 for i in indices:
665 if not hasattr(expect_list[i], "search"):
666 if not re: import re
667 expect_list[i] = re.compile(expect_list[i])
668 call_timeout = timeout
669 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200670 time_start = _time()
Gregory P. Smithdad57112012-07-15 23:42:26 -0700671 self.process_rawq()
672 m = None
673 for i in indices:
674 m = expect_list[i].search(self.cookedq)
675 if m:
676 e = m.end()
677 text = self.cookedq[:e]
678 self.cookedq = self.cookedq[e:]
679 break
680 if not m:
681 poller = select.poll()
682 poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
683 poller.register(self, poll_in_or_priority_flags)
684 while not m and not self.eof:
685 try:
686 ready = poller.poll(call_timeout)
687 except select.error as e:
688 if e.errno == errno.EINTR:
689 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200690 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700691 call_timeout = timeout-elapsed
692 continue
693 raise
694 for fd, mode in ready:
695 if mode & poll_in_or_priority_flags:
696 self.fill_rawq()
697 self.process_rawq()
698 for i in indices:
699 m = expect_list[i].search(self.cookedq)
700 if m:
701 e = m.end()
702 text = self.cookedq[:e]
703 self.cookedq = self.cookedq[e:]
704 break
705 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200706 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700707 if elapsed >= timeout:
708 break
709 call_timeout = timeout-elapsed
710 poller.unregister(self)
711 if m:
712 return (i, m, text)
713 text = self.read_very_lazy()
714 if not text and self.eof:
715 raise EOFError
716 return (-1, None, text)
717
718 def _expect_with_select(self, list, timeout=None):
719 """Read until one from a list of a regular expressions matches.
720
721 The timeout is implemented using select.select().
722 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000723 re = None
724 list = list[:]
725 indices = range(len(list))
726 for i in indices:
727 if not hasattr(list[i], "search"):
728 if not re: import re
729 list[i] = re.compile(list[i])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000730 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200731 time_start = _time()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000732 while 1:
733 self.process_rawq()
734 for i in indices:
735 m = list[i].search(self.cookedq)
736 if m:
737 e = m.end()
738 text = self.cookedq[:e]
739 self.cookedq = self.cookedq[e:]
740 return (i, m, text)
741 if self.eof:
742 break
743 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200744 elapsed = _time() - time_start
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000745 if elapsed >= timeout:
746 break
747 s_args = ([self.fileno()], [], [], timeout-elapsed)
748 r, w, x = select.select(*s_args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000749 if not r:
750 break
751 self.fill_rawq()
752 text = self.read_very_lazy()
753 if not text and self.eof:
754 raise EOFError
755 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000756
757
758def test():
759 """Test program for telnetlib.
760
761 Usage: python telnetlib.py [-d] ... [host [port]]
762
763 Default host is localhost; default port is 23.
764
765 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000766 debuglevel = 0
767 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000768 debuglevel = debuglevel+1
769 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000770 host = 'localhost'
771 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000772 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000773 port = 0
774 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000775 portstr = sys.argv[2]
776 try:
777 port = int(portstr)
778 except ValueError:
779 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000780 tn = Telnet()
781 tn.set_debuglevel(debuglevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000782 tn.open(host, port, timeout=0.5)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000783 tn.interact()
784 tn.close()
785
786if __name__ == '__main__':
787 test()