2 # -*- coding: utf-8 -*-
3 #***************************************************************************
5 # Project ___| | | | _ \| |
7 # | (__| |_| | _ <| |___
8 # \___|\___/|_| \_\_____|
10 # Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
20 # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21 # KIND, either express or implied.
23 # SPDX-License-Identifier: curl
25 ###########################################################################
29 from __future__ import (absolute_import, division, print_function,
37 from util import ClosingFileHandler
40 import SocketServer as socketserver
41 except ImportError: # Python 3
44 log = logging.getLogger(__name__)
47 # The strings that indicate the test framework is checking our aliveness
48 VERIFIED_REQ = b"verifiedserver"
49 VERIFIED_RSP = "WE ROOLZ: {pid}"
52 def dictserver(options):
54 Starts up a TCP server with a DICT handler and serves DICT requests
59 # see tests/server/util.c function write_pidfile
62 with open(options.pidfile, "w") as f:
65 local_bind = (options.host, options.port)
66 log.info("[DICT] Listening on %s", local_bind)
68 # Need to set the allow_reuse on the class, not on the instance.
69 socketserver.TCPServer.allow_reuse_address = True
70 server = socketserver.TCPServer(local_bind, DictHandler)
71 server.serve_forever()
73 return ScriptRC.SUCCESS
76 class DictHandler(socketserver.BaseRequestHandler):
77 """Handler class for DICT connections.
82 Simple function which responds to all queries with a 552.
85 # First, send a response to allow the server to continue.
86 rsp = "220 dictserver <xnooptions> <msgid@msgid>\n"
87 self.request.sendall(rsp.encode("utf-8"))
89 # Receive the request.
90 data = self.request.recv(1024).strip()
91 log.debug("[DICT] Incoming data: %r", data)
93 if VERIFIED_REQ in data:
94 log.debug("[DICT] Received verification request from test "
97 # see tests/server/util.c function write_pidfile
100 response_data = VERIFIED_RSP.format(pid=pid)
102 log.debug("[DICT] Received normal request")
103 response_data = "No matches"
105 # Send back a failure to find.
106 response = "552 {0}\n".format(response_data)
107 log.debug("[DICT] Responding with %r", response)
108 self.request.sendall(response.encode("utf-8"))
111 log.exception("[DICT] IOError hit during request")
115 parser = argparse.ArgumentParser()
117 parser.add_argument("--port", action="store", default=9016,
118 type=int, help="port to listen on")
119 parser.add_argument("--host", action="store", default=HOST,
120 help="host to listen on")
121 parser.add_argument("--verbose", action="store", type=int, default=0,
122 help="verbose output")
123 parser.add_argument("--pidfile", action="store",
124 help="file name for the PID")
125 parser.add_argument("--logfile", action="store",
126 help="file name for the log")
127 parser.add_argument("--srcdir", action="store", help="test directory")
128 parser.add_argument("--id", action="store", help="server ID")
129 parser.add_argument("--ipv4", action="store_true", default=0,
132 return parser.parse_args()
135 def setup_logging(options):
137 Set up logging from the command line options
139 root_logger = logging.getLogger()
142 formatter = logging.Formatter("%(asctime)s %(levelname)-5.5s %(message)s")
144 # Write out to a logfile
146 handler = ClosingFileHandler(options.logfile)
147 handler.setFormatter(formatter)
148 handler.setLevel(logging.DEBUG)
149 root_logger.addHandler(handler)
151 # The logfile wasn't specified. Add a stdout logger.
155 # Add a stdout logger as well in verbose mode
156 root_logger.setLevel(logging.DEBUG)
159 root_logger.setLevel(logging.INFO)
162 stdout_handler = logging.StreamHandler(sys.stdout)
163 stdout_handler.setFormatter(formatter)
164 stdout_handler.setLevel(logging.DEBUG)
165 root_logger.addHandler(stdout_handler)
168 class ScriptRC(object):
169 """Enum for script return codes"""
175 class ScriptException(Exception):
179 if __name__ == '__main__':
180 # Get the options from the user.
181 options = get_options()
183 # Setup logging using the user options
184 setup_logging(options)
188 rc = dictserver(options)
189 except Exception as e:
191 rc = ScriptRC.EXCEPTION
193 if options.pidfile and os.path.isfile(options.pidfile):
194 os.unlink(options.pidfile)
196 log.info("[DICT] Returning %d", rc)