Debian Codegraph @

lib-python/3/http/server.py

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