server.py 47 KB

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