Debian Codegraph @

Lib/http/server.py

raw
1 """HTTP server classes.
2
3 Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
4 SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
5 and (deprecated) CGIHTTPRequestHandler for CGI scripts.
6
7 It does, however, optionally implement HTTP/1.1 persistent connections.
8
9 Notes on CGIHTTPRequestHandler
10 ------------------------------
11
12 This class is deprecated. It implements GET and POST requests to cgi-bin scripts.
13
14 If the os.fork() function is not present (Windows), subprocess.Popen() is used,
15 with slightly altered but never documented semantics. Use from a threaded
16 process is likely to trigger a warning at os.fork() time.
17
18 In all cases, the implementation is intentionally naive -- all
19 requests are executed synchronously.
20
21 SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
22 -- it may execute arbitrary Python code or external programs.
23
24 Note that status code 200 is sent prior to execution of a CGI script, so
25 scripts cannot send other status codes such as 302 (redirect).
26
27 XXX 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__ = [
86 "HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler",
87 "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler",
88 ]
89
90 import copy
91 import datetime
92 import email.utils
93 import html
94 import http.client
95 import io
96 import itertools
97 import mimetypes
98 import os
99 import posixpath
100 import select
101 import shutil
102 import socket # For gethostbyaddr()
103 import socketserver
104 import sys
105 import time
106 import urllib.parse
107
108 from http import HTTPStatus
109
110
111 # Default error message template
112 DEFAULT_ERROR_MESSAGE = """\
113 <!DOCTYPE HTML>
114 <html lang="en">
115 <head>
116 <meta charset="utf-8">
117 <title>Error response</title>
118 </head>
119 <body>
120 <h1>Error response</h1>
121 <p>Error code: %(code)d</p>
122 <p>Message: %(message)s.</p>
123 <p>Error code explanation: %(code)s - %(explain)s.</p>
124 </body>
125 </html>
126 """
127
128 DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
129
130 # Data larger than this will be read in chunks, to prevent extreme
131 # overallocation.
132 _MIN_READ_BUF_SIZE = 1 << 20
133
134 class HTTPServer(socketserver.TCPServer):
135
136 allow_reuse_address = 1 # Seems to make sense in testing environment
137
138 def server_bind(self):
139 """Override server_bind to store the server name."""
140 socketserver.TCPServer.server_bind(self)
141 host, port = self.server_address[:2]
142 self.server_name = socket.getfqdn(host)
143 self.server_port = port
144
145
146 class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
147 daemon_threads = True
148
149
150 class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
151
152 """HTTP request handler base class.
153
154 The following explanation of HTTP serves to guide you through the
155 code as well as to expose any misunderstandings I may have about
156 HTTP (so you don't need to read the code to figure out I'm wrong
157 :-).
158
159 HTTP (HyperText Transfer Protocol) is an extensible protocol on
160 top of a reliable stream transport (e.g. TCP/IP). The protocol
161 recognizes three parts to a request:
162
163 1. One line identifying the request type and path
164 2. An optional set of RFC-822-style headers
165 3. An optional data part
166
167 The headers and data are separated by a blank line.
168
169 The first line of the request has the form
170
171 <command> <path> <version>
172
173 where <command> is a (case-sensitive) keyword such as GET or POST,
174 <path> is a string containing path information for the request,
175 and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
176 <path> is encoded using the URL encoding scheme (using %xx to signify
177 the ASCII character with hex code xx).
178
179 The specification specifies that lines are separated by CRLF but
180 for compatibility with the widest range of clients recommends
181 servers also handle LF. Similarly, whitespace in the request line
182 is treated sensibly (allowing multiple spaces between components
183 and allowing trailing whitespace).
184
185 Similarly, for output, lines ought to be separated by CRLF pairs
186 but most clients grok LF characters just fine.
187
188 If the first line of the request has the form
189
190 <command> <path>
191
192 (i.e. <version> is left out) then this is assumed to be an HTTP
193 0.9 request; this form has no optional headers and data part and
194 the reply consists of just the data.
195
196 The reply form of the HTTP 1.x protocol again has three parts:
197
198 1. One line giving the response code
199 2. An optional set of RFC-822-style headers
200 3. The data
201
202 Again, the headers and data are separated by a blank line.
203
204 The response code line has the form
205
206 <version> <responsecode> <responsestring>
207
208 where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
209 <responsecode> is a 3-digit response code indicating success or
210 failure of the request, and <responsestring> is an optional
211 human-readable string explaining what the response code means.
212
213 This server parses the request and the headers, and then calls a
214 function specific to the request type (<command>). Specifically,
215 a request SPAM will be handled by a method do_SPAM(). If no
216 such method exists the server sends an error response to the
217 client. If it exists, it is called with no arguments:
218
219 do_SPAM()
220
221 Note that the request name is case sensitive (i.e. SPAM and spam
222 are different requests).
223
224 The various request details are stored in instance variables:
225
226 - client_address is the client IP address in the form (host,
227 port);
228
229 - command, path and version are the broken-down request line;
230
231 - headers is an instance of email.message.Message (or a derived
232 class) containing the header information;
233
234 - rfile is a file object open for reading positioned at the
235 start of the optional input data part;
236
237 - wfile is a file object open for writing.
238
239 IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
240
241 The first thing to be written must be the response line. Then
242 follow 0 or more header lines, then a blank line, and then the
243 actual data (if any). The meaning of the header lines depends on
244 the command executed by the server; in most cases, when data is
245 returned, there should be at least one header line of the form
246
247 Content-type: <type>/<subtype>
248
249 where <type> and <subtype> should be registered MIME types,
250 e.g. "text/html" or "text/plain".
251
252 """
253
254 # The Python system version, truncated to its first component.
255 sys_version = "Python/" + sys.version.split()[0]
256
257 # The server software version. You may want to override this.
258 # The format is multiple whitespace-separated strings,
259 # where each string is of the form name[/version].
260 server_version = "BaseHTTP/" + __version__
261
262 error_message_format = DEFAULT_ERROR_MESSAGE
263 error_content_type = DEFAULT_ERROR_CONTENT_TYPE
264
265 # The default request version. This only affects responses up until
266 # the point where the request line is parsed, so it mainly decides what
267 # the client gets back when sending a malformed request line.
268 # Most web servers default to HTTP 0.9, i.e. don't send a status line.
269 default_request_version = "HTTP/0.9"
270
271 def parse_request(self):
272 """Parse a request (internal).
273
274 The request should be stored in self.raw_requestline; the results
275 are in self.command, self.path, self.request_version and
276 self.headers.
277
278 Return True for success, False for failure; on failure, any relevant
279 error response has already been sent back.
280
281 """
282 is_http_0_9 = False
283 self.command = None # set in case of error on the first line
284 self.request_version = version = self.default_request_version
285 self.close_connection = True
286 requestline = str(self.raw_requestline, 'iso-8859-1')
287 requestline = requestline.rstrip('\r\n')
288 self.requestline = requestline
289 words = requestline.split()
290 if len(words) == 0:
291 return False
292
293 if len(words) >= 3: # Enough to determine protocol version
294 version = words[-1]
295 try:
296 if not version.startswith('HTTP/'):
297 raise ValueError
298 base_version_number = version.split('/', 1)[1]
299 version_number = base_version_number.split(".")
300 # RFC 2145 section 3.1 says there can be only one "." and
301 # - major and minor numbers MUST be treated as
302 # separate integers;
303 # - HTTP/2.4 is a lower version than HTTP/2.13, which in
304 # turn is lower than HTTP/12.3;
305 # - Leading zeros MUST be ignored by recipients.
306 if len(version_number) != 2:
307 raise ValueError
308 if any(not component.isdigit() for component in version_number):
309 raise ValueError("non digit in http version")
310 if any(len(component) > 10 for component in version_number):
311 raise ValueError("unreasonable length http version")
312 version_number = int(version_number[0]), int(version_number[1])
313 except (ValueError, IndexError):
314 self.send_error(
315 HTTPStatus.BAD_REQUEST,
316 "Bad request version (%r)" % version)
317 return False
318 if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
319 self.close_connection = False
320 if version_number >= (2, 0):
321 self.send_error(
322 HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
323 "Invalid HTTP version (%s)" % base_version_number)
324 return False
325 self.request_version = version
326
327 if not 2 <= len(words) <= 3:
328 self.send_error(
329 HTTPStatus.BAD_REQUEST,
330 "Bad request syntax (%r)" % requestline)
331 return False
332 command, path = words[:2]
333 if len(words) == 2:
334 self.close_connection = True
335 if command != 'GET':
336 self.send_error(
337 HTTPStatus.BAD_REQUEST,
338 "Bad HTTP/0.9 request type (%r)" % command)
339 return False
340 is_http_0_9 = True
341 self.command, self.path = command, path
342
343 # gh-87389: The purpose of replacing '//' with '/' is to protect
344 # against open redirect attacks possibly triggered if the path starts
345 # with '//' because http clients treat //path as an absolute URI
346 # without scheme (similar to http://path) rather than a path.
347 if self.path.startswith('//'):
348 self.path = '/' + self.path.lstrip('/') # Reduce to a single /
349
350 # For HTTP/0.9, headers are not expected at all.
351 if is_http_0_9:
352 self.headers = {}
353 return True
354
355 # Examine the headers and look for a Connection directive.
356 try:
357 self.headers = http.client.parse_headers(self.rfile,
358 _class=self.MessageClass)
359 except http.client.LineTooLong as err:
360 self.send_error(
361 HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
362 "Line too long",
363 str(err))
364 return False
365 except http.client.HTTPException as err:
366 self.send_error(
367 HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
368 "Too many headers",
369 str(err)
370 )
371 return False
372
373 conntype = self.headers.get('Connection', "")
374 if conntype.lower() == 'close':
375 self.close_connection = True
376 elif (conntype.lower() == 'keep-alive' and
377 self.protocol_version >= "HTTP/1.1"):
378 self.close_connection = False
379 # Examine the headers and look for an Expect directive
380 expect = self.headers.get('Expect', "")
381 if (expect.lower() == "100-continue" and
382 self.protocol_version >= "HTTP/1.1" and
383 self.request_version >= "HTTP/1.1"):
384 if not self.handle_expect_100():
385 return False
386 return True
387
388 def handle_expect_100(self):
389 """Decide what to do with an "Expect: 100-continue" header.
390
391 If the client is expecting a 100 Continue response, we must
392 respond with either a 100 Continue or a final response before
393 waiting for the request body. The default is to always respond
394 with a 100 Continue. You can behave differently (for example,
395 reject unauthorized requests) by overriding this method.
396
397 This method should either return True (possibly after sending
398 a 100 Continue response) or send an error response and return
399 False.
400
401 """
402 self.send_response_only(HTTPStatus.CONTINUE)
403 self.end_headers()
404 return True
405
406 def handle_one_request(self):
407 """Handle a single HTTP request.
408
409 You normally don't need to override this method; see the class
410 __doc__ string for information on how to handle specific HTTP
411 commands such as GET and POST.
412
413 """
414 try:
415 self.raw_requestline = self.rfile.readline(65537)
416 if len(self.raw_requestline) > 65536:
417 self.requestline = ''
418 self.request_version = ''
419 self.command = ''
420 self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
421 return
422 if not self.raw_requestline:
423 self.close_connection = True
424 return
425 if not self.parse_request():
426 # An error code has been sent, just exit
427 return
428 mname = 'do_' + self.command
429 if not hasattr(self, mname):
430 self.send_error(
431 HTTPStatus.NOT_IMPLEMENTED,
432 "Unsupported method (%r)" % self.command)
433 return
434 method = getattr(self, mname)
435 method()
436 self.wfile.flush() #actually send the response if not already done.
437 except TimeoutError as e:
438 #a read or a write timed out. Discard this connection
439 self.log_error("Request timed out: %r", e)
440 self.close_connection = True
441 return
442
443 def handle(self):
444 """Handle multiple requests if necessary."""
445 self.close_connection = True
446
447 self.handle_one_request()
448 while not self.close_connection:
449 self.handle_one_request()
450
451 def send_error(self, code, message=None, explain=None):
452 """Send and log an error reply.
453
454 Arguments are
455 * code: an HTTP error code
456 3 digits
457 * message: a simple optional 1 line reason phrase.
458 *( HTAB / SP / VCHAR / %x80-FF )
459 defaults to short entry matching the response code
460 * explain: a detailed message defaults to the long entry
461 matching the response code.
462
463 This sends an error response (so it must be called before any
464 output has been generated), logs the error, and finally sends
465 a piece of HTML explaining the error to the user.
466
467 """
468
469 try:
470 shortmsg, longmsg = self.responses[code]
471 except KeyError:
472 shortmsg, longmsg = '???', '???'
473 if message is None:
474 message = shortmsg
475 if explain is None:
476 explain = longmsg
477 self.log_error("code %d, message %s", code, message)
478 self.send_response(code, message)
479 self.send_header('Connection', 'close')
480
481 # Message body is omitted for cases described in:
482 # - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
483 # - RFC7231: 6.3.6. 205(Reset Content)
484 body = None
485 if (code >= 200 and
486 code not in (HTTPStatus.NO_CONTENT,
487 HTTPStatus.RESET_CONTENT,
488 HTTPStatus.NOT_MODIFIED)):
489 # HTML encode to prevent Cross Site Scripting attacks
490 # (see bug #1100201)
491 content = (self.error_message_format % {
492 'code': code,
493 'message': html.escape(message, quote=False),
494 'explain': html.escape(explain, quote=False)
495 })
496 body = content.encode('UTF-8', 'replace')
497 self.send_header("Content-Type", self.error_content_type)
498 self.send_header('Content-Length', str(len(body)))
499 self.end_headers()
500
501 if self.command != 'HEAD' and body:
502 self.wfile.write(body)
503
504 def send_response(self, code, message=None):
505 """Add the response header to the headers buffer and log the
506 response code.
507
508 Also send two standard headers with the server software
509 version and the current date.
510
511 """
512 self.log_request(code)
513 self.send_response_only(code, message)
514 self.send_header('Server', self.version_string())
515 self.send_header('Date', self.date_time_string())
516
517 def send_response_only(self, code, message=None):
518 """Send the response header only."""
519 if self.request_version != 'HTTP/0.9':
520 if message is None:
521 if code in self.responses:
522 message = self.responses[code][0]
523 else:
524 message = ''
525 if not hasattr(self, '_headers_buffer'):
526 self._headers_buffer = []
527 self._headers_buffer.append(("%s %d %s\r\n" %
528 (self.protocol_version, code, message)).encode(
529 'latin-1', 'strict'))
530
531 def send_header(self, keyword, value):
532 """Send a MIME header to the headers buffer."""
533 if self.request_version != 'HTTP/0.9':
534 if not hasattr(self, '_headers_buffer'):
535 self._headers_buffer = []
536 self._headers_buffer.append(
537 ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
538
539 if keyword.lower() == 'connection':
540 if value.lower() == 'close':
541 self.close_connection = True
542 elif value.lower() == 'keep-alive':
543 self.close_connection = False
544
545 def end_headers(self):
546 """Send the blank line ending the MIME headers."""
547 if self.request_version != 'HTTP/0.9':
548 self._headers_buffer.append(b"\r\n")
549 self.flush_headers()
550
551 def flush_headers(self):
552 if hasattr(self, '_headers_buffer'):
553 self.wfile.write(b"".join(self._headers_buffer))
554 self._headers_buffer = []
555
556 def log_request(self, code='-', size='-'):
557 """Log an accepted request.
558
559 This is called by send_response().
560
561 """
562 if isinstance(code, HTTPStatus):
563 code = code.value
564 self.log_message('"%s" %s %s',
565 self.requestline, str(code), str(size))
566
567 def log_error(self, format, *args):
568 """Log an error.
569
570 This is called when a request cannot be fulfilled. By
571 default it passes the message on to log_message().
572
573 Arguments are the same as for log_message().
574
575 XXX This should go to the separate error log.
576
577 """
578
579 self.log_message(format, *args)
580
581 # https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes
582 _control_char_table = str.maketrans(
583 {c: fr'\x{c:02x}' for c in itertools.chain(range(0x20), range(0x7f,0xa0))})
584 _control_char_table[ord('\\')] = r'\\'
585
586 def log_message(self, format, *args):
587 """Log an arbitrary message.
588
589 This is used by all other logging functions. Override
590 it if you have specific logging wishes.
591
592 The first argument, FORMAT, is a format string for the
593 message to be logged. If the format string contains
594 any % escapes requiring parameters, they should be
595 specified as subsequent arguments (it's just like
596 printf!).
597
598 The client ip and current date/time are prefixed to
599 every message.
600
601 Unicode control characters are replaced with escaped hex
602 before writing the output to stderr.
603
604 """
605
606 message = format % args
607 sys.stderr.write("%s - - [%s] %s\n" %
608 (self.address_string(),
609 self.log_date_time_string(),
610 message.translate(self._control_char_table)))
611
612 def version_string(self):
613 """Return the server software version string."""
614 return self.server_version + ' ' + self.sys_version
615
616 def date_time_string(self, timestamp=None):
617 """Return the current date and time formatted for a message header."""
618 if timestamp is None:
619 timestamp = time.time()
620 return email.utils.formatdate(timestamp, usegmt=True)
621
622 def log_date_time_string(self):
623 """Return the current time formatted for logging."""
624 now = time.time()
625 year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
626 s = "%02d/%3s/%04d %02d:%02d:%02d" % (
627 day, self.monthname[month], year, hh, mm, ss)
628 return s
629
630 weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
631
632 monthname = [None,
633 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
634 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
635
636 def address_string(self):
637 """Return the client address."""
638
639 return self.client_address[0]
640
641 # Essentially static class variables
642
643 # The version of the HTTP protocol we support.
644 # Set this to HTTP/1.1 to enable automatic keepalive
645 protocol_version = "HTTP/1.0"
646
647 # MessageClass used to parse headers
648 MessageClass = http.client.HTTPMessage
649
650 # hack to maintain backwards compatibility
651 responses = {
652 v: (v.phrase, v.description)
653 for v in HTTPStatus.__members__.values()
654 }
655
656
657 class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
658
659 """Simple HTTP request handler with GET and HEAD commands.
660
661 This serves files from the current directory and any of its
662 subdirectories. The MIME type for files is determined by
663 calling the .guess_type() method.
664
665 The GET and HEAD requests are identical except that the HEAD
666 request omits the actual contents of the file.
667
668 """
669
670 server_version = "SimpleHTTP/" + __version__
671 index_pages = ("index.html", "index.htm")
672 extensions_map = _encodings_map_default = {
673 '.gz': 'application/gzip',
674 '.Z': 'application/octet-stream',
675 '.bz2': 'application/x-bzip2',
676 '.xz': 'application/x-xz',
677 }
678
679 def __init__(self, *args, directory=None, **kwargs):
680 if directory is None:
681 directory = os.getcwd()
682 self.directory = os.fspath(directory)
683 super().__init__(*args, **kwargs)
684
685 def do_GET(self):
686 """Serve a GET request."""
687 f = self.send_head()
688 if f:
689 try:
690 self.copyfile(f, self.wfile)
691 finally:
692 f.close()
693
694 def do_HEAD(self):
695 """Serve a HEAD request."""
696 f = self.send_head()
697 if f:
698 f.close()
699
700 def send_head(self):
701 """Common code for GET and HEAD commands.
702
703 This sends the response code and MIME headers.
704
705 Return value is either a file object (which has to be copied
706 to the outputfile by the caller unless the command was HEAD,
707 and must be closed by the caller under all circumstances), or
708 None, in which case the caller has nothing further to do.
709
710 """
711 path = self.translate_path(self.path)
712 f = None
713 if os.path.isdir(path):
714 parts = urllib.parse.urlsplit(self.path)
715 if not parts.path.endswith(('/', '%2f', '%2F')):
716 # redirect browser - doing basically what apache does
717 self.send_response(HTTPStatus.MOVED_PERMANENTLY)
718 new_parts = (parts[0], parts[1], parts[2] + '/',
719 parts[3], parts[4])
720 new_url = urllib.parse.urlunsplit(new_parts)
721 self.send_header("Location", new_url)
722 self.send_header("Content-Length", "0")
723 self.end_headers()
724 return None
725 for index in self.index_pages:
726 index = os.path.join(path, index)
727 if os.path.isfile(index):
728 path = index
729 break
730 else:
731 return self.list_directory(path)
732 ctype = self.guess_type(path)
733 # check for trailing "/" which should return 404. See Issue17324
734 # The test for this was added in test_httpserver.py
735 # However, some OS platforms accept a trailingSlash as a filename
736 # See discussion on python-dev and Issue34711 regarding
737 # parsing and rejection of filenames with a trailing slash
738 if path.endswith("/"):
739 self.send_error(HTTPStatus.NOT_FOUND, "File not found")
740 return None
741 try:
742 f = open(path, 'rb')
743 except OSError:
744 self.send_error(HTTPStatus.NOT_FOUND, "File not found")
745 return None
746
747 try:
748 fs = os.fstat(f.fileno())
749 # Use browser cache if possible
750 if ("If-Modified-Since" in self.headers
751 and "If-None-Match" not in self.headers):
752 # compare If-Modified-Since and time of last file modification
753 try:
754 ims = email.utils.parsedate_to_datetime(
755 self.headers["If-Modified-Since"])
756 except (TypeError, IndexError, OverflowError, ValueError):
757 # ignore ill-formed values
758 pass
759 else:
760 if ims.tzinfo is None:
761 # obsolete format with no timezone, cf.
762 # https://tools.ietf.org/html/rfc7231#section-7.1.1.1
763 ims = ims.replace(tzinfo=datetime.timezone.utc)
764 if ims.tzinfo is datetime.timezone.utc:
765 # compare to UTC datetime of last modification
766 last_modif = datetime.datetime.fromtimestamp(
767 fs.st_mtime, datetime.timezone.utc)
768 # remove microseconds, like in If-Modified-Since
769 last_modif = last_modif.replace(microsecond=0)
770
771 if last_modif <= ims:
772 self.send_response(HTTPStatus.NOT_MODIFIED)
773 self.end_headers()
774 f.close()
775 return None
776
777 self.send_response(HTTPStatus.OK)
778 self.send_header("Content-type", ctype)
779 self.send_header("Content-Length", str(fs[6]))
780 self.send_header("Last-Modified",
781 self.date_time_string(fs.st_mtime))
782 self.end_headers()
783 return f
784 except:
785 f.close()
786 raise
787
788 def list_directory(self, path):
789 """Helper to produce a directory listing (absent index.html).
790
791 Return value is either a file object, or None (indicating an
792 error). In either case, the headers are sent, making the
793 interface the same as for send_head().
794
795 """
796 try:
797 list = os.listdir(path)
798 except OSError:
799 self.send_error(
800 HTTPStatus.NOT_FOUND,
801 "No permission to list directory")
802 return None
803 list.sort(key=lambda a: a.lower())
804 r = []
805 displaypath = self.path
806 displaypath = displaypath.split('#', 1)[0]
807 displaypath = displaypath.split('?', 1)[0]
808 try:
809 displaypath = urllib.parse.unquote(displaypath,
810 errors='surrogatepass')
811 except UnicodeDecodeError:
812 displaypath = urllib.parse.unquote(displaypath)
813 displaypath = html.escape(displaypath, quote=False)
814 enc = sys.getfilesystemencoding()
815 title = f'Directory listing for {displaypath}'
816 r.append('<!DOCTYPE HTML>')
817 r.append('<html lang="en">')
818 r.append('<head>')
819 r.append(f'<meta charset="{enc}">')
820 r.append(f'<title>{title}</title>\n</head>')
821 r.append(f'<body>\n<h1>{title}</h1>')
822 r.append('<hr>\n<ul>')
823 for name in list:
824 fullname = os.path.join(path, name)
825 displayname = linkname = name
826 # Append / for directories or @ for symbolic links
827 if os.path.isdir(fullname):
828 displayname = name + "/"
829 linkname = name + "/"
830 if os.path.islink(fullname):
831 displayname = name + "@"
832 # Note: a link to a directory displays with @ and links with /
833 r.append('<li><a href="%s">%s</a></li>'
834 % (urllib.parse.quote(linkname,
835 errors='surrogatepass'),
836 html.escape(displayname, quote=False)))
837 r.append('</ul>\n<hr>\n</body>\n</html>\n')
838 encoded = '\n'.join(r).encode(enc, 'surrogateescape')
839 f = io.BytesIO()
840 f.write(encoded)
841 f.seek(0)
842 self.send_response(HTTPStatus.OK)
843 self.send_header("Content-type", "text/html; charset=%s" % enc)
844 self.send_header("Content-Length", str(len(encoded)))
845 self.end_headers()
846 return f
847
848 def translate_path(self, path):
849 """Translate a /-separated PATH to the local filename syntax.
850
851 Components that mean special things to the local file system
852 (e.g. drive or directory names) are ignored. (XXX They should
853 probably be diagnosed.)
854
855 """
856 # abandon query parameters
857 path = path.split('#', 1)[0]
858 path = path.split('?', 1)[0]
859 # Don't forget explicit trailing slash when normalizing. Issue17324
860 try:
861 path = urllib.parse.unquote(path, errors='surrogatepass')
862 except UnicodeDecodeError:
863 path = urllib.parse.unquote(path)
864 trailing_slash = path.endswith('/')
865 path = posixpath.normpath(path)
866 words = path.split('/')
867 words = filter(None, words)
868 path = self.directory
869 for word in words:
870 if os.path.dirname(word) or word in (os.curdir, os.pardir):
871 # Ignore components that are not a simple file/directory name
872 continue
873 path = os.path.join(path, word)
874 if trailing_slash:
875 path += '/'
876 return path
877
878 def copyfile(self, source, outputfile):
879 """Copy all data between two file objects.
880
881 The SOURCE argument is a file object open for reading
882 (or anything with a read() method) and the DESTINATION
883 argument is a file object open for writing (or
884 anything with a write() method).
885
886 The only reason for overriding this would be to change
887 the block size or perhaps to replace newlines by CRLF
888 -- note however that this the default server uses this
889 to copy binary data as well.
890
891 """
892 shutil.copyfileobj(source, outputfile)
893
894 def guess_type(self, path):
895 """Guess the type of a file.
896
897 Argument is a PATH (a filename).
898
899 Return value is a string of the form type/subtype,
900 usable for a MIME Content-type header.
901
902 The default implementation looks the file's extension
903 up in the table self.extensions_map, using application/octet-stream
904 as a default; however it would be permissible (if
905 slow) to look inside the data to make a better guess.
906
907 """
908 base, ext = posixpath.splitext(path)
909 if ext in self.extensions_map:
910 return self.extensions_map[ext]
911 ext = ext.lower()
912 if ext in self.extensions_map:
913 return self.extensions_map[ext]
914 guess, _ = mimetypes.guess_file_type(path)
915 if guess:
916 return guess
917 return 'application/octet-stream'
918
919
920 # Utilities for CGIHTTPRequestHandler
921
922 def _url_collapse_path(path):
923 """
924 Given a URL path, remove extra '/'s and '.' path elements and collapse
925 any '..' references and returns a collapsed path.
926
927 Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
928 The utility of this function is limited to is_cgi method and helps
929 preventing some security attacks.
930
931 Returns: The reconstituted URL, which will always start with a '/'.
932
933 Raises: IndexError if too many '..' occur within the path.
934
935 """
936 # Query component should not be involved.
937 path, _, query = path.partition('?')
938 path = urllib.parse.unquote(path)
939
940 # Similar to os.path.split(os.path.normpath(path)) but specific to URL
941 # path semantics rather than local operating system semantics.
942 path_parts = path.split('/')
943 head_parts = []
944 for part in path_parts[:-1]:
945 if part == '..':
946 head_parts.pop() # IndexError if more '..' than prior parts
947 elif part and part != '.':
948 head_parts.append( part )
949 if path_parts:
950 tail_part = path_parts.pop()
951 if tail_part:
952 if tail_part == '..':
953 head_parts.pop()
954 tail_part = ''
955 elif tail_part == '.':
956 tail_part = ''
957 else:
958 tail_part = ''
959
960 if query:
961 tail_part = '?'.join((tail_part, query))
962
963 splitpath = ('/' + '/'.join(head_parts), tail_part)
964 collapsed_path = "/".join(splitpath)
965
966 return collapsed_path
967
968
969
970 nobody = None
971
972 def nobody_uid():
973 """Internal routine to get nobody's uid"""
974 global nobody
975 if nobody:
976 return nobody
977 try:
978 import pwd
979 except ImportError:
980 return -1
981 try:
982 nobody = pwd.getpwnam('nobody')[2]
983 except KeyError:
984 nobody = 1 + max(x[2] for x in pwd.getpwall())
985 return nobody
986
987
988 def executable(path):
989 """Test for executable file."""
990 return os.access(path, os.X_OK)
991
992
993 class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
994
995 """Complete HTTP server with GET, HEAD and POST commands.
996
997 GET and HEAD also support running CGI scripts.
998
999 The POST command is *only* implemented for CGI scripts.
1000
1001 """
1002
1003 def __init__(self, *args, **kwargs):
1004 import warnings
1005 warnings._deprecated("http.server.CGIHTTPRequestHandler",
1006 remove=(3, 15))
1007 super().__init__(*args, **kwargs)
1008
1009 # Determine platform specifics
1010 have_fork = hasattr(os, 'fork')
1011
1012 # Make rfile unbuffered -- we need to read one line and then pass
1013 # the rest to a subprocess, so we can't use buffered input.
1014 rbufsize = 0
1015
1016 def do_POST(self):
1017 """Serve a POST request.
1018
1019 This is only implemented for CGI scripts.
1020
1021 """
1022
1023 if self.is_cgi():
1024 self.run_cgi()
1025 else:
1026 self.send_error(
1027 HTTPStatus.NOT_IMPLEMENTED,
1028 "Can only POST to CGI scripts")
1029
1030 def send_head(self):
1031 """Version of send_head that support CGI scripts"""
1032 if self.is_cgi():
1033 return self.run_cgi()
1034 else:
1035 return SimpleHTTPRequestHandler.send_head(self)
1036
1037 def is_cgi(self):
1038 """Test whether self.path corresponds to a CGI script.
1039
1040 Returns True and updates the cgi_info attribute to the tuple
1041 (dir, rest) if self.path requires running a CGI script.
1042 Returns False otherwise.
1043
1044 If any exception is raised, the caller should assume that
1045 self.path was rejected as invalid and act accordingly.
1046
1047 The default implementation tests whether the normalized url
1048 path begins with one of the strings in self.cgi_directories
1049 (and the next character is a '/' or the end of the string).
1050
1051 """
1052 collapsed_path = _url_collapse_path(self.path)
1053 dir_sep = collapsed_path.find('/', 1)
1054 while dir_sep > 0 and not collapsed_path[:dir_sep] in self.cgi_directories:
1055 dir_sep = collapsed_path.find('/', dir_sep+1)
1056 if dir_sep > 0:
1057 head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
1058 self.cgi_info = head, tail
1059 return True
1060 return False
1061
1062
1063 cgi_directories = ['/cgi-bin', '/htbin']
1064
1065 def is_executable(self, path):
1066 """Test whether argument path is an executable file."""
1067 return executable(path)
1068
1069 def is_python(self, path):
1070 """Test whether argument path is a Python script."""
1071 head, tail = os.path.splitext(path)
1072 return tail.lower() in (".py", ".pyw")
1073
1074 def run_cgi(self):
1075 """Execute a CGI script."""
1076 dir, rest = self.cgi_info
1077 path = dir + '/' + rest
1078 i = path.find('/', len(dir)+1)
1079 while i >= 0:
1080 nextdir = path[:i]
1081 nextrest = path[i+1:]
1082
1083 scriptdir = self.translate_path(nextdir)
1084 if os.path.isdir(scriptdir):
1085 dir, rest = nextdir, nextrest
1086 i = path.find('/', len(dir)+1)
1087 else:
1088 break
1089
1090 # find an explicit query string, if present.
1091 rest, _, query = rest.partition('?')
1092
1093 # dissect the part after the directory name into a script name &
1094 # a possible additional path, to be stored in PATH_INFO.
1095 i = rest.find('/')
1096 if i >= 0:
1097 script, rest = rest[:i], rest[i:]
1098 else:
1099 script, rest = rest, ''
1100
1101 scriptname = dir + '/' + script
1102 scriptfile = self.translate_path(scriptname)
1103 if not os.path.exists(scriptfile):
1104 self.send_error(
1105 HTTPStatus.NOT_FOUND,
1106 "No such CGI script (%r)" % scriptname)
1107 return
1108 if not os.path.isfile(scriptfile):
1109 self.send_error(
1110 HTTPStatus.FORBIDDEN,
1111 "CGI script is not a plain file (%r)" % scriptname)
1112 return
1113 ispy = self.is_python(scriptname)
1114 if self.have_fork or not ispy:
1115 if not self.is_executable(scriptfile):
1116 self.send_error(
1117 HTTPStatus.FORBIDDEN,
1118 "CGI script is not executable (%r)" % scriptname)
1119 return
1120
1121 # Reference: https://www6.uniovi.es/~antonio/ncsa_httpd/cgi/env.html
1122 # XXX Much of the following could be prepared ahead of time!
1123 env = copy.deepcopy(os.environ)
1124 env['SERVER_SOFTWARE'] = self.version_string()
1125 env['SERVER_NAME'] = self.server.server_name
1126 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
1127 env['SERVER_PROTOCOL'] = self.protocol_version
1128 env['SERVER_PORT'] = str(self.server.server_port)
1129 env['REQUEST_METHOD'] = self.command
1130 uqrest = urllib.parse.unquote(rest)
1131 env['PATH_INFO'] = uqrest
1132 env['PATH_TRANSLATED'] = self.translate_path(uqrest)
1133 env['SCRIPT_NAME'] = scriptname
1134 env['QUERY_STRING'] = query
1135 env['REMOTE_ADDR'] = self.client_address[0]
1136 authorization = self.headers.get("authorization")
1137 if authorization:
1138 authorization = authorization.split()
1139 if len(authorization) == 2:
1140 import base64, binascii
1141 env['AUTH_TYPE'] = authorization[0]
1142 if authorization[0].lower() == "basic":
1143 try:
1144 authorization = authorization[1].encode('ascii')
1145 authorization = base64.decodebytes(authorization).\
1146 decode('ascii')
1147 except (binascii.Error, UnicodeError):
1148 pass
1149 else:
1150 authorization = authorization.split(':')
1151 if len(authorization) == 2:
1152 env['REMOTE_USER'] = authorization[0]
1153 # XXX REMOTE_IDENT
1154 if self.headers.get('content-type') is None:
1155 env['CONTENT_TYPE'] = self.headers.get_content_type()
1156 else:
1157 env['CONTENT_TYPE'] = self.headers['content-type']
1158 length = self.headers.get('content-length')
1159 if length:
1160 env['CONTENT_LENGTH'] = length
1161 referer = self.headers.get('referer')
1162 if referer:
1163 env['HTTP_REFERER'] = referer
1164 accept = self.headers.get_all('accept', ())
1165 env['HTTP_ACCEPT'] = ','.join(accept)
1166 ua = self.headers.get('user-agent')
1167 if ua:
1168 env['HTTP_USER_AGENT'] = ua
1169 co = filter(None, self.headers.get_all('cookie', []))
1170 cookie_str = ', '.join(co)
1171 if cookie_str:
1172 env['HTTP_COOKIE'] = cookie_str
1173 # XXX Other HTTP_* headers
1174 # Since we're setting the env in the parent, provide empty
1175 # values to override previously set values
1176 for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
1177 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
1178 env.setdefault(k, "")
1179
1180 self.send_response(HTTPStatus.OK, "Script output follows")
1181 self.flush_headers()
1182
1183 decoded_query = query.replace('+', ' ')
1184
1185 if self.have_fork:
1186 # Unix -- fork as we should
1187 args = [script]
1188 if '=' not in decoded_query:
1189 args.append(decoded_query)
1190 nobody = nobody_uid()
1191 self.wfile.flush() # Always flush before forking
1192 pid = os.fork()
1193 if pid != 0:
1194 # Parent
1195 pid, sts = os.waitpid(pid, 0)
1196 # throw away additional data [see bug #427345]
1197 while select.select([self.rfile], [], [], 0)[0]:
1198 if not self.rfile.read(1):
1199 break
1200 exitcode = os.waitstatus_to_exitcode(sts)
1201 if exitcode:
1202 self.log_error(f"CGI script exit code {exitcode}")
1203 return
1204 # Child
1205 try:
1206 try:
1207 os.setuid(nobody)
1208 except OSError:
1209 pass
1210 os.dup2(self.rfile.fileno(), 0)
1211 os.dup2(self.wfile.fileno(), 1)
1212 os.execve(scriptfile, args, env)
1213 except:
1214 self.server.handle_error(self.request, self.client_address)
1215 os._exit(127)
1216
1217 else:
1218 # Non-Unix -- use subprocess
1219 import subprocess
1220 cmdline = [scriptfile]
1221 if self.is_python(scriptfile):
1222 interp = sys.executable
1223 if interp.lower().endswith("w.exe"):
1224 # On Windows, use python.exe, not pythonw.exe
1225 interp = interp[:-5] + interp[-4:]
1226 cmdline = [interp, '-u'] + cmdline
1227 if '=' not in query:
1228 cmdline.append(query)
1229 self.log_message("command: %s", subprocess.list2cmdline(cmdline))
1230 try:
1231 nbytes = int(length)
1232 except (TypeError, ValueError):
1233 nbytes = 0
1234 p = subprocess.Popen(cmdline,
1235 stdin=subprocess.PIPE,
1236 stdout=subprocess.PIPE,
1237 stderr=subprocess.PIPE,
1238 env = env
1239 )
1240 if self.command.lower() == "post" and nbytes > 0:
1241 cursize = 0
1242 data = self.rfile.read(min(nbytes, _MIN_READ_BUF_SIZE))
1243 while len(data) < nbytes and len(data) != cursize:
1244 cursize = len(data)
1245 # This is a geometric increase in read size (never more
1246 # than doubling out the current length of data per loop
1247 # iteration).
1248 delta = min(cursize, nbytes - cursize)
1249 try:
1250 data += self.rfile.read(delta)
1251 except TimeoutError:
1252 break
1253 else:
1254 data = None
1255 # throw away additional data [see bug #427345]
1256 while select.select([self.rfile._sock], [], [], 0)[0]:
1257 if not self.rfile._sock.recv(1):
1258 break
1259 stdout, stderr = p.communicate(data)
1260 self.wfile.write(stdout)
1261 if stderr:
1262 self.log_error('%s', stderr)
1263 p.stderr.close()
1264 p.stdout.close()
1265 status = p.returncode
1266 if status:
1267 self.log_error("CGI script exit status %#x", status)
1268 else:
1269 self.log_message("CGI script exited OK")
1270
1271
1272 def _get_best_family(*address):
1273 infos = socket.getaddrinfo(
1274 *address,
1275 type=socket.SOCK_STREAM,
1276 flags=socket.AI_PASSIVE,
1277 )
1278 family, type, proto, canonname, sockaddr = next(iter(infos))
1279 return family, sockaddr
1280
1281
1282 def test(HandlerClass=BaseHTTPRequestHandler,
1283 ServerClass=ThreadingHTTPServer,
1284 protocol="HTTP/1.0", port=8000, bind=None):
1285 """Test the HTTP request handler class.
1286
1287 This runs an HTTP server on port 8000 (or the port argument).
1288
1289 """
1290 ServerClass.address_family, addr = _get_best_family(bind, port)
1291 HandlerClass.protocol_version = protocol
1292 with ServerClass(addr, HandlerClass) as httpd:
1293 host, port = httpd.socket.getsockname()[:2]
1294 url_host = f'[{host}]' if ':' in host else host
1295 print(
1296 f"Serving HTTP on {host} port {port} "
1297 f"(http://{url_host}:{port}/) ..."
1298 )
1299 try:
1300 httpd.serve_forever()
1301 except KeyboardInterrupt:
1302 print("\nKeyboard interrupt received, exiting.")
1303 sys.exit(0)
1304
1305 if __name__ == '__main__':
1306 import argparse
1307 import contextlib
1308
1309 parser = argparse.ArgumentParser()
1310 parser.add_argument('--cgi', action='store_true',
1311 help='run as CGI server')
1312 parser.add_argument('-b', '--bind', metavar='ADDRESS',
1313 help='bind to this address '
1314 '(default: all interfaces)')
1315 parser.add_argument('-d', '--directory', default=os.getcwd(),
1316 help='serve this directory '
1317 '(default: current directory)')
1318 parser.add_argument('-p', '--protocol', metavar='VERSION',
1319 default='HTTP/1.0',
1320 help='conform to this HTTP version '
1321 '(default: %(default)s)')
1322 parser.add_argument('port', default=8000, type=int, nargs='?',
1323 help='bind to this port '
1324 '(default: %(default)s)')
1325 args = parser.parse_args()
1326 if args.cgi:
1327 handler_class = CGIHTTPRequestHandler
1328 else:
1329 handler_class = SimpleHTTPRequestHandler
1330
1331 # ensure dual-stack is not disabled; ref #38907
1332 class DualStackServer(ThreadingHTTPServer):
1333
1334 def server_bind(self):
1335 # suppress exception when protocol is IPv4
1336 with contextlib.suppress(Exception):
1337 self.socket.setsockopt(
1338 socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
1339 return super().server_bind()
1340
1341 def finish_request(self, request, client_address):
1342 self.RequestHandlerClass(request, client_address, self,
1343 directory=args.directory)
1344
1345 test(
1346 HandlerClass=handler_class,
1347 ServerClass=DualStackServer,
1348 port=args.port,
1349 bind=args.bind,
1350 protocol=args.protocol,
1351 )