2
0

dictserver.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #***************************************************************************
  4. # _ _ ____ _
  5. # Project ___| | | | _ \| |
  6. # / __| | | | |_) | |
  7. # | (__| |_| | _ <| |___
  8. # \___|\___/|_| \_\_____|
  9. #
  10. # Copyright (C) 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. # SPDX-License-Identifier: curl
  24. #
  25. ###########################################################################
  26. #
  27. """DICT server."""
  28. from __future__ import (absolute_import, division, print_function,
  29. unicode_literals)
  30. import argparse
  31. import logging
  32. import os
  33. import sys
  34. from util import ClosingFileHandler
  35. try: # Python 2
  36. import SocketServer as socketserver # type: ignore
  37. except ImportError: # Python 3
  38. import socketserver
  39. log = logging.getLogger(__name__)
  40. HOST = "localhost"
  41. # The strings that indicate the test framework is checking our aliveness
  42. VERIFIED_REQ = b"verifiedserver"
  43. VERIFIED_RSP = "WE ROOLZ: {pid}"
  44. def dictserver(options):
  45. """Start up a TCP server with a DICT handler and serve DICT requests forever."""
  46. if options.pidfile:
  47. pid = os.getpid()
  48. # see tests/server/util.c function write_pidfile
  49. if os.name == "nt":
  50. pid += 65536
  51. with open(options.pidfile, "w") as f:
  52. f.write(str(pid))
  53. local_bind = (options.host, options.port)
  54. log.info("[DICT] Listening on %s", local_bind)
  55. # Need to set the allow_reuse on the class, not on the instance.
  56. socketserver.TCPServer.allow_reuse_address = True
  57. server = socketserver.TCPServer(local_bind, DictHandler)
  58. server.serve_forever()
  59. return ScriptRC.SUCCESS
  60. class DictHandler(socketserver.BaseRequestHandler):
  61. """Handler class for DICT connections."""
  62. def handle(self):
  63. """Respond to all queries with a 552."""
  64. try:
  65. # First, send a response to allow the server to continue.
  66. rsp = "220 dictserver <xnooptions> <msgid@msgid>\n"
  67. self.request.sendall(rsp.encode("utf-8"))
  68. # Receive the request.
  69. data = self.request.recv(1024).strip()
  70. log.debug("[DICT] Incoming data: %r", data)
  71. if VERIFIED_REQ in data:
  72. log.debug("[DICT] Received verification request from test "
  73. "framework")
  74. pid = os.getpid()
  75. # see tests/server/util.c function write_pidfile
  76. if os.name == "nt":
  77. pid += 65536
  78. response_data = VERIFIED_RSP.format(pid=pid)
  79. else:
  80. log.debug("[DICT] Received normal request")
  81. response_data = "No matches"
  82. # Send back a failure to find.
  83. response = "552 {0}\n".format(response_data)
  84. log.debug("[DICT] Responding with %r", response)
  85. self.request.sendall(response.encode("utf-8"))
  86. except IOError:
  87. log.exception("[DICT] IOError hit during request")
  88. def get_options():
  89. parser = argparse.ArgumentParser()
  90. parser.add_argument("--port", action="store", default=9016,
  91. type=int, help="port to listen on")
  92. parser.add_argument("--host", action="store", default=HOST,
  93. help="host to listen on")
  94. parser.add_argument("--verbose", action="store", type=int, default=0,
  95. help="verbose output")
  96. parser.add_argument("--pidfile", action="store",
  97. help="file name for the PID")
  98. parser.add_argument("--logfile", action="store",
  99. help="file name for the log")
  100. parser.add_argument("--srcdir", action="store", help="test directory")
  101. parser.add_argument("--id", action="store", help="server ID")
  102. parser.add_argument("--ipv4", action="store_true", default=0,
  103. help="IPv4 flag")
  104. return parser.parse_args()
  105. def setup_logging(options):
  106. """Set up logging from the command line options."""
  107. root_logger = logging.getLogger()
  108. add_stdout = False
  109. formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
  110. # Write out to a logfile
  111. if options.logfile:
  112. handler = ClosingFileHandler(options.logfile)
  113. handler.setFormatter(formatter)
  114. handler.setLevel(logging.DEBUG)
  115. root_logger.addHandler(handler)
  116. else:
  117. # The logfile wasn't specified. Add a stdout logger.
  118. add_stdout = True
  119. if options.verbose:
  120. # Add a stdout logger as well in verbose mode
  121. root_logger.setLevel(logging.DEBUG)
  122. add_stdout = True
  123. else:
  124. root_logger.setLevel(logging.INFO)
  125. if add_stdout:
  126. stdout_handler = logging.StreamHandler(sys.stdout)
  127. stdout_handler.setFormatter(formatter)
  128. stdout_handler.setLevel(logging.DEBUG)
  129. root_logger.addHandler(stdout_handler)
  130. class ScriptRC(object):
  131. """Enum for script return codes."""
  132. SUCCESS = 0
  133. FAILURE = 1
  134. EXCEPTION = 2
  135. if __name__ == '__main__':
  136. # Get the options from the user.
  137. options = get_options()
  138. # Setup logging using the user options
  139. setup_logging(options)
  140. # Run main script.
  141. try:
  142. rc = dictserver(options)
  143. except Exception:
  144. log.exception('Error running server')
  145. rc = ScriptRC.EXCEPTION
  146. if options.pidfile and os.path.isfile(options.pidfile):
  147. os.unlink(options.pidfile)
  148. log.info("[DICT] Returning %d", rc)
  149. sys.exit(rc)