server.py 45 KB

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