dictserver.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #***************************************************************************
  4. # _ _ ____ _
  5. # Project ___| | | | _ \| |
  6. # / __| | | | |_) | |
  7. # | (__| |_| | _ <| |___
  8. # \___|\___/|_| \_\_____|
  9. #
  10. # Copyright (C) 2008 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
  11. #
  12. # This software is licensed as described in the file COPYING, which
  13. # you should have received as part of this distribution. The terms
  14. # are also available at https://curl.se/docs/copyright.html.
  15. #
  16. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  17. # copies of the Software, and permit persons to whom the Software is
  18. # furnished to do so, under the terms of the COPYING file.
  19. #
  20. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  21. # KIND, either express or implied.
  22. #
  23. ###########################################################################
  24. #
  25. """ DICT server """
  26. from __future__ import (absolute_import, division, print_function,
  27. unicode_literals)
  28. import argparse
  29. import logging
  30. import os
  31. import sys
  32. from util import ClosingFileHandler
  33. try: # Python 2
  34. import SocketServer as socketserver
  35. except ImportError: # Python 3
  36. import socketserver
  37. log = logging.getLogger(__name__)
  38. HOST = "localhost"
  39. # The strings that indicate the test framework is checking our aliveness
  40. VERIFIED_REQ = b"verifiedserver"
  41. VERIFIED_RSP = "WE ROOLZ: {pid}"
  42. def dictserver(options):
  43. """
  44. Starts up a TCP server with a DICT 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 = (options.host, options.port)
  55. log.info("[DICT] 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, DictHandler)
  59. server.serve_forever()
  60. return ScriptRC.SUCCESS
  61. class DictHandler(socketserver.BaseRequestHandler):
  62. """Handler class for DICT connections.
  63. """
  64. def handle(self):
  65. """
  66. Simple function which responds to all queries with a 552.
  67. """
  68. try:
  69. # First, send a response to allow the server to continue.
  70. rsp = "220 dictserver <xnooptions> <msgid@msgid>\n"
  71. self.request.sendall(rsp.encode("utf-8"))
  72. # Receive the request.
  73. data = self.request.recv(1024).strip()
  74. log.debug("[DICT] Incoming data: %r", data)
  75. if VERIFIED_REQ in data:
  76. log.debug("[DICT] Received verification request from test "
  77. "framework")
  78. pid = os.getpid()
  79. # see tests/server/util.c function write_pidfile
  80. if os.name == "nt":
  81. pid += 65536
  82. response_data = VERIFIED_RSP.format(pid=pid)
  83. else:
  84. log.debug("[DICT] Received normal request")
  85. response_data = "No matches"
  86. # Send back a failure to find.
  87. response = "552 {0}\n".format(response_data)
  88. log.debug("[DICT] Responding with %r", response)
  89. self.request.sendall(response.encode("utf-8"))
  90. except IOError:
  91. log.exception("[DICT] IOError hit during request")
  92. def get_options():
  93. parser = argparse.ArgumentParser()
  94. parser.add_argument("--port", action="store", default=9016,
  95. type=int, help="port to listen on")
  96. parser.add_argument("--host", action="store", default=HOST,
  97. help="host to listen on")
  98. parser.add_argument("--verbose", action="store", type=int, default=0,
  99. help="verbose output")
  100. parser.add_argument("--pidfile", action="store",
  101. help="file name for the PID")
  102. parser.add_argument("--logfile", action="store",
  103. help="file name for the log")
  104. parser.add_argument("--srcdir", action="store", help="test directory")
  105. parser.add_argument("--id", action="store", help="server ID")
  106. parser.add_argument("--ipv4", action="store_true", default=0,
  107. help="IPv4 flag")
  108. return parser.parse_args()
  109. def setup_logging(options):
  110. """
  111. Set up logging from the command line options
  112. """
  113. root_logger = logging.getLogger()
  114. add_stdout = False
  115. formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
  116. # Write out to a logfile
  117. if options.logfile:
  118. handler = ClosingFileHandler(options.logfile)
  119. handler.setFormatter(formatter)
  120. handler.setLevel(logging.DEBUG)
  121. root_logger.addHandler(handler)
  122. else:
  123. # The logfile wasn't specified. Add a stdout logger.
  124. add_stdout = True
  125. if options.verbose:
  126. # Add a stdout logger as well in verbose mode
  127. root_logger.setLevel(logging.DEBUG)
  128. add_stdout = True
  129. else:
  130. root_logger.setLevel(logging.INFO)
  131. if add_stdout:
  132. stdout_handler = logging.StreamHandler(sys.stdout)
  133. stdout_handler.setFormatter(formatter)
  134. stdout_handler.setLevel(logging.DEBUG)
  135. root_logger.addHandler(stdout_handler)
  136. class ScriptRC(object):
  137. """Enum for script return codes"""
  138. SUCCESS = 0
  139. FAILURE = 1
  140. EXCEPTION = 2
  141. class ScriptException(Exception):
  142. pass
  143. if __name__ == '__main__':
  144. # Get the options from the user.
  145. options = get_options()
  146. # Setup logging using the user options
  147. setup_logging(options)
  148. # Run main script.
  149. try:
  150. rc = dictserver(options)
  151. except Exception as e:
  152. log.exception(e)
  153. rc = ScriptRC.EXCEPTION
  154. log.info("[DICT] Returning %d", rc)
  155. sys.exit(rc)