Debian Codegraph @

lib-python/3/test/test_httpservers.py

raw symbols SCIP
1 """Unittests for the various HTTPServer modules.
2
3 Written by Cody A.W. Somerville <[email protected]>,
4 Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
5 """
6 from collections import OrderedDict
7 from http.server import BaseHTTPRequestHandler, HTTPServer, \
8 SimpleHTTPRequestHandler, CGIHTTPRequestHandler
9 from http import server, HTTPStatus
10
11 import os
12 import socket
13 import sys
14 import re
15 import base64
16 import ntpath
17 import pathlib
18 import shutil
19 import email.message
20 import email.utils
21 import html
22 import http, http.client
23 import urllib.parse
24 import tempfile
25 import time
26 import datetime
27 import threading
28 from unittest import mock
29 from io import BytesIO, StringIO
30
31 import unittest
32 from test import support
33 from test.support import os_helper
34 from test.support import threading_helper
35
36 support.requires_working_socket(module=True)
37
38 class NoLogRequestHandler:
39 def log_message(self, *args):
40 # don't write log messages to stderr
41 pass
42
43 def read(self, n=None):
44 return ''
45
46
47 class TestServerThread(threading.Thread):
48 def __init__(self, test_object, request_handler):
49 threading.Thread.__init__(self)
50 self.request_handler = request_handler
51 self.test_object = test_object
52
53 def run(self):
54 self.server = HTTPServer(('localhost', 0), self.request_handler)
55 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
56 self.test_object.server_started.set()
57 self.test_object = None
58 try:
59 self.server.serve_forever(0.05)
60 finally:
61 self.server.server_close()
62
63 def stop(self):
64 self.server.shutdown()
65 self.join()
66
67
68 class BaseTestCase(unittest.TestCase):
69 def setUp(self):
70 self._threads = threading_helper.threading_setup()
71 os.environ = os_helper.EnvironmentVarGuard()
72 self.server_started = threading.Event()
73 self.thread = TestServerThread(self, self.request_handler)
74 self.thread.start()
75 self.server_started.wait()
76
77 def tearDown(self):
78 self.thread.stop()
79 self.thread = None
80 os.environ.__exit__()
81 threading_helper.threading_cleanup(*self._threads)
82
83 def request(self, uri, method='GET', body=None, headers={}):
84 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
85 self.connection.request(method, uri, body, headers)
86 return self.connection.getresponse()
87
88
89 class BaseHTTPServerTestCase(BaseTestCase):
90 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
91 protocol_version = 'HTTP/1.1'
92 default_request_version = 'HTTP/1.1'
93
94 def do_TEST(self):
95 self.send_response(HTTPStatus.NO_CONTENT)
96 self.send_header('Content-Type', 'text/html')
97 self.send_header('Connection', 'close')
98 self.end_headers()
99
100 def do_KEEP(self):
101 self.send_response(HTTPStatus.NO_CONTENT)
102 self.send_header('Content-Type', 'text/html')
103 self.send_header('Connection', 'keep-alive')
104 self.end_headers()
105
106 def do_KEYERROR(self):
107 self.send_error(999)
108
109 def do_NOTFOUND(self):
110 self.send_error(HTTPStatus.NOT_FOUND)
111
112 def do_EXPLAINERROR(self):
113 self.send_error(999, "Short Message",
114 "This is a long \n explanation")
115
116 def do_CUSTOM(self):
117 self.send_response(999)
118 self.send_header('Content-Type', 'text/html')
119 self.send_header('Connection', 'close')
120 self.end_headers()
121
122 def do_LATINONEHEADER(self):
123 self.send_response(999)
124 self.send_header('X-Special', 'Dängerous Mind')
125 self.send_header('Connection', 'close')
126 self.end_headers()
127 body = self.headers['x-special-incoming'].encode('utf-8')
128 self.wfile.write(body)
129
130 def do_SEND_ERROR(self):
131 self.send_error(int(self.path[1:]))
132
133 def do_HEAD(self):
134 self.send_error(int(self.path[1:]))
135
136 def setUp(self):
137 BaseTestCase.setUp(self)
138 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
139 self.con.connect()
140
141 def test_command(self):
142 self.con.request('GET', '/')
143 res = self.con.getresponse()
144 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
145
146 def test_request_line_trimming(self):
147 self.con._http_vsn_str = 'HTTP/1.1\n'
148 self.con.putrequest('XYZBOGUS', '/')
149 self.con.endheaders()
150 res = self.con.getresponse()
151 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
152
153 def test_version_bogus(self):
154 self.con._http_vsn_str = 'FUBAR'
155 self.con.putrequest('GET', '/')
156 self.con.endheaders()
157 res = self.con.getresponse()
158 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
159
160 def test_version_digits(self):
161 self.con._http_vsn_str = 'HTTP/9.9.9'
162 self.con.putrequest('GET', '/')
163 self.con.endheaders()
164 res = self.con.getresponse()
165 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
166
167 def test_version_signs_and_underscores(self):
168 self.con._http_vsn_str = 'HTTP/-9_9_9.+9_9_9'
169 self.con.putrequest('GET', '/')
170 self.con.endheaders()
171 res = self.con.getresponse()
172 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
173
174 def test_major_version_number_too_long(self):
175 self.con._http_vsn_str = 'HTTP/909876543210.0'
176 self.con.putrequest('GET', '/')
177 self.con.endheaders()
178 res = self.con.getresponse()
179 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
180
181 def test_minor_version_number_too_long(self):
182 self.con._http_vsn_str = 'HTTP/1.909876543210'
183 self.con.putrequest('GET', '/')
184 self.con.endheaders()
185 res = self.con.getresponse()
186 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
187
188 def test_version_none_get(self):
189 self.con._http_vsn_str = ''
190 self.con.putrequest('GET', '/')
191 self.con.endheaders()
192 res = self.con.getresponse()
193 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
194
195 def test_version_none(self):
196 # Test that a valid method is rejected when not HTTP/1.x
197 self.con._http_vsn_str = ''
198 self.con.putrequest('CUSTOM', '/')
199 self.con.endheaders()
200 res = self.con.getresponse()
201 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
202
203 def test_version_invalid(self):
204 self.con._http_vsn = 99
205 self.con._http_vsn_str = 'HTTP/9.9'
206 self.con.putrequest('GET', '/')
207 self.con.endheaders()
208 res = self.con.getresponse()
209 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
210
211 def test_send_blank(self):
212 self.con._http_vsn_str = ''
213 self.con.putrequest('', '')
214 self.con.endheaders()
215 res = self.con.getresponse()
216 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
217
218 def test_header_close(self):
219 self.con.putrequest('GET', '/')
220 self.con.putheader('Connection', 'close')
221 self.con.endheaders()
222 res = self.con.getresponse()
223 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
224
225 def test_header_keep_alive(self):
226 self.con._http_vsn_str = 'HTTP/1.1'
227 self.con.putrequest('GET', '/')
228 self.con.putheader('Connection', 'keep-alive')
229 self.con.endheaders()
230 res = self.con.getresponse()
231 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
232
233 def test_handler(self):
234 self.con.request('TEST', '/')
235 res = self.con.getresponse()
236 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
237
238 def test_return_header_keep_alive(self):
239 self.con.request('KEEP', '/')
240 res = self.con.getresponse()
241 self.assertEqual(res.getheader('Connection'), 'keep-alive')
242 self.con.request('TEST', '/')
243 self.addCleanup(self.con.close)
244
245 def test_internal_key_error(self):
246 self.con.request('KEYERROR', '/')
247 res = self.con.getresponse()
248 self.assertEqual(res.status, 999)
249
250 def test_return_custom_status(self):
251 self.con.request('CUSTOM', '/')
252 res = self.con.getresponse()
253 self.assertEqual(res.status, 999)
254
255 def test_return_explain_error(self):
256 self.con.request('EXPLAINERROR', '/')
257 res = self.con.getresponse()
258 self.assertEqual(res.status, 999)
259 self.assertTrue(int(res.getheader('Content-Length')))
260
261 def test_latin1_header(self):
262 self.con.request('LATINONEHEADER', '/', headers={
263 'X-Special-Incoming': 'Ärger mit Unicode'
264 })
265 res = self.con.getresponse()
266 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
267 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
268
269 def test_error_content_length(self):
270 # Issue #16088: standard error responses should have a content-length
271 self.con.request('NOTFOUND', '/')
272 res = self.con.getresponse()
273 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
274
275 data = res.read()
276 self.assertEqual(int(res.getheader('Content-Length')), len(data))
277
278 def test_send_error(self):
279 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
280 HTTPStatus.RESET_CONTENT)
281 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
282 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
283 HTTPStatus.SWITCHING_PROTOCOLS):
284 self.con.request('SEND_ERROR', '/{}'.format(code))
285 res = self.con.getresponse()
286 self.assertEqual(code, res.status)
287 self.assertEqual(None, res.getheader('Content-Length'))
288 self.assertEqual(None, res.getheader('Content-Type'))
289 if code not in allow_transfer_encoding_codes:
290 self.assertEqual(None, res.getheader('Transfer-Encoding'))
291
292 data = res.read()
293 self.assertEqual(b'', data)
294
295 def test_head_via_send_error(self):
296 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
297 HTTPStatus.RESET_CONTENT)
298 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
299 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
300 HTTPStatus.SWITCHING_PROTOCOLS):
301 self.con.request('HEAD', '/{}'.format(code))
302 res = self.con.getresponse()
303 self.assertEqual(code, res.status)
304 if code == HTTPStatus.OK:
305 self.assertTrue(int(res.getheader('Content-Length')) > 0)
306 self.assertIn('text/html', res.getheader('Content-Type'))
307 else:
308 self.assertEqual(None, res.getheader('Content-Length'))
309 self.assertEqual(None, res.getheader('Content-Type'))
310 if code not in allow_transfer_encoding_codes:
311 self.assertEqual(None, res.getheader('Transfer-Encoding'))
312
313 data = res.read()
314 self.assertEqual(b'', data)
315
316
317 class RequestHandlerLoggingTestCase(BaseTestCase):
318 class request_handler(BaseHTTPRequestHandler):
319 protocol_version = 'HTTP/1.1'
320 default_request_version = 'HTTP/1.1'
321
322 def do_GET(self):
323 self.send_response(HTTPStatus.OK)
324 # Needed for PyPy ???
325 self.send_header('Connection', 'close')
326 self.end_headers()
327
328 def do_ERROR(self):
329 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
330
331 def test_get(self):
332 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
333 self.con.connect()
334
335 with support.captured_stderr() as err:
336 self.con.request('GET', '/')
337 self.con.getresponse()
338
339 self.assertTrue(
340 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
341
342 def test_err(self):
343 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
344 self.con.connect()
345
346 with support.captured_stderr() as err:
347 self.con.request('ERROR', '/')
348 self.con.getresponse()
349
350 lines = err.getvalue().split('\n')
351 self.assertTrue(lines[0].endswith('code 404, message File not found'))
352 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
353
354
355 class SimpleHTTPServerTestCase(BaseTestCase):
356 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
357 pass
358
359 def setUp(self):
360 super().setUp()
361 self.cwd = os.getcwd()
362 basetempdir = tempfile.gettempdir()
363 os.chdir(basetempdir)
364 self.data = b'We are the knights who say Ni!'
365 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
366 self.tempdir_name = os.path.basename(self.tempdir)
367 self.base_url = '/' + self.tempdir_name
368 tempname = os.path.join(self.tempdir, 'test')
369 with open(tempname, 'wb') as temp:
370 temp.write(self.data)
371 temp.flush()
372 mtime = os.stat(tempname).st_mtime
373 # compute last modification datetime for browser cache tests
374 last_modif = datetime.datetime.fromtimestamp(mtime,
375 datetime.timezone.utc)
376 self.last_modif_datetime = last_modif.replace(microsecond=0)
377 self.last_modif_header = email.utils.formatdate(
378 last_modif.timestamp(), usegmt=True)
379
380 def tearDown(self):
381 try:
382 os.chdir(self.cwd)
383 try:
384 shutil.rmtree(self.tempdir)
385 except:
386 pass
387 finally:
388 super().tearDown()
389
390 def check_status_and_reason(self, response, status, data=None):
391 def close_conn():
392 """Don't close reader yet so we can check if there was leftover
393 buffered input"""
394 nonlocal reader
395 reader = response.fp
396 response.fp = None
397 reader = None
398 response._close_conn = close_conn
399
400 body = response.read()
401 self.assertTrue(response)
402 self.assertEqual(response.status, status)
403 self.assertIsNotNone(response.reason)
404 if data:
405 self.assertEqual(data, body)
406 # Ensure the server has not set up a persistent connection, and has
407 # not sent any extra data
408 self.assertEqual(response.version, 10)
409 self.assertEqual(response.msg.get("Connection", "close"), "close")
410 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
411
412 reader.close()
413 return body
414
415 @unittest.skipIf(sys.platform == 'darwin',
416 'undecodable name cannot always be decoded on macOS')
417 @unittest.skipIf(sys.platform == 'win32',
418 'undecodable name cannot be decoded on win32')
419 @unittest.skipUnless(os_helper.TESTFN_UNDECODABLE,
420 'need os_helper.TESTFN_UNDECODABLE')
421 def test_undecodable_filename(self):
422 enc = sys.getfilesystemencoding()
423 filename = os.fsdecode(os_helper.TESTFN_UNDECODABLE) + '.txt'
424 with open(os.path.join(self.tempdir, filename), 'wb') as f:
425 f.write(os_helper.TESTFN_UNDECODABLE)
426 response = self.request(self.base_url + '/')
427 if sys.platform == 'darwin':
428 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
429 # UTF-8 into a percent-encoded value.
430 for name in os.listdir(self.tempdir):
431 if name != 'test': # Ignore a filename created in setUp().
432 filename = name
433 break
434 body = self.check_status_and_reason(response, HTTPStatus.OK)
435 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
436 self.assertIn(('href="%s"' % quotedname)
437 .encode(enc, 'surrogateescape'), body)
438 self.assertIn(('>%s<' % html.escape(filename, quote=False))
439 .encode(enc, 'surrogateescape'), body)
440 response = self.request(self.base_url + '/' + quotedname)
441 self.check_status_and_reason(response, HTTPStatus.OK,
442 data=os_helper.TESTFN_UNDECODABLE)
443
444 def test_undecodable_parameter(self):
445 # sanity check using a valid parameter
446 response = self.request(self.base_url + '/?x=123').read()
447 self.assertRegex(response, rf'listing for {self.base_url}/\?x=123'.encode('latin1'))
448 # now the bogus encoding
449 response = self.request(self.base_url + '/?x=%bb').read()
450 self.assertRegex(response, rf'listing for {self.base_url}/\?x=\xef\xbf\xbd'.encode('latin1'))
451
452 def test_get_dir_redirect_location_domain_injection_bug(self):
453 """Ensure //evil.co/..%2f../../X does not put //evil.co/ in Location.
454
455 //netloc/ in a Location header is a redirect to a new host.
456 https://github.com/python/cpython/issues/87389
457
458 This checks that a path resolving to a directory on our server cannot
459 resolve into a redirect to another server.
460 """
461 os.mkdir(os.path.join(self.tempdir, 'existing_directory'))
462 url = f'/python.org/..%2f..%2f..%2f..%2f..%2f../%0a%0d/../{self.tempdir_name}/existing_directory'
463 expected_location = f'{url}/' # /python.org.../ single slash single prefix, trailing slash
464 # Canonicalizes to /tmp/tempdir_name/existing_directory which does
465 # exist and is a dir, triggering the 301 redirect logic.
466 response = self.request(url)
467 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
468 location = response.getheader('Location')
469 self.assertEqual(location, expected_location, msg='non-attack failed!')
470
471 # //python.org... multi-slash prefix, no trailing slash
472 attack_url = f'/{url}'
473 response = self.request(attack_url)
474 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
475 location = response.getheader('Location')
476 self.assertFalse(location.startswith('//'), msg=location)
477 self.assertEqual(location, expected_location,
478 msg='Expected Location header to start with a single / and '
479 'end with a / as this is a directory redirect.')
480
481 # ///python.org... triple-slash prefix, no trailing slash
482 attack3_url = f'//{url}'
483 response = self.request(attack3_url)
484 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
485 self.assertEqual(response.getheader('Location'), expected_location)
486
487 # If the second word in the http request (Request-URI for the http
488 # method) is a full URI, we don't worry about it, as that'll be parsed
489 # and reassembled as a full URI within BaseHTTPRequestHandler.send_head
490 # so no errant scheme-less //netloc//evil.co/ domain mixup can happen.
491 attack_scheme_netloc_2slash_url = f'https://pypi.org/{url}'
492 expected_scheme_netloc_location = f'{attack_scheme_netloc_2slash_url}/'
493 response = self.request(attack_scheme_netloc_2slash_url)
494 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
495 location = response.getheader('Location')
496 # We're just ensuring that the scheme and domain make it through, if
497 # there are or aren't multiple slashes at the start of the path that
498 # follows that isn't important in this Location: header.
499 self.assertTrue(location.startswith('https://pypi.org/'), msg=location)
500
501 def test_get(self):
502 #constructs the path relative to the root directory of the HTTPServer
503 response = self.request(self.base_url + '/test')
504 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
505 # check for trailing "/" which should return 404. See Issue17324
506 response = self.request(self.base_url + '/test/')
507 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
508 response = self.request(self.base_url + '/')
509 self.check_status_and_reason(response, HTTPStatus.OK)
510 response = self.request(self.base_url)
511 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
512 self.assertEqual(response.getheader("Content-Length"), "0")
513 response = self.request(self.base_url + '/?hi=2')
514 self.check_status_and_reason(response, HTTPStatus.OK)
515 response = self.request(self.base_url + '?hi=1')
516 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
517 self.assertEqual(response.getheader("Location"),
518 self.base_url + "/?hi=1")
519 response = self.request('/ThisDoesNotExist')
520 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
521 response = self.request('/' + 'ThisDoesNotExist' + '/')
522 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
523 os.makedirs(os.path.join(self.tempdir, 'spam', 'index.html'))
524 response = self.request(self.base_url + '/spam/')
525 self.check_status_and_reason(response, HTTPStatus.OK)
526
527 data = b"Dummy index file\r\n"
528 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
529 f.write(data)
530 response = self.request(self.base_url + '/')
531 self.check_status_and_reason(response, HTTPStatus.OK, data)
532
533 # chmod() doesn't work as expected on Windows, and filesystem
534 # permissions are ignored by root on Unix.
535 if os.name == 'posix' and os.geteuid() != 0:
536 os.chmod(self.tempdir, 0)
537 try:
538 response = self.request(self.base_url + '/')
539 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
540 finally:
541 os.chmod(self.tempdir, 0o755)
542
543 def test_head(self):
544 response = self.request(
545 self.base_url + '/test', method='HEAD')
546 self.check_status_and_reason(response, HTTPStatus.OK)
547 self.assertEqual(response.getheader('content-length'),
548 str(len(self.data)))
549 self.assertEqual(response.getheader('content-type'),
550 'application/octet-stream')
551
552 def test_browser_cache(self):
553 """Check that when a request to /test is sent with the request header
554 If-Modified-Since set to date of last modification, the server returns
555 status code 304, not 200
556 """
557 headers = email.message.Message()
558 headers['If-Modified-Since'] = self.last_modif_header
559 response = self.request(self.base_url + '/test', headers=headers)
560 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
561
562 # one hour after last modification : must return 304
563 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
564 headers = email.message.Message()
565 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
566 usegmt=True)
567 response = self.request(self.base_url + '/test', headers=headers)
568 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
569
570 def test_browser_cache_file_changed(self):
571 # with If-Modified-Since earlier than Last-Modified, must return 200
572 dt = self.last_modif_datetime
573 # build datetime object : 365 days before last modification
574 old_dt = dt - datetime.timedelta(days=365)
575 headers = email.message.Message()
576 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
577 usegmt=True)
578 response = self.request(self.base_url + '/test', headers=headers)
579 self.check_status_and_reason(response, HTTPStatus.OK)
580
581 def test_browser_cache_with_If_None_Match_header(self):
582 # if If-None-Match header is present, ignore If-Modified-Since
583
584 headers = email.message.Message()
585 headers['If-Modified-Since'] = self.last_modif_header
586 headers['If-None-Match'] = "*"
587 response = self.request(self.base_url + '/test', headers=headers)
588 self.check_status_and_reason(response, HTTPStatus.OK)
589
590 def test_invalid_requests(self):
591 response = self.request('/', method='FOO')
592 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
593 # requests must be case sensitive,so this should fail too
594 response = self.request('/', method='custom')
595 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
596 response = self.request('/', method='GETs')
597 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
598
599 def test_last_modified(self):
600 """Checks that the datetime returned in Last-Modified response header
601 is the actual datetime of last modification, rounded to the second
602 """
603 response = self.request(self.base_url + '/test')
604 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
605 last_modif_header = response.headers['Last-modified']
606 self.assertEqual(last_modif_header, self.last_modif_header)
607
608 def test_path_without_leading_slash(self):
609 response = self.request(self.tempdir_name + '/test')
610 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
611 response = self.request(self.tempdir_name + '/test/')
612 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
613 response = self.request(self.tempdir_name + '/')
614 self.check_status_and_reason(response, HTTPStatus.OK)
615 response = self.request(self.tempdir_name)
616 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
617 response = self.request(self.tempdir_name + '/?hi=2')
618 self.check_status_and_reason(response, HTTPStatus.OK)
619 response = self.request(self.tempdir_name + '?hi=1')
620 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
621 self.assertEqual(response.getheader("Location"),
622 self.tempdir_name + "/?hi=1")
623
624 def test_html_escape_filename(self):
625 filename = '<test&>.txt'
626 fullpath = os.path.join(self.tempdir, filename)
627
628 try:
629 open(fullpath, 'wb').close()
630 except OSError:
631 raise unittest.SkipTest('Can not create file %s on current file '
632 'system' % filename)
633
634 try:
635 response = self.request(self.base_url + '/')
636 body = self.check_status_and_reason(response, HTTPStatus.OK)
637 enc = response.headers.get_content_charset()
638 finally:
639 os.unlink(fullpath) # avoid affecting test_undecodable_filename
640
641 self.assertIsNotNone(enc)
642 html_text = '>%s<' % html.escape(filename, quote=False)
643 self.assertIn(html_text.encode(enc), body)
644
645
646 cgi_file1 = """\
647 #!%s
648
649 print("Content-type: text/html")
650 print()
651 print("Hello World")
652 """
653
654 cgi_file2 = """\
655 #!%s
656 import os
657 import sys
658 import urllib.parse
659
660 print("Content-type: text/html")
661 print()
662
663 content_length = int(os.environ["CONTENT_LENGTH"])
664 query_string = sys.stdin.buffer.read(content_length)
665 params = {key.decode("utf-8"): val.decode("utf-8")
666 for key, val in urllib.parse.parse_qsl(query_string)}
667
668 print("%%s, %%s, %%s" %% (params["spam"], params["eggs"], params["bacon"]))
669 """
670
671 cgi_file4 = """\
672 #!%s
673 import os
674
675 print("Content-type: text/html")
676 print()
677
678 print(os.environ["%s"])
679 """
680
681 cgi_file6 = """\
682 #!%s
683 import os
684
685 print("X-ambv: was here")
686 print("Content-type: text/html")
687 print()
688 print("<pre>")
689 for k, v in os.environ.items():
690 try:
691 k.encode('ascii')
692 v.encode('ascii')
693 except UnicodeEncodeError:
694 continue # see: BPO-44647
695 print(f"{k}={v}")
696 print("</pre>")
697 """
698
699 cgi_file7 = """\
700 #!%s
701 import os
702 import sys
703
704 print("Content-type: text/plain")
705 print()
706
707 content_length = int(os.environ["CONTENT_LENGTH"])
708 body = sys.stdin.buffer.read(content_length)
709
710 print(f"{content_length} {len(body)}")
711 """
712
713
714 @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
715 "This test can't be run reliably as root (issue #13308).")
716 class CGIHTTPServerTestCase(BaseTestCase):
717 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
718 pass
719
720 linesep = os.linesep.encode('ascii')
721
722 def setUp(self):
723 BaseTestCase.setUp(self)
724 self.cwd = os.getcwd()
725 self.parent_dir = tempfile.mkdtemp()
726 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
727 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
728 self.sub_dir_1 = os.path.join(self.parent_dir, 'sub')
729 self.sub_dir_2 = os.path.join(self.sub_dir_1, 'dir')
730 self.cgi_dir_in_sub_dir = os.path.join(self.sub_dir_2, 'cgi-bin')
731 os.mkdir(self.cgi_dir)
732 os.mkdir(self.cgi_child_dir)
733 os.mkdir(self.sub_dir_1)
734 os.mkdir(self.sub_dir_2)
735 os.mkdir(self.cgi_dir_in_sub_dir)
736 self.nocgi_path = None
737 self.file1_path = None
738 self.file2_path = None
739 self.file3_path = None
740 self.file4_path = None
741 self.file5_path = None
742 self.file6_path = None
743 self.file7_path = None
744
745 # The shebang line should be pure ASCII: use symlink if possible.
746 # See issue #7668.
747 self._pythonexe_symlink = None
748 if os_helper.can_symlink():
749 self.pythonexe = os.path.join(self.parent_dir, 'python')
750 self._pythonexe_symlink = support.PythonSymlink(self.pythonexe).__enter__()
751 else:
752 self.pythonexe = sys.executable
753
754 try:
755 # The python executable path is written as the first line of the
756 # CGI Python script. The encoding cookie cannot be used, and so the
757 # path should be encodable to the default script encoding (utf-8)
758 self.pythonexe.encode('utf-8')
759 except UnicodeEncodeError:
760 self.tearDown()
761 self.skipTest("Python executable path is not encodable to utf-8")
762
763 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
764 with open(self.nocgi_path, 'w', encoding='utf-8') as fp:
765 fp.write(cgi_file1 % self.pythonexe)
766 os.chmod(self.nocgi_path, 0o777)
767
768 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
769 with open(self.file1_path, 'w', encoding='utf-8') as file1:
770 file1.write(cgi_file1 % self.pythonexe)
771 os.chmod(self.file1_path, 0o777)
772
773 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
774 with open(self.file2_path, 'w', encoding='utf-8') as file2:
775 file2.write(cgi_file2 % self.pythonexe)
776 os.chmod(self.file2_path, 0o777)
777
778 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
779 with open(self.file3_path, 'w', encoding='utf-8') as file3:
780 file3.write(cgi_file1 % self.pythonexe)
781 os.chmod(self.file3_path, 0o777)
782
783 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
784 with open(self.file4_path, 'w', encoding='utf-8') as file4:
785 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
786 os.chmod(self.file4_path, 0o777)
787
788 self.file5_path = os.path.join(self.cgi_dir_in_sub_dir, 'file5.py')
789 with open(self.file5_path, 'w', encoding='utf-8') as file5:
790 file5.write(cgi_file1 % self.pythonexe)
791 os.chmod(self.file5_path, 0o777)
792
793 self.file6_path = os.path.join(self.cgi_dir, 'file6.py')
794 with open(self.file6_path, 'w', encoding='utf-8') as file6:
795 file6.write(cgi_file6 % self.pythonexe)
796 os.chmod(self.file6_path, 0o777)
797
798 self.file7_path = os.path.join(self.cgi_dir, 'file7.py')
799 with open(self.file7_path, 'w', encoding='utf-8') as file7:
800 file7.write(cgi_file7 % self.pythonexe)
801 os.chmod(self.file7_path, 0o777)
802
803 os.chdir(self.parent_dir)
804
805 def tearDown(self):
806 try:
807 os.chdir(self.cwd)
808 if self._pythonexe_symlink:
809 self._pythonexe_symlink.__exit__(None, None, None)
810 if self.nocgi_path:
811 os.remove(self.nocgi_path)
812 if self.file1_path:
813 os.remove(self.file1_path)
814 if self.file2_path:
815 os.remove(self.file2_path)
816 if self.file3_path:
817 os.remove(self.file3_path)
818 if self.file4_path:
819 os.remove(self.file4_path)
820 if self.file5_path:
821 os.remove(self.file5_path)
822 if self.file6_path:
823 os.remove(self.file6_path)
824 if self.file7_path:
825 os.remove(self.file7_path)
826 os.rmdir(self.cgi_child_dir)
827 os.rmdir(self.cgi_dir)
828 os.rmdir(self.cgi_dir_in_sub_dir)
829 os.rmdir(self.sub_dir_2)
830 os.rmdir(self.sub_dir_1)
831 os.rmdir(self.parent_dir)
832 finally:
833 BaseTestCase.tearDown(self)
834
835 def test_url_collapse_path(self):
836 # verify tail is the last portion and head is the rest on proper urls
837 test_vectors = {
838 '': '//',
839 '..': IndexError,
840 '/.//..': IndexError,
841 '/': '//',
842 '//': '//',
843 '/\\': '//\\',
844 '/.//': '//',
845 'cgi-bin/file1.py': '/cgi-bin/file1.py',
846 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
847 'a': '//a',
848 '/a': '//a',
849 '//a': '//a',
850 './a': '//a',
851 './C:/': '/C:/',
852 '/a/b': '/a/b',
853 '/a/b/': '/a/b/',
854 '/a/b/.': '/a/b/',
855 '/a/b/c/..': '/a/b/',
856 '/a/b/c/../d': '/a/b/d',
857 '/a/b/c/../d/e/../f': '/a/b/d/f',
858 '/a/b/c/../d/e/../../f': '/a/b/f',
859 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
860 '../a/b/c/../d/e/.././././..//f': IndexError,
861 '/a/b/c/../d/e/../../../f': '/a/f',
862 '/a/b/c/../d/e/../../../../f': '//f',
863 '/a/b/c/../d/e/../../../../../f': IndexError,
864 '/a/b/c/../d/e/../../../../f/..': '//',
865 '/a/b/c/../d/e/../../../../f/../.': '//',
866 }
867 for path, expected in test_vectors.items():
868 if isinstance(expected, type) and issubclass(expected, Exception):
869 self.assertRaises(expected,
870 server._url_collapse_path, path)
871 else:
872 actual = server._url_collapse_path(path)
873 self.assertEqual(expected, actual,
874 msg='path = %r\nGot: %r\nWanted: %r' %
875 (path, actual, expected))
876
877 def test_headers_and_content(self):
878 res = self.request('/cgi-bin/file1.py')
879 self.assertEqual(
880 (res.read(), res.getheader('Content-type'), res.status),
881 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
882
883 def test_issue19435(self):
884 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
885 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
886
887 def test_post(self):
888 params = urllib.parse.urlencode(
889 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
890 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
891 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
892
893 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
894
895 def test_large_content_length(self):
896 for w in range(15, 25):
897 size = 1 << w
898 body = b'X' * size
899 headers = {'Content-Length' : str(size)}
900 res = self.request('/cgi-bin/file7.py', 'POST', body, headers)
901 self.assertEqual(res.read(), b'%d %d' % (size, size) + self.linesep)
902
903 def test_large_content_length_truncated(self):
904 with support.swap_attr(self.request_handler, 'timeout', 0.001):
905 for w in range(18, 65):
906 size = 1 << w
907 headers = {'Content-Length' : str(size)}
908 res = self.request('/cgi-bin/file1.py', 'POST', b'x', headers)
909 self.assertEqual(res.read(), b'Hello World' + self.linesep)
910
911 def test_invaliduri(self):
912 res = self.request('/cgi-bin/invalid')
913 res.read()
914 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
915
916 def test_authorization(self):
917 headers = {b'Authorization' : b'Basic ' +
918 base64.b64encode(b'username:pass')}
919 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
920 self.assertEqual(
921 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
922 (res.read(), res.getheader('Content-type'), res.status))
923
924 def test_no_leading_slash(self):
925 # http://bugs.python.org/issue2254
926 res = self.request('cgi-bin/file1.py')
927 self.assertEqual(
928 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
929 (res.read(), res.getheader('Content-type'), res.status))
930
931 def test_os_environ_is_not_altered(self):
932 signature = "Test CGI Server"
933 os.environ['SERVER_SOFTWARE'] = signature
934 res = self.request('/cgi-bin/file1.py')
935 self.assertEqual(
936 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
937 (res.read(), res.getheader('Content-type'), res.status))
938 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
939
940 def test_urlquote_decoding_in_cgi_check(self):
941 res = self.request('/cgi-bin%2ffile1.py')
942 self.assertEqual(
943 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
944 (res.read(), res.getheader('Content-type'), res.status))
945
946 def test_nested_cgi_path_issue21323(self):
947 res = self.request('/cgi-bin/child-dir/file3.py')
948 self.assertEqual(
949 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
950 (res.read(), res.getheader('Content-type'), res.status))
951
952 def test_query_with_multiple_question_mark(self):
953 res = self.request('/cgi-bin/file4.py?a=b?c=d')
954 self.assertEqual(
955 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
956 (res.read(), res.getheader('Content-type'), res.status))
957
958 def test_query_with_continuous_slashes(self):
959 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
960 self.assertEqual(
961 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
962 'text/html', HTTPStatus.OK),
963 (res.read(), res.getheader('Content-type'), res.status))
964
965 def test_cgi_path_in_sub_directories(self):
966 try:
967 CGIHTTPRequestHandler.cgi_directories.append('/sub/dir/cgi-bin')
968 res = self.request('/sub/dir/cgi-bin/file5.py')
969 self.assertEqual(
970 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
971 (res.read(), res.getheader('Content-type'), res.status))
972 finally:
973 CGIHTTPRequestHandler.cgi_directories.remove('/sub/dir/cgi-bin')
974
975 def test_accept(self):
976 browser_accept = \
977 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
978 tests = (
979 ((('Accept', browser_accept),), browser_accept),
980 ((), ''),
981 # Hack case to get two values for the one header
982 ((('Accept', 'text/html'), ('ACCEPT', 'text/plain')),
983 'text/html,text/plain'),
984 )
985 for headers, expected in tests:
986 headers = OrderedDict(headers)
987 with self.subTest(headers):
988 res = self.request('/cgi-bin/file6.py', 'GET', headers=headers)
989 self.assertEqual(http.HTTPStatus.OK, res.status)
990 expected = f"HTTP_ACCEPT={expected}".encode('ascii')
991 self.assertIn(expected, res.read())
992
993
994 class SocketlessRequestHandler(SimpleHTTPRequestHandler):
995 def __init__(self, directory=None):
996 request = mock.Mock()
997 request.makefile.return_value = BytesIO()
998 super().__init__(request, None, None, directory=directory)
999
1000 self.get_called = False
1001 self.protocol_version = "HTTP/1.1"
1002
1003 def do_GET(self):
1004 self.get_called = True
1005 self.send_response(HTTPStatus.OK)
1006 self.send_header('Content-Type', 'text/html')
1007 self.end_headers()
1008 self.wfile.write(b'<html><body>Data</body></html>\r\n')
1009
1010 def log_message(self, format, *args):
1011 pass
1012
1013 class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
1014 def handle_expect_100(self):
1015 self.send_error(HTTPStatus.EXPECTATION_FAILED)
1016 return False
1017
1018
1019 class AuditableBytesIO:
1020
1021 def __init__(self):
1022 self.datas = []
1023
1024 def write(self, data):
1025 self.datas.append(data)
1026
1027 def getData(self):
1028 return b''.join(self.datas)
1029
1030 @property
1031 def numWrites(self):
1032 return len(self.datas)
1033
1034
1035 class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
1036 """Test the functionality of the BaseHTTPServer.
1037
1038 Test the support for the Expect 100-continue header.
1039 """
1040
1041 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
1042
1043 def setUp (self):
1044 self.handler = SocketlessRequestHandler()
1045
1046 def send_typical_request(self, message):
1047 input = BytesIO(message)
1048 output = BytesIO()
1049 self.handler.rfile = input
1050 self.handler.wfile = output
1051 self.handler.handle_one_request()
1052 output.seek(0)
1053 return output.readlines()
1054
1055 def verify_get_called(self):
1056 self.assertTrue(self.handler.get_called)
1057
1058 def verify_expected_headers(self, headers):
1059 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
1060 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
1061
1062 def verify_http_server_response(self, response):
1063 match = self.HTTPResponseMatch.search(response)
1064 self.assertIsNotNone(match)
1065
1066 def test_unprintable_not_logged(self):
1067 # We call the method from the class directly as our Socketless
1068 # Handler subclass overrode it... nice for everything BUT this test.
1069 self.handler.client_address = ('127.0.0.1', 1337)
1070 log_message = BaseHTTPRequestHandler.log_message
1071 with mock.patch.object(sys, 'stderr', StringIO()) as fake_stderr:
1072 log_message(self.handler, '/foo')
1073 log_message(self.handler, '/\033bar\000\033')
1074 log_message(self.handler, '/spam %s.', 'a')
1075 log_message(self.handler, '/spam %s.', '\033\x7f\x9f\xa0beans')
1076 log_message(self.handler, '"GET /foo\\b"ar\007 HTTP/1.0"')
1077 stderr = fake_stderr.getvalue()
1078 self.assertNotIn('\033', stderr) # non-printable chars are caught.
1079 self.assertNotIn('\000', stderr) # non-printable chars are caught.
1080 lines = stderr.splitlines()
1081 self.assertIn('/foo', lines[0])
1082 self.assertIn(r'/\x1bbar\x00\x1b', lines[1])
1083 self.assertIn('/spam a.', lines[2])
1084 self.assertIn('/spam \\x1b\\x7f\\x9f\xa0beans.', lines[3])
1085 self.assertIn(r'"GET /foo\\b"ar\x07 HTTP/1.0"', lines[4])
1086
1087 def test_http_1_1(self):
1088 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
1089 self.verify_http_server_response(result[0])
1090 self.verify_expected_headers(result[1:-1])
1091 self.verify_get_called()
1092 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
1093 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1094 self.assertEqual(self.handler.command, 'GET')
1095 self.assertEqual(self.handler.path, '/')
1096 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
1097 self.assertSequenceEqual(self.handler.headers.items(), ())
1098
1099 def test_http_1_0(self):
1100 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
1101 self.verify_http_server_response(result[0])
1102 self.verify_expected_headers(result[1:-1])
1103 self.verify_get_called()
1104 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
1105 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
1106 self.assertEqual(self.handler.command, 'GET')
1107 self.assertEqual(self.handler.path, '/')
1108 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
1109 self.assertSequenceEqual(self.handler.headers.items(), ())
1110
1111 def test_http_0_9(self):
1112 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
1113 self.assertEqual(len(result), 1)
1114 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
1115 self.verify_get_called()
1116
1117 def test_extra_space(self):
1118 result = self.send_typical_request(
1119 b'GET /spaced out HTTP/1.1\r\n'
1120 b'Host: dummy\r\n'
1121 b'\r\n'
1122 )
1123 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
1124 self.verify_expected_headers(result[1:result.index(b'\r\n')])
1125 self.assertFalse(self.handler.get_called)
1126
1127 def test_with_continue_1_0(self):
1128 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
1129 self.verify_http_server_response(result[0])
1130 self.verify_expected_headers(result[1:-1])
1131 self.verify_get_called()
1132 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
1133 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
1134 self.assertEqual(self.handler.command, 'GET')
1135 self.assertEqual(self.handler.path, '/')
1136 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
1137 headers = (("Expect", "100-continue"),)
1138 self.assertSequenceEqual(self.handler.headers.items(), headers)
1139
1140 def test_with_continue_1_1(self):
1141 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1142 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
1143 self.assertEqual(result[1], b'\r\n')
1144 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
1145 self.verify_expected_headers(result[2:-1])
1146 self.verify_get_called()
1147 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
1148 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1149 self.assertEqual(self.handler.command, 'GET')
1150 self.assertEqual(self.handler.path, '/')
1151 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
1152 headers = (("Expect", "100-continue"),)
1153 self.assertSequenceEqual(self.handler.headers.items(), headers)
1154
1155 def test_header_buffering_of_send_error(self):
1156
1157 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
1158 output = AuditableBytesIO()
1159 handler = SocketlessRequestHandler()
1160 handler.rfile = input
1161 handler.wfile = output
1162 handler.request_version = 'HTTP/1.1'
1163 handler.requestline = ''
1164 handler.command = None
1165
1166 handler.send_error(418)
1167 self.assertEqual(output.numWrites, 2)
1168
1169 def test_header_buffering_of_send_response_only(self):
1170
1171 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
1172 output = AuditableBytesIO()
1173 handler = SocketlessRequestHandler()
1174 handler.rfile = input
1175 handler.wfile = output
1176 handler.request_version = 'HTTP/1.1'
1177
1178 handler.send_response_only(418)
1179 self.assertEqual(output.numWrites, 0)
1180 handler.end_headers()
1181 self.assertEqual(output.numWrites, 1)
1182
1183 def test_header_buffering_of_send_header(self):
1184
1185 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
1186 output = AuditableBytesIO()
1187 handler = SocketlessRequestHandler()
1188 handler.rfile = input
1189 handler.wfile = output
1190 handler.request_version = 'HTTP/1.1'
1191
1192 handler.send_header('Foo', 'foo')
1193 handler.send_header('bar', 'bar')
1194 self.assertEqual(output.numWrites, 0)
1195 handler.end_headers()
1196 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
1197 self.assertEqual(output.numWrites, 1)
1198
1199 def test_header_unbuffered_when_continue(self):
1200
1201 def _readAndReseek(f):
1202 pos = f.tell()
1203 f.seek(0)
1204 data = f.read()
1205 f.seek(pos)
1206 return data
1207
1208 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1209 output = BytesIO()
1210 self.handler.rfile = input
1211 self.handler.wfile = output
1212 self.handler.request_version = 'HTTP/1.1'
1213
1214 self.handler.handle_one_request()
1215 self.assertNotEqual(_readAndReseek(output), b'')
1216 result = _readAndReseek(output).split(b'\r\n')
1217 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
1218 self.assertEqual(result[1], b'')
1219 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
1220
1221 def test_with_continue_rejected(self):
1222 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
1223 self.handler = RejectingSocketlessRequestHandler()
1224 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1225 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1226 self.verify_expected_headers(result[1:-1])
1227 # The expect handler should short circuit the usual get method by
1228 # returning false here, so get_called should be false
1229 self.assertFalse(self.handler.get_called)
1230 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1231 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1232
1233 def test_request_length(self):
1234 # Issue #10714: huge request lines are discarded, to avoid Denial
1235 # of Service attacks.
1236 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1237 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1238 self.assertFalse(self.handler.get_called)
1239 self.assertIsInstance(self.handler.requestline, str)
1240
1241 def test_header_length(self):
1242 # Issue #6791: same for headers
1243 result = self.send_typical_request(
1244 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
1245 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
1246 self.assertFalse(self.handler.get_called)
1247 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1248
1249 def test_too_many_headers(self):
1250 result = self.send_typical_request(
1251 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1252 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1253 self.assertFalse(self.handler.get_called)
1254 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1255
1256 def test_html_escape_on_error(self):
1257 result = self.send_typical_request(
1258 b'<script>alert("hello")</script> / HTTP/1.1')
1259 result = b''.join(result)
1260 text = '<script>alert("hello")</script>'
1261 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1262
1263 def test_close_connection(self):
1264 # handle_one_request() should be repeatedly called until
1265 # it sets close_connection
1266 def handle_one_request():
1267 self.handler.close_connection = next(close_values)
1268 self.handler.handle_one_request = handle_one_request
1269
1270 close_values = iter((True,))
1271 self.handler.handle()
1272 self.assertRaises(StopIteration, next, close_values)
1273
1274 close_values = iter((False, False, True))
1275 self.handler.handle()
1276 self.assertRaises(StopIteration, next, close_values)
1277
1278 def test_date_time_string(self):
1279 now = time.time()
1280 # this is the old code that formats the timestamp
1281 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1282 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1283 self.handler.weekdayname[wd],
1284 day,
1285 self.handler.monthname[month],
1286 year, hh, mm, ss
1287 )
1288 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1289
1290
1291 class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1292 """ Test url parsing """
1293 def setUp(self):
1294 self.translated_1 = os.path.join(os.getcwd(), 'filename')
1295 self.translated_2 = os.path.join('foo', 'filename')
1296 self.translated_3 = os.path.join('bar', 'filename')
1297 self.handler_1 = SocketlessRequestHandler()
1298 self.handler_2 = SocketlessRequestHandler(directory='foo')
1299 self.handler_3 = SocketlessRequestHandler(directory=pathlib.PurePath('bar'))
1300
1301 def test_query_arguments(self):
1302 path = self.handler_1.translate_path('/filename')
1303 self.assertEqual(path, self.translated_1)
1304 path = self.handler_2.translate_path('/filename')
1305 self.assertEqual(path, self.translated_2)
1306 path = self.handler_3.translate_path('/filename')
1307 self.assertEqual(path, self.translated_3)
1308
1309 path = self.handler_1.translate_path('/filename?foo=bar')
1310 self.assertEqual(path, self.translated_1)
1311 path = self.handler_2.translate_path('/filename?foo=bar')
1312 self.assertEqual(path, self.translated_2)
1313 path = self.handler_3.translate_path('/filename?foo=bar')
1314 self.assertEqual(path, self.translated_3)
1315
1316 path = self.handler_1.translate_path('/filename?a=b&spam=eggs#zot')
1317 self.assertEqual(path, self.translated_1)
1318 path = self.handler_2.translate_path('/filename?a=b&spam=eggs#zot')
1319 self.assertEqual(path, self.translated_2)
1320 path = self.handler_3.translate_path('/filename?a=b&spam=eggs#zot')
1321 self.assertEqual(path, self.translated_3)
1322
1323 def test_start_with_double_slash(self):
1324 path = self.handler_1.translate_path('//filename')
1325 self.assertEqual(path, self.translated_1)
1326 path = self.handler_2.translate_path('//filename')
1327 self.assertEqual(path, self.translated_2)
1328 path = self.handler_3.translate_path('//filename')
1329 self.assertEqual(path, self.translated_3)
1330
1331 path = self.handler_1.translate_path('//filename?foo=bar')
1332 self.assertEqual(path, self.translated_1)
1333 path = self.handler_2.translate_path('//filename?foo=bar')
1334 self.assertEqual(path, self.translated_2)
1335 path = self.handler_3.translate_path('//filename?foo=bar')
1336 self.assertEqual(path, self.translated_3)
1337
1338 def test_windows_colon(self):
1339 with support.swap_attr(server.os, 'path', ntpath):
1340 path = self.handler_1.translate_path('c:c:c:foo/filename')
1341 path = path.replace(ntpath.sep, os.sep)
1342 self.assertEqual(path, self.translated_1)
1343 path = self.handler_2.translate_path('c:c:c:foo/filename')
1344 path = path.replace(ntpath.sep, os.sep)
1345 self.assertEqual(path, self.translated_2)
1346 path = self.handler_3.translate_path('c:c:c:foo/filename')
1347 path = path.replace(ntpath.sep, os.sep)
1348 self.assertEqual(path, self.translated_3)
1349
1350 path = self.handler_1.translate_path('\\c:../filename')
1351 path = path.replace(ntpath.sep, os.sep)
1352 self.assertEqual(path, self.translated_1)
1353 path = self.handler_2.translate_path('\\c:../filename')
1354 path = path.replace(ntpath.sep, os.sep)
1355 self.assertEqual(path, self.translated_2)
1356 path = self.handler_3.translate_path('\\c:../filename')
1357 path = path.replace(ntpath.sep, os.sep)
1358 self.assertEqual(path, self.translated_3)
1359
1360 path = self.handler_1.translate_path('c:\\c:..\\foo/filename')
1361 path = path.replace(ntpath.sep, os.sep)
1362 self.assertEqual(path, self.translated_1)
1363 path = self.handler_2.translate_path('c:\\c:..\\foo/filename')
1364 path = path.replace(ntpath.sep, os.sep)
1365 self.assertEqual(path, self.translated_2)
1366 path = self.handler_3.translate_path('c:\\c:..\\foo/filename')
1367 path = path.replace(ntpath.sep, os.sep)
1368 self.assertEqual(path, self.translated_3)
1369
1370 path = self.handler_1.translate_path('c:c:foo\\c:c:bar/filename')
1371 path = path.replace(ntpath.sep, os.sep)
1372 self.assertEqual(path, self.translated_1)
1373 path = self.handler_2.translate_path('c:c:foo\\c:c:bar/filename')
1374 path = path.replace(ntpath.sep, os.sep)
1375 self.assertEqual(path, self.translated_2)
1376 path = self.handler_3.translate_path('c:c:foo\\c:c:bar/filename')
1377 path = path.replace(ntpath.sep, os.sep)
1378 self.assertEqual(path, self.translated_3)
1379
1380
1381 class MiscTestCase(unittest.TestCase):
1382 def test_all(self):
1383 expected = []
1384 denylist = {'executable', 'nobody_uid', 'test'}
1385 for name in dir(server):
1386 if name.startswith('_') or name in denylist:
1387 continue
1388 module_object = getattr(server, name)
1389 if getattr(module_object, '__module__', None) == 'http.server':
1390 expected.append(name)
1391 self.assertCountEqual(server.__all__, expected)
1392
1393
1394 class ScriptTestCase(unittest.TestCase):
1395
1396 def mock_server_class(self):
1397 return mock.MagicMock(
1398 return_value=mock.MagicMock(
1399 __enter__=mock.MagicMock(
1400 return_value=mock.MagicMock(
1401 socket=mock.MagicMock(
1402 getsockname=lambda: ('', 0),
1403 ),
1404 ),
1405 ),
1406 ),
1407 )
1408
1409 @mock.patch('builtins.print')
1410 def test_server_test_unspec(self, _):
1411 mock_server = self.mock_server_class()
1412 server.test(ServerClass=mock_server, bind=None)
1413 self.assertIn(
1414 mock_server.address_family,
1415 (socket.AF_INET6, socket.AF_INET),
1416 )
1417
1418 @mock.patch('builtins.print')
1419 def test_server_test_localhost(self, _):
1420 mock_server = self.mock_server_class()
1421 server.test(ServerClass=mock_server, bind="localhost")
1422 self.assertIn(
1423 mock_server.address_family,
1424 (socket.AF_INET6, socket.AF_INET),
1425 )
1426
1427 ipv6_addrs = (
1428 "::",
1429 "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
1430 "::1",
1431 )
1432
1433 ipv4_addrs = (
1434 "0.0.0.0",
1435 "8.8.8.8",
1436 "127.0.0.1",
1437 )
1438
1439 @mock.patch('builtins.print')
1440 def test_server_test_ipv6(self, _):
1441 for bind in self.ipv6_addrs:
1442 mock_server = self.mock_server_class()
1443 server.test(ServerClass=mock_server, bind=bind)
1444 self.assertEqual(mock_server.address_family, socket.AF_INET6)
1445
1446 @mock.patch('builtins.print')
1447 def test_server_test_ipv4(self, _):
1448 for bind in self.ipv4_addrs:
1449 mock_server = self.mock_server_class()
1450 server.test(ServerClass=mock_server, bind=bind)
1451 self.assertEqual(mock_server.address_family, socket.AF_INET)
1452
1453
1454 def setUpModule():
1455 unittest.addModuleCleanup(os.chdir, os.getcwd())
1456
1457
1458 if __name__ == '__main__':
1459 unittest.main()