blob: 5569037427dd9c8e6d05bf2566b6f9336086d09d [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001"""HTTP server classes.
2
3Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
4SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
5and CGIHTTPRequestHandler for CGI scripts.
6
7It does, however, optionally implement HTTP/1.1 persistent connections,
8as of version 0.3.
9
10Notes on CGIHTTPRequestHandler
11------------------------------
12
13This class implements GET and POST requests to cgi-bin scripts.
14
15If the os.fork() function is not present (e.g. on Windows),
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +000016subprocess.Popen() is used as a fallback, with slightly altered semantics.
Georg Brandl24420152008-05-26 16:32:26 +000017
18In all cases, the implementation is intentionally naive -- all
19requests are executed synchronously.
20
21SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
22-- it may execute arbitrary Python code or external programs.
23
24Note that status code 200 is sent prior to execution of a CGI script, so
25scripts cannot send other status codes such as 302 (redirect).
26
27XXX To do:
28
29- log requests even later (to capture byte count)
30- log user-agent header and other interesting goodies
31- send error log to separate file
32"""
33
34
35# See also:
36#
37# HTTP Working Group T. Berners-Lee
38# INTERNET-DRAFT R. T. Fielding
39# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
40# Expires September 8, 1995 March 8, 1995
41#
42# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
43#
44# and
45#
46# Network Working Group R. Fielding
47# Request for Comments: 2616 et al
48# Obsoletes: 2068 June 1999
49# Category: Standards Track
50#
51# URL: http://www.faqs.org/rfcs/rfc2616.html
52
53# Log files
54# ---------
55#
56# Here's a quote from the NCSA httpd docs about log file format.
57#
58# | The logfile format is as follows. Each line consists of:
59# |
60# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
61# |
62# | host: Either the DNS name or the IP number of the remote client
63# | rfc931: Any information returned by identd for this person,
64# | - otherwise.
65# | authuser: If user sent a userid for authentication, the user name,
66# | - otherwise.
67# | DD: Day
68# | Mon: Month (calendar name)
69# | YYYY: Year
70# | hh: hour (24-hour format, the machine's timezone)
71# | mm: minutes
72# | ss: seconds
73# | request: The first line of the HTTP request as sent by the client.
74# | ddd: the status code returned by the server, - if not available.
75# | bbbb: the total number of bytes sent,
76# | *not including the HTTP/1.0 header*, - if not available
77# |
78# | You can determine the name of the file accessed through request.
79#
80# (Actually, the latter is only true if you know the server configuration
81# at the time the request was made!)
82
83__version__ = "0.6"
84
85__all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
86
Georg Brandl1f7fffb2010-10-15 15:57:45 +000087import html
Barry Warsaw820c1202008-06-12 04:06:45 +000088import email.message
89import email.parser
Jeremy Hylton914ab452009-03-27 17:16:06 +000090import http.client
91import io
92import mimetypes
93import os
94import posixpath
95import select
96import shutil
97import socket # For gethostbyaddr()
98import socketserver
99import sys
100import time
101import urllib.parse
Senthil Kumaran42713722010-10-03 17:55:45 +0000102import copy
Georg Brandl24420152008-05-26 16:32:26 +0000103
104# Default error message template
105DEFAULT_ERROR_MESSAGE = """\
Senthil Kumaran1b407fe2011-03-20 10:44:30 +0800106<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
107 "http://www.w3.org/TR/html4/strict.dtd">
Senthil Kumaranb253c9f2011-03-17 16:43:22 +0800108 <head>
Senthil Kumaran1b407fe2011-03-20 10:44:30 +0800109 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
Senthil Kumaranb253c9f2011-03-17 16:43:22 +0800110 <title>Error response</title>
111 </head>
112 <body>
113 <h1>Error response</h1>
114 <p>Error code: %(code)d</p>
115 <p>Message: %(message)s.</p>
116 <p>Error code explanation: %(code)s - %(explain)s.</p>
117 </body>
118</html>
Georg Brandl24420152008-05-26 16:32:26 +0000119"""
120
121DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
122
123def _quote_html(html):
124 return html.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
125
126class HTTPServer(socketserver.TCPServer):
127
128 allow_reuse_address = 1 # Seems to make sense in testing environment
129
130 def server_bind(self):
131 """Override server_bind to store the server name."""
132 socketserver.TCPServer.server_bind(self)
133 host, port = self.socket.getsockname()[:2]
134 self.server_name = socket.getfqdn(host)
135 self.server_port = port
136
137
138class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
139
140 """HTTP request handler base class.
141
142 The following explanation of HTTP serves to guide you through the
143 code as well as to expose any misunderstandings I may have about
144 HTTP (so you don't need to read the code to figure out I'm wrong
145 :-).
146
147 HTTP (HyperText Transfer Protocol) is an extensible protocol on
148 top of a reliable stream transport (e.g. TCP/IP). The protocol
149 recognizes three parts to a request:
150
151 1. One line identifying the request type and path
152 2. An optional set of RFC-822-style headers
153 3. An optional data part
154
155 The headers and data are separated by a blank line.
156
157 The first line of the request has the form
158
159 <command> <path> <version>
160
161 where <command> is a (case-sensitive) keyword such as GET or POST,
162 <path> is a string containing path information for the request,
163 and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
164 <path> is encoded using the URL encoding scheme (using %xx to signify
165 the ASCII character with hex code xx).
166
167 The specification specifies that lines are separated by CRLF but
168 for compatibility with the widest range of clients recommends
169 servers also handle LF. Similarly, whitespace in the request line
170 is treated sensibly (allowing multiple spaces between components
171 and allowing trailing whitespace).
172
173 Similarly, for output, lines ought to be separated by CRLF pairs
174 but most clients grok LF characters just fine.
175
176 If the first line of the request has the form
177
178 <command> <path>
179
180 (i.e. <version> is left out) then this is assumed to be an HTTP
181 0.9 request; this form has no optional headers and data part and
182 the reply consists of just the data.
183
184 The reply form of the HTTP 1.x protocol again has three parts:
185
186 1. One line giving the response code
187 2. An optional set of RFC-822-style headers
188 3. The data
189
190 Again, the headers and data are separated by a blank line.
191
192 The response code line has the form
193
194 <version> <responsecode> <responsestring>
195
196 where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
197 <responsecode> is a 3-digit response code indicating success or
198 failure of the request, and <responsestring> is an optional
199 human-readable string explaining what the response code means.
200
201 This server parses the request and the headers, and then calls a
202 function specific to the request type (<command>). Specifically,
203 a request SPAM will be handled by a method do_SPAM(). If no
204 such method exists the server sends an error response to the
205 client. If it exists, it is called with no arguments:
206
207 do_SPAM()
208
209 Note that the request name is case sensitive (i.e. SPAM and spam
210 are different requests).
211
212 The various request details are stored in instance variables:
213
214 - client_address is the client IP address in the form (host,
215 port);
216
217 - command, path and version are the broken-down request line;
218
Barry Warsaw820c1202008-06-12 04:06:45 +0000219 - headers is an instance of email.message.Message (or a derived
Georg Brandl24420152008-05-26 16:32:26 +0000220 class) containing the header information;
221
222 - rfile is a file object open for reading positioned at the
223 start of the optional input data part;
224
225 - wfile is a file object open for writing.
226
227 IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
228
229 The first thing to be written must be the response line. Then
230 follow 0 or more header lines, then a blank line, and then the
231 actual data (if any). The meaning of the header lines depends on
232 the command executed by the server; in most cases, when data is
233 returned, there should be at least one header line of the form
234
235 Content-type: <type>/<subtype>
236
237 where <type> and <subtype> should be registered MIME types,
238 e.g. "text/html" or "text/plain".
239
240 """
241
242 # The Python system version, truncated to its first component.
243 sys_version = "Python/" + sys.version.split()[0]
244
245 # The server software version. You may want to override this.
246 # The format is multiple whitespace-separated strings,
247 # where each string is of the form name[/version].
248 server_version = "BaseHTTP/" + __version__
249
250 error_message_format = DEFAULT_ERROR_MESSAGE
251 error_content_type = DEFAULT_ERROR_CONTENT_TYPE
252
253 # The default request version. This only affects responses up until
254 # the point where the request line is parsed, so it mainly decides what
255 # the client gets back when sending a malformed request line.
256 # Most web servers default to HTTP 0.9, i.e. don't send a status line.
257 default_request_version = "HTTP/0.9"
258
259 def parse_request(self):
260 """Parse a request (internal).
261
262 The request should be stored in self.raw_requestline; the results
263 are in self.command, self.path, self.request_version and
264 self.headers.
265
266 Return True for success, False for failure; on failure, an
267 error is sent back.
268
269 """
270 self.command = None # set in case of error on the first line
271 self.request_version = version = self.default_request_version
272 self.close_connection = 1
273 requestline = str(self.raw_requestline, 'iso-8859-1')
Senthil Kumaran30755492011-12-23 17:03:41 +0800274 requestline = requestline.rstrip('\r\n')
Georg Brandl24420152008-05-26 16:32:26 +0000275 self.requestline = requestline
276 words = requestline.split()
277 if len(words) == 3:
Senthil Kumaran30755492011-12-23 17:03:41 +0800278 command, path, version = words
Georg Brandl24420152008-05-26 16:32:26 +0000279 if version[:5] != 'HTTP/':
280 self.send_error(400, "Bad request version (%r)" % version)
281 return False
282 try:
283 base_version_number = version.split('/', 1)[1]
284 version_number = base_version_number.split(".")
285 # RFC 2145 section 3.1 says there can be only one "." and
286 # - major and minor numbers MUST be treated as
287 # separate integers;
288 # - HTTP/2.4 is a lower version than HTTP/2.13, which in
289 # turn is lower than HTTP/12.3;
290 # - Leading zeros MUST be ignored by recipients.
291 if len(version_number) != 2:
292 raise ValueError
293 version_number = int(version_number[0]), int(version_number[1])
294 except (ValueError, IndexError):
295 self.send_error(400, "Bad request version (%r)" % version)
296 return False
297 if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
298 self.close_connection = 0
299 if version_number >= (2, 0):
300 self.send_error(505,
301 "Invalid HTTP Version (%s)" % base_version_number)
302 return False
303 elif len(words) == 2:
Senthil Kumaran30755492011-12-23 17:03:41 +0800304 command, path = words
Georg Brandl24420152008-05-26 16:32:26 +0000305 self.close_connection = 1
306 if command != 'GET':
307 self.send_error(400,
308 "Bad HTTP/0.9 request type (%r)" % command)
309 return False
310 elif not words:
311 return False
312 else:
313 self.send_error(400, "Bad request syntax (%r)" % requestline)
314 return False
315 self.command, self.path, self.request_version = command, path, version
316
317 # Examine the headers and look for a Connection directive.
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000318 try:
319 self.headers = http.client.parse_headers(self.rfile,
320 _class=self.MessageClass)
321 except http.client.LineTooLong:
322 self.send_error(400, "Line too long")
323 return False
Georg Brandl24420152008-05-26 16:32:26 +0000324
325 conntype = self.headers.get('Connection', "")
326 if conntype.lower() == 'close':
327 self.close_connection = 1
328 elif (conntype.lower() == 'keep-alive' and
329 self.protocol_version >= "HTTP/1.1"):
330 self.close_connection = 0
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000331 # Examine the headers and look for an Expect directive
332 expect = self.headers.get('Expect', "")
333 if (expect.lower() == "100-continue" and
334 self.protocol_version >= "HTTP/1.1" and
335 self.request_version >= "HTTP/1.1"):
336 if not self.handle_expect_100():
337 return False
338 return True
339
340 def handle_expect_100(self):
341 """Decide what to do with an "Expect: 100-continue" header.
342
343 If the client is expecting a 100 Continue response, we must
344 respond with either a 100 Continue or a final response before
345 waiting for the request body. The default is to always respond
346 with a 100 Continue. You can behave differently (for example,
347 reject unauthorized requests) by overriding this method.
348
349 This method should either return True (possibly after sending
350 a 100 Continue response) or send an error response and return
351 False.
352
353 """
354 self.send_response_only(100)
Georg Brandl24420152008-05-26 16:32:26 +0000355 return True
356
357 def handle_one_request(self):
358 """Handle a single HTTP request.
359
360 You normally don't need to override this method; see the class
361 __doc__ string for information on how to handle specific HTTP
362 commands such as GET and POST.
363
364 """
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000365 try:
Antoine Pitrouc4924372010-12-16 16:48:36 +0000366 self.raw_requestline = self.rfile.readline(65537)
367 if len(self.raw_requestline) > 65536:
368 self.requestline = ''
369 self.request_version = ''
370 self.command = ''
371 self.send_error(414)
372 return
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000373 if not self.raw_requestline:
374 self.close_connection = 1
375 return
376 if not self.parse_request():
377 # An error code has been sent, just exit
378 return
379 mname = 'do_' + self.command
380 if not hasattr(self, mname):
381 self.send_error(501, "Unsupported method (%r)" % self.command)
382 return
383 method = getattr(self, mname)
384 method()
385 self.wfile.flush() #actually send the response if not already done.
386 except socket.timeout as e:
387 #a read or a write timed out. Discard this connection
388 self.log_error("Request timed out: %r", e)
Georg Brandl24420152008-05-26 16:32:26 +0000389 self.close_connection = 1
390 return
Georg Brandl24420152008-05-26 16:32:26 +0000391
392 def handle(self):
393 """Handle multiple requests if necessary."""
394 self.close_connection = 1
395
396 self.handle_one_request()
397 while not self.close_connection:
398 self.handle_one_request()
399
400 def send_error(self, code, message=None):
401 """Send and log an error reply.
402
403 Arguments are the error code, and a detailed message.
404 The detailed message defaults to the short entry matching the
405 response code.
406
407 This sends an error response (so it must be called before any
408 output has been generated), logs the error, and finally sends
409 a piece of HTML explaining the error to the user.
410
411 """
412
413 try:
414 shortmsg, longmsg = self.responses[code]
415 except KeyError:
416 shortmsg, longmsg = '???', '???'
417 if message is None:
418 message = shortmsg
419 explain = longmsg
420 self.log_error("code %d, message %s", code, message)
421 # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
422 content = (self.error_message_format %
423 {'code': code, 'message': _quote_html(message), 'explain': explain})
424 self.send_response(code, message)
425 self.send_header("Content-Type", self.error_content_type)
426 self.send_header('Connection', 'close')
427 self.end_headers()
428 if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
429 self.wfile.write(content.encode('UTF-8', 'replace'))
430
431 def send_response(self, code, message=None):
432 """Send the response header and log the response code.
433
434 Also send two standard headers with the server software
435 version and the current date.
436
437 """
438 self.log_request(code)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000439 self.send_response_only(code, message)
440 self.send_header('Server', self.version_string())
441 self.send_header('Date', self.date_time_string())
442
443 def send_response_only(self, code, message=None):
444 """Send the response header only."""
Georg Brandl24420152008-05-26 16:32:26 +0000445 if message is None:
446 if code in self.responses:
447 message = self.responses[code][0]
448 else:
449 message = ''
450 if self.request_version != 'HTTP/0.9':
451 self.wfile.write(("%s %d %s\r\n" %
Armin Ronacher8d96d772011-01-22 13:13:05 +0000452 (self.protocol_version, code, message)).encode('latin1', 'strict'))
Georg Brandl24420152008-05-26 16:32:26 +0000453
454 def send_header(self, keyword, value):
455 """Send a MIME header."""
456 if self.request_version != 'HTTP/0.9':
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000457 if not hasattr(self, '_headers_buffer'):
458 self._headers_buffer = []
459 self._headers_buffer.append(
Armin Ronacher8d96d772011-01-22 13:13:05 +0000460 ("%s: %s\r\n" % (keyword, value)).encode('latin1', 'strict'))
Georg Brandl24420152008-05-26 16:32:26 +0000461
462 if keyword.lower() == 'connection':
463 if value.lower() == 'close':
464 self.close_connection = 1
465 elif value.lower() == 'keep-alive':
466 self.close_connection = 0
467
468 def end_headers(self):
469 """Send the blank line ending the MIME headers."""
470 if self.request_version != 'HTTP/0.9':
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000471 self._headers_buffer.append(b"\r\n")
472 self.wfile.write(b"".join(self._headers_buffer))
473 self._headers_buffer = []
Georg Brandl24420152008-05-26 16:32:26 +0000474
475 def log_request(self, code='-', size='-'):
476 """Log an accepted request.
477
478 This is called by send_response().
479
480 """
481
482 self.log_message('"%s" %s %s',
483 self.requestline, str(code), str(size))
484
485 def log_error(self, format, *args):
486 """Log an error.
487
488 This is called when a request cannot be fulfilled. By
489 default it passes the message on to log_message().
490
491 Arguments are the same as for log_message().
492
493 XXX This should go to the separate error log.
494
495 """
496
497 self.log_message(format, *args)
498
499 def log_message(self, format, *args):
500 """Log an arbitrary message.
501
502 This is used by all other logging functions. Override
503 it if you have specific logging wishes.
504
505 The first argument, FORMAT, is a format string for the
506 message to be logged. If the format string contains
507 any % escapes requiring parameters, they should be
508 specified as subsequent arguments (it's just like
509 printf!).
510
Senthil Kumarandb727b42012-04-29 13:41:03 +0800511 The client ip and current date/time are prefixed to
Georg Brandl24420152008-05-26 16:32:26 +0000512 every message.
513
514 """
515
516 sys.stderr.write("%s - - [%s] %s\n" %
Senthil Kumarandb727b42012-04-29 13:41:03 +0800517 (self.client_address[0],
Georg Brandl24420152008-05-26 16:32:26 +0000518 self.log_date_time_string(),
519 format%args))
520
521 def version_string(self):
522 """Return the server software version string."""
523 return self.server_version + ' ' + self.sys_version
524
525 def date_time_string(self, timestamp=None):
526 """Return the current date and time formatted for a message header."""
527 if timestamp is None:
528 timestamp = time.time()
529 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
530 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
531 self.weekdayname[wd],
532 day, self.monthname[month], year,
533 hh, mm, ss)
534 return s
535
536 def log_date_time_string(self):
537 """Return the current time formatted for logging."""
538 now = time.time()
539 year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
540 s = "%02d/%3s/%04d %02d:%02d:%02d" % (
541 day, self.monthname[month], year, hh, mm, ss)
542 return s
543
544 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
545
546 monthname = [None,
547 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
548 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
549
550 def address_string(self):
551 """Return the client address formatted for logging.
552
553 This version looks up the full hostname using gethostbyaddr(),
554 and tries to find a name that contains at least one dot.
555
556 """
557
558 host, port = self.client_address[:2]
559 return socket.getfqdn(host)
560
561 # Essentially static class variables
562
563 # The version of the HTTP protocol we support.
564 # Set this to HTTP/1.1 to enable automatic keepalive
565 protocol_version = "HTTP/1.0"
566
Barry Warsaw820c1202008-06-12 04:06:45 +0000567 # MessageClass used to parse headers
Barry Warsaw820c1202008-06-12 04:06:45 +0000568 MessageClass = http.client.HTTPMessage
Georg Brandl24420152008-05-26 16:32:26 +0000569
570 # Table mapping response codes to messages; entries have the
571 # form {code: (shortmessage, longmessage)}.
572 # See RFC 2616.
573 responses = {
574 100: ('Continue', 'Request received, please continue'),
575 101: ('Switching Protocols',
576 'Switching to new protocol; obey Upgrade header'),
577
578 200: ('OK', 'Request fulfilled, document follows'),
579 201: ('Created', 'Document created, URL follows'),
580 202: ('Accepted',
581 'Request accepted, processing continues off-line'),
582 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
583 204: ('No Content', 'Request fulfilled, nothing follows'),
584 205: ('Reset Content', 'Clear input form for further input.'),
585 206: ('Partial Content', 'Partial content follows.'),
586
587 300: ('Multiple Choices',
588 'Object has several resources -- see URI list'),
589 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
590 302: ('Found', 'Object moved temporarily -- see URI list'),
591 303: ('See Other', 'Object moved -- see Method and URL list'),
592 304: ('Not Modified',
593 'Document has not changed since given time'),
594 305: ('Use Proxy',
595 'You must use proxy specified in Location to access this '
596 'resource.'),
597 307: ('Temporary Redirect',
598 'Object moved temporarily -- see URI list'),
599
600 400: ('Bad Request',
601 'Bad request syntax or unsupported method'),
602 401: ('Unauthorized',
603 'No permission -- see authorization schemes'),
604 402: ('Payment Required',
605 'No payment -- see charging schemes'),
606 403: ('Forbidden',
607 'Request forbidden -- authorization will not help'),
608 404: ('Not Found', 'Nothing matches the given URI'),
609 405: ('Method Not Allowed',
Senthil Kumaran7aa26212010-02-22 11:00:50 +0000610 'Specified method is invalid for this resource.'),
Georg Brandl24420152008-05-26 16:32:26 +0000611 406: ('Not Acceptable', 'URI not available in preferred format.'),
612 407: ('Proxy Authentication Required', 'You must authenticate with '
613 'this proxy before proceeding.'),
614 408: ('Request Timeout', 'Request timed out; try again later.'),
615 409: ('Conflict', 'Request conflict.'),
616 410: ('Gone',
617 'URI no longer exists and has been permanently removed.'),
618 411: ('Length Required', 'Client must specify Content-Length.'),
619 412: ('Precondition Failed', 'Precondition in headers is false.'),
620 413: ('Request Entity Too Large', 'Entity is too large.'),
621 414: ('Request-URI Too Long', 'URI is too long.'),
622 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
623 416: ('Requested Range Not Satisfiable',
624 'Cannot satisfy request range.'),
625 417: ('Expectation Failed',
626 'Expect condition could not be satisfied.'),
627
628 500: ('Internal Server Error', 'Server got itself in trouble'),
629 501: ('Not Implemented',
630 'Server does not support this operation'),
631 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
632 503: ('Service Unavailable',
633 'The server cannot process the request due to a high load'),
634 504: ('Gateway Timeout',
635 'The gateway server did not receive a timely response'),
636 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
637 }
638
639
640class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
641
642 """Simple HTTP request handler with GET and HEAD commands.
643
644 This serves files from the current directory and any of its
645 subdirectories. The MIME type for files is determined by
646 calling the .guess_type() method.
647
648 The GET and HEAD requests are identical except that the HEAD
649 request omits the actual contents of the file.
650
651 """
652
653 server_version = "SimpleHTTP/" + __version__
654
655 def do_GET(self):
656 """Serve a GET request."""
657 f = self.send_head()
658 if f:
659 self.copyfile(f, self.wfile)
660 f.close()
661
662 def do_HEAD(self):
663 """Serve a HEAD request."""
664 f = self.send_head()
665 if f:
666 f.close()
667
668 def send_head(self):
669 """Common code for GET and HEAD commands.
670
671 This sends the response code and MIME headers.
672
673 Return value is either a file object (which has to be copied
674 to the outputfile by the caller unless the command was HEAD,
675 and must be closed by the caller under all circumstances), or
676 None, in which case the caller has nothing further to do.
677
678 """
679 path = self.translate_path(self.path)
680 f = None
681 if os.path.isdir(path):
682 if not self.path.endswith('/'):
683 # redirect browser - doing basically what apache does
684 self.send_response(301)
685 self.send_header("Location", self.path + "/")
686 self.end_headers()
687 return None
688 for index in "index.html", "index.htm":
689 index = os.path.join(path, index)
690 if os.path.exists(index):
691 path = index
692 break
693 else:
694 return self.list_directory(path)
695 ctype = self.guess_type(path)
696 try:
697 f = open(path, 'rb')
698 except IOError:
699 self.send_error(404, "File not found")
700 return None
701 self.send_response(200)
702 self.send_header("Content-type", ctype)
703 fs = os.fstat(f.fileno())
704 self.send_header("Content-Length", str(fs[6]))
705 self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
706 self.end_headers()
707 return f
708
709 def list_directory(self, path):
710 """Helper to produce a directory listing (absent index.html).
711
712 Return value is either a file object, or None (indicating an
713 error). In either case, the headers are sent, making the
714 interface the same as for send_head().
715
716 """
717 try:
718 list = os.listdir(path)
719 except os.error:
720 self.send_error(404, "No permission to list directory")
721 return None
722 list.sort(key=lambda a: a.lower())
723 r = []
Georg Brandl1f7fffb2010-10-15 15:57:45 +0000724 displaypath = html.escape(urllib.parse.unquote(self.path))
Georg Brandl24420152008-05-26 16:32:26 +0000725 r.append('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
726 r.append("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
727 r.append("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
728 r.append("<hr>\n<ul>\n")
729 for name in list:
730 fullname = os.path.join(path, name)
731 displayname = linkname = name
732 # Append / for directories or @ for symbolic links
733 if os.path.isdir(fullname):
734 displayname = name + "/"
735 linkname = name + "/"
736 if os.path.islink(fullname):
737 displayname = name + "@"
738 # Note: a link to a directory displays with @ and links with /
739 r.append('<li><a href="%s">%s</a>\n'
Georg Brandl1f7fffb2010-10-15 15:57:45 +0000740 % (urllib.parse.quote(linkname), html.escape(displayname)))
Georg Brandl24420152008-05-26 16:32:26 +0000741 r.append("</ul>\n<hr>\n</body>\n</html>\n")
742 enc = sys.getfilesystemencoding()
743 encoded = ''.join(r).encode(enc)
744 f = io.BytesIO()
745 f.write(encoded)
746 f.seek(0)
747 self.send_response(200)
748 self.send_header("Content-type", "text/html; charset=%s" % enc)
749 self.send_header("Content-Length", str(len(encoded)))
750 self.end_headers()
751 return f
752
753 def translate_path(self, path):
754 """Translate a /-separated PATH to the local filename syntax.
755
756 Components that mean special things to the local file system
757 (e.g. drive or directory names) are ignored. (XXX They should
758 probably be diagnosed.)
759
760 """
761 # abandon query parameters
762 path = path.split('?',1)[0]
763 path = path.split('#',1)[0]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000764 path = posixpath.normpath(urllib.parse.unquote(path))
Georg Brandl24420152008-05-26 16:32:26 +0000765 words = path.split('/')
766 words = filter(None, words)
767 path = os.getcwd()
768 for word in words:
769 drive, word = os.path.splitdrive(word)
770 head, word = os.path.split(word)
771 if word in (os.curdir, os.pardir): continue
772 path = os.path.join(path, word)
773 return path
774
775 def copyfile(self, source, outputfile):
776 """Copy all data between two file objects.
777
778 The SOURCE argument is a file object open for reading
779 (or anything with a read() method) and the DESTINATION
780 argument is a file object open for writing (or
781 anything with a write() method).
782
783 The only reason for overriding this would be to change
784 the block size or perhaps to replace newlines by CRLF
785 -- note however that this the default server uses this
786 to copy binary data as well.
787
788 """
789 shutil.copyfileobj(source, outputfile)
790
791 def guess_type(self, path):
792 """Guess the type of a file.
793
794 Argument is a PATH (a filename).
795
796 Return value is a string of the form type/subtype,
797 usable for a MIME Content-type header.
798
799 The default implementation looks the file's extension
800 up in the table self.extensions_map, using application/octet-stream
801 as a default; however it would be permissible (if
802 slow) to look inside the data to make a better guess.
803
804 """
805
806 base, ext = posixpath.splitext(path)
807 if ext in self.extensions_map:
808 return self.extensions_map[ext]
809 ext = ext.lower()
810 if ext in self.extensions_map:
811 return self.extensions_map[ext]
812 else:
813 return self.extensions_map['']
814
815 if not mimetypes.inited:
816 mimetypes.init() # try to read system mime.types
817 extensions_map = mimetypes.types_map.copy()
818 extensions_map.update({
819 '': 'application/octet-stream', # Default
820 '.py': 'text/plain',
821 '.c': 'text/plain',
822 '.h': 'text/plain',
823 })
824
825
826# Utilities for CGIHTTPRequestHandler
827
Senthil Kumarand70846b2012-04-12 02:34:32 +0800828def _url_collapse_path(path):
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000829 """
830 Given a URL path, remove extra '/'s and '.' path elements and collapse
Senthil Kumarand70846b2012-04-12 02:34:32 +0800831 any '..' references and returns a colllapsed path.
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000832
833 Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
Senthil Kumarand70846b2012-04-12 02:34:32 +0800834 The utility of this function is limited to is_cgi method and helps
835 preventing some security attacks.
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000836
837 Returns: A tuple of (head, tail) where tail is everything after the final /
838 and head is everything before it. Head will always start with a '/' and,
839 if it contains anything else, never have a trailing '/'.
840
841 Raises: IndexError if too many '..' occur within the path.
Senthil Kumarand70846b2012-04-12 02:34:32 +0800842
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000843 """
844 # Similar to os.path.split(os.path.normpath(path)) but specific to URL
845 # path semantics rather than local operating system semantics.
Senthil Kumarand70846b2012-04-12 02:34:32 +0800846 path_parts = path.split('/')
847 head_parts = []
848 for part in path_parts[:-1]:
849 if part == '..':
850 head_parts.pop() # IndexError if more '..' than prior parts
851 elif part and part != '.':
852 head_parts.append( part )
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000853 if path_parts:
Senthil Kumarandbb369d2012-04-11 03:15:28 +0800854 tail_part = path_parts.pop()
Senthil Kumarand70846b2012-04-12 02:34:32 +0800855 if tail_part:
856 if tail_part == '..':
857 head_parts.pop()
858 tail_part = ''
859 elif tail_part == '.':
860 tail_part = ''
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000861 else:
862 tail_part = ''
Senthil Kumarand70846b2012-04-12 02:34:32 +0800863
864 splitpath = ('/' + '/'.join(head_parts), tail_part)
865 collapsed_path = "/".join(splitpath)
866
867 return collapsed_path
868
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000869
870
Georg Brandl24420152008-05-26 16:32:26 +0000871nobody = None
872
873def nobody_uid():
874 """Internal routine to get nobody's uid"""
875 global nobody
876 if nobody:
877 return nobody
878 try:
879 import pwd
880 except ImportError:
881 return -1
882 try:
883 nobody = pwd.getpwnam('nobody')[2]
884 except KeyError:
Georg Brandlcbd2ab12010-12-04 10:39:14 +0000885 nobody = 1 + max(x[2] for x in pwd.getpwall())
Georg Brandl24420152008-05-26 16:32:26 +0000886 return nobody
887
888
889def executable(path):
890 """Test for executable file."""
891 try:
892 st = os.stat(path)
893 except os.error:
894 return False
895 return st.st_mode & 0o111 != 0
896
897
898class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
899
900 """Complete HTTP server with GET, HEAD and POST commands.
901
902 GET and HEAD also support running CGI scripts.
903
904 The POST command is *only* implemented for CGI scripts.
905
906 """
907
908 # Determine platform specifics
909 have_fork = hasattr(os, 'fork')
Georg Brandl24420152008-05-26 16:32:26 +0000910
911 # Make rfile unbuffered -- we need to read one line and then pass
912 # the rest to a subprocess, so we can't use buffered input.
913 rbufsize = 0
914
915 def do_POST(self):
916 """Serve a POST request.
917
918 This is only implemented for CGI scripts.
919
920 """
921
922 if self.is_cgi():
923 self.run_cgi()
924 else:
925 self.send_error(501, "Can only POST to CGI scripts")
926
927 def send_head(self):
928 """Version of send_head that support CGI scripts"""
929 if self.is_cgi():
930 return self.run_cgi()
931 else:
932 return SimpleHTTPRequestHandler.send_head(self)
933
934 def is_cgi(self):
935 """Test whether self.path corresponds to a CGI script.
936
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000937 Returns True and updates the cgi_info attribute to the tuple
938 (dir, rest) if self.path requires running a CGI script.
939 Returns False otherwise.
Georg Brandl24420152008-05-26 16:32:26 +0000940
Benjamin Petersona7deeee2009-05-08 20:54:42 +0000941 If any exception is raised, the caller should assume that
942 self.path was rejected as invalid and act accordingly.
943
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000944 The default implementation tests whether the normalized url
945 path begins with one of the strings in self.cgi_directories
946 (and the next character is a '/' or the end of the string).
Georg Brandl24420152008-05-26 16:32:26 +0000947
948 """
Senthil Kumarand70846b2012-04-12 02:34:32 +0800949 collapsed_path = _url_collapse_path(self.path)
950 dir_sep = collapsed_path.find('/', 1)
951 head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
Senthil Kumarandbb369d2012-04-11 03:15:28 +0800952 if head in self.cgi_directories:
953 self.cgi_info = head, tail
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000954 return True
Georg Brandl24420152008-05-26 16:32:26 +0000955 return False
956
Senthil Kumarand70846b2012-04-12 02:34:32 +0800957
Georg Brandl24420152008-05-26 16:32:26 +0000958 cgi_directories = ['/cgi-bin', '/htbin']
959
960 def is_executable(self, path):
961 """Test whether argument path is an executable file."""
962 return executable(path)
963
964 def is_python(self, path):
965 """Test whether argument path is a Python script."""
966 head, tail = os.path.splitext(path)
967 return tail.lower() in (".py", ".pyw")
968
969 def run_cgi(self):
970 """Execute a CGI script."""
971 path = self.path
972 dir, rest = self.cgi_info
973
974 i = path.find('/', len(dir) + 1)
975 while i >= 0:
976 nextdir = path[:i]
977 nextrest = path[i+1:]
978
979 scriptdir = self.translate_path(nextdir)
980 if os.path.isdir(scriptdir):
981 dir, rest = nextdir, nextrest
982 i = path.find('/', len(dir) + 1)
983 else:
984 break
985
986 # find an explicit query string, if present.
987 i = rest.rfind('?')
988 if i >= 0:
989 rest, query = rest[:i], rest[i+1:]
990 else:
991 query = ''
992
993 # dissect the part after the directory name into a script name &
994 # a possible additional path, to be stored in PATH_INFO.
995 i = rest.find('/')
996 if i >= 0:
997 script, rest = rest[:i], rest[i:]
998 else:
999 script, rest = rest, ''
1000
1001 scriptname = dir + '/' + script
1002 scriptfile = self.translate_path(scriptname)
1003 if not os.path.exists(scriptfile):
1004 self.send_error(404, "No such CGI script (%r)" % scriptname)
1005 return
1006 if not os.path.isfile(scriptfile):
1007 self.send_error(403, "CGI script is not a plain file (%r)" %
1008 scriptname)
1009 return
1010 ispy = self.is_python(scriptname)
1011 if not ispy:
Georg Brandl24420152008-05-26 16:32:26 +00001012 if not self.is_executable(scriptfile):
1013 self.send_error(403, "CGI script is not executable (%r)" %
1014 scriptname)
1015 return
1016
1017 # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
1018 # XXX Much of the following could be prepared ahead of time!
Senthil Kumaran42713722010-10-03 17:55:45 +00001019 env = copy.deepcopy(os.environ)
Georg Brandl24420152008-05-26 16:32:26 +00001020 env['SERVER_SOFTWARE'] = self.version_string()
1021 env['SERVER_NAME'] = self.server.server_name
1022 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
1023 env['SERVER_PROTOCOL'] = self.protocol_version
1024 env['SERVER_PORT'] = str(self.server.server_port)
1025 env['REQUEST_METHOD'] = self.command
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001026 uqrest = urllib.parse.unquote(rest)
Georg Brandl24420152008-05-26 16:32:26 +00001027 env['PATH_INFO'] = uqrest
1028 env['PATH_TRANSLATED'] = self.translate_path(uqrest)
1029 env['SCRIPT_NAME'] = scriptname
1030 if query:
1031 env['QUERY_STRING'] = query
1032 host = self.address_string()
1033 if host != self.client_address[0]:
1034 env['REMOTE_HOST'] = host
1035 env['REMOTE_ADDR'] = self.client_address[0]
Barry Warsaw820c1202008-06-12 04:06:45 +00001036 authorization = self.headers.get("authorization")
Georg Brandl24420152008-05-26 16:32:26 +00001037 if authorization:
1038 authorization = authorization.split()
1039 if len(authorization) == 2:
1040 import base64, binascii
1041 env['AUTH_TYPE'] = authorization[0]
1042 if authorization[0].lower() == "basic":
1043 try:
1044 authorization = authorization[1].encode('ascii')
Georg Brandl706824f2009-06-04 09:42:55 +00001045 authorization = base64.decodebytes(authorization).\
Georg Brandl24420152008-05-26 16:32:26 +00001046 decode('ascii')
1047 except (binascii.Error, UnicodeError):
1048 pass
1049 else:
1050 authorization = authorization.split(':')
1051 if len(authorization) == 2:
1052 env['REMOTE_USER'] = authorization[0]
1053 # XXX REMOTE_IDENT
Barry Warsaw820c1202008-06-12 04:06:45 +00001054 if self.headers.get('content-type') is None:
1055 env['CONTENT_TYPE'] = self.headers.get_content_type()
Georg Brandl24420152008-05-26 16:32:26 +00001056 else:
Barry Warsaw820c1202008-06-12 04:06:45 +00001057 env['CONTENT_TYPE'] = self.headers['content-type']
1058 length = self.headers.get('content-length')
Georg Brandl24420152008-05-26 16:32:26 +00001059 if length:
1060 env['CONTENT_LENGTH'] = length
Barry Warsaw820c1202008-06-12 04:06:45 +00001061 referer = self.headers.get('referer')
Georg Brandl24420152008-05-26 16:32:26 +00001062 if referer:
1063 env['HTTP_REFERER'] = referer
1064 accept = []
1065 for line in self.headers.getallmatchingheaders('accept'):
1066 if line[:1] in "\t\n\r ":
1067 accept.append(line.strip())
1068 else:
1069 accept = accept + line[7:].split(',')
1070 env['HTTP_ACCEPT'] = ','.join(accept)
Barry Warsaw820c1202008-06-12 04:06:45 +00001071 ua = self.headers.get('user-agent')
Georg Brandl24420152008-05-26 16:32:26 +00001072 if ua:
1073 env['HTTP_USER_AGENT'] = ua
Barry Warsaw820c1202008-06-12 04:06:45 +00001074 co = filter(None, self.headers.get_all('cookie', []))
Georg Brandl62e2ca22010-07-31 21:54:24 +00001075 cookie_str = ', '.join(co)
1076 if cookie_str:
1077 env['HTTP_COOKIE'] = cookie_str
Georg Brandl24420152008-05-26 16:32:26 +00001078 # XXX Other HTTP_* headers
1079 # Since we're setting the env in the parent, provide empty
1080 # values to override previously set values
1081 for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
1082 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
1083 env.setdefault(k, "")
Georg Brandl24420152008-05-26 16:32:26 +00001084
1085 self.send_response(200, "Script output follows")
1086
1087 decoded_query = query.replace('+', ' ')
1088
1089 if self.have_fork:
1090 # Unix -- fork as we should
1091 args = [script]
1092 if '=' not in decoded_query:
1093 args.append(decoded_query)
1094 nobody = nobody_uid()
1095 self.wfile.flush() # Always flush before forking
1096 pid = os.fork()
1097 if pid != 0:
1098 # Parent
1099 pid, sts = os.waitpid(pid, 0)
1100 # throw away additional data [see bug #427345]
1101 while select.select([self.rfile], [], [], 0)[0]:
1102 if not self.rfile.read(1):
1103 break
1104 if sts:
1105 self.log_error("CGI script exit status %#x", sts)
1106 return
1107 # Child
1108 try:
1109 try:
1110 os.setuid(nobody)
1111 except os.error:
1112 pass
1113 os.dup2(self.rfile.fileno(), 0)
1114 os.dup2(self.wfile.fileno(), 1)
Senthil Kumaran42713722010-10-03 17:55:45 +00001115 os.execve(scriptfile, args, env)
Georg Brandl24420152008-05-26 16:32:26 +00001116 except:
1117 self.server.handle_error(self.request, self.client_address)
1118 os._exit(127)
1119
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001120 else:
1121 # Non-Unix -- use subprocess
1122 import subprocess
Senthil Kumarane29cd162009-11-11 04:17:53 +00001123 cmdline = [scriptfile]
Georg Brandl24420152008-05-26 16:32:26 +00001124 if self.is_python(scriptfile):
1125 interp = sys.executable
1126 if interp.lower().endswith("w.exe"):
1127 # On Windows, use python.exe, not pythonw.exe
1128 interp = interp[:-5] + interp[-4:]
Senthil Kumarane29cd162009-11-11 04:17:53 +00001129 cmdline = [interp, '-u'] + cmdline
1130 if '=' not in query:
1131 cmdline.append(query)
1132 self.log_message("command: %s", subprocess.list2cmdline(cmdline))
Georg Brandl24420152008-05-26 16:32:26 +00001133 try:
1134 nbytes = int(length)
1135 except (TypeError, ValueError):
1136 nbytes = 0
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001137 p = subprocess.Popen(cmdline,
1138 stdin=subprocess.PIPE,
1139 stdout=subprocess.PIPE,
Senthil Kumaran42713722010-10-03 17:55:45 +00001140 stderr=subprocess.PIPE,
1141 env = env
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001142 )
Georg Brandl24420152008-05-26 16:32:26 +00001143 if self.command.lower() == "post" and nbytes > 0:
1144 data = self.rfile.read(nbytes)
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001145 else:
1146 data = None
Georg Brandl24420152008-05-26 16:32:26 +00001147 # throw away additional data [see bug #427345]
1148 while select.select([self.rfile._sock], [], [], 0)[0]:
1149 if not self.rfile._sock.recv(1):
1150 break
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001151 stdout, stderr = p.communicate(data)
1152 self.wfile.write(stdout)
1153 if stderr:
1154 self.log_error('%s', stderr)
Brian Curtincbad4df2010-11-05 15:04:48 +00001155 p.stderr.close()
1156 p.stdout.close()
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001157 status = p.returncode
1158 if status:
1159 self.log_error("CGI script exit status %#x", status)
Georg Brandl24420152008-05-26 16:32:26 +00001160 else:
1161 self.log_message("CGI script exited OK")
1162
1163
1164def test(HandlerClass = BaseHTTPRequestHandler,
1165 ServerClass = HTTPServer, protocol="HTTP/1.0"):
1166 """Test the HTTP request handler class.
1167
1168 This runs an HTTP server on port 8000 (or the first command line
1169 argument).
1170
1171 """
1172
1173 if sys.argv[1:]:
1174 port = int(sys.argv[1])
1175 else:
1176 port = 8000
1177 server_address = ('', port)
1178
1179 HandlerClass.protocol_version = protocol
1180 httpd = ServerClass(server_address, HandlerClass)
1181
1182 sa = httpd.socket.getsockname()
1183 print("Serving HTTP on", sa[0], "port", sa[1], "...")
Alexandre Vassalottib5292a22009-04-03 07:16:55 +00001184 try:
1185 httpd.serve_forever()
1186 except KeyboardInterrupt:
1187 print("\nKeyboard interrupt received, exiting.")
1188 httpd.server_close()
1189 sys.exit(0)
Georg Brandl24420152008-05-26 16:32:26 +00001190
1191if __name__ == '__main__':
Georg Brandl24420152008-05-26 16:32:26 +00001192 test(HandlerClass=SimpleHTTPRequestHandler)