1 from __future__ import absolute_import
7 from socket import error as SocketError, timeout as SocketTimeout
9 from .packages import six
12 from http.client import HTTPConnection as _HTTPConnection
13 from http.client import HTTPException # noqa: unused in this module
15 from httplib import HTTPConnection as _HTTPConnection
16 from httplib import HTTPException # noqa: unused in this module
18 try: # Compiled with SSL?
20 BaseSSLError = ssl.SSLError
21 except (ImportError, AttributeError): # Platform-specific: No SSL.
24 class BaseSSLError(BaseException):
29 # Not a no-op, we're adding this to the namespace so it can be imported.
30 ConnectionError = ConnectionError
31 except NameError: # Python 2:
32 class ConnectionError(Exception):
36 from .exceptions import (
39 SubjectAltNameWarning,
42 from .packages.ssl_match_hostname import match_hostname, CertificateError
44 from .util.ssl_ import (
52 from .util import connection
54 from ._collections import HTTPHeaderDict
56 log = logging.getLogger(__name__)
63 RECENT_DATE = datetime.date(2014, 1, 1)
66 class DummyConnection(object):
67 """Used to detect a failed ConnectionCls import."""
71 class HTTPConnection(_HTTPConnection, object):
73 Based on httplib.HTTPConnection but provides an extra constructor
74 backwards-compatibility layer between older and newer Pythons.
76 Additional keyword parameters are used to configure attributes of the connection.
77 Accepted parameters include:
79 - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
80 - ``source_address``: Set the source address for the current connection.
82 .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x
84 - ``socket_options``: Set specific options on the underlying socket. If not specified, then
85 defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
86 Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
88 For example, if you wish to enable TCP Keep Alive in addition to the defaults,
91 HTTPConnection.default_socket_options + [
92 (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
95 Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
98 default_port = port_by_scheme['http']
100 #: Disable Nagle's algorithm by default.
101 #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
102 default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
104 #: Whether this connection verifies the host's certificate.
107 def __init__(self, *args, **kw):
108 if six.PY3: # Python 3
109 kw.pop('strict', None)
111 # Pre-set source_address in case we have an older Python like 2.6.
112 self.source_address = kw.get('source_address')
114 if sys.version_info < (2, 7): # Python 2.6
115 # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
116 # not newer versions. We can still use it when creating a
117 # connection though, so we pop it *after* we have saved it as
118 # self.source_address.
119 kw.pop('source_address', None)
121 #: The socket options provided by the user. If no options are
122 #: provided, we use the default options.
123 self.socket_options = kw.pop('socket_options', self.default_socket_options)
125 # Superclass also sets self.source_address in Python 2.7+.
126 _HTTPConnection.__init__(self, *args, **kw)
129 """ Establish a socket connection and set nodelay settings on it.
131 :return: New socket connection.
134 if self.source_address:
135 extra_kw['source_address'] = self.source_address
137 if self.socket_options:
138 extra_kw['socket_options'] = self.socket_options
141 conn = connection.create_connection(
142 (self.host, self.port), self.timeout, **extra_kw)
144 except SocketTimeout as e:
145 raise ConnectTimeoutError(
146 self, "Connection to %s timed out. (connect timeout=%s)" %
147 (self.host, self.timeout))
149 except SocketError as e:
150 raise NewConnectionError(
151 self, "Failed to establish a new connection: %s" % e)
155 def _prepare_conn(self, conn):
157 # the _tunnel_host attribute was added in python 2.6.3 (via
158 # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do
160 if getattr(self, '_tunnel_host', None):
161 # TODO: Fix tunnel so it doesn't depend on self.sock state.
163 # Mark this connection as not reusable
167 conn = self._new_conn()
168 self._prepare_conn(conn)
170 def request_chunked(self, method, url, body=None, headers=None):
172 Alternative to the common request method, which sends the
173 body with chunked encoding and not as one block
175 headers = HTTPHeaderDict(headers if headers is not None else {})
176 skip_accept_encoding = 'accept-encoding' in headers
177 self.putrequest(method, url, skip_accept_encoding=skip_accept_encoding)
178 for header, value in headers.items():
179 self.putheader(header, value)
180 if 'transfer-encoding' not in headers:
181 self.putheader('Transfer-Encoding', 'chunked')
185 stringish_types = six.string_types + (six.binary_type,)
186 if isinstance(body, stringish_types):
191 if not isinstance(chunk, six.binary_type):
192 chunk = chunk.encode('utf8')
193 len_str = hex(len(chunk))[2:]
194 self.send(len_str.encode('utf-8'))
199 # After the if clause, to always have a closed body
200 self.send(b'0\r\n\r\n')
203 class HTTPSConnection(HTTPConnection):
204 default_port = port_by_scheme['https']
206 def __init__(self, host, port=None, key_file=None, cert_file=None,
207 strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw):
209 HTTPConnection.__init__(self, host, port, strict=strict,
210 timeout=timeout, **kw)
212 self.key_file = key_file
213 self.cert_file = cert_file
215 # Required property for Google AppEngine 1.9.0 which otherwise causes
216 # HTTPS requests to go out as HTTP. (See Issue #356)
217 self._protocol = 'https'
220 conn = self._new_conn()
221 self._prepare_conn(conn)
222 self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)
225 class VerifiedHTTPSConnection(HTTPSConnection):
227 Based on httplib.HTTPSConnection but wraps the socket with
234 assert_fingerprint = None
236 def set_cert(self, key_file=None, cert_file=None,
237 cert_reqs=None, ca_certs=None,
238 assert_hostname=None, assert_fingerprint=None,
241 if (ca_certs or ca_cert_dir) and cert_reqs is None:
242 cert_reqs = 'CERT_REQUIRED'
244 self.key_file = key_file
245 self.cert_file = cert_file
246 self.cert_reqs = cert_reqs
247 self.assert_hostname = assert_hostname
248 self.assert_fingerprint = assert_fingerprint
249 self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
250 self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
253 # Add certificate verification
254 conn = self._new_conn()
256 resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)
257 resolved_ssl_version = resolve_ssl_version(self.ssl_version)
260 if getattr(self, '_tunnel_host', None):
261 # _tunnel_host was added in Python 2.6.3
262 # (See: http://hg.python.org/cpython/rev/0f57b30a152f)
265 # Calls self._set_hostport(), so self.host is
266 # self._tunnel_host below.
268 # Mark this connection as not reusable
271 # Override the host with the one we're requesting data from.
272 hostname = self._tunnel_host
274 is_time_off = datetime.date.today() < RECENT_DATE
277 'System time is way off (before {0}). This will probably '
278 'lead to SSL verification errors').format(RECENT_DATE),
282 # Wrap socket using verification with the root certs in
284 self.sock = ssl_wrap_socket(conn, self.key_file, self.cert_file,
285 cert_reqs=resolved_cert_reqs,
286 ca_certs=self.ca_certs,
287 ca_cert_dir=self.ca_cert_dir,
288 server_hostname=hostname,
289 ssl_version=resolved_ssl_version)
291 if self.assert_fingerprint:
292 assert_fingerprint(self.sock.getpeercert(binary_form=True),
293 self.assert_fingerprint)
294 elif resolved_cert_reqs != ssl.CERT_NONE \
295 and self.assert_hostname is not False:
296 cert = self.sock.getpeercert()
297 if not cert.get('subjectAltName', ()):
299 'Certificate for {0} has no `subjectAltName`, falling back to check for a '
300 '`commonName` for now. This feature is being removed by major browsers and '
301 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '
302 'for details.)'.format(hostname)),
303 SubjectAltNameWarning
305 _match_hostname(cert, self.assert_hostname or hostname)
307 self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or
308 self.assert_fingerprint is not None)
311 def _match_hostname(cert, asserted_hostname):
313 match_hostname(cert, asserted_hostname)
314 except CertificateError as e:
316 'Certificate did not match expected hostname: %s. '
317 'Certificate: %s', asserted_hostname, cert
319 # Add cert to exception and reraise so client code can inspect
320 # the cert when catching the exception, if they want to
326 # Make a copy for testing.
327 UnverifiedHTTPSConnection = HTTPSConnection
328 HTTPSConnection = VerifiedHTTPSConnection
330 HTTPSConnection = DummyConnection