logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

server.py (47271B)


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