2
0

negtelnetserver.py 11 KB

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