test_httpservers.py 55 KB

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