server.py 47 KB

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