BaseHTTPServer.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. """HTTP server base class.
  2. Note: the class in this module doesn't implement any HTTP request; see
  3. SimpleHTTPServer for simple implementations of GET, HEAD and POST
  4. (including CGI scripts). It does, however, optionally implement HTTP/1.1
  5. persistent connections, as of version 0.3.
  6. Contents:
  7. - BaseHTTPRequestHandler: HTTP request handler base class
  8. - test: test function
  9. XXX To do:
  10. - log requests even later (to capture byte count)
  11. - log user-agent header and other interesting goodies
  12. - send error log to separate file
  13. """
  14. # See also:
  15. #
  16. # HTTP Working Group T. Berners-Lee
  17. # INTERNET-DRAFT R. T. Fielding
  18. # <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
  19. # Expires September 8, 1995 March 8, 1995
  20. #
  21. # URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
  22. #
  23. # and
  24. #
  25. # Network Working Group R. Fielding
  26. # Request for Comments: 2616 et al
  27. # Obsoletes: 2068 June 1999
  28. # Category: Standards Track
  29. #
  30. # URL: http://www.faqs.org/rfcs/rfc2616.html
  31. # Log files
  32. # ---------
  33. #
  34. # Here's a quote from the NCSA httpd docs about log file format.
  35. #
  36. # | The logfile format is as follows. Each line consists of:
  37. # |
  38. # | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
  39. # |
  40. # | host: Either the DNS name or the IP number of the remote client
  41. # | rfc931: Any information returned by identd for this person,
  42. # | - otherwise.
  43. # | authuser: If user sent a userid for authentication, the user name,
  44. # | - otherwise.
  45. # | DD: Day
  46. # | Mon: Month (calendar name)
  47. # | YYYY: Year
  48. # | hh: hour (24-hour format, the machine's timezone)
  49. # | mm: minutes
  50. # | ss: seconds
  51. # | request: The first line of the HTTP request as sent by the client.
  52. # | ddd: the status code returned by the server, - if not available.
  53. # | bbbb: the total number of bytes sent,
  54. # | *not including the HTTP/1.0 header*, - if not available
  55. # |
  56. # | You can determine the name of the file accessed through request.
  57. #
  58. # (Actually, the latter is only true if you know the server configuration
  59. # at the time the request was made!)
  60. __version__ = "0.3"
  61. __all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
  62. import sys
  63. import time
  64. import socket # For gethostbyaddr()
  65. from warnings import filterwarnings, catch_warnings
  66. with catch_warnings():
  67. if sys.py3kwarning:
  68. filterwarnings("ignore", ".*mimetools has been removed",
  69. DeprecationWarning)
  70. import mimetools
  71. import SocketServer
  72. # Default error message template
  73. DEFAULT_ERROR_MESSAGE = """\
  74. <head>
  75. <title>Error response</title>
  76. </head>
  77. <body>
  78. <h1>Error response</h1>
  79. <p>Error code %(code)d.
  80. <p>Message: %(message)s.
  81. <p>Error code explanation: %(code)s = %(explain)s.
  82. </body>
  83. """
  84. DEFAULT_ERROR_CONTENT_TYPE = "text/html"
  85. def _quote_html(html):
  86. return html.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
  87. class HTTPServer(SocketServer.TCPServer):
  88. allow_reuse_address = 1 # Seems to make sense in testing environment
  89. def server_bind(self):
  90. """Override server_bind to store the server name."""
  91. SocketServer.TCPServer.server_bind(self)
  92. host, port = self.socket.getsockname()[:2]
  93. self.server_name = socket.getfqdn(host)
  94. self.server_port = port
  95. class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
  96. """HTTP request handler base class.
  97. The following explanation of HTTP serves to guide you through the
  98. code as well as to expose any misunderstandings I may have about
  99. HTTP (so you don't need to read the code to figure out I'm wrong
  100. :-).
  101. HTTP (HyperText Transfer Protocol) is an extensible protocol on
  102. top of a reliable stream transport (e.g. TCP/IP). The protocol
  103. recognizes three parts to a request:
  104. 1. One line identifying the request type and path
  105. 2. An optional set of RFC-822-style headers
  106. 3. An optional data part
  107. The headers and data are separated by a blank line.
  108. The first line of the request has the form
  109. <command> <path> <version>
  110. where <command> is a (case-sensitive) keyword such as GET or POST,
  111. <path> is a string containing path information for the request,
  112. and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
  113. <path> is encoded using the URL encoding scheme (using %xx to signify
  114. the ASCII character with hex code xx).
  115. The specification specifies that lines are separated by CRLF but
  116. for compatibility with the widest range of clients recommends
  117. servers also handle LF. Similarly, whitespace in the request line
  118. is treated sensibly (allowing multiple spaces between components
  119. and allowing trailing whitespace).
  120. Similarly, for output, lines ought to be separated by CRLF pairs
  121. but most clients grok LF characters just fine.
  122. If the first line of the request has the form
  123. <command> <path>
  124. (i.e. <version> is left out) then this is assumed to be an HTTP
  125. 0.9 request; this form has no optional headers and data part and
  126. the reply consists of just the data.
  127. The reply form of the HTTP 1.x protocol again has three parts:
  128. 1. One line giving the response code
  129. 2. An optional set of RFC-822-style headers
  130. 3. The data
  131. Again, the headers and data are separated by a blank line.
  132. The response code line has the form
  133. <version> <responsecode> <responsestring>
  134. where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
  135. <responsecode> is a 3-digit response code indicating success or
  136. failure of the request, and <responsestring> is an optional
  137. human-readable string explaining what the response code means.
  138. This server parses the request and the headers, and then calls a
  139. function specific to the request type (<command>). Specifically,
  140. a request SPAM will be handled by a method do_SPAM(). If no
  141. such method exists the server sends an error response to the
  142. client. If it exists, it is called with no arguments:
  143. do_SPAM()
  144. Note that the request name is case sensitive (i.e. SPAM and spam
  145. are different requests).
  146. The various request details are stored in instance variables:
  147. - client_address is the client IP address in the form (host,
  148. port);
  149. - command, path and version are the broken-down request line;
  150. - headers is an instance of mimetools.Message (or a derived
  151. class) containing the header information;
  152. - rfile is a file object open for reading positioned at the
  153. start of the optional input data part;
  154. - wfile is a file object open for writing.
  155. IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
  156. The first thing to be written must be the response line. Then
  157. follow 0 or more header lines, then a blank line, and then the
  158. actual data (if any). The meaning of the header lines depends on
  159. the command executed by the server; in most cases, when data is
  160. returned, there should be at least one header line of the form
  161. Content-type: <type>/<subtype>
  162. where <type> and <subtype> should be registered MIME types,
  163. e.g. "text/html" or "text/plain".
  164. """
  165. # The Python system version, truncated to its first component.
  166. sys_version = "Python/" + sys.version.split()[0]
  167. # The server software version. You may want to override this.
  168. # The format is multiple whitespace-separated strings,
  169. # where each string is of the form name[/version].
  170. server_version = "BaseHTTP/" + __version__
  171. # The default request version. This only affects responses up until
  172. # the point where the request line is parsed, so it mainly decides what
  173. # the client gets back when sending a malformed request line.
  174. # Most web servers default to HTTP 0.9, i.e. don't send a status line.
  175. default_request_version = "HTTP/0.9"
  176. def parse_request(self):
  177. """Parse a request (internal).
  178. The request should be stored in self.raw_requestline; the results
  179. are in self.command, self.path, self.request_version and
  180. self.headers.
  181. Return True for success, False for failure; on failure, an
  182. error is sent back.
  183. """
  184. self.command = None # set in case of error on the first line
  185. self.request_version = version = self.default_request_version
  186. self.close_connection = 1
  187. requestline = self.raw_requestline
  188. requestline = requestline.rstrip('\r\n')
  189. self.requestline = requestline
  190. words = requestline.split()
  191. if len(words) == 3:
  192. command, path, version = words
  193. if version[:5] != 'HTTP/':
  194. self.send_error(400, "Bad request version (%r)" % version)
  195. return False
  196. try:
  197. base_version_number = version.split('/', 1)[1]
  198. version_number = base_version_number.split(".")
  199. # RFC 2145 section 3.1 says there can be only one "." and
  200. # - major and minor numbers MUST be treated as
  201. # separate integers;
  202. # - HTTP/2.4 is a lower version than HTTP/2.13, which in
  203. # turn is lower than HTTP/12.3;
  204. # - Leading zeros MUST be ignored by recipients.
  205. if len(version_number) != 2:
  206. raise ValueError
  207. version_number = int(version_number[0]), int(version_number[1])
  208. except (ValueError, IndexError):
  209. self.send_error(400, "Bad request version (%r)" % version)
  210. return False
  211. if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
  212. self.close_connection = 0
  213. if version_number >= (2, 0):
  214. self.send_error(505,
  215. "Invalid HTTP Version (%s)" % base_version_number)
  216. return False
  217. elif len(words) == 2:
  218. command, path = words
  219. self.close_connection = 1
  220. if command != 'GET':
  221. self.send_error(400,
  222. "Bad HTTP/0.9 request type (%r)" % command)
  223. return False
  224. elif not words:
  225. return False
  226. else:
  227. self.send_error(400, "Bad request syntax (%r)" % requestline)
  228. return False
  229. self.command, self.path, self.request_version = command, path, version
  230. # Examine the headers and look for a Connection directive
  231. self.headers = self.MessageClass(self.rfile, 0)
  232. conntype = self.headers.get('Connection', "")
  233. if conntype.lower() == 'close':
  234. self.close_connection = 1
  235. elif (conntype.lower() == 'keep-alive' and
  236. self.protocol_version >= "HTTP/1.1"):
  237. self.close_connection = 0
  238. return True
  239. def handle_one_request(self):
  240. """Handle a single HTTP request.
  241. You normally don't need to override this method; see the class
  242. __doc__ string for information on how to handle specific HTTP
  243. commands such as GET and POST.
  244. """
  245. try:
  246. self.raw_requestline = self.rfile.readline(65537)
  247. if len(self.raw_requestline) > 65536:
  248. self.requestline = ''
  249. self.request_version = ''
  250. self.command = ''
  251. self.send_error(414)
  252. return
  253. if not self.raw_requestline:
  254. self.close_connection = 1
  255. return
  256. if not self.parse_request():
  257. # An error code has been sent, just exit
  258. return
  259. mname = 'do_' + self.command
  260. if not hasattr(self, mname):
  261. self.send_error(501, "Unsupported method (%r)" % self.command)
  262. return
  263. method = getattr(self, mname)
  264. method()
  265. self.wfile.flush() #actually send the response if not already done.
  266. except socket.timeout, e:
  267. #a read or a write timed out. Discard this connection
  268. self.log_error("Request timed out: %r", e)
  269. self.close_connection = 1
  270. return
  271. def handle(self):
  272. """Handle multiple requests if necessary."""
  273. self.close_connection = 1
  274. self.handle_one_request()
  275. while not self.close_connection:
  276. self.handle_one_request()
  277. def send_error(self, code, message=None):
  278. """Send and log an error reply.
  279. Arguments are the error code, and a detailed message.
  280. The detailed message defaults to the short entry matching the
  281. response code.
  282. This sends an error response (so it must be called before any
  283. output has been generated), logs the error, and finally sends
  284. a piece of HTML explaining the error to the user.
  285. """
  286. try:
  287. short, long = self.responses[code]
  288. except KeyError:
  289. short, long = '???', '???'
  290. if message is None:
  291. message = short
  292. explain = long
  293. self.log_error("code %d, message %s", code, message)
  294. self.send_response(code, message)
  295. self.send_header('Connection', 'close')
  296. # Message body is omitted for cases described in:
  297. # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
  298. # - RFC7231: 6.3.6. 205(Reset Content)
  299. content = None
  300. if code >= 200 and code not in (204, 205, 304):
  301. # HTML encode to prevent Cross Site Scripting attacks
  302. # (see bug #1100201)
  303. content = (self.error_message_format % {
  304. 'code': code,
  305. 'message': _quote_html(message),
  306. 'explain': explain
  307. })
  308. self.send_header("Content-Type", self.error_content_type)
  309. self.end_headers()
  310. if self.command != 'HEAD' and content:
  311. self.wfile.write(content)
  312. error_message_format = DEFAULT_ERROR_MESSAGE
  313. error_content_type = DEFAULT_ERROR_CONTENT_TYPE
  314. def send_response(self, code, message=None):
  315. """Send the response header and log the response code.
  316. Also send two standard headers with the server software
  317. version and the current date.
  318. """
  319. self.log_request(code)
  320. if message is None:
  321. if code in self.responses:
  322. message = self.responses[code][0]
  323. else:
  324. message = ''
  325. if self.request_version != 'HTTP/0.9':
  326. self.wfile.write("%s %d %s\r\n" %
  327. (self.protocol_version, code, message))
  328. # print (self.protocol_version, code, message)
  329. self.send_header('Server', self.version_string())
  330. self.send_header('Date', self.date_time_string())
  331. def send_header(self, keyword, value):
  332. """Send a MIME header."""
  333. if self.request_version != 'HTTP/0.9':
  334. self.wfile.write("%s: %s\r\n" % (keyword, value))
  335. if keyword.lower() == 'connection':
  336. if value.lower() == 'close':
  337. self.close_connection = 1
  338. elif value.lower() == 'keep-alive':
  339. self.close_connection = 0
  340. def end_headers(self):
  341. """Send the blank line ending the MIME headers."""
  342. if self.request_version != 'HTTP/0.9':
  343. self.wfile.write("\r\n")
  344. def log_request(self, code='-', size='-'):
  345. """Log an accepted request.
  346. This is called by send_response().
  347. """
  348. self.log_message('"%s" %s %s',
  349. self.requestline, str(code), str(size))
  350. def log_error(self, format, *args):
  351. """Log an error.
  352. This is called when a request cannot be fulfilled. By
  353. default it passes the message on to log_message().
  354. Arguments are the same as for log_message().
  355. XXX This should go to the separate error log.
  356. """
  357. self.log_message(format, *args)
  358. def log_message(self, format, *args):
  359. """Log an arbitrary message.
  360. This is used by all other logging functions. Override
  361. it if you have specific logging wishes.
  362. The first argument, FORMAT, is a format string for the
  363. message to be logged. If the format string contains
  364. any % escapes requiring parameters, they should be
  365. specified as subsequent arguments (it's just like
  366. printf!).
  367. The client ip address and current date/time are prefixed to every
  368. message.
  369. """
  370. sys.stderr.write("%s - - [%s] %s\n" %
  371. (self.client_address[0],
  372. self.log_date_time_string(),
  373. format%args))
  374. def version_string(self):
  375. """Return the server software version string."""
  376. return self.server_version + ' ' + self.sys_version
  377. def date_time_string(self, timestamp=None):
  378. """Return the current date and time formatted for a message header."""
  379. if timestamp is None:
  380. timestamp = time.time()
  381. year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
  382. s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
  383. self.weekdayname[wd],
  384. day, self.monthname[month], year,
  385. hh, mm, ss)
  386. return s
  387. def log_date_time_string(self):
  388. """Return the current time formatted for logging."""
  389. now = time.time()
  390. year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
  391. s = "%02d/%3s/%04d %02d:%02d:%02d" % (
  392. day, self.monthname[month], year, hh, mm, ss)
  393. return s
  394. weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  395. monthname = [None,
  396. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  397. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  398. def address_string(self):
  399. """Return the client address formatted for logging.
  400. This version looks up the full hostname using gethostbyaddr(),
  401. and tries to find a name that contains at least one dot.
  402. """
  403. host, port = self.client_address[:2]
  404. return socket.getfqdn(host)
  405. # Essentially static class variables
  406. # The version of the HTTP protocol we support.
  407. # Set this to HTTP/1.1 to enable automatic keepalive
  408. protocol_version = "HTTP/1.0"
  409. # The Message-like class used to parse headers
  410. MessageClass = mimetools.Message
  411. # Table mapping response codes to messages; entries have the
  412. # form {code: (shortmessage, longmessage)}.
  413. # See RFC 2616.
  414. responses = {
  415. 100: ('Continue', 'Request received, please continue'),
  416. 101: ('Switching Protocols',
  417. 'Switching to new protocol; obey Upgrade header'),
  418. 200: ('OK', 'Request fulfilled, document follows'),
  419. 201: ('Created', 'Document created, URL follows'),
  420. 202: ('Accepted',
  421. 'Request accepted, processing continues off-line'),
  422. 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
  423. 204: ('No Content', 'Request fulfilled, nothing follows'),
  424. 205: ('Reset Content', 'Clear input form for further input.'),
  425. 206: ('Partial Content', 'Partial content follows.'),
  426. 300: ('Multiple Choices',
  427. 'Object has several resources -- see URI list'),
  428. 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
  429. 302: ('Found', 'Object moved temporarily -- see URI list'),
  430. 303: ('See Other', 'Object moved -- see Method and URL list'),
  431. 304: ('Not Modified',
  432. 'Document has not changed since given time'),
  433. 305: ('Use Proxy',
  434. 'You must use proxy specified in Location to access this '
  435. 'resource.'),
  436. 307: ('Temporary Redirect',
  437. 'Object moved temporarily -- see URI list'),
  438. 400: ('Bad Request',
  439. 'Bad request syntax or unsupported method'),
  440. 401: ('Unauthorized',
  441. 'No permission -- see authorization schemes'),
  442. 402: ('Payment Required',
  443. 'No payment -- see charging schemes'),
  444. 403: ('Forbidden',
  445. 'Request forbidden -- authorization will not help'),
  446. 404: ('Not Found', 'Nothing matches the given URI'),
  447. 405: ('Method Not Allowed',
  448. 'Specified method is invalid for this resource.'),
  449. 406: ('Not Acceptable', 'URI not available in preferred format.'),
  450. 407: ('Proxy Authentication Required', 'You must authenticate with '
  451. 'this proxy before proceeding.'),
  452. 408: ('Request Timeout', 'Request timed out; try again later.'),
  453. 409: ('Conflict', 'Request conflict.'),
  454. 410: ('Gone',
  455. 'URI no longer exists and has been permanently removed.'),
  456. 411: ('Length Required', 'Client must specify Content-Length.'),
  457. 412: ('Precondition Failed', 'Precondition in headers is false.'),
  458. 413: ('Request Entity Too Large', 'Entity is too large.'),
  459. 414: ('Request-URI Too Long', 'URI is too long.'),
  460. 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
  461. 416: ('Requested Range Not Satisfiable',
  462. 'Cannot satisfy request range.'),
  463. 417: ('Expectation Failed',
  464. 'Expect condition could not be satisfied.'),
  465. 500: ('Internal Server Error', 'Server got itself in trouble'),
  466. 501: ('Not Implemented',
  467. 'Server does not support this operation'),
  468. 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
  469. 503: ('Service Unavailable',
  470. 'The server cannot process the request due to a high load'),
  471. 504: ('Gateway Timeout',
  472. 'The gateway server did not receive a timely response'),
  473. 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
  474. }
  475. def test(HandlerClass = BaseHTTPRequestHandler,
  476. ServerClass = HTTPServer, protocol="HTTP/1.0"):
  477. """Test the HTTP request handler class.
  478. This runs an HTTP server on port 8000 (or the first command line
  479. argument).
  480. """
  481. if sys.argv[1:]:
  482. port = int(sys.argv[1])
  483. else:
  484. port = 8000
  485. server_address = ('', port)
  486. HandlerClass.protocol_version = protocol
  487. httpd = ServerClass(server_address, HandlerClass)
  488. sa = httpd.socket.getsockname()
  489. print "Serving HTTP on", sa[0], "port", sa[1], "..."
  490. httpd.serve_forever()
  491. if __name__ == '__main__':
  492. test()