negtelnetserver.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """ A telnet server which negotiates"""
  5. from __future__ import (absolute_import, division, print_function,
  6. unicode_literals)
  7. import argparse
  8. import os
  9. import sys
  10. import logging
  11. try: # Python 2
  12. import SocketServer as socketserver
  13. except ImportError: # Python 3
  14. import socketserver
  15. log = logging.getLogger(__name__)
  16. HOST = "localhost"
  17. IDENT = "NTEL"
  18. # The strings that indicate the test framework is checking our aliveness
  19. VERIFIED_REQ = "verifiedserver"
  20. VERIFIED_RSP = "WE ROOLZ: {pid}"
  21. def telnetserver(options):
  22. """
  23. Starts up a TCP server with a telnet handler and serves DICT requests
  24. forever.
  25. """
  26. if options.pidfile:
  27. pid = os.getpid()
  28. with open(options.pidfile, "w") as f:
  29. f.write(str(pid))
  30. local_bind = (HOST, options.port)
  31. log.info("Listening on %s", local_bind)
  32. # Need to set the allow_reuse on the class, not on the instance.
  33. socketserver.TCPServer.allow_reuse_address = True
  34. server = socketserver.TCPServer(local_bind, NegotiatingTelnetHandler)
  35. server.serve_forever()
  36. return ScriptRC.SUCCESS
  37. class NegotiatingTelnetHandler(socketserver.BaseRequestHandler):
  38. """Handler class for Telnet connections.
  39. """
  40. def handle(self):
  41. """
  42. Negotiates options before reading data.
  43. """
  44. neg = Negotiator(self.request)
  45. try:
  46. # Send some initial negotiations.
  47. neg.send_do("NEW_ENVIRON")
  48. neg.send_will("NEW_ENVIRON")
  49. neg.send_dont("NAWS")
  50. neg.send_wont("NAWS")
  51. # Get the data passed through the negotiator
  52. data = neg.recv(1024)
  53. log.debug("Incoming data: %r", data)
  54. if VERIFIED_REQ.encode('ascii') in data:
  55. log.debug("Received verification request from test framework")
  56. response = VERIFIED_RSP.format(pid=os.getpid())
  57. response_data = response.encode('ascii')
  58. else:
  59. log.debug("Received normal request - echoing back")
  60. response_data = data.strip()
  61. if response_data:
  62. log.debug("Sending %r", response_data)
  63. self.request.sendall(response_data)
  64. except IOError:
  65. log.exception("IOError hit during request")
  66. class Negotiator(object):
  67. NO_NEG = 0
  68. START_NEG = 1
  69. WILL = 2
  70. WONT = 3
  71. DO = 4
  72. DONT = 5
  73. def __init__(self, tcp):
  74. self.tcp = tcp
  75. self.state = self.NO_NEG
  76. def recv(self, bytes):
  77. """
  78. Read bytes from TCP, handling negotiation sequences
  79. :param bytes: Number of bytes to read
  80. :return: a buffer of bytes
  81. """
  82. buffer = bytearray()
  83. # If we keep receiving negotiation sequences, we won't fill the buffer.
  84. # Keep looping while we can, and until we have something to give back
  85. # to the caller.
  86. while len(buffer) == 0:
  87. data = self.tcp.recv(bytes)
  88. if not data:
  89. # TCP failed to give us any data. Break out.
  90. break
  91. for byte_int in bytearray(data):
  92. if self.state == self.NO_NEG:
  93. self.no_neg(byte_int, buffer)
  94. elif self.state == self.START_NEG:
  95. self.start_neg(byte_int)
  96. elif self.state in [self.WILL, self.WONT, self.DO, self.DONT]:
  97. self.handle_option(byte_int)
  98. else:
  99. # Received an unexpected byte. Stop negotiations
  100. log.error("Unexpected byte %s in state %s",
  101. byte_int,
  102. self.state)
  103. self.state = self.NO_NEG
  104. return buffer
  105. def no_neg(self, byte_int, buffer):
  106. # Not negotiating anything thus far. Check to see if we
  107. # should.
  108. if byte_int == NegTokens.IAC:
  109. # Start negotiation
  110. log.debug("Starting negotiation (IAC)")
  111. self.state = self.START_NEG
  112. else:
  113. # Just append the incoming byte to the buffer
  114. buffer.append(byte_int)
  115. def start_neg(self, byte_int):
  116. # In a negotiation.
  117. log.debug("In negotiation (%s)",
  118. NegTokens.from_val(byte_int))
  119. if byte_int == NegTokens.WILL:
  120. # Client is confirming they are willing to do an option
  121. log.debug("Client is willing")
  122. self.state = self.WILL
  123. elif byte_int == NegTokens.WONT:
  124. # Client is confirming they are unwilling to do an
  125. # option
  126. log.debug("Client is unwilling")
  127. self.state = self.WONT
  128. elif byte_int == NegTokens.DO:
  129. # Client is indicating they can do an option
  130. log.debug("Client can do")
  131. self.state = self.DO
  132. elif byte_int == NegTokens.DONT:
  133. # Client is indicating they can't do an option
  134. log.debug("Client can't do")
  135. self.state = self.DONT
  136. else:
  137. # Received an unexpected byte. Stop negotiations
  138. log.error("Unexpected byte %s in state %s",
  139. byte_int,
  140. self.state)
  141. self.state = self.NO_NEG
  142. def handle_option(self, byte_int):
  143. if byte_int in [NegOptions.BINARY,
  144. NegOptions.CHARSET,
  145. NegOptions.SUPPRESS_GO_AHEAD,
  146. NegOptions.NAWS,
  147. NegOptions.NEW_ENVIRON]:
  148. log.debug("Option: %s", NegOptions.from_val(byte_int))
  149. # No further negotiation of this option needed. Reset the state.
  150. self.state = self.NO_NEG
  151. else:
  152. # Received an unexpected byte. Stop negotiations
  153. log.error("Unexpected byte %s in state %s",
  154. byte_int,
  155. self.state)
  156. self.state = self.NO_NEG
  157. def send_message(self, message_ints):
  158. self.tcp.sendall(bytearray(message_ints))
  159. def send_iac(self, arr):
  160. message = [NegTokens.IAC]
  161. message.extend(arr)
  162. self.send_message(message)
  163. def send_do(self, option_str):
  164. log.debug("Sending DO %s", option_str)
  165. self.send_iac([NegTokens.DO, NegOptions.to_val(option_str)])
  166. def send_dont(self, option_str):
  167. log.debug("Sending DONT %s", option_str)
  168. self.send_iac([NegTokens.DONT, NegOptions.to_val(option_str)])
  169. def send_will(self, option_str):
  170. log.debug("Sending WILL %s", option_str)
  171. self.send_iac([NegTokens.WILL, NegOptions.to_val(option_str)])
  172. def send_wont(self, option_str):
  173. log.debug("Sending WONT %s", option_str)
  174. self.send_iac([NegTokens.WONT, NegOptions.to_val(option_str)])
  175. class NegBase(object):
  176. @classmethod
  177. def to_val(cls, name):
  178. return getattr(cls, name)
  179. @classmethod
  180. def from_val(cls, val):
  181. for k in cls.__dict__.keys():
  182. if getattr(cls, k) == val:
  183. return k
  184. return "<unknown>"
  185. class NegTokens(NegBase):
  186. # The start of a negotiation sequence
  187. IAC = 255
  188. # Confirm willingness to negotiate
  189. WILL = 251
  190. # Confirm unwillingness to negotiate
  191. WONT = 252
  192. # Indicate willingness to negotiate
  193. DO = 253
  194. # Indicate unwillingness to negotiate
  195. DONT = 254
  196. # The start of sub-negotiation options.
  197. SB = 250
  198. # The end of sub-negotiation options.
  199. SE = 240
  200. class NegOptions(NegBase):
  201. # Binary Transmission
  202. BINARY = 0
  203. # Suppress Go Ahead
  204. SUPPRESS_GO_AHEAD = 3
  205. # NAWS - width and height of client
  206. NAWS = 31
  207. # NEW-ENVIRON - environment variables on client
  208. NEW_ENVIRON = 39
  209. # Charset option
  210. CHARSET = 42
  211. def get_options():
  212. parser = argparse.ArgumentParser()
  213. parser.add_argument("--port", action="store", default=9019,
  214. type=int, help="port to listen on")
  215. parser.add_argument("--verbose", action="store", type=int, default=0,
  216. help="verbose output")
  217. parser.add_argument("--pidfile", action="store",
  218. help="file name for the PID")
  219. parser.add_argument("--logfile", action="store",
  220. help="file name for the log")
  221. parser.add_argument("--srcdir", action="store", help="test directory")
  222. parser.add_argument("--id", action="store", help="server ID")
  223. parser.add_argument("--ipv4", action="store_true", default=0,
  224. help="IPv4 flag")
  225. return parser.parse_args()
  226. def setup_logging(options):
  227. """
  228. Set up logging from the command line options
  229. """
  230. root_logger = logging.getLogger()
  231. add_stdout = False
  232. formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s "
  233. "[{ident}] %(message)s"
  234. .format(ident=IDENT))
  235. # Write out to a logfile
  236. if options.logfile:
  237. handler = logging.FileHandler(options.logfile, mode="w")
  238. handler.setFormatter(formatter)
  239. handler.setLevel(logging.DEBUG)
  240. root_logger.addHandler(handler)
  241. else:
  242. # The logfile wasn't specified. Add a stdout logger.
  243. add_stdout = True
  244. if options.verbose:
  245. # Add a stdout logger as well in verbose mode
  246. root_logger.setLevel(logging.DEBUG)
  247. add_stdout = True
  248. else:
  249. root_logger.setLevel(logging.INFO)
  250. if add_stdout:
  251. stdout_handler = logging.StreamHandler(sys.stdout)
  252. stdout_handler.setFormatter(formatter)
  253. stdout_handler.setLevel(logging.DEBUG)
  254. root_logger.addHandler(stdout_handler)
  255. class ScriptRC(object):
  256. """Enum for script return codes"""
  257. SUCCESS = 0
  258. FAILURE = 1
  259. EXCEPTION = 2
  260. class ScriptException(Exception):
  261. pass
  262. if __name__ == '__main__':
  263. # Get the options from the user.
  264. options = get_options()
  265. # Setup logging using the user options
  266. setup_logging(options)
  267. # Run main script.
  268. try:
  269. rc = telnetserver(options)
  270. except Exception as e:
  271. log.exception(e)
  272. rc = ScriptRC.EXCEPTION
  273. log.info("Returning %d", rc)
  274. sys.exit(rc)