connection.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
  11. from .packages.six.moves.http_client import HTTPException # noqa: F401
  12. try: # Compiled with SSL?
  13. import ssl
  14. BaseSSLError = ssl.SSLError
  15. except (ImportError, AttributeError): # Platform-specific: No SSL.
  16. ssl = None
  17. class BaseSSLError(BaseException):
  18. pass
  19. try: # Python 3:
  20. # Not a no-op, we're adding this to the namespace so it can be imported.
  21. ConnectionError = ConnectionError
  22. except NameError: # Python 2:
  23. class ConnectionError(Exception):
  24. pass
  25. from .exceptions import (
  26. NewConnectionError,
  27. ConnectTimeoutError,
  28. SubjectAltNameWarning,
  29. SystemTimeWarning,
  30. )
  31. from .packages.ssl_match_hostname import match_hostname, CertificateError
  32. from .util.ssl_ import (
  33. resolve_cert_reqs,
  34. resolve_ssl_version,
  35. assert_fingerprint,
  36. create_urllib3_context,
  37. ssl_wrap_socket
  38. )
  39. from .util import connection
  40. from ._collections import HTTPHeaderDict
  41. log = logging.getLogger(__name__)
  42. port_by_scheme = {
  43. 'http': 80,
  44. 'https': 443,
  45. }
  46. # When updating RECENT_DATE, move it to
  47. # within two years of the current date, and no
  48. # earlier than 6 months ago.
  49. RECENT_DATE = datetime.date(2016, 1, 1)
  50. class DummyConnection(object):
  51. """Used to detect a failed ConnectionCls import."""
  52. pass
  53. class HTTPConnection(_HTTPConnection, object):
  54. """
  55. Based on httplib.HTTPConnection but provides an extra constructor
  56. backwards-compatibility layer between older and newer Pythons.
  57. Additional keyword parameters are used to configure attributes of the connection.
  58. Accepted parameters include:
  59. - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
  60. - ``source_address``: Set the source address for the current connection.
  61. .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x
  62. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  63. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  64. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  65. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  66. you might pass::
  67. HTTPConnection.default_socket_options + [
  68. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  69. ]
  70. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  71. """
  72. default_port = port_by_scheme['http']
  73. #: Disable Nagle's algorithm by default.
  74. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  75. default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  76. #: Whether this connection verifies the host's certificate.
  77. is_verified = False
  78. def __init__(self, *args, **kw):
  79. if six.PY3: # Python 3
  80. kw.pop('strict', None)
  81. # Pre-set source_address in case we have an older Python like 2.6.
  82. self.source_address = kw.get('source_address')
  83. if sys.version_info < (2, 7): # Python 2.6
  84. # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
  85. # not newer versions. We can still use it when creating a
  86. # connection though, so we pop it *after* we have saved it as
  87. # self.source_address.
  88. kw.pop('source_address', None)
  89. #: The socket options provided by the user. If no options are
  90. #: provided, we use the default options.
  91. self.socket_options = kw.pop('socket_options', self.default_socket_options)
  92. # Superclass also sets self.source_address in Python 2.7+.
  93. _HTTPConnection.__init__(self, *args, **kw)
  94. def _new_conn(self):
  95. """ Establish a socket connection and set nodelay settings on it.
  96. :return: New socket connection.
  97. """
  98. extra_kw = {}
  99. if self.source_address:
  100. extra_kw['source_address'] = self.source_address
  101. if self.socket_options:
  102. extra_kw['socket_options'] = self.socket_options
  103. try:
  104. conn = connection.create_connection(
  105. (self.host, self.port), self.timeout, **extra_kw)
  106. except SocketTimeout as e:
  107. raise ConnectTimeoutError(
  108. self, "Connection to %s timed out. (connect timeout=%s)" %
  109. (self.host, self.timeout))
  110. except SocketError as e:
  111. raise NewConnectionError(
  112. self, "Failed to establish a new connection: %s" % e)
  113. return conn
  114. def _prepare_conn(self, conn):
  115. self.sock = conn
  116. # the _tunnel_host attribute was added in python 2.6.3 (via
  117. # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do
  118. # not have them.
  119. if getattr(self, '_tunnel_host', None):
  120. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  121. self._tunnel()
  122. # Mark this connection as not reusable
  123. self.auto_open = 0
  124. def connect(self):
  125. conn = self._new_conn()
  126. self._prepare_conn(conn)
  127. def request_chunked(self, method, url, body=None, headers=None):
  128. """
  129. Alternative to the common request method, which sends the
  130. body with chunked encoding and not as one block
  131. """
  132. headers = HTTPHeaderDict(headers if headers is not None else {})
  133. skip_accept_encoding = 'accept-encoding' in headers
  134. skip_host = 'host' in headers
  135. self.putrequest(
  136. method,
  137. url,
  138. skip_accept_encoding=skip_accept_encoding,
  139. skip_host=skip_host
  140. )
  141. for header, value in headers.items():
  142. self.putheader(header, value)
  143. if 'transfer-encoding' not in headers:
  144. self.putheader('Transfer-Encoding', 'chunked')
  145. self.endheaders()
  146. if body is not None:
  147. stringish_types = six.string_types + (six.binary_type,)
  148. if isinstance(body, stringish_types):
  149. body = (body,)
  150. for chunk in body:
  151. if not chunk:
  152. continue
  153. if not isinstance(chunk, six.binary_type):
  154. chunk = chunk.encode('utf8')
  155. len_str = hex(len(chunk))[2:]
  156. self.send(len_str.encode('utf-8'))
  157. self.send(b'\r\n')
  158. self.send(chunk)
  159. self.send(b'\r\n')
  160. # After the if clause, to always have a closed body
  161. self.send(b'0\r\n\r\n')
  162. class HTTPSConnection(HTTPConnection):
  163. default_port = port_by_scheme['https']
  164. ssl_version = None
  165. def __init__(self, host, port=None, key_file=None, cert_file=None,
  166. strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  167. ssl_context=None, **kw):
  168. HTTPConnection.__init__(self, host, port, strict=strict,
  169. timeout=timeout, **kw)
  170. self.key_file = key_file
  171. self.cert_file = cert_file
  172. self.ssl_context = ssl_context
  173. # Required property for Google AppEngine 1.9.0 which otherwise causes
  174. # HTTPS requests to go out as HTTP. (See Issue #356)
  175. self._protocol = 'https'
  176. def connect(self):
  177. conn = self._new_conn()
  178. self._prepare_conn(conn)
  179. if self.ssl_context is None:
  180. self.ssl_context = create_urllib3_context(
  181. ssl_version=resolve_ssl_version(None),
  182. cert_reqs=resolve_cert_reqs(None),
  183. )
  184. self.sock = ssl_wrap_socket(
  185. sock=conn,
  186. keyfile=self.key_file,
  187. certfile=self.cert_file,
  188. ssl_context=self.ssl_context,
  189. )
  190. class VerifiedHTTPSConnection(HTTPSConnection):
  191. """
  192. Based on httplib.HTTPSConnection but wraps the socket with
  193. SSL certification.
  194. """
  195. cert_reqs = None
  196. ca_certs = None
  197. ca_cert_dir = None
  198. ssl_version = None
  199. assert_fingerprint = None
  200. def set_cert(self, key_file=None, cert_file=None,
  201. cert_reqs=None, ca_certs=None,
  202. assert_hostname=None, assert_fingerprint=None,
  203. ca_cert_dir=None):
  204. """
  205. This method should only be called once, before the connection is used.
  206. """
  207. # If cert_reqs is not provided, we can try to guess. If the user gave
  208. # us a cert database, we assume they want to use it: otherwise, if
  209. # they gave us an SSL Context object we should use whatever is set for
  210. # it.
  211. if cert_reqs is None:
  212. if ca_certs or ca_cert_dir:
  213. cert_reqs = 'CERT_REQUIRED'
  214. elif self.ssl_context is not None:
  215. cert_reqs = self.ssl_context.verify_mode
  216. self.key_file = key_file
  217. self.cert_file = cert_file
  218. self.cert_reqs = cert_reqs
  219. self.assert_hostname = assert_hostname
  220. self.assert_fingerprint = assert_fingerprint
  221. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  222. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  223. def connect(self):
  224. # Add certificate verification
  225. conn = self._new_conn()
  226. hostname = self.host
  227. if getattr(self, '_tunnel_host', None):
  228. # _tunnel_host was added in Python 2.6.3
  229. # (See: http://hg.python.org/cpython/rev/0f57b30a152f)
  230. self.sock = conn
  231. # Calls self._set_hostport(), so self.host is
  232. # self._tunnel_host below.
  233. self._tunnel()
  234. # Mark this connection as not reusable
  235. self.auto_open = 0
  236. # Override the host with the one we're requesting data from.
  237. hostname = self._tunnel_host
  238. is_time_off = datetime.date.today() < RECENT_DATE
  239. if is_time_off:
  240. warnings.warn((
  241. 'System time is way off (before {0}). This will probably '
  242. 'lead to SSL verification errors').format(RECENT_DATE),
  243. SystemTimeWarning
  244. )
  245. # Wrap socket using verification with the root certs in
  246. # trusted_root_certs
  247. if self.ssl_context is None:
  248. self.ssl_context = create_urllib3_context(
  249. ssl_version=resolve_ssl_version(self.ssl_version),
  250. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  251. )
  252. context = self.ssl_context
  253. context.verify_mode = resolve_cert_reqs(self.cert_reqs)
  254. self.sock = ssl_wrap_socket(
  255. sock=conn,
  256. keyfile=self.key_file,
  257. certfile=self.cert_file,
  258. ca_certs=self.ca_certs,
  259. ca_cert_dir=self.ca_cert_dir,
  260. server_hostname=hostname,
  261. ssl_context=context)
  262. if self.assert_fingerprint:
  263. assert_fingerprint(self.sock.getpeercert(binary_form=True),
  264. self.assert_fingerprint)
  265. elif context.verify_mode != ssl.CERT_NONE \
  266. and not getattr(context, 'check_hostname', False) \
  267. and self.assert_hostname is not False:
  268. # While urllib3 attempts to always turn off hostname matching from
  269. # the TLS library, this cannot always be done. So we check whether
  270. # the TLS Library still thinks it's matching hostnames.
  271. cert = self.sock.getpeercert()
  272. if not cert.get('subjectAltName', ()):
  273. warnings.warn((
  274. 'Certificate for {0} has no `subjectAltName`, falling back to check for a '
  275. '`commonName` for now. This feature is being removed by major browsers and '
  276. 'deprecated by RFC 2818. (See https://github.com/shazow/urllib3/issues/497 '
  277. 'for details.)'.format(hostname)),
  278. SubjectAltNameWarning
  279. )
  280. _match_hostname(cert, self.assert_hostname or hostname)
  281. self.is_verified = (
  282. context.verify_mode == ssl.CERT_REQUIRED or
  283. self.assert_fingerprint is not None
  284. )
  285. def _match_hostname(cert, asserted_hostname):
  286. try:
  287. match_hostname(cert, asserted_hostname)
  288. except CertificateError as e:
  289. log.error(
  290. 'Certificate did not match expected hostname: %s. '
  291. 'Certificate: %s', asserted_hostname, cert
  292. )
  293. # Add cert to exception and reraise so client code can inspect
  294. # the cert when catching the exception, if they want to
  295. e._peer_cert = cert
  296. raise
  297. if ssl:
  298. # Make a copy for testing.
  299. UnverifiedHTTPSConnection = HTTPSConnection
  300. HTTPSConnection = VerifiedHTTPSConnection
  301. else:
  302. HTTPSConnection = DummyConnection