2008-05-26 13:32:26 -03:00
|
|
|
"""HTTP server classes.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
|
|
|
|
SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
|
2023-09-15 18:26:45 -03:00
|
|
|
and (deprecated) CGIHTTPRequestHandler for CGI scripts.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2023-09-15 18:26:45 -03:00
|
|
|
It does, however, optionally implement HTTP/1.1 persistent connections.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
Notes on CGIHTTPRequestHandler
|
|
|
|
------------------------------
|
|
|
|
|
2023-09-15 18:26:45 -03:00
|
|
|
This class is deprecated. It implements GET and POST requests to cgi-bin scripts.
|
2008-05-26 13:32:26 -03:00
|
|
|
|
2023-09-15 18:26:45 -03:00
|
|
|
If the os.fork() function is not present (Windows), subprocess.Popen() is used,
|
|
|
|
with slightly altered but never documented semantics. Use from a threaded
|
|
|
|
process is likely to trigger a warning at os.fork() time.
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
In all cases, the implementation is intentionally naive -- all
|
|
|
|
requests are executed synchronously.
|
|
|
|
|
|
|
|
SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
|
|
|
|
-- it may execute arbitrary Python code or external programs.
|
|
|
|
|
|
|
|
Note that status code 200 is sent prior to execution of a CGI script, so
|
|
|
|
scripts cannot send other status codes such as 302 (redirect).
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
XXX To do:
|
|
|
|
|
|
|
|
- log requests even later (to capture byte count)
|
|
|
|
- log user-agent header and other interesting goodies
|
|
|
|
- send error log to separate file
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
# See also:
|
|
|
|
#
|
|
|
|
# HTTP Working Group T. Berners-Lee
|
|
|
|
# INTERNET-DRAFT R. T. Fielding
|
|
|
|
# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
|
|
|
|
# Expires September 8, 1995 March 8, 1995
|
|
|
|
#
|
|
|
|
# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
|
2002-03-17 14:37:22 -04:00
|
|
|
#
|
|
|
|
# and
|
|
|
|
#
|
|
|
|
# Network Working Group R. Fielding
|
|
|
|
# Request for Comments: 2616 et al
|
|
|
|
# Obsoletes: 2068 June 1999
|
2002-04-15 22:38:40 -03:00
|
|
|
# Category: Standards Track
|
2002-03-17 14:37:22 -04:00
|
|
|
#
|
|
|
|
# URL: http://www.faqs.org/rfcs/rfc2616.html
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
# Log files
|
|
|
|
# ---------
|
2001-01-14 17:54:20 -04:00
|
|
|
#
|
1995-08-04 01:00:20 -03:00
|
|
|
# Here's a quote from the NCSA httpd docs about log file format.
|
2001-01-14 17:54:20 -04:00
|
|
|
#
|
|
|
|
# | The logfile format is as follows. Each line consists of:
|
|
|
|
# |
|
|
|
|
# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
|
|
|
|
# |
|
|
|
|
# | host: Either the DNS name or the IP number of the remote client
|
1995-08-04 01:00:20 -03:00
|
|
|
# | rfc931: Any information returned by identd for this person,
|
2001-01-14 17:54:20 -04:00
|
|
|
# | - otherwise.
|
1995-08-04 01:00:20 -03:00
|
|
|
# | authuser: If user sent a userid for authentication, the user name,
|
2001-01-14 17:54:20 -04:00
|
|
|
# | - otherwise.
|
|
|
|
# | DD: Day
|
|
|
|
# | Mon: Month (calendar name)
|
|
|
|
# | YYYY: Year
|
|
|
|
# | hh: hour (24-hour format, the machine's timezone)
|
|
|
|
# | mm: minutes
|
|
|
|
# | ss: seconds
|
|
|
|
# | request: The first line of the HTTP request as sent by the client.
|
|
|
|
# | ddd: the status code returned by the server, - if not available.
|
1995-08-04 01:00:20 -03:00
|
|
|
# | bbbb: the total number of bytes sent,
|
2001-01-14 17:54:20 -04:00
|
|
|
# | *not including the HTTP/1.0 header*, - if not available
|
|
|
|
# |
|
1995-08-04 01:00:20 -03:00
|
|
|
# | You can determine the name of the file accessed through request.
|
2001-01-14 17:54:20 -04:00
|
|
|
#
|
1995-08-04 01:00:20 -03:00
|
|
|
# (Actually, the latter is only true if you know the server configuration
|
|
|
|
# at the time the request was made!)
|
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
__version__ = "0.6"
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2015-02-13 14:48:15 -04:00
|
|
|
__all__ = [
|
2018-05-29 17:10:30 -03:00
|
|
|
"HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler",
|
2015-02-13 14:48:15 -04:00
|
|
|
"SimpleHTTPRequestHandler", "CGIHTTPRequestHandler",
|
|
|
|
]
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2017-04-02 07:26:12 -03:00
|
|
|
import copy
|
|
|
|
import datetime
|
2016-03-14 01:06:03 -03:00
|
|
|
import email.utils
|
2010-10-15 12:57:45 -03:00
|
|
|
import html
|
2009-03-27 14:14:18 -03:00
|
|
|
import http.client
|
2009-03-27 14:16:06 -03:00
|
|
|
import io
|
2022-12-05 16:55:45 -04:00
|
|
|
import itertools
|
2008-05-26 13:32:26 -03:00
|
|
|
import mimetypes
|
2009-03-27 14:16:06 -03:00
|
|
|
import os
|
2008-05-26 13:32:26 -03:00
|
|
|
import posixpath
|
2009-03-27 14:16:06 -03:00
|
|
|
import select
|
|
|
|
import shutil
|
|
|
|
import socket # For gethostbyaddr()
|
2008-05-11 23:31:37 -03:00
|
|
|
import socketserver
|
2009-03-27 14:16:06 -03:00
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import urllib.parse
|
2012-06-03 05:15:54 -03:00
|
|
|
|
2014-12-23 10:28:28 -04:00
|
|
|
from http import HTTPStatus
|
|
|
|
|
1995-08-04 01:00:20 -03:00
|
|
|
|
Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900,60902-60906,60908,60911-60917,60919-60920,60922,60926,60929-60931,60933-60935,60937,60939-60941,60943-60954,60959-60961,60963-60964,60966-60967,60971,60977,60979-60989 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r60980 | georg.brandl | 2008-02-23 16:02:28 +0100 (Sat, 23 Feb 2008) | 2 lines
#1492: allow overriding BaseHTTPServer's content type for error messages.
........
r60982 | georg.brandl | 2008-02-23 16:06:25 +0100 (Sat, 23 Feb 2008) | 2 lines
#2165: fix test_logging failure on some machines.
........
r60983 | facundo.batista | 2008-02-23 16:07:35 +0100 (Sat, 23 Feb 2008) | 6 lines
Issue 1089358. Adds the siginterrupt() function, that is just a
wrapper around the system call with the same name. Also added
test cases, doc changes and NEWS entry. Thanks Jason and Ralf
Schmitt.
........
r60984 | georg.brandl | 2008-02-23 16:11:18 +0100 (Sat, 23 Feb 2008) | 2 lines
#2067: file.__exit__() now calls subclasses' close() method.
........
r60985 | georg.brandl | 2008-02-23 16:19:54 +0100 (Sat, 23 Feb 2008) | 2 lines
More difflib examples. Written for GHOP by Josip Dzolonga.
........
r60987 | andrew.kuchling | 2008-02-23 16:41:51 +0100 (Sat, 23 Feb 2008) | 1 line
#2072: correct documentation for .rpc_paths
........
r60988 | georg.brandl | 2008-02-23 16:43:48 +0100 (Sat, 23 Feb 2008) | 2 lines
#2161: Fix opcode name.
........
r60989 | andrew.kuchling | 2008-02-23 16:49:35 +0100 (Sat, 23 Feb 2008) | 2 lines
#1119331: ncurses will just call exit() if the terminal name isn't found.
Call setupterm() first so that we get a Python exception instead of just existing.
........
2008-02-23 12:23:06 -04:00
|
|
|
# Default error message template
|
1995-08-04 01:00:20 -03:00
|
|
|
DEFAULT_ERROR_MESSAGE = """\
|
2022-02-23 13:59:32 -04:00
|
|
|
<!DOCTYPE HTML>
|
|
|
|
<html lang="en">
|
2011-03-17 05:43:22 -03:00
|
|
|
<head>
|
2022-02-23 13:59:32 -04:00
|
|
|
<meta charset="utf-8">
|
2024-09-03 03:32:11 -03:00
|
|
|
<style type="text/css">
|
|
|
|
:root {
|
|
|
|
color-scheme: light dark;
|
|
|
|
}
|
|
|
|
</style>
|
2011-03-17 05:43:22 -03:00
|
|
|
<title>Error response</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h1>Error response</h1>
|
|
|
|
<p>Error code: %(code)d</p>
|
|
|
|
<p>Message: %(message)s.</p>
|
|
|
|
<p>Error code explanation: %(code)s - %(explain)s.</p>
|
|
|
|
</body>
|
|
|
|
</html>
|
1995-08-04 01:00:20 -03:00
|
|
|
"""
|
|
|
|
|
Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900,60902-60906,60908,60911-60917,60919-60920,60922,60926,60929-60931,60933-60935,60937,60939-60941,60943-60954,60959-60961,60963-60964,60966-60967,60971,60977,60979-60989 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r60980 | georg.brandl | 2008-02-23 16:02:28 +0100 (Sat, 23 Feb 2008) | 2 lines
#1492: allow overriding BaseHTTPServer's content type for error messages.
........
r60982 | georg.brandl | 2008-02-23 16:06:25 +0100 (Sat, 23 Feb 2008) | 2 lines
#2165: fix test_logging failure on some machines.
........
r60983 | facundo.batista | 2008-02-23 16:07:35 +0100 (Sat, 23 Feb 2008) | 6 lines
Issue 1089358. Adds the siginterrupt() function, that is just a
wrapper around the system call with the same name. Also added
test cases, doc changes and NEWS entry. Thanks Jason and Ralf
Schmitt.
........
r60984 | georg.brandl | 2008-02-23 16:11:18 +0100 (Sat, 23 Feb 2008) | 2 lines
#2067: file.__exit__() now calls subclasses' close() method.
........
r60985 | georg.brandl | 2008-02-23 16:19:54 +0100 (Sat, 23 Feb 2008) | 2 lines
More difflib examples. Written for GHOP by Josip Dzolonga.
........
r60987 | andrew.kuchling | 2008-02-23 16:41:51 +0100 (Sat, 23 Feb 2008) | 1 line
#2072: correct documentation for .rpc_paths
........
r60988 | georg.brandl | 2008-02-23 16:43:48 +0100 (Sat, 23 Feb 2008) | 2 lines
#2161: Fix opcode name.
........
r60989 | andrew.kuchling | 2008-02-23 16:49:35 +0100 (Sat, 23 Feb 2008) | 2 lines
#1119331: ncurses will just call exit() if the terminal name isn't found.
Call setupterm() first so that we get a Python exception instead of just existing.
........
2008-02-23 12:23:06 -04:00
|
|
|
DEFAULT_ERROR_CONTENT_TYPE = "text/html;charset=utf-8"
|
|
|
|
|
2008-05-11 23:31:37 -03:00
|
|
|
class HTTPServer(socketserver.TCPServer):
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2024-06-16 09:15:03 -03:00
|
|
|
allow_reuse_address = True # Seems to make sense in testing environment
|
|
|
|
allow_reuse_port = True
|
2000-05-09 11:54:13 -03:00
|
|
|
|
1995-08-04 01:00:20 -03:00
|
|
|
def server_bind(self):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Override server_bind to store the server name."""
|
2008-05-11 23:31:37 -03:00
|
|
|
socketserver.TCPServer.server_bind(self)
|
2016-04-02 22:28:53 -03:00
|
|
|
host, port = self.server_address[:2]
|
2000-08-16 17:30:21 -03:00
|
|
|
self.server_name = socket.getfqdn(host)
|
1998-03-26 17:13:24 -04:00
|
|
|
self.server_port = port
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
|
2018-05-29 17:10:30 -03:00
|
|
|
class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer):
|
2018-03-23 13:40:33 -03:00
|
|
|
daemon_threads = True
|
|
|
|
|
|
|
|
|
2008-05-11 23:31:37 -03:00
|
|
|
class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
"""HTTP request handler base class.
|
|
|
|
|
|
|
|
The following explanation of HTTP serves to guide you through the
|
|
|
|
code as well as to expose any misunderstandings I may have about
|
|
|
|
HTTP (so you don't need to read the code to figure out I'm wrong
|
|
|
|
:-).
|
|
|
|
|
|
|
|
HTTP (HyperText Transfer Protocol) is an extensible protocol on
|
|
|
|
top of a reliable stream transport (e.g. TCP/IP). The protocol
|
|
|
|
recognizes three parts to a request:
|
|
|
|
|
|
|
|
1. One line identifying the request type and path
|
|
|
|
2. An optional set of RFC-822-style headers
|
|
|
|
3. An optional data part
|
|
|
|
|
|
|
|
The headers and data are separated by a blank line.
|
|
|
|
|
|
|
|
The first line of the request has the form
|
|
|
|
|
|
|
|
<command> <path> <version>
|
|
|
|
|
|
|
|
where <command> is a (case-sensitive) keyword such as GET or POST,
|
|
|
|
<path> is a string containing path information for the request,
|
2002-03-17 14:37:22 -04:00
|
|
|
and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
|
|
|
|
<path> is encoded using the URL encoding scheme (using %xx to signify
|
|
|
|
the ASCII character with hex code xx).
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2003-02-03 11:21:15 -04:00
|
|
|
The specification specifies that lines are separated by CRLF but
|
|
|
|
for compatibility with the widest range of clients recommends
|
|
|
|
servers also handle LF. Similarly, whitespace in the request line
|
|
|
|
is treated sensibly (allowing multiple spaces between components
|
|
|
|
and allowing trailing whitespace).
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
Similarly, for output, lines ought to be separated by CRLF pairs
|
|
|
|
but most clients grok LF characters just fine.
|
|
|
|
|
|
|
|
If the first line of the request has the form
|
|
|
|
|
|
|
|
<command> <path>
|
|
|
|
|
|
|
|
(i.e. <version> is left out) then this is assumed to be an HTTP
|
|
|
|
0.9 request; this form has no optional headers and data part and
|
|
|
|
the reply consists of just the data.
|
|
|
|
|
2002-03-17 14:37:22 -04:00
|
|
|
The reply form of the HTTP 1.x protocol again has three parts:
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
1. One line giving the response code
|
|
|
|
2. An optional set of RFC-822-style headers
|
|
|
|
3. The data
|
|
|
|
|
|
|
|
Again, the headers and data are separated by a blank line.
|
|
|
|
|
|
|
|
The response code line has the form
|
|
|
|
|
|
|
|
<version> <responsecode> <responsestring>
|
|
|
|
|
2002-03-17 14:37:22 -04:00
|
|
|
where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
|
1995-08-04 01:00:20 -03:00
|
|
|
<responsecode> is a 3-digit response code indicating success or
|
|
|
|
failure of the request, and <responsestring> is an optional
|
|
|
|
human-readable string explaining what the response code means.
|
|
|
|
|
|
|
|
This server parses the request and the headers, and then calls a
|
|
|
|
function specific to the request type (<command>). Specifically,
|
1999-09-15 12:28:25 -03:00
|
|
|
a request SPAM will be handled by a method do_SPAM(). If no
|
1995-08-04 01:00:20 -03:00
|
|
|
such method exists the server sends an error response to the
|
|
|
|
client. If it exists, it is called with no arguments:
|
|
|
|
|
|
|
|
do_SPAM()
|
|
|
|
|
|
|
|
Note that the request name is case sensitive (i.e. SPAM and spam
|
|
|
|
are different requests).
|
|
|
|
|
|
|
|
The various request details are stored in instance variables:
|
|
|
|
|
|
|
|
- client_address is the client IP address in the form (host,
|
|
|
|
port);
|
|
|
|
|
|
|
|
- command, path and version are the broken-down request line;
|
|
|
|
|
2008-06-12 01:06:45 -03:00
|
|
|
- headers is an instance of email.message.Message (or a derived
|
1995-08-04 01:00:20 -03:00
|
|
|
class) containing the header information;
|
|
|
|
|
|
|
|
- rfile is a file object open for reading positioned at the
|
|
|
|
start of the optional input data part;
|
|
|
|
|
|
|
|
- wfile is a file object open for writing.
|
|
|
|
|
|
|
|
IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
|
|
|
|
|
|
|
|
The first thing to be written must be the response line. Then
|
|
|
|
follow 0 or more header lines, then a blank line, and then the
|
|
|
|
actual data (if any). The meaning of the header lines depends on
|
|
|
|
the command executed by the server; in most cases, when data is
|
|
|
|
returned, there should be at least one header line of the form
|
|
|
|
|
|
|
|
Content-type: <type>/<subtype>
|
|
|
|
|
|
|
|
where <type> and <subtype> should be registered MIME types,
|
|
|
|
e.g. "text/html" or "text/plain".
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
# The Python system version, truncated to its first component.
|
2001-02-09 01:07:04 -04:00
|
|
|
sys_version = "Python/" + sys.version.split()[0]
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
# The server software version. You may want to override this.
|
|
|
|
# The format is multiple whitespace-separated strings,
|
|
|
|
# where each string is of the form name[/version].
|
|
|
|
server_version = "BaseHTTP/" + __version__
|
|
|
|
|
Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900,60902-60906,60908,60911-60917,60919-60920,60922,60926,60929-60931,60933-60935,60937,60939-60941,60943-60954,60959-60961,60963-60964,60966-60967,60971,60977,60979-60989 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r60980 | georg.brandl | 2008-02-23 16:02:28 +0100 (Sat, 23 Feb 2008) | 2 lines
#1492: allow overriding BaseHTTPServer's content type for error messages.
........
r60982 | georg.brandl | 2008-02-23 16:06:25 +0100 (Sat, 23 Feb 2008) | 2 lines
#2165: fix test_logging failure on some machines.
........
r60983 | facundo.batista | 2008-02-23 16:07:35 +0100 (Sat, 23 Feb 2008) | 6 lines
Issue 1089358. Adds the siginterrupt() function, that is just a
wrapper around the system call with the same name. Also added
test cases, doc changes and NEWS entry. Thanks Jason and Ralf
Schmitt.
........
r60984 | georg.brandl | 2008-02-23 16:11:18 +0100 (Sat, 23 Feb 2008) | 2 lines
#2067: file.__exit__() now calls subclasses' close() method.
........
r60985 | georg.brandl | 2008-02-23 16:19:54 +0100 (Sat, 23 Feb 2008) | 2 lines
More difflib examples. Written for GHOP by Josip Dzolonga.
........
r60987 | andrew.kuchling | 2008-02-23 16:41:51 +0100 (Sat, 23 Feb 2008) | 1 line
#2072: correct documentation for .rpc_paths
........
r60988 | georg.brandl | 2008-02-23 16:43:48 +0100 (Sat, 23 Feb 2008) | 2 lines
#2161: Fix opcode name.
........
r60989 | andrew.kuchling | 2008-02-23 16:49:35 +0100 (Sat, 23 Feb 2008) | 2 lines
#1119331: ncurses will just call exit() if the terminal name isn't found.
Call setupterm() first so that we get a Python exception instead of just existing.
........
2008-02-23 12:23:06 -04:00
|
|
|
error_message_format = DEFAULT_ERROR_MESSAGE
|
|
|
|
error_content_type = DEFAULT_ERROR_CONTENT_TYPE
|
|
|
|
|
Merged revisions 63412,63445-63447,63449-63450,63452,63454,63459,63463,63465,63470,63483-63484,63496-63497,63499-63501,63530-63531,63540,63614 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r63412 | georg.brandl | 2008-05-17 19:57:01 +0200 (Sat, 17 May 2008) | 2 lines
#961805: fix Edit.text_modified().
........
r63445 | georg.brandl | 2008-05-18 10:52:59 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #180 by Michael Schneider: add examples to the socketserver documentation.
........
r63446 | georg.brandl | 2008-05-18 11:12:20 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #134, #171, #137: unit tests for the three HTTPServer modules.
........
r63447 | georg.brandl | 2008-05-18 12:39:26 +0200 (Sun, 18 May 2008) | 3 lines
Take namedtuple item names only from ascii_letters (this blew up on OSX),
and make sure there are no duplicate names.
........
r63449 | georg.brandl | 2008-05-18 13:46:51 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #217: add support for compiling Python with coverage checking enabled.
........
r63450 | georg.brandl | 2008-05-18 13:52:36 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #257: test distutils' build_ext command, written by Josip Dzolonga.
........
r63452 | georg.brandl | 2008-05-18 15:34:06 +0200 (Sun, 18 May 2008) | 2 lines
Add GHOP students.
........
r63454 | georg.brandl | 2008-05-18 18:32:48 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #121: improve test_pydoc, by Benjamin Peterson.
........
r63459 | benjamin.peterson | 2008-05-18 22:48:07 +0200 (Sun, 18 May 2008) | 2 lines
bring test_pydoc up to my high standards (now that I have them)
........
r63463 | georg.brandl | 2008-05-18 23:10:19 +0200 (Sun, 18 May 2008) | 2 lines
Fix test_pyclbr after another platform-dependent function was added to urllib.
........
r63465 | benjamin.peterson | 2008-05-19 01:07:07 +0200 (Mon, 19 May 2008) | 2 lines
change some imports in tests so they will not be skipped in 3.0
........
r63470 | georg.brandl | 2008-05-19 18:47:25 +0200 (Mon, 19 May 2008) | 2 lines
test_httpservers has unpredictable refcount behavior.
........
r63483 | georg.brandl | 2008-05-20 08:15:36 +0200 (Tue, 20 May 2008) | 2 lines
Activate two more test cases in test_httpservers.
........
r63484 | georg.brandl | 2008-05-20 08:47:31 +0200 (Tue, 20 May 2008) | 2 lines
Argh, this is the *actual* test that works under Windows.
........
r63496 | georg.brandl | 2008-05-20 10:07:36 +0200 (Tue, 20 May 2008) | 2 lines
Improve diffing logic and output for test_pydoc.
........
r63497 | georg.brandl | 2008-05-20 10:10:03 +0200 (Tue, 20 May 2008) | 2 lines
Use inspect.getabsfile() to get the documented module's filename.
........
r63499 | georg.brandl | 2008-05-20 10:25:48 +0200 (Tue, 20 May 2008) | 3 lines
Patch #1775025: allow opening zipfile members via ZipInfo instances.
Patch by Graham Horler.
........
r63500 | georg.brandl | 2008-05-20 10:40:43 +0200 (Tue, 20 May 2008) | 2 lines
#2592: delegate nb_index and the floor/truediv slots in weakref.proxy.
........
r63501 | georg.brandl | 2008-05-20 10:48:34 +0200 (Tue, 20 May 2008) | 2 lines
#615772: raise a more explicit error from Tkinter.Misc.__contains__.
........
r63530 | benjamin.peterson | 2008-05-22 02:57:02 +0200 (Thu, 22 May 2008) | 2 lines
use more specific asserts in test_opcode
........
r63531 | benjamin.peterson | 2008-05-22 03:02:23 +0200 (Thu, 22 May 2008) | 2 lines
remove redundant invocation of json doctests
........
r63540 | benjamin.peterson | 2008-05-23 01:09:26 +0200 (Fri, 23 May 2008) | 3 lines
fix test_pydoc so it works on make installed Python installations
Also let it pass when invoked directly
........
r63614 | georg.brandl | 2008-05-25 10:07:37 +0200 (Sun, 25 May 2008) | 2 lines
#2959: allow multiple close() calls for GzipFile.
........
2008-05-25 15:19:30 -03:00
|
|
|
# The default request version. This only affects responses up until
|
|
|
|
# the point where the request line is parsed, so it mainly decides what
|
|
|
|
# the client gets back when sending a malformed request line.
|
|
|
|
# Most web servers default to HTTP 0.9, i.e. don't send a status line.
|
|
|
|
default_request_version = "HTTP/0.9"
|
|
|
|
|
1999-10-26 10:01:36 -03:00
|
|
|
def parse_request(self):
|
|
|
|
"""Parse a request (internal).
|
1998-03-26 17:13:24 -04:00
|
|
|
|
2003-06-02 11:25:43 -03:00
|
|
|
The request should be stored in self.raw_requestline; the results
|
1999-10-26 10:01:36 -03:00
|
|
|
are in self.command, self.path, self.request_version and
|
|
|
|
self.headers.
|
1998-03-26 17:13:24 -04:00
|
|
|
|
2016-11-18 21:06:37 -04:00
|
|
|
Return True for success, False for failure; on failure, any relevant
|
|
|
|
error response has already been sent back.
|
1998-03-26 17:13:24 -04:00
|
|
|
|
1999-10-26 10:01:36 -03:00
|
|
|
"""
|
2003-02-03 15:11:18 -04:00
|
|
|
self.command = None # set in case of error on the first line
|
Merged revisions 63412,63445-63447,63449-63450,63452,63454,63459,63463,63465,63470,63483-63484,63496-63497,63499-63501,63530-63531,63540,63614 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r63412 | georg.brandl | 2008-05-17 19:57:01 +0200 (Sat, 17 May 2008) | 2 lines
#961805: fix Edit.text_modified().
........
r63445 | georg.brandl | 2008-05-18 10:52:59 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #180 by Michael Schneider: add examples to the socketserver documentation.
........
r63446 | georg.brandl | 2008-05-18 11:12:20 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #134, #171, #137: unit tests for the three HTTPServer modules.
........
r63447 | georg.brandl | 2008-05-18 12:39:26 +0200 (Sun, 18 May 2008) | 3 lines
Take namedtuple item names only from ascii_letters (this blew up on OSX),
and make sure there are no duplicate names.
........
r63449 | georg.brandl | 2008-05-18 13:46:51 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #217: add support for compiling Python with coverage checking enabled.
........
r63450 | georg.brandl | 2008-05-18 13:52:36 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #257: test distutils' build_ext command, written by Josip Dzolonga.
........
r63452 | georg.brandl | 2008-05-18 15:34:06 +0200 (Sun, 18 May 2008) | 2 lines
Add GHOP students.
........
r63454 | georg.brandl | 2008-05-18 18:32:48 +0200 (Sun, 18 May 2008) | 2 lines
GHOP #121: improve test_pydoc, by Benjamin Peterson.
........
r63459 | benjamin.peterson | 2008-05-18 22:48:07 +0200 (Sun, 18 May 2008) | 2 lines
bring test_pydoc up to my high standards (now that I have them)
........
r63463 | georg.brandl | 2008-05-18 23:10:19 +0200 (Sun, 18 May 2008) | 2 lines
Fix test_pyclbr after another platform-dependent function was added to urllib.
........
r63465 | benjamin.peterson | 2008-05-19 01:07:07 +0200 (Mon, 19 May 2008) | 2 lines
change some imports in tests so they will not be skipped in 3.0
........
r63470 | georg.brandl | 2008-05-19 18:47:25 +0200 (Mon, 19 May 2008) | 2 lines
test_httpservers has unpredictable refcount behavior.
........
r63483 | georg.brandl | 2008-05-20 08:15:36 +0200 (Tue, 20 May 2008) | 2 lines
Activate two more test cases in test_httpservers.
........
r63484 | georg.brandl | 2008-05-20 08:47:31 +0200 (Tue, 20 May 2008) | 2 lines
Argh, this is the *actual* test that works under Windows.
........
r63496 | georg.brandl | 2008-05-20 10:07:36 +0200 (Tue, 20 May 2008) | 2 lines
Improve diffing logic and output for test_pydoc.
........
r63497 | georg.brandl | 2008-05-20 10:10:03 +0200 (Tue, 20 May 2008) | 2 lines
Use inspect.getabsfile() to get the documented module's filename.
........
r63499 | georg.brandl | 2008-05-20 10:25:48 +0200 (Tue, 20 May 2008) | 3 lines
Patch #1775025: allow opening zipfile members via ZipInfo instances.
Patch by Graham Horler.
........
r63500 | georg.brandl | 2008-05-20 10:40:43 +0200 (Tue, 20 May 2008) | 2 lines
#2592: delegate nb_index and the floor/truediv slots in weakref.proxy.
........
r63501 | georg.brandl | 2008-05-20 10:48:34 +0200 (Tue, 20 May 2008) | 2 lines
#615772: raise a more explicit error from Tkinter.Misc.__contains__.
........
r63530 | benjamin.peterson | 2008-05-22 02:57:02 +0200 (Thu, 22 May 2008) | 2 lines
use more specific asserts in test_opcode
........
r63531 | benjamin.peterson | 2008-05-22 03:02:23 +0200 (Thu, 22 May 2008) | 2 lines
remove redundant invocation of json doctests
........
r63540 | benjamin.peterson | 2008-05-23 01:09:26 +0200 (Fri, 23 May 2008) | 3 lines
fix test_pydoc so it works on make installed Python installations
Also let it pass when invoked directly
........
r63614 | georg.brandl | 2008-05-25 10:07:37 +0200 (Sun, 25 May 2008) | 2 lines
#2959: allow multiple close() calls for GzipFile.
........
2008-05-25 15:19:30 -03:00
|
|
|
self.request_version = version = self.default_request_version
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
2007-08-03 17:32:27 -03:00
|
|
|
requestline = str(self.raw_requestline, 'iso-8859-1')
|
2011-12-23 05:03:41 -04:00
|
|
|
requestline = requestline.rstrip('\r\n')
|
1998-03-26 17:13:24 -04:00
|
|
|
self.requestline = requestline
|
2001-02-09 01:07:04 -04:00
|
|
|
words = requestline.split()
|
2016-11-18 21:06:37 -04:00
|
|
|
if len(words) == 0:
|
|
|
|
return False
|
|
|
|
|
|
|
|
if len(words) >= 3: # Enough to determine protocol version
|
|
|
|
version = words[-1]
|
2002-03-17 14:37:22 -04:00
|
|
|
try:
|
2016-11-18 21:06:37 -04:00
|
|
|
if not version.startswith('HTTP/'):
|
2016-04-02 22:28:53 -03:00
|
|
|
raise ValueError
|
2003-02-03 15:11:18 -04:00
|
|
|
base_version_number = version.split('/', 1)[1]
|
|
|
|
version_number = base_version_number.split(".")
|
|
|
|
# RFC 2145 section 3.1 says there can be only one "." and
|
|
|
|
# - major and minor numbers MUST be treated as
|
|
|
|
# separate integers;
|
|
|
|
# - HTTP/2.4 is a lower version than HTTP/2.13, which in
|
|
|
|
# turn is lower than HTTP/12.3;
|
|
|
|
# - Leading zeros MUST be ignored by recipients.
|
|
|
|
if len(version_number) != 2:
|
|
|
|
raise ValueError
|
2023-05-12 17:25:58 -03:00
|
|
|
if any(not component.isdigit() for component in version_number):
|
|
|
|
raise ValueError("non digit in http version")
|
|
|
|
if any(len(component) > 10 for component in version_number):
|
|
|
|
raise ValueError("unreasonable length http version")
|
2003-02-03 15:11:18 -04:00
|
|
|
version_number = int(version_number[0]), int(version_number[1])
|
|
|
|
except (ValueError, IndexError):
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.BAD_REQUEST,
|
|
|
|
"Bad request version (%r)" % version)
|
2002-04-04 18:55:58 -04:00
|
|
|
return False
|
2003-02-03 15:11:18 -04:00
|
|
|
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = False
|
2003-02-03 15:11:18 -04:00
|
|
|
if version_number >= (2, 0):
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
|
2016-04-02 22:28:53 -03:00
|
|
|
"Invalid HTTP version (%s)" % base_version_number)
|
2002-04-04 18:55:58 -04:00
|
|
|
return False
|
2016-11-18 21:06:37 -04:00
|
|
|
self.request_version = version
|
|
|
|
|
|
|
|
if not 2 <= len(words) <= 3:
|
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.BAD_REQUEST,
|
|
|
|
"Bad request syntax (%r)" % requestline)
|
|
|
|
return False
|
|
|
|
command, path = words[:2]
|
|
|
|
if len(words) == 2:
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
1998-03-26 17:13:24 -04:00
|
|
|
if command != 'GET':
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.BAD_REQUEST,
|
|
|
|
"Bad HTTP/0.9 request type (%r)" % command)
|
2002-04-04 18:55:58 -04:00
|
|
|
return False
|
2016-11-18 21:06:37 -04:00
|
|
|
self.command, self.path = command, path
|
2002-03-17 14:37:22 -04:00
|
|
|
|
2022-06-21 17:16:57 -03:00
|
|
|
# gh-87389: The purpose of replacing '//' with '/' is to protect
|
|
|
|
# against open redirect attacks possibly triggered if the path starts
|
|
|
|
# with '//' because http clients treat //path as an absolute URI
|
|
|
|
# without scheme (similar to http://path) rather than a path.
|
|
|
|
if self.path.startswith('//'):
|
|
|
|
self.path = '/' + self.path.lstrip('/') # Reduce to a single /
|
|
|
|
|
2007-08-22 20:45:42 -03:00
|
|
|
# Examine the headers and look for a Connection directive.
|
2010-12-18 12:55:23 -04:00
|
|
|
try:
|
|
|
|
self.headers = http.client.parse_headers(self.rfile,
|
|
|
|
_class=self.MessageClass)
|
2016-04-02 22:28:53 -03:00
|
|
|
except http.client.LineTooLong as err:
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
2016-04-02 22:28:53 -03:00
|
|
|
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
|
|
|
|
"Line too long",
|
|
|
|
str(err))
|
2010-12-18 12:55:23 -04:00
|
|
|
return False
|
2016-04-02 21:45:46 -03:00
|
|
|
except http.client.HTTPException as err:
|
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE,
|
|
|
|
"Too many headers",
|
|
|
|
str(err)
|
|
|
|
)
|
|
|
|
return False
|
2002-03-17 14:37:22 -04:00
|
|
|
|
|
|
|
conntype = self.headers.get('Connection', "")
|
|
|
|
if conntype.lower() == 'close':
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
2002-03-17 14:37:22 -04:00
|
|
|
elif (conntype.lower() == 'keep-alive' and
|
|
|
|
self.protocol_version >= "HTTP/1.1"):
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = False
|
2010-09-30 03:09:18 -03:00
|
|
|
# Examine the headers and look for an Expect directive
|
|
|
|
expect = self.headers.get('Expect', "")
|
|
|
|
if (expect.lower() == "100-continue" and
|
|
|
|
self.protocol_version >= "HTTP/1.1" and
|
|
|
|
self.request_version >= "HTTP/1.1"):
|
|
|
|
if not self.handle_expect_100():
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def handle_expect_100(self):
|
|
|
|
"""Decide what to do with an "Expect: 100-continue" header.
|
|
|
|
|
|
|
|
If the client is expecting a 100 Continue response, we must
|
|
|
|
respond with either a 100 Continue or a final response before
|
|
|
|
waiting for the request body. The default is to always respond
|
|
|
|
with a 100 Continue. You can behave differently (for example,
|
|
|
|
reject unauthorized requests) by overriding this method.
|
|
|
|
|
|
|
|
This method should either return True (possibly after sending
|
|
|
|
a 100 Continue response) or send an error response and return
|
|
|
|
False.
|
|
|
|
|
|
|
|
"""
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_response_only(HTTPStatus.CONTINUE)
|
2014-01-18 22:50:18 -04:00
|
|
|
self.end_headers()
|
2002-04-04 18:55:58 -04:00
|
|
|
return True
|
1999-10-26 10:01:36 -03:00
|
|
|
|
2002-03-17 14:37:22 -04:00
|
|
|
def handle_one_request(self):
|
1999-10-26 10:01:36 -03:00
|
|
|
"""Handle a single HTTP request.
|
|
|
|
|
|
|
|
You normally don't need to override this method; see the class
|
|
|
|
__doc__ string for information on how to handle specific HTTP
|
|
|
|
commands such as GET and POST.
|
|
|
|
|
|
|
|
"""
|
2009-07-01 07:01:31 -03:00
|
|
|
try:
|
2010-12-16 12:48:36 -04:00
|
|
|
self.raw_requestline = self.rfile.readline(65537)
|
|
|
|
if len(self.raw_requestline) > 65536:
|
|
|
|
self.requestline = ''
|
|
|
|
self.request_version = ''
|
|
|
|
self.command = ''
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG)
|
2010-12-16 12:48:36 -04:00
|
|
|
return
|
2009-07-01 07:01:31 -03:00
|
|
|
if not self.raw_requestline:
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
2009-07-01 07:01:31 -03:00
|
|
|
return
|
|
|
|
if not self.parse_request():
|
|
|
|
# An error code has been sent, just exit
|
|
|
|
return
|
|
|
|
mname = 'do_' + self.command
|
|
|
|
if not hasattr(self, mname):
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.NOT_IMPLEMENTED,
|
|
|
|
"Unsupported method (%r)" % self.command)
|
2009-07-01 07:01:31 -03:00
|
|
|
return
|
|
|
|
method = getattr(self, mname)
|
|
|
|
method()
|
|
|
|
self.wfile.flush() #actually send the response if not already done.
|
2020-11-20 04:26:07 -04:00
|
|
|
except TimeoutError as e:
|
2009-07-01 07:01:31 -03:00
|
|
|
#a read or a write timed out. Discard this connection
|
|
|
|
self.log_error("Request timed out: %r", e)
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
2002-03-17 14:37:22 -04:00
|
|
|
return
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2002-03-17 14:37:22 -04:00
|
|
|
def handle(self):
|
|
|
|
"""Handle multiple requests if necessary."""
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
2002-03-17 14:37:22 -04:00
|
|
|
|
|
|
|
self.handle_one_request()
|
|
|
|
while not self.close_connection:
|
|
|
|
self.handle_one_request()
|
|
|
|
|
2013-03-15 11:53:21 -03:00
|
|
|
def send_error(self, code, message=None, explain=None):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Send and log an error reply.
|
|
|
|
|
2013-03-15 11:53:21 -03:00
|
|
|
Arguments are
|
|
|
|
* code: an HTTP error code
|
|
|
|
3 digits
|
|
|
|
* message: a simple optional 1 line reason phrase.
|
|
|
|
*( HTAB / SP / VCHAR / %x80-FF )
|
|
|
|
defaults to short entry matching the response code
|
|
|
|
* explain: a detailed message defaults to the long entry
|
|
|
|
matching the response code.
|
1998-03-26 17:13:24 -04:00
|
|
|
|
|
|
|
This sends an error response (so it must be called before any
|
|
|
|
output has been generated), logs the error, and finally sends
|
|
|
|
a piece of HTML explaining the error to the user.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
2007-01-15 12:59:06 -04:00
|
|
|
shortmsg, longmsg = self.responses[code]
|
1998-03-26 17:13:24 -04:00
|
|
|
except KeyError:
|
2007-01-15 12:59:06 -04:00
|
|
|
shortmsg, longmsg = '???', '???'
|
2002-05-31 20:03:33 -03:00
|
|
|
if message is None:
|
2007-01-15 12:59:06 -04:00
|
|
|
message = shortmsg
|
2013-03-15 11:53:21 -03:00
|
|
|
if explain is None:
|
|
|
|
explain = longmsg
|
1998-03-26 17:13:24 -04:00
|
|
|
self.log_error("code %d, message %s", code, message)
|
2013-03-05 06:25:58 -04:00
|
|
|
self.send_response(code, message)
|
2002-03-17 14:37:22 -04:00
|
|
|
self.send_header('Connection', 'close')
|
2016-06-08 05:29:13 -03:00
|
|
|
|
|
|
|
# Message body is omitted for cases described in:
|
|
|
|
# - RFC7230: 3.3. 1xx, 204(No Content), 304(Not Modified)
|
|
|
|
# - RFC7231: 6.3.6. 205(Reset Content)
|
|
|
|
body = None
|
|
|
|
if (code >= 200 and
|
|
|
|
code not in (HTTPStatus.NO_CONTENT,
|
|
|
|
HTTPStatus.RESET_CONTENT,
|
|
|
|
HTTPStatus.NOT_MODIFIED)):
|
|
|
|
# HTML encode to prevent Cross Site Scripting attacks
|
|
|
|
# (see bug #1100201)
|
|
|
|
content = (self.error_message_format % {
|
|
|
|
'code': code,
|
2016-06-08 06:45:58 -03:00
|
|
|
'message': html.escape(message, quote=False),
|
|
|
|
'explain': html.escape(explain, quote=False)
|
2016-06-08 05:29:13 -03:00
|
|
|
})
|
|
|
|
body = content.encode('UTF-8', 'replace')
|
|
|
|
self.send_header("Content-Type", self.error_content_type)
|
2018-06-18 18:17:53 -03:00
|
|
|
self.send_header('Content-Length', str(len(body)))
|
1998-03-26 17:13:24 -04:00
|
|
|
self.end_headers()
|
2014-12-23 10:28:28 -04:00
|
|
|
|
2016-06-08 05:29:13 -03:00
|
|
|
if self.command != 'HEAD' and body:
|
2012-10-11 03:16:21 -03:00
|
|
|
self.wfile.write(body)
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
def send_response(self, code, message=None):
|
2011-05-09 12:25:02 -03:00
|
|
|
"""Add the response header to the headers buffer and log the
|
|
|
|
response code.
|
1998-03-26 17:13:24 -04:00
|
|
|
|
|
|
|
Also send two standard headers with the server software
|
|
|
|
version and the current date.
|
|
|
|
|
|
|
|
"""
|
|
|
|
self.log_request(code)
|
2010-09-30 03:09:18 -03:00
|
|
|
self.send_response_only(code, message)
|
|
|
|
self.send_header('Server', self.version_string())
|
|
|
|
self.send_header('Date', self.date_time_string())
|
|
|
|
|
|
|
|
def send_response_only(self, code, message=None):
|
|
|
|
"""Send the response header only."""
|
1998-03-26 17:13:24 -04:00
|
|
|
if self.request_version != 'HTTP/0.9':
|
2016-04-02 22:28:53 -03:00
|
|
|
if message is None:
|
|
|
|
if code in self.responses:
|
|
|
|
message = self.responses[code][0]
|
|
|
|
else:
|
|
|
|
message = ''
|
2011-05-09 12:25:02 -03:00
|
|
|
if not hasattr(self, '_headers_buffer'):
|
|
|
|
self._headers_buffer = []
|
|
|
|
self._headers_buffer.append(("%s %d %s\r\n" %
|
|
|
|
(self.protocol_version, code, message)).encode(
|
|
|
|
'latin-1', 'strict'))
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
def send_header(self, keyword, value):
|
2011-05-09 12:25:02 -03:00
|
|
|
"""Send a MIME header to the headers buffer."""
|
1998-03-26 17:13:24 -04:00
|
|
|
if self.request_version != 'HTTP/0.9':
|
2010-11-21 10:36:14 -04:00
|
|
|
if not hasattr(self, '_headers_buffer'):
|
|
|
|
self._headers_buffer = []
|
|
|
|
self._headers_buffer.append(
|
2011-02-25 11:42:01 -04:00
|
|
|
("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2002-03-17 14:37:22 -04:00
|
|
|
if keyword.lower() == 'connection':
|
|
|
|
if value.lower() == 'close':
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = True
|
2002-03-17 14:37:22 -04:00
|
|
|
elif value.lower() == 'keep-alive':
|
2015-02-17 22:11:10 -04:00
|
|
|
self.close_connection = False
|
2002-03-17 14:37:22 -04:00
|
|
|
|
1995-08-04 01:00:20 -03:00
|
|
|
def end_headers(self):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Send the blank line ending the MIME headers."""
|
|
|
|
if self.request_version != 'HTTP/0.9':
|
2010-11-21 10:36:14 -04:00
|
|
|
self._headers_buffer.append(b"\r\n")
|
2011-05-09 12:25:02 -03:00
|
|
|
self.flush_headers()
|
|
|
|
|
|
|
|
def flush_headers(self):
|
|
|
|
if hasattr(self, '_headers_buffer'):
|
2010-11-21 10:36:14 -04:00
|
|
|
self.wfile.write(b"".join(self._headers_buffer))
|
|
|
|
self._headers_buffer = []
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
def log_request(self, code='-', size='-'):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Log an accepted request.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2006-03-07 12:16:07 -04:00
|
|
|
This is called by send_response().
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
"""
|
2015-03-07 05:51:37 -04:00
|
|
|
if isinstance(code, HTTPStatus):
|
|
|
|
code = code.value
|
1998-03-26 17:13:24 -04:00
|
|
|
self.log_message('"%s" %s %s',
|
|
|
|
self.requestline, str(code), str(size))
|
1995-08-04 01:00:20 -03:00
|
|
|
|
Merged revisions 53304-53433,53435-53450 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53304 | vinay.sajip | 2007-01-09 15:50:28 +0100 (Tue, 09 Jan 2007) | 1 line
Bug #1627575: Added _open() method to FileHandler which can be used to reopen files. The FileHandler instance now saves the encoding (which can be None) in an attribute called "encoding".
........
r53305 | vinay.sajip | 2007-01-09 15:51:36 +0100 (Tue, 09 Jan 2007) | 1 line
Added entry about addition of _open() method to logging.FileHandler.
........
r53306 | vinay.sajip | 2007-01-09 15:54:56 +0100 (Tue, 09 Jan 2007) | 1 line
Added a docstring
........
r53316 | thomas.heller | 2007-01-09 20:19:33 +0100 (Tue, 09 Jan 2007) | 4 lines
Verify the sizes of the basic ctypes data types against the struct
module.
Will backport to release25-maint.
........
r53340 | gustavo.niemeyer | 2007-01-10 17:13:40 +0100 (Wed, 10 Jan 2007) | 3 lines
Mention in the int() docstring that a base zero has meaning, as
stated in http://docs.python.org/lib/built-in-funcs.html as well.
........
r53341 | gustavo.niemeyer | 2007-01-10 17:15:48 +0100 (Wed, 10 Jan 2007) | 2 lines
Minor change in int() docstring for proper spacing.
........
r53358 | thomas.heller | 2007-01-10 21:12:13 +0100 (Wed, 10 Jan 2007) | 1 line
Change the ctypes version number to "1.1.0".
........
r53361 | thomas.heller | 2007-01-10 21:51:19 +0100 (Wed, 10 Jan 2007) | 1 line
Must change the version number in the _ctypes extension as well.
........
r53362 | guido.van.rossum | 2007-01-11 00:12:56 +0100 (Thu, 11 Jan 2007) | 3 lines
Fix the signature of log_error(). (A subclass that did the right thing
was getting complaints from pychecker.)
........
r53370 | matthias.klose | 2007-01-11 11:26:31 +0100 (Thu, 11 Jan 2007) | 2 lines
- Make the documentation match the code and the docstring
........
r53375 | matthias.klose | 2007-01-11 12:44:04 +0100 (Thu, 11 Jan 2007) | 2 lines
- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092).
........
r53381 | raymond.hettinger | 2007-01-11 19:22:55 +0100 (Thu, 11 Jan 2007) | 1 line
SF #1486663 -- Allow keyword args in subclasses of set() and frozenset().
........
r53388 | thomas.heller | 2007-01-11 22:18:56 +0100 (Thu, 11 Jan 2007) | 4 lines
Fixes for 64-bit Windows: In ctypes.wintypes, correct the definitions
of HANDLE, WPARAM, LPARAM data types. Make parameterless foreign
function calls work.
........
r53390 | thomas.heller | 2007-01-11 22:23:12 +0100 (Thu, 11 Jan 2007) | 2 lines
Correct the comments: the code is right.
........
r53393 | brett.cannon | 2007-01-12 08:27:52 +0100 (Fri, 12 Jan 2007) | 3 lines
Fix error where the end of a funcdesc environment was accidentally moved too
far down.
........
r53397 | anthony.baxter | 2007-01-12 10:35:56 +0100 (Fri, 12 Jan 2007) | 3 lines
add parsetok.h as a dependency - previously, changing this file doesn't
cause the right files to be rebuilt.
........
r53401 | thomas.heller | 2007-01-12 21:08:19 +0100 (Fri, 12 Jan 2007) | 3 lines
Avoid warnings in the test suite because ctypes.wintypes cannot be
imported on non-windows systems.
........
r53402 | thomas.heller | 2007-01-12 21:17:34 +0100 (Fri, 12 Jan 2007) | 6 lines
patch #1610795: BSD version of ctypes.util.find_library, by Martin
Kammerhofer.
release25-maint backport candidate, but the release manager has to
decide.
........
r53403 | thomas.heller | 2007-01-12 21:21:53 +0100 (Fri, 12 Jan 2007) | 3 lines
patch #1610795: BSD version of ctypes.util.find_library, by Martin
Kammerhofer.
........
r53406 | brett.cannon | 2007-01-13 01:29:49 +0100 (Sat, 13 Jan 2007) | 2 lines
Deprecate the sets module.
........
r53407 | georg.brandl | 2007-01-13 13:31:51 +0100 (Sat, 13 Jan 2007) | 3 lines
Fix typo.
........
r53409 | marc-andre.lemburg | 2007-01-13 22:00:08 +0100 (Sat, 13 Jan 2007) | 16 lines
Bump version number and change copyright year.
Add new API linux_distribution() which supports reading the full distribution
name and also knows how to parse LSB-style release files.
Redirect the old dist() API to the new API (using the short distribution name
taken from the release file filename).
Add branch and revision to _sys_version().
Add work-around for Cygwin to libc_ver().
Add support for IronPython (thanks for Anthony Baxter) and make
Jython support more robust.
........
r53410 | neal.norwitz | 2007-01-13 22:22:37 +0100 (Sat, 13 Jan 2007) | 1 line
Fix grammar in docstrings
........
r53411 | marc-andre.lemburg | 2007-01-13 23:32:21 +0100 (Sat, 13 Jan 2007) | 9 lines
Add parameter sys_version to _sys_version().
Change the cache for _sys_version() to take the parameter into account.
Add support for parsing the IronPython 1.0.1 sys.version value - even
though it still returns '1.0.0'; the version string no longer includes
the patch level.
........
r53412 | peter.astrand | 2007-01-13 23:35:35 +0100 (Sat, 13 Jan 2007) | 1 line
Fix for bug #1634343: allow specifying empty arguments on Windows
........
r53414 | marc-andre.lemburg | 2007-01-13 23:59:36 +0100 (Sat, 13 Jan 2007) | 14 lines
Add Python implementation to the machine details.
Pretty-print the Python version used for running PyBench.
Let the user know when calibration has finished.
[ 1563844 ] pybench support for IronPython:
Simplify Unicode version detection.
Make garbage collection and check interval settings optional if
the Python implementation doesn't support thess (e.g. IronPython).
........
r53415 | marc-andre.lemburg | 2007-01-14 00:13:54 +0100 (Sun, 14 Jan 2007) | 5 lines
Use defaults if sys.executable isn't set (e.g. on Jython).
This change allows running PyBench under Jython.
........
r53416 | marc-andre.lemburg | 2007-01-14 00:15:33 +0100 (Sun, 14 Jan 2007) | 3 lines
Jython doesn't have sys.setcheckinterval() - ignore it in that case.
........
r53420 | gerhard.haering | 2007-01-14 02:43:50 +0100 (Sun, 14 Jan 2007) | 29 lines
Merged changes from standalone version 2.3.3. This should probably all be
merged into the 2.5 maintenance branch:
- self->statement was not checked while fetching data, which could
lead to crashes if you used the pysqlite API in unusual ways.
Closing the cursor and continuing to fetch data was enough.
- Converters are stored in a converters dictionary. The converter name
is uppercased first. The old upper-casing algorithm was wrong and
was replaced by a simple call to the Python string's upper() method
instead.
-Applied patch by Glyph Lefkowitz that fixes the problem with
subsequent SQLITE_SCHEMA errors.
- Improvement to the row type: rows can now be iterated over and have a keys()
method. This improves compatibility with both tuple and dict a lot.
- A bugfix for the subsecond resolution in timestamps.
- Corrected the way the flags PARSE_DECLTYPES and PARSE_COLNAMES are
checked for. Now they work as documented.
- gcc on Linux sucks. It exports all symbols by default in shared
libraries, so if symbols are not unique it can lead to problems with
symbol lookup. pysqlite used to crash under Apache when mod_cache
was enabled because both modules had the symbol cache_init. I fixed
this by applying the prefix pysqlite_ almost everywhere. Sigh.
........
r53423 | guido.van.rossum | 2007-01-14 04:46:33 +0100 (Sun, 14 Jan 2007) | 2 lines
Remove a dependency of this test on $COLUMNS.
........
r53425 | ka-ping.yee | 2007-01-14 05:25:15 +0100 (Sun, 14 Jan 2007) | 3 lines
Handle old-style instances more gracefully (display documentation on
the relevant class instead of documentation on <type 'instance'>).
........
r53440 | vinay.sajip | 2007-01-14 22:49:59 +0100 (Sun, 14 Jan 2007) | 1 line
Added WatchedFileHandler (based on SF patch #1598415)
........
r53441 | vinay.sajip | 2007-01-14 22:50:50 +0100 (Sun, 14 Jan 2007) | 1 line
Added documentation for WatchedFileHandler (based on SF patch #1598415)
........
r53442 | guido.van.rossum | 2007-01-15 01:02:35 +0100 (Mon, 15 Jan 2007) | 2 lines
Doc patch matching r53434 (htonl etc. now always take/return positive ints).
........
2007-01-15 11:49:28 -04:00
|
|
|
def log_error(self, format, *args):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Log an error.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
This is called when a request cannot be fulfilled. By
|
|
|
|
default it passes the message on to log_message().
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
Arguments are the same as for log_message().
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
XXX This should go to the separate error log.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
"""
|
1995-08-04 01:00:20 -03:00
|
|
|
|
Merged revisions 53304-53433,53435-53450 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53304 | vinay.sajip | 2007-01-09 15:50:28 +0100 (Tue, 09 Jan 2007) | 1 line
Bug #1627575: Added _open() method to FileHandler which can be used to reopen files. The FileHandler instance now saves the encoding (which can be None) in an attribute called "encoding".
........
r53305 | vinay.sajip | 2007-01-09 15:51:36 +0100 (Tue, 09 Jan 2007) | 1 line
Added entry about addition of _open() method to logging.FileHandler.
........
r53306 | vinay.sajip | 2007-01-09 15:54:56 +0100 (Tue, 09 Jan 2007) | 1 line
Added a docstring
........
r53316 | thomas.heller | 2007-01-09 20:19:33 +0100 (Tue, 09 Jan 2007) | 4 lines
Verify the sizes of the basic ctypes data types against the struct
module.
Will backport to release25-maint.
........
r53340 | gustavo.niemeyer | 2007-01-10 17:13:40 +0100 (Wed, 10 Jan 2007) | 3 lines
Mention in the int() docstring that a base zero has meaning, as
stated in http://docs.python.org/lib/built-in-funcs.html as well.
........
r53341 | gustavo.niemeyer | 2007-01-10 17:15:48 +0100 (Wed, 10 Jan 2007) | 2 lines
Minor change in int() docstring for proper spacing.
........
r53358 | thomas.heller | 2007-01-10 21:12:13 +0100 (Wed, 10 Jan 2007) | 1 line
Change the ctypes version number to "1.1.0".
........
r53361 | thomas.heller | 2007-01-10 21:51:19 +0100 (Wed, 10 Jan 2007) | 1 line
Must change the version number in the _ctypes extension as well.
........
r53362 | guido.van.rossum | 2007-01-11 00:12:56 +0100 (Thu, 11 Jan 2007) | 3 lines
Fix the signature of log_error(). (A subclass that did the right thing
was getting complaints from pychecker.)
........
r53370 | matthias.klose | 2007-01-11 11:26:31 +0100 (Thu, 11 Jan 2007) | 2 lines
- Make the documentation match the code and the docstring
........
r53375 | matthias.klose | 2007-01-11 12:44:04 +0100 (Thu, 11 Jan 2007) | 2 lines
- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092).
........
r53381 | raymond.hettinger | 2007-01-11 19:22:55 +0100 (Thu, 11 Jan 2007) | 1 line
SF #1486663 -- Allow keyword args in subclasses of set() and frozenset().
........
r53388 | thomas.heller | 2007-01-11 22:18:56 +0100 (Thu, 11 Jan 2007) | 4 lines
Fixes for 64-bit Windows: In ctypes.wintypes, correct the definitions
of HANDLE, WPARAM, LPARAM data types. Make parameterless foreign
function calls work.
........
r53390 | thomas.heller | 2007-01-11 22:23:12 +0100 (Thu, 11 Jan 2007) | 2 lines
Correct the comments: the code is right.
........
r53393 | brett.cannon | 2007-01-12 08:27:52 +0100 (Fri, 12 Jan 2007) | 3 lines
Fix error where the end of a funcdesc environment was accidentally moved too
far down.
........
r53397 | anthony.baxter | 2007-01-12 10:35:56 +0100 (Fri, 12 Jan 2007) | 3 lines
add parsetok.h as a dependency - previously, changing this file doesn't
cause the right files to be rebuilt.
........
r53401 | thomas.heller | 2007-01-12 21:08:19 +0100 (Fri, 12 Jan 2007) | 3 lines
Avoid warnings in the test suite because ctypes.wintypes cannot be
imported on non-windows systems.
........
r53402 | thomas.heller | 2007-01-12 21:17:34 +0100 (Fri, 12 Jan 2007) | 6 lines
patch #1610795: BSD version of ctypes.util.find_library, by Martin
Kammerhofer.
release25-maint backport candidate, but the release manager has to
decide.
........
r53403 | thomas.heller | 2007-01-12 21:21:53 +0100 (Fri, 12 Jan 2007) | 3 lines
patch #1610795: BSD version of ctypes.util.find_library, by Martin
Kammerhofer.
........
r53406 | brett.cannon | 2007-01-13 01:29:49 +0100 (Sat, 13 Jan 2007) | 2 lines
Deprecate the sets module.
........
r53407 | georg.brandl | 2007-01-13 13:31:51 +0100 (Sat, 13 Jan 2007) | 3 lines
Fix typo.
........
r53409 | marc-andre.lemburg | 2007-01-13 22:00:08 +0100 (Sat, 13 Jan 2007) | 16 lines
Bump version number and change copyright year.
Add new API linux_distribution() which supports reading the full distribution
name and also knows how to parse LSB-style release files.
Redirect the old dist() API to the new API (using the short distribution name
taken from the release file filename).
Add branch and revision to _sys_version().
Add work-around for Cygwin to libc_ver().
Add support for IronPython (thanks for Anthony Baxter) and make
Jython support more robust.
........
r53410 | neal.norwitz | 2007-01-13 22:22:37 +0100 (Sat, 13 Jan 2007) | 1 line
Fix grammar in docstrings
........
r53411 | marc-andre.lemburg | 2007-01-13 23:32:21 +0100 (Sat, 13 Jan 2007) | 9 lines
Add parameter sys_version to _sys_version().
Change the cache for _sys_version() to take the parameter into account.
Add support for parsing the IronPython 1.0.1 sys.version value - even
though it still returns '1.0.0'; the version string no longer includes
the patch level.
........
r53412 | peter.astrand | 2007-01-13 23:35:35 +0100 (Sat, 13 Jan 2007) | 1 line
Fix for bug #1634343: allow specifying empty arguments on Windows
........
r53414 | marc-andre.lemburg | 2007-01-13 23:59:36 +0100 (Sat, 13 Jan 2007) | 14 lines
Add Python implementation to the machine details.
Pretty-print the Python version used for running PyBench.
Let the user know when calibration has finished.
[ 1563844 ] pybench support for IronPython:
Simplify Unicode version detection.
Make garbage collection and check interval settings optional if
the Python implementation doesn't support thess (e.g. IronPython).
........
r53415 | marc-andre.lemburg | 2007-01-14 00:13:54 +0100 (Sun, 14 Jan 2007) | 5 lines
Use defaults if sys.executable isn't set (e.g. on Jython).
This change allows running PyBench under Jython.
........
r53416 | marc-andre.lemburg | 2007-01-14 00:15:33 +0100 (Sun, 14 Jan 2007) | 3 lines
Jython doesn't have sys.setcheckinterval() - ignore it in that case.
........
r53420 | gerhard.haering | 2007-01-14 02:43:50 +0100 (Sun, 14 Jan 2007) | 29 lines
Merged changes from standalone version 2.3.3. This should probably all be
merged into the 2.5 maintenance branch:
- self->statement was not checked while fetching data, which could
lead to crashes if you used the pysqlite API in unusual ways.
Closing the cursor and continuing to fetch data was enough.
- Converters are stored in a converters dictionary. The converter name
is uppercased first. The old upper-casing algorithm was wrong and
was replaced by a simple call to the Python string's upper() method
instead.
-Applied patch by Glyph Lefkowitz that fixes the problem with
subsequent SQLITE_SCHEMA errors.
- Improvement to the row type: rows can now be iterated over and have a keys()
method. This improves compatibility with both tuple and dict a lot.
- A bugfix for the subsecond resolution in timestamps.
- Corrected the way the flags PARSE_DECLTYPES and PARSE_COLNAMES are
checked for. Now they work as documented.
- gcc on Linux sucks. It exports all symbols by default in shared
libraries, so if symbols are not unique it can lead to problems with
symbol lookup. pysqlite used to crash under Apache when mod_cache
was enabled because both modules had the symbol cache_init. I fixed
this by applying the prefix pysqlite_ almost everywhere. Sigh.
........
r53423 | guido.van.rossum | 2007-01-14 04:46:33 +0100 (Sun, 14 Jan 2007) | 2 lines
Remove a dependency of this test on $COLUMNS.
........
r53425 | ka-ping.yee | 2007-01-14 05:25:15 +0100 (Sun, 14 Jan 2007) | 3 lines
Handle old-style instances more gracefully (display documentation on
the relevant class instead of documentation on <type 'instance'>).
........
r53440 | vinay.sajip | 2007-01-14 22:49:59 +0100 (Sun, 14 Jan 2007) | 1 line
Added WatchedFileHandler (based on SF patch #1598415)
........
r53441 | vinay.sajip | 2007-01-14 22:50:50 +0100 (Sun, 14 Jan 2007) | 1 line
Added documentation for WatchedFileHandler (based on SF patch #1598415)
........
r53442 | guido.van.rossum | 2007-01-15 01:02:35 +0100 (Mon, 15 Jan 2007) | 2 lines
Doc patch matching r53434 (htonl etc. now always take/return positive ints).
........
2007-01-15 11:49:28 -04:00
|
|
|
self.log_message(format, *args)
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2022-12-05 16:55:45 -04:00
|
|
|
# https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes
|
|
|
|
_control_char_table = str.maketrans(
|
|
|
|
{c: fr'\x{c:02x}' for c in itertools.chain(range(0x20), range(0x7f,0xa0))})
|
2022-12-05 18:27:55 -04:00
|
|
|
_control_char_table[ord('\\')] = r'\\'
|
2022-12-05 16:55:45 -04:00
|
|
|
|
1995-08-04 01:00:20 -03:00
|
|
|
def log_message(self, format, *args):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Log an arbitrary message.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
This is used by all other logging functions. Override
|
|
|
|
it if you have specific logging wishes.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
The first argument, FORMAT, is a format string for the
|
|
|
|
message to be logged. If the format string contains
|
|
|
|
any % escapes requiring parameters, they should be
|
|
|
|
specified as subsequent arguments (it's just like
|
|
|
|
printf!).
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2012-04-29 02:41:03 -03:00
|
|
|
The client ip and current date/time are prefixed to
|
1998-03-26 17:13:24 -04:00
|
|
|
every message.
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2022-12-05 16:55:45 -04:00
|
|
|
Unicode control characters are replaced with escaped hex
|
|
|
|
before writing the output to stderr.
|
|
|
|
|
1998-03-26 17:13:24 -04:00
|
|
|
"""
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2022-12-05 16:55:45 -04:00
|
|
|
message = format % args
|
1998-03-26 17:13:24 -04:00
|
|
|
sys.stderr.write("%s - - [%s] %s\n" %
|
|
|
|
(self.address_string(),
|
|
|
|
self.log_date_time_string(),
|
2022-12-05 16:55:45 -04:00
|
|
|
message.translate(self._control_char_table)))
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
def version_string(self):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Return the server software version string."""
|
|
|
|
return self.server_version + ' ' + self.sys_version
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2006-02-17 09:34:16 -04:00
|
|
|
def date_time_string(self, timestamp=None):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Return the current date and time formatted for a message header."""
|
2006-02-17 09:34:16 -04:00
|
|
|
if timestamp is None:
|
|
|
|
timestamp = time.time()
|
2016-03-14 01:06:03 -03:00
|
|
|
return email.utils.formatdate(timestamp, usegmt=True)
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
def log_date_time_string(self):
|
1998-03-26 17:13:24 -04:00
|
|
|
"""Return the current time formatted for logging."""
|
|
|
|
now = time.time()
|
|
|
|
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
|
|
|
|
s = "%02d/%3s/%04d %02d:%02d:%02d" % (
|
|
|
|
day, self.monthname[month], year, hh, mm, ss)
|
|
|
|
return s
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
|
|
|
|
|
|
|
monthname = [None,
|
1998-03-26 17:13:24 -04:00
|
|
|
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
|
|
|
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
def address_string(self):
|
2012-04-29 01:51:54 -03:00
|
|
|
"""Return the client address."""
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2012-04-29 01:51:54 -03:00
|
|
|
return self.client_address[0]
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
# Essentially static class variables
|
|
|
|
|
|
|
|
# The version of the HTTP protocol we support.
|
2002-03-17 14:37:22 -04:00
|
|
|
# Set this to HTTP/1.1 to enable automatic keepalive
|
1995-08-04 01:00:20 -03:00
|
|
|
protocol_version = "HTTP/1.0"
|
|
|
|
|
2008-06-12 01:06:45 -03:00
|
|
|
# MessageClass used to parse headers
|
|
|
|
MessageClass = http.client.HTTPMessage
|
1995-08-04 01:00:20 -03:00
|
|
|
|
2014-12-23 10:28:28 -04:00
|
|
|
# hack to maintain backwards compatibility
|
1995-08-04 01:00:20 -03:00
|
|
|
responses = {
|
2014-12-23 10:28:28 -04:00
|
|
|
v: (v.phrase, v.description)
|
|
|
|
for v in HTTPStatus.__members__.values()
|
|
|
|
}
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
|
|
|
|
|
|
|
|
"""Simple HTTP request handler with GET and HEAD commands.
|
|
|
|
|
|
|
|
This serves files from the current directory and any of its
|
|
|
|
subdirectories. The MIME type for files is determined by
|
|
|
|
calling the .guess_type() method.
|
|
|
|
|
|
|
|
The GET and HEAD requests are identical except that the HEAD
|
|
|
|
request omits the actual contents of the file.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
server_version = "SimpleHTTP/" + __version__
|
2023-01-03 19:20:08 -04:00
|
|
|
index_pages = ("index.html", "index.htm")
|
2020-01-08 14:28:14 -04:00
|
|
|
extensions_map = _encodings_map_default = {
|
|
|
|
'.gz': 'application/gzip',
|
|
|
|
'.Z': 'application/octet-stream',
|
|
|
|
'.bz2': 'application/x-bzip2',
|
|
|
|
'.xz': 'application/x-xz',
|
|
|
|
}
|
2008-05-26 13:32:26 -03:00
|
|
|
|
2023-01-03 19:20:08 -04:00
|
|
|
def __init__(self, *args, directory=None, **kwargs):
|
2017-05-24 04:29:06 -03:00
|
|
|
if directory is None:
|
|
|
|
directory = os.getcwd()
|
2019-09-11 10:03:46 -03:00
|
|
|
self.directory = os.fspath(directory)
|
2017-05-24 04:29:06 -03:00
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
def do_GET(self):
|
|
|
|
"""Serve a GET request."""
|
|
|
|
f = self.send_head()
|
|
|
|
if f:
|
2014-01-25 13:43:02 -04:00
|
|
|
try:
|
|
|
|
self.copyfile(f, self.wfile)
|
|
|
|
finally:
|
|
|
|
f.close()
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
def do_HEAD(self):
|
|
|
|
"""Serve a HEAD request."""
|
|
|
|
f = self.send_head()
|
|
|
|
if f:
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
def send_head(self):
|
|
|
|
"""Common code for GET and HEAD commands.
|
|
|
|
|
|
|
|
This sends the response code and MIME headers.
|
|
|
|
|
|
|
|
Return value is either a file object (which has to be copied
|
|
|
|
to the outputfile by the caller unless the command was HEAD,
|
|
|
|
and must be closed by the caller under all circumstances), or
|
|
|
|
None, in which case the caller has nothing further to do.
|
|
|
|
|
|
|
|
"""
|
|
|
|
path = self.translate_path(self.path)
|
|
|
|
f = None
|
|
|
|
if os.path.isdir(path):
|
2014-12-26 12:53:43 -04:00
|
|
|
parts = urllib.parse.urlsplit(self.path)
|
|
|
|
if not parts.path.endswith('/'):
|
2008-05-26 13:32:26 -03:00
|
|
|
# redirect browser - doing basically what apache does
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_response(HTTPStatus.MOVED_PERMANENTLY)
|
2014-12-26 12:53:43 -04:00
|
|
|
new_parts = (parts[0], parts[1], parts[2] + '/',
|
|
|
|
parts[3], parts[4])
|
|
|
|
new_url = urllib.parse.urlunsplit(new_parts)
|
|
|
|
self.send_header("Location", new_url)
|
2021-05-06 16:25:52 -03:00
|
|
|
self.send_header("Content-Length", "0")
|
2008-05-26 13:32:26 -03:00
|
|
|
self.end_headers()
|
|
|
|
return None
|
2022-06-23 17:30:44 -03:00
|
|
|
for index in self.index_pages:
|
2008-05-26 13:32:26 -03:00
|
|
|
index = os.path.join(path, index)
|
2022-12-24 14:28:59 -04:00
|
|
|
if os.path.isfile(index):
|
2008-05-26 13:32:26 -03:00
|
|
|
path = index
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
return self.list_directory(path)
|
|
|
|
ctype = self.guess_type(path)
|
2018-12-26 01:43:42 -04:00
|
|
|
# check for trailing "/" which should return 404. See Issue17324
|
|
|
|
# The test for this was added in test_httpserver.py
|
|
|
|
# However, some OS platforms accept a trailingSlash as a filename
|
|
|
|
# See discussion on python-dev and Issue34711 regarding
|
2021-06-12 23:47:44 -03:00
|
|
|
# parsing and rejection of filenames with a trailing slash
|
2018-12-26 01:43:42 -04:00
|
|
|
if path.endswith("/"):
|
|
|
|
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
|
|
|
|
return None
|
2008-05-26 13:32:26 -03:00
|
|
|
try:
|
|
|
|
f = open(path, 'rb')
|
2012-12-25 10:47:37 -04:00
|
|
|
except OSError:
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
|
2008-05-26 13:32:26 -03:00
|
|
|
return None
|
2017-04-02 07:26:12 -03:00
|
|
|
|
2014-01-25 13:43:02 -04:00
|
|
|
try:
|
2017-04-02 07:26:12 -03:00
|
|
|
fs = os.fstat(f.fileno())
|
|
|
|
# Use browser cache if possible
|
|
|
|
if ("If-Modified-Since" in self.headers
|
|
|
|
and "If-None-Match" not in self.headers):
|
|
|
|
# compare If-Modified-Since and time of last file modification
|
|
|
|
try:
|
|
|
|
ims = email.utils.parsedate_to_datetime(
|
|
|
|
self.headers["If-Modified-Since"])
|
|
|
|
except (TypeError, IndexError, OverflowError, ValueError):
|
|
|
|
# ignore ill-formed values
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if ims.tzinfo is None:
|
|
|
|
# obsolete format with no timezone, cf.
|
|
|
|
# https://tools.ietf.org/html/rfc7231#section-7.1.1.1
|
|
|
|
ims = ims.replace(tzinfo=datetime.timezone.utc)
|
|
|
|
if ims.tzinfo is datetime.timezone.utc:
|
|
|
|
# compare to UTC datetime of last modification
|
|
|
|
last_modif = datetime.datetime.fromtimestamp(
|
|
|
|
fs.st_mtime, datetime.timezone.utc)
|
|
|
|
# remove microseconds, like in If-Modified-Since
|
|
|
|
last_modif = last_modif.replace(microsecond=0)
|
2017-09-14 03:38:36 -03:00
|
|
|
|
2017-04-02 07:26:12 -03:00
|
|
|
if last_modif <= ims:
|
|
|
|
self.send_response(HTTPStatus.NOT_MODIFIED)
|
|
|
|
self.end_headers()
|
|
|
|
f.close()
|
|
|
|
return None
|
|
|
|
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_response(HTTPStatus.OK)
|
2014-01-25 13:43:02 -04:00
|
|
|
self.send_header("Content-type", ctype)
|
|
|
|
self.send_header("Content-Length", str(fs[6]))
|
2017-09-14 03:38:36 -03:00
|
|
|
self.send_header("Last-Modified",
|
2017-04-02 07:26:12 -03:00
|
|
|
self.date_time_string(fs.st_mtime))
|
2014-01-25 13:43:02 -04:00
|
|
|
self.end_headers()
|
|
|
|
return f
|
|
|
|
except:
|
|
|
|
f.close()
|
|
|
|
raise
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
def list_directory(self, path):
|
|
|
|
"""Helper to produce a directory listing (absent index.html).
|
|
|
|
|
|
|
|
Return value is either a file object, or None (indicating an
|
|
|
|
error). In either case, the headers are sent, making the
|
|
|
|
interface the same as for send_head().
|
|
|
|
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
list = os.listdir(path)
|
2012-12-18 16:02:39 -04:00
|
|
|
except OSError:
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.NOT_FOUND,
|
|
|
|
"No permission to list directory")
|
2008-05-26 13:32:26 -03:00
|
|
|
return None
|
|
|
|
list.sort(key=lambda a: a.lower())
|
|
|
|
r = []
|
2014-08-17 02:22:11 -03:00
|
|
|
try:
|
|
|
|
displaypath = urllib.parse.unquote(self.path,
|
|
|
|
errors='surrogatepass')
|
|
|
|
except UnicodeDecodeError:
|
2023-05-03 00:42:00 -03:00
|
|
|
displaypath = urllib.parse.unquote(self.path)
|
2016-04-10 21:40:08 -03:00
|
|
|
displaypath = html.escape(displaypath, quote=False)
|
2011-11-02 14:33:29 -03:00
|
|
|
enc = sys.getfilesystemencoding()
|
2022-02-23 13:59:32 -04:00
|
|
|
title = f'Directory listing for {displaypath}'
|
|
|
|
r.append('<!DOCTYPE HTML>')
|
|
|
|
r.append('<html lang="en">')
|
|
|
|
r.append('<head>')
|
|
|
|
r.append(f'<meta charset="{enc}">')
|
2024-09-03 03:32:11 -03:00
|
|
|
r.append('<style type="text/css">\n:root {\ncolor-scheme: light dark;\n}\n</style>')
|
2022-02-23 13:59:32 -04:00
|
|
|
r.append(f'<title>{title}</title>\n</head>')
|
|
|
|
r.append(f'<body>\n<h1>{title}</h1>')
|
2011-11-02 14:33:29 -03:00
|
|
|
r.append('<hr>\n<ul>')
|
2008-05-26 13:32:26 -03:00
|
|
|
for name in list:
|
|
|
|
fullname = os.path.join(path, name)
|
|
|
|
displayname = linkname = name
|
|
|
|
# Append / for directories or @ for symbolic links
|
|
|
|
if os.path.isdir(fullname):
|
|
|
|
displayname = name + "/"
|
|
|
|
linkname = name + "/"
|
|
|
|
if os.path.islink(fullname):
|
|
|
|
displayname = name + "@"
|
|
|
|
# Note: a link to a directory displays with @ and links with /
|
2011-11-02 14:33:29 -03:00
|
|
|
r.append('<li><a href="%s">%s</a></li>'
|
2014-08-17 02:22:11 -03:00
|
|
|
% (urllib.parse.quote(linkname,
|
|
|
|
errors='surrogatepass'),
|
2016-04-10 21:40:08 -03:00
|
|
|
html.escape(displayname, quote=False)))
|
2011-11-02 14:33:29 -03:00
|
|
|
r.append('</ul>\n<hr>\n</body>\n</html>\n')
|
2014-08-17 02:22:11 -03:00
|
|
|
encoded = '\n'.join(r).encode(enc, 'surrogateescape')
|
2008-05-26 13:32:26 -03:00
|
|
|
f = io.BytesIO()
|
|
|
|
f.write(encoded)
|
|
|
|
f.seek(0)
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_response(HTTPStatus.OK)
|
2008-05-26 13:32:26 -03:00
|
|
|
self.send_header("Content-type", "text/html; charset=%s" % enc)
|
|
|
|
self.send_header("Content-Length", str(len(encoded)))
|
|
|
|
self.end_headers()
|
|
|
|
return f
|
|
|
|
|
|
|
|
def translate_path(self, path):
|
|
|
|
"""Translate a /-separated PATH to the local filename syntax.
|
|
|
|
|
|
|
|
Components that mean special things to the local file system
|
|
|
|
(e.g. drive or directory names) are ignored. (XXX They should
|
|
|
|
probably be diagnosed.)
|
|
|
|
|
|
|
|
"""
|
|
|
|
# abandon query parameters
|
|
|
|
path = path.split('?',1)[0]
|
|
|
|
path = path.split('#',1)[0]
|
2013-09-13 04:21:18 -03:00
|
|
|
# Don't forget explicit trailing slash when normalizing. Issue17324
|
2013-09-29 22:59:04 -03:00
|
|
|
trailing_slash = path.rstrip().endswith('/')
|
2014-08-17 02:22:11 -03:00
|
|
|
try:
|
|
|
|
path = urllib.parse.unquote(path, errors='surrogatepass')
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
path = urllib.parse.unquote(path)
|
|
|
|
path = posixpath.normpath(path)
|
2008-05-26 13:32:26 -03:00
|
|
|
words = path.split('/')
|
|
|
|
words = filter(None, words)
|
2017-05-24 04:29:06 -03:00
|
|
|
path = self.directory
|
2008-05-26 13:32:26 -03:00
|
|
|
for word in words:
|
2016-04-18 00:45:18 -03:00
|
|
|
if os.path.dirname(word) or word in (os.curdir, os.pardir):
|
|
|
|
# Ignore components that are not a simple file/directory name
|
|
|
|
continue
|
2008-05-26 13:32:26 -03:00
|
|
|
path = os.path.join(path, word)
|
2013-09-13 04:21:18 -03:00
|
|
|
if trailing_slash:
|
|
|
|
path += '/'
|
2008-05-26 13:32:26 -03:00
|
|
|
return path
|
|
|
|
|
|
|
|
def copyfile(self, source, outputfile):
|
|
|
|
"""Copy all data between two file objects.
|
|
|
|
|
|
|
|
The SOURCE argument is a file object open for reading
|
|
|
|
(or anything with a read() method) and the DESTINATION
|
|
|
|
argument is a file object open for writing (or
|
|
|
|
anything with a write() method).
|
|
|
|
|
|
|
|
The only reason for overriding this would be to change
|
|
|
|
the block size or perhaps to replace newlines by CRLF
|
|
|
|
-- note however that this the default server uses this
|
|
|
|
to copy binary data as well.
|
|
|
|
|
|
|
|
"""
|
|
|
|
shutil.copyfileobj(source, outputfile)
|
|
|
|
|
|
|
|
def guess_type(self, path):
|
|
|
|
"""Guess the type of a file.
|
|
|
|
|
|
|
|
Argument is a PATH (a filename).
|
|
|
|
|
|
|
|
Return value is a string of the form type/subtype,
|
|
|
|
usable for a MIME Content-type header.
|
|
|
|
|
|
|
|
The default implementation looks the file's extension
|
|
|
|
up in the table self.extensions_map, using application/octet-stream
|
|
|
|
as a default; however it would be permissible (if
|
|
|
|
slow) to look inside the data to make a better guess.
|
|
|
|
|
|
|
|
"""
|
|
|
|
base, ext = posixpath.splitext(path)
|
|
|
|
if ext in self.extensions_map:
|
|
|
|
return self.extensions_map[ext]
|
|
|
|
ext = ext.lower()
|
|
|
|
if ext in self.extensions_map:
|
|
|
|
return self.extensions_map[ext]
|
2024-05-06 09:50:52 -03:00
|
|
|
guess, _ = mimetypes.guess_file_type(path)
|
2020-01-08 14:28:14 -04:00
|
|
|
if guess:
|
|
|
|
return guess
|
|
|
|
return 'application/octet-stream'
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
# Utilities for CGIHTTPRequestHandler
|
|
|
|
|
2012-04-11 15:34:32 -03:00
|
|
|
def _url_collapse_path(path):
|
2009-04-11 17:12:10 -03:00
|
|
|
"""
|
|
|
|
Given a URL path, remove extra '/'s and '.' path elements and collapse
|
2015-10-07 07:26:23 -03:00
|
|
|
any '..' references and returns a collapsed path.
|
2009-04-11 17:12:10 -03:00
|
|
|
|
|
|
|
Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
|
2012-04-11 15:34:32 -03:00
|
|
|
The utility of this function is limited to is_cgi method and helps
|
|
|
|
preventing some security attacks.
|
2009-04-11 17:12:10 -03:00
|
|
|
|
2015-10-03 02:55:46 -03:00
|
|
|
Returns: The reconstituted URL, which will always start with a '/'.
|
2009-04-11 17:12:10 -03:00
|
|
|
|
|
|
|
Raises: IndexError if too many '..' occur within the path.
|
2012-04-11 15:34:32 -03:00
|
|
|
|
2009-04-11 17:12:10 -03:00
|
|
|
"""
|
2015-10-03 02:55:46 -03:00
|
|
|
# Query component should not be involved.
|
|
|
|
path, _, query = path.partition('?')
|
|
|
|
path = urllib.parse.unquote(path)
|
|
|
|
|
2009-04-11 17:12:10 -03:00
|
|
|
# Similar to os.path.split(os.path.normpath(path)) but specific to URL
|
|
|
|
# path semantics rather than local operating system semantics.
|
2012-04-11 15:34:32 -03:00
|
|
|
path_parts = path.split('/')
|
|
|
|
head_parts = []
|
|
|
|
for part in path_parts[:-1]:
|
|
|
|
if part == '..':
|
|
|
|
head_parts.pop() # IndexError if more '..' than prior parts
|
|
|
|
elif part and part != '.':
|
|
|
|
head_parts.append( part )
|
2009-04-11 17:12:10 -03:00
|
|
|
if path_parts:
|
2012-04-10 16:15:28 -03:00
|
|
|
tail_part = path_parts.pop()
|
2012-04-11 15:34:32 -03:00
|
|
|
if tail_part:
|
|
|
|
if tail_part == '..':
|
|
|
|
head_parts.pop()
|
|
|
|
tail_part = ''
|
|
|
|
elif tail_part == '.':
|
|
|
|
tail_part = ''
|
2009-04-11 17:12:10 -03:00
|
|
|
else:
|
|
|
|
tail_part = ''
|
2012-04-11 15:34:32 -03:00
|
|
|
|
2015-10-03 02:55:46 -03:00
|
|
|
if query:
|
|
|
|
tail_part = '?'.join((tail_part, query))
|
|
|
|
|
2012-04-11 15:34:32 -03:00
|
|
|
splitpath = ('/' + '/'.join(head_parts), tail_part)
|
|
|
|
collapsed_path = "/".join(splitpath)
|
|
|
|
|
|
|
|
return collapsed_path
|
|
|
|
|
2009-04-11 17:12:10 -03:00
|
|
|
|
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
nobody = None
|
|
|
|
|
|
|
|
def nobody_uid():
|
|
|
|
"""Internal routine to get nobody's uid"""
|
|
|
|
global nobody
|
|
|
|
if nobody:
|
|
|
|
return nobody
|
|
|
|
try:
|
|
|
|
import pwd
|
2013-07-04 18:43:24 -03:00
|
|
|
except ImportError:
|
2008-05-26 13:32:26 -03:00
|
|
|
return -1
|
|
|
|
try:
|
|
|
|
nobody = pwd.getpwnam('nobody')[2]
|
|
|
|
except KeyError:
|
2010-12-04 06:39:14 -04:00
|
|
|
nobody = 1 + max(x[2] for x in pwd.getpwall())
|
2008-05-26 13:32:26 -03:00
|
|
|
return nobody
|
|
|
|
|
|
|
|
|
|
|
|
def executable(path):
|
|
|
|
"""Test for executable file."""
|
2011-06-20 12:45:54 -03:00
|
|
|
return os.access(path, os.X_OK)
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
|
|
|
|
class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
|
|
|
|
|
|
|
|
"""Complete HTTP server with GET, HEAD and POST commands.
|
|
|
|
|
|
|
|
GET and HEAD also support running CGI scripts.
|
|
|
|
|
|
|
|
The POST command is *only* implemented for CGI scripts.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2023-09-15 18:26:45 -03:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
import warnings
|
|
|
|
warnings._deprecated("http.server.CGIHTTPRequestHandler",
|
|
|
|
remove=(3, 15))
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
# Determine platform specifics
|
|
|
|
have_fork = hasattr(os, 'fork')
|
|
|
|
|
|
|
|
# Make rfile unbuffered -- we need to read one line and then pass
|
|
|
|
# the rest to a subprocess, so we can't use buffered input.
|
|
|
|
rbufsize = 0
|
|
|
|
|
|
|
|
def do_POST(self):
|
|
|
|
"""Serve a POST request.
|
|
|
|
|
|
|
|
This is only implemented for CGI scripts.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
if self.is_cgi():
|
|
|
|
self.run_cgi()
|
|
|
|
else:
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.NOT_IMPLEMENTED,
|
|
|
|
"Can only POST to CGI scripts")
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
def send_head(self):
|
|
|
|
"""Version of send_head that support CGI scripts"""
|
|
|
|
if self.is_cgi():
|
|
|
|
return self.run_cgi()
|
|
|
|
else:
|
|
|
|
return SimpleHTTPRequestHandler.send_head(self)
|
|
|
|
|
|
|
|
def is_cgi(self):
|
|
|
|
"""Test whether self.path corresponds to a CGI script.
|
|
|
|
|
2009-04-11 17:12:10 -03:00
|
|
|
Returns True and updates the cgi_info attribute to the tuple
|
|
|
|
(dir, rest) if self.path requires running a CGI script.
|
|
|
|
Returns False otherwise.
|
2008-05-26 13:32:26 -03:00
|
|
|
|
2009-05-08 17:54:42 -03:00
|
|
|
If any exception is raised, the caller should assume that
|
|
|
|
self.path was rejected as invalid and act accordingly.
|
|
|
|
|
2009-04-11 17:12:10 -03:00
|
|
|
The default implementation tests whether the normalized url
|
|
|
|
path begins with one of the strings in self.cgi_directories
|
|
|
|
(and the next character is a '/' or the end of the string).
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
"""
|
2015-10-03 02:55:46 -03:00
|
|
|
collapsed_path = _url_collapse_path(self.path)
|
2012-04-11 15:34:32 -03:00
|
|
|
dir_sep = collapsed_path.find('/', 1)
|
2019-11-22 05:13:05 -04:00
|
|
|
while dir_sep > 0 and not collapsed_path[:dir_sep] in self.cgi_directories:
|
|
|
|
dir_sep = collapsed_path.find('/', dir_sep+1)
|
|
|
|
if dir_sep > 0:
|
|
|
|
head, tail = collapsed_path[:dir_sep], collapsed_path[dir_sep+1:]
|
2012-04-10 16:15:28 -03:00
|
|
|
self.cgi_info = head, tail
|
2009-04-11 17:12:10 -03:00
|
|
|
return True
|
2008-05-26 13:32:26 -03:00
|
|
|
return False
|
|
|
|
|
2012-04-11 15:34:32 -03:00
|
|
|
|
2008-05-26 13:32:26 -03:00
|
|
|
cgi_directories = ['/cgi-bin', '/htbin']
|
|
|
|
|
|
|
|
def is_executable(self, path):
|
|
|
|
"""Test whether argument path is an executable file."""
|
|
|
|
return executable(path)
|
|
|
|
|
|
|
|
def is_python(self, path):
|
|
|
|
"""Test whether argument path is a Python script."""
|
|
|
|
head, tail = os.path.splitext(path)
|
|
|
|
return tail.lower() in (".py", ".pyw")
|
|
|
|
|
|
|
|
def run_cgi(self):
|
|
|
|
"""Execute a CGI script."""
|
|
|
|
dir, rest = self.cgi_info
|
2014-07-13 02:06:26 -03:00
|
|
|
path = dir + '/' + rest
|
|
|
|
i = path.find('/', len(dir)+1)
|
2008-05-26 13:32:26 -03:00
|
|
|
while i >= 0:
|
2014-07-13 02:06:26 -03:00
|
|
|
nextdir = path[:i]
|
|
|
|
nextrest = path[i+1:]
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
scriptdir = self.translate_path(nextdir)
|
|
|
|
if os.path.isdir(scriptdir):
|
|
|
|
dir, rest = nextdir, nextrest
|
2014-07-13 02:06:26 -03:00
|
|
|
i = path.find('/', len(dir)+1)
|
2008-05-26 13:32:26 -03:00
|
|
|
else:
|
|
|
|
break
|
|
|
|
|
|
|
|
# find an explicit query string, if present.
|
2015-10-03 02:38:07 -03:00
|
|
|
rest, _, query = rest.partition('?')
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
# dissect the part after the directory name into a script name &
|
|
|
|
# a possible additional path, to be stored in PATH_INFO.
|
|
|
|
i = rest.find('/')
|
|
|
|
if i >= 0:
|
|
|
|
script, rest = rest[:i], rest[i:]
|
|
|
|
else:
|
|
|
|
script, rest = rest, ''
|
|
|
|
|
|
|
|
scriptname = dir + '/' + script
|
|
|
|
scriptfile = self.translate_path(scriptname)
|
|
|
|
if not os.path.exists(scriptfile):
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.NOT_FOUND,
|
|
|
|
"No such CGI script (%r)" % scriptname)
|
2008-05-26 13:32:26 -03:00
|
|
|
return
|
|
|
|
if not os.path.isfile(scriptfile):
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.FORBIDDEN,
|
|
|
|
"CGI script is not a plain file (%r)" % scriptname)
|
2008-05-26 13:32:26 -03:00
|
|
|
return
|
|
|
|
ispy = self.is_python(scriptname)
|
2011-06-20 12:45:54 -03:00
|
|
|
if self.have_fork or not ispy:
|
2008-05-26 13:32:26 -03:00
|
|
|
if not self.is_executable(scriptfile):
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_error(
|
|
|
|
HTTPStatus.FORBIDDEN,
|
|
|
|
"CGI script is not executable (%r)" % scriptname)
|
2008-05-26 13:32:26 -03:00
|
|
|
return
|
|
|
|
|
|
|
|
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
|
|
|
|
# XXX Much of the following could be prepared ahead of time!
|
2010-10-03 14:55:45 -03:00
|
|
|
env = copy.deepcopy(os.environ)
|
2008-05-26 13:32:26 -03:00
|
|
|
env['SERVER_SOFTWARE'] = self.version_string()
|
|
|
|
env['SERVER_NAME'] = self.server.server_name
|
|
|
|
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
|
|
|
|
env['SERVER_PROTOCOL'] = self.protocol_version
|
|
|
|
env['SERVER_PORT'] = str(self.server.server_port)
|
|
|
|
env['REQUEST_METHOD'] = self.command
|
2008-06-18 17:49:58 -03:00
|
|
|
uqrest = urllib.parse.unquote(rest)
|
2008-05-26 13:32:26 -03:00
|
|
|
env['PATH_INFO'] = uqrest
|
|
|
|
env['PATH_TRANSLATED'] = self.translate_path(uqrest)
|
|
|
|
env['SCRIPT_NAME'] = scriptname
|
2020-12-02 23:48:14 -04:00
|
|
|
env['QUERY_STRING'] = query
|
2008-05-26 13:32:26 -03:00
|
|
|
env['REMOTE_ADDR'] = self.client_address[0]
|
2008-06-12 01:06:45 -03:00
|
|
|
authorization = self.headers.get("authorization")
|
2008-05-26 13:32:26 -03:00
|
|
|
if authorization:
|
|
|
|
authorization = authorization.split()
|
|
|
|
if len(authorization) == 2:
|
|
|
|
import base64, binascii
|
|
|
|
env['AUTH_TYPE'] = authorization[0]
|
|
|
|
if authorization[0].lower() == "basic":
|
|
|
|
try:
|
|
|
|
authorization = authorization[1].encode('ascii')
|
2009-06-04 06:42:55 -03:00
|
|
|
authorization = base64.decodebytes(authorization).\
|
2008-05-26 13:32:26 -03:00
|
|
|
decode('ascii')
|
|
|
|
except (binascii.Error, UnicodeError):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
authorization = authorization.split(':')
|
|
|
|
if len(authorization) == 2:
|
|
|
|
env['REMOTE_USER'] = authorization[0]
|
|
|
|
# XXX REMOTE_IDENT
|
2008-06-12 01:06:45 -03:00
|
|
|
if self.headers.get('content-type') is None:
|
|
|
|
env['CONTENT_TYPE'] = self.headers.get_content_type()
|
2008-05-26 13:32:26 -03:00
|
|
|
else:
|
2008-06-12 01:06:45 -03:00
|
|
|
env['CONTENT_TYPE'] = self.headers['content-type']
|
|
|
|
length = self.headers.get('content-length')
|
2008-05-26 13:32:26 -03:00
|
|
|
if length:
|
|
|
|
env['CONTENT_LENGTH'] = length
|
2008-06-12 01:06:45 -03:00
|
|
|
referer = self.headers.get('referer')
|
2008-05-26 13:32:26 -03:00
|
|
|
if referer:
|
|
|
|
env['HTTP_REFERER'] = referer
|
2020-12-05 09:26:24 -04:00
|
|
|
accept = self.headers.get_all('accept', ())
|
2008-05-26 13:32:26 -03:00
|
|
|
env['HTTP_ACCEPT'] = ','.join(accept)
|
2008-06-12 01:06:45 -03:00
|
|
|
ua = self.headers.get('user-agent')
|
2008-05-26 13:32:26 -03:00
|
|
|
if ua:
|
|
|
|
env['HTTP_USER_AGENT'] = ua
|
2008-06-12 01:06:45 -03:00
|
|
|
co = filter(None, self.headers.get_all('cookie', []))
|
2010-07-31 18:54:24 -03:00
|
|
|
cookie_str = ', '.join(co)
|
|
|
|
if cookie_str:
|
|
|
|
env['HTTP_COOKIE'] = cookie_str
|
2008-05-26 13:32:26 -03:00
|
|
|
# XXX Other HTTP_* headers
|
|
|
|
# Since we're setting the env in the parent, provide empty
|
|
|
|
# values to override previously set values
|
|
|
|
for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
|
|
|
|
'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
|
|
|
|
env.setdefault(k, "")
|
|
|
|
|
2014-12-23 10:28:28 -04:00
|
|
|
self.send_response(HTTPStatus.OK, "Script output follows")
|
2011-05-09 12:25:02 -03:00
|
|
|
self.flush_headers()
|
2008-05-26 13:32:26 -03:00
|
|
|
|
|
|
|
decoded_query = query.replace('+', ' ')
|
|
|
|
|
|
|
|
if self.have_fork:
|
|
|
|
# Unix -- fork as we should
|
|
|
|
args = [script]
|
|
|
|
if '=' not in decoded_query:
|
|
|
|
args.append(decoded_query)
|
|
|
|
nobody = nobody_uid()
|
|
|
|
self.wfile.flush() # Always flush before forking
|
|
|
|
pid = os.fork()
|
|
|
|
if pid != 0:
|
|
|
|
# Parent
|
|
|
|
pid, sts = os.waitpid(pid, 0)
|
|
|
|
# throw away additional data [see bug #427345]
|
|
|
|
while select.select([self.rfile], [], [], 0)[0]:
|
|
|
|
if not self.rfile.read(1):
|
|
|
|
break
|
2020-04-01 22:42:05 -03:00
|
|
|
exitcode = os.waitstatus_to_exitcode(sts)
|
|
|
|
if exitcode:
|
|
|
|
self.log_error(f"CGI script exit code {exitcode}")
|
2008-05-26 13:32:26 -03:00
|
|
|
return
|
|
|
|
# Child
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
os.setuid(nobody)
|
2012-12-18 16:02:39 -04:00
|
|
|
except OSError:
|
2008-05-26 13:32:26 -03:00
|
|
|
pass
|
|
|
|
os.dup2(self.rfile.fileno(), 0)
|
|
|
|
os.dup2(self.wfile.fileno(), 1)
|
2010-10-03 14:55:45 -03:00
|
|
|
os.execve(scriptfile, args, env)
|
2008-05-26 13:32:26 -03:00
|
|
|
except:
|
|
|
|
self.server.handle_error(self.request, self.client_address)
|
|
|
|
os._exit(127)
|
|
|
|
|
2008-06-18 19:19:22 -03:00
|
|
|
else:
|
|
|
|
# Non-Unix -- use subprocess
|
|
|
|
import subprocess
|
2009-11-11 00:17:53 -04:00
|
|
|
cmdline = [scriptfile]
|
2008-05-26 13:32:26 -03:00
|
|
|
if self.is_python(scriptfile):
|
|
|
|
interp = sys.executable
|
|
|
|
if interp.lower().endswith("w.exe"):
|
|
|
|
# On Windows, use python.exe, not pythonw.exe
|
|
|
|
interp = interp[:-5] + interp[-4:]
|
2009-11-11 00:17:53 -04:00
|
|
|
cmdline = [interp, '-u'] + cmdline
|
|
|
|
if '=' not in query:
|
|
|
|
cmdline.append(query)
|
|
|
|
self.log_message("command: %s", subprocess.list2cmdline(cmdline))
|
2008-05-26 13:32:26 -03:00
|
|
|
try:
|
|
|
|
nbytes = int(length)
|
|
|
|
except (TypeError, ValueError):
|
|
|
|
nbytes = 0
|
2008-06-18 19:19:22 -03:00
|
|
|
p = subprocess.Popen(cmdline,
|
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
stdout=subprocess.PIPE,
|
2010-10-03 14:55:45 -03:00
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
env = env
|
2008-06-18 19:19:22 -03:00
|
|
|
)
|
2008-05-26 13:32:26 -03:00
|
|
|
if self.command.lower() == "post" and nbytes > 0:
|
|
|
|
data = self.rfile.read(nbytes)
|
2008-06-18 19:19:22 -03:00
|
|
|
else:
|
|
|
|
data = None
|
2008-05-26 13:32:26 -03:00
|
|
|
# throw away additional data [see bug #427345]
|
|
|
|
while select.select([self.rfile._sock], [], [], 0)[0]:
|
|
|
|
if not self.rfile._sock.recv(1):
|
|
|
|
break
|
2008-06-18 19:19:22 -03:00
|
|
|
stdout, stderr = p.communicate(data)
|
|
|
|
self.wfile.write(stdout)
|
|
|
|
if stderr:
|
|
|
|
self.log_error('%s', stderr)
|
2010-11-05 12:04:48 -03:00
|
|
|
p.stderr.close()
|
|
|
|
p.stdout.close()
|
2008-06-18 19:19:22 -03:00
|
|
|
status = p.returncode
|
|
|
|
if status:
|
|
|
|
self.log_error("CGI script exit status %#x", status)
|
2008-05-26 13:32:26 -03:00
|
|
|
else:
|
|
|
|
self.log_message("CGI script exited OK")
|
|
|
|
|
|
|
|
|
2019-02-07 09:22:45 -04:00
|
|
|
def _get_best_family(*address):
|
|
|
|
infos = socket.getaddrinfo(
|
|
|
|
*address,
|
|
|
|
type=socket.SOCK_STREAM,
|
|
|
|
flags=socket.AI_PASSIVE,
|
|
|
|
)
|
|
|
|
family, type, proto, canonname, sockaddr = next(iter(infos))
|
|
|
|
return family, sockaddr
|
|
|
|
|
|
|
|
|
2013-09-15 13:37:27 -03:00
|
|
|
def test(HandlerClass=BaseHTTPRequestHandler,
|
2018-05-29 17:10:30 -03:00
|
|
|
ServerClass=ThreadingHTTPServer,
|
2019-02-07 09:22:45 -04:00
|
|
|
protocol="HTTP/1.0", port=8000, bind=None):
|
1995-08-04 01:00:20 -03:00
|
|
|
"""Test the HTTP request handler class.
|
|
|
|
|
2015-08-16 21:18:35 -03:00
|
|
|
This runs an HTTP server on port 8000 (or the port argument).
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
"""
|
2019-02-07 09:22:45 -04:00
|
|
|
ServerClass.address_family, addr = _get_best_family(bind, port)
|
2002-03-17 14:37:22 -04:00
|
|
|
HandlerClass.protocol_version = protocol
|
2019-02-07 09:22:45 -04:00
|
|
|
with ServerClass(addr, HandlerClass) as httpd:
|
|
|
|
host, port = httpd.socket.getsockname()[:2]
|
|
|
|
url_host = f'[{host}]' if ':' in host else host
|
|
|
|
print(
|
|
|
|
f"Serving HTTP on {host} port {port} "
|
|
|
|
f"(http://{url_host}:{port}/) ..."
|
|
|
|
)
|
2016-04-12 21:36:52 -03:00
|
|
|
try:
|
|
|
|
httpd.serve_forever()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
print("\nKeyboard interrupt received, exiting.")
|
|
|
|
sys.exit(0)
|
1995-08-04 01:00:20 -03:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2017-05-04 02:17:47 -03:00
|
|
|
import argparse
|
2022-02-03 11:51:05 -04:00
|
|
|
import contextlib
|
2017-05-04 02:17:47 -03:00
|
|
|
|
2012-06-03 05:15:54 -03:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('--cgi', action='store_true',
|
2022-02-03 11:51:05 -04:00
|
|
|
help='run as CGI server')
|
2022-05-02 19:28:45 -03:00
|
|
|
parser.add_argument('-b', '--bind', metavar='ADDRESS',
|
|
|
|
help='bind to this address '
|
2022-02-03 11:51:05 -04:00
|
|
|
'(default: all interfaces)')
|
2022-05-02 19:28:45 -03:00
|
|
|
parser.add_argument('-d', '--directory', default=os.getcwd(),
|
|
|
|
help='serve this directory '
|
2022-02-03 11:51:05 -04:00
|
|
|
'(default: current directory)')
|
2022-05-02 19:28:45 -03:00
|
|
|
parser.add_argument('-p', '--protocol', metavar='VERSION',
|
|
|
|
default='HTTP/1.0',
|
|
|
|
help='conform to this HTTP version '
|
|
|
|
'(default: %(default)s)')
|
|
|
|
parser.add_argument('port', default=8000, type=int, nargs='?',
|
|
|
|
help='bind to this port '
|
|
|
|
'(default: %(default)s)')
|
2012-06-03 05:15:54 -03:00
|
|
|
args = parser.parse_args()
|
|
|
|
if args.cgi:
|
2013-09-15 13:37:27 -03:00
|
|
|
handler_class = CGIHTTPRequestHandler
|
2012-06-03 05:15:54 -03:00
|
|
|
else:
|
2022-02-03 11:51:05 -04:00
|
|
|
handler_class = SimpleHTTPRequestHandler
|
2020-01-05 23:32:19 -04:00
|
|
|
|
|
|
|
# ensure dual-stack is not disabled; ref #38907
|
|
|
|
class DualStackServer(ThreadingHTTPServer):
|
2022-02-03 11:51:05 -04:00
|
|
|
|
2020-01-05 23:32:19 -04:00
|
|
|
def server_bind(self):
|
2020-01-06 08:59:36 -04:00
|
|
|
# suppress exception when protocol is IPv4
|
|
|
|
with contextlib.suppress(Exception):
|
|
|
|
self.socket.setsockopt(
|
|
|
|
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
|
2020-01-05 23:32:19 -04:00
|
|
|
return super().server_bind()
|
|
|
|
|
2022-02-03 11:51:05 -04:00
|
|
|
def finish_request(self, request, client_address):
|
|
|
|
self.RequestHandlerClass(request, client_address, self,
|
|
|
|
directory=args.directory)
|
|
|
|
|
2020-01-05 23:32:19 -04:00
|
|
|
test(
|
|
|
|
HandlerClass=handler_class,
|
|
|
|
ServerClass=DualStackServer,
|
|
|
|
port=args.port,
|
|
|
|
bind=args.bind,
|
2022-05-02 19:28:45 -03:00
|
|
|
protocol=args.protocol,
|
2020-01-05 23:32:19 -04:00
|
|
|
)
|