OSDN Git Service

5ce0080480a6f82da6e3b459c8d831f8fcea8d99
[stux/ultron.git] / venv / Lib / site-packages / pip / _vendor / requests / packages / urllib3 / connection.py
1 from __future__ import absolute_import
2 import datetime
3 import logging
4 import os
5 import sys
6 import socket
7 from socket import error as SocketError, timeout as SocketTimeout
8 import warnings
9 from .packages import six
10
11 try:  # Python 3
12     from http.client import HTTPConnection as _HTTPConnection
13     from http.client import HTTPException  # noqa: unused in this module
14 except ImportError:
15     from httplib import HTTPConnection as _HTTPConnection
16     from httplib import HTTPException  # noqa: unused in this module
17
18 try:  # Compiled with SSL?
19     import ssl
20     BaseSSLError = ssl.SSLError
21 except (ImportError, AttributeError):  # Platform-specific: No SSL.
22     ssl = None
23
24     class BaseSSLError(BaseException):
25         pass
26
27
28 try:  # Python 3:
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):
33         pass
34
35
36 from .exceptions import (
37     NewConnectionError,
38     ConnectTimeoutError,
39     SubjectAltNameWarning,
40     SystemTimeWarning,
41 )
42 from .packages.ssl_match_hostname import match_hostname, CertificateError
43
44 from .util.ssl_ import (
45     resolve_cert_reqs,
46     resolve_ssl_version,
47     ssl_wrap_socket,
48     assert_fingerprint,
49 )
50
51
52 from .util import connection
53
54 from ._collections import HTTPHeaderDict
55
56 log = logging.getLogger(__name__)
57
58 port_by_scheme = {
59     'http': 80,
60     'https': 443,
61 }
62
63 RECENT_DATE = datetime.date(2014, 1, 1)
64
65
66 class DummyConnection(object):
67     """Used to detect a failed ConnectionCls import."""
68     pass
69
70
71 class HTTPConnection(_HTTPConnection, object):
72     """
73     Based on httplib.HTTPConnection but provides an extra constructor
74     backwards-compatibility layer between older and newer Pythons.
75
76     Additional keyword parameters are used to configure attributes of the connection.
77     Accepted parameters include:
78
79       - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
80       - ``source_address``: Set the source address for the current connection.
81
82         .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x
83
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.
87
88         For example, if you wish to enable TCP Keep Alive in addition to the defaults,
89         you might pass::
90
91             HTTPConnection.default_socket_options + [
92                 (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
93             ]
94
95         Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
96     """
97
98     default_port = port_by_scheme['http']
99
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)]
103
104     #: Whether this connection verifies the host's certificate.
105     is_verified = False
106
107     def __init__(self, *args, **kw):
108         if six.PY3:  # Python 3
109             kw.pop('strict', None)
110
111         # Pre-set source_address in case we have an older Python like 2.6.
112         self.source_address = kw.get('source_address')
113
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)
120
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)
124
125         # Superclass also sets self.source_address in Python 2.7+.
126         _HTTPConnection.__init__(self, *args, **kw)
127
128     def _new_conn(self):
129         """ Establish a socket connection and set nodelay settings on it.
130
131         :return: New socket connection.
132         """
133         extra_kw = {}
134         if self.source_address:
135             extra_kw['source_address'] = self.source_address
136
137         if self.socket_options:
138             extra_kw['socket_options'] = self.socket_options
139
140         try:
141             conn = connection.create_connection(
142                 (self.host, self.port), self.timeout, **extra_kw)
143
144         except SocketTimeout as e:
145             raise ConnectTimeoutError(
146                 self, "Connection to %s timed out. (connect timeout=%s)" %
147                 (self.host, self.timeout))
148
149         except SocketError as e:
150             raise NewConnectionError(
151                 self, "Failed to establish a new connection: %s" % e)
152
153         return conn
154
155     def _prepare_conn(self, conn):
156         self.sock = 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
159         # not have them.
160         if getattr(self, '_tunnel_host', None):
161             # TODO: Fix tunnel so it doesn't depend on self.sock state.
162             self._tunnel()
163             # Mark this connection as not reusable
164             self.auto_open = 0
165
166     def connect(self):
167         conn = self._new_conn()
168         self._prepare_conn(conn)
169
170     def request_chunked(self, method, url, body=None, headers=None):
171         """
172         Alternative to the common request method, which sends the
173         body with chunked encoding and not as one block
174         """
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')
182         self.endheaders()
183
184         if body is not None:
185             stringish_types = six.string_types + (six.binary_type,)
186             if isinstance(body, stringish_types):
187                 body = (body,)
188             for chunk in body:
189                 if not chunk:
190                     continue
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'))
195                 self.send(b'\r\n')
196                 self.send(chunk)
197                 self.send(b'\r\n')
198
199         # After the if clause, to always have a closed body
200         self.send(b'0\r\n\r\n')
201
202
203 class HTTPSConnection(HTTPConnection):
204     default_port = port_by_scheme['https']
205
206     def __init__(self, host, port=None, key_file=None, cert_file=None,
207                  strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw):
208
209         HTTPConnection.__init__(self, host, port, strict=strict,
210                                 timeout=timeout, **kw)
211
212         self.key_file = key_file
213         self.cert_file = cert_file
214
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'
218
219     def connect(self):
220         conn = self._new_conn()
221         self._prepare_conn(conn)
222         self.sock = ssl.wrap_socket(conn, self.key_file, self.cert_file)
223
224
225 class VerifiedHTTPSConnection(HTTPSConnection):
226     """
227     Based on httplib.HTTPSConnection but wraps the socket with
228     SSL certification.
229     """
230     cert_reqs = None
231     ca_certs = None
232     ca_cert_dir = None
233     ssl_version = None
234     assert_fingerprint = None
235
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,
239                  ca_cert_dir=None):
240
241         if (ca_certs or ca_cert_dir) and cert_reqs is None:
242             cert_reqs = 'CERT_REQUIRED'
243
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)
251
252     def connect(self):
253         # Add certificate verification
254         conn = self._new_conn()
255
256         resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)
257         resolved_ssl_version = resolve_ssl_version(self.ssl_version)
258
259         hostname = self.host
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)
263
264             self.sock = conn
265             # Calls self._set_hostport(), so self.host is
266             # self._tunnel_host below.
267             self._tunnel()
268             # Mark this connection as not reusable
269             self.auto_open = 0
270
271             # Override the host with the one we're requesting data from.
272             hostname = self._tunnel_host
273
274         is_time_off = datetime.date.today() < RECENT_DATE
275         if is_time_off:
276             warnings.warn((
277                 'System time is way off (before {0}). This will probably '
278                 'lead to SSL verification errors').format(RECENT_DATE),
279                 SystemTimeWarning
280             )
281
282         # Wrap socket using verification with the root certs in
283         # trusted_root_certs
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)
290
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', ()):
298                 warnings.warn((
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
304                 )
305             _match_hostname(cert, self.assert_hostname or hostname)
306
307         self.is_verified = (resolved_cert_reqs == ssl.CERT_REQUIRED or
308                             self.assert_fingerprint is not None)
309
310
311 def _match_hostname(cert, asserted_hostname):
312     try:
313         match_hostname(cert, asserted_hostname)
314     except CertificateError as e:
315         log.error(
316             'Certificate did not match expected hostname: %s. '
317             'Certificate: %s', asserted_hostname, cert
318         )
319         # Add cert to exception and reraise so client code can inspect
320         # the cert when catching the exception, if they want to
321         e._peer_cert = cert
322         raise
323
324
325 if ssl:
326     # Make a copy for testing.
327     UnverifiedHTTPSConnection = HTTPSConnection
328     HTTPSConnection = VerifiedHTTPSConnection
329 else:
330     HTTPSConnection = DummyConnection