blob: f019bd9fc3ca357c15ff3056c5949e6841641e7f [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
Senthil Kumaran1251faf2012-06-03 16:15:54 +0800103import argparse
104
Georg Brandl24420152008-05-26 16:32:26 +0000105
106# Default error message template
107DEFAULT_ERROR_MESSAGE = """\
Senthil Kumaran1b407fe2011-03-20 10:44:30 +0800108<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
109 "http://www.w3.org/TR/html4/strict.dtd">
Ezio Melottica897e92011-11-02 19:33:29 +0200110<html>
Senthil Kumaranb253c9f2011-03-17 16:43:22 +0800111 <head>
Senthil Kumaran1b407fe2011-03-20 10:44:30 +0800112 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
Senthil Kumaranb253c9f2011-03-17 16:43:22 +0800113 <title>Error response</title>
114 </head>
115 <body>
116 <h1>Error response</h1>
117 <p>Error code: %(code)d</p>
118 <p>Message: %(message)s.</p>
119 <p>Error code explanation: %(code)s - %(explain)s.</p>
120 </body>
121</html>
Georg Brandl24420152008-05-26 16:32:26 +0000122"""
123
124DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
125
126def _quote_html(html):
127 return html.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
128
129class HTTPServer(socketserver.TCPServer):
130
131 allow_reuse_address = 1 # Seems to make sense in testing environment
132
133 def server_bind(self):
134 """Override server_bind to store the server name."""
135 socketserver.TCPServer.server_bind(self)
136 host, port = self.socket.getsockname()[:2]
137 self.server_name = socket.getfqdn(host)
138 self.server_port = port
139
140
141class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
142
143 """HTTP request handler base class.
144
145 The following explanation of HTTP serves to guide you through the
146 code as well as to expose any misunderstandings I may have about
147 HTTP (so you don't need to read the code to figure out I'm wrong
148 :-).
149
150 HTTP (HyperText Transfer Protocol) is an extensible protocol on
151 top of a reliable stream transport (e.g. TCP/IP). The protocol
152 recognizes three parts to a request:
153
154 1. One line identifying the request type and path
155 2. An optional set of RFC-822-style headers
156 3. An optional data part
157
158 The headers and data are separated by a blank line.
159
160 The first line of the request has the form
161
162 <command> <path> <version>
163
164 where <command> is a (case-sensitive) keyword such as GET or POST,
165 <path> is a string containing path information for the request,
166 and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
167 <path> is encoded using the URL encoding scheme (using %xx to signify
168 the ASCII character with hex code xx).
169
170 The specification specifies that lines are separated by CRLF but
171 for compatibility with the widest range of clients recommends
172 servers also handle LF. Similarly, whitespace in the request line
173 is treated sensibly (allowing multiple spaces between components
174 and allowing trailing whitespace).
175
176 Similarly, for output, lines ought to be separated by CRLF pairs
177 but most clients grok LF characters just fine.
178
179 If the first line of the request has the form
180
181 <command> <path>
182
183 (i.e. <version> is left out) then this is assumed to be an HTTP
184 0.9 request; this form has no optional headers and data part and
185 the reply consists of just the data.
186
187 The reply form of the HTTP 1.x protocol again has three parts:
188
189 1. One line giving the response code
190 2. An optional set of RFC-822-style headers
191 3. The data
192
193 Again, the headers and data are separated by a blank line.
194
195 The response code line has the form
196
197 <version> <responsecode> <responsestring>
198
199 where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
200 <responsecode> is a 3-digit response code indicating success or
201 failure of the request, and <responsestring> is an optional
202 human-readable string explaining what the response code means.
203
204 This server parses the request and the headers, and then calls a
205 function specific to the request type (<command>). Specifically,
206 a request SPAM will be handled by a method do_SPAM(). If no
207 such method exists the server sends an error response to the
208 client. If it exists, it is called with no arguments:
209
210 do_SPAM()
211
212 Note that the request name is case sensitive (i.e. SPAM and spam
213 are different requests).
214
215 The various request details are stored in instance variables:
216
217 - client_address is the client IP address in the form (host,
218 port);
219
220 - command, path and version are the broken-down request line;
221
Barry Warsaw820c1202008-06-12 04:06:45 +0000222 - headers is an instance of email.message.Message (or a derived
Georg Brandl24420152008-05-26 16:32:26 +0000223 class) containing the header information;
224
225 - rfile is a file object open for reading positioned at the
226 start of the optional input data part;
227
228 - wfile is a file object open for writing.
229
230 IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
231
232 The first thing to be written must be the response line. Then
233 follow 0 or more header lines, then a blank line, and then the
234 actual data (if any). The meaning of the header lines depends on
235 the command executed by the server; in most cases, when data is
236 returned, there should be at least one header line of the form
237
238 Content-type: <type>/<subtype>
239
240 where <type> and <subtype> should be registered MIME types,
241 e.g. "text/html" or "text/plain".
242
243 """
244
245 # The Python system version, truncated to its first component.
246 sys_version = "Python/" + sys.version.split()[0]
247
248 # The server software version. You may want to override this.
249 # The format is multiple whitespace-separated strings,
250 # where each string is of the form name[/version].
251 server_version = "BaseHTTP/" + __version__
252
253 error_message_format = DEFAULT_ERROR_MESSAGE
254 error_content_type = DEFAULT_ERROR_CONTENT_TYPE
255
256 # The default request version. This only affects responses up until
257 # the point where the request line is parsed, so it mainly decides what
258 # the client gets back when sending a malformed request line.
259 # Most web servers default to HTTP 0.9, i.e. don't send a status line.
260 default_request_version = "HTTP/0.9"
261
262 def parse_request(self):
263 """Parse a request (internal).
264
265 The request should be stored in self.raw_requestline; the results
266 are in self.command, self.path, self.request_version and
267 self.headers.
268
269 Return True for success, False for failure; on failure, an
270 error is sent back.
271
272 """
273 self.command = None # set in case of error on the first line
274 self.request_version = version = self.default_request_version
275 self.close_connection = 1
276 requestline = str(self.raw_requestline, 'iso-8859-1')
Senthil Kumaran30755492011-12-23 17:03:41 +0800277 requestline = requestline.rstrip('\r\n')
Georg Brandl24420152008-05-26 16:32:26 +0000278 self.requestline = requestline
279 words = requestline.split()
280 if len(words) == 3:
Senthil Kumaran30755492011-12-23 17:03:41 +0800281 command, path, version = words
Georg Brandl24420152008-05-26 16:32:26 +0000282 if version[:5] != 'HTTP/':
283 self.send_error(400, "Bad request version (%r)" % version)
284 return False
285 try:
286 base_version_number = version.split('/', 1)[1]
287 version_number = base_version_number.split(".")
288 # RFC 2145 section 3.1 says there can be only one "." and
289 # - major and minor numbers MUST be treated as
290 # separate integers;
291 # - HTTP/2.4 is a lower version than HTTP/2.13, which in
292 # turn is lower than HTTP/12.3;
293 # - Leading zeros MUST be ignored by recipients.
294 if len(version_number) != 2:
295 raise ValueError
296 version_number = int(version_number[0]), int(version_number[1])
297 except (ValueError, IndexError):
298 self.send_error(400, "Bad request version (%r)" % version)
299 return False
300 if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
301 self.close_connection = 0
302 if version_number >= (2, 0):
303 self.send_error(505,
304 "Invalid HTTP Version (%s)" % base_version_number)
305 return False
306 elif len(words) == 2:
Senthil Kumaran30755492011-12-23 17:03:41 +0800307 command, path = words
Georg Brandl24420152008-05-26 16:32:26 +0000308 self.close_connection = 1
309 if command != 'GET':
310 self.send_error(400,
311 "Bad HTTP/0.9 request type (%r)" % command)
312 return False
313 elif not words:
314 return False
315 else:
316 self.send_error(400, "Bad request syntax (%r)" % requestline)
317 return False
318 self.command, self.path, self.request_version = command, path, version
319
320 # Examine the headers and look for a Connection directive.
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000321 try:
322 self.headers = http.client.parse_headers(self.rfile,
323 _class=self.MessageClass)
324 except http.client.LineTooLong:
325 self.send_error(400, "Line too long")
326 return False
Georg Brandl24420152008-05-26 16:32:26 +0000327
328 conntype = self.headers.get('Connection', "")
329 if conntype.lower() == 'close':
330 self.close_connection = 1
331 elif (conntype.lower() == 'keep-alive' and
332 self.protocol_version >= "HTTP/1.1"):
333 self.close_connection = 0
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000334 # Examine the headers and look for an Expect directive
335 expect = self.headers.get('Expect', "")
336 if (expect.lower() == "100-continue" and
337 self.protocol_version >= "HTTP/1.1" and
338 self.request_version >= "HTTP/1.1"):
339 if not self.handle_expect_100():
340 return False
341 return True
342
343 def handle_expect_100(self):
344 """Decide what to do with an "Expect: 100-continue" header.
345
346 If the client is expecting a 100 Continue response, we must
347 respond with either a 100 Continue or a final response before
348 waiting for the request body. The default is to always respond
349 with a 100 Continue. You can behave differently (for example,
350 reject unauthorized requests) by overriding this method.
351
352 This method should either return True (possibly after sending
353 a 100 Continue response) or send an error response and return
354 False.
355
356 """
357 self.send_response_only(100)
Benjamin Peterson04424232014-01-18 21:50:18 -0500358 self.end_headers()
Georg Brandl24420152008-05-26 16:32:26 +0000359 return True
360
361 def handle_one_request(self):
362 """Handle a single HTTP request.
363
364 You normally don't need to override this method; see the class
365 __doc__ string for information on how to handle specific HTTP
366 commands such as GET and POST.
367
368 """
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000369 try:
Antoine Pitrouc4924372010-12-16 16:48:36 +0000370 self.raw_requestline = self.rfile.readline(65537)
371 if len(self.raw_requestline) > 65536:
372 self.requestline = ''
373 self.request_version = ''
374 self.command = ''
375 self.send_error(414)
376 return
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000377 if not self.raw_requestline:
378 self.close_connection = 1
379 return
380 if not self.parse_request():
381 # An error code has been sent, just exit
382 return
383 mname = 'do_' + self.command
384 if not hasattr(self, mname):
385 self.send_error(501, "Unsupported method (%r)" % self.command)
386 return
387 method = getattr(self, mname)
388 method()
389 self.wfile.flush() #actually send the response if not already done.
390 except socket.timeout as e:
391 #a read or a write timed out. Discard this connection
392 self.log_error("Request timed out: %r", e)
Georg Brandl24420152008-05-26 16:32:26 +0000393 self.close_connection = 1
394 return
Georg Brandl24420152008-05-26 16:32:26 +0000395
396 def handle(self):
397 """Handle multiple requests if necessary."""
398 self.close_connection = 1
399
400 self.handle_one_request()
401 while not self.close_connection:
402 self.handle_one_request()
403
Senthil Kumaran26886442013-03-15 07:53:21 -0700404 def send_error(self, code, message=None, explain=None):
Georg Brandl24420152008-05-26 16:32:26 +0000405 """Send and log an error reply.
406
Senthil Kumaran26886442013-03-15 07:53:21 -0700407 Arguments are
408 * code: an HTTP error code
409 3 digits
410 * message: a simple optional 1 line reason phrase.
411 *( HTAB / SP / VCHAR / %x80-FF )
412 defaults to short entry matching the response code
413 * explain: a detailed message defaults to the long entry
414 matching the response code.
Georg Brandl24420152008-05-26 16:32:26 +0000415
416 This sends an error response (so it must be called before any
417 output has been generated), logs the error, and finally sends
418 a piece of HTML explaining the error to the user.
419
420 """
421
422 try:
423 shortmsg, longmsg = self.responses[code]
424 except KeyError:
425 shortmsg, longmsg = '???', '???'
426 if message is None:
427 message = shortmsg
Senthil Kumaran26886442013-03-15 07:53:21 -0700428 if explain is None:
429 explain = longmsg
Georg Brandl24420152008-05-26 16:32:26 +0000430 self.log_error("code %d, message %s", code, message)
431 # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
432 content = (self.error_message_format %
Senthil Kumaran26886442013-03-15 07:53:21 -0700433 {'code': code, 'message': _quote_html(message), 'explain': _quote_html(explain)})
Senthil Kumaran52d27202012-10-10 23:16:21 -0700434 body = content.encode('UTF-8', 'replace')
Senthil Kumaran1e7551d2013-03-05 02:25:58 -0800435 self.send_response(code, message)
Georg Brandl24420152008-05-26 16:32:26 +0000436 self.send_header("Content-Type", self.error_content_type)
437 self.send_header('Connection', 'close')
Senthil Kumaran52d27202012-10-10 23:16:21 -0700438 self.send_header('Content-Length', int(len(body)))
Georg Brandl24420152008-05-26 16:32:26 +0000439 self.end_headers()
440 if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
Senthil Kumaran52d27202012-10-10 23:16:21 -0700441 self.wfile.write(body)
Georg Brandl24420152008-05-26 16:32:26 +0000442
443 def send_response(self, code, message=None):
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800444 """Add the response header to the headers buffer and log the
445 response code.
Georg Brandl24420152008-05-26 16:32:26 +0000446
447 Also send two standard headers with the server software
448 version and the current date.
449
450 """
451 self.log_request(code)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000452 self.send_response_only(code, message)
453 self.send_header('Server', self.version_string())
454 self.send_header('Date', self.date_time_string())
455
456 def send_response_only(self, code, message=None):
457 """Send the response header only."""
Georg Brandl24420152008-05-26 16:32:26 +0000458 if message is None:
459 if code in self.responses:
460 message = self.responses[code][0]
461 else:
462 message = ''
463 if self.request_version != 'HTTP/0.9':
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800464 if not hasattr(self, '_headers_buffer'):
465 self._headers_buffer = []
466 self._headers_buffer.append(("%s %d %s\r\n" %
467 (self.protocol_version, code, message)).encode(
468 'latin-1', 'strict'))
Georg Brandl24420152008-05-26 16:32:26 +0000469
470 def send_header(self, keyword, value):
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800471 """Send a MIME header to the headers buffer."""
Georg Brandl24420152008-05-26 16:32:26 +0000472 if self.request_version != 'HTTP/0.9':
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000473 if not hasattr(self, '_headers_buffer'):
474 self._headers_buffer = []
475 self._headers_buffer.append(
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000476 ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
Georg Brandl24420152008-05-26 16:32:26 +0000477
478 if keyword.lower() == 'connection':
479 if value.lower() == 'close':
480 self.close_connection = 1
481 elif value.lower() == 'keep-alive':
482 self.close_connection = 0
483
484 def end_headers(self):
485 """Send the blank line ending the MIME headers."""
486 if self.request_version != 'HTTP/0.9':
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000487 self._headers_buffer.append(b"\r\n")
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800488 self.flush_headers()
489
490 def flush_headers(self):
491 if hasattr(self, '_headers_buffer'):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000492 self.wfile.write(b"".join(self._headers_buffer))
493 self._headers_buffer = []
Georg Brandl24420152008-05-26 16:32:26 +0000494
495 def log_request(self, code='-', size='-'):
496 """Log an accepted request.
497
498 This is called by send_response().
499
500 """
501
502 self.log_message('"%s" %s %s',
503 self.requestline, str(code), str(size))
504
505 def log_error(self, format, *args):
506 """Log an error.
507
508 This is called when a request cannot be fulfilled. By
509 default it passes the message on to log_message().
510
511 Arguments are the same as for log_message().
512
513 XXX This should go to the separate error log.
514
515 """
516
517 self.log_message(format, *args)
518
519 def log_message(self, format, *args):
520 """Log an arbitrary message.
521
522 This is used by all other logging functions. Override
523 it if you have specific logging wishes.
524
525 The first argument, FORMAT, is a format string for the
526 message to be logged. If the format string contains
527 any % escapes requiring parameters, they should be
528 specified as subsequent arguments (it's just like
529 printf!).
530
Senthil Kumarandb727b42012-04-29 13:41:03 +0800531 The client ip and current date/time are prefixed to
Georg Brandl24420152008-05-26 16:32:26 +0000532 every message.
533
534 """
535
536 sys.stderr.write("%s - - [%s] %s\n" %
537 (self.address_string(),
538 self.log_date_time_string(),
539 format%args))
540
541 def version_string(self):
542 """Return the server software version string."""
543 return self.server_version + ' ' + self.sys_version
544
545 def date_time_string(self, timestamp=None):
546 """Return the current date and time formatted for a message header."""
547 if timestamp is None:
548 timestamp = time.time()
549 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
550 s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
551 self.weekdayname[wd],
552 day, self.monthname[month], year,
553 hh, mm, ss)
554 return s
555
556 def log_date_time_string(self):
557 """Return the current time formatted for logging."""
558 now = time.time()
559 year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
560 s = "%02d/%3s/%04d %02d:%02d:%02d" % (
561 day, self.monthname[month], year, hh, mm, ss)
562 return s
563
564 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
565
566 monthname = [None,
567 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
568 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
569
570 def address_string(self):
Senthil Kumaran1aacba42012-04-29 12:51:54 +0800571 """Return the client address."""
Georg Brandl24420152008-05-26 16:32:26 +0000572
Senthil Kumaran1aacba42012-04-29 12:51:54 +0800573 return self.client_address[0]
Georg Brandl24420152008-05-26 16:32:26 +0000574
575 # Essentially static class variables
576
577 # The version of the HTTP protocol we support.
578 # Set this to HTTP/1.1 to enable automatic keepalive
579 protocol_version = "HTTP/1.0"
580
Barry Warsaw820c1202008-06-12 04:06:45 +0000581 # MessageClass used to parse headers
Barry Warsaw820c1202008-06-12 04:06:45 +0000582 MessageClass = http.client.HTTPMessage
Georg Brandl24420152008-05-26 16:32:26 +0000583
584 # Table mapping response codes to messages; entries have the
585 # form {code: (shortmessage, longmessage)}.
Hynek Schlawack51b2ed52012-05-16 09:51:07 +0200586 # See RFC 2616 and 6585.
Georg Brandl24420152008-05-26 16:32:26 +0000587 responses = {
588 100: ('Continue', 'Request received, please continue'),
589 101: ('Switching Protocols',
590 'Switching to new protocol; obey Upgrade header'),
591
592 200: ('OK', 'Request fulfilled, document follows'),
593 201: ('Created', 'Document created, URL follows'),
594 202: ('Accepted',
595 'Request accepted, processing continues off-line'),
596 203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
597 204: ('No Content', 'Request fulfilled, nothing follows'),
598 205: ('Reset Content', 'Clear input form for further input.'),
599 206: ('Partial Content', 'Partial content follows.'),
600
601 300: ('Multiple Choices',
602 'Object has several resources -- see URI list'),
603 301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
604 302: ('Found', 'Object moved temporarily -- see URI list'),
605 303: ('See Other', 'Object moved -- see Method and URL list'),
606 304: ('Not Modified',
607 'Document has not changed since given time'),
608 305: ('Use Proxy',
609 'You must use proxy specified in Location to access this '
610 'resource.'),
611 307: ('Temporary Redirect',
612 'Object moved temporarily -- see URI list'),
613
614 400: ('Bad Request',
615 'Bad request syntax or unsupported method'),
616 401: ('Unauthorized',
617 'No permission -- see authorization schemes'),
618 402: ('Payment Required',
619 'No payment -- see charging schemes'),
620 403: ('Forbidden',
621 'Request forbidden -- authorization will not help'),
622 404: ('Not Found', 'Nothing matches the given URI'),
623 405: ('Method Not Allowed',
Senthil Kumaran7aa26212010-02-22 11:00:50 +0000624 'Specified method is invalid for this resource.'),
Georg Brandl24420152008-05-26 16:32:26 +0000625 406: ('Not Acceptable', 'URI not available in preferred format.'),
626 407: ('Proxy Authentication Required', 'You must authenticate with '
627 'this proxy before proceeding.'),
628 408: ('Request Timeout', 'Request timed out; try again later.'),
629 409: ('Conflict', 'Request conflict.'),
630 410: ('Gone',
631 'URI no longer exists and has been permanently removed.'),
632 411: ('Length Required', 'Client must specify Content-Length.'),
633 412: ('Precondition Failed', 'Precondition in headers is false.'),
634 413: ('Request Entity Too Large', 'Entity is too large.'),
635 414: ('Request-URI Too Long', 'URI is too long.'),
636 415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
637 416: ('Requested Range Not Satisfiable',
638 'Cannot satisfy request range.'),
639 417: ('Expectation Failed',
640 'Expect condition could not be satisfied.'),
Hynek Schlawack51b2ed52012-05-16 09:51:07 +0200641 428: ('Precondition Required',
642 'The origin server requires the request to be conditional.'),
643 429: ('Too Many Requests', 'The user has sent too many requests '
644 'in a given amount of time ("rate limiting").'),
645 431: ('Request Header Fields Too Large', 'The server is unwilling to '
646 'process the request because its header fields are too large.'),
Georg Brandl24420152008-05-26 16:32:26 +0000647
648 500: ('Internal Server Error', 'Server got itself in trouble'),
649 501: ('Not Implemented',
650 'Server does not support this operation'),
651 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
652 503: ('Service Unavailable',
653 'The server cannot process the request due to a high load'),
654 504: ('Gateway Timeout',
655 'The gateway server did not receive a timely response'),
656 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
Hynek Schlawack51b2ed52012-05-16 09:51:07 +0200657 511: ('Network Authentication Required',
658 'The client needs to authenticate to gain network access.'),
Georg Brandl24420152008-05-26 16:32:26 +0000659 }
660
661
662class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
663
664 """Simple HTTP request handler with GET and HEAD commands.
665
666 This serves files from the current directory and any of its
667 subdirectories. The MIME type for files is determined by
668 calling the .guess_type() method.
669
670 The GET and HEAD requests are identical except that the HEAD
671 request omits the actual contents of the file.
672
673 """
674
675 server_version = "SimpleHTTP/" + __version__
676
677 def do_GET(self):
678 """Serve a GET request."""
679 f = self.send_head()
680 if f:
Serhiy Storchaka91b0bc22014-01-25 19:43:02 +0200681 try:
682 self.copyfile(f, self.wfile)
683 finally:
684 f.close()
Georg Brandl24420152008-05-26 16:32:26 +0000685
686 def do_HEAD(self):
687 """Serve a HEAD request."""
688 f = self.send_head()
689 if f:
690 f.close()
691
692 def send_head(self):
693 """Common code for GET and HEAD commands.
694
695 This sends the response code and MIME headers.
696
697 Return value is either a file object (which has to be copied
698 to the outputfile by the caller unless the command was HEAD,
699 and must be closed by the caller under all circumstances), or
700 None, in which case the caller has nothing further to do.
701
702 """
703 path = self.translate_path(self.path)
704 f = None
705 if os.path.isdir(path):
706 if not self.path.endswith('/'):
707 # redirect browser - doing basically what apache does
708 self.send_response(301)
709 self.send_header("Location", self.path + "/")
710 self.end_headers()
711 return None
712 for index in "index.html", "index.htm":
713 index = os.path.join(path, index)
714 if os.path.exists(index):
715 path = index
716 break
717 else:
718 return self.list_directory(path)
719 ctype = self.guess_type(path)
720 try:
721 f = open(path, 'rb')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200722 except OSError:
Georg Brandl24420152008-05-26 16:32:26 +0000723 self.send_error(404, "File not found")
724 return None
Serhiy Storchaka91b0bc22014-01-25 19:43:02 +0200725 try:
726 self.send_response(200)
727 self.send_header("Content-type", ctype)
728 fs = os.fstat(f.fileno())
729 self.send_header("Content-Length", str(fs[6]))
730 self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
731 self.end_headers()
732 return f
733 except:
734 f.close()
735 raise
Georg Brandl24420152008-05-26 16:32:26 +0000736
737 def list_directory(self, path):
738 """Helper to produce a directory listing (absent index.html).
739
740 Return value is either a file object, or None (indicating an
741 error). In either case, the headers are sent, making the
742 interface the same as for send_head().
743
744 """
745 try:
746 list = os.listdir(path)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200747 except OSError:
Georg Brandl24420152008-05-26 16:32:26 +0000748 self.send_error(404, "No permission to list directory")
749 return None
750 list.sort(key=lambda a: a.lower())
751 r = []
Georg Brandl1f7fffb2010-10-15 15:57:45 +0000752 displaypath = html.escape(urllib.parse.unquote(self.path))
Ezio Melottica897e92011-11-02 19:33:29 +0200753 enc = sys.getfilesystemencoding()
754 title = 'Directory listing for %s' % displaypath
755 r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
756 '"http://www.w3.org/TR/html4/strict.dtd">')
757 r.append('<html>\n<head>')
758 r.append('<meta http-equiv="Content-Type" '
759 'content="text/html; charset=%s">' % enc)
760 r.append('<title>%s</title>\n</head>' % title)
761 r.append('<body>\n<h1>%s</h1>' % title)
762 r.append('<hr>\n<ul>')
Georg Brandl24420152008-05-26 16:32:26 +0000763 for name in list:
764 fullname = os.path.join(path, name)
765 displayname = linkname = name
766 # Append / for directories or @ for symbolic links
767 if os.path.isdir(fullname):
768 displayname = name + "/"
769 linkname = name + "/"
770 if os.path.islink(fullname):
771 displayname = name + "@"
772 # Note: a link to a directory displays with @ and links with /
Ezio Melottica897e92011-11-02 19:33:29 +0200773 r.append('<li><a href="%s">%s</a></li>'
Georg Brandl1f7fffb2010-10-15 15:57:45 +0000774 % (urllib.parse.quote(linkname), html.escape(displayname)))
Ezio Melottica897e92011-11-02 19:33:29 +0200775 r.append('</ul>\n<hr>\n</body>\n</html>\n')
776 encoded = '\n'.join(r).encode(enc)
Georg Brandl24420152008-05-26 16:32:26 +0000777 f = io.BytesIO()
778 f.write(encoded)
779 f.seek(0)
780 self.send_response(200)
781 self.send_header("Content-type", "text/html; charset=%s" % enc)
782 self.send_header("Content-Length", str(len(encoded)))
783 self.end_headers()
784 return f
785
786 def translate_path(self, path):
787 """Translate a /-separated PATH to the local filename syntax.
788
789 Components that mean special things to the local file system
790 (e.g. drive or directory names) are ignored. (XXX They should
791 probably be diagnosed.)
792
793 """
794 # abandon query parameters
795 path = path.split('?',1)[0]
796 path = path.split('#',1)[0]
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700797 # Don't forget explicit trailing slash when normalizing. Issue17324
Senthil Kumaran600b7352013-09-29 18:59:04 -0700798 trailing_slash = path.rstrip().endswith('/')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000799 path = posixpath.normpath(urllib.parse.unquote(path))
Georg Brandl24420152008-05-26 16:32:26 +0000800 words = path.split('/')
801 words = filter(None, words)
802 path = os.getcwd()
803 for word in words:
804 drive, word = os.path.splitdrive(word)
805 head, word = os.path.split(word)
806 if word in (os.curdir, os.pardir): continue
807 path = os.path.join(path, word)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700808 if trailing_slash:
809 path += '/'
Georg Brandl24420152008-05-26 16:32:26 +0000810 return path
811
812 def copyfile(self, source, outputfile):
813 """Copy all data between two file objects.
814
815 The SOURCE argument is a file object open for reading
816 (or anything with a read() method) and the DESTINATION
817 argument is a file object open for writing (or
818 anything with a write() method).
819
820 The only reason for overriding this would be to change
821 the block size or perhaps to replace newlines by CRLF
822 -- note however that this the default server uses this
823 to copy binary data as well.
824
825 """
826 shutil.copyfileobj(source, outputfile)
827
828 def guess_type(self, path):
829 """Guess the type of a file.
830
831 Argument is a PATH (a filename).
832
833 Return value is a string of the form type/subtype,
834 usable for a MIME Content-type header.
835
836 The default implementation looks the file's extension
837 up in the table self.extensions_map, using application/octet-stream
838 as a default; however it would be permissible (if
839 slow) to look inside the data to make a better guess.
840
841 """
842
843 base, ext = posixpath.splitext(path)
844 if ext in self.extensions_map:
845 return self.extensions_map[ext]
846 ext = ext.lower()
847 if ext in self.extensions_map:
848 return self.extensions_map[ext]
849 else:
850 return self.extensions_map['']
851
852 if not mimetypes.inited:
853 mimetypes.init() # try to read system mime.types
854 extensions_map = mimetypes.types_map.copy()
855 extensions_map.update({
856 '': 'application/octet-stream', # Default
857 '.py': 'text/plain',
858 '.c': 'text/plain',
859 '.h': 'text/plain',
860 })
861
862
863# Utilities for CGIHTTPRequestHandler
864
Senthil Kumarand70846b2012-04-12 02:34:32 +0800865def _url_collapse_path(path):
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000866 """
867 Given a URL path, remove extra '/'s and '.' path elements and collapse
Senthil Kumarand70846b2012-04-12 02:34:32 +0800868 any '..' references and returns a colllapsed path.
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000869
870 Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
Senthil Kumarand70846b2012-04-12 02:34:32 +0800871 The utility of this function is limited to is_cgi method and helps
872 preventing some security attacks.
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000873
874 Returns: A tuple of (head, tail) where tail is everything after the final /
875 and head is everything before it. Head will always start with a '/' and,
876 if it contains anything else, never have a trailing '/'.
877
878 Raises: IndexError if too many '..' occur within the path.
Senthil Kumarand70846b2012-04-12 02:34:32 +0800879
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000880 """
881 # Similar to os.path.split(os.path.normpath(path)) but specific to URL
882 # path semantics rather than local operating system semantics.
Senthil Kumarand70846b2012-04-12 02:34:32 +0800883 path_parts = path.split('/')
884 head_parts = []
885 for part in path_parts[:-1]:
886 if part == '..':
887 head_parts.pop() # IndexError if more '..' than prior parts
888 elif part and part != '.':
889 head_parts.append( part )
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000890 if path_parts:
Senthil Kumarandbb369d2012-04-11 03:15:28 +0800891 tail_part = path_parts.pop()
Senthil Kumarand70846b2012-04-12 02:34:32 +0800892 if tail_part:
893 if tail_part == '..':
894 head_parts.pop()
895 tail_part = ''
896 elif tail_part == '.':
897 tail_part = ''
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000898 else:
899 tail_part = ''
Senthil Kumarand70846b2012-04-12 02:34:32 +0800900
901 splitpath = ('/' + '/'.join(head_parts), tail_part)
902 collapsed_path = "/".join(splitpath)
903
904 return collapsed_path
905
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000906
907
Georg Brandl24420152008-05-26 16:32:26 +0000908nobody = None
909
910def nobody_uid():
911 """Internal routine to get nobody's uid"""
912 global nobody
913 if nobody:
914 return nobody
915 try:
916 import pwd
Brett Cannoncd171c82013-07-04 17:43:24 -0400917 except ImportError:
Georg Brandl24420152008-05-26 16:32:26 +0000918 return -1
919 try:
920 nobody = pwd.getpwnam('nobody')[2]
921 except KeyError:
Georg Brandlcbd2ab12010-12-04 10:39:14 +0000922 nobody = 1 + max(x[2] for x in pwd.getpwall())
Georg Brandl24420152008-05-26 16:32:26 +0000923 return nobody
924
925
926def executable(path):
927 """Test for executable file."""
Victor Stinnerfb25ba92011-06-20 17:45:54 +0200928 return os.access(path, os.X_OK)
Georg Brandl24420152008-05-26 16:32:26 +0000929
930
931class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
932
933 """Complete HTTP server with GET, HEAD and POST commands.
934
935 GET and HEAD also support running CGI scripts.
936
937 The POST command is *only* implemented for CGI scripts.
938
939 """
940
941 # Determine platform specifics
942 have_fork = hasattr(os, 'fork')
Georg Brandl24420152008-05-26 16:32:26 +0000943
944 # Make rfile unbuffered -- we need to read one line and then pass
945 # the rest to a subprocess, so we can't use buffered input.
946 rbufsize = 0
947
948 def do_POST(self):
949 """Serve a POST request.
950
951 This is only implemented for CGI scripts.
952
953 """
954
955 if self.is_cgi():
956 self.run_cgi()
957 else:
958 self.send_error(501, "Can only POST to CGI scripts")
959
960 def send_head(self):
961 """Version of send_head that support CGI scripts"""
962 if self.is_cgi():
963 return self.run_cgi()
964 else:
965 return SimpleHTTPRequestHandler.send_head(self)
966
967 def is_cgi(self):
968 """Test whether self.path corresponds to a CGI script.
969
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000970 Returns True and updates the cgi_info attribute to the tuple
971 (dir, rest) if self.path requires running a CGI script.
972 Returns False otherwise.
Georg Brandl24420152008-05-26 16:32:26 +0000973
Benjamin Petersona7deeee2009-05-08 20:54:42 +0000974 If any exception is raised, the caller should assume that
975 self.path was rejected as invalid and act accordingly.
976
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000977 The default implementation tests whether the normalized url
978 path begins with one of the strings in self.cgi_directories
979 (and the next character is a '/' or the end of the string).
Georg Brandl24420152008-05-26 16:32:26 +0000980
981 """
Senthil Kumarand70846b2012-04-12 02:34:32 +0800982 collapsed_path = _url_collapse_path(self.path)
983 dir_sep = collapsed_path.find('/', 1)
984 head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
Senthil Kumarandbb369d2012-04-11 03:15:28 +0800985 if head in self.cgi_directories:
986 self.cgi_info = head, tail
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000987 return True
Georg Brandl24420152008-05-26 16:32:26 +0000988 return False
989
Senthil Kumarand70846b2012-04-12 02:34:32 +0800990
Georg Brandl24420152008-05-26 16:32:26 +0000991 cgi_directories = ['/cgi-bin', '/htbin']
992
993 def is_executable(self, path):
994 """Test whether argument path is an executable file."""
995 return executable(path)
996
997 def is_python(self, path):
998 """Test whether argument path is a Python script."""
999 head, tail = os.path.splitext(path)
1000 return tail.lower() in (".py", ".pyw")
1001
1002 def run_cgi(self):
1003 """Execute a CGI script."""
Georg Brandl24420152008-05-26 16:32:26 +00001004 dir, rest = self.cgi_info
1005
Benjamin Peterson04e9de42013-10-30 12:43:09 -04001006 i = rest.find('/')
Georg Brandl24420152008-05-26 16:32:26 +00001007 while i >= 0:
Benjamin Peterson04e9de42013-10-30 12:43:09 -04001008 nextdir = rest[:i]
1009 nextrest = rest[i+1:]
Georg Brandl24420152008-05-26 16:32:26 +00001010
1011 scriptdir = self.translate_path(nextdir)
1012 if os.path.isdir(scriptdir):
1013 dir, rest = nextdir, nextrest
Benjamin Peterson04e9de42013-10-30 12:43:09 -04001014 i = rest.find('/')
Georg Brandl24420152008-05-26 16:32:26 +00001015 else:
1016 break
1017
1018 # find an explicit query string, if present.
1019 i = rest.rfind('?')
1020 if i >= 0:
1021 rest, query = rest[:i], rest[i+1:]
1022 else:
1023 query = ''
1024
1025 # dissect the part after the directory name into a script name &
1026 # a possible additional path, to be stored in PATH_INFO.
1027 i = rest.find('/')
1028 if i >= 0:
1029 script, rest = rest[:i], rest[i:]
1030 else:
1031 script, rest = rest, ''
1032
1033 scriptname = dir + '/' + script
1034 scriptfile = self.translate_path(scriptname)
1035 if not os.path.exists(scriptfile):
1036 self.send_error(404, "No such CGI script (%r)" % scriptname)
1037 return
1038 if not os.path.isfile(scriptfile):
1039 self.send_error(403, "CGI script is not a plain file (%r)" %
1040 scriptname)
1041 return
1042 ispy = self.is_python(scriptname)
Victor Stinnerfb25ba92011-06-20 17:45:54 +02001043 if self.have_fork or not ispy:
Georg Brandl24420152008-05-26 16:32:26 +00001044 if not self.is_executable(scriptfile):
1045 self.send_error(403, "CGI script is not executable (%r)" %
1046 scriptname)
1047 return
1048
1049 # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
1050 # XXX Much of the following could be prepared ahead of time!
Senthil Kumaran42713722010-10-03 17:55:45 +00001051 env = copy.deepcopy(os.environ)
Georg Brandl24420152008-05-26 16:32:26 +00001052 env['SERVER_SOFTWARE'] = self.version_string()
1053 env['SERVER_NAME'] = self.server.server_name
1054 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
1055 env['SERVER_PROTOCOL'] = self.protocol_version
1056 env['SERVER_PORT'] = str(self.server.server_port)
1057 env['REQUEST_METHOD'] = self.command
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001058 uqrest = urllib.parse.unquote(rest)
Georg Brandl24420152008-05-26 16:32:26 +00001059 env['PATH_INFO'] = uqrest
1060 env['PATH_TRANSLATED'] = self.translate_path(uqrest)
1061 env['SCRIPT_NAME'] = scriptname
1062 if query:
1063 env['QUERY_STRING'] = query
Georg Brandl24420152008-05-26 16:32:26 +00001064 env['REMOTE_ADDR'] = self.client_address[0]
Barry Warsaw820c1202008-06-12 04:06:45 +00001065 authorization = self.headers.get("authorization")
Georg Brandl24420152008-05-26 16:32:26 +00001066 if authorization:
1067 authorization = authorization.split()
1068 if len(authorization) == 2:
1069 import base64, binascii
1070 env['AUTH_TYPE'] = authorization[0]
1071 if authorization[0].lower() == "basic":
1072 try:
1073 authorization = authorization[1].encode('ascii')
Georg Brandl706824f2009-06-04 09:42:55 +00001074 authorization = base64.decodebytes(authorization).\
Georg Brandl24420152008-05-26 16:32:26 +00001075 decode('ascii')
1076 except (binascii.Error, UnicodeError):
1077 pass
1078 else:
1079 authorization = authorization.split(':')
1080 if len(authorization) == 2:
1081 env['REMOTE_USER'] = authorization[0]
1082 # XXX REMOTE_IDENT
Barry Warsaw820c1202008-06-12 04:06:45 +00001083 if self.headers.get('content-type') is None:
1084 env['CONTENT_TYPE'] = self.headers.get_content_type()
Georg Brandl24420152008-05-26 16:32:26 +00001085 else:
Barry Warsaw820c1202008-06-12 04:06:45 +00001086 env['CONTENT_TYPE'] = self.headers['content-type']
1087 length = self.headers.get('content-length')
Georg Brandl24420152008-05-26 16:32:26 +00001088 if length:
1089 env['CONTENT_LENGTH'] = length
Barry Warsaw820c1202008-06-12 04:06:45 +00001090 referer = self.headers.get('referer')
Georg Brandl24420152008-05-26 16:32:26 +00001091 if referer:
1092 env['HTTP_REFERER'] = referer
1093 accept = []
1094 for line in self.headers.getallmatchingheaders('accept'):
1095 if line[:1] in "\t\n\r ":
1096 accept.append(line.strip())
1097 else:
1098 accept = accept + line[7:].split(',')
1099 env['HTTP_ACCEPT'] = ','.join(accept)
Barry Warsaw820c1202008-06-12 04:06:45 +00001100 ua = self.headers.get('user-agent')
Georg Brandl24420152008-05-26 16:32:26 +00001101 if ua:
1102 env['HTTP_USER_AGENT'] = ua
Barry Warsaw820c1202008-06-12 04:06:45 +00001103 co = filter(None, self.headers.get_all('cookie', []))
Georg Brandl62e2ca22010-07-31 21:54:24 +00001104 cookie_str = ', '.join(co)
1105 if cookie_str:
1106 env['HTTP_COOKIE'] = cookie_str
Georg Brandl24420152008-05-26 16:32:26 +00001107 # XXX Other HTTP_* headers
1108 # Since we're setting the env in the parent, provide empty
1109 # values to override previously set values
1110 for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
1111 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
1112 env.setdefault(k, "")
Georg Brandl24420152008-05-26 16:32:26 +00001113
1114 self.send_response(200, "Script output follows")
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +08001115 self.flush_headers()
Georg Brandl24420152008-05-26 16:32:26 +00001116
1117 decoded_query = query.replace('+', ' ')
1118
1119 if self.have_fork:
1120 # Unix -- fork as we should
1121 args = [script]
1122 if '=' not in decoded_query:
1123 args.append(decoded_query)
1124 nobody = nobody_uid()
1125 self.wfile.flush() # Always flush before forking
1126 pid = os.fork()
1127 if pid != 0:
1128 # Parent
1129 pid, sts = os.waitpid(pid, 0)
1130 # throw away additional data [see bug #427345]
1131 while select.select([self.rfile], [], [], 0)[0]:
1132 if not self.rfile.read(1):
1133 break
1134 if sts:
1135 self.log_error("CGI script exit status %#x", sts)
1136 return
1137 # Child
1138 try:
1139 try:
1140 os.setuid(nobody)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +02001141 except OSError:
Georg Brandl24420152008-05-26 16:32:26 +00001142 pass
1143 os.dup2(self.rfile.fileno(), 0)
1144 os.dup2(self.wfile.fileno(), 1)
Senthil Kumaran42713722010-10-03 17:55:45 +00001145 os.execve(scriptfile, args, env)
Georg Brandl24420152008-05-26 16:32:26 +00001146 except:
1147 self.server.handle_error(self.request, self.client_address)
1148 os._exit(127)
1149
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001150 else:
1151 # Non-Unix -- use subprocess
1152 import subprocess
Senthil Kumarane29cd162009-11-11 04:17:53 +00001153 cmdline = [scriptfile]
Georg Brandl24420152008-05-26 16:32:26 +00001154 if self.is_python(scriptfile):
1155 interp = sys.executable
1156 if interp.lower().endswith("w.exe"):
1157 # On Windows, use python.exe, not pythonw.exe
1158 interp = interp[:-5] + interp[-4:]
Senthil Kumarane29cd162009-11-11 04:17:53 +00001159 cmdline = [interp, '-u'] + cmdline
1160 if '=' not in query:
1161 cmdline.append(query)
1162 self.log_message("command: %s", subprocess.list2cmdline(cmdline))
Georg Brandl24420152008-05-26 16:32:26 +00001163 try:
1164 nbytes = int(length)
1165 except (TypeError, ValueError):
1166 nbytes = 0
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001167 p = subprocess.Popen(cmdline,
1168 stdin=subprocess.PIPE,
1169 stdout=subprocess.PIPE,
Senthil Kumaran42713722010-10-03 17:55:45 +00001170 stderr=subprocess.PIPE,
1171 env = env
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001172 )
Georg Brandl24420152008-05-26 16:32:26 +00001173 if self.command.lower() == "post" and nbytes > 0:
1174 data = self.rfile.read(nbytes)
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001175 else:
1176 data = None
Georg Brandl24420152008-05-26 16:32:26 +00001177 # throw away additional data [see bug #427345]
1178 while select.select([self.rfile._sock], [], [], 0)[0]:
1179 if not self.rfile._sock.recv(1):
1180 break
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001181 stdout, stderr = p.communicate(data)
1182 self.wfile.write(stdout)
1183 if stderr:
1184 self.log_error('%s', stderr)
Brian Curtincbad4df2010-11-05 15:04:48 +00001185 p.stderr.close()
1186 p.stdout.close()
Amaury Forgeot d'Arccb0d2d72008-06-18 22:19:22 +00001187 status = p.returncode
1188 if status:
1189 self.log_error("CGI script exit status %#x", status)
Georg Brandl24420152008-05-26 16:32:26 +00001190 else:
1191 self.log_message("CGI script exited OK")
1192
1193
Senthil Kumarandefe7f42013-09-15 09:37:27 -07001194def test(HandlerClass=BaseHTTPRequestHandler,
1195 ServerClass=HTTPServer, protocol="HTTP/1.0", port=8000, bind=""):
Georg Brandl24420152008-05-26 16:32:26 +00001196 """Test the HTTP request handler class.
1197
1198 This runs an HTTP server on port 8000 (or the first command line
1199 argument).
1200
1201 """
Senthil Kumarandefe7f42013-09-15 09:37:27 -07001202 server_address = (bind, port)
Georg Brandl24420152008-05-26 16:32:26 +00001203
1204 HandlerClass.protocol_version = protocol
1205 httpd = ServerClass(server_address, HandlerClass)
1206
1207 sa = httpd.socket.getsockname()
1208 print("Serving HTTP on", sa[0], "port", sa[1], "...")
Alexandre Vassalottib5292a22009-04-03 07:16:55 +00001209 try:
1210 httpd.serve_forever()
1211 except KeyboardInterrupt:
1212 print("\nKeyboard interrupt received, exiting.")
1213 httpd.server_close()
1214 sys.exit(0)
Georg Brandl24420152008-05-26 16:32:26 +00001215
1216if __name__ == '__main__':
Senthil Kumaran1251faf2012-06-03 16:15:54 +08001217 parser = argparse.ArgumentParser()
1218 parser.add_argument('--cgi', action='store_true',
1219 help='Run as CGI Server')
Senthil Kumarandefe7f42013-09-15 09:37:27 -07001220 parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
1221 help='Specify alternate bind address '
1222 '[default: all interfaces]')
Senthil Kumaran1251faf2012-06-03 16:15:54 +08001223 parser.add_argument('port', action='store',
1224 default=8000, type=int,
1225 nargs='?',
1226 help='Specify alternate port [default: 8000]')
1227 args = parser.parse_args()
1228 if args.cgi:
Senthil Kumarandefe7f42013-09-15 09:37:27 -07001229 handler_class = CGIHTTPRequestHandler
Senthil Kumaran1251faf2012-06-03 16:15:54 +08001230 else:
Senthil Kumarandefe7f42013-09-15 09:37:27 -07001231 handler_class = SimpleHTTPRequestHandler
1232 test(HandlerClass=handler_class, port=args.port, bind=args.bind)