2014-09-30 16:15:32 +00:00
|
|
|
"""HTTP/1.1 client library
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
<intro stuff goes here>
|
|
|
|
<other stuff, too>
|
|
|
|
|
|
|
|
HTTPConnection goes through a number of "states", which define when a client
|
|
|
|
may legally make another request or fetch the response for a particular
|
|
|
|
request. This diagram details these state transitions:
|
|
|
|
|
|
|
|
(null)
|
|
|
|
|
|
|
|
|
| HTTPConnection()
|
|
|
|
v
|
|
|
|
Idle
|
|
|
|
|
|
|
|
|
| putrequest()
|
|
|
|
v
|
|
|
|
Request-started
|
|
|
|
|
|
|
|
|
| ( putheader() )* endheaders()
|
|
|
|
v
|
|
|
|
Request-sent
|
2015-11-25 01:25:01 +00:00
|
|
|
|\_____________________________
|
|
|
|
| | getresponse() raises
|
|
|
|
| response = getresponse() | ConnectionError
|
|
|
|
v v
|
|
|
|
Unread-response Idle
|
|
|
|
[Response-headers-read]
|
2013-10-11 17:28:32 +00:00
|
|
|
|\____________________
|
|
|
|
| |
|
|
|
|
| response.read() | putrequest()
|
|
|
|
v v
|
|
|
|
Idle Req-started-unread-response
|
|
|
|
______/|
|
|
|
|
/ |
|
|
|
|
response.read() | | ( putheader() )* endheaders()
|
|
|
|
v v
|
|
|
|
Request-started Req-sent-unread-response
|
|
|
|
|
|
|
|
|
| response.read()
|
|
|
|
v
|
|
|
|
Request-sent
|
|
|
|
|
|
|
|
This diagram presents the following rules:
|
|
|
|
-- a second request may not be started until {response-headers-read}
|
|
|
|
-- a response [object] cannot be retrieved until {request-sent}
|
|
|
|
-- there is no differentiation between an unread response body and a
|
|
|
|
partially read response body
|
|
|
|
|
|
|
|
Note: this enforcement is applied by the HTTPConnection class. The
|
|
|
|
HTTPResponse class does not enforce this state machine, which
|
|
|
|
implies sophisticated clients may accelerate the request/response
|
|
|
|
pipeline. Caution should be taken, though: accelerating the states
|
|
|
|
beyond the above pattern may imply knowledge of the server's
|
|
|
|
connection-close behavior for certain requests. For example, it
|
|
|
|
is impossible to tell whether the server will close the connection
|
|
|
|
UNTIL the response headers have been read; this means that further
|
|
|
|
requests cannot be placed into the pipeline until it is known that
|
|
|
|
the server will NOT be closing the connection.
|
|
|
|
|
|
|
|
Logical State __state __response
|
|
|
|
------------- ------- ----------
|
|
|
|
Idle _CS_IDLE None
|
|
|
|
Request-started _CS_REQ_STARTED None
|
|
|
|
Request-sent _CS_REQ_SENT None
|
|
|
|
Unread-response _CS_IDLE <response_class>
|
|
|
|
Req-started-unread-response _CS_REQ_STARTED <response_class>
|
|
|
|
Req-sent-unread-response _CS_REQ_SENT <response_class>
|
|
|
|
"""
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
import email.parser
|
|
|
|
import email.message
|
2015-11-25 01:25:01 +00:00
|
|
|
import http
|
2014-09-30 16:15:32 +00:00
|
|
|
import io
|
2013-10-11 17:28:32 +00:00
|
|
|
import os
|
2015-11-25 01:25:01 +00:00
|
|
|
import re
|
2013-10-11 17:28:32 +00:00
|
|
|
import socket
|
2014-09-30 16:15:32 +00:00
|
|
|
import collections
|
|
|
|
from urllib.parse import urlsplit
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
# HTTPMessage, parse_headers(), and the HTTP status code constants are
|
|
|
|
# intentionally omitted for simplicity
|
2014-09-30 16:15:32 +00:00
|
|
|
__all__ = ["HTTPResponse", "HTTPConnection",
|
2013-10-11 17:28:32 +00:00
|
|
|
"HTTPException", "NotConnected", "UnknownProtocol",
|
|
|
|
"UnknownTransferEncoding", "UnimplementedFileMode",
|
|
|
|
"IncompleteRead", "InvalidURL", "ImproperConnectionState",
|
|
|
|
"CannotSendRequest", "CannotSendHeader", "ResponseNotReady",
|
2015-11-25 01:25:01 +00:00
|
|
|
"BadStatusLine", "LineTooLong", "RemoteDisconnected", "error",
|
|
|
|
"responses"]
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
HTTP_PORT = 80
|
|
|
|
HTTPS_PORT = 443
|
|
|
|
|
|
|
|
_UNKNOWN = 'UNKNOWN'
|
|
|
|
|
|
|
|
# connection states
|
|
|
|
_CS_IDLE = 'Idle'
|
|
|
|
_CS_REQ_STARTED = 'Request-started'
|
|
|
|
_CS_REQ_SENT = 'Request-sent'
|
|
|
|
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
# hack to maintain backwards compatibility
|
|
|
|
globals().update(http.HTTPStatus.__members__)
|
|
|
|
|
|
|
|
# another hack to maintain backwards compatibility
|
2013-10-11 17:28:32 +00:00
|
|
|
# Mapping status codes to official W3C names
|
2015-11-25 01:25:01 +00:00
|
|
|
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# maximal amount of data to read at one time in _safe_read
|
|
|
|
MAXAMOUNT = 1048576
|
|
|
|
|
|
|
|
# maximal line length when calling readline().
|
|
|
|
_MAXLINE = 65536
|
2014-09-30 16:15:32 +00:00
|
|
|
_MAXHEADERS = 100
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
# Header name/value ABNF (http://tools.ietf.org/html/rfc7230#section-3.2)
|
|
|
|
#
|
|
|
|
# VCHAR = %x21-7E
|
|
|
|
# obs-text = %x80-FF
|
|
|
|
# header-field = field-name ":" OWS field-value OWS
|
|
|
|
# field-name = token
|
|
|
|
# field-value = *( field-content / obs-fold )
|
|
|
|
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
|
|
|
# field-vchar = VCHAR / obs-text
|
|
|
|
#
|
|
|
|
# obs-fold = CRLF 1*( SP / HTAB )
|
|
|
|
# ; obsolete line folding
|
|
|
|
# ; see Section 3.2.4
|
|
|
|
|
|
|
|
# token = 1*tchar
|
|
|
|
#
|
|
|
|
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
|
|
|
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
|
|
|
# / DIGIT / ALPHA
|
|
|
|
# ; any VCHAR, except delimiters
|
|
|
|
#
|
|
|
|
# VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
|
|
|
|
|
|
|
|
# the patterns for both name and value are more leniant than RFC
|
|
|
|
# definitions to allow for backwards compatibility
|
|
|
|
_is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
|
|
|
|
_is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
|
|
|
|
|
|
|
|
# We always set the Content-Length header for these methods because some
|
|
|
|
# servers will otherwise respond with a 411
|
|
|
|
_METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
class HTTPMessage(email.message.Message):
|
|
|
|
# XXX The only usage of this method is in
|
|
|
|
# http.server.CGIHTTPRequestHandler. Maybe move the code there so
|
|
|
|
# that it doesn't need to be part of the public API. The API has
|
|
|
|
# never been defined so this could cause backwards compatibility
|
|
|
|
# issues.
|
|
|
|
|
|
|
|
def getallmatchingheaders(self, name):
|
|
|
|
"""Find all header lines matching a given header name.
|
|
|
|
|
|
|
|
Look through the list of headers and find all lines matching a given
|
|
|
|
header name (and their continuation lines). A list of the lines is
|
|
|
|
returned, without interpretation. If the header does not occur, an
|
|
|
|
empty list is returned. If the header occurs multiple times, all
|
|
|
|
occurrences are returned. Case is not important in the header name.
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
"""
|
2014-09-30 16:15:32 +00:00
|
|
|
name = name.lower() + ':'
|
|
|
|
n = len(name)
|
|
|
|
lst = []
|
|
|
|
hit = 0
|
|
|
|
for line in self.keys():
|
|
|
|
if line[:n].lower() == name:
|
|
|
|
hit = 1
|
|
|
|
elif not line[:1].isspace():
|
|
|
|
hit = 0
|
|
|
|
if hit:
|
|
|
|
lst.append(line)
|
|
|
|
return lst
|
|
|
|
|
|
|
|
def parse_headers(fp, _class=HTTPMessage):
|
|
|
|
"""Parses only RFC2822 headers from a file pointer.
|
|
|
|
|
|
|
|
email Parser wants to see strings rather than bytes.
|
|
|
|
But a TextIOWrapper around self.rfile would buffer too many bytes
|
|
|
|
from the stream, bytes which we later need to read as bytes.
|
|
|
|
So we read the correct bytes here, as bytes, for email Parser
|
|
|
|
to parse.
|
|
|
|
|
|
|
|
"""
|
|
|
|
headers = []
|
|
|
|
while True:
|
|
|
|
line = fp.readline(_MAXLINE + 1)
|
|
|
|
if len(line) > _MAXLINE:
|
|
|
|
raise LineTooLong("header line")
|
|
|
|
headers.append(line)
|
|
|
|
if len(headers) > _MAXHEADERS:
|
|
|
|
raise HTTPException("got more than %d headers" % _MAXHEADERS)
|
|
|
|
if line in (b'\r\n', b'\n', b''):
|
|
|
|
break
|
|
|
|
hstring = b''.join(headers).decode('iso-8859-1')
|
|
|
|
return email.parser.Parser(_class=_class).parsestr(hstring)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
class HTTPResponse(io.BufferedIOBase):
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
# The bytes from the socket object are iso-8859-1 strings.
|
|
|
|
# See RFC 2616 sec 2.2 which notes an exception for MIME-encoded
|
|
|
|
# text following RFC 2047. The basic status line parsing only
|
|
|
|
# accepts iso-8859-1.
|
|
|
|
|
|
|
|
def __init__(self, sock, debuglevel=0, method=None, url=None):
|
|
|
|
# If the response includes a content-length header, we need to
|
|
|
|
# make sure that the client doesn't read more than the
|
|
|
|
# specified number of bytes. If it does, it will block until
|
|
|
|
# the server times out and closes the connection. This will
|
|
|
|
# happen if a self.fp.read() is done (without a size) whether
|
|
|
|
# self.fp is buffered or not. So, no self.fp.read() by
|
|
|
|
# clients unless they know what they are doing.
|
|
|
|
self.fp = sock.makefile("rb")
|
2013-10-11 17:28:32 +00:00
|
|
|
self.debuglevel = debuglevel
|
|
|
|
self._method = method
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
# The HTTPResponse object is returned via urllib. The clients
|
|
|
|
# of http and urllib expect different attributes for the
|
|
|
|
# headers. headers is used here and supports urllib. msg is
|
|
|
|
# provided as a backwards compatibility layer for http
|
|
|
|
# clients.
|
|
|
|
|
|
|
|
self.headers = self.msg = None
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# from the Status-Line of the response
|
|
|
|
self.version = _UNKNOWN # HTTP-Version
|
|
|
|
self.status = _UNKNOWN # Status-Code
|
|
|
|
self.reason = _UNKNOWN # Reason-Phrase
|
|
|
|
|
|
|
|
self.chunked = _UNKNOWN # is "chunked" being used?
|
|
|
|
self.chunk_left = _UNKNOWN # bytes left to read in current chunk
|
|
|
|
self.length = _UNKNOWN # number of bytes left in response
|
|
|
|
self.will_close = _UNKNOWN # conn will close at end of response
|
|
|
|
|
|
|
|
def _read_status(self):
|
2014-09-30 16:15:32 +00:00
|
|
|
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
|
2013-10-11 17:28:32 +00:00
|
|
|
if len(line) > _MAXLINE:
|
2014-09-30 16:15:32 +00:00
|
|
|
raise LineTooLong("status line")
|
2013-10-11 17:28:32 +00:00
|
|
|
if self.debuglevel > 0:
|
2014-09-30 16:15:32 +00:00
|
|
|
print("reply:", repr(line))
|
2013-10-11 17:28:32 +00:00
|
|
|
if not line:
|
|
|
|
# Presumably, the server closed the connection before
|
|
|
|
# sending a valid response.
|
2015-11-25 01:25:01 +00:00
|
|
|
raise RemoteDisconnected("Remote end closed connection without"
|
|
|
|
" response")
|
2013-10-11 17:28:32 +00:00
|
|
|
try:
|
2014-09-30 16:15:32 +00:00
|
|
|
version, status, reason = line.split(None, 2)
|
2013-10-11 17:28:32 +00:00
|
|
|
except ValueError:
|
|
|
|
try:
|
2014-09-30 16:15:32 +00:00
|
|
|
version, status = line.split(None, 1)
|
2013-10-11 17:28:32 +00:00
|
|
|
reason = ""
|
|
|
|
except ValueError:
|
2014-09-30 16:15:32 +00:00
|
|
|
# empty version will cause next test to fail.
|
2013-10-11 17:28:32 +00:00
|
|
|
version = ""
|
2014-09-30 16:15:32 +00:00
|
|
|
if not version.startswith("HTTP/"):
|
|
|
|
self._close_conn()
|
|
|
|
raise BadStatusLine(line)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# The status code is a three-digit number
|
|
|
|
try:
|
|
|
|
status = int(status)
|
|
|
|
if status < 100 or status > 999:
|
|
|
|
raise BadStatusLine(line)
|
|
|
|
except ValueError:
|
|
|
|
raise BadStatusLine(line)
|
|
|
|
return version, status, reason
|
|
|
|
|
|
|
|
def begin(self):
|
2014-09-30 16:15:32 +00:00
|
|
|
if self.headers is not None:
|
2013-10-11 17:28:32 +00:00
|
|
|
# we've already started reading the response
|
|
|
|
return
|
|
|
|
|
|
|
|
# read until we get a non-100 response
|
|
|
|
while True:
|
|
|
|
version, status, reason = self._read_status()
|
|
|
|
if status != CONTINUE:
|
|
|
|
break
|
|
|
|
# skip the header from the 100 response
|
|
|
|
while True:
|
|
|
|
skip = self.fp.readline(_MAXLINE + 1)
|
|
|
|
if len(skip) > _MAXLINE:
|
|
|
|
raise LineTooLong("header line")
|
|
|
|
skip = skip.strip()
|
|
|
|
if not skip:
|
|
|
|
break
|
|
|
|
if self.debuglevel > 0:
|
2014-09-30 16:15:32 +00:00
|
|
|
print("header:", skip)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
self.code = self.status = status
|
2013-10-11 17:28:32 +00:00
|
|
|
self.reason = reason.strip()
|
2014-09-30 16:15:32 +00:00
|
|
|
if version in ("HTTP/1.0", "HTTP/0.9"):
|
|
|
|
# Some servers might still return "0.9", treat it as 1.0 anyway
|
2013-10-11 17:28:32 +00:00
|
|
|
self.version = 10
|
2014-09-30 16:15:32 +00:00
|
|
|
elif version.startswith("HTTP/1."):
|
2013-10-11 17:28:32 +00:00
|
|
|
self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
|
|
|
|
else:
|
|
|
|
raise UnknownProtocol(version)
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
self.headers = self.msg = parse_headers(self.fp)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
if self.debuglevel > 0:
|
2014-09-30 16:15:32 +00:00
|
|
|
for hdr in self.headers:
|
|
|
|
print("header:", hdr, end=" ")
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# are we using the chunked-style of transfer encoding?
|
2014-09-30 16:15:32 +00:00
|
|
|
tr_enc = self.headers.get("transfer-encoding")
|
2013-10-11 17:28:32 +00:00
|
|
|
if tr_enc and tr_enc.lower() == "chunked":
|
2014-09-30 16:15:32 +00:00
|
|
|
self.chunked = True
|
2013-10-11 17:28:32 +00:00
|
|
|
self.chunk_left = None
|
|
|
|
else:
|
2014-09-30 16:15:32 +00:00
|
|
|
self.chunked = False
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# will the connection close at the end of the response?
|
|
|
|
self.will_close = self._check_close()
|
|
|
|
|
|
|
|
# do we have a Content-Length?
|
|
|
|
# NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
|
2014-09-30 16:15:32 +00:00
|
|
|
self.length = None
|
|
|
|
length = self.headers.get("content-length")
|
|
|
|
|
|
|
|
# are we using the chunked-style of transfer encoding?
|
|
|
|
tr_enc = self.headers.get("transfer-encoding")
|
2013-10-11 17:28:32 +00:00
|
|
|
if length and not self.chunked:
|
|
|
|
try:
|
|
|
|
self.length = int(length)
|
|
|
|
except ValueError:
|
|
|
|
self.length = None
|
|
|
|
else:
|
|
|
|
if self.length < 0: # ignore nonsensical negative lengths
|
|
|
|
self.length = None
|
|
|
|
else:
|
|
|
|
self.length = None
|
|
|
|
|
|
|
|
# does the body have a fixed length? (of zero)
|
|
|
|
if (status == NO_CONTENT or status == NOT_MODIFIED or
|
|
|
|
100 <= status < 200 or # 1xx codes
|
2014-09-30 16:15:32 +00:00
|
|
|
self._method == "HEAD"):
|
2013-10-11 17:28:32 +00:00
|
|
|
self.length = 0
|
|
|
|
|
|
|
|
# if the connection remains open, and we aren't using chunked, and
|
|
|
|
# a content-length was not provided, then assume that the connection
|
|
|
|
# WILL close.
|
2014-09-30 16:15:32 +00:00
|
|
|
if (not self.will_close and
|
|
|
|
not self.chunked and
|
|
|
|
self.length is None):
|
|
|
|
self.will_close = True
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def _check_close(self):
|
2014-09-30 16:15:32 +00:00
|
|
|
conn = self.headers.get("connection")
|
2013-10-11 17:28:32 +00:00
|
|
|
if self.version == 11:
|
|
|
|
# An HTTP/1.1 proxy is assumed to stay open unless
|
|
|
|
# explicitly closed.
|
2014-09-30 16:15:32 +00:00
|
|
|
conn = self.headers.get("connection")
|
2013-10-11 17:28:32 +00:00
|
|
|
if conn and "close" in conn.lower():
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Some HTTP/1.0 implementations have support for persistent
|
|
|
|
# connections, using rules different than HTTP/1.1.
|
|
|
|
|
|
|
|
# For older HTTP, Keep-Alive indicates persistent connection.
|
2014-09-30 16:15:32 +00:00
|
|
|
if self.headers.get("keep-alive"):
|
2013-10-11 17:28:32 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
# At least Akamai returns a "Connection: Keep-Alive" header,
|
|
|
|
# which was supposed to be sent by the client.
|
|
|
|
if conn and "keep-alive" in conn.lower():
|
|
|
|
return False
|
|
|
|
|
|
|
|
# Proxy-Connection is a netscape hack.
|
2014-09-30 16:15:32 +00:00
|
|
|
pconn = self.headers.get("proxy-connection")
|
2013-10-11 17:28:32 +00:00
|
|
|
if pconn and "keep-alive" in pconn.lower():
|
|
|
|
return False
|
|
|
|
|
|
|
|
# otherwise, assume it will close
|
|
|
|
return True
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def _close_conn(self):
|
|
|
|
fp = self.fp
|
|
|
|
self.fp = None
|
|
|
|
fp.close()
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
def close(self):
|
2015-11-25 01:25:01 +00:00
|
|
|
try:
|
|
|
|
super().close() # set "closed" flag
|
|
|
|
finally:
|
|
|
|
if self.fp:
|
|
|
|
self._close_conn()
|
2014-09-30 16:15:32 +00:00
|
|
|
|
|
|
|
# These implementations are for the benefit of io.BufferedReader.
|
|
|
|
|
|
|
|
# XXX This class should probably be revised to act more like
|
|
|
|
# the "raw stream" that BufferedReader expects.
|
|
|
|
|
|
|
|
def flush(self):
|
|
|
|
super().flush()
|
2013-10-11 17:28:32 +00:00
|
|
|
if self.fp:
|
2014-09-30 16:15:32 +00:00
|
|
|
self.fp.flush()
|
|
|
|
|
|
|
|
def readable(self):
|
|
|
|
return True
|
|
|
|
|
|
|
|
# End of "raw stream" methods
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def isclosed(self):
|
2014-09-30 16:15:32 +00:00
|
|
|
"""True if the connection is closed."""
|
2013-10-11 17:28:32 +00:00
|
|
|
# NOTE: it is possible that we will not ever call self.close(). This
|
|
|
|
# case occurs when will_close is TRUE, length is None, and we
|
|
|
|
# read up to the last byte, but NOT past it.
|
|
|
|
#
|
|
|
|
# IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
|
|
|
|
# called, meaning self.isclosed() is meaningful.
|
|
|
|
return self.fp is None
|
|
|
|
|
|
|
|
def read(self, amt=None):
|
|
|
|
if self.fp is None:
|
2014-09-30 16:15:32 +00:00
|
|
|
return b""
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
if self._method == "HEAD":
|
|
|
|
self._close_conn()
|
|
|
|
return b""
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
if amt is not None:
|
2015-11-25 01:25:01 +00:00
|
|
|
# Amount is given, implement using readinto
|
|
|
|
b = bytearray(amt)
|
|
|
|
n = self.readinto(b)
|
|
|
|
return memoryview(b)[:n].tobytes()
|
2014-09-30 16:15:32 +00:00
|
|
|
else:
|
|
|
|
# Amount is not given (unbounded read) so we must check self.length
|
|
|
|
# and self.chunked
|
|
|
|
|
|
|
|
if self.chunked:
|
|
|
|
return self._readall_chunked()
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
if self.length is None:
|
|
|
|
s = self.fp.read()
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
s = self._safe_read(self.length)
|
|
|
|
except IncompleteRead:
|
2014-09-30 16:15:32 +00:00
|
|
|
self._close_conn()
|
2013-10-11 17:28:32 +00:00
|
|
|
raise
|
|
|
|
self.length = 0
|
2014-09-30 16:15:32 +00:00
|
|
|
self._close_conn() # we read everything
|
2013-10-11 17:28:32 +00:00
|
|
|
return s
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def readinto(self, b):
|
|
|
|
if self.fp is None:
|
|
|
|
return 0
|
|
|
|
|
|
|
|
if self._method == "HEAD":
|
|
|
|
self._close_conn()
|
|
|
|
return 0
|
|
|
|
|
|
|
|
if self.chunked:
|
|
|
|
return self._readinto_chunked(b)
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
if self.length is not None:
|
2014-09-30 16:15:32 +00:00
|
|
|
if len(b) > self.length:
|
2013-10-11 17:28:32 +00:00
|
|
|
# clip the read to the "end of response"
|
2014-09-30 16:15:32 +00:00
|
|
|
b = memoryview(b)[0:self.length]
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# we do not use _safe_read() here because this may be a .will_close
|
|
|
|
# connection, and the user is reading more bytes than will be provided
|
|
|
|
# (for example, reading in 1k chunks)
|
2014-09-30 16:15:32 +00:00
|
|
|
n = self.fp.readinto(b)
|
|
|
|
if not n and b:
|
2013-10-11 17:28:32 +00:00
|
|
|
# Ideally, we would raise IncompleteRead if the content-length
|
|
|
|
# wasn't satisfied, but it might break compatibility.
|
2014-09-30 16:15:32 +00:00
|
|
|
self._close_conn()
|
|
|
|
elif self.length is not None:
|
|
|
|
self.length -= n
|
2013-10-11 17:28:32 +00:00
|
|
|
if not self.length:
|
2014-09-30 16:15:32 +00:00
|
|
|
self._close_conn()
|
|
|
|
return n
|
|
|
|
|
|
|
|
def _read_next_chunk_size(self):
|
|
|
|
# Read the next chunk size from the file
|
|
|
|
line = self.fp.readline(_MAXLINE + 1)
|
|
|
|
if len(line) > _MAXLINE:
|
|
|
|
raise LineTooLong("chunk size")
|
|
|
|
i = line.find(b";")
|
|
|
|
if i >= 0:
|
|
|
|
line = line[:i] # strip chunk-extensions
|
|
|
|
try:
|
|
|
|
return int(line, 16)
|
|
|
|
except ValueError:
|
|
|
|
# close the connection as protocol synchronisation is
|
|
|
|
# probably lost
|
|
|
|
self._close_conn()
|
|
|
|
raise
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def _read_and_discard_trailer(self):
|
|
|
|
# read and discard trailer up to the CRLF terminator
|
|
|
|
### note: we shouldn't have any trailers!
|
|
|
|
while True:
|
|
|
|
line = self.fp.readline(_MAXLINE + 1)
|
|
|
|
if len(line) > _MAXLINE:
|
|
|
|
raise LineTooLong("trailer line")
|
|
|
|
if not line:
|
|
|
|
# a vanishingly small number of sites EOF without
|
|
|
|
# sending the trailer
|
|
|
|
break
|
|
|
|
if line in (b'\r\n', b'\n', b''):
|
|
|
|
break
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
def _get_chunk_left(self):
|
|
|
|
# return self.chunk_left, reading a new chunk if necessary.
|
|
|
|
# chunk_left == 0: at the end of the current chunk, need to close it
|
|
|
|
# chunk_left == None: No current chunk, should read next.
|
|
|
|
# This function returns non-zero or None if the last chunk has
|
|
|
|
# been read.
|
|
|
|
chunk_left = self.chunk_left
|
|
|
|
if not chunk_left: # Can be 0 or None
|
|
|
|
if chunk_left is not None:
|
|
|
|
# We are at the end of chunk. dicard chunk end
|
|
|
|
self._safe_read(2) # toss the CRLF at the end of the chunk
|
|
|
|
try:
|
|
|
|
chunk_left = self._read_next_chunk_size()
|
|
|
|
except ValueError:
|
|
|
|
raise IncompleteRead(b'')
|
|
|
|
if chunk_left == 0:
|
|
|
|
# last chunk: 1*("0") [ chunk-extension ] CRLF
|
|
|
|
self._read_and_discard_trailer()
|
|
|
|
# we read everything; close the "file"
|
|
|
|
self._close_conn()
|
|
|
|
chunk_left = None
|
|
|
|
self.chunk_left = chunk_left
|
|
|
|
return chunk_left
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def _readall_chunked(self):
|
2013-10-11 17:28:32 +00:00
|
|
|
assert self.chunked != _UNKNOWN
|
|
|
|
value = []
|
2015-11-25 01:25:01 +00:00
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
chunk_left = self._get_chunk_left()
|
|
|
|
if chunk_left is None:
|
|
|
|
break
|
|
|
|
value.append(self._safe_read(chunk_left))
|
|
|
|
self.chunk_left = 0
|
|
|
|
return b''.join(value)
|
|
|
|
except IncompleteRead:
|
|
|
|
raise IncompleteRead(b''.join(value))
|
2014-09-30 16:15:32 +00:00
|
|
|
|
|
|
|
def _readinto_chunked(self, b):
|
|
|
|
assert self.chunked != _UNKNOWN
|
|
|
|
total_bytes = 0
|
|
|
|
mvb = memoryview(b)
|
2015-11-25 01:25:01 +00:00
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
chunk_left = self._get_chunk_left()
|
|
|
|
if chunk_left is None:
|
|
|
|
return total_bytes
|
|
|
|
|
|
|
|
if len(mvb) <= chunk_left:
|
|
|
|
n = self._safe_readinto(mvb)
|
|
|
|
self.chunk_left = chunk_left - n
|
|
|
|
return total_bytes + n
|
|
|
|
|
|
|
|
temp_mvb = mvb[:chunk_left]
|
2014-09-30 16:15:32 +00:00
|
|
|
n = self._safe_readinto(temp_mvb)
|
|
|
|
mvb = mvb[n:]
|
|
|
|
total_bytes += n
|
2015-11-25 01:25:01 +00:00
|
|
|
self.chunk_left = 0
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
except IncompleteRead:
|
|
|
|
raise IncompleteRead(bytes(b[0:total_bytes]))
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def _safe_read(self, amt):
|
|
|
|
"""Read the number of bytes requested, compensating for partial reads.
|
|
|
|
|
|
|
|
Normally, we have a blocking socket, but a read() can be interrupted
|
|
|
|
by a signal (resulting in a partial read).
|
|
|
|
|
|
|
|
Note that we cannot distinguish between EOF and an interrupt when zero
|
|
|
|
bytes have been read. IncompleteRead() will be raised in this
|
|
|
|
situation.
|
|
|
|
|
|
|
|
This function should be used when <amt> bytes "should" be present for
|
|
|
|
reading. If the bytes are truly not available (due to EOF), then the
|
|
|
|
IncompleteRead exception can be used to detect the problem.
|
|
|
|
"""
|
|
|
|
s = []
|
|
|
|
while amt > 0:
|
|
|
|
chunk = self.fp.read(min(amt, MAXAMOUNT))
|
|
|
|
if not chunk:
|
2014-09-30 16:15:32 +00:00
|
|
|
raise IncompleteRead(b''.join(s), amt)
|
2013-10-11 17:28:32 +00:00
|
|
|
s.append(chunk)
|
|
|
|
amt -= len(chunk)
|
2014-09-30 16:15:32 +00:00
|
|
|
return b"".join(s)
|
|
|
|
|
|
|
|
def _safe_readinto(self, b):
|
|
|
|
"""Same as _safe_read, but for reading into a buffer."""
|
|
|
|
total_bytes = 0
|
|
|
|
mvb = memoryview(b)
|
|
|
|
while total_bytes < len(b):
|
|
|
|
if MAXAMOUNT < len(mvb):
|
|
|
|
temp_mvb = mvb[0:MAXAMOUNT]
|
|
|
|
n = self.fp.readinto(temp_mvb)
|
|
|
|
else:
|
|
|
|
n = self.fp.readinto(mvb)
|
|
|
|
if not n:
|
|
|
|
raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b))
|
|
|
|
mvb = mvb[n:]
|
|
|
|
total_bytes += n
|
|
|
|
return total_bytes
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
def read1(self, n=-1):
|
|
|
|
"""Read with at most one underlying system call. If at least one
|
|
|
|
byte is buffered, return that instead.
|
|
|
|
"""
|
|
|
|
if self.fp is None or self._method == "HEAD":
|
|
|
|
return b""
|
|
|
|
if self.chunked:
|
|
|
|
return self._read1_chunked(n)
|
|
|
|
try:
|
|
|
|
result = self.fp.read1(n)
|
|
|
|
except ValueError:
|
|
|
|
if n >= 0:
|
|
|
|
raise
|
|
|
|
# some implementations, like BufferedReader, don't support -1
|
|
|
|
# Read an arbitrarily selected largeish chunk.
|
|
|
|
result = self.fp.read1(16*1024)
|
|
|
|
if not result and n:
|
|
|
|
self._close_conn()
|
|
|
|
return result
|
|
|
|
|
|
|
|
def peek(self, n=-1):
|
|
|
|
# Having this enables IOBase.readline() to read more than one
|
|
|
|
# byte at a time
|
|
|
|
if self.fp is None or self._method == "HEAD":
|
|
|
|
return b""
|
|
|
|
if self.chunked:
|
|
|
|
return self._peek_chunked(n)
|
|
|
|
return self.fp.peek(n)
|
|
|
|
|
|
|
|
def readline(self, limit=-1):
|
|
|
|
if self.fp is None or self._method == "HEAD":
|
|
|
|
return b""
|
|
|
|
if self.chunked:
|
|
|
|
# Fallback to IOBase readline which uses peek() and read()
|
|
|
|
return super().readline(limit)
|
|
|
|
result = self.fp.readline(limit)
|
|
|
|
if not result and limit:
|
|
|
|
self._close_conn()
|
|
|
|
return result
|
|
|
|
|
|
|
|
def _read1_chunked(self, n):
|
|
|
|
# Strictly speaking, _get_chunk_left() may cause more than one read,
|
|
|
|
# but that is ok, since that is to satisfy the chunked protocol.
|
|
|
|
chunk_left = self._get_chunk_left()
|
|
|
|
if chunk_left is None or n == 0:
|
|
|
|
return b''
|
|
|
|
if not (0 <= n <= chunk_left):
|
|
|
|
n = chunk_left # if n is negative or larger than chunk_left
|
|
|
|
read = self.fp.read1(n)
|
|
|
|
self.chunk_left -= len(read)
|
|
|
|
if not read:
|
|
|
|
raise IncompleteRead(b"")
|
|
|
|
return read
|
|
|
|
|
|
|
|
def _peek_chunked(self, n):
|
|
|
|
# Strictly speaking, _get_chunk_left() may cause more than one read,
|
|
|
|
# but that is ok, since that is to satisfy the chunked protocol.
|
|
|
|
try:
|
|
|
|
chunk_left = self._get_chunk_left()
|
|
|
|
except IncompleteRead:
|
|
|
|
return b'' # peek doesn't worry about protocol
|
|
|
|
if chunk_left is None:
|
|
|
|
return b'' # eof
|
|
|
|
# peek is allowed to return more than requested. Just request the
|
|
|
|
# entire chunk, and truncate what we get.
|
|
|
|
return self.fp.peek(chunk_left)[:chunk_left]
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
def fileno(self):
|
|
|
|
return self.fp.fileno()
|
|
|
|
|
|
|
|
def getheader(self, name, default=None):
|
2014-09-30 16:15:32 +00:00
|
|
|
if self.headers is None:
|
2013-10-11 17:28:32 +00:00
|
|
|
raise ResponseNotReady()
|
2014-09-30 16:15:32 +00:00
|
|
|
headers = self.headers.get_all(name) or default
|
|
|
|
if isinstance(headers, str) or not hasattr(headers, '__iter__'):
|
|
|
|
return headers
|
|
|
|
else:
|
|
|
|
return ', '.join(headers)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def getheaders(self):
|
|
|
|
"""Return list of (header, value) tuples."""
|
2014-09-30 16:15:32 +00:00
|
|
|
if self.headers is None:
|
2013-10-11 17:28:32 +00:00
|
|
|
raise ResponseNotReady()
|
2014-09-30 16:15:32 +00:00
|
|
|
return list(self.headers.items())
|
|
|
|
|
|
|
|
# We override IOBase.__iter__ so that it doesn't check for closed-ness
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
# For compatibility with old-style urllib responses.
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def info(self):
|
|
|
|
return self.headers
|
|
|
|
|
|
|
|
def geturl(self):
|
|
|
|
return self.url
|
|
|
|
|
|
|
|
def getcode(self):
|
|
|
|
return self.status
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
class HTTPConnection:
|
|
|
|
|
|
|
|
_http_vsn = 11
|
|
|
|
_http_vsn_str = 'HTTP/1.1'
|
|
|
|
|
|
|
|
response_class = HTTPResponse
|
|
|
|
default_port = HTTP_PORT
|
|
|
|
auto_open = 1
|
|
|
|
debuglevel = 0
|
2014-09-30 16:15:32 +00:00
|
|
|
|
|
|
|
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
|
|
|
source_address=None):
|
2013-10-11 17:28:32 +00:00
|
|
|
self.timeout = timeout
|
|
|
|
self.source_address = source_address
|
|
|
|
self.sock = None
|
|
|
|
self._buffer = []
|
|
|
|
self.__response = None
|
|
|
|
self.__state = _CS_IDLE
|
|
|
|
self._method = None
|
|
|
|
self._tunnel_host = None
|
|
|
|
self._tunnel_port = None
|
|
|
|
self._tunnel_headers = {}
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
(self.host, self.port) = self._get_hostport(host, port)
|
|
|
|
|
|
|
|
# This is stored as an instance variable to allow unit
|
|
|
|
# tests to replace it with a suitable mockup
|
|
|
|
self._create_connection = socket.create_connection
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def set_tunnel(self, host, port=None, headers=None):
|
2014-09-30 16:15:32 +00:00
|
|
|
"""Set up host and port for HTTP CONNECT tunnelling.
|
|
|
|
|
|
|
|
In a connection that uses HTTP CONNECT tunneling, the host passed to the
|
|
|
|
constructor is used as a proxy server that relays all communication to
|
|
|
|
the endpoint passed to `set_tunnel`. This done by sending an HTTP
|
|
|
|
CONNECT request to the proxy server when the connection is established.
|
|
|
|
|
|
|
|
This method must be called before the HTML connection has been
|
|
|
|
established.
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
The headers argument should be a mapping of extra HTTP headers to send
|
|
|
|
with the CONNECT request.
|
2013-10-11 17:28:32 +00:00
|
|
|
"""
|
2014-09-30 16:15:32 +00:00
|
|
|
|
|
|
|
if self.sock:
|
|
|
|
raise RuntimeError("Can't set up tunnel for established connection")
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
self._tunnel_host, self._tunnel_port = self._get_hostport(host, port)
|
2013-10-11 17:28:32 +00:00
|
|
|
if headers:
|
|
|
|
self._tunnel_headers = headers
|
|
|
|
else:
|
|
|
|
self._tunnel_headers.clear()
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def _get_hostport(self, host, port):
|
2013-10-11 17:28:32 +00:00
|
|
|
if port is None:
|
|
|
|
i = host.rfind(':')
|
|
|
|
j = host.rfind(']') # ipv6 addresses have [...]
|
|
|
|
if i > j:
|
|
|
|
try:
|
|
|
|
port = int(host[i+1:])
|
|
|
|
except ValueError:
|
2014-09-30 16:15:32 +00:00
|
|
|
if host[i+1:] == "": # http://foo.com:/ == http://foo.com/
|
2013-10-11 17:28:32 +00:00
|
|
|
port = self.default_port
|
|
|
|
else:
|
|
|
|
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
|
|
|
|
host = host[:i]
|
|
|
|
else:
|
|
|
|
port = self.default_port
|
|
|
|
if host and host[0] == '[' and host[-1] == ']':
|
|
|
|
host = host[1:-1]
|
2014-09-30 16:15:32 +00:00
|
|
|
|
|
|
|
return (host, port)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def set_debuglevel(self, level):
|
|
|
|
self.debuglevel = level
|
|
|
|
|
|
|
|
def _tunnel(self):
|
2015-11-25 01:25:01 +00:00
|
|
|
connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self._tunnel_host,
|
|
|
|
self._tunnel_port)
|
2014-09-30 16:15:32 +00:00
|
|
|
connect_bytes = connect_str.encode("ascii")
|
|
|
|
self.send(connect_bytes)
|
|
|
|
for header, value in self._tunnel_headers.items():
|
|
|
|
header_str = "%s: %s\r\n" % (header, value)
|
|
|
|
header_bytes = header_str.encode("latin-1")
|
|
|
|
self.send(header_bytes)
|
|
|
|
self.send(b'\r\n')
|
|
|
|
|
|
|
|
response = self.response_class(self.sock, method=self._method)
|
2013-10-11 17:28:32 +00:00
|
|
|
(version, code, message) = response._read_status()
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
if code != http.HTTPStatus.OK:
|
2013-10-11 17:28:32 +00:00
|
|
|
self.close()
|
2014-09-30 16:15:32 +00:00
|
|
|
raise OSError("Tunnel connection failed: %d %s" % (code,
|
|
|
|
message.strip()))
|
2013-10-11 17:28:32 +00:00
|
|
|
while True:
|
|
|
|
line = response.fp.readline(_MAXLINE + 1)
|
|
|
|
if len(line) > _MAXLINE:
|
|
|
|
raise LineTooLong("header line")
|
|
|
|
if not line:
|
2014-09-30 16:15:32 +00:00
|
|
|
# for sites which EOF without sending a trailer
|
2013-10-11 17:28:32 +00:00
|
|
|
break
|
2014-09-30 16:15:32 +00:00
|
|
|
if line in (b'\r\n', b'\n', b''):
|
2013-10-11 17:28:32 +00:00
|
|
|
break
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
if self.debuglevel > 0:
|
|
|
|
print('header:', line.decode())
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
def connect(self):
|
|
|
|
"""Connect to the host and port specified in __init__."""
|
2015-11-25 01:25:01 +00:00
|
|
|
self.sock = self._create_connection(
|
|
|
|
(self.host,self.port), self.timeout, self.source_address)
|
|
|
|
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
if self._tunnel_host:
|
|
|
|
self._tunnel()
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
"""Close the connection to the HTTP server."""
|
|
|
|
self.__state = _CS_IDLE
|
2015-11-25 01:25:01 +00:00
|
|
|
try:
|
|
|
|
sock = self.sock
|
|
|
|
if sock:
|
|
|
|
self.sock = None
|
|
|
|
sock.close() # close it manually... there may be other refs
|
|
|
|
finally:
|
|
|
|
response = self.__response
|
|
|
|
if response:
|
|
|
|
self.__response = None
|
|
|
|
response.close()
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def send(self, data):
|
2014-09-30 16:15:32 +00:00
|
|
|
"""Send `data' to the server.
|
|
|
|
``data`` can be a string object, a bytes object, an array object, a
|
|
|
|
file-like object that supports a .read() method, or an iterable object.
|
|
|
|
"""
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
if self.sock is None:
|
|
|
|
if self.auto_open:
|
|
|
|
self.connect()
|
|
|
|
else:
|
|
|
|
raise NotConnected()
|
|
|
|
|
|
|
|
if self.debuglevel > 0:
|
2014-09-30 16:15:32 +00:00
|
|
|
print("send:", repr(data))
|
2013-10-11 17:28:32 +00:00
|
|
|
blocksize = 8192
|
2014-09-30 16:15:32 +00:00
|
|
|
if hasattr(data, "read") :
|
|
|
|
if self.debuglevel > 0:
|
|
|
|
print("sendIng a read()able")
|
|
|
|
encode = False
|
|
|
|
try:
|
|
|
|
mode = data.mode
|
|
|
|
except AttributeError:
|
|
|
|
# io.BytesIO and other file-like objects don't have a `mode`
|
|
|
|
# attribute.
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if "b" not in mode:
|
|
|
|
encode = True
|
|
|
|
if self.debuglevel > 0:
|
|
|
|
print("encoding file using iso-8859-1")
|
|
|
|
while 1:
|
2013-10-11 17:28:32 +00:00
|
|
|
datablock = data.read(blocksize)
|
2014-09-30 16:15:32 +00:00
|
|
|
if not datablock:
|
|
|
|
break
|
|
|
|
if encode:
|
|
|
|
datablock = datablock.encode("iso-8859-1")
|
|
|
|
self.sock.sendall(datablock)
|
|
|
|
return
|
|
|
|
try:
|
2013-10-11 17:28:32 +00:00
|
|
|
self.sock.sendall(data)
|
2014-09-30 16:15:32 +00:00
|
|
|
except TypeError:
|
|
|
|
if isinstance(data, collections.Iterable):
|
|
|
|
for d in data:
|
|
|
|
self.sock.sendall(d)
|
|
|
|
else:
|
|
|
|
raise TypeError("data should be a bytes-like object "
|
|
|
|
"or an iterable, got %r" % type(data))
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def _output(self, s):
|
|
|
|
"""Add a line of output to the current request buffer.
|
|
|
|
|
|
|
|
Assumes that the line does *not* end with \\r\\n.
|
|
|
|
"""
|
|
|
|
self._buffer.append(s)
|
|
|
|
|
|
|
|
def _send_output(self, message_body=None):
|
|
|
|
"""Send the currently buffered request and clear the buffer.
|
|
|
|
|
|
|
|
Appends an extra \\r\\n to the buffer.
|
|
|
|
A message_body may be specified, to be appended to the request.
|
|
|
|
"""
|
2014-09-30 16:15:32 +00:00
|
|
|
self._buffer.extend((b"", b""))
|
|
|
|
msg = b"\r\n".join(self._buffer)
|
2013-10-11 17:28:32 +00:00
|
|
|
del self._buffer[:]
|
2015-11-25 01:25:01 +00:00
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
self.send(msg)
|
|
|
|
if message_body is not None:
|
|
|
|
self.send(message_body)
|
|
|
|
|
|
|
|
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
|
|
|
|
"""Send a request to the server.
|
|
|
|
|
|
|
|
`method' specifies an HTTP request method, e.g. 'GET'.
|
|
|
|
`url' specifies the object being requested, e.g. '/index.html'.
|
|
|
|
`skip_host' if True does not add automatically a 'Host:' header
|
|
|
|
`skip_accept_encoding' if True does not add automatically an
|
|
|
|
'Accept-Encoding:' header
|
|
|
|
"""
|
|
|
|
|
|
|
|
# if a prior response has been completed, then forget about it.
|
|
|
|
if self.__response and self.__response.isclosed():
|
|
|
|
self.__response = None
|
|
|
|
|
|
|
|
|
|
|
|
# in certain cases, we cannot issue another request on this connection.
|
|
|
|
# this occurs when:
|
|
|
|
# 1) we are in the process of sending a request. (_CS_REQ_STARTED)
|
|
|
|
# 2) a response to a previous request has signalled that it is going
|
|
|
|
# to close the connection upon completion.
|
|
|
|
# 3) the headers for the previous response have not been read, thus
|
|
|
|
# we cannot determine whether point (2) is true. (_CS_REQ_SENT)
|
|
|
|
#
|
|
|
|
# if there is no prior response, then we can request at will.
|
|
|
|
#
|
|
|
|
# if point (2) is true, then we will have passed the socket to the
|
|
|
|
# response (effectively meaning, "there is no prior response"), and
|
|
|
|
# will open a new one when a new request is made.
|
|
|
|
#
|
|
|
|
# Note: if a prior response exists, then we *can* start a new request.
|
|
|
|
# We are not allowed to begin fetching the response to this new
|
|
|
|
# request, however, until that prior response is complete.
|
|
|
|
#
|
|
|
|
if self.__state == _CS_IDLE:
|
|
|
|
self.__state = _CS_REQ_STARTED
|
|
|
|
else:
|
2014-09-30 16:15:32 +00:00
|
|
|
raise CannotSendRequest(self.__state)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# Save the method we use, we need it later in the response phase
|
|
|
|
self._method = method
|
|
|
|
if not url:
|
|
|
|
url = '/'
|
2014-09-30 16:15:32 +00:00
|
|
|
request = '%s %s %s' % (method, url, self._http_vsn_str)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
# Non-ASCII characters should have been eliminated earlier
|
|
|
|
self._output(request.encode('ascii'))
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
if self._http_vsn == 11:
|
|
|
|
# Issue some standard headers for better HTTP/1.1 compliance
|
|
|
|
|
|
|
|
if not skip_host:
|
|
|
|
# this header is issued *only* for HTTP/1.1
|
|
|
|
# connections. more specifically, this means it is
|
|
|
|
# only issued when the client uses the new
|
|
|
|
# HTTPConnection() class. backwards-compat clients
|
|
|
|
# will be using HTTP/1.0 and those clients may be
|
|
|
|
# issuing this header themselves. we should NOT issue
|
|
|
|
# it twice; some web servers (such as Apache) barf
|
|
|
|
# when they see two Host: headers
|
|
|
|
|
|
|
|
# If we need a non-standard port,include it in the
|
|
|
|
# header. If the request is going through a proxy,
|
|
|
|
# but the host of the actual URL, not the host of the
|
|
|
|
# proxy.
|
|
|
|
|
|
|
|
netloc = ''
|
|
|
|
if url.startswith('http'):
|
|
|
|
nil, netloc, nil, nil, nil = urlsplit(url)
|
|
|
|
|
|
|
|
if netloc:
|
|
|
|
try:
|
|
|
|
netloc_enc = netloc.encode("ascii")
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
netloc_enc = netloc.encode("idna")
|
|
|
|
self.putheader('Host', netloc_enc)
|
|
|
|
else:
|
2014-09-30 16:15:32 +00:00
|
|
|
if self._tunnel_host:
|
|
|
|
host = self._tunnel_host
|
|
|
|
port = self._tunnel_port
|
|
|
|
else:
|
|
|
|
host = self.host
|
|
|
|
port = self.port
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
try:
|
2014-09-30 16:15:32 +00:00
|
|
|
host_enc = host.encode("ascii")
|
2013-10-11 17:28:32 +00:00
|
|
|
except UnicodeEncodeError:
|
2014-09-30 16:15:32 +00:00
|
|
|
host_enc = host.encode("idna")
|
|
|
|
|
|
|
|
# As per RFC 273, IPv6 address should be wrapped with []
|
|
|
|
# when used as Host header
|
|
|
|
|
|
|
|
if host.find(':') >= 0:
|
|
|
|
host_enc = b'[' + host_enc + b']'
|
|
|
|
|
|
|
|
if port == self.default_port:
|
2013-10-11 17:28:32 +00:00
|
|
|
self.putheader('Host', host_enc)
|
|
|
|
else:
|
2014-09-30 16:15:32 +00:00
|
|
|
host_enc = host_enc.decode("ascii")
|
|
|
|
self.putheader('Host', "%s:%s" % (host_enc, port))
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# note: we are assuming that clients will not attempt to set these
|
|
|
|
# headers since *this* library must deal with the
|
|
|
|
# consequences. this also means that when the supporting
|
|
|
|
# libraries are updated to recognize other forms, then this
|
|
|
|
# code should be changed (removed or updated).
|
|
|
|
|
|
|
|
# we only want a Content-Encoding of "identity" since we don't
|
|
|
|
# support encodings such as x-gzip or x-deflate.
|
|
|
|
if not skip_accept_encoding:
|
|
|
|
self.putheader('Accept-Encoding', 'identity')
|
|
|
|
|
|
|
|
# we can accept "chunked" Transfer-Encodings, but no others
|
|
|
|
# NOTE: no TE header implies *only* "chunked"
|
|
|
|
#self.putheader('TE', 'chunked')
|
|
|
|
|
|
|
|
# if TE is supplied in the header, then it must appear in a
|
|
|
|
# Connection header.
|
|
|
|
#self.putheader('Connection', 'TE')
|
|
|
|
|
|
|
|
else:
|
|
|
|
# For HTTP/1.0, the server will assume "not chunked"
|
|
|
|
pass
|
|
|
|
|
|
|
|
def putheader(self, header, *values):
|
|
|
|
"""Send a request header line to the server.
|
|
|
|
|
|
|
|
For example: h.putheader('Accept', 'text/html')
|
|
|
|
"""
|
|
|
|
if self.__state != _CS_REQ_STARTED:
|
|
|
|
raise CannotSendHeader()
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
if hasattr(header, 'encode'):
|
|
|
|
header = header.encode('ascii')
|
2015-11-25 01:25:01 +00:00
|
|
|
|
|
|
|
if not _is_legal_header_name(header):
|
|
|
|
raise ValueError('Invalid header name %r' % (header,))
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
values = list(values)
|
|
|
|
for i, one_value in enumerate(values):
|
|
|
|
if hasattr(one_value, 'encode'):
|
|
|
|
values[i] = one_value.encode('latin-1')
|
|
|
|
elif isinstance(one_value, int):
|
|
|
|
values[i] = str(one_value).encode('ascii')
|
2015-11-25 01:25:01 +00:00
|
|
|
|
|
|
|
if _is_illegal_header_value(values[i]):
|
|
|
|
raise ValueError('Invalid header value %r' % (values[i],))
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
value = b'\r\n\t'.join(values)
|
|
|
|
header = header + b': ' + value
|
|
|
|
self._output(header)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def endheaders(self, message_body=None):
|
|
|
|
"""Indicate that the last header line has been sent to the server.
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
This method sends the request to the server. The optional message_body
|
|
|
|
argument can be used to pass a message body associated with the
|
|
|
|
request. The message body will be sent in the same packet as the
|
|
|
|
message headers if it is a string, otherwise it is sent as a separate
|
|
|
|
packet.
|
2013-10-11 17:28:32 +00:00
|
|
|
"""
|
|
|
|
if self.__state == _CS_REQ_STARTED:
|
|
|
|
self.__state = _CS_REQ_SENT
|
|
|
|
else:
|
|
|
|
raise CannotSendHeader()
|
|
|
|
self._send_output(message_body)
|
|
|
|
|
|
|
|
def request(self, method, url, body=None, headers={}):
|
|
|
|
"""Send a complete request to the server."""
|
|
|
|
self._send_request(method, url, body, headers)
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
def _set_content_length(self, body, method):
|
|
|
|
# Set the content-length based on the body. If the body is "empty", we
|
|
|
|
# set Content-Length: 0 for methods that expect a body (RFC 7230,
|
|
|
|
# Section 3.3.2). If the body is set for other methods, we set the
|
|
|
|
# header provided we can figure out what the length is.
|
2013-10-11 17:28:32 +00:00
|
|
|
thelen = None
|
2015-11-25 01:25:01 +00:00
|
|
|
method_expects_body = method.upper() in _METHODS_EXPECTING_BODY
|
|
|
|
if body is None and method_expects_body:
|
|
|
|
thelen = '0'
|
|
|
|
elif body is not None:
|
2013-10-11 17:28:32 +00:00
|
|
|
try:
|
2015-11-25 01:25:01 +00:00
|
|
|
thelen = str(len(body))
|
|
|
|
except TypeError:
|
|
|
|
# If this is a file-like object, try to
|
|
|
|
# fstat its file descriptor
|
|
|
|
try:
|
|
|
|
thelen = str(os.fstat(body.fileno()).st_size)
|
|
|
|
except (AttributeError, OSError):
|
|
|
|
# Don't send a length if this failed
|
|
|
|
if self.debuglevel > 0: print("Cannot stat!!")
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
if thelen is not None:
|
|
|
|
self.putheader('Content-Length', thelen)
|
|
|
|
|
|
|
|
def _send_request(self, method, url, body, headers):
|
|
|
|
# Honor explicitly requested Host: and Accept-Encoding: headers.
|
|
|
|
header_names = dict.fromkeys([k.lower() for k in headers])
|
|
|
|
skips = {}
|
|
|
|
if 'host' in header_names:
|
|
|
|
skips['skip_host'] = 1
|
|
|
|
if 'accept-encoding' in header_names:
|
|
|
|
skips['skip_accept_encoding'] = 1
|
|
|
|
|
|
|
|
self.putrequest(method, url, **skips)
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
if 'content-length' not in header_names:
|
|
|
|
self._set_content_length(body, method)
|
2014-09-30 16:15:32 +00:00
|
|
|
for hdr, value in headers.items():
|
2013-10-11 17:28:32 +00:00
|
|
|
self.putheader(hdr, value)
|
2014-09-30 16:15:32 +00:00
|
|
|
if isinstance(body, str):
|
|
|
|
# RFC 2616 Section 3.7.1 says that text default has a
|
|
|
|
# default charset of iso-8859-1.
|
|
|
|
body = body.encode('iso-8859-1')
|
2013-10-11 17:28:32 +00:00
|
|
|
self.endheaders(body)
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
def getresponse(self):
|
|
|
|
"""Get the response from the server.
|
|
|
|
|
|
|
|
If the HTTPConnection is in the correct state, returns an
|
|
|
|
instance of HTTPResponse or of whatever object is returned by
|
|
|
|
class the response_class variable.
|
|
|
|
|
|
|
|
If a request has not been sent or if a previous response has
|
|
|
|
not be handled, ResponseNotReady is raised. If the HTTP
|
|
|
|
response indicates that the connection should be closed, then
|
|
|
|
it will be closed before the response is returned. When the
|
|
|
|
connection is closed, the underlying socket is closed.
|
|
|
|
"""
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
# if a prior response has been completed, then forget about it.
|
|
|
|
if self.__response and self.__response.isclosed():
|
|
|
|
self.__response = None
|
|
|
|
|
|
|
|
# if a prior response exists, then it must be completed (otherwise, we
|
|
|
|
# cannot read this response's header to determine the connection-close
|
|
|
|
# behavior)
|
|
|
|
#
|
|
|
|
# note: if a prior response existed, but was connection-close, then the
|
|
|
|
# socket and response were made independent of this HTTPConnection
|
|
|
|
# object since a new request requires that we open a whole new
|
|
|
|
# connection
|
|
|
|
#
|
|
|
|
# this means the prior response had one of two states:
|
|
|
|
# 1) will_close: this connection was reset and the prior socket and
|
|
|
|
# response operate independently
|
|
|
|
# 2) persistent: the response was retained and we await its
|
|
|
|
# isclosed() status to become true.
|
|
|
|
#
|
|
|
|
if self.__state != _CS_REQ_SENT or self.__response:
|
2014-09-30 16:15:32 +00:00
|
|
|
raise ResponseNotReady(self.__state)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
if self.debuglevel > 0:
|
2014-09-30 16:15:32 +00:00
|
|
|
response = self.response_class(self.sock, self.debuglevel,
|
|
|
|
method=self._method)
|
|
|
|
else:
|
|
|
|
response = self.response_class(self.sock, method=self._method)
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
try:
|
|
|
|
try:
|
|
|
|
response.begin()
|
|
|
|
except ConnectionError:
|
|
|
|
self.close()
|
|
|
|
raise
|
|
|
|
assert response.will_close != _UNKNOWN
|
|
|
|
self.__state = _CS_IDLE
|
|
|
|
|
|
|
|
if response.will_close:
|
|
|
|
# this effectively passes the connection to the response
|
|
|
|
self.close()
|
|
|
|
else:
|
|
|
|
# remember this, so we can tell when it is complete
|
|
|
|
self.__response = response
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
return response
|
|
|
|
except:
|
|
|
|
response.close()
|
|
|
|
raise
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
import ssl
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
class HTTPSConnection(HTTPConnection):
|
|
|
|
"This class allows communication via SSL."
|
|
|
|
|
|
|
|
default_port = HTTPS_PORT
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
# XXX Should key_file and cert_file be deprecated in favour of context?
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
def __init__(self, host, port=None, key_file=None, cert_file=None,
|
2014-09-30 16:15:32 +00:00
|
|
|
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
|
|
|
|
source_address=None, *, context=None,
|
|
|
|
check_hostname=None):
|
|
|
|
super(HTTPSConnection, self).__init__(host, port, timeout,
|
|
|
|
source_address)
|
2013-10-11 17:28:32 +00:00
|
|
|
self.key_file = key_file
|
|
|
|
self.cert_file = cert_file
|
2014-09-30 16:15:32 +00:00
|
|
|
if context is None:
|
2015-11-25 01:25:01 +00:00
|
|
|
context = ssl._create_default_https_context()
|
2014-09-30 16:15:32 +00:00
|
|
|
will_verify = context.verify_mode != ssl.CERT_NONE
|
|
|
|
if check_hostname is None:
|
2015-11-25 01:25:01 +00:00
|
|
|
check_hostname = context.check_hostname
|
|
|
|
if check_hostname and not will_verify:
|
2014-09-30 16:15:32 +00:00
|
|
|
raise ValueError("check_hostname needs a SSL context with "
|
|
|
|
"either CERT_OPTIONAL or CERT_REQUIRED")
|
|
|
|
if key_file or cert_file:
|
|
|
|
context.load_cert_chain(cert_file, key_file)
|
|
|
|
self._context = context
|
|
|
|
self._check_hostname = check_hostname
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
def connect(self):
|
|
|
|
"Connect to a host on a given (SSL) port."
|
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
super().connect()
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
if self._tunnel_host:
|
|
|
|
server_hostname = self._tunnel_host
|
|
|
|
else:
|
|
|
|
server_hostname = self.host
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
self.sock = self._context.wrap_socket(self.sock,
|
2015-11-25 01:25:01 +00:00
|
|
|
server_hostname=server_hostname)
|
2014-09-30 16:15:32 +00:00
|
|
|
if not self._context.check_hostname and self._check_hostname:
|
|
|
|
try:
|
|
|
|
ssl.match_hostname(self.sock.getpeercert(), server_hostname)
|
|
|
|
except Exception:
|
|
|
|
self.sock.shutdown(socket.SHUT_RDWR)
|
|
|
|
self.sock.close()
|
|
|
|
raise
|
2013-10-11 17:28:32 +00:00
|
|
|
|
2014-09-30 16:15:32 +00:00
|
|
|
__all__.append("HTTPSConnection")
|
2013-10-11 17:28:32 +00:00
|
|
|
|
|
|
|
class HTTPException(Exception):
|
|
|
|
# Subclasses that define an __init__ must call Exception.__init__
|
|
|
|
# or define self.args. Otherwise, str() will fail.
|
|
|
|
pass
|
|
|
|
|
|
|
|
class NotConnected(HTTPException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class InvalidURL(HTTPException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class UnknownProtocol(HTTPException):
|
|
|
|
def __init__(self, version):
|
|
|
|
self.args = version,
|
|
|
|
self.version = version
|
|
|
|
|
|
|
|
class UnknownTransferEncoding(HTTPException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class UnimplementedFileMode(HTTPException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class IncompleteRead(HTTPException):
|
|
|
|
def __init__(self, partial, expected=None):
|
|
|
|
self.args = partial,
|
|
|
|
self.partial = partial
|
|
|
|
self.expected = expected
|
|
|
|
def __repr__(self):
|
|
|
|
if self.expected is not None:
|
|
|
|
e = ', %i more expected' % self.expected
|
|
|
|
else:
|
|
|
|
e = ''
|
2015-11-25 01:25:01 +00:00
|
|
|
return '%s(%i bytes read%s)' % (self.__class__.__name__,
|
|
|
|
len(self.partial), e)
|
2013-10-11 17:28:32 +00:00
|
|
|
def __str__(self):
|
|
|
|
return repr(self)
|
|
|
|
|
|
|
|
class ImproperConnectionState(HTTPException):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class CannotSendRequest(ImproperConnectionState):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class CannotSendHeader(ImproperConnectionState):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class ResponseNotReady(ImproperConnectionState):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class BadStatusLine(HTTPException):
|
|
|
|
def __init__(self, line):
|
|
|
|
if not line:
|
|
|
|
line = repr(line)
|
|
|
|
self.args = line,
|
|
|
|
self.line = line
|
|
|
|
|
|
|
|
class LineTooLong(HTTPException):
|
|
|
|
def __init__(self, line_type):
|
|
|
|
HTTPException.__init__(self, "got more than %d bytes when reading %s"
|
|
|
|
% (_MAXLINE, line_type))
|
|
|
|
|
2015-11-25 01:25:01 +00:00
|
|
|
class RemoteDisconnected(ConnectionResetError, BadStatusLine):
|
|
|
|
def __init__(self, *pos, **kw):
|
|
|
|
BadStatusLine.__init__(self, "")
|
|
|
|
ConnectionResetError.__init__(self, *pos, **kw)
|
|
|
|
|
2013-10-11 17:28:32 +00:00
|
|
|
# for backwards compatibility
|
|
|
|
error = HTTPException
|