negtelnetserver.py 11 KB

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