Debian Codegraph @

cpython27/Lib/test/ssl_servers.py

raw symbols SCIP
1 import os
2 import sys
3 import ssl
4 import pprint
5 import urllib
6 import urlparse
7 # Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer.
8 from BaseHTTPServer import HTTPServer as _HTTPServer, BaseHTTPRequestHandler
9 from SimpleHTTPServer import SimpleHTTPRequestHandler
10
11 from test import test_support as support
12 threading = support.import_module("threading")
13
14 here = os.path.dirname(__file__)
15
16 HOST = support.HOST
17 CERTFILE = os.path.join(here, 'keycert.pem')
18
19 # This one's based on HTTPServer, which is based on SocketServer
20
21 class HTTPSServer(_HTTPServer):
22
23 def __init__(self, server_address, handler_class, context):
24 _HTTPServer.__init__(self, server_address, handler_class)
25 self.context = context
26
27 def __str__(self):
28 return ('<%s %s:%s>' %
29 (self.__class__.__name__,
30 self.server_name,
31 self.server_port))
32
33 def get_request(self):
34 # override this to wrap socket with SSL
35 try:
36 sock, addr = self.socket.accept()
37 sslconn = self.context.wrap_socket(sock, server_side=True)
38 except OSError as e:
39 # socket errors are silenced by the caller, print them here
40 if support.verbose:
41 sys.stderr.write("Got an error:\n%s\n" % e)
42 raise
43 return sslconn, addr
44
45 def handle_error(self, request, client_address):
46 "Suppose noisy error output by default."
47 if support.verbose:
48 _HTTPServer.handle_error(self, request, client_address)
49
50 class RootedHTTPRequestHandler(SimpleHTTPRequestHandler):
51 # need to override translate_path to get a known root,
52 # instead of using os.curdir, since the test could be
53 # run from anywhere
54
55 server_version = "TestHTTPS/1.0"
56 root = here
57 # Avoid hanging when a request gets interrupted by the client
58 timeout = 5
59
60 def translate_path(self, path):
61 """Translate a /-separated PATH to the local filename syntax.
62
63 Components that mean special things to the local file system
64 (e.g. drive or directory names) are ignored. (XXX They should
65 probably be diagnosed.)
66
67 """
68 # abandon query parameters
69 path = urlparse.urlparse(path)[2]
70 path = os.path.normpath(urllib.unquote(path))
71 words = path.split('/')
72 words = filter(None, words)
73 path = self.root
74 for word in words:
75 drive, word = os.path.splitdrive(word)
76 head, word = os.path.split(word)
77 path = os.path.join(path, word)
78 return path
79
80 def log_message(self, format, *args):
81 # we override this to suppress logging unless "verbose"
82 if support.verbose:
83 sys.stdout.write(" server (%s:%d %s):\n [%s] %s\n" %
84 (self.server.server_address,
85 self.server.server_port,
86 self.request.cipher(),
87 self.log_date_time_string(),
88 format%args))
89
90
91 class StatsRequestHandler(BaseHTTPRequestHandler):
92 """Example HTTP request handler which returns SSL statistics on GET
93 requests.
94 """
95
96 server_version = "StatsHTTPS/1.0"
97
98 def do_GET(self, send_body=True):
99 """Serve a GET request."""
100 sock = self.rfile.raw._sock
101 context = sock.context
102 stats = {
103 'session_cache': context.session_stats(),
104 'cipher': sock.cipher(),
105 'compression': sock.compression(),
106 }
107 body = pprint.pformat(stats)
108 body = body.encode('utf-8')
109 self.send_response(200)
110 self.send_header("Content-type", "text/plain; charset=utf-8")
111 self.send_header("Content-Length", str(len(body)))
112 self.end_headers()
113 if send_body:
114 self.wfile.write(body)
115
116 def do_HEAD(self):
117 """Serve a HEAD request."""
118 self.do_GET(send_body=False)
119
120 def log_request(self, format, *args):
121 if support.verbose:
122 BaseHTTPRequestHandler.log_request(self, format, *args)
123
124
125 class HTTPSServerThread(threading.Thread):
126
127 def __init__(self, context, host=HOST, handler_class=None):
128 self.flag = None
129 self.server = HTTPSServer((host, 0),
130 handler_class or RootedHTTPRequestHandler,
131 context)
132 self.port = self.server.server_port
133 threading.Thread.__init__(self)
134 self.daemon = True
135
136 def __str__(self):
137 return "<%s %s>" % (self.__class__.__name__, self.server)
138
139 def start(self, flag=None):
140 self.flag = flag
141 threading.Thread.start(self)
142
143 def run(self):
144 if self.flag:
145 self.flag.set()
146 try:
147 self.server.serve_forever(0.05)
148 finally:
149 self.server.server_close()
150
151 def stop(self):
152 self.server.shutdown()
153
154
155 def make_https_server(case, context=None, certfile=CERTFILE,
156 host=HOST, handler_class=None):
157 if context is None:
158 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
159 # We assume the certfile contains both private key and certificate
160 context.load_cert_chain(certfile)
161 server = HTTPSServerThread(context, host, handler_class)
162 flag = threading.Event()
163 server.start(flag)
164 flag.wait()
165 def cleanup():
166 if support.verbose:
167 sys.stdout.write('stopping HTTPS server\n')
168 server.stop()
169 if support.verbose:
170 sys.stdout.write('joining HTTPS thread\n')
171 server.join()
172 case.addCleanup(cleanup)
173 return server
174
175
176 if __name__ == "__main__":
177 import argparse
178 parser = argparse.ArgumentParser(
179 description='Run a test HTTPS server. '
180 'By default, the current directory is served.')
181 parser.add_argument('-p', '--port', type=int, default=4433,
182 help='port to listen on (default: %(default)s)')
183 parser.add_argument('-q', '--quiet', dest='verbose', default=True,
184 action='store_false', help='be less verbose')
185 parser.add_argument('-s', '--stats', dest='use_stats_handler', default=False,
186 action='store_true', help='always return stats page')
187 parser.add_argument('--curve-name', dest='curve_name', type=str,
188 action='store',
189 help='curve name for EC-based Diffie-Hellman')
190 parser.add_argument('--ciphers', dest='ciphers', type=str,
191 help='allowed cipher list')
192 parser.add_argument('--dh', dest='dh_file', type=str, action='store',
193 help='PEM file containing DH parameters')
194 args = parser.parse_args()
195
196 support.verbose = args.verbose
197 if args.use_stats_handler:
198 handler_class = StatsRequestHandler
199 else:
200 handler_class = RootedHTTPRequestHandler
201 handler_class.root = os.getcwd()
202 context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
203 context.load_cert_chain(CERTFILE)
204 if args.curve_name:
205 context.set_ecdh_curve(args.curve_name)
206 if args.dh_file:
207 context.load_dh_params(args.dh_file)
208 if args.ciphers:
209 context.set_ciphers(args.ciphers)
210
211 server = HTTPSServer(("", args.port), handler_class, context)
212 if args.verbose:
213 print("Listening on https://localhost:{0.port}".format(args))
214 server.serve_forever(0.1)