server.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. """HTTP server classes.
  2. Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
  3. SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
  4. and CGIHTTPRequestHandler for CGI scripts.
  5. It does, however, optionally implement HTTP/1.1 persistent connections,
  6. as of version 0.3.
  7. Notes on CGIHTTPRequestHandler
  8. ------------------------------
  9. This class implements GET and POST requests to cgi-bin scripts.
  10. If the os.fork() function is not present (e.g. on Windows),
  11. subprocess.Popen() is used as a fallback, with slightly altered semantics.
  12. In all cases, the implementation is intentionally naive -- all
  13. requests are executed synchronously.
  14. SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
  15. -- it may execute arbitrary Python code or external programs.
  16. Note that status code 200 is sent prior to execution of a CGI script, so
  17. scripts cannot send other status codes such as 302 (redirect).
  18. XXX To do:
  19. - log requests even later (to capture byte count)
  20. - log user-agent header and other interesting goodies
  21. - send error log to separate file
  22. """
  23. # See also:
  24. #
  25. # HTTP Working Group T. Berners-Lee
  26. # INTERNET-DRAFT R. T. Fielding
  27. # <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
  28. # Expires September 8, 1995 March 8, 1995
  29. #
  30. # URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
  31. #
  32. # and
  33. #
  34. # Network Working Group R. Fielding
  35. # Request for Comments: 2616 et al
  36. # Obsoletes: 2068 June 1999
  37. # Category: Standards Track
  38. #
  39. # URL: http://www.faqs.org/rfcs/rfc2616.html
  40. # Log files
  41. # ---------
  42. #
  43. # Here's a quote from the NCSA httpd docs about log file format.
  44. #
  45. # | The logfile format is as follows. Each line consists of:
  46. # |
  47. # | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
  48. # |
  49. # | host: Either the DNS name or the IP number of the remote client
  50. # | rfc931: Any information returned by identd for this person,
  51. # | - otherwise.
  52. # | authuser: If user sent a userid for authentication, the user name,
  53. # | - otherwise.
  54. # | DD: Day
  55. # | Mon: Month (calendar name)
  56. # | YYYY: Year
  57. # | hh: hour (24-hour format, the machine's timezone)
  58. # | mm: minutes
  59. # | ss: seconds
  60. # | request: The first line of the HTTP request as sent by the client.
  61. # | ddd: the status code returned by the server, - if not available.
  62. # | bbbb: the total number of bytes sent,
  63. # | *not including the HTTP/1.0 header*, - if not available
  64. # |
  65. # | You can determine the name of the file accessed through request.
  66. #
  67. # (Actually, the latter is only true if you know the server configuration
  68. # at the time the request was made!)
  69. __version__ = "0.6"
  70. __all__ = [
  71. "HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler",
  72. "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler",
  73. ]
  74. import copy
  75. import datetime
  76. import email.utils
  77. import html
  78. import http.client
  79. import io
  80. import itertools
  81. import mimetypes
  82. import os
  83. import posixpath
  84. import select
  85. import shutil
  86. import socket # For gethostbyaddr()
  87. import socketserver
  88. import sys
  89. import time
  90. import urllib.parse
  91. from http import HTTPStatus
  92. # Default error message template
  93. DEFAULT_ERROR_MESSAGE = """\
  94. <!DOCTYPE HTML>
  95. <html lang="en">
  96. <head>
  97. <meta charset="utf-8">
  98. <title>Error response</title>
  99. </head>
  100. <body>
  101. <h1>Error response</h1>
  102. <p>Error code: %(code)d</p>
  103. <p>Message: %(message)s.</p>
  104. <p>Error code explanation: %(code)s - %(explain)s.</p>
  105. </body>
  106. </html>
  107. """
  108. DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
  109. class HTTPServer(socketserver.TCPServer):
  110. allow_reuse_address = 1 # Seems to make sense in testing environment
  111. def server_bind(self):
  112. """Override server_bind to store the server name."""
  113. socketserver.TCPServer.server_bind(self)
  114. host, port = self.server_address[:2]
  115. self.server_name = socket.getfqdn(host)
  116. self.server_port = port
  117. class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
  118. daemon_threads = True
  119. class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
  120. """HTTP request handler base class.
  121. The following explanation of HTTP serves to guide you through the
  122. code as well as to expose any misunderstandings I may have about
  123. HTTP (so you don't need to read the code to figure out I'm wrong
  124. :-).
  125. HTTP (HyperText Transfer Protocol) is an extensible protocol on
  126. top of a reliable stream transport (e.g. TCP/IP). The protocol
  127. recognizes three parts to a request:
  128. 1. One line identifying the request type and path
  129. 2. An optional set of RFC-822-style headers
  130. 3. An optional data part
  131. The headers and data are separated by a blank line.
  132. The first line of the request has the form
  133. <command> <path> <version>
  134. where <command> is a (case-sensitive) keyword such as GET or POST,
  135. <path> is a string containing path information for the request,
  136. and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
  137. <path> is encoded using the URL encoding scheme (using %xx to signify
  138. the ASCII character with hex code xx).
  139. The specification specifies that lines are separated by CRLF but
  140. for compatibility with the widest range of clients recommends
  141. servers also handle LF. Similarly, whitespace in the request line
  142. is treated sensibly (allowing multiple spaces between components
  143. and allowing trailing whitespace).
  144. Similarly, for output, lines ought to be separated by CRLF pairs
  145. but most clients grok LF characters just fine.
  146. If the first line of the request has the form
  147. <command> <path>
  148. (i.e. <version> is left out) then this is assumed to be an HTTP
  149. 0.9 request; this form has no optional headers and data part and
  150. the reply consists of just the data.
  151. The reply form of the HTTP 1.x protocol again has three parts:
  152. 1. One line giving the response code
  153. 2. An optional set of RFC-822-style headers
  154. 3. The data
  155. Again, the headers and data are separated by a blank line.
  156. The response code line has the form
  157. <version> <responsecode> <responsestring>
  158. where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
  159. <responsecode> is a 3-digit response code indicating success or
  160. failure of the request, and <responsestring> is an optional
  161. human-readable string explaining what the response code means.
  162. This server parses the request and the headers, and then calls a
  163. function specific to the request type (<command>). Specifically,
  164. a request SPAM will be handled by a method do_SPAM(). If no
  165. such method exists the server sends an error response to the
  166. client. If it exists, it is called with no arguments:
  167. do_SPAM()
  168. Note that the request name is case sensitive (i.e. SPAM and spam
  169. are different requests).
  170. The various request details are stored in instance variables:
  171. - client_address is the client IP address in the form (host,
  172. port);
  173. - command, path and version are the broken-down request line;
  174. - headers is an instance of email.message.Message (or a derived
  175. class) containing the header information;
  176. - rfile is a file object open for reading positioned at the
  177. start of the optional input data part;
  178. - wfile is a file object open for writing.
  179. IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
  180. The first thing to be written must be the response line. Then
  181. follow 0 or more header lines, then a blank line, and then the
  182. actual data (if any). The meaning of the header lines depends on
  183. the command executed by the server; in most cases, when data is
  184. returned, there should be at least one header line of the form
  185. Content-type: <type>/<subtype>
  186. where <type> and <subtype> should be registered MIME types,
  187. e.g. "text/html" or "text/plain".
  188. """
  189. # The Python system version, truncated to its first component.
  190. sys_version = "Python/" + sys.version.split()[0]
  191. # The server software version. You may want to override this.
  192. # The format is multiple whitespace-separated strings,
  193. # where each string is of the form name[/version].
  194. server_version = "BaseHTTP/" + __version__
  195. error_message_format = DEFAULT_ERROR_MESSAGE
  196. error_content_type = DEFAULT_ERROR_CONTENT_TYPE
  197. # The default request version. This only affects responses up until
  198. # the point where the request line is parsed, so it mainly decides what
  199. # the client gets back when sending a malformed request line.
  200. # Most web servers default to HTTP 0.9, i.e. don't send a status line.
  201. default_request_version = "HTTP/0.9"
  202. def parse_request(self):
  203. """Parse a request (internal).
  204. The request should be stored in self.raw_requestline; the results
  205. are in self.command, self.path, self.request_version and
  206. self.headers.
  207. Return True for success, False for failure; on failure, any relevant
  208. error response has already been sent back.
  209. """
  210. self.command = None # set in case of error on the first line
  211. self.request_version = version = self.default_request_version
  212. self.close_connection = True
  213. requestline = str(self.raw_requestline, 'iso-8859-1')
  214. requestline = requestline.rstrip('\r\n')
  215. self.requestline = requestline
  216. words = requestline.split()
  217. if len(words) == 0:
  218. return False
  219. if len(words) >= 3: # Enough to determine protocol version
  220. version = words[-1]
  221. try:
  222. if not version.startswith('HTTP/'):
  223. raise ValueError
  224. base_version_number = version.split('/', 1)[1]
  225. version_number = base_version_number.split(".")
  226. # RFC 2145 section 3.1 says there can be only one "." and
  227. # - major and minor numbers MUST be treated as
  228. # separate integers;
  229. # - HTTP/2.4 is a lower version than HTTP/2.13, which in
  230. # turn is lower than HTTP/12.3;
  231. # - Leading zeros MUST be ignored by recipients.
  232. if len(version_number) != 2:
  233. raise ValueError
  234. version_number = int(version_number[0]), int(version_number[1])
  235. except (ValueError, IndexError):
  236. self.send_error(
  237. HTTPStatus.BAD_REQUEST,
  238. "Bad request version (%r)" % version)
  239. return False
  240. if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
  241. self.close_connection = False
  242. if version_number >= (2, 0):
  243. self.send_error(
  244. HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
  245. "Invalid HTTP version (%s)" % base_version_number)
  246. return False
  247. self.request_version = version
  248. if not 2 <= len(words) <= 3:
  249. self.send_error(
  250. HTTPStatus.BAD_REQUEST,
  251. "Bad request syntax (%r)" % requestline)
  252. return False
  253. command, path = words[:2]
  254. if len(words) == 2:
  255. self.close_connection = True
  256. if command != 'GET':
  257. self.send_error(
  258. HTTPStatus.BAD_REQUEST,
  259. "Bad HTTP/0.9 request type (%r)" % command)
  260. return False
  261. self.command, self.path = command, path
  262. # gh-87389: The purpose of replacing '//' with '/' is to protect
  263. # against open redirect attacks possibly triggered if the path starts
  264. # with '//' because http clients treat //path as an absolute URI
  265. # without scheme (similar to http://path) rather than a path.
  266. if self.path.startswith('//'):
  267. self.path = '/' + self.path.lstrip('/') # Reduce to a single /
  268. # Examine the headers and look for a Connection directive.
  269. try:
  270. self.headers = http.client.parse_headers(self.rfile,
  271. _class=self.MessageClass)
  272. except http.client.LineTooLong as err:
  273. self.send_error(
  274. HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
  275. "Line too long",
  276. str(err))
  277. return False
  278. except http.client.HTTPException as err:
  279. self.send_error(
  280. HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
  281. "Too many headers",
  282. str(err)
  283. )
  284. return False
  285. conntype = self.headers.get('Connection', "")
  286. if conntype.lower() == 'close':
  287. self.close_connection = True
  288. elif (conntype.lower() == 'keep-alive' and
  289. self.protocol_version >= "HTTP/1.1"):
  290. self.close_connection = False
  291. # Examine the headers and look for an Expect directive
  292. expect = self.headers.get('Expect', "")
  293. if (expect.lower() == "100-continue" and
  294. self.protocol_version >= "HTTP/1.1" and
  295. self.request_version >= "HTTP/1.1"):
  296. if not self.handle_expect_100():
  297. return False
  298. return True
  299. def handle_expect_100(self):
  300. """Decide what to do with an "Expect: 100-continue" header.
  301. If the client is expecting a 100 Continue response, we must
  302. respond with either a 100 Continue or a final response before
  303. waiting for the request body. The default is to always respond
  304. with a 100 Continue. You can behave differently (for example,
  305. reject unauthorized requests) by overriding this method.
  306. This method should either return True (possibly after sending
  307. a 100 Continue response) or send an error response and return
  308. False.
  309. """
  310. self.send_response_only(HTTPStatus.CONTINUE)
  311. self.end_headers()
  312. return True
  313. def handle_one_request(self):
  314. """Handle a single HTTP request.
  315. You normally don't need to override this method; see the class
  316. __doc__ string for information on how to handle specific HTTP
  317. commands such as GET and POST.
  318. """
  319. try:
  320. self.raw_requestline = self.rfile.readline(65537)
  321. if len(self.raw_requestline) > 65536:
  322. self.requestline = ''
  323. self.request_version = ''
  324. self.command = ''
  325. self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
  326. return
  327. if not self.raw_requestline:
  328. self.close_connection = True
  329. return
  330. if not self.parse_request():
  331. # An error code has been sent, just exit
  332. return
  333. mname = 'do_' + self.command
  334. if not hasattr(self, mname):
  335. self.send_error(
  336. HTTPStatus.NOT_IMPLEMENTED,
  337. "Unsupported method (%r)" % self.command)
  338. return
  339. method = getattr(self, mname)
  340. method()
  341. self.wfile.flush() #actually send the response if not already done.
  342. except TimeoutError as e:
  343. #a read or a write timed out. Discard this connection
  344. self.log_error("Request timed out: %r", e)
  345. self.close_connection = True
  346. return
  347. def handle(self):
  348. """Handle multiple requests if necessary."""
  349. self.close_connection = True
  350. self.handle_one_request()
  351. while not self.close_connection:
  352. self.handle_one_request()
  353. def send_error(self, code, message=None, explain=None):
  354. """Send and log an error reply.
  355. Arguments are
  356. * code: an HTTP error code
  357. 3 digits
  358. * message: a simple optional 1 line reason phrase.
  359. *( HTAB / SP / VCHAR / %x80-FF )
  360. defaults to short entry matching the response code
  361. * explain: a detailed message defaults to the long entry
  362. matching the response code.
  363. This sends an error response (so it must be called before any
  364. output has been generated), logs the error, and finally sends
  365. a piece of HTML explaining the error to the user.
  366. """
  367. try:
  368. shortmsg, longmsg = self.responses[code]
  369. except KeyError:
  370. shortmsg, longmsg = '???', '???'
  371. if message is None:
  372. message = shortmsg
  373. if explain is None:
  374. explain = longmsg
  375. self.log_error("code %d, message %s", code, message)
  376. self.send_response(code, message)
  377. self.send_header('Connection', 'close')
  378. # Message body is omitted for cases described in:
  379. # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
  380. # - RFC7231: 6.3.6. 205(Reset Content)
  381. body = None
  382. if (code >= 200 and
  383. code not in (HTTPStatus.NO_CONTENT,
  384. HTTPStatus.RESET_CONTENT,
  385. HTTPStatus.NOT_MODIFIED)):
  386. # HTML encode to prevent Cross Site Scripting attacks
  387. # (see bug #1100201)
  388. content = (self.error_message_format % {
  389. 'code': code,
  390. 'message': html.escape(message, quote=False),
  391. 'explain': html.escape(explain, quote=False)
  392. })
  393. body = content.encode('UTF-8', 'replace')
  394. self.send_header("Content-Type", self.error_content_type)
  395. self.send_header('Content-Length', str(len(body)))
  396. self.end_headers()
  397. if self.command != 'HEAD' and body:
  398. self.wfile.write(body)
  399. def send_response(self, code, message=None):
  400. """Add the response header to the headers buffer and log the
  401. response code.
  402. Also send two standard headers with the server software
  403. version and the current date.
  404. """
  405. self.log_request(code)
  406. self.send_response_only(code, message)
  407. self.send_header('Server', self.version_string())
  408. self.send_header('Date', self.date_time_string())
  409. def send_response_only(self, code, message=None):
  410. """Send the response header only."""
  411. if self.request_version != 'HTTP/0.9':
  412. if message is None:
  413. if code in self.responses:
  414. message = self.responses[code][0]
  415. else:
  416. message = ''
  417. if not hasattr(self, '_headers_buffer'):
  418. self._headers_buffer = []
  419. self._headers_buffer.append(("%s %d %s\r\n" %
  420. (self.protocol_version, code, message)).encode(
  421. 'latin-1', 'strict'))
  422. def send_header(self, keyword, value):
  423. """Send a MIME header to the headers buffer."""
  424. if self.request_version != 'HTTP/0.9':
  425. if not hasattr(self, '_headers_buffer'):
  426. self._headers_buffer = []
  427. self._headers_buffer.append(
  428. ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
  429. if keyword.lower() == 'connection':
  430. if value.lower() == 'close':
  431. self.close_connection = True
  432. elif value.lower() == 'keep-alive':
  433. self.close_connection = False
  434. def end_headers(self):
  435. """Send the blank line ending the MIME headers."""
  436. if self.request_version != 'HTTP/0.9':
  437. self._headers_buffer.append(b"\r\n")
  438. self.flush_headers()
  439. def flush_headers(self):
  440. if hasattr(self, '_headers_buffer'):
  441. self.wfile.write(b"".join(self._headers_buffer))
  442. self._headers_buffer = []
  443. def log_request(self, code='-', size='-'):
  444. """Log an accepted request.
  445. This is called by send_response().
  446. """
  447. if isinstance(code, HTTPStatus):
  448. code = code.value
  449. self.log_message('"%s" %s %s',
  450. self.requestline, str(code), str(size))
  451. def log_error(self, format, *args):
  452. """Log an error.
  453. This is called when a request cannot be fulfilled. By
  454. default it passes the message on to log_message().
  455. Arguments are the same as for log_message().
  456. XXX This should go to the separate error log.
  457. """
  458. self.log_message(format, *args)
  459. # https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes
  460. _control_char_table = str.maketrans(
  461. {c: fr'\x{c:02x}' for c in itertools.chain(range(0x20), range(0x7f,0xa0))})
  462. _control_char_table[ord('\\')] = r'\\'
  463. def log_message(self, format, *args):
  464. """Log an arbitrary message.
  465. This is used by all other logging functions. Override
  466. it if you have specific logging wishes.
  467. The first argument, FORMAT, is a format string for the
  468. message to be logged. If the format string contains
  469. any % escapes requiring parameters, they should be
  470. specified as subsequent arguments (it's just like
  471. printf!).
  472. The client ip and current date/time are prefixed to
  473. every message.
  474. Unicode control characters are replaced with escaped hex
  475. before writing the output to stderr.
  476. """
  477. message = format % args
  478. sys.stderr.write("%s - - [%s] %s\n" %
  479. (self.address_string(),
  480. self.log_date_time_string(),
  481. message.translate(self._control_char_table)))
  482. def version_string(self):
  483. """Return the server software version string."""
  484. return self.server_version + ' ' + self.sys_version
  485. def date_time_string(self, timestamp=None):
  486. """Return the current date and time formatted for a message header."""
  487. if timestamp is None:
  488. timestamp = time.time()
  489. return email.utils.formatdate(timestamp, usegmt=True)
  490. def log_date_time_string(self):
  491. """Return the current time formatted for logging."""
  492. now = time.time()
  493. year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
  494. s = "%02d/%3s/%04d %02d:%02d:%02d" % (
  495. day, self.monthname[month], year, hh, mm, ss)
  496. return s
  497. weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  498. monthname = [None,
  499. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  500. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  501. def address_string(self):
  502. """Return the client address."""
  503. return self.client_address[0]
  504. # Essentially static class variables
  505. # The version of the HTTP protocol we support.
  506. # Set this to HTTP/1.1 to enable automatic keepalive
  507. protocol_version = "HTTP/1.0"
  508. # MessageClass used to parse headers
  509. MessageClass = http.client.HTTPMessage
  510. # hack to maintain backwards compatibility
  511. responses = {
  512. v: (v.phrase, v.description)
  513. for v in HTTPStatus.__members__.values()
  514. }
  515. class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
  516. """Simple HTTP request handler with GET and HEAD commands.
  517. This serves files from the current directory and any of its
  518. subdirectories. The MIME type for files is determined by
  519. calling the .guess_type() method.
  520. The GET and HEAD requests are identical except that the HEAD
  521. request omits the actual contents of the file.
  522. """
  523. server_version = "SimpleHTTP/" + __version__
  524. extensions_map = _encodings_map_default = {
  525. '.gz': 'application/gzip',
  526. '.Z': 'application/octet-stream',
  527. '.bz2': 'application/x-bzip2',
  528. '.xz': 'application/x-xz',
  529. }
  530. def __init__(self, *args, directory=None, **kwargs):
  531. if directory is None:
  532. directory = os.getcwd()
  533. self.directory = os.fspath(directory)
  534. super().__init__(*args, **kwargs)
  535. def do_GET(self):
  536. """Serve a GET request."""
  537. f = self.send_head()
  538. if f:
  539. try:
  540. self.copyfile(f, self.wfile)
  541. finally:
  542. f.close()
  543. def do_HEAD(self):
  544. """Serve a HEAD request."""
  545. f = self.send_head()
  546. if f:
  547. f.close()
  548. def send_head(self):
  549. """Common code for GET and HEAD commands.
  550. This sends the response code and MIME headers.
  551. Return value is either a file object (which has to be copied
  552. to the outputfile by the caller unless the command was HEAD,
  553. and must be closed by the caller under all circumstances), or
  554. None, in which case the caller has nothing further to do.
  555. """
  556. path = self.translate_path(self.path)
  557. f = None
  558. if os.path.isdir(path):
  559. parts = urllib.parse.urlsplit(self.path)
  560. if not parts.path.endswith('/'):
  561. # redirect browser - doing basically what apache does
  562. self.send_response(HTTPStatus.MOVED_PERMANENTLY)
  563. new_parts = (parts[0], parts[1], parts[2] + '/',
  564. parts[3], parts[4])
  565. new_url = urllib.parse.urlunsplit(new_parts)
  566. self.send_header("Location", new_url)
  567. self.send_header("Content-Length", "0")
  568. self.end_headers()
  569. return None
  570. for index in "index.html", "index.htm":
  571. index = os.path.join(path, index)
  572. if os.path.isfile(index):
  573. path = index
  574. break
  575. else:
  576. return self.list_directory(path)
  577. ctype = self.guess_type(path)
  578. # check for trailing "/" which should return 404. See Issue17324
  579. # The test for this was added in test_httpserver.py
  580. # However, some OS platforms accept a trailingSlash as a filename
  581. # See discussion on python-dev and Issue34711 regarding
  582. # parsing and rejection of filenames with a trailing slash
  583. if path.endswith("/"):
  584. self.send_error(HTTPStatus.NOT_FOUND, "File not found")
  585. return None
  586. try:
  587. f = open(path, 'rb')
  588. except OSError:
  589. self.send_error(HTTPStatus.NOT_FOUND, "File not found")
  590. return None
  591. try:
  592. fs = os.fstat(f.fileno())
  593. # Use browser cache if possible
  594. if ("If-Modified-Since" in self.headers
  595. and "If-None-Match" not in self.headers):
  596. # compare If-Modified-Since and time of last file modification
  597. try:
  598. ims = email.utils.parsedate_to_datetime(
  599. self.headers["If-Modified-Since"])
  600. except (TypeError, IndexError, OverflowError, ValueError):
  601. # ignore ill-formed values
  602. pass
  603. else:
  604. if ims.tzinfo is None:
  605. # obsolete format with no timezone, cf.
  606. # https://tools.ietf.org/html/rfc7231#section-7.1.1.1
  607. ims = ims.replace(tzinfo=datetime.timezone.utc)
  608. if ims.tzinfo is datetime.timezone.utc:
  609. # compare to UTC datetime of last modification
  610. last_modif = datetime.datetime.fromtimestamp(
  611. fs.st_mtime, datetime.timezone.utc)
  612. # remove microseconds, like in If-Modified-Since
  613. last_modif = last_modif.replace(microsecond=0)
  614. if last_modif <= ims:
  615. self.send_response(HTTPStatus.NOT_MODIFIED)
  616. self.end_headers()
  617. f.close()
  618. return None
  619. self.send_response(HTTPStatus.OK)
  620. self.send_header("Content-type", ctype)
  621. self.send_header("Content-Length", str(fs[6]))
  622. self.send_header("Last-Modified",
  623. self.date_time_string(fs.st_mtime))
  624. self.end_headers()
  625. return f
  626. except:
  627. f.close()
  628. raise
  629. def list_directory(self, path):
  630. """Helper to produce a directory listing (absent index.html).
  631. Return value is either a file object, or None (indicating an
  632. error). In either case, the headers are sent, making the
  633. interface the same as for send_head().
  634. """
  635. try:
  636. list = os.listdir(path)
  637. except OSError:
  638. self.send_error(
  639. HTTPStatus.NOT_FOUND,
  640. "No permission to list directory")
  641. return None
  642. list.sort(key=lambda a: a.lower())
  643. r = []
  644. try:
  645. displaypath = urllib.parse.unquote(self.path,
  646. errors='surrogatepass')
  647. except UnicodeDecodeError:
  648. displaypath = urllib.parse.unquote(path)
  649. displaypath = html.escape(displaypath, quote=False)
  650. enc = sys.getfilesystemencoding()
  651. title = f'Directory listing for {displaypath}'
  652. r.append('<!DOCTYPE HTML>')
  653. r.append('<html lang="en">')
  654. r.append('<head>')
  655. r.append(f'<meta charset="{enc}">')
  656. r.append(f'<title>{title}</title>\n</head>')
  657. r.append(f'<body>\n<h1>{title}</h1>')
  658. r.append('<hr>\n<ul>')
  659. for name in list:
  660. fullname = os.path.join(path, name)
  661. displayname = linkname = name
  662. # Append / for directories or @ for symbolic links
  663. if os.path.isdir(fullname):
  664. displayname = name + "/"
  665. linkname = name + "/"
  666. if os.path.islink(fullname):
  667. displayname = name + "@"
  668. # Note: a link to a directory displays with @ and links with /
  669. r.append('<li><a href="%s">%s</a></li>'
  670. % (urllib.parse.quote(linkname,
  671. errors='surrogatepass'),
  672. html.escape(displayname, quote=False)))
  673. r.append('</ul>\n<hr>\n</body>\n</html>\n')
  674. encoded = '\n'.join(r).encode(enc, 'surrogateescape')
  675. f = io.BytesIO()
  676. f.write(encoded)
  677. f.seek(0)
  678. self.send_response(HTTPStatus.OK)
  679. self.send_header("Content-type", "text/html; charset=%s" % enc)
  680. self.send_header("Content-Length", str(len(encoded)))
  681. self.end_headers()
  682. return f
  683. def translate_path(self, path):
  684. """Translate a /-separated PATH to the local filename syntax.
  685. Components that mean special things to the local file system
  686. (e.g. drive or directory names) are ignored. (XXX They should
  687. probably be diagnosed.)
  688. """
  689. # abandon query parameters
  690. path = path.split('?',1)[0]
  691. path = path.split('#',1)[0]
  692. # Don't forget explicit trailing slash when normalizing. Issue17324
  693. trailing_slash = path.rstrip().endswith('/')
  694. try:
  695. path = urllib.parse.unquote(path, errors='surrogatepass')
  696. except UnicodeDecodeError:
  697. path = urllib.parse.unquote(path)
  698. path = posixpath.normpath(path)
  699. words = path.split('/')
  700. words = filter(None, words)
  701. path = self.directory
  702. for word in words:
  703. if os.path.dirname(word) or word in (os.curdir, os.pardir):
  704. # Ignore components that are not a simple file/directory name
  705. continue
  706. path = os.path.join(path, word)
  707. if trailing_slash:
  708. path += '/'
  709. return path
  710. def copyfile(self, source, outputfile):
  711. """Copy all data between two file objects.
  712. The SOURCE argument is a file object open for reading
  713. (or anything with a read() method) and the DESTINATION
  714. argument is a file object open for writing (or
  715. anything with a write() method).
  716. The only reason for overriding this would be to change
  717. the block size or perhaps to replace newlines by CRLF
  718. -- note however that this the default server uses this
  719. to copy binary data as well.
  720. """
  721. shutil.copyfileobj(source, outputfile)
  722. def guess_type(self, path):
  723. """Guess the type of a file.
  724. Argument is a PATH (a filename).
  725. Return value is a string of the form type/subtype,
  726. usable for a MIME Content-type header.
  727. The default implementation looks the file's extension
  728. up in the table self.extensions_map, using application/octet-stream
  729. as a default; however it would be permissible (if
  730. slow) to look inside the data to make a better guess.
  731. """
  732. base, ext = posixpath.splitext(path)
  733. if ext in self.extensions_map:
  734. return self.extensions_map[ext]
  735. ext = ext.lower()
  736. if ext in self.extensions_map:
  737. return self.extensions_map[ext]
  738. guess, _ = mimetypes.guess_type(path)
  739. if guess:
  740. return guess
  741. return 'application/octet-stream'
  742. # Utilities for CGIHTTPRequestHandler
  743. def _url_collapse_path(path):
  744. """
  745. Given a URL path, remove extra '/'s and '.' path elements and collapse
  746. any '..' references and returns a collapsed path.
  747. Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
  748. The utility of this function is limited to is_cgi method and helps
  749. preventing some security attacks.
  750. Returns: The reconstituted URL, which will always start with a '/'.
  751. Raises: IndexError if too many '..' occur within the path.
  752. """
  753. # Query component should not be involved.
  754. path, _, query = path.partition('?')
  755. path = urllib.parse.unquote(path)
  756. # Similar to os.path.split(os.path.normpath(path)) but specific to URL
  757. # path semantics rather than local operating system semantics.
  758. path_parts = path.split('/')
  759. head_parts = []
  760. for part in path_parts[:-1]:
  761. if part == '..':
  762. head_parts.pop() # IndexError if more '..' than prior parts
  763. elif part and part != '.':
  764. head_parts.append( part )
  765. if path_parts:
  766. tail_part = path_parts.pop()
  767. if tail_part:
  768. if tail_part == '..':
  769. head_parts.pop()
  770. tail_part = ''
  771. elif tail_part == '.':
  772. tail_part = ''
  773. else:
  774. tail_part = ''
  775. if query:
  776. tail_part = '?'.join((tail_part, query))
  777. splitpath = ('/' + '/'.join(head_parts), tail_part)
  778. collapsed_path = "/".join(splitpath)
  779. return collapsed_path
  780. nobody = None
  781. def nobody_uid():
  782. """Internal routine to get nobody's uid"""
  783. global nobody
  784. if nobody:
  785. return nobody
  786. try:
  787. import pwd
  788. except ImportError:
  789. return -1
  790. try:
  791. nobody = pwd.getpwnam('nobody')[2]
  792. except KeyError:
  793. nobody = 1 + max(x[2] for x in pwd.getpwall())
  794. return nobody
  795. def executable(path):
  796. """Test for executable file."""
  797. return os.access(path, os.X_OK)
  798. class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
  799. """Complete HTTP server with GET, HEAD and POST commands.
  800. GET and HEAD also support running CGI scripts.
  801. The POST command is *only* implemented for CGI scripts.
  802. """
  803. # Determine platform specifics
  804. have_fork = hasattr(os, 'fork')
  805. # Make rfile unbuffered -- we need to read one line and then pass
  806. # the rest to a subprocess, so we can't use buffered input.
  807. rbufsize = 0
  808. def do_POST(self):
  809. """Serve a POST request.
  810. This is only implemented for CGI scripts.
  811. """
  812. if self.is_cgi():
  813. self.run_cgi()
  814. else:
  815. self.send_error(
  816. HTTPStatus.NOT_IMPLEMENTED,
  817. "Can only POST to CGI scripts")
  818. def send_head(self):
  819. """Version of send_head that support CGI scripts"""
  820. if self.is_cgi():
  821. return self.run_cgi()
  822. else:
  823. return SimpleHTTPRequestHandler.send_head(self)
  824. def is_cgi(self):
  825. """Test whether self.path corresponds to a CGI script.
  826. Returns True and updates the cgi_info attribute to the tuple
  827. (dir, rest) if self.path requires running a CGI script.
  828. Returns False otherwise.
  829. If any exception is raised, the caller should assume that
  830. self.path was rejected as invalid and act accordingly.
  831. The default implementation tests whether the normalized url
  832. path begins with one of the strings in self.cgi_directories
  833. (and the next character is a '/' or the end of the string).
  834. """
  835. collapsed_path = _url_collapse_path(self.path)
  836. dir_sep = collapsed_path.find('/', 1)
  837. while dir_sep > 0 and not collapsed_path[:dir_sep] in self.cgi_directories:
  838. dir_sep = collapsed_path.find('/', dir_sep+1)
  839. if dir_sep > 0:
  840. head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
  841. self.cgi_info = head, tail
  842. return True
  843. return False
  844. cgi_directories = ['/cgi-bin', '/htbin']
  845. def is_executable(self, path):
  846. """Test whether argument path is an executable file."""
  847. return executable(path)
  848. def is_python(self, path):
  849. """Test whether argument path is a Python script."""
  850. head, tail = os.path.splitext(path)
  851. return tail.lower() in (".py", ".pyw")
  852. def run_cgi(self):
  853. """Execute a CGI script."""
  854. dir, rest = self.cgi_info
  855. path = dir + '/' + rest
  856. i = path.find('/', len(dir)+1)
  857. while i >= 0:
  858. nextdir = path[:i]
  859. nextrest = path[i+1:]
  860. scriptdir = self.translate_path(nextdir)
  861. if os.path.isdir(scriptdir):
  862. dir, rest = nextdir, nextrest
  863. i = path.find('/', len(dir)+1)
  864. else:
  865. break
  866. # find an explicit query string, if present.
  867. rest, _, query = rest.partition('?')
  868. # dissect the part after the directory name into a script name &
  869. # a possible additional path, to be stored in PATH_INFO.
  870. i = rest.find('/')
  871. if i >= 0:
  872. script, rest = rest[:i], rest[i:]
  873. else:
  874. script, rest = rest, ''
  875. scriptname = dir + '/' + script
  876. scriptfile = self.translate_path(scriptname)
  877. if not os.path.exists(scriptfile):
  878. self.send_error(
  879. HTTPStatus.NOT_FOUND,
  880. "No such CGI script (%r)" % scriptname)
  881. return
  882. if not os.path.isfile(scriptfile):
  883. self.send_error(
  884. HTTPStatus.FORBIDDEN,
  885. "CGI script is not a plain file (%r)" % scriptname)
  886. return
  887. ispy = self.is_python(scriptname)
  888. if self.have_fork or not ispy:
  889. if not self.is_executable(scriptfile):
  890. self.send_error(
  891. HTTPStatus.FORBIDDEN,
  892. "CGI script is not executable (%r)" % scriptname)
  893. return
  894. # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
  895. # XXX Much of the following could be prepared ahead of time!
  896. env = copy.deepcopy(os.environ)
  897. env['SERVER_SOFTWARE'] = self.version_string()
  898. env['SERVER_NAME'] = self.server.server_name
  899. env['GATEWAY_INTERFACE'] = 'CGI/1.1'
  900. env['SERVER_PROTOCOL'] = self.protocol_version
  901. env['SERVER_PORT'] = str(self.server.server_port)
  902. env['REQUEST_METHOD'] = self.command
  903. uqrest = urllib.parse.unquote(rest)
  904. env['PATH_INFO'] = uqrest
  905. env['PATH_TRANSLATED'] = self.translate_path(uqrest)
  906. env['SCRIPT_NAME'] = scriptname
  907. env['QUERY_STRING'] = query
  908. env['REMOTE_ADDR'] = self.client_address[0]
  909. authorization = self.headers.get("authorization")
  910. if authorization:
  911. authorization = authorization.split()
  912. if len(authorization) == 2:
  913. import base64, binascii
  914. env['AUTH_TYPE'] = authorization[0]
  915. if authorization[0].lower() == "basic":
  916. try:
  917. authorization = authorization[1].encode('ascii')
  918. authorization = base64.decodebytes(authorization).\
  919. decode('ascii')
  920. except (binascii.Error, UnicodeError):
  921. pass
  922. else:
  923. authorization = authorization.split(':')
  924. if len(authorization) == 2:
  925. env['REMOTE_USER'] = authorization[0]
  926. # XXX REMOTE_IDENT
  927. if self.headers.get('content-type') is None:
  928. env['CONTENT_TYPE'] = self.headers.get_content_type()
  929. else:
  930. env['CONTENT_TYPE'] = self.headers['content-type']
  931. length = self.headers.get('content-length')
  932. if length:
  933. env['CONTENT_LENGTH'] = length
  934. referer = self.headers.get('referer')
  935. if referer:
  936. env['HTTP_REFERER'] = referer
  937. accept = self.headers.get_all('accept', ())
  938. env['HTTP_ACCEPT'] = ','.join(accept)
  939. ua = self.headers.get('user-agent')
  940. if ua:
  941. env['HTTP_USER_AGENT'] = ua
  942. co = filter(None, self.headers.get_all('cookie', []))
  943. cookie_str = ', '.join(co)
  944. if cookie_str:
  945. env['HTTP_COOKIE'] = cookie_str
  946. # XXX Other HTTP_* headers
  947. # Since we're setting the env in the parent, provide empty
  948. # values to override previously set values
  949. for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
  950. 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
  951. env.setdefault(k, "")
  952. self.send_response(HTTPStatus.OK, "Script output follows")
  953. self.flush_headers()
  954. decoded_query = query.replace('+', ' ')
  955. if self.have_fork:
  956. # Unix -- fork as we should
  957. args = [script]
  958. if '=' not in decoded_query:
  959. args.append(decoded_query)
  960. nobody = nobody_uid()
  961. self.wfile.flush() # Always flush before forking
  962. pid = os.fork()
  963. if pid != 0:
  964. # Parent
  965. pid, sts = os.waitpid(pid, 0)
  966. # throw away additional data [see bug #427345]
  967. while select.select([self.rfile], [], [], 0)[0]:
  968. if not self.rfile.read(1):
  969. break
  970. exitcode = os.waitstatus_to_exitcode(sts)
  971. if exitcode:
  972. self.log_error(f"CGI script exit code {exitcode}")
  973. return
  974. # Child
  975. try:
  976. try:
  977. os.setuid(nobody)
  978. except OSError:
  979. pass
  980. os.dup2(self.rfile.fileno(), 0)
  981. os.dup2(self.wfile.fileno(), 1)
  982. os.execve(scriptfile, args, env)
  983. except:
  984. self.server.handle_error(self.request, self.client_address)
  985. os._exit(127)
  986. else:
  987. # Non-Unix -- use subprocess
  988. import subprocess
  989. cmdline = [scriptfile]
  990. if self.is_python(scriptfile):
  991. interp = sys.executable
  992. if interp.lower().endswith("w.exe"):
  993. # On Windows, use python.exe, not pythonw.exe
  994. interp = interp[:-5] + interp[-4:]
  995. cmdline = [interp, '-u'] + cmdline
  996. if '=' not in query:
  997. cmdline.append(query)
  998. self.log_message("command: %s", subprocess.list2cmdline(cmdline))
  999. try:
  1000. nbytes = int(length)
  1001. except (TypeError, ValueError):
  1002. nbytes = 0
  1003. p = subprocess.Popen(cmdline,
  1004. stdin=subprocess.PIPE,
  1005. stdout=subprocess.PIPE,
  1006. stderr=subprocess.PIPE,
  1007. env = env
  1008. )
  1009. if self.command.lower() == "post" and nbytes > 0:
  1010. data = self.rfile.read(nbytes)
  1011. else:
  1012. data = None
  1013. # throw away additional data [see bug #427345]
  1014. while select.select([self.rfile._sock], [], [], 0)[0]:
  1015. if not self.rfile._sock.recv(1):
  1016. break
  1017. stdout, stderr = p.communicate(data)
  1018. self.wfile.write(stdout)
  1019. if stderr:
  1020. self.log_error('%s', stderr)
  1021. p.stderr.close()
  1022. p.stdout.close()
  1023. status = p.returncode
  1024. if status:
  1025. self.log_error("CGI script exit status %#x", status)
  1026. else:
  1027. self.log_message("CGI script exited OK")
  1028. def _get_best_family(*address):
  1029. infos = socket.getaddrinfo(
  1030. *address,
  1031. type=socket.SOCK_STREAM,
  1032. flags=socket.AI_PASSIVE,
  1033. )
  1034. family, type, proto, canonname, sockaddr = next(iter(infos))
  1035. return family, sockaddr
  1036. def test(HandlerClass=BaseHTTPRequestHandler,
  1037. ServerClass=ThreadingHTTPServer,
  1038. protocol="HTTP/1.0", port=8000, bind=None):
  1039. """Test the HTTP request handler class.
  1040. This runs an HTTP server on port 8000 (or the port argument).
  1041. """
  1042. ServerClass.address_family, addr = _get_best_family(bind, port)
  1043. HandlerClass.protocol_version = protocol
  1044. with ServerClass(addr, HandlerClass) as httpd:
  1045. host, port = httpd.socket.getsockname()[:2]
  1046. url_host = f'[{host}]' if ':' in host else host
  1047. print(
  1048. f"Serving HTTP on {host} port {port} "
  1049. f"(http://{url_host}:{port}/) ..."
  1050. )
  1051. try:
  1052. httpd.serve_forever()
  1053. except KeyboardInterrupt:
  1054. print("\nKeyboard interrupt received, exiting.")
  1055. sys.exit(0)
  1056. if __name__ == '__main__':
  1057. import argparse
  1058. import contextlib
  1059. parser = argparse.ArgumentParser()
  1060. parser.add_argument('--cgi', action='store_true',
  1061. help='run as CGI server')
  1062. parser.add_argument('-b', '--bind', metavar='ADDRESS',
  1063. help='bind to this address '
  1064. '(default: all interfaces)')
  1065. parser.add_argument('-d', '--directory', default=os.getcwd(),
  1066. help='serve this directory '
  1067. '(default: current directory)')
  1068. parser.add_argument('-p', '--protocol', metavar='VERSION',
  1069. default='HTTP/1.0',
  1070. help='conform to this HTTP version '
  1071. '(default: %(default)s)')
  1072. parser.add_argument('port', default=8000, type=int, nargs='?',
  1073. help='bind to this port '
  1074. '(default: %(default)s)')
  1075. args = parser.parse_args()
  1076. if args.cgi:
  1077. handler_class = CGIHTTPRequestHandler
  1078. else:
  1079. handler_class = SimpleHTTPRequestHandler
  1080. # ensure dual-stack is not disabled; ref #38907
  1081. class DualStackServer(ThreadingHTTPServer):
  1082. def server_bind(self):
  1083. # suppress exception when protocol is IPv4
  1084. with contextlib.suppress(Exception):
  1085. self.socket.setsockopt(
  1086. socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
  1087. return super().server_bind()
  1088. def finish_request(self, request, client_address):
  1089. self.RequestHandlerClass(request, client_address, self,
  1090. directory=args.directory)
  1091. test(
  1092. HandlerClass=handler_class,
  1093. ServerClass=DualStackServer,
  1094. port=args.port,
  1095. bind=args.bind,
  1096. protocol=args.protocol,
  1097. )