blob: 3df3323a97eae69d0284df9280d01a2dd45a2add [file] [log] [blame]
Guido van Rossume7e578f1995-08-04 04:00:20 +00001"""HTTP server base class.
2
3Note: the class in this module doesn't implement any HTTP request; see
4SimpleHTTPServer for simple implementations of GET, HEAD and POST
Martin v. Löwis587c98c2002-03-17 18:37:22 +00005(including CGI scripts). It does, however, optionally implement HTTP/1.1
6persistent connections, as of version 0.3.
Guido van Rossume7e578f1995-08-04 04:00:20 +00007
8Contents:
9
10- BaseHTTPRequestHandler: HTTP request handler base class
11- test: test function
12
13XXX To do:
14
Guido van Rossume7e578f1995-08-04 04:00:20 +000015- log requests even later (to capture byte count)
16- log user-agent header and other interesting goodies
17- send error log to separate file
Guido van Rossume7e578f1995-08-04 04:00:20 +000018"""
19
20
21# See also:
22#
23# HTTP Working Group T. Berners-Lee
24# INTERNET-DRAFT R. T. Fielding
25# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
26# Expires September 8, 1995 March 8, 1995
27#
28# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
Martin v. Löwis587c98c2002-03-17 18:37:22 +000029#
30# and
31#
32# Network Working Group R. Fielding
33# Request for Comments: 2616 et al
34# Obsoletes: 2068 June 1999
Tim Peters863ac442002-04-16 01:38:40 +000035# Category: Standards Track
Martin v. Löwis587c98c2002-03-17 18:37:22 +000036#
37# URL: http://www.faqs.org/rfcs/rfc2616.html
Guido van Rossume7e578f1995-08-04 04:00:20 +000038
39# Log files
40# ---------
Tim Peters11cf6052001-01-14 21:54:20 +000041#
Guido van Rossume7e578f1995-08-04 04:00:20 +000042# Here's a quote from the NCSA httpd docs about log file format.
Tim Peters11cf6052001-01-14 21:54:20 +000043#
44# | The logfile format is as follows. Each line consists of:
45# |
46# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
47# |
48# | host: Either the DNS name or the IP number of the remote client
Guido van Rossume7e578f1995-08-04 04:00:20 +000049# | rfc931: Any information returned by identd for this person,
Tim Peters11cf6052001-01-14 21:54:20 +000050# | - otherwise.
Guido van Rossume7e578f1995-08-04 04:00:20 +000051# | authuser: If user sent a userid for authentication, the user name,
Tim Peters11cf6052001-01-14 21:54:20 +000052# | - otherwise.
53# | DD: Day
54# | Mon: Month (calendar name)
55# | YYYY: Year
56# | hh: hour (24-hour format, the machine's timezone)
57# | mm: minutes
58# | ss: seconds
59# | request: The first line of the HTTP request as sent by the client.
60# | ddd: the status code returned by the server, - if not available.
Guido van Rossume7e578f1995-08-04 04:00:20 +000061# | bbbb: the total number of bytes sent,
Tim Peters11cf6052001-01-14 21:54:20 +000062# | *not including the HTTP/1.0 header*, - if not available
63# |
Guido van Rossume7e578f1995-08-04 04:00:20 +000064# | You can determine the name of the file accessed through request.
Tim Peters11cf6052001-01-14 21:54:20 +000065#
Guido van Rossume7e578f1995-08-04 04:00:20 +000066# (Actually, the latter is only true if you know the server configuration
67# at the time the request was made!)
68
Martin v. Löwis587c98c2002-03-17 18:37:22 +000069__version__ = "0.3"
Guido van Rossume7e578f1995-08-04 04:00:20 +000070
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000071__all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
Guido van Rossume7e578f1995-08-04 04:00:20 +000072
73import sys
74import time
75import socket # For gethostbyaddr()
Brett Cannon1eaf0742008-09-02 01:25:16 +000076from warnings import filterwarnings, catch_warnings
77with catch_warnings():
78 if sys.py3kwarning:
79 filterwarnings("ignore", ".*mimetools has been removed",
80 DeprecationWarning)
Brett Cannonabe423e2008-08-16 21:47:07 +000081 import mimetools
Georg Brandle152a772008-05-24 18:31:28 +000082import SocketServer
Guido van Rossume7e578f1995-08-04 04:00:20 +000083
Georg Brandl16479232008-02-23 15:02:28 +000084# Default error message template
Guido van Rossume7e578f1995-08-04 04:00:20 +000085DEFAULT_ERROR_MESSAGE = """\
86<head>
87<title>Error response</title>
88</head>
89<body>
90<h1>Error response</h1>
91<p>Error code %(code)d.
92<p>Message: %(message)s.
93<p>Error code explanation: %(code)s = %(explain)s.
94</body>
95"""
96
Georg Brandl16479232008-02-23 15:02:28 +000097DEFAULT_ERROR_CONTENT_TYPE = "text/html"
98
Georg Brandla2aa1ac2005-06-26 21:33:14 +000099def _quote_html(html):
100 return html.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
Guido van Rossume7e578f1995-08-04 04:00:20 +0000101
Georg Brandle152a772008-05-24 18:31:28 +0000102class HTTPServer(SocketServer.TCPServer):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000103
Guido van Rossum18865de2000-05-09 14:54:13 +0000104 allow_reuse_address = 1 # Seems to make sense in testing environment
105
Guido van Rossume7e578f1995-08-04 04:00:20 +0000106 def server_bind(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 """Override server_bind to store the server name."""
Georg Brandle152a772008-05-24 18:31:28 +0000108 SocketServer.TCPServer.server_bind(self)
Martin v. Löwis3c120de2003-05-31 07:55:43 +0000109 host, port = self.socket.getsockname()[:2]
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000110 self.server_name = socket.getfqdn(host)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 self.server_port = port
Guido van Rossume7e578f1995-08-04 04:00:20 +0000112
113
Georg Brandle152a772008-05-24 18:31:28 +0000114class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000115
116 """HTTP request handler base class.
117
118 The following explanation of HTTP serves to guide you through the
119 code as well as to expose any misunderstandings I may have about
120 HTTP (so you don't need to read the code to figure out I'm wrong
121 :-).
122
123 HTTP (HyperText Transfer Protocol) is an extensible protocol on
124 top of a reliable stream transport (e.g. TCP/IP). The protocol
125 recognizes three parts to a request:
126
127 1. One line identifying the request type and path
128 2. An optional set of RFC-822-style headers
129 3. An optional data part
130
131 The headers and data are separated by a blank line.
132
133 The first line of the request has the form
134
135 <command> <path> <version>
136
137 where <command> is a (case-sensitive) keyword such as GET or POST,
138 <path> is a string containing path information for the request,
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000139 and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
140 <path> is encoded using the URL encoding scheme (using %xx to signify
141 the ASCII character with hex code xx).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000142
Andrew M. Kuchling8ca202e2003-02-03 15:21:15 +0000143 The specification specifies that lines are separated by CRLF but
144 for compatibility with the widest range of clients recommends
145 servers also handle LF. Similarly, whitespace in the request line
146 is treated sensibly (allowing multiple spaces between components
147 and allowing trailing whitespace).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000148
149 Similarly, for output, lines ought to be separated by CRLF pairs
150 but most clients grok LF characters just fine.
151
152 If the first line of the request has the form
153
154 <command> <path>
155
156 (i.e. <version> is left out) then this is assumed to be an HTTP
157 0.9 request; this form has no optional headers and data part and
158 the reply consists of just the data.
159
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000160 The reply form of the HTTP 1.x protocol again has three parts:
Guido van Rossume7e578f1995-08-04 04:00:20 +0000161
162 1. One line giving the response code
163 2. An optional set of RFC-822-style headers
164 3. The data
165
166 Again, the headers and data are separated by a blank line.
167
168 The response code line has the form
169
170 <version> <responsecode> <responsestring>
171
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000172 where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
Guido van Rossume7e578f1995-08-04 04:00:20 +0000173 <responsecode> is a 3-digit response code indicating success or
174 failure of the request, and <responsestring> is an optional
175 human-readable string explaining what the response code means.
176
177 This server parses the request and the headers, and then calls a
178 function specific to the request type (<command>). Specifically,
Guido van Rossumba895d81999-09-15 15:28:25 +0000179 a request SPAM will be handled by a method do_SPAM(). If no
Guido van Rossume7e578f1995-08-04 04:00:20 +0000180 such method exists the server sends an error response to the
181 client. If it exists, it is called with no arguments:
182
183 do_SPAM()
184
185 Note that the request name is case sensitive (i.e. SPAM and spam
186 are different requests).
187
188 The various request details are stored in instance variables:
189
190 - client_address is the client IP address in the form (host,
191 port);
192
193 - command, path and version are the broken-down request line;
194
195 - headers is an instance of mimetools.Message (or a derived
196 class) containing the header information;
197
198 - rfile is a file object open for reading positioned at the
199 start of the optional input data part;
200
201 - wfile is a file object open for writing.
202
203 IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
204
205 The first thing to be written must be the response line. Then
206 follow 0 or more header lines, then a blank line, and then the
207 actual data (if any). The meaning of the header lines depends on
208 the command executed by the server; in most cases, when data is
209 returned, there should be at least one header line of the form
210
211 Content-type: <type>/<subtype>
212
213 where <type> and <subtype> should be registered MIME types,
214 e.g. "text/html" or "text/plain".
215
216 """
217
218 # The Python system version, truncated to its first component.
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000219 sys_version = "Python/" + sys.version.split()[0]
Guido van Rossume7e578f1995-08-04 04:00:20 +0000220
221 # The server software version. You may want to override this.
222 # The format is multiple whitespace-separated strings,
223 # where each string is of the form name[/version].
224 server_version = "BaseHTTP/" + __version__
225
Georg Brandlf899dfa2008-05-18 09:12:20 +0000226 # The default request version. This only affects responses up until
227 # the point where the request line is parsed, so it mainly decides what
228 # the client gets back when sending a malformed request line.
229 # Most web servers default to HTTP 0.9, i.e. don't send a status line.
230 default_request_version = "HTTP/0.9"
231
Guido van Rossumd65b5391999-10-26 13:01:36 +0000232 def parse_request(self):
233 """Parse a request (internal).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000234
Raymond Hettingerbf68c782003-06-02 14:25:43 +0000235 The request should be stored in self.raw_requestline; the results
Guido van Rossumd65b5391999-10-26 13:01:36 +0000236 are in self.command, self.path, self.request_version and
237 self.headers.
238
Tim Petersbc0e9102002-04-04 22:55:58 +0000239 Return True for success, False for failure; on failure, an
Guido van Rossumd65b5391999-10-26 13:01:36 +0000240 error is sent back.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000241
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 """
Andrew M. Kuchling2de97d32003-02-03 19:11:18 +0000243 self.command = None # set in case of error on the first line
Georg Brandlf899dfa2008-05-18 09:12:20 +0000244 self.request_version = version = self.default_request_version
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000245 self.close_connection = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 requestline = self.raw_requestline
Senthil Kumaran139c4572011-12-23 17:07:13 +0800247 requestline = requestline.rstrip('\r\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 self.requestline = requestline
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000249 words = requestline.split()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000250 if len(words) == 3:
Senthil Kumaran139c4572011-12-23 17:07:13 +0800251 command, path, version = words
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 if version[:5] != 'HTTP/':
Walter Dörwald70a6b492004-02-12 17:35:32 +0000253 self.send_error(400, "Bad request version (%r)" % version)
Tim Petersbc0e9102002-04-04 22:55:58 +0000254 return False
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000255 try:
Andrew M. Kuchling2de97d32003-02-03 19:11:18 +0000256 base_version_number = version.split('/', 1)[1]
257 version_number = base_version_number.split(".")
258 # RFC 2145 section 3.1 says there can be only one "." and
259 # - major and minor numbers MUST be treated as
260 # separate integers;
261 # - HTTP/2.4 is a lower version than HTTP/2.13, which in
262 # turn is lower than HTTP/12.3;
263 # - Leading zeros MUST be ignored by recipients.
264 if len(version_number) != 2:
265 raise ValueError
266 version_number = int(version_number[0]), int(version_number[1])
267 except (ValueError, IndexError):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000268 self.send_error(400, "Bad request version (%r)" % version)
Tim Petersbc0e9102002-04-04 22:55:58 +0000269 return False
Andrew M. Kuchling2de97d32003-02-03 19:11:18 +0000270 if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000271 self.close_connection = 0
Andrew M. Kuchling2de97d32003-02-03 19:11:18 +0000272 if version_number >= (2, 0):
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000273 self.send_error(505,
Andrew M. Kuchling2de97d32003-02-03 19:11:18 +0000274 "Invalid HTTP Version (%s)" % base_version_number)
Tim Petersbc0e9102002-04-04 22:55:58 +0000275 return False
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000276 elif len(words) == 2:
Senthil Kumaran139c4572011-12-23 17:07:13 +0800277 command, path = words
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000278 self.close_connection = 1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 if command != 'GET':
280 self.send_error(400,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000281 "Bad HTTP/0.9 request type (%r)" % command)
Tim Petersbc0e9102002-04-04 22:55:58 +0000282 return False
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000283 elif not words:
Tim Petersbc0e9102002-04-04 22:55:58 +0000284 return False
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000286 self.send_error(400, "Bad request syntax (%r)" % requestline)
Tim Petersbc0e9102002-04-04 22:55:58 +0000287 return False
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 self.command, self.path, self.request_version = command, path, version
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000289
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000290 # Examine the headers and look for a Connection directive
Raymond Hettingercffb9de2003-08-09 05:01:41 +0000291 self.headers = self.MessageClass(self.rfile, 0)
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000292
293 conntype = self.headers.get('Connection', "")
294 if conntype.lower() == 'close':
295 self.close_connection = 1
296 elif (conntype.lower() == 'keep-alive' and
297 self.protocol_version >= "HTTP/1.1"):
298 self.close_connection = 0
Tim Petersbc0e9102002-04-04 22:55:58 +0000299 return True
Guido van Rossumd65b5391999-10-26 13:01:36 +0000300
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000301 def handle_one_request(self):
Guido van Rossumd65b5391999-10-26 13:01:36 +0000302 """Handle a single HTTP request.
303
304 You normally don't need to override this method; see the class
305 __doc__ string for information on how to handle specific HTTP
306 commands such as GET and POST.
307
308 """
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000309 try:
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000310 self.raw_requestline = self.rfile.readline(65537)
311 if len(self.raw_requestline) > 65536:
312 self.requestline = ''
313 self.request_version = ''
314 self.command = ''
315 self.send_error(414)
316 return
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000317 if not self.raw_requestline:
318 self.close_connection = 1
319 return
320 if not self.parse_request():
321 # An error code has been sent, just exit
322 return
323 mname = 'do_' + self.command
324 if not hasattr(self, mname):
325 self.send_error(501, "Unsupported method (%r)" % self.command)
326 return
327 method = getattr(self, mname)
328 method()
329 self.wfile.flush() #actually send the response if not already done.
330 except socket.timeout, e:
331 #a read or a write timed out. Discard this connection
332 self.log_error("Request timed out: %r", e)
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000333 self.close_connection = 1
334 return
Guido van Rossume7e578f1995-08-04 04:00:20 +0000335
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000336 def handle(self):
337 """Handle multiple requests if necessary."""
338 self.close_connection = 1
339
340 self.handle_one_request()
341 while not self.close_connection:
342 self.handle_one_request()
343
Guido van Rossume7e578f1995-08-04 04:00:20 +0000344 def send_error(self, code, message=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000345 """Send and log an error reply.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000346
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 Arguments are the error code, and a detailed message.
348 The detailed message defaults to the short entry matching the
349 response code.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000350
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000351 This sends an error response (so it must be called before any
352 output has been generated), logs the error, and finally sends
353 a piece of HTML explaining the error to the user.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000354
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000355 """
Guido van Rossume7e578f1995-08-04 04:00:20 +0000356
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000357 try:
358 short, long = self.responses[code]
359 except KeyError:
360 short, long = '???', '???'
Raymond Hettingerc0418602002-05-31 23:03:33 +0000361 if message is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000362 message = short
363 explain = long
364 self.log_error("code %d, message %s", code, message)
Senthil Kumaran6234cc02013-03-05 02:24:03 -0800365 self.send_response(code, message)
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000366 self.send_header('Connection', 'close')
Martin Panter6af1c492016-06-08 07:16:14 +0000367
368 # Message body is omitted for cases described in:
369 # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
370 # - RFC7231: 6.3.6. 205(Reset Content)
371 content = None
372 if code >= 200 and code not in (204, 205, 304):
373 # HTML encode to prevent Cross Site Scripting attacks
374 # (see bug #1100201)
375 content = (self.error_message_format % {
376 'code': code,
377 'message': _quote_html(message),
378 'explain': explain
379 })
380 self.send_header("Content-Type", self.error_content_type)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 self.end_headers()
Martin Panter6af1c492016-06-08 07:16:14 +0000382
383 if self.command != 'HEAD' and content:
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000384 self.wfile.write(content)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000385
386 error_message_format = DEFAULT_ERROR_MESSAGE
Georg Brandl16479232008-02-23 15:02:28 +0000387 error_content_type = DEFAULT_ERROR_CONTENT_TYPE
Guido van Rossume7e578f1995-08-04 04:00:20 +0000388
389 def send_response(self, code, message=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000390 """Send the response header and log the response code.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000391
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000392 Also send two standard headers with the server software
393 version and the current date.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000394
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000395 """
396 self.log_request(code)
397 if message is None:
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000398 if code in self.responses:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000399 message = self.responses[code][0]
400 else:
401 message = ''
402 if self.request_version != 'HTTP/0.9':
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000403 self.wfile.write("%s %d %s\r\n" %
404 (self.protocol_version, code, message))
405 # print (self.protocol_version, code, message)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 self.send_header('Server', self.version_string())
407 self.send_header('Date', self.date_time_string())
Guido van Rossume7e578f1995-08-04 04:00:20 +0000408
409 def send_header(self, keyword, value):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 """Send a MIME header."""
411 if self.request_version != 'HTTP/0.9':
412 self.wfile.write("%s: %s\r\n" % (keyword, value))
Guido van Rossume7e578f1995-08-04 04:00:20 +0000413
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000414 if keyword.lower() == 'connection':
415 if value.lower() == 'close':
416 self.close_connection = 1
417 elif value.lower() == 'keep-alive':
418 self.close_connection = 0
419
Guido van Rossume7e578f1995-08-04 04:00:20 +0000420 def end_headers(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000421 """Send the blank line ending the MIME headers."""
422 if self.request_version != 'HTTP/0.9':
423 self.wfile.write("\r\n")
Guido van Rossume7e578f1995-08-04 04:00:20 +0000424
425 def log_request(self, code='-', size='-'):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 """Log an accepted request.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000427
Andrew M. Kuchlingec73cd42006-03-07 16:16:07 +0000428 This is called by send_response().
Guido van Rossume7e578f1995-08-04 04:00:20 +0000429
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 """
Guido van Rossume7e578f1995-08-04 04:00:20 +0000431
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000432 self.log_message('"%s" %s %s',
433 self.requestline, str(code), str(size))
Guido van Rossume7e578f1995-08-04 04:00:20 +0000434
Guido van Rossum833e9612007-01-10 23:12:56 +0000435 def log_error(self, format, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 """Log an error.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000437
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000438 This is called when a request cannot be fulfilled. By
439 default it passes the message on to log_message().
Guido van Rossume7e578f1995-08-04 04:00:20 +0000440
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000441 Arguments are the same as for log_message().
Guido van Rossume7e578f1995-08-04 04:00:20 +0000442
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000443 XXX This should go to the separate error log.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000444
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 """
Guido van Rossume7e578f1995-08-04 04:00:20 +0000446
Guido van Rossum833e9612007-01-10 23:12:56 +0000447 self.log_message(format, *args)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000448
449 def log_message(self, format, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 """Log an arbitrary message.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000451
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000452 This is used by all other logging functions. Override
453 it if you have specific logging wishes.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000454
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000455 The first argument, FORMAT, is a format string for the
456 message to be logged. If the format string contains
457 any % escapes requiring parameters, they should be
458 specified as subsequent arguments (it's just like
459 printf!).
Guido van Rossume7e578f1995-08-04 04:00:20 +0000460
Senthil Kumaranfb5aebc2012-04-29 13:39:16 +0800461 The client ip address and current date/time are prefixed to every
462 message.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000463
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000464 """
Guido van Rossume7e578f1995-08-04 04:00:20 +0000465
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000466 sys.stderr.write("%s - - [%s] %s\n" %
Senthil Kumaranfb5aebc2012-04-29 13:39:16 +0800467 (self.client_address[0],
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000468 self.log_date_time_string(),
469 format%args))
Guido van Rossume7e578f1995-08-04 04:00:20 +0000470
471 def version_string(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 """Return the server software version string."""
473 return self.server_version + ' ' + self.sys_version
Guido van Rossume7e578f1995-08-04 04:00:20 +0000474
Georg Brandl5d076962006-02-17 13:34:16 +0000475 def date_time_string(self, timestamp=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000476 """Return the current date and time formatted for a message header."""
Georg Brandl5d076962006-02-17 13:34:16 +0000477 if timestamp is None:
478 timestamp = time.time()
479 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000480 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
481 self.weekdayname[wd],
482 day, self.monthname[month], year,
483 hh, mm, ss)
484 return s
Guido van Rossume7e578f1995-08-04 04:00:20 +0000485
486 def log_date_time_string(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000487 """Return the current time formatted for logging."""
488 now = time.time()
489 year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
490 s = "%02d/%3s/%04d %02d:%02d:%02d" % (
491 day, self.monthname[month], year, hh, mm, ss)
492 return s
Guido van Rossume7e578f1995-08-04 04:00:20 +0000493
494 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
495
496 monthname = [None,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000497 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
498 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Guido van Rossume7e578f1995-08-04 04:00:20 +0000499
500 def address_string(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000501 """Return the client address formatted for logging.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000502
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000503 This version looks up the full hostname using gethostbyaddr(),
504 and tries to find a name that contains at least one dot.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000505
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000506 """
Guido van Rossume7e578f1995-08-04 04:00:20 +0000507
Martin v. Löwis3c120de2003-05-31 07:55:43 +0000508 host, port = self.client_address[:2]
Peter Schneider-Kamp2d2785a2000-08-16 20:30:21 +0000509 return socket.getfqdn(host)
Guido van Rossume7e578f1995-08-04 04:00:20 +0000510
511 # Essentially static class variables
512
513 # The version of the HTTP protocol we support.
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000514 # Set this to HTTP/1.1 to enable automatic keepalive
Guido van Rossume7e578f1995-08-04 04:00:20 +0000515 protocol_version = "HTTP/1.0"
516
517 # The Message-like class used to parse headers
518 MessageClass = mimetools.Message
519
520 # Table mapping response codes to messages; entries have the
521 # form {code: (shortmessage, longmessage)}.
Georg Brandl6aab16e2006-02-17 19:17:25 +0000522 # See RFC 2616.
Guido van Rossume7e578f1995-08-04 04:00:20 +0000523 responses = {
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000524 100: ('Continue', 'Request received, please continue'),
525 101: ('Switching Protocols',
526 'Switching to new protocol; obey Upgrade header'),
527
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000528 200: ('OK', 'Request fulfilled, document follows'),
529 201: ('Created', 'Document created, URL follows'),
530 202: ('Accepted',
531 'Request accepted, processing continues off-line'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000532 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000533 204: ('No Content', 'Request fulfilled, nothing follows'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000534 205: ('Reset Content', 'Clear input form for further input.'),
535 206: ('Partial Content', 'Partial content follows.'),
Tim Peters11cf6052001-01-14 21:54:20 +0000536
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000537 300: ('Multiple Choices',
538 'Object has several resources -- see URI list'),
539 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000540 302: ('Found', 'Object moved temporarily -- see URI list'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000541 303: ('See Other', 'Object moved -- see Method and URL list'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000542 304: ('Not Modified',
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000543 'Document has not changed since given time'),
544 305: ('Use Proxy',
545 'You must use proxy specified in Location to access this '
546 'resource.'),
547 307: ('Temporary Redirect',
548 'Object moved temporarily -- see URI list'),
Tim Peters11cf6052001-01-14 21:54:20 +0000549
Georg Brandl6aab16e2006-02-17 19:17:25 +0000550 400: ('Bad Request',
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000551 'Bad request syntax or unsupported method'),
552 401: ('Unauthorized',
553 'No permission -- see authorization schemes'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000554 402: ('Payment Required',
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000555 'No payment -- see charging schemes'),
556 403: ('Forbidden',
557 'Request forbidden -- authorization will not help'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000558 404: ('Not Found', 'Nothing matches the given URI'),
559 405: ('Method Not Allowed',
Senthil Kumaranee5546c2010-02-22 10:55:08 +0000560 'Specified method is invalid for this resource.'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000561 406: ('Not Acceptable', 'URI not available in preferred format.'),
562 407: ('Proxy Authentication Required', 'You must authenticate with '
563 'this proxy before proceeding.'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000564 408: ('Request Timeout', 'Request timed out; try again later.'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000565 409: ('Conflict', 'Request conflict.'),
566 410: ('Gone',
567 'URI no longer exists and has been permanently removed.'),
568 411: ('Length Required', 'Client must specify Content-Length.'),
569 412: ('Precondition Failed', 'Precondition in headers is false.'),
570 413: ('Request Entity Too Large', 'Entity is too large.'),
571 414: ('Request-URI Too Long', 'URI is too long.'),
572 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
573 416: ('Requested Range Not Satisfiable',
574 'Cannot satisfy request range.'),
575 417: ('Expectation Failed',
576 'Expect condition could not be satisfied.'),
Tim Peters11cf6052001-01-14 21:54:20 +0000577
Georg Brandl6aab16e2006-02-17 19:17:25 +0000578 500: ('Internal Server Error', 'Server got itself in trouble'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000579 501: ('Not Implemented',
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000580 'Server does not support this operation'),
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000581 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000582 503: ('Service Unavailable',
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000583 'The server cannot process the request due to a high load'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000584 504: ('Gateway Timeout',
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000585 'The gateway server did not receive a timely response'),
Georg Brandl6aab16e2006-02-17 19:17:25 +0000586 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000587 }
Guido van Rossume7e578f1995-08-04 04:00:20 +0000588
589
590def test(HandlerClass = BaseHTTPRequestHandler,
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000591 ServerClass = HTTPServer, protocol="HTTP/1.0"):
Guido van Rossume7e578f1995-08-04 04:00:20 +0000592 """Test the HTTP request handler class.
593
594 This runs an HTTP server on port 8000 (or the first command line
595 argument).
596
597 """
598
599 if sys.argv[1:]:
Eric S. Raymond5ff63d62001-02-09 05:38:46 +0000600 port = int(sys.argv[1])
Guido van Rossume7e578f1995-08-04 04:00:20 +0000601 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000602 port = 8000
Guido van Rossume7e578f1995-08-04 04:00:20 +0000603 server_address = ('', port)
604
Martin v. Löwis587c98c2002-03-17 18:37:22 +0000605 HandlerClass.protocol_version = protocol
Guido van Rossume7e578f1995-08-04 04:00:20 +0000606 httpd = ServerClass(server_address, HandlerClass)
607
Martin v. Löwisa43c2f82001-07-24 20:34:08 +0000608 sa = httpd.socket.getsockname()
609 print "Serving HTTP on", sa[0], "port", sa[1], "..."
Guido van Rossume7e578f1995-08-04 04:00:20 +0000610 httpd.serve_forever()
611
612
613if __name__ == '__main__':
614 test()