server.py 44 KB

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