Path: blob/master/venv/Lib/site-packages/urllib3/connection.py
811 views
from __future__ import absolute_import1import re2import datetime3import logging4import os5import socket6from socket import error as SocketError, timeout as SocketTimeout7import warnings8from .packages import six9from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection10from .packages.six.moves.http_client import HTTPException # noqa: F4011112try: # Compiled with SSL?13import ssl1415BaseSSLError = ssl.SSLError16except (ImportError, AttributeError): # Platform-specific: No SSL.17ssl = None1819class BaseSSLError(BaseException):20pass212223try:24# Python 3: not a no-op, we're adding this to the namespace so it can be imported.25ConnectionError = ConnectionError26except NameError:27# Python 228class ConnectionError(Exception):29pass303132from .exceptions import (33NewConnectionError,34ConnectTimeoutError,35SubjectAltNameWarning,36SystemTimeWarning,37)38from .packages.ssl_match_hostname import match_hostname, CertificateError3940from .util.ssl_ import (41resolve_cert_reqs,42resolve_ssl_version,43assert_fingerprint,44create_urllib3_context,45ssl_wrap_socket,46)474849from .util import connection5051from ._collections import HTTPHeaderDict5253log = logging.getLogger(__name__)5455port_by_scheme = {"http": 80, "https": 443}5657# When it comes time to update this value as a part of regular maintenance58# (ie test_recent_date is failing) update it to ~6 months before the current date.59RECENT_DATE = datetime.date(2019, 1, 1)6061_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")626364class DummyConnection(object):65"""Used to detect a failed ConnectionCls import."""6667pass686970class HTTPConnection(_HTTPConnection, object):71"""72Based on httplib.HTTPConnection but provides an extra constructor73backwards-compatibility layer between older and newer Pythons.7475Additional keyword parameters are used to configure attributes of the connection.76Accepted parameters include:7778- ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`79- ``source_address``: Set the source address for the current connection.80- ``socket_options``: Set specific options on the underlying socket. If not specified, then81defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling82Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.8384For example, if you wish to enable TCP Keep Alive in addition to the defaults,85you might pass::8687HTTPConnection.default_socket_options + [88(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),89]9091Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).92"""9394default_port = port_by_scheme["http"]9596#: Disable Nagle's algorithm by default.97#: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``98default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]99100#: Whether this connection verifies the host's certificate.101is_verified = False102103def __init__(self, *args, **kw):104if not six.PY2:105kw.pop("strict", None)106107# Pre-set source_address.108self.source_address = kw.get("source_address")109110#: The socket options provided by the user. If no options are111#: provided, we use the default options.112self.socket_options = kw.pop("socket_options", self.default_socket_options)113114_HTTPConnection.__init__(self, *args, **kw)115116@property117def host(self):118"""119Getter method to remove any trailing dots that indicate the hostname is an FQDN.120121In general, SSL certificates don't include the trailing dot indicating a122fully-qualified domain name, and thus, they don't validate properly when123checked against a domain name that includes the dot. In addition, some124servers may not expect to receive the trailing dot when provided.125126However, the hostname with trailing dot is critical to DNS resolution; doing a127lookup with the trailing dot will properly only resolve the appropriate FQDN,128whereas a lookup without a trailing dot will search the system's search domain129list. Thus, it's important to keep the original host around for use only in130those cases where it's appropriate (i.e., when doing DNS lookup to establish the131actual TCP connection across which we're going to send HTTP requests).132"""133return self._dns_host.rstrip(".")134135@host.setter136def host(self, value):137"""138Setter for the `host` property.139140We assume that only urllib3 uses the _dns_host attribute; httplib itself141only uses `host`, and it seems reasonable that other libraries follow suit.142"""143self._dns_host = value144145def _new_conn(self):146""" Establish a socket connection and set nodelay settings on it.147148:return: New socket connection.149"""150extra_kw = {}151if self.source_address:152extra_kw["source_address"] = self.source_address153154if self.socket_options:155extra_kw["socket_options"] = self.socket_options156157try:158conn = connection.create_connection(159(self._dns_host, self.port), self.timeout, **extra_kw160)161162except SocketTimeout:163raise ConnectTimeoutError(164self,165"Connection to %s timed out. (connect timeout=%s)"166% (self.host, self.timeout),167)168169except SocketError as e:170raise NewConnectionError(171self, "Failed to establish a new connection: %s" % e172)173174return conn175176def _prepare_conn(self, conn):177self.sock = conn178# Google App Engine's httplib does not define _tunnel_host179if getattr(self, "_tunnel_host", None):180# TODO: Fix tunnel so it doesn't depend on self.sock state.181self._tunnel()182# Mark this connection as not reusable183self.auto_open = 0184185def connect(self):186conn = self._new_conn()187self._prepare_conn(conn)188189def putrequest(self, method, url, *args, **kwargs):190"""Send a request to the server"""191match = _CONTAINS_CONTROL_CHAR_RE.search(method)192if match:193raise ValueError(194"Method cannot contain non-token characters %r (found at least %r)"195% (method, match.group())196)197198return _HTTPConnection.putrequest(self, method, url, *args, **kwargs)199200def request_chunked(self, method, url, body=None, headers=None):201"""202Alternative to the common request method, which sends the203body with chunked encoding and not as one block204"""205headers = HTTPHeaderDict(headers if headers is not None else {})206skip_accept_encoding = "accept-encoding" in headers207skip_host = "host" in headers208self.putrequest(209method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host210)211for header, value in headers.items():212self.putheader(header, value)213if "transfer-encoding" not in headers:214self.putheader("Transfer-Encoding", "chunked")215self.endheaders()216217if body is not None:218stringish_types = six.string_types + (bytes,)219if isinstance(body, stringish_types):220body = (body,)221for chunk in body:222if not chunk:223continue224if not isinstance(chunk, bytes):225chunk = chunk.encode("utf8")226len_str = hex(len(chunk))[2:]227self.send(len_str.encode("utf-8"))228self.send(b"\r\n")229self.send(chunk)230self.send(b"\r\n")231232# After the if clause, to always have a closed body233self.send(b"0\r\n\r\n")234235236class HTTPSConnection(HTTPConnection):237default_port = port_by_scheme["https"]238239cert_reqs = None240ca_certs = None241ca_cert_dir = None242ca_cert_data = None243ssl_version = None244assert_fingerprint = None245246def __init__(247self,248host,249port=None,250key_file=None,251cert_file=None,252key_password=None,253strict=None,254timeout=socket._GLOBAL_DEFAULT_TIMEOUT,255ssl_context=None,256server_hostname=None,257**kw258):259260HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)261262self.key_file = key_file263self.cert_file = cert_file264self.key_password = key_password265self.ssl_context = ssl_context266self.server_hostname = server_hostname267268# Required property for Google AppEngine 1.9.0 which otherwise causes269# HTTPS requests to go out as HTTP. (See Issue #356)270self._protocol = "https"271272def set_cert(273self,274key_file=None,275cert_file=None,276cert_reqs=None,277key_password=None,278ca_certs=None,279assert_hostname=None,280assert_fingerprint=None,281ca_cert_dir=None,282ca_cert_data=None,283):284"""285This method should only be called once, before the connection is used.286"""287# If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also288# have an SSLContext object in which case we'll use its verify_mode.289if cert_reqs is None:290if self.ssl_context is not None:291cert_reqs = self.ssl_context.verify_mode292else:293cert_reqs = resolve_cert_reqs(None)294295self.key_file = key_file296self.cert_file = cert_file297self.cert_reqs = cert_reqs298self.key_password = key_password299self.assert_hostname = assert_hostname300self.assert_fingerprint = assert_fingerprint301self.ca_certs = ca_certs and os.path.expanduser(ca_certs)302self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)303self.ca_cert_data = ca_cert_data304305def connect(self):306# Add certificate verification307conn = self._new_conn()308hostname = self.host309310# Google App Engine's httplib does not define _tunnel_host311if getattr(self, "_tunnel_host", None):312self.sock = conn313# Calls self._set_hostport(), so self.host is314# self._tunnel_host below.315self._tunnel()316# Mark this connection as not reusable317self.auto_open = 0318319# Override the host with the one we're requesting data from.320hostname = self._tunnel_host321322server_hostname = hostname323if self.server_hostname is not None:324server_hostname = self.server_hostname325326is_time_off = datetime.date.today() < RECENT_DATE327if is_time_off:328warnings.warn(329(330"System time is way off (before {0}). This will probably "331"lead to SSL verification errors"332).format(RECENT_DATE),333SystemTimeWarning,334)335336# Wrap socket using verification with the root certs in337# trusted_root_certs338default_ssl_context = False339if self.ssl_context is None:340default_ssl_context = True341self.ssl_context = create_urllib3_context(342ssl_version=resolve_ssl_version(self.ssl_version),343cert_reqs=resolve_cert_reqs(self.cert_reqs),344)345346context = self.ssl_context347context.verify_mode = resolve_cert_reqs(self.cert_reqs)348349# Try to load OS default certs if none are given.350# Works well on Windows (requires Python3.4+)351if (352not self.ca_certs353and not self.ca_cert_dir354and not self.ca_cert_data355and default_ssl_context356and hasattr(context, "load_default_certs")357):358context.load_default_certs()359360self.sock = ssl_wrap_socket(361sock=conn,362keyfile=self.key_file,363certfile=self.cert_file,364key_password=self.key_password,365ca_certs=self.ca_certs,366ca_cert_dir=self.ca_cert_dir,367ca_cert_data=self.ca_cert_data,368server_hostname=server_hostname,369ssl_context=context,370)371372if self.assert_fingerprint:373assert_fingerprint(374self.sock.getpeercert(binary_form=True), self.assert_fingerprint375)376elif (377context.verify_mode != ssl.CERT_NONE378and not getattr(context, "check_hostname", False)379and self.assert_hostname is not False380):381# While urllib3 attempts to always turn off hostname matching from382# the TLS library, this cannot always be done. So we check whether383# the TLS Library still thinks it's matching hostnames.384cert = self.sock.getpeercert()385if not cert.get("subjectAltName", ()):386warnings.warn(387(388"Certificate for {0} has no `subjectAltName`, falling back to check for a "389"`commonName` for now. This feature is being removed by major browsers and "390"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "391"for details.)".format(hostname)392),393SubjectAltNameWarning,394)395_match_hostname(cert, self.assert_hostname or server_hostname)396397self.is_verified = (398context.verify_mode == ssl.CERT_REQUIRED399or self.assert_fingerprint is not None400)401402403def _match_hostname(cert, asserted_hostname):404try:405match_hostname(cert, asserted_hostname)406except CertificateError as e:407log.warning(408"Certificate did not match expected hostname: %s. Certificate: %s",409asserted_hostname,410cert,411)412# Add cert to exception and reraise so client code can inspect413# the cert when catching the exception, if they want to414e._peer_cert = cert415raise416417418if not ssl:419HTTPSConnection = DummyConnection # noqa: F811420421422VerifiedHTTPSConnection = HTTPSConnection423424425