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