Debian Codegraph @

Lib/test/test_httpservers.py

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