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