Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 within two years of the current date,
  47. # and not less than 6 months ago.
  48. # Example: if Today is 2018-01-01, then RECENT_DATE should be any date on or
  49. # after 2016-01-01 (today - 2 years) AND before 2017-07-01 (today - 6 months)
  50. RECENT_DATE = datetime.date(2017, 6, 30)
  51. class DummyConnection(object):
  52. """Used to detect a failed ConnectionCls import."""
  53. pass
  54. class HTTPConnection(_HTTPConnection, object):
  55. """
  56. Based on httplib.HTTPConnection but provides an extra constructor
  57. backwards-compatibility layer between older and newer Pythons.
  58. Additional keyword parameters are used to configure attributes of the connection.
  59. Accepted parameters include:
  60. - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
  61. - ``source_address``: Set the source address for the current connection.
  62. .. note:: This is ignored for Python 2.6. It is only applied for 2.7 and 3.x
  63. - ``socket_options``: Set specific options on the underlying socket. If not specified, then
  64. defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
  65. Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
  66. For example, if you wish to enable TCP Keep Alive in addition to the defaults,
  67. you might pass::
  68. HTTPConnection.default_socket_options + [
  69. (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
  70. ]
  71. Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
  72. """
  73. default_port = port_by_scheme['http']
  74. #: Disable Nagle's algorithm by default.
  75. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
  76. default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
  77. #: Whether this connection verifies the host's certificate.
  78. is_verified = False
  79. def __init__(self, *args, **kw):
  80. if six.PY3: # Python 3
  81. kw.pop('strict', None)
  82. # Pre-set source_address in case we have an older Python like 2.6.
  83. self.source_address = kw.get('source_address')
  84. if sys.version_info < (2, 7): # Python 2.6
  85. # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
  86. # not newer versions. We can still use it when creating a
  87. # connection though, so we pop it *after* we have saved it as
  88. # self.source_address.
  89. kw.pop('source_address', None)
  90. #: The socket options provided by the user. If no options are
  91. #: provided, we use the default options.
  92. self.socket_options = kw.pop('socket_options', self.default_socket_options)
  93. # Superclass also sets self.source_address in Python 2.7+.
  94. _HTTPConnection.__init__(self, *args, **kw)
  95. @property
  96. def host(self):
  97. """
  98. Getter method to remove any trailing dots that indicate the hostname is an FQDN.
  99. In general, SSL certificates don't include the trailing dot indicating a
  100. fully-qualified domain name, and thus, they don't validate properly when
  101. checked against a domain name that includes the dot. In addition, some
  102. servers may not expect to receive the trailing dot when provided.
  103. However, the hostname with trailing dot is critical to DNS resolution; doing a
  104. lookup with the trailing dot will properly only resolve the appropriate FQDN,
  105. whereas a lookup without a trailing dot will search the system's search domain
  106. list. Thus, it's important to keep the original host around for use only in
  107. those cases where it's appropriate (i.e., when doing DNS lookup to establish the
  108. actual TCP connection across which we're going to send HTTP requests).
  109. """
  110. return self._dns_host.rstrip('.')
  111. @host.setter
  112. def host(self, value):
  113. """
  114. Setter for the `host` property.
  115. We assume that only urllib3 uses the _dns_host attribute; httplib itself
  116. only uses `host`, and it seems reasonable that other libraries follow suit.
  117. """
  118. self._dns_host = value
  119. def _new_conn(self):
  120. """ Establish a socket connection and set nodelay settings on it.
  121. :return: New socket connection.
  122. """
  123. extra_kw = {}
  124. if self.source_address:
  125. extra_kw['source_address'] = self.source_address
  126. if self.socket_options:
  127. extra_kw['socket_options'] = self.socket_options
  128. try:
  129. conn = connection.create_connection(
  130. (self._dns_host, self.port), self.timeout, **extra_kw)
  131. except SocketTimeout as e:
  132. raise ConnectTimeoutError(
  133. self, "Connection to %s timed out. (connect timeout=%s)" %
  134. (self.host, self.timeout))
  135. except SocketError as e:
  136. raise NewConnectionError(
  137. self, "Failed to establish a new connection: %s" % e)
  138. return conn
  139. def _prepare_conn(self, conn):
  140. self.sock = conn
  141. # the _tunnel_host attribute was added in python 2.6.3 (via
  142. # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do
  143. # not have them.
  144. if getattr(self, '_tunnel_host', None):
  145. # TODO: Fix tunnel so it doesn't depend on self.sock state.
  146. self._tunnel()
  147. # Mark this connection as not reusable
  148. self.auto_open = 0
  149. def connect(self):
  150. conn = self._new_conn()
  151. self._prepare_conn(conn)
  152. def request_chunked(self, method, url, body=None, headers=None):
  153. """
  154. Alternative to the common request method, which sends the
  155. body with chunked encoding and not as one block
  156. """
  157. headers = HTTPHeaderDict(headers if headers is not None else {})
  158. skip_accept_encoding = 'accept-encoding' in headers
  159. skip_host = 'host' in headers
  160. self.putrequest(
  161. method,
  162. url,
  163. skip_accept_encoding=skip_accept_encoding,
  164. skip_host=skip_host
  165. )
  166. for header, value in headers.items():
  167. self.putheader(header, value)
  168. if 'transfer-encoding' not in headers:
  169. self.putheader('Transfer-Encoding', 'chunked')
  170. self.endheaders()
  171. if body is not None:
  172. stringish_types = six.string_types + (six.binary_type,)
  173. if isinstance(body, stringish_types):
  174. body = (body,)
  175. for chunk in body:
  176. if not chunk:
  177. continue
  178. if not isinstance(chunk, six.binary_type):
  179. chunk = chunk.encode('utf8')
  180. len_str = hex(len(chunk))[2:]
  181. self.send(len_str.encode('utf-8'))
  182. self.send(b'\r\n')
  183. self.send(chunk)
  184. self.send(b'\r\n')
  185. # After the if clause, to always have a closed body
  186. self.send(b'0\r\n\r\n')
  187. class HTTPSConnection(HTTPConnection):
  188. default_port = port_by_scheme['https']
  189. ssl_version = None
  190. def __init__(self, host, port=None, key_file=None, cert_file=None,
  191. strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  192. ssl_context=None, **kw):
  193. HTTPConnection.__init__(self, host, port, strict=strict,
  194. timeout=timeout, **kw)
  195. self.key_file = key_file
  196. self.cert_file = cert_file
  197. self.ssl_context = ssl_context
  198. # Required property for Google AppEngine 1.9.0 which otherwise causes
  199. # HTTPS requests to go out as HTTP. (See Issue #356)
  200. self._protocol = 'https'
  201. def connect(self):
  202. conn = self._new_conn()
  203. self._prepare_conn(conn)
  204. if self.ssl_context is None:
  205. self.ssl_context = create_urllib3_context(
  206. ssl_version=resolve_ssl_version(None),
  207. cert_reqs=resolve_cert_reqs(None),
  208. )
  209. self.sock = ssl_wrap_socket(
  210. sock=conn,
  211. keyfile=self.key_file,
  212. certfile=self.cert_file,
  213. ssl_context=self.ssl_context,
  214. )
  215. class VerifiedHTTPSConnection(HTTPSConnection):
  216. """
  217. Based on httplib.HTTPSConnection but wraps the socket with
  218. SSL certification.
  219. """
  220. cert_reqs = None
  221. ca_certs = None
  222. ca_cert_dir = None
  223. ssl_version = None
  224. assert_fingerprint = None
  225. def set_cert(self, key_file=None, cert_file=None,
  226. cert_reqs=None, ca_certs=None,
  227. assert_hostname=None, assert_fingerprint=None,
  228. ca_cert_dir=None):
  229. """
  230. This method should only be called once, before the connection is used.
  231. """
  232. # If cert_reqs is not provided, we can try to guess. If the user gave
  233. # us a cert database, we assume they want to use it: otherwise, if
  234. # they gave us an SSL Context object we should use whatever is set for
  235. # it.
  236. if cert_reqs is None:
  237. if ca_certs or ca_cert_dir:
  238. cert_reqs = 'CERT_REQUIRED'
  239. elif self.ssl_context is not None:
  240. cert_reqs = self.ssl_context.verify_mode
  241. self.key_file = key_file
  242. self.cert_file = cert_file
  243. self.cert_reqs = cert_reqs
  244. self.assert_hostname = assert_hostname
  245. self.assert_fingerprint = assert_fingerprint
  246. self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
  247. self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
  248. def connect(self):
  249. # Add certificate verification
  250. conn = self._new_conn()
  251. hostname = self.host
  252. if getattr(self, '_tunnel_host', None):
  253. # _tunnel_host was added in Python 2.6.3
  254. # (See: http://hg.python.org/cpython/rev/0f57b30a152f)
  255. self.sock = conn
  256. # Calls self._set_hostport(), so self.host is
  257. # self._tunnel_host below.
  258. self._tunnel()
  259. # Mark this connection as not reusable
  260. self.auto_open = 0
  261. # Override the host with the one we're requesting data from.
  262. hostname = self._tunnel_host
  263. is_time_off = datetime.date.today() < RECENT_DATE
  264. if is_time_off:
  265. warnings.warn((
  266. 'System time is way off (before {0}). This will probably '
  267. 'lead to SSL verification errors').format(RECENT_DATE),
  268. SystemTimeWarning
  269. )
  270. # Wrap socket using verification with the root certs in
  271. # trusted_root_certs
  272. if self.ssl_context is None:
  273. self.ssl_context = create_urllib3_context(
  274. ssl_version=resolve_ssl_version(self.ssl_version),
  275. cert_reqs=resolve_cert_reqs(self.cert_reqs),
  276. )
  277. context = self.ssl_context
  278. context.verify_mode = resolve_cert_reqs(self.cert_reqs)
  279. self.sock = ssl_wrap_socket(
  280. sock=conn,
  281. keyfile=self.key_file,
  282. certfile=self.cert_file,
  283. ca_certs=self.ca_certs,
  284. ca_cert_dir=self.ca_cert_dir,
  285. server_hostname=hostname,
  286. ssl_context=context)
  287. if self.assert_fingerprint:
  288. assert_fingerprint(self.sock.getpeercert(binary_form=True),
  289. self.assert_fingerprint)
  290. elif context.verify_mode != ssl.CERT_NONE \
  291. and not getattr(context, 'check_hostname', False) \
  292. and self.assert_hostname is not False:
  293. # While urllib3 attempts to always turn off hostname matching from
  294. # the TLS library, this cannot always be done. So we check whether
  295. # the TLS Library still thinks it's matching hostnames.
  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. self.is_verified = (
  307. context.verify_mode == ssl.CERT_REQUIRED or
  308. self.assert_fingerprint is not None
  309. )
  310. def _match_hostname(cert, asserted_hostname):
  311. try:
  312. match_hostname(cert, asserted_hostname)
  313. except CertificateError as e:
  314. log.error(
  315. 'Certificate did not match expected hostname: %s. '
  316. 'Certificate: %s', asserted_hostname, cert
  317. )
  318. # Add cert to exception and reraise so client code can inspect
  319. # the cert when catching the exception, if they want to
  320. e._peer_cert = cert
  321. raise
  322. if ssl:
  323. # Make a copy for testing.
  324. UnverifiedHTTPSConnection = HTTPSConnection
  325. HTTPSConnection = VerifiedHTTPSConnection
  326. else:
  327. HTTPSConnection = DummyConnection