dictserver.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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.haxx.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 os
  30. import sys
  31. import logging
  32. try: # Python 2
  33. import SocketServer as socketserver
  34. except ImportError: # Python 3
  35. import socketserver
  36. log = logging.getLogger(__name__)
  37. HOST = "localhost"
  38. # The strings that indicate the test framework is checking our aliveness
  39. VERIFIED_REQ = b"verifiedserver"
  40. VERIFIED_RSP = "WE ROOLZ: {pid}"
  41. def dictserver(options):
  42. """
  43. Starts up a TCP server with a DICT handler and serves DICT requests
  44. forever.
  45. """
  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. """
  63. def handle(self):
  64. """
  65. Simple function which responds to all queries with a 552.
  66. """
  67. try:
  68. # First, send a response to allow the server to continue.
  69. rsp = "220 dictserver <xnooptions> <msgid@msgid>\n"
  70. self.request.sendall(rsp.encode("utf-8"))
  71. # Receive the request.
  72. data = self.request.recv(1024).strip()
  73. log.debug("[DICT] Incoming data: %r", data)
  74. if VERIFIED_REQ in data:
  75. log.debug("[DICT] Received verification request from test "
  76. "framework")
  77. pid = os.getpid()
  78. # see tests/server/util.c function write_pidfile
  79. if os.name == "nt":
  80. pid += 65536
  81. response_data = VERIFIED_RSP.format(pid=pid)
  82. else:
  83. log.debug("[DICT] Received normal request")
  84. response_data = "No matches"
  85. # Send back a failure to find.
  86. response = "552 {0}\n".format(response_data)
  87. log.debug("[DICT] Responding with %r", response)
  88. self.request.sendall(response.encode("utf-8"))
  89. except IOError:
  90. log.exception("[DICT] IOError hit during request")
  91. def get_options():
  92. parser = argparse.ArgumentParser()
  93. parser.add_argument("--port", action="store", default=9016,
  94. type=int, help="port to listen on")
  95. parser.add_argument("--host", action="store", default=HOST,
  96. help="host to listen on")
  97. parser.add_argument("--verbose", action="store", type=int, default=0,
  98. help="verbose output")
  99. parser.add_argument("--pidfile", action="store",
  100. help="file name for the PID")
  101. parser.add_argument("--logfile", action="store",
  102. help="file name for the log")
  103. parser.add_argument("--srcdir", action="store", help="test directory")
  104. parser.add_argument("--id", action="store", help="server ID")
  105. parser.add_argument("--ipv4", action="store_true", default=0,
  106. help="IPv4 flag")
  107. return parser.parse_args()
  108. def setup_logging(options):
  109. """
  110. Set up logging from the command line options
  111. """
  112. root_logger = logging.getLogger()
  113. add_stdout = False
  114. formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
  115. # Write out to a logfile
  116. if options.logfile:
  117. handler = logging.FileHandler(options.logfile, mode="w")
  118. handler.setFormatter(formatter)
  119. handler.setLevel(logging.DEBUG)
  120. root_logger.addHandler(handler)
  121. else:
  122. # The logfile wasn't specified. Add a stdout logger.
  123. add_stdout = True
  124. if options.verbose:
  125. # Add a stdout logger as well in verbose mode
  126. root_logger.setLevel(logging.DEBUG)
  127. add_stdout = True
  128. else:
  129. root_logger.setLevel(logging.INFO)
  130. if add_stdout:
  131. stdout_handler = logging.StreamHandler(sys.stdout)
  132. stdout_handler.setFormatter(formatter)
  133. stdout_handler.setLevel(logging.DEBUG)
  134. root_logger.addHandler(stdout_handler)
  135. class ScriptRC(object):
  136. """Enum for script return codes"""
  137. SUCCESS = 0
  138. FAILURE = 1
  139. EXCEPTION = 2
  140. class ScriptException(Exception):
  141. pass
  142. if __name__ == '__main__':
  143. # Get the options from the user.
  144. options = get_options()
  145. # Setup logging using the user options
  146. setup_logging(options)
  147. # Run main script.
  148. try:
  149. rc = dictserver(options)
  150. except Exception as e:
  151. log.exception(e)
  152. rc = ScriptRC.EXCEPTION
  153. log.info("[DICT] Returning %d", rc)
  154. sys.exit(rc)