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