././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/0000755000175000017500000000000000000000000016104 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/CHANGES.rst0000644000175000017500000010144600000000000017714 0ustar00sethmlarsonsethmlarson00000000000000Changes ======= 1.25.8 (2020-01-20) ------------------- * Drop support for EOL Python 3.4 (Pull #1774) * Optimize _encode_invalid_chars (Pull #1787) 1.25.7 (2019-11-11) ------------------- * Preserve ``chunked`` parameter on retries (Pull #1715, Pull #1734) * Allow unset ``SERVER_SOFTWARE`` in App Engine (Pull #1704, Issue #1470) * Fix issue where URL fragment was sent within the request target. (Pull #1732) * Fix issue where an empty query section in a URL would fail to parse. (Pull #1732) * Remove TLS 1.3 support in SecureTransport due to Apple removing support (Pull #1703) 1.25.6 (2019-09-24) ------------------- * Fix issue where tilde (``~``) characters were incorrectly percent-encoded in the path. (Pull #1692) 1.25.5 (2019-09-19) ------------------- * Add mitigation for BPO-37428 affecting Python <3.7.4 and OpenSSL 1.1.1+ which caused certificate verification to be enabled when using ``cert_reqs=CERT_NONE``. (Issue #1682) 1.25.4 (2019-09-19) ------------------- * Propagate Retry-After header settings to subsequent retries. (Pull #1607) * Fix edge case where Retry-After header was still respected even when explicitly opted out of. (Pull #1607) * Remove dependency on ``rfc3986`` for URL parsing. * Fix issue where URLs containing invalid characters within ``Url.auth`` would raise an exception instead of percent-encoding those characters. * Add support for ``HTTPResponse.auto_close = False`` which makes HTTP responses work well with BufferedReaders and other ``io`` module features. (Pull #1652) * Percent-encode invalid characters in URL for ``HTTPConnectionPool.request()`` (Pull #1673) 1.25.3 (2019-05-23) ------------------- * Change ``HTTPSConnection`` to load system CA certificates when ``ca_certs``, ``ca_cert_dir``, and ``ssl_context`` are unspecified. (Pull #1608, Issue #1603) * Upgrade bundled rfc3986 to v1.3.2. (Pull #1609, Issue #1605) 1.25.2 (2019-04-28) ------------------- * Change ``is_ipaddress`` to not detect IPvFuture addresses. (Pull #1583) * Change ``parse_url`` to percent-encode invalid characters within the path, query, and target components. (Pull #1586) 1.25.1 (2019-04-24) ------------------- * Add support for Google's ``Brotli`` package. (Pull #1572, Pull #1579) * Upgrade bundled rfc3986 to v1.3.1 (Pull #1578) 1.25 (2019-04-22) ----------------- * Require and validate certificates by default when using HTTPS (Pull #1507) * Upgraded ``urllib3.utils.parse_url()`` to be RFC 3986 compliant. (Pull #1487) * Added support for ``key_password`` for ``HTTPSConnectionPool`` to use encrypted ``key_file`` without creating your own ``SSLContext`` object. (Pull #1489) * Add TLSv1.3 support to CPython, pyOpenSSL, and SecureTransport ``SSLContext`` implementations. (Pull #1496) * Switched the default multipart header encoder from RFC 2231 to HTML 5 working draft. (Issue #303, PR #1492) * Fixed issue where OpenSSL would block if an encrypted client private key was given and no password was given. Instead an ``SSLError`` is raised. (Pull #1489) * Added support for Brotli content encoding. It is enabled automatically if ``brotlipy`` package is installed which can be requested with ``urllib3[brotli]`` extra. (Pull #1532) * Drop ciphers using DSS key exchange from default TLS cipher suites. Improve default ciphers when using SecureTransport. (Pull #1496) * Implemented a more efficient ``HTTPResponse.__iter__()`` method. (Issue #1483) 1.24.3 (2019-05-01) ------------------- * Apply fix for CVE-2019-9740. (Pull #1591) 1.24.2 (2019-04-17) ------------------- * Don't load system certificates by default when any other ``ca_certs``, ``ca_certs_dir`` or ``ssl_context`` parameters are specified. * Remove Authorization header regardless of case when redirecting to cross-site. (Issue #1510) * Add support for IPv6 addresses in subjectAltName section of certificates. (Issue #1269) 1.24.1 (2018-11-02) ------------------- * Remove quadratic behavior within ``GzipDecoder.decompress()`` (Issue #1467) * Restored functionality of ``ciphers`` parameter for ``create_urllib3_context()``. (Issue #1462) 1.24 (2018-10-16) ----------------- * Allow key_server_hostname to be specified when initializing a PoolManager to allow custom SNI to be overridden. (Pull #1449) * Test against Python 3.7 on AppVeyor. (Pull #1453) * Early-out ipv6 checks when running on App Engine. (Pull #1450) * Change ambiguous description of backoff_factor (Pull #1436) * Add ability to handle multiple Content-Encodings (Issue #1441 and Pull #1442) * Skip DNS names that can't be idna-decoded when using pyOpenSSL (Issue #1405). * Add a server_hostname parameter to HTTPSConnection which allows for overriding the SNI hostname sent in the handshake. (Pull #1397) * Drop support for EOL Python 2.6 (Pull #1429 and Pull #1430) * Fixed bug where responses with header Content-Type: message/* erroneously raised HeaderParsingError, resulting in a warning being logged. (Pull #1439) * Move urllib3 to src/urllib3 (Pull #1409) 1.23 (2018-06-04) ----------------- * Allow providing a list of headers to strip from requests when redirecting to a different host. Defaults to the ``Authorization`` header. Different headers can be set via ``Retry.remove_headers_on_redirect``. (Issue #1316) * Fix ``util.selectors._fileobj_to_fd`` to accept ``long`` (Issue #1247). * Dropped Python 3.3 support. (Pull #1242) * Put the connection back in the pool when calling stream() or read_chunked() on a chunked HEAD response. (Issue #1234) * Fixed pyOpenSSL-specific ssl client authentication issue when clients attempted to auth via certificate + chain (Issue #1060) * Add the port to the connectionpool connect print (Pull #1251) * Don't use the ``uuid`` module to create multipart data boundaries. (Pull #1380) * ``read_chunked()`` on a closed response returns no chunks. (Issue #1088) * Add Python 2.6 support to ``contrib.securetransport`` (Pull #1359) * Added support for auth info in url for SOCKS proxy (Pull #1363) 1.22 (2017-07-20) ----------------- * Fixed missing brackets in ``HTTP CONNECT`` when connecting to IPv6 address via IPv6 proxy. (Issue #1222) * Made the connection pool retry on ``SSLError``. The original ``SSLError`` is available on ``MaxRetryError.reason``. (Issue #1112) * Drain and release connection before recursing on retry/redirect. Fixes deadlocks with a blocking connectionpool. (Issue #1167) * Fixed compatibility for cookiejar. (Issue #1229) * pyopenssl: Use vendored version of ``six``. (Issue #1231) 1.21.1 (2017-05-02) ------------------- * Fixed SecureTransport issue that would cause long delays in response body delivery. (Pull #1154) * Fixed regression in 1.21 that threw exceptions when users passed the ``socket_options`` flag to the ``PoolManager``. (Issue #1165) * Fixed regression in 1.21 that threw exceptions when users passed the ``assert_hostname`` or ``assert_fingerprint`` flag to the ``PoolManager``. (Pull #1157) 1.21 (2017-04-25) ----------------- * Improved performance of certain selector system calls on Python 3.5 and later. (Pull #1095) * Resolved issue where the PyOpenSSL backend would not wrap SysCallError exceptions appropriately when sending data. (Pull #1125) * Selectors now detects a monkey-patched select module after import for modules that patch the select module like eventlet, greenlet. (Pull #1128) * Reduced memory consumption when streaming zlib-compressed responses (as opposed to raw deflate streams). (Pull #1129) * Connection pools now use the entire request context when constructing the pool key. (Pull #1016) * ``PoolManager.connection_from_*`` methods now accept a new keyword argument, ``pool_kwargs``, which are merged with the existing ``connection_pool_kw``. (Pull #1016) * Add retry counter for ``status_forcelist``. (Issue #1147) * Added ``contrib`` module for using SecureTransport on macOS: ``urllib3.contrib.securetransport``. (Pull #1122) * urllib3 now only normalizes the case of ``http://`` and ``https://`` schemes: for schemes it does not recognise, it assumes they are case-sensitive and leaves them unchanged. (Issue #1080) 1.20 (2017-01-19) ----------------- * Added support for waiting for I/O using selectors other than select, improving urllib3's behaviour with large numbers of concurrent connections. (Pull #1001) * Updated the date for the system clock check. (Issue #1005) * ConnectionPools now correctly consider hostnames to be case-insensitive. (Issue #1032) * Outdated versions of PyOpenSSL now cause the PyOpenSSL contrib module to fail when it is injected, rather than at first use. (Pull #1063) * Outdated versions of cryptography now cause the PyOpenSSL contrib module to fail when it is injected, rather than at first use. (Issue #1044) * Automatically attempt to rewind a file-like body object when a request is retried or redirected. (Pull #1039) * Fix some bugs that occur when modules incautiously patch the queue module. (Pull #1061) * Prevent retries from occurring on read timeouts for which the request method was not in the method whitelist. (Issue #1059) * Changed the PyOpenSSL contrib module to lazily load idna to avoid unnecessarily bloating the memory of programs that don't need it. (Pull #1076) * Add support for IPv6 literals with zone identifiers. (Pull #1013) * Added support for socks5h:// and socks4a:// schemes when working with SOCKS proxies, and controlled remote DNS appropriately. (Issue #1035) 1.19.1 (2016-11-16) ------------------- * Fixed AppEngine import that didn't function on Python 3.5. (Pull #1025) 1.19 (2016-11-03) ----------------- * urllib3 now respects Retry-After headers on 413, 429, and 503 responses when using the default retry logic. (Pull #955) * Remove markers from setup.py to assist ancient setuptools versions. (Issue #986) * Disallow superscripts and other integerish things in URL ports. (Issue #989) * Allow urllib3's HTTPResponse.stream() method to continue to work with non-httplib underlying FPs. (Pull #990) * Empty filenames in multipart headers are now emitted as such, rather than being suppressed. (Issue #1015) * Prefer user-supplied Host headers on chunked uploads. (Issue #1009) 1.18.1 (2016-10-27) ------------------- * CVE-2016-9015. Users who are using urllib3 version 1.17 or 1.18 along with PyOpenSSL injection and OpenSSL 1.1.0 *must* upgrade to this version. This release fixes a vulnerability whereby urllib3 in the above configuration would silently fail to validate TLS certificates due to erroneously setting invalid flags in OpenSSL's ``SSL_CTX_set_verify`` function. These erroneous flags do not cause a problem in OpenSSL versions before 1.1.0, which interprets the presence of any flag as requesting certificate validation. There is no PR for this patch, as it was prepared for simultaneous disclosure and release. The master branch received the same fix in PR #1010. 1.18 (2016-09-26) ----------------- * Fixed incorrect message for IncompleteRead exception. (PR #973) * Accept ``iPAddress`` subject alternative name fields in TLS certificates. (Issue #258) * Fixed consistency of ``HTTPResponse.closed`` between Python 2 and 3. (Issue #977) * Fixed handling of wildcard certificates when using PyOpenSSL. (Issue #979) 1.17 (2016-09-06) ----------------- * Accept ``SSLContext`` objects for use in SSL/TLS negotiation. (Issue #835) * ConnectionPool debug log now includes scheme, host, and port. (Issue #897) * Substantially refactored documentation. (Issue #887) * Used URLFetch default timeout on AppEngine, rather than hardcoding our own. (Issue #858) * Normalize the scheme and host in the URL parser (Issue #833) * ``HTTPResponse`` contains the last ``Retry`` object, which now also contains retries history. (Issue #848) * Timeout can no longer be set as boolean, and must be greater than zero. (PR #924) * Removed pyasn1 and ndg-httpsclient from dependencies used for PyOpenSSL. We now use cryptography and idna, both of which are already dependencies of PyOpenSSL. (PR #930) * Fixed infinite loop in ``stream`` when amt=None. (Issue #928) * Try to use the operating system's certificates when we are using an ``SSLContext``. (PR #941) * Updated cipher suite list to allow ChaCha20+Poly1305. AES-GCM is preferred to ChaCha20, but ChaCha20 is then preferred to everything else. (PR #947) * Updated cipher suite list to remove 3DES-based cipher suites. (PR #958) * Removed the cipher suite fallback to allow HIGH ciphers. (PR #958) * Implemented ``length_remaining`` to determine remaining content to be read. (PR #949) * Implemented ``enforce_content_length`` to enable exceptions when incomplete data chunks are received. (PR #949) * Dropped connection start, dropped connection reset, redirect, forced retry, and new HTTPS connection log levels to DEBUG, from INFO. (PR #967) 1.16 (2016-06-11) ----------------- * Disable IPv6 DNS when IPv6 connections are not possible. (Issue #840) * Provide ``key_fn_by_scheme`` pool keying mechanism that can be overridden. (Issue #830) * Normalize scheme and host to lowercase for pool keys, and include ``source_address``. (Issue #830) * Cleaner exception chain in Python 3 for ``_make_request``. (Issue #861) * Fixed installing ``urllib3[socks]`` extra. (Issue #864) * Fixed signature of ``ConnectionPool.close`` so it can actually safely be called by subclasses. (Issue #873) * Retain ``release_conn`` state across retries. (Issues #651, #866) * Add customizable ``HTTPConnectionPool.ResponseCls``, which defaults to ``HTTPResponse`` but can be replaced with a subclass. (Issue #879) 1.15.1 (2016-04-11) ------------------- * Fix packaging to include backports module. (Issue #841) 1.15 (2016-04-06) ----------------- * Added Retry(raise_on_status=False). (Issue #720) * Always use setuptools, no more distutils fallback. (Issue #785) * Dropped support for Python 3.2. (Issue #786) * Chunked transfer encoding when requesting with ``chunked=True``. (Issue #790) * Fixed regression with IPv6 port parsing. (Issue #801) * Append SNIMissingWarning messages to allow users to specify it in the PYTHONWARNINGS environment variable. (Issue #816) * Handle unicode headers in Py2. (Issue #818) * Log certificate when there is a hostname mismatch. (Issue #820) * Preserve order of request/response headers. (Issue #821) 1.14 (2015-12-29) ----------------- * contrib: SOCKS proxy support! (Issue #762) * Fixed AppEngine handling of transfer-encoding header and bug in Timeout defaults checking. (Issue #763) 1.13.1 (2015-12-18) ------------------- * Fixed regression in IPv6 + SSL for match_hostname. (Issue #761) 1.13 (2015-12-14) ----------------- * Fixed ``pip install urllib3[secure]`` on modern pip. (Issue #706) * pyopenssl: Fixed SSL3_WRITE_PENDING error. (Issue #717) * pyopenssl: Support for TLSv1.1 and TLSv1.2. (Issue #696) * Close connections more defensively on exception. (Issue #734) * Adjusted ``read_chunked`` to handle gzipped, chunk-encoded bodies without repeatedly flushing the decoder, to function better on Jython. (Issue #743) * Accept ``ca_cert_dir`` for SSL-related PoolManager configuration. (Issue #758) 1.12 (2015-09-03) ----------------- * Rely on ``six`` for importing ``httplib`` to work around conflicts with other Python 3 shims. (Issue #688) * Add support for directories of certificate authorities, as supported by OpenSSL. (Issue #701) * New exception: ``NewConnectionError``, raised when we fail to establish a new connection, usually ``ECONNREFUSED`` socket error. 1.11 (2015-07-21) ----------------- * When ``ca_certs`` is given, ``cert_reqs`` defaults to ``'CERT_REQUIRED'``. (Issue #650) * ``pip install urllib3[secure]`` will install Certifi and PyOpenSSL as dependencies. (Issue #678) * Made ``HTTPHeaderDict`` usable as a ``headers`` input value (Issues #632, #679) * Added `urllib3.contrib.appengine `_ which has an ``AppEngineManager`` for using ``URLFetch`` in a Google AppEngine environment. (Issue #664) * Dev: Added test suite for AppEngine. (Issue #631) * Fix performance regression when using PyOpenSSL. (Issue #626) * Passing incorrect scheme (e.g. ``foo://``) will raise ``ValueError`` instead of ``AssertionError`` (backwards compatible for now, but please migrate). (Issue #640) * Fix pools not getting replenished when an error occurs during a request using ``release_conn=False``. (Issue #644) * Fix pool-default headers not applying for url-encoded requests like GET. (Issue #657) * log.warning in Python 3 when headers are skipped due to parsing errors. (Issue #642) * Close and discard connections if an error occurs during read. (Issue #660) * Fix host parsing for IPv6 proxies. (Issue #668) * Separate warning type SubjectAltNameWarning, now issued once per host. (Issue #671) * Fix ``httplib.IncompleteRead`` not getting converted to ``ProtocolError`` when using ``HTTPResponse.stream()`` (Issue #674) 1.10.4 (2015-05-03) ------------------- * Migrate tests to Tornado 4. (Issue #594) * Append default warning configuration rather than overwrite. (Issue #603) * Fix streaming decoding regression. (Issue #595) * Fix chunked requests losing state across keep-alive connections. (Issue #599) * Fix hanging when chunked HEAD response has no body. (Issue #605) 1.10.3 (2015-04-21) ------------------- * Emit ``InsecurePlatformWarning`` when SSLContext object is missing. (Issue #558) * Fix regression of duplicate header keys being discarded. (Issue #563) * ``Response.stream()`` returns a generator for chunked responses. (Issue #560) * Set upper-bound timeout when waiting for a socket in PyOpenSSL. (Issue #585) * Work on platforms without `ssl` module for plain HTTP requests. (Issue #587) * Stop relying on the stdlib's default cipher list. (Issue #588) 1.10.2 (2015-02-25) ------------------- * Fix file descriptor leakage on retries. (Issue #548) * Removed RC4 from default cipher list. (Issue #551) * Header performance improvements. (Issue #544) * Fix PoolManager not obeying redirect retry settings. (Issue #553) 1.10.1 (2015-02-10) ------------------- * Pools can be used as context managers. (Issue #545) * Don't re-use connections which experienced an SSLError. (Issue #529) * Don't fail when gzip decoding an empty stream. (Issue #535) * Add sha256 support for fingerprint verification. (Issue #540) * Fixed handling of header values containing commas. (Issue #533) 1.10 (2014-12-14) ----------------- * Disabled SSLv3. (Issue #473) * Add ``Url.url`` property to return the composed url string. (Issue #394) * Fixed PyOpenSSL + gevent ``WantWriteError``. (Issue #412) * ``MaxRetryError.reason`` will always be an exception, not string. (Issue #481) * Fixed SSL-related timeouts not being detected as timeouts. (Issue #492) * Py3: Use ``ssl.create_default_context()`` when available. (Issue #473) * Emit ``InsecureRequestWarning`` for *every* insecure HTTPS request. (Issue #496) * Emit ``SecurityWarning`` when certificate has no ``subjectAltName``. (Issue #499) * Close and discard sockets which experienced SSL-related errors. (Issue #501) * Handle ``body`` param in ``.request(...)``. (Issue #513) * Respect timeout with HTTPS proxy. (Issue #505) * PyOpenSSL: Handle ZeroReturnError exception. (Issue #520) 1.9.1 (2014-09-13) ------------------ * Apply socket arguments before binding. (Issue #427) * More careful checks if fp-like object is closed. (Issue #435) * Fixed packaging issues of some development-related files not getting included. (Issue #440) * Allow performing *only* fingerprint verification. (Issue #444) * Emit ``SecurityWarning`` if system clock is waaay off. (Issue #445) * Fixed PyOpenSSL compatibility with PyPy. (Issue #450) * Fixed ``BrokenPipeError`` and ``ConnectionError`` handling in Py3. (Issue #443) 1.9 (2014-07-04) ---------------- * Shuffled around development-related files. If you're maintaining a distro package of urllib3, you may need to tweak things. (Issue #415) * Unverified HTTPS requests will trigger a warning on the first request. See our new `security documentation `_ for details. (Issue #426) * New retry logic and ``urllib3.util.retry.Retry`` configuration object. (Issue #326) * All raised exceptions should now wrapped in a ``urllib3.exceptions.HTTPException``-extending exception. (Issue #326) * All errors during a retry-enabled request should be wrapped in ``urllib3.exceptions.MaxRetryError``, including timeout-related exceptions which were previously exempt. Underlying error is accessible from the ``.reason`` property. (Issue #326) * ``urllib3.exceptions.ConnectionError`` renamed to ``urllib3.exceptions.ProtocolError``. (Issue #326) * Errors during response read (such as IncompleteRead) are now wrapped in ``urllib3.exceptions.ProtocolError``. (Issue #418) * Requesting an empty host will raise ``urllib3.exceptions.LocationValueError``. (Issue #417) * Catch read timeouts over SSL connections as ``urllib3.exceptions.ReadTimeoutError``. (Issue #419) * Apply socket arguments before connecting. (Issue #427) 1.8.3 (2014-06-23) ------------------ * Fix TLS verification when using a proxy in Python 3.4.1. (Issue #385) * Add ``disable_cache`` option to ``urllib3.util.make_headers``. (Issue #393) * Wrap ``socket.timeout`` exception with ``urllib3.exceptions.ReadTimeoutError``. (Issue #399) * Fixed proxy-related bug where connections were being reused incorrectly. (Issues #366, #369) * Added ``socket_options`` keyword parameter which allows to define ``setsockopt`` configuration of new sockets. (Issue #397) * Removed ``HTTPConnection.tcp_nodelay`` in favor of ``HTTPConnection.default_socket_options``. (Issue #397) * Fixed ``TypeError`` bug in Python 2.6.4. (Issue #411) 1.8.2 (2014-04-17) ------------------ * Fix ``urllib3.util`` not being included in the package. 1.8.1 (2014-04-17) ------------------ * Fix AppEngine bug of HTTPS requests going out as HTTP. (Issue #356) * Don't install ``dummyserver`` into ``site-packages`` as it's only needed for the test suite. (Issue #362) * Added support for specifying ``source_address``. (Issue #352) 1.8 (2014-03-04) ---------------- * Improved url parsing in ``urllib3.util.parse_url`` (properly parse '@' in username, and blank ports like 'hostname:'). * New ``urllib3.connection`` module which contains all the HTTPConnection objects. * Several ``urllib3.util.Timeout``-related fixes. Also changed constructor signature to a more sensible order. [Backwards incompatible] (Issues #252, #262, #263) * Use ``backports.ssl_match_hostname`` if it's installed. (Issue #274) * Added ``.tell()`` method to ``urllib3.response.HTTPResponse`` which returns the number of bytes read so far. (Issue #277) * Support for platforms without threading. (Issue #289) * Expand default-port comparison in ``HTTPConnectionPool.is_same_host`` to allow a pool with no specified port to be considered equal to to an HTTP/HTTPS url with port 80/443 explicitly provided. (Issue #305) * Improved default SSL/TLS settings to avoid vulnerabilities. (Issue #309) * Fixed ``urllib3.poolmanager.ProxyManager`` not retrying on connect errors. (Issue #310) * Disable Nagle's Algorithm on the socket for non-proxies. A subset of requests will send the entire HTTP request ~200 milliseconds faster; however, some of the resulting TCP packets will be smaller. (Issue #254) * Increased maximum number of SubjectAltNames in ``urllib3.contrib.pyopenssl`` from the default 64 to 1024 in a single certificate. (Issue #318) * Headers are now passed and stored as a custom ``urllib3.collections_.HTTPHeaderDict`` object rather than a plain ``dict``. (Issue #329, #333) * Headers no longer lose their case on Python 3. (Issue #236) * ``urllib3.contrib.pyopenssl`` now uses the operating system's default CA certificates on inject. (Issue #332) * Requests with ``retries=False`` will immediately raise any exceptions without wrapping them in ``MaxRetryError``. (Issue #348) * Fixed open socket leak with SSL-related failures. (Issue #344, #348) 1.7.1 (2013-09-25) ------------------ * Added granular timeout support with new ``urllib3.util.Timeout`` class. (Issue #231) * Fixed Python 3.4 support. (Issue #238) 1.7 (2013-08-14) ---------------- * More exceptions are now pickle-able, with tests. (Issue #174) * Fixed redirecting with relative URLs in Location header. (Issue #178) * Support for relative urls in ``Location: ...`` header. (Issue #179) * ``urllib3.response.HTTPResponse`` now inherits from ``io.IOBase`` for bonus file-like functionality. (Issue #187) * Passing ``assert_hostname=False`` when creating a HTTPSConnectionPool will skip hostname verification for SSL connections. (Issue #194) * New method ``urllib3.response.HTTPResponse.stream(...)`` which acts as a generator wrapped around ``.read(...)``. (Issue #198) * IPv6 url parsing enforces brackets around the hostname. (Issue #199) * Fixed thread race condition in ``urllib3.poolmanager.PoolManager.connection_from_host(...)`` (Issue #204) * ``ProxyManager`` requests now include non-default port in ``Host: ...`` header. (Issue #217) * Added HTTPS proxy support in ``ProxyManager``. (Issue #170 #139) * New ``RequestField`` object can be passed to the ``fields=...`` param which can specify headers. (Issue #220) * Raise ``urllib3.exceptions.ProxyError`` when connecting to proxy fails. (Issue #221) * Use international headers when posting file names. (Issue #119) * Improved IPv6 support. (Issue #203) 1.6 (2013-04-25) ---------------- * Contrib: Optional SNI support for Py2 using PyOpenSSL. (Issue #156) * ``ProxyManager`` automatically adds ``Host: ...`` header if not given. * Improved SSL-related code. ``cert_req`` now optionally takes a string like "REQUIRED" or "NONE". Same with ``ssl_version`` takes strings like "SSLv23" The string values reflect the suffix of the respective constant variable. (Issue #130) * Vendored ``socksipy`` now based on Anorov's fork which handles unexpectedly closed proxy connections and larger read buffers. (Issue #135) * Ensure the connection is closed if no data is received, fixes connection leak on some platforms. (Issue #133) * Added SNI support for SSL/TLS connections on Py32+. (Issue #89) * Tests fixed to be compatible with Py26 again. (Issue #125) * Added ability to choose SSL version by passing an ``ssl.PROTOCOL_*`` constant to the ``ssl_version`` parameter of ``HTTPSConnectionPool``. (Issue #109) * Allow an explicit content type to be specified when encoding file fields. (Issue #126) * Exceptions are now pickleable, with tests. (Issue #101) * Fixed default headers not getting passed in some cases. (Issue #99) * Treat "content-encoding" header value as case-insensitive, per RFC 2616 Section 3.5. (Issue #110) * "Connection Refused" SocketErrors will get retried rather than raised. (Issue #92) * Updated vendored ``six``, no longer overrides the global ``six`` module namespace. (Issue #113) * ``urllib3.exceptions.MaxRetryError`` contains a ``reason`` property holding the exception that prompted the final retry. If ``reason is None`` then it was due to a redirect. (Issue #92, #114) * Fixed ``PoolManager.urlopen()`` from not redirecting more than once. (Issue #149) * Don't assume ``Content-Type: text/plain`` for multi-part encoding parameters that are not files. (Issue #111) * Pass `strict` param down to ``httplib.HTTPConnection``. (Issue #122) * Added mechanism to verify SSL certificates by fingerprint (md5, sha1) or against an arbitrary hostname (when connecting by IP or for misconfigured servers). (Issue #140) * Streaming decompression support. (Issue #159) 1.5 (2012-08-02) ---------------- * Added ``urllib3.add_stderr_logger()`` for quickly enabling STDERR debug logging in urllib3. * Native full URL parsing (including auth, path, query, fragment) available in ``urllib3.util.parse_url(url)``. * Built-in redirect will switch method to 'GET' if status code is 303. (Issue #11) * ``urllib3.PoolManager`` strips the scheme and host before sending the request uri. (Issue #8) * New ``urllib3.exceptions.DecodeError`` exception for when automatic decoding, based on the Content-Type header, fails. * Fixed bug with pool depletion and leaking connections (Issue #76). Added explicit connection closing on pool eviction. Added ``urllib3.PoolManager.clear()``. * 99% -> 100% unit test coverage. 1.4 (2012-06-16) ---------------- * Minor AppEngine-related fixes. * Switched from ``mimetools.choose_boundary`` to ``uuid.uuid4()``. * Improved url parsing. (Issue #73) * IPv6 url support. (Issue #72) 1.3 (2012-03-25) ---------------- * Removed pre-1.0 deprecated API. * Refactored helpers into a ``urllib3.util`` submodule. * Fixed multipart encoding to support list-of-tuples for keys with multiple values. (Issue #48) * Fixed multiple Set-Cookie headers in response not getting merged properly in Python 3. (Issue #53) * AppEngine support with Py27. (Issue #61) * Minor ``encode_multipart_formdata`` fixes related to Python 3 strings vs bytes. 1.2.2 (2012-02-06) ------------------ * Fixed packaging bug of not shipping ``test-requirements.txt``. (Issue #47) 1.2.1 (2012-02-05) ------------------ * Fixed another bug related to when ``ssl`` module is not available. (Issue #41) * Location parsing errors now raise ``urllib3.exceptions.LocationParseError`` which inherits from ``ValueError``. 1.2 (2012-01-29) ---------------- * Added Python 3 support (tested on 3.2.2) * Dropped Python 2.5 support (tested on 2.6.7, 2.7.2) * Use ``select.poll`` instead of ``select.select`` for platforms that support it. * Use ``Queue.LifoQueue`` instead of ``Queue.Queue`` for more aggressive connection reusing. Configurable by overriding ``ConnectionPool.QueueCls``. * Fixed ``ImportError`` during install when ``ssl`` module is not available. (Issue #41) * Fixed ``PoolManager`` redirects between schemes (such as HTTP -> HTTPS) not completing properly. (Issue #28, uncovered by Issue #10 in v1.1) * Ported ``dummyserver`` to use ``tornado`` instead of ``webob`` + ``eventlet``. Removed extraneous unsupported dummyserver testing backends. Added socket-level tests. * More tests. Achievement Unlocked: 99% Coverage. 1.1 (2012-01-07) ---------------- * Refactored ``dummyserver`` to its own root namespace module (used for testing). * Added hostname verification for ``VerifiedHTTPSConnection`` by vendoring in Py32's ``ssl_match_hostname``. (Issue #25) * Fixed cross-host HTTP redirects when using ``PoolManager``. (Issue #10) * Fixed ``decode_content`` being ignored when set through ``urlopen``. (Issue #27) * Fixed timeout-related bugs. (Issues #17, #23) 1.0.2 (2011-11-04) ------------------ * Fixed typo in ``VerifiedHTTPSConnection`` which would only present as a bug if you're using the object manually. (Thanks pyos) * Made RecentlyUsedContainer (and consequently PoolManager) more thread-safe by wrapping the access log in a mutex. (Thanks @christer) * Made RecentlyUsedContainer more dict-like (corrected ``__delitem__`` and ``__getitem__`` behaviour), with tests. Shouldn't affect core urllib3 code. 1.0.1 (2011-10-10) ------------------ * Fixed a bug where the same connection would get returned into the pool twice, causing extraneous "HttpConnectionPool is full" log warnings. 1.0 (2011-10-08) ---------------- * Added ``PoolManager`` with LRU expiration of connections (tested and documented). * Added ``ProxyManager`` (needs tests, docs, and confirmation that it works with HTTPS proxies). * Added optional partial-read support for responses when ``preload_content=False``. You can now make requests and just read the headers without loading the content. * Made response decoding optional (default on, same as before). * Added optional explicit boundary string for ``encode_multipart_formdata``. * Convenience request methods are now inherited from ``RequestMethods``. Old helpers like ``get_url`` and ``post_url`` should be abandoned in favour of the new ``request(method, url, ...)``. * Refactored code to be even more decoupled, reusable, and extendable. * License header added to ``.py`` files. * Embiggened the documentation: Lots of Sphinx-friendly docstrings in the code and docs in ``docs/`` and on https://urllib3.readthedocs.io/. * Embettered all the things! * Started writing this file. 0.4.1 (2011-07-17) ------------------ * Minor bug fixes, code cleanup. 0.4 (2011-03-01) ---------------- * Better unicode support. * Added ``VerifiedHTTPSConnection``. * Added ``NTLMConnectionPool`` in contrib. * Minor improvements. 0.3.1 (2010-07-13) ------------------ * Added ``assert_host_name`` optional parameter. Now compatible with proxies. 0.3 (2009-12-10) ---------------- * Added HTTPS support. * Minor bug fixes. * Refactored, broken backwards compatibility with 0.2. * API to be treated as stable from this version forward. 0.2 (2008-11-17) ---------------- * Added unit tests. * Bug fixes. 0.1 (2008-11-16) ---------------- * First release. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/CONTRIBUTORS.txt0000644000175000017500000002227100000000000020606 0ustar00sethmlarsonsethmlarson00000000000000# Contributions to the urllib3 project ## Creator & Maintainer * Andrey Petrov ## Contributors In chronological order: * victor.vde * HTTPS patch (which inspired HTTPSConnectionPool) * erikcederstrand * NTLM-authenticated HTTPSConnectionPool * Basic-authenticated HTTPSConnectionPool (merged into make_headers) * niphlod * Client-verified SSL certificates for HTTPSConnectionPool * Response gzip and deflate encoding support * Better unicode support for filepost using StringIO buffers * btoconnor * Non-multipart encoding for POST requests * p.dobrogost * Code review, PEP8 compliance, benchmark fix * kennethreitz * Bugfixes, suggestions, Requests integration * georgemarshall * Bugfixes, Improvements and Test coverage * Thomas Kluyver * Python 3 support * brandon-rhodes * Design review, bugfixes, test coverage. * studer * IPv6 url support and test coverage * Shivaram Lingamneni * Support for explicitly closing pooled connections * hartator * Corrected multipart behavior for params * Thomas Weißschuh * Support for TLS SNI * API unification of ssl_version/cert_reqs * SSL fingerprint and alternative hostname verification * Bugfixes in testsuite * Sune Kirkeby * Optional SNI-support for Python 2 via PyOpenSSL. * Marc Schlaich * Various bugfixes and test improvements. * Bryce Boe * Correct six.moves conflict * Fixed pickle support of some exceptions * Boris Figovsky * Allowed to skip SSL hostname verification * Cory Benfield * Stream method for Response objects. * Return native strings in header values. * Generate 'Host' header when using proxies. * Jason Robinson * Add missing WrappedSocket.fileno method in PyOpenSSL * Audrius Butkevicius * Fixed a race condition * Stanislav Vitkovskiy * Added HTTPS (CONNECT) proxy support * Stephen Holsapple * Added abstraction for granular control of request fields * Martin von Gagern * Support for non-ASCII header parameters * Kevin Burke and Pavel Kirichenko * Support for separate connect and request timeouts * Peter Waller * HTTPResponse.tell() for determining amount received over the wire * Nipunn Koorapati * Ignore default ports when comparing hosts for equality * Danilo @dbrgn * Disabled TLS compression by default on Python 3.2+ * Disabled TLS compression in pyopenssl contrib module * Configurable cipher suites in pyopenssl contrib module * Roman Bogorodskiy * Account retries on proxy errors * Nicolas Delaby * Use the platform-specific CA certificate locations * Josh Schneier * HTTPHeaderDict and associated tests and docs * Bugfixes, docs, test coverage * Tahia Khan * Added Timeout examples in docs * Arthur Grunseid * source_address support and tests (with https://github.com/bui) * Ian Cordasco * PEP8 Compliance and Linting * Add ability to pass socket options to an HTTP Connection * Erik Tollerud * Support for standard library io module. * Krishna Prasad * Google App Engine documentation * Aaron Meurer * Added Url.url, which unparses a Url * Evgeny Kapun * Bugfixes * Benjamen Meyer * Security Warning Documentation update for proper capture * Shivan Sornarajah * Support for using ConnectionPool and PoolManager as context managers. * Alex Gaynor * Updates to the default SSL configuration * Tomas Tomecek * Implemented generator for getting chunks from chunked responses. * tlynn * Respect the warning preferences at import. * David D. Riddle * IPv6 bugfixes in testsuite * Thea Flowers * App Engine environment tests. * Documentation re-write. * John Krauss * Clues to debugging problems with `cryptography` dependency in docs * Disassem * Fix pool-default headers not applying for url-encoded requests like GET. * James Atherfold * Bugfixes relating to cleanup of connections during errors. * Christian Pedersen * IPv6 HTTPS proxy bugfix * Jordan Moldow * Fix low-level exceptions leaking from ``HTTPResponse.stream()``. * Bugfix for ``ConnectionPool.urlopen(release_conn=False)``. * Creation of ``HTTPConnectionPool.ResponseCls``. * Predrag Gruevski * Made cert digest comparison use a constant-time algorithm. * Adam Talsma * Bugfix to ca_cert file paths. * Evan Meagher * Bugfix related to `memoryview` usage in PyOpenSSL adapter * John Vandenberg * Python 2.6 fixes; pyflakes and pep8 compliance * Andy Caldwell * Bugfix related to reusing connections in indeterminate states. * Ville Skyttä * Logging efficiency improvements, spelling fixes, Travis config. * Shige Takeda * Started Recipes documentation and added a recipe about handling concatenated gzip data in HTTP response * Jess Shapiro * Various character-encoding fixes/tweaks * Disabling IPv6 DNS when IPv6 connections not supported * David Foster * Ensure order of request and response headers are preserved. * Jeremy Cline * Added connection pool keys by scheme * Aviv Palivoda * History list to Retry object. * HTTPResponse contains the last Retry object. * Nate Prewitt * Ensure timeouts are not booleans and greater than zero. * Fixed infinite loop in ``stream`` when amt=None. * Added length_remaining to determine remaining data to be read. * Added enforce_content_length to raise exception when incorrect content-length received. * Seth Michael Larson * Created selectors backport that supports PEP 475. * Alexandre Dias * Don't retry on timeout if method not in whitelist * Moinuddin Quadri * Lazily load idna package * Tom White * Made SOCKS handler differentiate socks5h from socks5 and socks4a from socks4. * Tim Burke * Stop buffering entire deflate-encoded responses. * Tuukka Mustonen * Add counter for status_forcelist retries. * Erik Rose * Bugfix to pyopenssl vendoring * Wolfgang Richter * Bugfix related to loading full certificate chains with PyOpenSSL backend. * Mike Miller * Logging improvements to include the HTTP(S) port when opening a new connection * Ioannis Tziakos * Fix ``util.selectors._fileobj_to_fd`` to accept ``long``. * Update appveyor tox setup to use the 64bit python. * Akamai (through Jess Shapiro) * Ongoing maintenance; 2017-2018 * Dominique Leuenberger * Minor fixes in the test suite * Will Bond * Add Python 2.6 support to ``contrib.securetransport`` * Aleksei Alekseev * using auth info for socks proxy * Chris Wilcox * Improve contribution guide * Add ``HTTPResponse.geturl`` method to provide ``urllib2.urlopen().geturl()`` behavior * Bruce Merry * Fix leaking exceptions when system calls are interrupted with zero timeout * Hugo van Kemenade * Drop support for EOL Python 2.6 * Tim Bell * Bugfix for responses with Content-Type: message/* logging warnings * Justin Bramley * Add ability to handle multiple Content-Encodings * Katsuhiko YOSHIDA * Remove Authorization header regardless of case when redirecting to cross-site * James Meickle * Improve handling of Retry-After header * Chris Jerdonek * Remove a spurious TypeError from the exception chain inside HTTPConnectionPool._make_request(), also for BaseExceptions. * [Your name or handle] <[email or website]> * [Brief summary of your changes] ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/LICENSE.txt0000644000175000017500000000213300000000000017726 0ustar00sethmlarsonsethmlarson00000000000000MIT License Copyright (c) 2008-2019 Andrey Petrov and contributors (see CONTRIBUTORS.txt) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/MANIFEST.in0000644000175000017500000000031400000000000017640 0ustar00sethmlarsonsethmlarson00000000000000include README.rst CHANGES.rst LICENSE.txt CONTRIBUTORS.txt dev-requirements.txt Makefile recursive-include dummyserver * recursive-include test * recursive-include docs * recursive-exclude docs/_build * ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/PKG-INFO0000644000175000017500000013601400000000000017206 0ustar00sethmlarsonsethmlarson00000000000000Metadata-Version: 2.1 Name: urllib3 Version: 1.25.8 Summary: HTTP library with thread-safe connection pooling, file post, and more. Home-page: https://urllib3.readthedocs.io/ Author: Andrey Petrov Author-email: andrey.petrov@shazow.net License: MIT Project-URL: Documentation, https://urllib3.readthedocs.io/ Project-URL: Code, https://github.com/urllib3/urllib3 Project-URL: Issue tracker, https://github.com/urllib3/urllib3/issues Description: urllib3 ======= urllib3 is a powerful, *sanity-friendly* HTTP client for Python. Much of the Python ecosystem already uses urllib3 and you should too. urllib3 brings many critical features that are missing from the Python standard libraries: - Thread safety. - Connection pooling. - Client-side SSL/TLS verification. - File uploads with multipart encoding. - Helpers for retrying requests and dealing with HTTP redirects. - Support for gzip, deflate, and brotli encoding. - Proxy support for HTTP and SOCKS. - 100% test coverage. urllib3 is powerful and easy to use:: >>> import urllib3 >>> http = urllib3.PoolManager() >>> r = http.request('GET', 'http://httpbin.org/robots.txt') >>> r.status 200 >>> r.data 'User-agent: *\nDisallow: /deny\n' Installing ---------- urllib3 can be installed with `pip `_:: $ pip install urllib3 Alternatively, you can grab the latest source code from `GitHub `_:: $ git clone git://github.com/urllib3/urllib3.git $ python setup.py install Documentation ------------- urllib3 has usage and reference documentation at `urllib3.readthedocs.io `_. Contributing ------------ urllib3 happily accepts contributions. Please see our `contributing documentation `_ for some tips on getting started. Security Disclosures -------------------- To report a security vulnerability, please use the `Tidelift security contact `_. Tidelift will coordinate the fix and disclosure with maintainers. Maintainers ----------- - `@sethmlarson `_ (Seth M. Larson) - `@pquentin `_ (Quentin Pradet) - `@theacodes `_ (Thea Flowers) - `@haikuginger `_ (Jess Shapiro) - `@lukasa `_ (Cory Benfield) - `@sigmavirus24 `_ (Ian Stapleton Cordasco) - `@shazow `_ (Andrey Petrov) 👋 Sponsorship ----------- .. |tideliftlogo| image:: https://nedbatchelder.com/pix/Tidelift_Logos_RGB_Tidelift_Shorthand_On-White_small.png :width: 75 :alt: Tidelift .. list-table:: :widths: 10 100 * - |tideliftlogo| - Professional support for urllib3 is available as part of the `Tidelift Subscription`_. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools. .. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=readme If your company benefits from this library, please consider `sponsoring its development `_. Sponsors include: - Abbott (2018-2019), sponsored `@sethmlarson `_'s work on urllib3. - Google Cloud Platform (2018-2019), sponsored `@theacodes `_'s work on urllib3. - Akamai (2017-2018), sponsored `@haikuginger `_'s work on urllib3 - Hewlett Packard Enterprise (2016-2017), sponsored `@Lukasa’s `_ work on urllib3. Changes ======= 1.25.8 (2020-01-20) ------------------- * Drop support for EOL Python 3.4 (Pull #1774) * Optimize _encode_invalid_chars (Pull #1787) 1.25.7 (2019-11-11) ------------------- * Preserve ``chunked`` parameter on retries (Pull #1715, Pull #1734) * Allow unset ``SERVER_SOFTWARE`` in App Engine (Pull #1704, Issue #1470) * Fix issue where URL fragment was sent within the request target. (Pull #1732) * Fix issue where an empty query section in a URL would fail to parse. (Pull #1732) * Remove TLS 1.3 support in SecureTransport due to Apple removing support (Pull #1703) 1.25.6 (2019-09-24) ------------------- * Fix issue where tilde (``~``) characters were incorrectly percent-encoded in the path. (Pull #1692) 1.25.5 (2019-09-19) ------------------- * Add mitigation for BPO-37428 affecting Python <3.7.4 and OpenSSL 1.1.1+ which caused certificate verification to be enabled when using ``cert_reqs=CERT_NONE``. (Issue #1682) 1.25.4 (2019-09-19) ------------------- * Propagate Retry-After header settings to subsequent retries. (Pull #1607) * Fix edge case where Retry-After header was still respected even when explicitly opted out of. (Pull #1607) * Remove dependency on ``rfc3986`` for URL parsing. * Fix issue where URLs containing invalid characters within ``Url.auth`` would raise an exception instead of percent-encoding those characters. * Add support for ``HTTPResponse.auto_close = False`` which makes HTTP responses work well with BufferedReaders and other ``io`` module features. (Pull #1652) * Percent-encode invalid characters in URL for ``HTTPConnectionPool.request()`` (Pull #1673) 1.25.3 (2019-05-23) ------------------- * Change ``HTTPSConnection`` to load system CA certificates when ``ca_certs``, ``ca_cert_dir``, and ``ssl_context`` are unspecified. (Pull #1608, Issue #1603) * Upgrade bundled rfc3986 to v1.3.2. (Pull #1609, Issue #1605) 1.25.2 (2019-04-28) ------------------- * Change ``is_ipaddress`` to not detect IPvFuture addresses. (Pull #1583) * Change ``parse_url`` to percent-encode invalid characters within the path, query, and target components. (Pull #1586) 1.25.1 (2019-04-24) ------------------- * Add support for Google's ``Brotli`` package. (Pull #1572, Pull #1579) * Upgrade bundled rfc3986 to v1.3.1 (Pull #1578) 1.25 (2019-04-22) ----------------- * Require and validate certificates by default when using HTTPS (Pull #1507) * Upgraded ``urllib3.utils.parse_url()`` to be RFC 3986 compliant. (Pull #1487) * Added support for ``key_password`` for ``HTTPSConnectionPool`` to use encrypted ``key_file`` without creating your own ``SSLContext`` object. (Pull #1489) * Add TLSv1.3 support to CPython, pyOpenSSL, and SecureTransport ``SSLContext`` implementations. (Pull #1496) * Switched the default multipart header encoder from RFC 2231 to HTML 5 working draft. (Issue #303, PR #1492) * Fixed issue where OpenSSL would block if an encrypted client private key was given and no password was given. Instead an ``SSLError`` is raised. (Pull #1489) * Added support for Brotli content encoding. It is enabled automatically if ``brotlipy`` package is installed which can be requested with ``urllib3[brotli]`` extra. (Pull #1532) * Drop ciphers using DSS key exchange from default TLS cipher suites. Improve default ciphers when using SecureTransport. (Pull #1496) * Implemented a more efficient ``HTTPResponse.__iter__()`` method. (Issue #1483) 1.24.3 (2019-05-01) ------------------- * Apply fix for CVE-2019-9740. (Pull #1591) 1.24.2 (2019-04-17) ------------------- * Don't load system certificates by default when any other ``ca_certs``, ``ca_certs_dir`` or ``ssl_context`` parameters are specified. * Remove Authorization header regardless of case when redirecting to cross-site. (Issue #1510) * Add support for IPv6 addresses in subjectAltName section of certificates. (Issue #1269) 1.24.1 (2018-11-02) ------------------- * Remove quadratic behavior within ``GzipDecoder.decompress()`` (Issue #1467) * Restored functionality of ``ciphers`` parameter for ``create_urllib3_context()``. (Issue #1462) 1.24 (2018-10-16) ----------------- * Allow key_server_hostname to be specified when initializing a PoolManager to allow custom SNI to be overridden. (Pull #1449) * Test against Python 3.7 on AppVeyor. (Pull #1453) * Early-out ipv6 checks when running on App Engine. (Pull #1450) * Change ambiguous description of backoff_factor (Pull #1436) * Add ability to handle multiple Content-Encodings (Issue #1441 and Pull #1442) * Skip DNS names that can't be idna-decoded when using pyOpenSSL (Issue #1405). * Add a server_hostname parameter to HTTPSConnection which allows for overriding the SNI hostname sent in the handshake. (Pull #1397) * Drop support for EOL Python 2.6 (Pull #1429 and Pull #1430) * Fixed bug where responses with header Content-Type: message/* erroneously raised HeaderParsingError, resulting in a warning being logged. (Pull #1439) * Move urllib3 to src/urllib3 (Pull #1409) 1.23 (2018-06-04) ----------------- * Allow providing a list of headers to strip from requests when redirecting to a different host. Defaults to the ``Authorization`` header. Different headers can be set via ``Retry.remove_headers_on_redirect``. (Issue #1316) * Fix ``util.selectors._fileobj_to_fd`` to accept ``long`` (Issue #1247). * Dropped Python 3.3 support. (Pull #1242) * Put the connection back in the pool when calling stream() or read_chunked() on a chunked HEAD response. (Issue #1234) * Fixed pyOpenSSL-specific ssl client authentication issue when clients attempted to auth via certificate + chain (Issue #1060) * Add the port to the connectionpool connect print (Pull #1251) * Don't use the ``uuid`` module to create multipart data boundaries. (Pull #1380) * ``read_chunked()`` on a closed response returns no chunks. (Issue #1088) * Add Python 2.6 support to ``contrib.securetransport`` (Pull #1359) * Added support for auth info in url for SOCKS proxy (Pull #1363) 1.22 (2017-07-20) ----------------- * Fixed missing brackets in ``HTTP CONNECT`` when connecting to IPv6 address via IPv6 proxy. (Issue #1222) * Made the connection pool retry on ``SSLError``. The original ``SSLError`` is available on ``MaxRetryError.reason``. (Issue #1112) * Drain and release connection before recursing on retry/redirect. Fixes deadlocks with a blocking connectionpool. (Issue #1167) * Fixed compatibility for cookiejar. (Issue #1229) * pyopenssl: Use vendored version of ``six``. (Issue #1231) 1.21.1 (2017-05-02) ------------------- * Fixed SecureTransport issue that would cause long delays in response body delivery. (Pull #1154) * Fixed regression in 1.21 that threw exceptions when users passed the ``socket_options`` flag to the ``PoolManager``. (Issue #1165) * Fixed regression in 1.21 that threw exceptions when users passed the ``assert_hostname`` or ``assert_fingerprint`` flag to the ``PoolManager``. (Pull #1157) 1.21 (2017-04-25) ----------------- * Improved performance of certain selector system calls on Python 3.5 and later. (Pull #1095) * Resolved issue where the PyOpenSSL backend would not wrap SysCallError exceptions appropriately when sending data. (Pull #1125) * Selectors now detects a monkey-patched select module after import for modules that patch the select module like eventlet, greenlet. (Pull #1128) * Reduced memory consumption when streaming zlib-compressed responses (as opposed to raw deflate streams). (Pull #1129) * Connection pools now use the entire request context when constructing the pool key. (Pull #1016) * ``PoolManager.connection_from_*`` methods now accept a new keyword argument, ``pool_kwargs``, which are merged with the existing ``connection_pool_kw``. (Pull #1016) * Add retry counter for ``status_forcelist``. (Issue #1147) * Added ``contrib`` module for using SecureTransport on macOS: ``urllib3.contrib.securetransport``. (Pull #1122) * urllib3 now only normalizes the case of ``http://`` and ``https://`` schemes: for schemes it does not recognise, it assumes they are case-sensitive and leaves them unchanged. (Issue #1080) 1.20 (2017-01-19) ----------------- * Added support for waiting for I/O using selectors other than select, improving urllib3's behaviour with large numbers of concurrent connections. (Pull #1001) * Updated the date for the system clock check. (Issue #1005) * ConnectionPools now correctly consider hostnames to be case-insensitive. (Issue #1032) * Outdated versions of PyOpenSSL now cause the PyOpenSSL contrib module to fail when it is injected, rather than at first use. (Pull #1063) * Outdated versions of cryptography now cause the PyOpenSSL contrib module to fail when it is injected, rather than at first use. (Issue #1044) * Automatically attempt to rewind a file-like body object when a request is retried or redirected. (Pull #1039) * Fix some bugs that occur when modules incautiously patch the queue module. (Pull #1061) * Prevent retries from occurring on read timeouts for which the request method was not in the method whitelist. (Issue #1059) * Changed the PyOpenSSL contrib module to lazily load idna to avoid unnecessarily bloating the memory of programs that don't need it. (Pull #1076) * Add support for IPv6 literals with zone identifiers. (Pull #1013) * Added support for socks5h:// and socks4a:// schemes when working with SOCKS proxies, and controlled remote DNS appropriately. (Issue #1035) 1.19.1 (2016-11-16) ------------------- * Fixed AppEngine import that didn't function on Python 3.5. (Pull #1025) 1.19 (2016-11-03) ----------------- * urllib3 now respects Retry-After headers on 413, 429, and 503 responses when using the default retry logic. (Pull #955) * Remove markers from setup.py to assist ancient setuptools versions. (Issue #986) * Disallow superscripts and other integerish things in URL ports. (Issue #989) * Allow urllib3's HTTPResponse.stream() method to continue to work with non-httplib underlying FPs. (Pull #990) * Empty filenames in multipart headers are now emitted as such, rather than being suppressed. (Issue #1015) * Prefer user-supplied Host headers on chunked uploads. (Issue #1009) 1.18.1 (2016-10-27) ------------------- * CVE-2016-9015. Users who are using urllib3 version 1.17 or 1.18 along with PyOpenSSL injection and OpenSSL 1.1.0 *must* upgrade to this version. This release fixes a vulnerability whereby urllib3 in the above configuration would silently fail to validate TLS certificates due to erroneously setting invalid flags in OpenSSL's ``SSL_CTX_set_verify`` function. These erroneous flags do not cause a problem in OpenSSL versions before 1.1.0, which interprets the presence of any flag as requesting certificate validation. There is no PR for this patch, as it was prepared for simultaneous disclosure and release. The master branch received the same fix in PR #1010. 1.18 (2016-09-26) ----------------- * Fixed incorrect message for IncompleteRead exception. (PR #973) * Accept ``iPAddress`` subject alternative name fields in TLS certificates. (Issue #258) * Fixed consistency of ``HTTPResponse.closed`` between Python 2 and 3. (Issue #977) * Fixed handling of wildcard certificates when using PyOpenSSL. (Issue #979) 1.17 (2016-09-06) ----------------- * Accept ``SSLContext`` objects for use in SSL/TLS negotiation. (Issue #835) * ConnectionPool debug log now includes scheme, host, and port. (Issue #897) * Substantially refactored documentation. (Issue #887) * Used URLFetch default timeout on AppEngine, rather than hardcoding our own. (Issue #858) * Normalize the scheme and host in the URL parser (Issue #833) * ``HTTPResponse`` contains the last ``Retry`` object, which now also contains retries history. (Issue #848) * Timeout can no longer be set as boolean, and must be greater than zero. (PR #924) * Removed pyasn1 and ndg-httpsclient from dependencies used for PyOpenSSL. We now use cryptography and idna, both of which are already dependencies of PyOpenSSL. (PR #930) * Fixed infinite loop in ``stream`` when amt=None. (Issue #928) * Try to use the operating system's certificates when we are using an ``SSLContext``. (PR #941) * Updated cipher suite list to allow ChaCha20+Poly1305. AES-GCM is preferred to ChaCha20, but ChaCha20 is then preferred to everything else. (PR #947) * Updated cipher suite list to remove 3DES-based cipher suites. (PR #958) * Removed the cipher suite fallback to allow HIGH ciphers. (PR #958) * Implemented ``length_remaining`` to determine remaining content to be read. (PR #949) * Implemented ``enforce_content_length`` to enable exceptions when incomplete data chunks are received. (PR #949) * Dropped connection start, dropped connection reset, redirect, forced retry, and new HTTPS connection log levels to DEBUG, from INFO. (PR #967) 1.16 (2016-06-11) ----------------- * Disable IPv6 DNS when IPv6 connections are not possible. (Issue #840) * Provide ``key_fn_by_scheme`` pool keying mechanism that can be overridden. (Issue #830) * Normalize scheme and host to lowercase for pool keys, and include ``source_address``. (Issue #830) * Cleaner exception chain in Python 3 for ``_make_request``. (Issue #861) * Fixed installing ``urllib3[socks]`` extra. (Issue #864) * Fixed signature of ``ConnectionPool.close`` so it can actually safely be called by subclasses. (Issue #873) * Retain ``release_conn`` state across retries. (Issues #651, #866) * Add customizable ``HTTPConnectionPool.ResponseCls``, which defaults to ``HTTPResponse`` but can be replaced with a subclass. (Issue #879) 1.15.1 (2016-04-11) ------------------- * Fix packaging to include backports module. (Issue #841) 1.15 (2016-04-06) ----------------- * Added Retry(raise_on_status=False). (Issue #720) * Always use setuptools, no more distutils fallback. (Issue #785) * Dropped support for Python 3.2. (Issue #786) * Chunked transfer encoding when requesting with ``chunked=True``. (Issue #790) * Fixed regression with IPv6 port parsing. (Issue #801) * Append SNIMissingWarning messages to allow users to specify it in the PYTHONWARNINGS environment variable. (Issue #816) * Handle unicode headers in Py2. (Issue #818) * Log certificate when there is a hostname mismatch. (Issue #820) * Preserve order of request/response headers. (Issue #821) 1.14 (2015-12-29) ----------------- * contrib: SOCKS proxy support! (Issue #762) * Fixed AppEngine handling of transfer-encoding header and bug in Timeout defaults checking. (Issue #763) 1.13.1 (2015-12-18) ------------------- * Fixed regression in IPv6 + SSL for match_hostname. (Issue #761) 1.13 (2015-12-14) ----------------- * Fixed ``pip install urllib3[secure]`` on modern pip. (Issue #706) * pyopenssl: Fixed SSL3_WRITE_PENDING error. (Issue #717) * pyopenssl: Support for TLSv1.1 and TLSv1.2. (Issue #696) * Close connections more defensively on exception. (Issue #734) * Adjusted ``read_chunked`` to handle gzipped, chunk-encoded bodies without repeatedly flushing the decoder, to function better on Jython. (Issue #743) * Accept ``ca_cert_dir`` for SSL-related PoolManager configuration. (Issue #758) 1.12 (2015-09-03) ----------------- * Rely on ``six`` for importing ``httplib`` to work around conflicts with other Python 3 shims. (Issue #688) * Add support for directories of certificate authorities, as supported by OpenSSL. (Issue #701) * New exception: ``NewConnectionError``, raised when we fail to establish a new connection, usually ``ECONNREFUSED`` socket error. 1.11 (2015-07-21) ----------------- * When ``ca_certs`` is given, ``cert_reqs`` defaults to ``'CERT_REQUIRED'``. (Issue #650) * ``pip install urllib3[secure]`` will install Certifi and PyOpenSSL as dependencies. (Issue #678) * Made ``HTTPHeaderDict`` usable as a ``headers`` input value (Issues #632, #679) * Added `urllib3.contrib.appengine `_ which has an ``AppEngineManager`` for using ``URLFetch`` in a Google AppEngine environment. (Issue #664) * Dev: Added test suite for AppEngine. (Issue #631) * Fix performance regression when using PyOpenSSL. (Issue #626) * Passing incorrect scheme (e.g. ``foo://``) will raise ``ValueError`` instead of ``AssertionError`` (backwards compatible for now, but please migrate). (Issue #640) * Fix pools not getting replenished when an error occurs during a request using ``release_conn=False``. (Issue #644) * Fix pool-default headers not applying for url-encoded requests like GET. (Issue #657) * log.warning in Python 3 when headers are skipped due to parsing errors. (Issue #642) * Close and discard connections if an error occurs during read. (Issue #660) * Fix host parsing for IPv6 proxies. (Issue #668) * Separate warning type SubjectAltNameWarning, now issued once per host. (Issue #671) * Fix ``httplib.IncompleteRead`` not getting converted to ``ProtocolError`` when using ``HTTPResponse.stream()`` (Issue #674) 1.10.4 (2015-05-03) ------------------- * Migrate tests to Tornado 4. (Issue #594) * Append default warning configuration rather than overwrite. (Issue #603) * Fix streaming decoding regression. (Issue #595) * Fix chunked requests losing state across keep-alive connections. (Issue #599) * Fix hanging when chunked HEAD response has no body. (Issue #605) 1.10.3 (2015-04-21) ------------------- * Emit ``InsecurePlatformWarning`` when SSLContext object is missing. (Issue #558) * Fix regression of duplicate header keys being discarded. (Issue #563) * ``Response.stream()`` returns a generator for chunked responses. (Issue #560) * Set upper-bound timeout when waiting for a socket in PyOpenSSL. (Issue #585) * Work on platforms without `ssl` module for plain HTTP requests. (Issue #587) * Stop relying on the stdlib's default cipher list. (Issue #588) 1.10.2 (2015-02-25) ------------------- * Fix file descriptor leakage on retries. (Issue #548) * Removed RC4 from default cipher list. (Issue #551) * Header performance improvements. (Issue #544) * Fix PoolManager not obeying redirect retry settings. (Issue #553) 1.10.1 (2015-02-10) ------------------- * Pools can be used as context managers. (Issue #545) * Don't re-use connections which experienced an SSLError. (Issue #529) * Don't fail when gzip decoding an empty stream. (Issue #535) * Add sha256 support for fingerprint verification. (Issue #540) * Fixed handling of header values containing commas. (Issue #533) 1.10 (2014-12-14) ----------------- * Disabled SSLv3. (Issue #473) * Add ``Url.url`` property to return the composed url string. (Issue #394) * Fixed PyOpenSSL + gevent ``WantWriteError``. (Issue #412) * ``MaxRetryError.reason`` will always be an exception, not string. (Issue #481) * Fixed SSL-related timeouts not being detected as timeouts. (Issue #492) * Py3: Use ``ssl.create_default_context()`` when available. (Issue #473) * Emit ``InsecureRequestWarning`` for *every* insecure HTTPS request. (Issue #496) * Emit ``SecurityWarning`` when certificate has no ``subjectAltName``. (Issue #499) * Close and discard sockets which experienced SSL-related errors. (Issue #501) * Handle ``body`` param in ``.request(...)``. (Issue #513) * Respect timeout with HTTPS proxy. (Issue #505) * PyOpenSSL: Handle ZeroReturnError exception. (Issue #520) 1.9.1 (2014-09-13) ------------------ * Apply socket arguments before binding. (Issue #427) * More careful checks if fp-like object is closed. (Issue #435) * Fixed packaging issues of some development-related files not getting included. (Issue #440) * Allow performing *only* fingerprint verification. (Issue #444) * Emit ``SecurityWarning`` if system clock is waaay off. (Issue #445) * Fixed PyOpenSSL compatibility with PyPy. (Issue #450) * Fixed ``BrokenPipeError`` and ``ConnectionError`` handling in Py3. (Issue #443) 1.9 (2014-07-04) ---------------- * Shuffled around development-related files. If you're maintaining a distro package of urllib3, you may need to tweak things. (Issue #415) * Unverified HTTPS requests will trigger a warning on the first request. See our new `security documentation `_ for details. (Issue #426) * New retry logic and ``urllib3.util.retry.Retry`` configuration object. (Issue #326) * All raised exceptions should now wrapped in a ``urllib3.exceptions.HTTPException``-extending exception. (Issue #326) * All errors during a retry-enabled request should be wrapped in ``urllib3.exceptions.MaxRetryError``, including timeout-related exceptions which were previously exempt. Underlying error is accessible from the ``.reason`` property. (Issue #326) * ``urllib3.exceptions.ConnectionError`` renamed to ``urllib3.exceptions.ProtocolError``. (Issue #326) * Errors during response read (such as IncompleteRead) are now wrapped in ``urllib3.exceptions.ProtocolError``. (Issue #418) * Requesting an empty host will raise ``urllib3.exceptions.LocationValueError``. (Issue #417) * Catch read timeouts over SSL connections as ``urllib3.exceptions.ReadTimeoutError``. (Issue #419) * Apply socket arguments before connecting. (Issue #427) 1.8.3 (2014-06-23) ------------------ * Fix TLS verification when using a proxy in Python 3.4.1. (Issue #385) * Add ``disable_cache`` option to ``urllib3.util.make_headers``. (Issue #393) * Wrap ``socket.timeout`` exception with ``urllib3.exceptions.ReadTimeoutError``. (Issue #399) * Fixed proxy-related bug where connections were being reused incorrectly. (Issues #366, #369) * Added ``socket_options`` keyword parameter which allows to define ``setsockopt`` configuration of new sockets. (Issue #397) * Removed ``HTTPConnection.tcp_nodelay`` in favor of ``HTTPConnection.default_socket_options``. (Issue #397) * Fixed ``TypeError`` bug in Python 2.6.4. (Issue #411) 1.8.2 (2014-04-17) ------------------ * Fix ``urllib3.util`` not being included in the package. 1.8.1 (2014-04-17) ------------------ * Fix AppEngine bug of HTTPS requests going out as HTTP. (Issue #356) * Don't install ``dummyserver`` into ``site-packages`` as it's only needed for the test suite. (Issue #362) * Added support for specifying ``source_address``. (Issue #352) 1.8 (2014-03-04) ---------------- * Improved url parsing in ``urllib3.util.parse_url`` (properly parse '@' in username, and blank ports like 'hostname:'). * New ``urllib3.connection`` module which contains all the HTTPConnection objects. * Several ``urllib3.util.Timeout``-related fixes. Also changed constructor signature to a more sensible order. [Backwards incompatible] (Issues #252, #262, #263) * Use ``backports.ssl_match_hostname`` if it's installed. (Issue #274) * Added ``.tell()`` method to ``urllib3.response.HTTPResponse`` which returns the number of bytes read so far. (Issue #277) * Support for platforms without threading. (Issue #289) * Expand default-port comparison in ``HTTPConnectionPool.is_same_host`` to allow a pool with no specified port to be considered equal to to an HTTP/HTTPS url with port 80/443 explicitly provided. (Issue #305) * Improved default SSL/TLS settings to avoid vulnerabilities. (Issue #309) * Fixed ``urllib3.poolmanager.ProxyManager`` not retrying on connect errors. (Issue #310) * Disable Nagle's Algorithm on the socket for non-proxies. A subset of requests will send the entire HTTP request ~200 milliseconds faster; however, some of the resulting TCP packets will be smaller. (Issue #254) * Increased maximum number of SubjectAltNames in ``urllib3.contrib.pyopenssl`` from the default 64 to 1024 in a single certificate. (Issue #318) * Headers are now passed and stored as a custom ``urllib3.collections_.HTTPHeaderDict`` object rather than a plain ``dict``. (Issue #329, #333) * Headers no longer lose their case on Python 3. (Issue #236) * ``urllib3.contrib.pyopenssl`` now uses the operating system's default CA certificates on inject. (Issue #332) * Requests with ``retries=False`` will immediately raise any exceptions without wrapping them in ``MaxRetryError``. (Issue #348) * Fixed open socket leak with SSL-related failures. (Issue #344, #348) 1.7.1 (2013-09-25) ------------------ * Added granular timeout support with new ``urllib3.util.Timeout`` class. (Issue #231) * Fixed Python 3.4 support. (Issue #238) 1.7 (2013-08-14) ---------------- * More exceptions are now pickle-able, with tests. (Issue #174) * Fixed redirecting with relative URLs in Location header. (Issue #178) * Support for relative urls in ``Location: ...`` header. (Issue #179) * ``urllib3.response.HTTPResponse`` now inherits from ``io.IOBase`` for bonus file-like functionality. (Issue #187) * Passing ``assert_hostname=False`` when creating a HTTPSConnectionPool will skip hostname verification for SSL connections. (Issue #194) * New method ``urllib3.response.HTTPResponse.stream(...)`` which acts as a generator wrapped around ``.read(...)``. (Issue #198) * IPv6 url parsing enforces brackets around the hostname. (Issue #199) * Fixed thread race condition in ``urllib3.poolmanager.PoolManager.connection_from_host(...)`` (Issue #204) * ``ProxyManager`` requests now include non-default port in ``Host: ...`` header. (Issue #217) * Added HTTPS proxy support in ``ProxyManager``. (Issue #170 #139) * New ``RequestField`` object can be passed to the ``fields=...`` param which can specify headers. (Issue #220) * Raise ``urllib3.exceptions.ProxyError`` when connecting to proxy fails. (Issue #221) * Use international headers when posting file names. (Issue #119) * Improved IPv6 support. (Issue #203) 1.6 (2013-04-25) ---------------- * Contrib: Optional SNI support for Py2 using PyOpenSSL. (Issue #156) * ``ProxyManager`` automatically adds ``Host: ...`` header if not given. * Improved SSL-related code. ``cert_req`` now optionally takes a string like "REQUIRED" or "NONE". Same with ``ssl_version`` takes strings like "SSLv23" The string values reflect the suffix of the respective constant variable. (Issue #130) * Vendored ``socksipy`` now based on Anorov's fork which handles unexpectedly closed proxy connections and larger read buffers. (Issue #135) * Ensure the connection is closed if no data is received, fixes connection leak on some platforms. (Issue #133) * Added SNI support for SSL/TLS connections on Py32+. (Issue #89) * Tests fixed to be compatible with Py26 again. (Issue #125) * Added ability to choose SSL version by passing an ``ssl.PROTOCOL_*`` constant to the ``ssl_version`` parameter of ``HTTPSConnectionPool``. (Issue #109) * Allow an explicit content type to be specified when encoding file fields. (Issue #126) * Exceptions are now pickleable, with tests. (Issue #101) * Fixed default headers not getting passed in some cases. (Issue #99) * Treat "content-encoding" header value as case-insensitive, per RFC 2616 Section 3.5. (Issue #110) * "Connection Refused" SocketErrors will get retried rather than raised. (Issue #92) * Updated vendored ``six``, no longer overrides the global ``six`` module namespace. (Issue #113) * ``urllib3.exceptions.MaxRetryError`` contains a ``reason`` property holding the exception that prompted the final retry. If ``reason is None`` then it was due to a redirect. (Issue #92, #114) * Fixed ``PoolManager.urlopen()`` from not redirecting more than once. (Issue #149) * Don't assume ``Content-Type: text/plain`` for multi-part encoding parameters that are not files. (Issue #111) * Pass `strict` param down to ``httplib.HTTPConnection``. (Issue #122) * Added mechanism to verify SSL certificates by fingerprint (md5, sha1) or against an arbitrary hostname (when connecting by IP or for misconfigured servers). (Issue #140) * Streaming decompression support. (Issue #159) 1.5 (2012-08-02) ---------------- * Added ``urllib3.add_stderr_logger()`` for quickly enabling STDERR debug logging in urllib3. * Native full URL parsing (including auth, path, query, fragment) available in ``urllib3.util.parse_url(url)``. * Built-in redirect will switch method to 'GET' if status code is 303. (Issue #11) * ``urllib3.PoolManager`` strips the scheme and host before sending the request uri. (Issue #8) * New ``urllib3.exceptions.DecodeError`` exception for when automatic decoding, based on the Content-Type header, fails. * Fixed bug with pool depletion and leaking connections (Issue #76). Added explicit connection closing on pool eviction. Added ``urllib3.PoolManager.clear()``. * 99% -> 100% unit test coverage. 1.4 (2012-06-16) ---------------- * Minor AppEngine-related fixes. * Switched from ``mimetools.choose_boundary`` to ``uuid.uuid4()``. * Improved url parsing. (Issue #73) * IPv6 url support. (Issue #72) 1.3 (2012-03-25) ---------------- * Removed pre-1.0 deprecated API. * Refactored helpers into a ``urllib3.util`` submodule. * Fixed multipart encoding to support list-of-tuples for keys with multiple values. (Issue #48) * Fixed multiple Set-Cookie headers in response not getting merged properly in Python 3. (Issue #53) * AppEngine support with Py27. (Issue #61) * Minor ``encode_multipart_formdata`` fixes related to Python 3 strings vs bytes. 1.2.2 (2012-02-06) ------------------ * Fixed packaging bug of not shipping ``test-requirements.txt``. (Issue #47) 1.2.1 (2012-02-05) ------------------ * Fixed another bug related to when ``ssl`` module is not available. (Issue #41) * Location parsing errors now raise ``urllib3.exceptions.LocationParseError`` which inherits from ``ValueError``. 1.2 (2012-01-29) ---------------- * Added Python 3 support (tested on 3.2.2) * Dropped Python 2.5 support (tested on 2.6.7, 2.7.2) * Use ``select.poll`` instead of ``select.select`` for platforms that support it. * Use ``Queue.LifoQueue`` instead of ``Queue.Queue`` for more aggressive connection reusing. Configurable by overriding ``ConnectionPool.QueueCls``. * Fixed ``ImportError`` during install when ``ssl`` module is not available. (Issue #41) * Fixed ``PoolManager`` redirects between schemes (such as HTTP -> HTTPS) not completing properly. (Issue #28, uncovered by Issue #10 in v1.1) * Ported ``dummyserver`` to use ``tornado`` instead of ``webob`` + ``eventlet``. Removed extraneous unsupported dummyserver testing backends. Added socket-level tests. * More tests. Achievement Unlocked: 99% Coverage. 1.1 (2012-01-07) ---------------- * Refactored ``dummyserver`` to its own root namespace module (used for testing). * Added hostname verification for ``VerifiedHTTPSConnection`` by vendoring in Py32's ``ssl_match_hostname``. (Issue #25) * Fixed cross-host HTTP redirects when using ``PoolManager``. (Issue #10) * Fixed ``decode_content`` being ignored when set through ``urlopen``. (Issue #27) * Fixed timeout-related bugs. (Issues #17, #23) 1.0.2 (2011-11-04) ------------------ * Fixed typo in ``VerifiedHTTPSConnection`` which would only present as a bug if you're using the object manually. (Thanks pyos) * Made RecentlyUsedContainer (and consequently PoolManager) more thread-safe by wrapping the access log in a mutex. (Thanks @christer) * Made RecentlyUsedContainer more dict-like (corrected ``__delitem__`` and ``__getitem__`` behaviour), with tests. Shouldn't affect core urllib3 code. 1.0.1 (2011-10-10) ------------------ * Fixed a bug where the same connection would get returned into the pool twice, causing extraneous "HttpConnectionPool is full" log warnings. 1.0 (2011-10-08) ---------------- * Added ``PoolManager`` with LRU expiration of connections (tested and documented). * Added ``ProxyManager`` (needs tests, docs, and confirmation that it works with HTTPS proxies). * Added optional partial-read support for responses when ``preload_content=False``. You can now make requests and just read the headers without loading the content. * Made response decoding optional (default on, same as before). * Added optional explicit boundary string for ``encode_multipart_formdata``. * Convenience request methods are now inherited from ``RequestMethods``. Old helpers like ``get_url`` and ``post_url`` should be abandoned in favour of the new ``request(method, url, ...)``. * Refactored code to be even more decoupled, reusable, and extendable. * License header added to ``.py`` files. * Embiggened the documentation: Lots of Sphinx-friendly docstrings in the code and docs in ``docs/`` and on https://urllib3.readthedocs.io/. * Embettered all the things! * Started writing this file. 0.4.1 (2011-07-17) ------------------ * Minor bug fixes, code cleanup. 0.4 (2011-03-01) ---------------- * Better unicode support. * Added ``VerifiedHTTPSConnection``. * Added ``NTLMConnectionPool`` in contrib. * Minor improvements. 0.3.1 (2010-07-13) ------------------ * Added ``assert_host_name`` optional parameter. Now compatible with proxies. 0.3 (2009-12-10) ---------------- * Added HTTPS support. * Minor bug fixes. * Refactored, broken backwards compatibility with 0.2. * API to be treated as stable from this version forward. 0.2 (2008-11-17) ---------------- * Added unit tests. * Bug fixes. 0.1 (2008-11-16) ---------------- * First release. Keywords: urllib httplib threadsafe filepost http https ssl pooling Platform: UNKNOWN Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Software Development :: Libraries Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4 Provides-Extra: secure Provides-Extra: brotli Provides-Extra: socks ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639256.0 urllib3-1.25.8/README.rst0000644000175000017500000000662500000000000017604 0ustar00sethmlarsonsethmlarson00000000000000urllib3 ======= urllib3 is a powerful, *sanity-friendly* HTTP client for Python. Much of the Python ecosystem already uses urllib3 and you should too. urllib3 brings many critical features that are missing from the Python standard libraries: - Thread safety. - Connection pooling. - Client-side SSL/TLS verification. - File uploads with multipart encoding. - Helpers for retrying requests and dealing with HTTP redirects. - Support for gzip, deflate, and brotli encoding. - Proxy support for HTTP and SOCKS. - 100% test coverage. urllib3 is powerful and easy to use:: >>> import urllib3 >>> http = urllib3.PoolManager() >>> r = http.request('GET', 'http://httpbin.org/robots.txt') >>> r.status 200 >>> r.data 'User-agent: *\nDisallow: /deny\n' Installing ---------- urllib3 can be installed with `pip `_:: $ pip install urllib3 Alternatively, you can grab the latest source code from `GitHub `_:: $ git clone git://github.com/urllib3/urllib3.git $ python setup.py install Documentation ------------- urllib3 has usage and reference documentation at `urllib3.readthedocs.io `_. Contributing ------------ urllib3 happily accepts contributions. Please see our `contributing documentation `_ for some tips on getting started. Security Disclosures -------------------- To report a security vulnerability, please use the `Tidelift security contact `_. Tidelift will coordinate the fix and disclosure with maintainers. Maintainers ----------- - `@sethmlarson `_ (Seth M. Larson) - `@pquentin `_ (Quentin Pradet) - `@theacodes `_ (Thea Flowers) - `@haikuginger `_ (Jess Shapiro) - `@lukasa `_ (Cory Benfield) - `@sigmavirus24 `_ (Ian Stapleton Cordasco) - `@shazow `_ (Andrey Petrov) 👋 Sponsorship ----------- .. |tideliftlogo| image:: https://nedbatchelder.com/pix/Tidelift_Logos_RGB_Tidelift_Shorthand_On-White_small.png :width: 75 :alt: Tidelift .. list-table:: :widths: 10 100 * - |tideliftlogo| - Professional support for urllib3 is available as part of the `Tidelift Subscription`_. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools. .. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=readme If your company benefits from this library, please consider `sponsoring its development `_. Sponsors include: - Abbott (2018-2019), sponsored `@sethmlarson `_'s work on urllib3. - Google Cloud Platform (2018-2019), sponsored `@theacodes `_'s work on urllib3. - Akamai (2017-2018), sponsored `@haikuginger `_'s work on urllib3 - Hewlett Packard Enterprise (2016-2017), sponsored `@Lukasa’s `_ work on urllib3. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dev-requirements.txt0000644000175000017500000000074200000000000022147 0ustar00sethmlarsonsethmlarson00000000000000mock==3.0.5 coverage~=4.5 tornado==5.1.1;python_version<="2.7" tornado==6.0.3;python_version>="3.5" PySocks==1.7.1 # https://github.com/Anorov/PySocks/issues/131 win-inet-pton==1.1.0 pytest==4.6.6 pytest-timeout==1.3.3 flaky==3.6.1 trustme==0.5.3 # https://github.com/GoogleCloudPlatform/python-repo-tools/issues/23 pylint<2.0;python_version<="2.7" # Because typed-ast doesn't provide Python 3.4+Windows wheels gcp-devrel-py-tools;python_version>='3.5' or sys_platform != 'win32' ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8938637 urllib3-1.25.8/docs/0000755000175000017500000000000000000000000017034 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/Makefile0000644000175000017500000001077200000000000020503 0ustar00sethmlarsonsethmlarson00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = '-W' SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/urllib3.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/urllib3.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/urllib3" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/urllib3" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8938637 urllib3-1.25.8/docs/_templates/0000755000175000017500000000000000000000000021171 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/_templates/fonts.html0000644000175000017500000000015200000000000023206 0ustar00sethmlarsonsethmlarson00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/advanced-usage.rst0000644000175000017500000002501400000000000022437 0ustar00sethmlarsonsethmlarson00000000000000Advanced Usage ============== .. currentmodule:: urllib3 Customizing pool behavior ------------------------- The :class:`~poolmanager.PoolManager` class automatically handles creating :class:`~connectionpool.ConnectionPool` instances for each host as needed. By default, it will keep a maximum of 10 :class:`~connectionpool.ConnectionPool` instances. If you're making requests to many different hosts it might improve performance to increase this number:: >>> import urllib3 >>> http = urllib3.PoolManager(num_pools=50) However, keep in mind that this does increase memory and socket consumption. Similarly, the :class:`~connectionpool.ConnectionPool` class keeps a pool of individual :class:`~connection.HTTPConnection` instances. These connections are used during an individual request and returned to the pool when the request is complete. By default only one connection will be saved for re-use. If you are making many requests to the same host simultaneously it might improve performance to increase this number:: >>> import urllib3 >>> http = urllib3.PoolManager(maxsize=10) # Alternatively >>> http = urllib3.HTTPConnectionPool('google.com', maxsize=10) The behavior of the pooling for :class:`~connectionpool.ConnectionPool` is different from :class:`~poolmanager.PoolManager`. By default, if a new request is made and there is no free connection in the pool then a new connection will be created. However, this connection will not be saved if more than ``maxsize`` connections exist. This means that ``maxsize`` does not determine the maximum number of connections that can be open to a particular host, just the maximum number of connections to keep in the pool. However, if you specify ``block=True`` then there can be at most ``maxsize`` connections open to a particular host:: >>> http = urllib3.PoolManager(maxsize=10, block=True) # Alternatively >>> http = urllib3.HTTPConnectionPool('google.com', maxsize=10, block=True) Any new requests will block until a connection is available from the pool. This is a great way to prevent flooding a host with too many connections in multi-threaded applications. .. _stream: Streaming and IO ---------------- When dealing with large responses it's often better to stream the response content:: >>> import urllib3 >>> http = urllib3.PoolManager() >>> r = http.request( ... 'GET', ... 'http://httpbin.org/bytes/1024', ... preload_content=False) >>> for chunk in r.stream(32): ... print(chunk) b'...' b'...' ... >>> r.release_conn() Setting ``preload_content`` to ``False`` means that urllib3 will stream the response content. :meth:`~response.HTTPResponse.stream` lets you iterate over chunks of the response content. .. note:: When using ``preload_content=False``, you should call :meth:`~response.HTTPResponse.release_conn` to release the http connection back to the connection pool so that it can be re-used. However, you can also treat the :class:`~response.HTTPResponse` instance as a file-like object. This allows you to do buffering:: >>> r = http.request( ... 'GET', ... 'http://httpbin.org/bytes/1024', ... preload_content=False) >>> r.read(4) b'\x88\x1f\x8b\xe5' Calls to :meth:`~response.HTTPResponse.read()` will block until more response data is available. >>> import io >>> reader = io.BufferedReader(r, 8) >>> reader.read(4) >>> r.release_conn() You can use this file-like object to do things like decode the content using :mod:`codecs`:: >>> import codecs >>> reader = codecs.getreader('utf-8') >>> r = http.request( ... 'GET', ... 'http://httpbin.org/ip', ... preload_content=False) >>> json.load(reader(r)) {'origin': '127.0.0.1'} >>> r.release_conn() .. _proxies: Proxies ------- You can use :class:`~poolmanager.ProxyManager` to tunnel requests through an HTTP proxy:: >>> import urllib3 >>> proxy = urllib3.ProxyManager('http://localhost:3128/') >>> proxy.request('GET', 'http://google.com/') The usage of :class:`~poolmanager.ProxyManager` is the same as :class:`~poolmanager.PoolManager`. You can use :class:`~contrib.socks.SOCKSProxyManager` to connect to SOCKS4 or SOCKS5 proxies. In order to use SOCKS proxies you will need to install `PySocks `_ or install urllib3 with the ``socks`` extra:: pip install urllib3[socks] Once PySocks is installed, you can use :class:`~contrib.socks.SOCKSProxyManager`:: >>> from urllib3.contrib.socks import SOCKSProxyManager >>> proxy = SOCKSProxyManager('socks5://localhost:8889/') >>> proxy.request('GET', 'http://google.com/') .. _ssl_custom: Custom SSL certificates ----------------------- Instead of using `certifi `_ you can provide your own certificate authority bundle. This is useful for cases where you've generated your own certificates or when you're using a private certificate authority. Just provide the full path to the certificate bundle when creating a :class:`~poolmanager.PoolManager`:: >>> import urllib3 >>> http = urllib3.PoolManager( ... cert_reqs='CERT_REQUIRED', ... ca_certs='/path/to/your/certificate_bundle') When you specify your own certificate bundle only requests that can be verified with that bundle will succeed. It's recommended to use a separate :class:`~poolmanager.PoolManager` to make requests to URLs that do not need the custom certificate. .. _ssl_client: Client certificates ------------------- You can also specify a client certificate. This is useful when both the server and the client need to verify each other's identity. Typically these certificates are issued from the same authority. To use a client certificate, provide the full path when creating a :class:`~poolmanager.PoolManager`:: >>> http = urllib3.PoolManager( ... cert_file='/path/to/your/client_cert.pem', ... cert_reqs='CERT_REQUIRED', ... ca_certs='/path/to/your/certificate_bundle') If you have an encrypted client certificate private key you can use the ``key_password`` parameter to specify a password to decrypt the key. :: >>> http = urllib3.PoolManager( ... cert_file='/path/to/your/client_cert.pem', ... cert_reqs='CERT_REQUIRED', ... key_file='/path/to/your/client.key', ... key_password='keyfile_password') If your key isn't encrypted the ``key_password`` parameter isn't required. .. _ssl_mac: Certificate validation and Mac OS X ----------------------------------- Apple-provided Python and OpenSSL libraries contain a patches that make them automatically check the system keychain's certificates. This can be surprising if you specify custom certificates and see requests unexpectedly succeed. For example, if you are specifying your own certificate for validation and the server presents a different certificate you would expect the connection to fail. However, if that server presents a certificate that is in the system keychain then the connection will succeed. `This article `_ has more in-depth analysis and explanation. .. _ssl_warnings: SSL Warnings ------------ urllib3 will issue several different warnings based on the level of certificate verification support. These warnings indicate particular situations and can be resolved in different ways. * :class:`~exceptions.InsecureRequestWarning` This happens when a request is made to an HTTPS URL without certificate verification enabled. Follow the :ref:`certificate verification ` guide to resolve this warning. * :class:`~exceptions.InsecurePlatformWarning` This happens on Python 2 platforms that have an outdated :mod:`ssl` module. These older :mod:`ssl` modules can cause some insecure requests to succeed where they should fail and secure requests to fail where they should succeed. Follow the :ref:`pyOpenSSL ` guide to resolve this warning. .. _sni_warning: * :class:`~exceptions.SNIMissingWarning` This happens on Python 2 versions older than 2.7.9. These older versions lack `SNI `_ support. This can cause servers to present a certificate that the client thinks is invalid. Follow the :ref:`pyOpenSSL ` guide to resolve this warning. .. _disable_ssl_warnings: Making unverified HTTPS requests is **strongly** discouraged, however, if you understand the risks and wish to disable these warnings, you can use :func:`~urllib3.disable_warnings`:: >>> import urllib3 >>> urllib3.disable_warnings() Alternatively you can capture the warnings with the standard :mod:`logging` module:: >>> logging.captureWarnings(True) Finally, you can suppress the warnings at the interpreter level by setting the ``PYTHONWARNINGS`` environment variable or by using the `-W flag `_. Google App Engine ----------------- urllib3 supports `Google App Engine `_ with some caveats. If you're using the `Flexible environment `_, you do not have to do any configuration- urllib3 will just work. However, if you're using the `Standard environment `_ then you either have to use :mod:`urllib3.contrib.appengine`'s :class:`~urllib3.contrib.appengine.AppEngineManager` or use the `Sockets API `_ To use :class:`~urllib3.contrib.appengine.AppEngineManager`:: >>> from urllib3.contrib.appengine import AppEngineManager >>> http = AppEngineManager() >>> http.request('GET', 'https://google.com/') To use the Sockets API, add the following to your app.yaml and use :class:`~urllib3.poolmanager.PoolManager` as usual:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' For more details on the limitations and gotchas, see :mod:`urllib3.contrib.appengine`. Brotli Encoding --------------- Brotli is a compression algorithm created by Google with better compression than gzip and deflate and is supported by urllib3 if the `brotlipy `_ package is installed. You may also request the package be installed via the ``urllib3[brotli]`` extra:: python -m pip install urllib3[brotli] Here's an example using brotli encoding via the ``Accept-Encoding`` header:: >>> from urllib3 import PoolManager >>> http = PoolManager() >>> http.request('GET', 'https://www.google.com/', headers={'Accept-Encoding': 'br'}) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/conf.py0000644000175000017500000002030500000000000020333 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- # # urllib3 documentation build configuration file, created by # sphinx-quickstart on Wed Oct 5 13:15:40 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. from datetime import date import os import sys import alabaster # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, root_path) # Mock some expensive/platform-specific modules so build will work. # (https://read-the-docs.readthedocs.io/en/latest/faq.html#\ # i-get-import-errors-on-libraries-that-depend-on-c-modules) import mock class MockModule(mock.Mock): @classmethod def __getattr__(cls, name): return MockModule() MOCK_MODULES = ( 'ntlm', ) sys.modules.update((mod_name, MockModule()) for mod_name in MOCK_MODULES) import urllib3 # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'alabaster', 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', ] # Test code blocks only when explicitly specified doctest_test_doctest_blocks = '' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'urllib3' copyright = u'{year}, Andrey Petrov'.format(year=date.today().year) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = urllib3.__version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'description': 'Sanity-friendly HTTP client.', 'github_user': 'urllib3', 'github_repo': 'urllib3', 'github_button': False, 'github_banner': True, 'travis_button': True, 'show_powered_by': False, 'font_family': "'Roboto', Georgia, sans", 'head_font_family': "'Roboto', Georgia, serif", 'code_font_family': "'Roboto Mono', 'Consolas', monospace", } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [alabaster.get_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', 'searchbox.html', 'donate.html', ] } # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'urllib3doc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'urllib3.tex', u'urllib3 Documentation', u'Andrey Petrov', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'urllib3', u'urllib3 Documentation', [u'Andrey Petrov'], 1) ] intersphinx_mapping = { 'python': ('https://docs.python.org/3.7', None),} ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/contributing.rst0000644000175000017500000001301500000000000022275 0ustar00sethmlarsonsethmlarson00000000000000Contributing ============ urllib3 is a community-maintained project and we happily accept contributions. If you wish to add a new feature or fix a bug: #. `Check for open issues `_ or open a fresh issue to start a discussion around a feature idea or a bug. There is a *Contributor Friendly* tag for issues that should be ideal for people who are not very familiar with the codebase yet. #. Fork the `urllib3 repository on Github `_ to start making your changes. #. Write a test which shows that the bug was fixed or that the feature works as expected. #. Format your changes with black using command `$ nox -s blacken` and lint your changes using command `nox -s lint`. #. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to ``CONTRIBUTORS.txt``. Setting up your development environment --------------------------------------- In order to setup the development environment all that you need is `nox `_ installed in your machine:: $ pip install --user --upgrade nox Running the tests ----------------- We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. Our ``noxfile.py`` handles much of this for you:: $ nox --sessions test-2.7 test-3.7 [ Nox will create virtualenv, install the specified dependencies, and run the commands in order.] nox > Running session test-2.7 ....... ....... nox > Session test-2.7 was successful. ....... ....... nox > Running session test-3.7 ....... ....... nox > Session test-3.7 was successful. There is also a nox command for running all of our tests and multiple python versions. $ nox --sessions test Note that code coverage less than 100% is regarded as a failing run. Some platform-specific tests are skipped unless run in that platform. To make sure the code works in all of urllib3's supported platforms, you can run our ``tox`` suite:: $ nox --sessions test [ Nox will create virtualenv, install the specified dependencies, and run the commands in order.] ....... ....... nox > Session test-2.7 was successful. nox > Session test-3.4 was successful. nox > Session test-3.5 was successful. nox > Session test-3.6 was successful. nox > Session test-3.7 was successful. nox > Session test-3.8 was successful. nox > Session test-pypy was successful. Our test suite `runs continuously on Travis CI `_ with every pull request. Releases -------- A release candidate can be created by any contributor by creating a branch named ``release-x.x`` where ``x.x`` is the version of the proposed release. - Update ``CHANGES.rst`` and ``urllib3/__init__.py`` with the proper version number and commit the changes to ``release-x.x``. - Open a pull request to merge the ``release-x.x`` branch into the ``master`` branch. - Integration tests are run against the release candidate on Travis. From here on all the steps below will be handled by a maintainer so unless you receive review comments you are done here. - Once the pull request is squash merged into master the merging maintainer will tag the merge commit with the version number: - ``git tag -a 1.24.1 [commit sha]`` - ``git push origin master --tags`` - After the commit is tagged Travis will build the tagged commit and upload the sdist and wheel to PyPI and create a draft release on GitHub for the tag. The merging maintainer will ensure that the PyPI sdist and wheel are properly uploaded. - The merging maintainer will mark the draft release on GitHub as an approved release. Sponsorship ----------- .. |tideliftlogo| image:: https://nedbatchelder.com/pix/Tidelift_Logos_RGB_Tidelift_Shorthand_On-White_small.png :width: 75 :alt: Tidelift .. list-table:: :widths: 10 100 * - |tideliftlogo| - Professional support for urllib3 is available as part of the `Tidelift Subscription`_. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools. .. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=docs Please consider sponsoring urllib3 development, especially if your company benefits from this library. Your contribution will go towards adding new features to urllib3 and making sure all functionality continues to meet our high quality standards. We also welcome sponsorship in the form of time. We greatly appreciate companies who encourage employees to contribute on an ongoing basis during their work hours. Please let us know and we'll be glad to add you to our sponsors list! A grant for contiguous full-time development has the biggest impact for progress. Periods of 3 to 10 days allow a contributor to tackle substantial complex issues which are otherwise left to linger until somebody can't afford to not fix them. Contact `@theacodes `_ or `@shazow `_ to arrange a grant for a core contributor. Huge thanks to all the companies and individuals who financially contributed to the development of urllib3. Please send a PR if you've donated and would like to be listed. * `GOVCERT.LU `_ (October 23, 2018) * `Stripe `_ (June 23, 2014) .. * [Company] ([date]) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8938637 urllib3-1.25.8/docs/images/0000755000175000017500000000000000000000000020301 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/images/banner.svg0000644000175000017500000000335100000000000022271 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/images/demo-button.png0000644000175000017500000001730000000000000023245 0ustar00sethmlarsonsethmlarson00000000000000PNG  IHDR?d pHYs  iTXtXML:com.adobe.xmp 4IDATxygfgMrvL/sܹ$0I{Xu`T qThpD7UH#F?0b18^(ʙ{!؀/ow~:yٝGBٙvfyy 6|AD ($ ͻӭ >O%e6 ;Xyx@C"Q.)#tǣi:t+ #jon]QC|ڷ^O 2 'bC | 6 'bC | 6 'bC | 6 'bC | 6 'bC | 6 'bC | 6 'bC | 6 'bc5@#X6t2{|{̭APubae[EB9>[TvH ߛLiZ;Tr[Cm#շN .XnzpDDDQN%]a憤km/~_URv̭| +f蕿_{rTw_1}aKKo)qR|➘Z/sr.D}s m5zrZ=<-}5Dm4g™hxko{DAZ75pl=Y>qKVmk`o@c^q?=2eV#ӯ''l>5ف'Gř~{PwOG"Pv5mೃG$uǤgk[_xܐ:b]%gnK%"9nVz׈ю>~FGR nO=޾}XaqRzjBVU:mTpԁEˤkbݔX7I-0"у[Z) I ߊUrb,nȶEw8hRF3rvūYsIO!jt^{gEc|v({t|ͨYz5s#=9\=<]׼$I]2xʣڤKg#s'ljEcoD跭aɬ׆!`F¶Vo 41=}N:B+XZ~ÆnՙKkNV{j6wMGKW+#nɟorq9mO{uz (ױgq kGR}9!kɮ}`G8FON{7^(b$u٧}i^esp83^*Gqz5zQg*#SтyPz׈wbS$ *q}x5ư)vCنܙ0Kw^L+j jiGFGkoѮ'3G){n^koͩ&-q uYqMwJ93[+ՏoL-e/j^kɿ)Yz\=!uFj=4畧o'=2)gRc^pIL5tμo'WSJqzF&+o Vxryi|g {||F'GŞx/2֪XҾ]M@⑽?rؓu3+5O꒏^Ҏf""@Ds|v7?&^\|Qѓ)L:V >\fZC[r.nD#gyq&]ģҳkFDdeb. Uu5CmsĜID!w~Vd}N~"ta)v0Y7#guAѓS&9ωW'?Nßj@˚޿S;x@Ρ̋ Mb:o'NO4<G{A~ݨ5xSTsjc37:o#DVd!q嵌*/YARnZxR:I>;E7N \ү3'"fřzwJo]$4^Vt};|u]|O{62YI_yۚ+̊=r;9;:d*9vZ]oS4g0sC,P1&8A5SgZ}2ο0u \B2÷KvnI_sX7+s\OՅDv*OkΫ]{wbA-?ozBmR™K%sok顛$=iaۆzszgmȤxł< s5/6A|V0|ؓͿ[wMڤRq|k%VE-C*¬f|oeێwoKUK.^%OOsI7jqHh|!sJޯ_/@yX3!11|:e]6sWNJoSu|?]j#LIe@|G6]qZ]UYBhj r5$OH*QN#׉i᯸gt|# ѽP҃#rAÍt|*Fڑ.iUT 畧}"tu'!ț;.n~,T{s>;{lmk$6*IʛW'Ǡ>l^w}Sӑn]#]<БTͪG+O~d%{hv Bf󾿫6d|Q뒴¢FgKqf7nMkG(l^GLd52YZP37EV=:U+"ڏsnA$TV1P%"nL@ ѾK(fԯmϙ#! &3uVNyt V̥+=]\+3ڍlobt$ׄVu ^ ē=jw}=mU8dܐaA;߻E Ȩ5G&=2)E:1盍DS7cI(|{?zzԊxd.hWi0+ΡU_iyf4<-!z)?QQ5 Ýy9mɛW/SD{e^}.z'O/H2QgumS0(0{""(JbZ~T? ]1xsѲPD )Юl;{ۭ9/}ߧn^tG&\=V~~[ yxކJc;mYq+J3U5¬g:{{#"z&4>P_@{=wೕ.'U 6~DZZkzpDّ1''ӫE#A TLV;\֪z_i{b[$}ݡF+HjejԬkc_Xwj߹^՚ވڞQ*u|D!=aټ}ݚH3#wרˣ ozpD˥>f)={.rĥ39S{[{o[Ӄ#eel[\z׈ջF8הjڨ}mfK;^2WڮէE֪@YşC90*'tUmjed{M;)As|&=]Y=lOsJ"Jp^yڷ Rz]Tn@Rxş']7|v'j:S+nsJr-ubG{x:8m*7P$o{rTwř|E(շNR6_XXΒ/K~F rn]((\ϸzj~gkGȩ>K.ە~ I>C";NCuħo,=R:BnջFwvPǛ;.>JbSI]|waXz'uvD14=b}zg+ W%>95C/^+q_̣<7ED{#{F}_=T5?+ێ&Qg4s>͏iܜ[L#/LIo6/ē h՟|&](ٓmJh'Bg:ꤓvL<:}`͈gE\qN~s;c3tsn*u.M&Ħ#d 5aosHGn*c3b=v;xBPt[ǵPQDym<>#}o]նIx[;8niqhb$b3*]T'6Pzƺ"='i))ۦv|o'ku'۴UwXl>rѽ02Yqrr_5[ < gjwcGhXPct/k0#rZIKv#wMy&{|{9Y@IE\/użkL>\n l䨜W=$(mXҾ]r[9&x,ˍ+Sywِ"?j탡G;޿S՛j~ m\"F՛z_MLT[vGhY 0+N~lVNRBIVeţ}.,lha֪>33zru㽾sb>/FGYp>+ J4`mT+h֗ݼP-'DKS֢sʹUQ~I|2ϙڣ|hcH.O@ʯTeaZÒ[cH&SJ]8[@2|G&#y3cwĆ!@l>OĆ!@l>OĆ!@l>OĆ!@l>OĆ!@l>OĆ!@lt\,@u+#5ɧuK5n]+vҭ >H$cG%eݼ("UXwe7׭-ݼQID[OŌZA|~]D 'X1[.lp+".$k"ݏ򡚂O¶ AD+DC"i#h7%)'("ȣjRsy¶ >ݼφ>&| 6 'bBt'7IENDB`././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/images/learn-more-button.png0000644000175000017500000001412200000000000024361 0ustar00sethmlarsonsethmlarson00000000000000PNG  IHDR?d pHYs  iTXtXML:com.adobe.xmp EIDATxolyg6L@6B}\pJ+)G IaGA" /$ !z!iEPv".rtTV 0@t6HeĻ۾pnr3y`up |'!|'q^46hȯ-TΉ>+"D$h+""rVDȿGˍ^Y%";Z"OyQYΈ??DkZԷEn$x0'|ƆRD(NR닋ΉHƆRD-B [v :)(|hi n#A'?>tBPu>45/pˠ hC1OC1OC1OC1OC1OC1OC1OC1OC1OC1OC1OC1OC1OC1OC1Ou7'g`HN6>Jqc#R=̚[o\{ױm))?Z]i~3ǵ["K?/^i!R|xil8u?Ajd/ǺHwطnoGΞymO{I hb >/VGAgw#""G:.S_kNSԊhle87M[E6m瞇̀9@Y?\A# +}{bub_/S_~2G^nvaH>=D }_. ij/@lDꑶkwy@fXHjܢr앶ptPSzBz]t_>&0ܕǴjǿN./OhhQ:Yw|6k3c$l&!=VF' #-Nq}'#ddujno8[ZPC/4rF@b8%Ku3"\e b;"#crd sŝ>N.Ҋ䴋fzwƞvO*FV;wu>iiBP#2OaEJtEn#'=\y#4f?*fR_F?ӨA|d?x[K̝9.Hq-xW˱?ߴߴ|I;d=#W^$S_GRطnrVZot"pVN_ =)x*ܟ]kb 4B#w5qO£ZqBr}ew4<</5TTC8:Y9u,;s\*G6&/J@: ʅFܫ-N>n=f{eGBqϟ=f~wk(pQ\?<bO}F'E6VAX|.N5bԇl7忿}GLPR0'#-hr嵧#_{#7{h"NsgH[dvio[dm{[@Vl6޵E0)TNEnݧ-J μ{&T"ƹF$. )w]z7uUDoل?ݷ~{,葳gKΞܦGQ(ܹWM.IRK@Cc_46kT%ro v^He1Z$_TS{\kWXSZ{fM߃FՊ-~ny|C{lZV*׮{KYE${0 4 RFjvy7tdzP{{6BʥX!re-[uպUu%UFSP=\J/ӯOD_䓦 2'TT?rS1RUVuXmJ RCҶ[X ʋ"4͗}wܹ~Y-^Zq"V{,ŜGY^IŻ_) Mhej5걩˾rylJ~Zvb]VYޞ1ӻ3LR0Wvم!GɸZp-:ꢫ ]R>:V=6Uuǵ-^ڮW<)Q: 4+"8!:5 t2cSUPmLUyY: {W^:$Ͷ;{·UVC2W0}VBیJ5+ݨhRh5vc9h^ׁ%V#g6n[^$թ{Tf#KO :yqϟJ4H[^=fbiW,"bw)ck{0 46T>c~AePW*|'5L1[#"oo[?Oݾn]gsqk{~Z ګp迦g@61.+g`z? I"".ÁerT4MT5?mNwƭv{FDJU6J$zmM_U0HF:%(h?>A?j-D\m軟L_k;'Q[3mhO K^1P }҂T&[㑦jߨڞV""{>>GtW jrRT㪞}FY1׺;s\ztBP!h}1(|!h}N 7cA'gEd^KS~)QI>e{]-@ڟ_ :)R~tY9IhEg@a|~UD%z{Т+Y1W. ?,"D|5?:\#/j(|Ɔs"[Dv"rdME"A i8|ި46h.ȯ>.8b#|'!|^/+IENDB`././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/images/logo.png0000644000175000017500000000416500000000000021755 0ustar00sethmlarsonsethmlarson00000000000000PNG  IHDR xsBIT|dtEXtSoftwaregnome-screenshot>IDATx1e'' E0jHih\ZZE4EASAKSP EǧW~|ͽ2fVyb@X'Vyb@X'Vyb@X'Vyk:ͱusYY#Ǧ0f۷g01VwMaqcI70߾cޅ\Z~ۇ,< rkSO׾\zs{Ȥ~q7&|/\gN[M߀yb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X6uKS`gZMgNz @X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'VM=~toO=9Ο}}<⥅+ϭogO[M߀yb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'Vyb@X'V-/:v9 湷3a+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ < O+ e~3^\y"S`]SOwCOzsY߻+l@+ < O+ < O+ < O+ < O+ < O+Tx\IENDB`././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/images/logo.svg0000644000175000017500000000100400000000000021755 0ustar00sethmlarsonsethmlarson00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/index.rst0000644000175000017500000000572700000000000020710 0ustar00sethmlarsonsethmlarson00000000000000urllib3 ======= .. toctree:: :hidden: :maxdepth: 2 For Enterprise user-guide advanced-usage reference/index contributing urllib3 is a powerful, *sanity-friendly* HTTP client for Python. Much of the Python ecosystem :ref:`already uses ` urllib3 and you should too. urllib3 brings many critical features that are missing from the Python standard libraries: - Thread safety. - Connection pooling. - Client-side SSL/TLS verification. - File uploads with multipart encoding. - Helpers for retrying requests and dealing with HTTP redirects. - Support for gzip and deflate encoding. - Proxy support for HTTP and SOCKS. - 100% test coverage. urllib3 is powerful and easy to use:: >>> import urllib3 >>> http = urllib3.PoolManager() >>> r = http.request('GET', 'http://httpbin.org/robots.txt') >>> r.status 200 >>> r.data 'User-agent: *\nDisallow: /deny\n' For Enterprise -------------- `urllib3 is available as part of the Tidelift Subscription `_ urllib3 and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. If you want the flexibility of open source and the confidence of commercial-grade software, this is for you. |learn-more|_ |request-a-demo|_ .. |learn-more| image:: https://raw.githubusercontent.com/urllib3/urllib3/master/docs/images/learn-more-button.png .. _learn-more: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=docs .. |request-a-demo| image:: https://raw.githubusercontent.com/urllib3/urllib3/master/docs/images/demo-button.png .. _request-a-demo: https://tidelift.com/subscription/request-a-demo?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=docs Installing ---------- urllib3 can be installed with `pip `_:: $ pip install urllib3 Alternatively, you can grab the latest source code from `GitHub `_:: $ git clone git://github.com/urllib3/urllib3.git $ python setup.py install Usage ----- The :doc:`user-guide` is the place to go to learn how to use the library and accomplish common tasks. The more in-depth :doc:`advanced-usage` guide is the place to go for lower-level tweaking. The :doc:`reference/index` documentation provides API-level documentation. .. _who-uses: Who uses urllib3? ----------------- * `Requests `_ * `Pip `_ * & more! License ------- urllib3 is made available under the MIT License. For more details, see `LICENSE.txt `_. Contributing ------------ We happily welcome contributions, please see :doc:`contributing` for details. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/make.bat0000644000175000017500000001064100000000000020443 0ustar00sethmlarsonsethmlarson00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\urllib3.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\urllib3.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8938637 urllib3-1.25.8/docs/reference/0000755000175000017500000000000000000000000020772 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/reference/index.rst0000644000175000017500000000263200000000000022636 0ustar00sethmlarsonsethmlarson00000000000000Reference ========= .. contents:: :local: :backlinks: none Subpackages ----------- .. toctree:: urllib3.contrib urllib3.util Submodules ---------- urllib3.connection module ------------------------- .. automodule:: urllib3.connection :members: :undoc-members: :show-inheritance: urllib3.connectionpool module ----------------------------- .. automodule:: urllib3.connectionpool :members: :undoc-members: :show-inheritance: urllib3.exceptions module ------------------------- .. automodule:: urllib3.exceptions :members: :undoc-members: :show-inheritance: urllib3.fields module --------------------- .. automodule:: urllib3.fields :members: :undoc-members: :show-inheritance: urllib3.filepost module ----------------------- .. automodule:: urllib3.filepost :members: :undoc-members: :show-inheritance: urllib3.poolmanager module -------------------------- .. automodule:: urllib3.poolmanager :members: :undoc-members: :show-inheritance: urllib3.request module ---------------------- .. automodule:: urllib3.request :members: :undoc-members: :show-inheritance: urllib3.response module ----------------------- .. automodule:: urllib3.response :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: urllib3 :members: :undoc-members: :show-inheritance: ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/reference/urllib3.contrib.rst0000644000175000017500000000150600000000000024541 0ustar00sethmlarsonsethmlarson00000000000000urllib3.contrib package ======================= These modules implement various extra features, that may not be ready for prime time or that require optional third-party dependencies. urllib3.contrib.appengine module -------------------------------- .. automodule:: urllib3.contrib.appengine :members: :undoc-members: :show-inheritance: urllib3.contrib.ntlmpool module ------------------------------- .. automodule:: urllib3.contrib.ntlmpool :members: :undoc-members: :show-inheritance: urllib3.contrib.pyopenssl module -------------------------------- .. automodule:: urllib3.contrib.pyopenssl :members: :undoc-members: :show-inheritance: urllib3.contrib.socks module ---------------------------- .. automodule:: urllib3.contrib.socks :members: :undoc-members: :show-inheritance: ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/reference/urllib3.util.rst0000644000175000017500000000300300000000000024050 0ustar00sethmlarsonsethmlarson00000000000000urllib3.util package ==================== Useful methods for working with :mod:`httplib`, completely decoupled from code specific to **urllib3**. At the very core, just like its predecessors, :mod:`urllib3` is built on top of :mod:`httplib` -- the lowest level HTTP library included in the Python standard library. To aid the limited functionality of the :mod:`httplib` module, :mod:`urllib3` provides various helper methods which are used with the higher level components but can also be used independently. urllib3.util.connection module ------------------------------ .. automodule:: urllib3.util.connection :members: :undoc-members: :show-inheritance: urllib3.util.request module --------------------------- .. automodule:: urllib3.util.request :members: :undoc-members: :show-inheritance: urllib3.util.response module ---------------------------- .. automodule:: urllib3.util.response :members: :undoc-members: :show-inheritance: urllib3.util.retry module ------------------------- .. automodule:: urllib3.util.retry :members: :undoc-members: :show-inheritance: urllib3.util.timeout module --------------------------- .. automodule:: urllib3.util.timeout :members: :undoc-members: :show-inheritance: urllib3.util.url module ----------------------- .. automodule:: urllib3.util.url :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: urllib3.util :members: :undoc-members: :show-inheritance: ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/requirements.txt0000644000175000017500000000007600000000000022323 0ustar00sethmlarsonsethmlarson00000000000000-r ../dev-requirements.txt sphinx alabaster requests>=2,<2.16 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/docs/user-guide.rst0000644000175000017500000003415600000000000021650 0ustar00sethmlarsonsethmlarson00000000000000User Guide ========== .. currentmodule:: urllib3 Making requests --------------- First things first, import the urllib3 module:: >>> import urllib3 You'll need a :class:`~poolmanager.PoolManager` instance to make requests. This object handles all of the details of connection pooling and thread safety so that you don't have to:: >>> http = urllib3.PoolManager() To make a request use :meth:`~poolmanager.PoolManager.request`:: >>> r = http.request('GET', 'http://httpbin.org/robots.txt') >>> r.data b'User-agent: *\nDisallow: /deny\n' ``request()`` returns a :class:`~response.HTTPResponse` object, the :ref:`response_content` section explains how to handle various responses. You can use :meth:`~poolmanager.PoolManager.request` to make requests using any HTTP verb:: >>> r = http.request( ... 'POST', ... 'http://httpbin.org/post', ... fields={'hello': 'world'}) The :ref:`request_data` section covers sending other kinds of requests data, including JSON, files, and binary data. .. _response_content: Response content ---------------- The :class:`~response.HTTPResponse` object provides :attr:`~response.HTTPResponse.status`, :attr:`~response.HTTPResponse.data`, and :attr:`~response.HTTPResponse.header` attributes:: >>> r = http.request('GET', 'http://httpbin.org/ip') >>> r.status 200 >>> r.data b'{\n "origin": "104.232.115.37"\n}\n' >>> r.headers HTTPHeaderDict({'Content-Length': '33', ...}) JSON content ~~~~~~~~~~~~ JSON content can be loaded by decoding and deserializing the :attr:`~response.HTTPResponse.data` attribute of the request:: >>> import json >>> r = http.request('GET', 'http://httpbin.org/ip') >>> json.loads(r.data.decode('utf-8')) {'origin': '127.0.0.1'} Binary content ~~~~~~~~~~~~~~ The :attr:`~response.HTTPResponse.data` attribute of the response is always set to a byte string representing the response content:: >>> r = http.request('GET', 'http://httpbin.org/bytes/8') >>> r.data b'\xaa\xa5H?\x95\xe9\x9b\x11' .. note:: For larger responses, it's sometimes better to :ref:`stream ` the response. Using io Wrappers with Response content ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes you want to use :class:`io.TextIOWrapper` or similar objects like a CSV reader directly with :class:`~response.HTTPResponse` data. Making these two interfaces play nice together requires using the :attr:`~response.HTTPResponse.auto_close` attribute by setting it to ``False``. By default HTTP responses are closed after reading all bytes, this disables that behavior:: >>> import io >>> r = http.request('GET', 'https://example.com', preload_content=False) >>> r.auto_close = False >>> for line in io.TextIOWrapper(r): >>> print(line) .. _request_data: Request data ------------ Headers ~~~~~~~ You can specify headers as a dictionary in the ``headers`` argument in :meth:`~poolmanager.PoolManager.request`:: >>> r = http.request( ... 'GET', ... 'http://httpbin.org/headers', ... headers={ ... 'X-Something': 'value' ... }) >>> json.loads(r.data.decode('utf-8'))['headers'] {'X-Something': 'value', ...} Query parameters ~~~~~~~~~~~~~~~~ For ``GET``, ``HEAD``, and ``DELETE`` requests, you can simply pass the arguments as a dictionary in the ``fields`` argument to :meth:`~poolmanager.PoolManager.request`:: >>> r = http.request( ... 'GET', ... 'http://httpbin.org/get', ... fields={'arg': 'value'}) >>> json.loads(r.data.decode('utf-8'))['args'] {'arg': 'value'} For ``POST`` and ``PUT`` requests, you need to manually encode query parameters in the URL:: >>> from urllib.parse import urlencode >>> encoded_args = urlencode({'arg': 'value'}) >>> url = 'http://httpbin.org/post?' + encoded_args >>> r = http.request('POST', url) >>> json.loads(r.data.decode('utf-8'))['args'] {'arg': 'value'} .. _form_data: Form data ~~~~~~~~~ For ``PUT`` and ``POST`` requests, urllib3 will automatically form-encode the dictionary in the ``fields`` argument provided to :meth:`~poolmanager.PoolManager.request`:: >>> r = http.request( ... 'POST', ... 'http://httpbin.org/post', ... fields={'field': 'value'}) >>> json.loads(r.data.decode('utf-8'))['form'] {'field': 'value'} JSON ~~~~ You can send a JSON request by specifying the encoded data as the ``body`` argument and setting the ``Content-Type`` header when calling :meth:`~poolmanager.PoolManager.request`:: >>> import json >>> data = {'attribute': 'value'} >>> encoded_data = json.dumps(data).encode('utf-8') >>> r = http.request( ... 'POST', ... 'http://httpbin.org/post', ... body=encoded_data, ... headers={'Content-Type': 'application/json'}) >>> json.loads(r.data.decode('utf-8'))['json'] {'attribute': 'value'} Files & binary data ~~~~~~~~~~~~~~~~~~~ For uploading files using ``multipart/form-data`` encoding you can use the same approach as :ref:`form_data` and specify the file field as a tuple of ``(file_name, file_data)``:: >>> with open('example.txt') as fp: ... file_data = fp.read() >>> r = http.request( ... 'POST', ... 'http://httpbin.org/post', ... fields={ ... 'filefield': ('example.txt', file_data), ... }) >>> json.loads(r.data.decode('utf-8'))['files'] {'filefield': '...'} While specifying the filename is not strictly required, it's recommended in order to match browser behavior. You can also pass a third item in the tuple to specify the file's MIME type explicitly:: >>> r = http.request( ... 'POST', ... 'http://httpbin.org/post', ... fields={ ... 'filefield': ('example.txt', file_data, 'text/plain'), ... }) For sending raw binary data simply specify the ``body`` argument. It's also recommended to set the ``Content-Type`` header:: >>> with open('example.jpg', 'rb') as fp: ... binary_data = fp.read() >>> r = http.request( ... 'POST', ... 'http://httpbin.org/post', ... body=binary_data, ... headers={'Content-Type': 'image/jpeg'}) >>> json.loads(r.data.decode('utf-8'))['data'] b'...' .. _ssl: Certificate verification ------------------------ .. note:: *New in version 1.25* HTTPS connections are now verified by default (``cert_reqs = 'CERT_REQUIRED'``). While you can disable certification verification, it is highly recommend to leave it on. Unless otherwise specified urllib3 will try to load the default system certificate stores. The most reliable cross-platform method is to use the `certifi `_ package which provides Mozilla's root certificate bundle:: pip install certifi You can also install certifi along with urllib3 by using the ``secure`` extra:: pip install urllib3[secure] .. warning:: If you're using Python 2 you may need additional packages. See the :ref:`section below ` for more details. Once you have certificates, you can create a :class:`~poolmanager.PoolManager` that verifies certificates when making requests:: >>> import certifi >>> import urllib3 >>> http = urllib3.PoolManager( ... cert_reqs='CERT_REQUIRED', ... ca_certs=certifi.where()) The :class:`~poolmanager.PoolManager` will automatically handle certificate verification and will raise :class:`~exceptions.SSLError` if verification fails:: >>> http.request('GET', 'https://google.com') (No exception) >>> http.request('GET', 'https://expired.badssl.com') urllib3.exceptions.SSLError ... .. note:: You can use OS-provided certificates if desired. Just specify the full path to the certificate bundle as the ``ca_certs`` argument instead of ``certifi.where()``. For example, most Linux systems store the certificates at ``/etc/ssl/certs/ca-certificates.crt``. Other operating systems can be `difficult `_. .. _ssl_py2: Certificate verification in Python 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Older versions of Python 2 are built with an :mod:`ssl` module that lacks :ref:`SNI support ` and can lag behind security updates. For these reasons it's recommended to use `pyOpenSSL `_. If you install urllib3 with the ``secure`` extra, all required packages for certificate verification on Python 2 will be installed:: pip install urllib3[secure] If you want to install the packages manually, you will need ``pyOpenSSL``, ``cryptography``, ``idna``, and ``certifi``. .. note:: If you are not using macOS or Windows, note that `cryptography `_ requires additional system packages to compile. See `building cryptography on Linux `_ for the list of packages required. Once installed, you can tell urllib3 to use pyOpenSSL by using :mod:`urllib3.contrib.pyopenssl`:: >>> import urllib3.contrib.pyopenssl >>> urllib3.contrib.pyopenssl.inject_into_urllib3() Finally, you can create a :class:`~poolmanager.PoolManager` that verifies certificates when performing requests:: >>> import certifi >>> import urllib3 >>> http = urllib3.PoolManager( ... cert_reqs='CERT_REQUIRED', ... ca_certs=certifi.where()) If you do not wish to use pyOpenSSL, you can simply omit the call to :func:`urllib3.contrib.pyopenssl.inject_into_urllib3`. urllib3 will fall back to the standard-library :mod:`ssl` module. You may experience :ref:`several warnings ` when doing this. .. warning:: If you do not use pyOpenSSL, Python must be compiled with ssl support for certificate verification to work. It is uncommon, but it is possible to compile Python without SSL support. See this `Stackoverflow thread `_ for more details. If you are on Google App Engine, you must explicitly enable SSL support in your ``app.yaml``:: libraries: - name: ssl version: latest Using timeouts -------------- Timeouts allow you to control how long (in seconds) requests are allowed to run before being aborted. In simple cases, you can specify a timeout as a ``float`` to :meth:`~poolmanager.PoolManager.request`:: >>> http.request( ... 'GET', 'http://httpbin.org/delay/3', timeout=4.0) >>> http.request( ... 'GET', 'http://httpbin.org/delay/3', timeout=2.5) MaxRetryError caused by ReadTimeoutError For more granular control you can use a :class:`~util.timeout.Timeout` instance which lets you specify separate connect and read timeouts:: >>> http.request( ... 'GET', ... 'http://httpbin.org/delay/3', ... timeout=urllib3.Timeout(connect=1.0)) >>> http.request( ... 'GET', ... 'http://httpbin.org/delay/3', ... timeout=urllib3.Timeout(connect=1.0, read=2.0)) MaxRetryError caused by ReadTimeoutError If you want all requests to be subject to the same timeout, you can specify the timeout at the :class:`~urllib3.poolmanager.PoolManager` level:: >>> http = urllib3.PoolManager(timeout=3.0) >>> http = urllib3.PoolManager( ... timeout=urllib3.Timeout(connect=1.0, read=2.0)) You still override this pool-level timeout by specifying ``timeout`` to :meth:`~poolmanager.PoolManager.request`. Retrying requests ----------------- urllib3 can automatically retry idempotent requests. This same mechanism also handles redirects. You can control the retries using the ``retries`` parameter to :meth:`~poolmanager.PoolManager.request`. By default, urllib3 will retry requests 3 times and follow up to 3 redirects. To change the number of retries just specify an integer:: >>> http.requests('GET', 'http://httpbin.org/ip', retries=10) To disable all retry and redirect logic specify ``retries=False``:: >>> http.request( ... 'GET', 'http://nxdomain.example.com', retries=False) NewConnectionError >>> r = http.request( ... 'GET', 'http://httpbin.org/redirect/1', retries=False) >>> r.status 302 To disable redirects but keep the retrying logic, specify ``redirect=False``:: >>> r = http.request( ... 'GET', 'http://httpbin.org/redirect/1', redirect=False) >>> r.status 302 For more granular control you can use a :class:`~util.retry.Retry` instance. This class allows you far greater control of how requests are retried. For example, to do a total of 3 retries, but limit to only 2 redirects:: >>> http.request( ... 'GET', ... 'http://httpbin.org/redirect/3', ... retries=urllib3.Retry(3, redirect=2)) MaxRetryError You can also disable exceptions for too many redirects and just return the ``302`` response:: >>> r = http.request( ... 'GET', ... 'http://httpbin.org/redirect/3', ... retries=urllib3.Retry( ... redirect=2, raise_on_redirect=False)) >>> r.status 302 If you want all requests to be subject to the same retry policy, you can specify the retry at the :class:`~urllib3.poolmanager.PoolManager` level:: >>> http = urllib3.PoolManager(retries=False) >>> http = urllib3.PoolManager( ... retries=urllib3.Retry(5, redirect=2)) You still override this pool-level retry policy by specifying ``retries`` to :meth:`~poolmanager.PoolManager.request`. Errors & Exceptions ------------------- urllib3 wraps lower-level exceptions, for example:: >>> try: ... http.request('GET', 'nx.example.com', retries=False) >>> except urllib3.exceptions.NewConnectionError: ... print('Connection failed.') See :mod:`~urllib3.exceptions` for the full list of all exceptions. Logging ------- If you are using the standard library :mod:`logging` module urllib3 will emit several logs. In some cases this can be undesirable. You can use the standard logger interface to change the log level for urllib3's logger:: >>> logging.getLogger("urllib3").setLevel(logging.WARNING) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8938637 urllib3-1.25.8/dummyserver/0000755000175000017500000000000000000000000020466 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/__init__.py0000644000175000017500000000000000000000000022565 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8938637 urllib3-1.25.8/dummyserver/certs/0000755000175000017500000000000000000000000021606 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/README.rst0000644000175000017500000000115400000000000023276 0ustar00sethmlarsonsethmlarson00000000000000Creating a new SAN-less CRT --------------------------- (Instructions lifted from Heroku_) 1. Generate a new CSR:: openssl req -new -key server.key -out server.new.csr -nodes -days 10957 2. Generate a new CRT:: openssl x509 -req -in server.new.csr -signkey server.key -out server.new.crt -days 10957 Creating a new PEM file with your new CRT ----------------------------------------- 1. Concatenate the ``crt`` and ``key`` files into one:: cat server.new.crt server.key > cacert.new.pem :Last Modified: 1 Nov 2014 .. _Heroku: https://devcenter.heroku.com/articles/ssl-certificate-self ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/cacert.key0000644000175000017500000000157300000000000023567 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDKz8a9X2SfNms9TffyNaFO/K42fAjUI1dAM1G8TVoj0a81ay7W z4R7V1zfjXFT/WoRW04Y6xek0bff0OtsW+AriooUy7+pPYnrchpAW0p7hPjH1DIB Vab01CJMhQ24er92Q1dF4WBv4yKqEaV1IYz1cvqvCCJgAbsWn1I8Cna1lwIDAQAB AoGAPpkK+oBrCkk9qFpcYUH0W/DZxK9b+j4+O+6bF8e4Pr4FmjNO7bZ3aap5W/bI N+hLyLepzz8guRqR6l8NixCAi+JiVW/agh5o4Jrek8UJWQamwSL4nJ36U3Iw/l7w vcN1txfkpsA2SB9QFPGfDKcP3+IZMOZ7uFLzk/gzgLYiCEECQQD+M5Lj+e/sNBkb XeIBxWIrPfEeIkk4SDkqImzDjq1FcfxZkvfskqyJgUvcLe5hb+ibY8jqWvtpvFTI 5v/tzHvPAkEAzD8fNrGz8KiAVTo7+0vrb4AebAdSLZUvbp0AGs5pXUAuQx6VEgz8 opNKpZjBwAFsZKlwhgDqaChiAt9aKUkzuQJBALlai9I2Dg7SkjgVRdX6wjE7slRB tdgXOa+SeHJD1+5aRiJeeu8CqFJ/d/wtdbOQsTCVGwxfmREpZT00ywrvXpsCQQCU gs1Kcrn5Ijx2PCrDFbfyUkFMoaIiXNipYGVkGHRKhtFcoo8YGfNUry7W7BTtbNuI 8h9MgLvw0nQ5zHf9jymZAkEA7o4uA6XSS1zUqEQ55bZRFHcz/99pLH35G906iwVb d5rd1Z4Cf5s/91o5gwL6ZP2Ig34CCn+NSL4avgz6K0VUaA== -----END RSA PRIVATE KEY----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/cacert.pem0000644000175000017500000000254300000000000023556 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIIDzDCCAzWgAwIBAgIJALPrscov4b/jMA0GCSqGSIb3DQEBBQUAMIGBMQswCQYD VQQGEwJGSTEOMAwGA1UECAwFZHVtbXkxDjAMBgNVBAcMBWR1bW15MQ4wDAYDVQQK DAVkdW1teTEOMAwGA1UECwwFZHVtbXkxETAPBgNVBAMMCFNuYWtlT2lsMR8wHQYJ KoZIhvcNAQkBFhBkdW1teUB0ZXN0LmxvY2FsMB4XDTExMTIyMjA3NTYxNVoXDTIx MTIxOTA3NTYxNVowgYExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVkdW1teTEOMAwG A1UEBwwFZHVtbXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVkdW1teTERMA8G A1UEAwwIU25ha2VPaWwxHzAdBgkqhkiG9w0BCQEWEGR1bW15QHRlc3QubG9jYWww gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMrPxr1fZJ82az1N9/I1oU78rjZ8 CNQjV0AzUbxNWiPRrzVrLtbPhHtXXN+NcVP9ahFbThjrF6TRt9/Q62xb4CuKihTL v6k9ietyGkBbSnuE+MfUMgFVpvTUIkyFDbh6v3ZDV0XhYG/jIqoRpXUhjPVy+q8I ImABuxafUjwKdrWXAgMBAAGjggFIMIIBRDAdBgNVHQ4EFgQUGXd/I2JiQllF+3Wd x3NyBLszCi0wgbYGA1UdIwSBrjCBq4AUGXd/I2JiQllF+3Wdx3NyBLszCi2hgYek gYQwgYExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UEBwwFZHVt bXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVkdW1teTERMA8GA1UEAwwIU25h a2VPaWwxHzAdBgkqhkiG9w0BCQEWEGR1bW15QHRlc3QubG9jYWyCCQCz67HKL+G/ 4zAPBgNVHRMBAf8EBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIBBjAJBgNVHRIEAjAA MCsGCWCGSAGG+EIBDQQeFhxUaW55Q0EgR2VuZXJhdGVkIENlcnRpZmljYXRlMA4G A1UdDwEB/wQEAwICBDANBgkqhkiG9w0BAQUFAAOBgQBvz3AlIM1x7CMmwkmhLV6+ PJkMnPW7XbP+cDYUlddCk7XhIDY4486JxqZegMTWgbUt0AgXYfHLFsTqUJXrnLj2 WqLb3KP2D1HvnvxJjdJV3M6+TP7tGiY4ICi0zff96FG5C2w9Avsozhr3xDFtjKBv gyA6UdP3oZGN93oOFiMJXg== -----END CERTIFICATE----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/client_bad.pem0000644000175000017500000000174100000000000024400 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIICsDCCAhmgAwIBAgIJAL63Nc6KY94BMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTExMDExMjMxMjAzWhcNMjExMDA4MjMxMjAzWjBF MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC8HGxvblJ4Z0i/lIlG8jrNsFrCqYRAXtj3xdnnjfUpd/kNhU/KahMsG6urAe/4 Yj+Zqf1sVnt0Cye8FZE3cN9RAcwJrlTCRiicJiXEbA7cPfMphqNGqjVHtmxQ1OsU NHK7cxKa9OX3xmg4h55vxSZYgibAEPO2g3ueGk7RWIAQ8wIDAQABo4GnMIGkMB0G A1UdDgQWBBSeeo/YRpdn5DK6bUI7ZDJ57pzGdDB1BgNVHSMEbjBsgBSeeo/YRpdn 5DK6bUI7ZDJ57pzGdKFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUt U3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAL63Nc6K Y94BMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAOntoloMGt1325UR0 GGEKQJbiRhLXY4otdgFjEvCG2RPZVLxWYhLMu0LkB6HBYULEuoy12ushtRWlhS1k 6PNRkaZ+LQTSREj6Do4c4zzLxCDmxYmejOz63cIWX2x5IY6qEx2BNOfmM4xEdF8W LSGGbQfuAghiEh0giAi4AQloDlY= -----END CERTIFICATE----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/client_intermediate.pem0000644000175000017500000000364100000000000026325 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIIChzCCAfCgAwIBAgIUZgix95Zxzc+WryIWanrDezW1VjcwDQYJKoZIhvcNAQEL BQAwRDEbMBkGA1UECgwSdHJ1c3RtZSB2MC40LjArZGV2MSUwIwYDVQQLDBxUZXN0 aW5nIENBICNwN2dEd0tMS3EydlJOajZmMCAXDTAwMDEwMTAwMDAwMFoYDzMwMDAw MTAxMDAwMDAwWjBNMRswGQYDVQQKDBJ0cnVzdG1lIHYwLjQuMCtkZXYxLjAsBgNV BAsMJVRlc3Rpbmcgc2VydmVyIGNlcnQgI0NPajVGVkxXWEVtcmFHNTQwgZ8wDQYJ KoZIhvcNAQEBBQADgY0AMIGJAoGBAKeE765+Ws1ZdC86tfZ5LvLTjWluQgmsTx2o 7xhYAOFmTbZb6qNLCDS07R1VP74ve6UlFD55cV8VbxvEZd8Z3LOADF6nTN61XPbj dn2J6GfsSjaHE6+mJDXhCtVrD4EGdD4nXRem48mjsrAkrvJ8v4gQNzGzQ27D2dWT B7Ij6mWNAgMBAAGjazBpMB0GA1UdDgQWBBT66uW6I2OfZYacXgQkop4qlX+qJTAM BgNVHRMBAf8EAjAAMB8GA1UdIwQYMBaAFESoDYfzVyFP3QHyZG9cvxmlBIGsMBkG A1UdEQEB/wQPMA2CC2xvY2FsY2xpZW50MA0GCSqGSIb3DQEBCwUAA4GBAG8zoqW0 w5ROSuNFE7fi5I4bdC6sbddiFRXX//TkP2vRD3cM11AKp52UjzK2nUrkoigrJ5p8 xa/PGnPfOVCPiKIb1kzeI/7tyBet6n3q2L0wQo3PR/QCHeSiIpm8lAi1a+8ShXFM F2CG+z7IN0cQO4bzcwtkk8MhcCsMP14K5PK2 -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIICwjCCAiugAwIBAgIUWL7wOmK0BVMR8LM5UBewDZEEuH0wDQYJKoZIhvcNAQEL BQAwgYExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UEBwwFZHVt bXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVkdW1teTERMA8GA1UEAwwIU25h a2VPaWwxHzAdBgkqhkiG9w0BCQEWEGR1bW15QHRlc3QubG9jYWwwIBcNMDAwMTAx MDAwMDAwWhgPMzAwMDAxMDEwMDAwMDBaMEQxGzAZBgNVBAoMEnRydXN0bWUgdjAu NC4wK2RldjElMCMGA1UECwwcVGVzdGluZyBDQSAjcDdnRHdLTEtxMnZSTmo2ZjCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAr7134NKsqNQ44gIFElVC5KnGYIYv D96Kv+5UgXVAyNNK4NpQXHVFmCZpSuyvlz4UZzFBoykISjU+vcGqbFqwRrYciPwh 45HVQgtoe0SSpze7sv0qsMJiGNRDK06nVI/aCHP9FRoD5iPq8E7lSNVYipai466G 1lEvVLb0SGNihAUCAwEAAaNxMG8wHQYDVR0OBBYEFESoDYfzVyFP3QHyZG9cvxml BIGsMBIGA1UdEwEB/wQIMAYBAf8CAQgwDgYDVR0PAQH/BAQDAgEGMCoGA1UdJQEB /wQgMB4GCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMwDQYJKoZIhvcNAQEL BQADgYEAEs9EAeL3300UxzmT4zyj2cHB2GQxisteEuz9VcWhrvyNDxQ3ko0BxG04 4fye7dpElrrbSq8PYkygA1qiBCN2NL+v78XWb2OYd7PptpbPehzaEpCTK37O+Num sB4v1c63r2w1mH1lSjZDkJfd1hml+VwntSzuCmGERlroE6PQwf8= -----END CERTIFICATE----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/client_password.key0000644000175000017500000000173200000000000025523 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-256-CBC,70C641602D5F366DC5DB70645351993D /Ijrtw+2Rjc1mQCXWoNCtzjbRoIhBHQu9ZbQoCnC4/lHru2megV0vDQju0yYjs2H 7Y7tnMe0hlR9F21be6AkoKDF4B5Kg2X47fwG5V9SIbHBkz3KClfnPp/ojrhIWLTo grtZoXBFkivDnkuF9NO3qRlskP7u//r3kB5uXIG0ZpfUbRwgm13SqHj1oEB9RdYM bGhB3tL6dxdIXEgyc9numKBQ0lQu5yYlOH+1aiJSQQdN59ZunreIq//UM1Qc7Uj/ ILJusFmnec40ArJ+aykENWkToHSKkpeL6no6ZRCnkAYqtUJ84B6zMv9zYhN5UF3O WHP/4FAu4AylJvNx9sYxXdGaBb+YcX46B7wQk2mkmCtK6cgkrNV3/bohUbYt3tSe K9dH2xe9orxsGQjoKxylwh7+h8o+BwHpk1naFSzliQV4gvi8yBEzXxM98vNU5B4L ex8Q2ARWvfNc7OBqboPP0yBMKP/cV9n+fNMwbP0koHxBt71527fVQLoemMiPRb5M +rcufc+80AUK4baAA5Nu2sZGRqoiFemQ2vgEAxOzRbt/pHzdheO6OHqLJ5W4IWaW Erojm7/ar6gDlIIGwM8IJdbcMG69s7r8u47lD45ONQMq41Io4Svvs0SCgdRhLt/3 Nb6Smxy7vWFOcrHEJVsv27UD0FViaYHy37DIc6lVvX9s6+VKbdIYuiqxalbaCpKo VP8kdQZ4SFBAxV9cgPjFbQKVBXkLBdxJKGPzzK3Jc9khD1uHp5Um8OSM21Kh55N3 jvDY5h8fQ0cPyJmlZJzRdYi1+8H5TSFvEXd6cqVkYWiJ1ac0gPOoVt7+YAZ6JB2J -----END RSA PRIVATE KEY----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/server.combined.pem0000644000175000017500000000414400000000000025401 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIIDczCCAtygAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UEBhMCRkkx DjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQHDAVkdW1teTEOMAwGA1UECgwFZHVtbXkx DjAMBgNVBAsMBWR1bW15MREwDwYDVQQDDAhTbmFrZU9pbDEfMB0GCSqGSIb3DQEJ ARYQZHVtbXlAdGVzdC5sb2NhbDAeFw0xMTEyMjIwNzU4NDBaFw0yMTEyMTgwNzU4 NDBaMGExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UEBwwFZHVt bXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVkdW1teTESMBAGA1UEAwwJbG9j YWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXe3FqmCWvP8XPxqtT +0bfL1Tvzvebi46k0WIcUV8bP3vyYiSRXG9ALmyzZH4GHY9UVs4OEDkCMDOBSezB 0y9ai/9doTNcaictdEBu8nfdXKoTtzrn+VX4UPrkH5hm7NQ1fTQuj1MR7yBCmYqN 3Q2Q+Efuujyx0FwBzAuy1aKYuwIDAQABo4IBGDCCARQwCQYDVR0TBAIwADAdBgNV HQ4EFgQUG+dK5Uos08QUwAWofDb3a8YcYlIwgbYGA1UdIwSBrjCBq4AUGXd/I2Ji QllF+3Wdx3NyBLszCi2hgYekgYQwgYExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVk dW1teTEOMAwGA1UEBwwFZHVtbXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVk dW1teTERMA8GA1UEAwwIU25ha2VPaWwxHzAdBgkqhkiG9w0BCQEWEGR1bW15QHRl c3QubG9jYWyCCQCz67HKL+G/4zAJBgNVHRIEAjAAMCQGA1UdEQQdMBuBDnJvb3RA bG9jYWxob3N0gglsb2NhbGhvc3QwDQYJKoZIhvcNAQEFBQADgYEAgcW6X1ZUyufm TFEqEAdpKXdL0rxDwcsM/qqqsXbkz17otH6ujPhBEagzdKtgeNKfy0aXz6rWZugk lF0IqyC4mcI+vvfgGR5Iy4KdXMrIX98MbrvGJBfbdKhGW2b84wDV42DIDiD2ZGGe 6YZQQIo9LxjuOTf9jsvf+PIkbI4H0To= -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDXe3FqmCWvP8XPxqtT+0bfL1Tvzvebi46k0WIcUV8bP3vyYiSR XG9ALmyzZH4GHY9UVs4OEDkCMDOBSezB0y9ai/9doTNcaictdEBu8nfdXKoTtzrn +VX4UPrkH5hm7NQ1fTQuj1MR7yBCmYqN3Q2Q+Efuujyx0FwBzAuy1aKYuwIDAQAB AoGBANOGBM6bbhq7ImYU4qf8+RQrdVg2tc9Fzo+yTnn30sF/rx8/AiCDOV4qdGAh HKjKKaGj2H/rotqoEFcxBy05LrgJXxydBP72e9PYhNgKOcSmCQu4yALIPEXfKuIM zgAErHVJ2l79fif3D4hzNyz+u5E1A9n3FG9cgaJSiYP8IG2RAkEA82GZ8rBkSGQQ ZQ3oFuzPAAL21lbj8D0p76fsCpvS7427DtZDOjhOIKZmaeykpv+qSzRraqEqjDRi S4kjQvwh6QJBAOKniZ+NDo2lSpbOFk+XlmABK1DormVpj8KebHEZYok1lRI+WiX9 Nnoe9YLgix7++6H5SBBCcTB4HvM+5A4BuwMCQQChcX/eZbXP81iQwB3Rfzp8xnqY icDf7qKvz9Ma4myU7Y5E9EpaB1mD/P14jDpYcMW050vNyqTfpiwB8TFL0NZpAkEA 02jkFH9UyMgZV6qo4tqI98l/ZrtyF8OrxSNSEPhVkZf6EQc5vN9/lc8Uv1vESEgb 3AwRrKDcxRH2BHtv6qSwkwJAGjqnkIcEkA75r1e55/EF2chcZW1+tpwKupE8CtAH VXGd5DVwt4cYWkLUj2gF2fJbV97uu2MAg5CFDb+vQ6p5eA== -----END RSA PRIVATE KEY----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/server.crt0000644000175000017500000000235100000000000023627 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIIDczCCAtygAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UEBhMCRkkx DjAMBgNVBAgMBWR1bW15MQ4wDAYDVQQHDAVkdW1teTEOMAwGA1UECgwFZHVtbXkx DjAMBgNVBAsMBWR1bW15MREwDwYDVQQDDAhTbmFrZU9pbDEfMB0GCSqGSIb3DQEJ ARYQZHVtbXlAdGVzdC5sb2NhbDAeFw0xMTEyMjIwNzU4NDBaFw0yMTEyMTgwNzU4 NDBaMGExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVkdW1teTEOMAwGA1UEBwwFZHVt bXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVkdW1teTESMBAGA1UEAwwJbG9j YWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXe3FqmCWvP8XPxqtT +0bfL1Tvzvebi46k0WIcUV8bP3vyYiSRXG9ALmyzZH4GHY9UVs4OEDkCMDOBSezB 0y9ai/9doTNcaictdEBu8nfdXKoTtzrn+VX4UPrkH5hm7NQ1fTQuj1MR7yBCmYqN 3Q2Q+Efuujyx0FwBzAuy1aKYuwIDAQABo4IBGDCCARQwCQYDVR0TBAIwADAdBgNV HQ4EFgQUG+dK5Uos08QUwAWofDb3a8YcYlIwgbYGA1UdIwSBrjCBq4AUGXd/I2Ji QllF+3Wdx3NyBLszCi2hgYekgYQwgYExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIDAVk dW1teTEOMAwGA1UEBwwFZHVtbXkxDjAMBgNVBAoMBWR1bW15MQ4wDAYDVQQLDAVk dW1teTERMA8GA1UEAwwIU25ha2VPaWwxHzAdBgkqhkiG9w0BCQEWEGR1bW15QHRl c3QubG9jYWyCCQCz67HKL+G/4zAJBgNVHRIEAjAAMCQGA1UdEQQdMBuBDnJvb3RA bG9jYWxob3N0gglsb2NhbGhvc3QwDQYJKoZIhvcNAQEFBQADgYEAgcW6X1ZUyufm TFEqEAdpKXdL0rxDwcsM/qqqsXbkz17otH6ujPhBEagzdKtgeNKfy0aXz6rWZugk lF0IqyC4mcI+vvfgGR5Iy4KdXMrIX98MbrvGJBfbdKhGW2b84wDV42DIDiD2ZGGe 6YZQQIo9LxjuOTf9jsvf+PIkbI4H0To= -----END CERTIFICATE----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/server.csr0000644000175000017500000000246200000000000023631 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIIDqDCCAxGgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UEBhMCRkkx DjAMBgNVBAgTBWR1bW15MQ4wDAYDVQQHEwVkdW1teTEOMAwGA1UEChMFZHVtbXkx DjAMBgNVBAsTBWR1bW15MREwDwYDVQQDEwhTbmFrZU9pbDEfMB0GCSqGSIb3DQEJ ARYQZHVtbXlAdGVzdC5sb2NhbDAeFw0xMTEyMjIwNzU4NDBaFw0yMTEyMTgwNzU4 NDBaMGExCzAJBgNVBAYTAkZJMQ4wDAYDVQQIEwVkdW1teTEOMAwGA1UEBxMFZHVt bXkxDjAMBgNVBAoTBWR1bW15MQ4wDAYDVQQLEwVkdW1teTESMBAGA1UEAxMJbG9j YWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXe3FqmCWvP8XPxqtT +0bfL1Tvzvebi46k0WIcUV8bP3vyYiSRXG9ALmyzZH4GHY9UVs4OEDkCMDOBSezB 0y9ai/9doTNcaictdEBu8nfdXKoTtzrn+VX4UPrkH5hm7NQ1fTQuj1MR7yBCmYqN 3Q2Q+Efuujyx0FwBzAuy1aKYuwIDAQABo4IBTTCCAUkwCQYDVR0TBAIwADARBglg hkgBhvhCAQEEBAMCBkAwKwYJYIZIAYb4QgENBB4WHFRpbnlDQSBHZW5lcmF0ZWQg Q2VydGlmaWNhdGUwHQYDVR0OBBYEFBvnSuVKLNPEFMAFqHw292vGHGJSMIG2BgNV HSMEga4wgauAFBl3fyNiYkJZRft1ncdzcgS7MwotoYGHpIGEMIGBMQswCQYDVQQG EwJGSTEOMAwGA1UECBMFZHVtbXkxDjAMBgNVBAcTBWR1bW15MQ4wDAYDVQQKEwVk dW1teTEOMAwGA1UECxMFZHVtbXkxETAPBgNVBAMTCFNuYWtlT2lsMR8wHQYJKoZI hvcNAQkBFhBkdW1teUB0ZXN0LmxvY2FsggkAs+uxyi/hv+MwCQYDVR0SBAIwADAZ BgNVHREEEjAQgQ5yb290QGxvY2FsaG9zdDANBgkqhkiG9w0BAQUFAAOBgQBXdedG XHLPmOVBeKWjTmaekcaQi44snhYqE1uXRoIQXQsyw+Ya5+n/uRxPKZO/C78EESL0 8rnLTdZXm4GBYyHYmMy0AdWR7y030viOzAkWWRRRbuecsaUzFCI+F9jTV5LHuRzz V8fUKwiEE9swzkWgMpfVTPFuPgzxwG9gMbrBfg== -----END CERTIFICATE----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/server.key0000644000175000017500000000157300000000000023634 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDXe3FqmCWvP8XPxqtT+0bfL1Tvzvebi46k0WIcUV8bP3vyYiSR XG9ALmyzZH4GHY9UVs4OEDkCMDOBSezB0y9ai/9doTNcaictdEBu8nfdXKoTtzrn +VX4UPrkH5hm7NQ1fTQuj1MR7yBCmYqN3Q2Q+Efuujyx0FwBzAuy1aKYuwIDAQAB AoGBANOGBM6bbhq7ImYU4qf8+RQrdVg2tc9Fzo+yTnn30sF/rx8/AiCDOV4qdGAh HKjKKaGj2H/rotqoEFcxBy05LrgJXxydBP72e9PYhNgKOcSmCQu4yALIPEXfKuIM zgAErHVJ2l79fif3D4hzNyz+u5E1A9n3FG9cgaJSiYP8IG2RAkEA82GZ8rBkSGQQ ZQ3oFuzPAAL21lbj8D0p76fsCpvS7427DtZDOjhOIKZmaeykpv+qSzRraqEqjDRi S4kjQvwh6QJBAOKniZ+NDo2lSpbOFk+XlmABK1DormVpj8KebHEZYok1lRI+WiX9 Nnoe9YLgix7++6H5SBBCcTB4HvM+5A4BuwMCQQChcX/eZbXP81iQwB3Rfzp8xnqY icDf7qKvz9Ma4myU7Y5E9EpaB1mD/P14jDpYcMW050vNyqTfpiwB8TFL0NZpAkEA 02jkFH9UyMgZV6qo4tqI98l/ZrtyF8OrxSNSEPhVkZf6EQc5vN9/lc8Uv1vESEgb 3AwRrKDcxRH2BHtv6qSwkwJAGjqnkIcEkA75r1e55/EF2chcZW1+tpwKupE8CtAH VXGd5DVwt4cYWkLUj2gF2fJbV97uu2MAg5CFDb+vQ6p5eA== -----END RSA PRIVATE KEY----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/server.key.org0000644000175000017500000000106100000000000024412 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,8B3708EAD53963D4 uyLo4sFmSo7+K1uVgSENI+85JsG5o1JmovvxD/ucUl9CDhDj4KgFzs95r7gjjlhS kA/hIY8Ec9i6T3zMXpAswWI5Mv2LE+UdYR5h60dYtIinLC7KF0QIztSecNWy20Bi /NkobZhN7VZUuCEoSRWj4Ia3EuATF8Y9ZRGFPNsqMbSAhsGZ1P5xbDMEpE+5PbJP LvdF9yWDT77rHeI4CKV4aP/yxtm1heEhKw5o6hdpPBQajPpjSQbh7/V6Qd0QsKcV n27kPnSabsTbbc2IR40il4mZfHvXAlp4KoHL3RUgaons7q0hAUpUi+vJXbEukGGt 3dlyWwKwEFS7xBQ1pQvzcePI4/fRQxhZNxeFZW6n12Y3X61vg1IsG7usPhRe3iDP 3g1MXQMAhxaECnDN9b006IeoYdaktd4wrs/fn8x6Yz4= -----END RSA PRIVATE KEY----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/certs/server_password.key0000644000175000017500000000173200000000000025553 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-256-CBC,D1BAE8F8B899FD9C2367B4CCF40917CF emTIXrQCcOcHtknXXZwK9X4qS8WcT6ozH2TTTDOcz9+G6CnszwvnsLCnO3eiLVbI NXiFib7ulQksoHQd2MPC9pjWm1a8vadMYOWgx8jnYkgVE+l1ICGgZVACg55/E6Xj qC4hZijQnKhPPyzdebeos2IIk7B3op4kHYJQGpwisAuSmT06c2x/jsmFr+2UMSq5 Xf+kWuQlHUPcDct6uLJJ4zhFljcxFvk3cgMZIJaqyWCX7+gDCOi2gWrP2l1osllc q0egNUdg3RVrbxgxFn4XdHpmTNbIc3NTTR+xYuqHun8UbJrss1Ed25rrK0QzuV0l vyKLj1MSOV9VRCujF58I9whDZSwt07Aozmm1JC9F8kyMhbL9C4gmwEKHIQ5N5I+V mZKKAbJyQ2B1Oza/yZUnJG6hUyKTVbbCW57OltTDr4KlUzYUJJzTVyMy14AVv3zU GzKX5m3AzWMjykpmHjYNcI/zMQem0OQB2U9Pqyyh2GzItnHpnkqb7RDJSIYiOToc jA65NhS4sIZWWzwsRRaE2sq1rlssQFkzM3gIHi2C+tJD3PvmYRKW+6fLLNCqikMk w4OvHc8U/hIY2YnGAzjE7bbCrkQduhCwBL7bK08HYrluQv6dgVJLA9TtC4jYLYeo 1uXDNGcY943fwU5h/YwQbvVQ5oo9oHBJuLgUzXlPjc+va4gw0JSG59GgXaTMVTjw wybmcNlaFZbK0XrveX3ykJimnuDK29yY4nWSzPFRxvaaWaRAL4IgEXvKCiQhg8NE snV2L3uQgJNv6RmE+c4HzQQ71iZuZ+iJglzt/iG4pO88zxjLLfT4qwfPAlEdxRmN -----END RSA PRIVATE KEY----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/handlers.py0000644000175000017500000002530400000000000022644 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import print_function import collections import contextlib import gzip import json import logging import sys import time import zlib from io import BytesIO from tornado.web import RequestHandler from tornado import httputil from datetime import datetime from datetime import timedelta from urllib3.packages.six.moves.http_client import responses from urllib3.packages.six.moves.urllib.parse import urlsplit from urllib3.packages.six import binary_type, ensure_str log = logging.getLogger(__name__) class Response(object): def __init__(self, body="", status="200 OK", headers=None): self.body = body self.status = status self.headers = headers or [("Content-type", "text/plain")] def __call__(self, request_handler): status, reason = self.status.split(" ", 1) request_handler.set_status(int(status), reason) for header, value in self.headers: request_handler.add_header(header, value) # chunked if isinstance(self.body, list): for item in self.body: if not isinstance(item, bytes): item = item.encode("utf8") request_handler.write(item) request_handler.flush() else: body = self.body if not isinstance(body, bytes): body = body.encode("utf8") request_handler.write(body) RETRY_TEST_NAMES = collections.defaultdict(int) class TestingApp(RequestHandler): """ Simple app that performs various operations, useful for testing an HTTP library. Given any path, it will attempt to load a corresponding local method if it exists. Status code 200 indicates success, 400 indicates failure. Each method has its own conditions for success/failure. """ def get(self): """ Handle GET requests """ self._call_method() def post(self): """ Handle POST requests """ self._call_method() def put(self): """ Handle PUT requests """ self._call_method() def options(self): """ Handle OPTIONS requests """ self._call_method() def head(self): """ Handle HEAD requests """ self._call_method() def _call_method(self): """ Call the correct method in this class based on the incoming URI """ req = self.request req.params = {} for k, v in req.arguments.items(): req.params[k] = next(iter(v)) path = req.path[:] if not path.startswith("/"): path = urlsplit(path).path target = path[1:].replace("/", "_") method = getattr(self, target, self.index) resp = method(req) if dict(resp.headers).get("Connection") == "close": # FIXME: Can we kill the connection somehow? pass resp(self) def index(self, _request): "Render simple message" return Response("Dummy server!") def certificate(self, request): """Return the requester's certificate.""" cert = request.get_ssl_certificate() subject = dict() if cert is not None: subject = dict((k, v) for (k, v) in [y for z in cert["subject"] for y in z]) return Response(json.dumps(subject)) def source_address(self, request): """Return the requester's IP address.""" return Response(request.remote_ip) def set_up(self, request): test_type = request.params.get("test_type") test_id = request.params.get("test_id") if test_id: print("\nNew test %s: %s" % (test_type, test_id)) else: print("\nNew test %s" % test_type) return Response("Dummy server is ready!") def specific_method(self, request): "Confirm that the request matches the desired method type" method = request.params.get("method") if method and not isinstance(method, str): method = method.decode("utf8") if request.method != method: return Response( "Wrong method: %s != %s" % (method, request.method), status="400 Bad Request", ) return Response() def upload(self, request): "Confirm that the uploaded file conforms to specification" # FIXME: This is a huge broken mess param = request.params.get("upload_param", b"myfile").decode("ascii") filename = request.params.get("upload_filename", b"").decode("utf-8") size = int(request.params.get("upload_size", "0")) files_ = request.files.get(param) if len(files_) != 1: return Response( "Expected 1 file for '%s', not %d" % (param, len(files_)), status="400 Bad Request", ) file_ = files_[0] data = file_["body"] if int(size) != len(data): return Response( "Wrong size: %d != %d" % (size, len(data)), status="400 Bad Request" ) got_filename = file_["filename"] if isinstance(got_filename, binary_type): got_filename = got_filename.decode("utf-8") # Tornado can leave the trailing \n in place on the filename. if filename != got_filename: return Response( u"Wrong filename: %s != %s" % (filename, file_.filename), status="400 Bad Request", ) return Response() def redirect(self, request): "Perform a redirect to ``target``" target = request.params.get("target", "/") status = request.params.get("status", "303 See Other") if len(status) == 3: status = "%s Redirect" % status.decode("latin-1") headers = [("Location", target)] return Response(status=status, headers=headers) def not_found(self, request): return Response("Not found", status="404 Not Found") def multi_redirect(self, request): "Performs a redirect chain based on ``redirect_codes``" codes = request.params.get("redirect_codes", b"200").decode("utf-8") head, tail = codes.split(",", 1) if "," in codes else (codes, None) status = "{0} {1}".format(head, responses[int(head)]) if not tail: return Response("Done redirecting", status=status) headers = [("Location", "/multi_redirect?redirect_codes=%s" % tail)] return Response(status=status, headers=headers) def keepalive(self, request): if request.params.get("close", b"0") == b"1": headers = [("Connection", "close")] return Response("Closing", headers=headers) headers = [("Connection", "keep-alive")] return Response("Keeping alive", headers=headers) def echo_params(self, request): params = sorted( [(ensure_str(k), ensure_str(v)) for k, v in request.params.items()] ) return Response(repr(params)) def sleep(self, request): "Sleep for a specified amount of ``seconds``" # DO NOT USE THIS, IT'S DEPRECATED. # FIXME: Delete this once appengine tests are fixed to not use this handler. seconds = float(request.params.get("seconds", "1")) time.sleep(seconds) return Response() def echo(self, request): "Echo back the params" if request.method == "GET": return Response(request.query) return Response(request.body) def echo_uri(self, request): "Echo back the requested URI" return Response(request.uri) def encodingrequest(self, request): "Check for UA accepting gzip/deflate encoding" data = b"hello, world!" encoding = request.headers.get("Accept-Encoding", "") headers = None if encoding == "gzip": headers = [("Content-Encoding", "gzip")] file_ = BytesIO() with contextlib.closing( gzip.GzipFile("", mode="w", fileobj=file_) ) as zipfile: zipfile.write(data) data = file_.getvalue() elif encoding == "deflate": headers = [("Content-Encoding", "deflate")] data = zlib.compress(data) elif encoding == "garbage-gzip": headers = [("Content-Encoding", "gzip")] data = "garbage" elif encoding == "garbage-deflate": headers = [("Content-Encoding", "deflate")] data = "garbage" return Response(data, headers=headers) def headers(self, request): return Response(json.dumps(dict(request.headers))) def successful_retry(self, request): """ Handler which will return an error and then success It's not currently very flexible as the number of retries is hard-coded. """ test_name = request.headers.get("test-name", None) if not test_name: return Response("test-name header not set", status="400 Bad Request") RETRY_TEST_NAMES[test_name] += 1 if RETRY_TEST_NAMES[test_name] >= 2: return Response("Retry successful!") else: return Response("need to keep retrying!", status="418 I'm A Teapot") def chunked(self, request): return Response(["123"] * 4) def chunked_gzip(self, request): chunks = [] compressor = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) for uncompressed in [b"123"] * 4: chunks.append(compressor.compress(uncompressed)) chunks.append(compressor.flush()) return Response(chunks, headers=[("Content-Encoding", "gzip")]) def nbytes(self, request): length = int(request.params.get("length")) data = b"1" * length return Response(data, headers=[("Content-Type", "application/octet-stream")]) def status(self, request): status = request.params.get("status", "200 OK") return Response(status=status) def retry_after(self, request): if datetime.now() - self.application.last_req < timedelta(seconds=1): status = request.params.get("status", b"429 Too Many Requests") return Response( status=status.decode("utf-8"), headers=[("Retry-After", "1")] ) self.application.last_req = datetime.now() return Response(status="200 OK") def redirect_after(self, request): "Perform a redirect to ``target``" date = request.params.get("date") if date: retry_after = str( httputil.format_timestamp(datetime.fromtimestamp(float(date))) ) else: retry_after = "1" target = request.params.get("target", "/") headers = [("Location", target), ("Retry-After", retry_after)] return Response(status="303 See Other", headers=headers) def shutdown(self, request): sys.exit() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/proxy.py0000755000175000017500000001116500000000000022230 0ustar00sethmlarsonsethmlarson00000000000000#!/usr/bin/env python # # Simple asynchronous HTTP proxy with tunnelling (CONNECT). # # GET/POST proxying based on # http://groups.google.com/group/python-tornado/msg/7bea08e7a049cf26 # # Copyright (C) 2012 Senko Rasic # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys import socket import tornado.gen import tornado.httpserver import tornado.ioloop import tornado.iostream import tornado.web import tornado.httpclient __all__ = ["ProxyHandler", "run_proxy"] class ProxyHandler(tornado.web.RequestHandler): SUPPORTED_METHODS = ["GET", "POST", "CONNECT"] @tornado.gen.coroutine def get(self): def handle_response(response): if response.error and not isinstance( response.error, tornado.httpclient.HTTPError ): self.set_status(500) self.write("Internal server error:\n" + str(response.error)) self.finish() else: self.set_status(response.code) for header in ( "Date", "Cache-Control", "Server", "Content-Type", "Location", ): v = response.headers.get(header) if v: self.set_header(header, v) if response.body: self.write(response.body) self.finish() req = tornado.httpclient.HTTPRequest( url=self.request.uri, method=self.request.method, body=self.request.body, headers=self.request.headers, follow_redirects=False, allow_nonstandard_methods=True, ) client = tornado.httpclient.AsyncHTTPClient() try: response = yield client.fetch(req) yield handle_response(response) except tornado.httpclient.HTTPError as e: if hasattr(e, "response") and e.response: yield handle_response(e.response) else: self.set_status(500) self.write("Internal server error:\n" + str(e)) self.finish() @tornado.gen.coroutine def post(self): yield self.get() @tornado.gen.coroutine def connect(self): host, port = self.request.uri.split(":") client = self.request.connection.stream @tornado.gen.coroutine def start_forward(reader, writer): while True: try: data = yield reader.read_bytes(4096, partial=True) except tornado.iostream.StreamClosedError: break if not data: break writer.write(data) writer.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) upstream = tornado.iostream.IOStream(s) yield upstream.connect((host, int(port))) client.write(b"HTTP/1.0 200 Connection established\r\n\r\n") fu1 = start_forward(client, upstream) fu2 = start_forward(upstream, client) yield [fu1, fu2] def run_proxy(port, start_ioloop=True): """ Run proxy on the specified port. If start_ioloop is True (default), the tornado IOLoop will be started immediately. """ app = tornado.web.Application([(r".*", ProxyHandler)]) app.listen(port) ioloop = tornado.ioloop.IOLoop.instance() if start_ioloop: ioloop.start() if __name__ == "__main__": port = 8888 if len(sys.argv) > 1: port = int(sys.argv[1]) print("Starting HTTP proxy on port %d" % port) run_proxy(port) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/server.py0000755000175000017500000001221500000000000022352 0ustar00sethmlarsonsethmlarson00000000000000#!/usr/bin/env python """ Dummy server used for unit testing. """ from __future__ import print_function import logging import os import random import string import sys import threading import socket import warnings import ssl from datetime import datetime from urllib3.exceptions import HTTPWarning import tornado.httpserver import tornado.ioloop import tornado.netutil import tornado.web log = logging.getLogger(__name__) CERTS_PATH = os.path.join(os.path.dirname(__file__), "certs") DEFAULT_CERTS = { "certfile": os.path.join(CERTS_PATH, "server.crt"), "keyfile": os.path.join(CERTS_PATH, "server.key"), "cert_reqs": ssl.CERT_OPTIONAL, "ca_certs": os.path.join(CERTS_PATH, "cacert.pem"), } CLIENT_INTERMEDIATE_PEM = "client_intermediate.pem" CLIENT_NO_INTERMEDIATE_PEM = "client_no_intermediate.pem" CLIENT_INTERMEDIATE_KEY = "client_intermediate.key" CLIENT_CERT = os.path.join(CERTS_PATH, CLIENT_INTERMEDIATE_PEM) PASSWORD_KEYFILE = os.path.join(CERTS_PATH, "server_password.key") PASSWORD_CLIENT_KEYFILE = os.path.join(CERTS_PATH, "client_password.key") DEFAULT_CA = os.path.join(CERTS_PATH, "cacert.pem") DEFAULT_CA_KEY = os.path.join(CERTS_PATH, "cacert.key") DEFAULT_CA_BAD = os.path.join(CERTS_PATH, "client_bad.pem") COMBINED_CERT_AND_KEY = os.path.join(CERTS_PATH, "server.combined.pem") def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/urllib3/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6 # Some systems may have IPv6 support but DNS may not be configured # properly. We can not count that localhost will resolve to ::1 on all # systems. See https://github.com/urllib3/urllib3/pull/611 and # https://bugs.python.org/issue18792 HAS_IPV6_AND_DNS = _has_ipv6("localhost") HAS_IPV6 = _has_ipv6("::1") # Different types of servers we have: class NoIPv6Warning(HTTPWarning): "IPv6 is not available" pass class SocketServerThread(threading.Thread): """ :param socket_handler: Callable which receives a socket argument for one request. :param ready_event: Event which gets set when the socket handler is ready to receive requests. """ USE_IPV6 = HAS_IPV6_AND_DNS def __init__(self, socket_handler, host="localhost", port=8081, ready_event=None): threading.Thread.__init__(self) self.daemon = True self.socket_handler = socket_handler self.host = host self.ready_event = ready_event def _start_server(self): if self.USE_IPV6: sock = socket.socket(socket.AF_INET6) else: warnings.warn("No IPv6 support. Falling back to IPv4.", NoIPv6Warning) sock = socket.socket(socket.AF_INET) if sys.platform != "win32": sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((self.host, 0)) self.port = sock.getsockname()[1] # Once listen() returns, the server socket is ready sock.listen(1) if self.ready_event: self.ready_event.set() self.socket_handler(sock) sock.close() def run(self): self.server = self._start_server() def run_tornado_app(app, io_loop, certs, scheme, host): assert io_loop == tornado.ioloop.IOLoop.current() # We can't use fromtimestamp(0) because of CPython issue 29097, so we'll # just construct the datetime object directly. app.last_req = datetime(1970, 1, 1) if scheme == "https": http_server = tornado.httpserver.HTTPServer(app, ssl_options=certs) else: http_server = tornado.httpserver.HTTPServer(app) sockets = tornado.netutil.bind_sockets(None, address=host) port = sockets[0].getsockname()[1] http_server.add_sockets(sockets) return http_server, port def run_loop_in_thread(io_loop): t = threading.Thread(target=io_loop.start) t.start() return t def get_unreachable_address(): while True: host = "".join(random.choice(string.ascii_lowercase) for _ in range(60)) sockaddr = (host, 54321) # check if we are really "lucky" and hit an actual server try: s = socket.create_connection(sockaddr) except socket.error: return sockaddr else: s.close() if __name__ == "__main__": # For debugging dummyserver itself - python -m dummyserver.server from .testcase import TestingApp host = "127.0.0.1" io_loop = tornado.ioloop.IOLoop.current() app = tornado.web.Application([(r".*", TestingApp)]) server, port = run_tornado_app(app, io_loop, None, "http", host) server_thread = run_loop_in_thread(io_loop) print("Listening on http://{host}:{port}".format(host=host, port=port)) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/dummyserver/testcase.py0000644000175000017500000001405100000000000022654 0ustar00sethmlarsonsethmlarson00000000000000import threading import pytest from tornado import ioloop, web from dummyserver.server import ( SocketServerThread, run_tornado_app, run_loop_in_thread, DEFAULT_CERTS, HAS_IPV6, ) from dummyserver.handlers import TestingApp from dummyserver.proxy import ProxyHandler def consume_socket(sock, chunks=65536): consumed = bytearray() while True: b = sock.recv(chunks) consumed += b if b.endswith(b"\r\n\r\n"): break return consumed class SocketDummyServerTestCase(object): """ A simple socket-based server is created for this class that is good for exactly one request. """ scheme = "http" host = "localhost" @classmethod def _start_server(cls, socket_handler): ready_event = threading.Event() cls.server_thread = SocketServerThread( socket_handler=socket_handler, ready_event=ready_event, host=cls.host ) cls.server_thread.start() ready_event.wait(5) if not ready_event.is_set(): raise Exception("most likely failed to start server") cls.port = cls.server_thread.port @classmethod def start_response_handler(cls, response, num=1, block_send=None): ready_event = threading.Event() def socket_handler(listener): for _ in range(num): ready_event.set() sock = listener.accept()[0] consume_socket(sock) if block_send: block_send.wait() block_send.clear() sock.send(response) sock.close() cls._start_server(socket_handler) return ready_event @classmethod def start_basic_handler(cls, **kw): return cls.start_response_handler( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n" b"\r\n", **kw ) @classmethod def teardown_class(cls): if hasattr(cls, "server_thread"): cls.server_thread.join(0.1) def assert_header_received( self, received_headers, header_name, expected_value=None ): header_name = header_name.encode("ascii") if expected_value is not None: expected_value = expected_value.encode("ascii") header_titles = [] for header in received_headers: key, value = header.split(b": ") header_titles.append(key) if key == header_name and expected_value is not None: assert value == expected_value assert header_name in header_titles class IPV4SocketDummyServerTestCase(SocketDummyServerTestCase): @classmethod def _start_server(cls, socket_handler): ready_event = threading.Event() cls.server_thread = SocketServerThread( socket_handler=socket_handler, ready_event=ready_event, host=cls.host ) cls.server_thread.USE_IPV6 = False cls.server_thread.start() ready_event.wait(5) if not ready_event.is_set(): raise Exception("most likely failed to start server") cls.port = cls.server_thread.port class HTTPDummyServerTestCase(object): """ A simple HTTP server that runs when your test class runs Have your test class inherit from this one, and then a simple server will start when your tests run, and automatically shut down when they complete. For examples of what test requests you can send to the server, see the TestingApp in dummyserver/handlers.py. """ scheme = "http" host = "localhost" host_alt = "127.0.0.1" # Some tests need two hosts certs = DEFAULT_CERTS @classmethod def _start_server(cls): cls.io_loop = ioloop.IOLoop.current() app = web.Application([(r".*", TestingApp)]) cls.server, cls.port = run_tornado_app( app, cls.io_loop, cls.certs, cls.scheme, cls.host ) cls.server_thread = run_loop_in_thread(cls.io_loop) @classmethod def _stop_server(cls): cls.io_loop.add_callback(cls.server.stop) cls.io_loop.add_callback(cls.io_loop.stop) cls.server_thread.join() @classmethod def setup_class(cls): cls._start_server() @classmethod def teardown_class(cls): cls._stop_server() class HTTPSDummyServerTestCase(HTTPDummyServerTestCase): scheme = "https" host = "localhost" certs = DEFAULT_CERTS class HTTPDummyProxyTestCase(object): http_host = "localhost" http_host_alt = "127.0.0.1" https_host = "localhost" https_host_alt = "127.0.0.1" https_certs = DEFAULT_CERTS proxy_host = "localhost" proxy_host_alt = "127.0.0.1" @classmethod def setup_class(cls): cls.io_loop = ioloop.IOLoop.current() app = web.Application([(r".*", TestingApp)]) cls.http_server, cls.http_port = run_tornado_app( app, cls.io_loop, None, "http", cls.http_host ) app = web.Application([(r".*", TestingApp)]) cls.https_server, cls.https_port = run_tornado_app( app, cls.io_loop, cls.https_certs, "https", cls.http_host ) app = web.Application([(r".*", ProxyHandler)]) cls.proxy_server, cls.proxy_port = run_tornado_app( app, cls.io_loop, None, "http", cls.proxy_host ) cls.server_thread = run_loop_in_thread(cls.io_loop) @classmethod def teardown_class(cls): cls.io_loop.add_callback(cls.http_server.stop) cls.io_loop.add_callback(cls.https_server.stop) cls.io_loop.add_callback(cls.proxy_server.stop) cls.io_loop.add_callback(cls.io_loop.stop) cls.server_thread.join() @pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available") class IPv6HTTPDummyServerTestCase(HTTPDummyServerTestCase): host = "::1" @pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available") class IPv6HTTPDummyProxyTestCase(HTTPDummyProxyTestCase): http_host = "localhost" http_host_alt = "127.0.0.1" https_host = "localhost" https_host_alt = "127.0.0.1" https_certs = DEFAULT_CERTS proxy_host = "::1" proxy_host_alt = "127.0.0.1" ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/setup.cfg0000644000175000017500000000115300000000000017725 0ustar00sethmlarsonsethmlarson00000000000000[flake8] ignore = E501, E203, W503, W504 exclude = ./docs/conf.py,./src/urllib3/packages/* max-line-length = 99 [bdist_wheel] universal = 1 [metadata] license_file = LICENSE.txt provides-extra = secure socks brotli requires-dist = pyOpenSSL>=0.14; extra == 'secure' cryptography>=1.3.4; extra == 'secure' idna>=2.0.0; extra == 'secure' certifi; extra == 'secure' ipaddress; python_version=="2.7" and extra == 'secure' PySocks>=1.5.6,<2.0,!=1.5.7; extra == 'socks' brotlipy>=0.6.0; extra == 'brotli' [tool:pytest] xfail_strict = true python_classes = Test *TestCase [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/setup.py0000755000175000017500000000557500000000000017635 0ustar00sethmlarsonsethmlarson00000000000000#!/usr/bin/env python from setuptools import setup import os import re import codecs base_path = os.path.dirname(__file__) # Get the version (borrowed from SQLAlchemy) with open(os.path.join(base_path, "src", "urllib3", "__init__.py")) as fp: VERSION = ( re.compile(r""".*__version__ = ["'](.*?)['"]""", re.S).match(fp.read()).group(1) ) with codecs.open("README.rst", encoding="utf-8") as fp: readme = fp.read() with codecs.open("CHANGES.rst", encoding="utf-8") as fp: changes = fp.read() version = VERSION setup( name="urllib3", version=version, description="HTTP library with thread-safe connection pooling, file post, and more.", long_description=u"\n\n".join([readme, changes]), classifiers=[ "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries", ], keywords="urllib httplib threadsafe filepost http https ssl pooling", author="Andrey Petrov", author_email="andrey.petrov@shazow.net", url="https://urllib3.readthedocs.io/", project_urls={ "Documentation": "https://urllib3.readthedocs.io/", "Code": "https://github.com/urllib3/urllib3", "Issue tracker": "https://github.com/urllib3/urllib3/issues", }, license="MIT", packages=[ "urllib3", "urllib3.packages", "urllib3.packages.ssl_match_hostname", "urllib3.packages.backports", "urllib3.contrib", "urllib3.contrib._securetransport", "urllib3.util", ], package_dir={"": "src"}, requires=[], python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4", tests_require=[ # These are a less-specific subset of dev-requirements.txt, for the # convenience of distro package maintainers. "pytest", "mock", "tornado", ], test_suite="test", extras_require={ "brotli": ["brotlipy>=0.6.0"], "secure": [ "pyOpenSSL>=0.14", "cryptography>=1.3.4", "idna>=2.0.0", "certifi", "ipaddress; python_version=='2.7'", ], "socks": ["PySocks>=1.5.6,<2.0,!=1.5.7"], }, ) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8898635 urllib3-1.25.8/src/0000755000175000017500000000000000000000000016673 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/0000755000175000017500000000000000000000000020247 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/__init__.py0000644000175000017500000000517300000000000022366 0ustar00sethmlarsonsethmlarson00000000000000""" urllib3 - Thread-safe connection pooling and re-using. """ from __future__ import absolute_import import warnings from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url from . import exceptions from .filepost import encode_multipart_formdata from .poolmanager import PoolManager, ProxyManager, proxy_from_url from .response import HTTPResponse from .util.request import make_headers from .util.url import get_host from .util.timeout import Timeout from .util.retry import Retry # Set default logging handler to avoid "No handler found" warnings. import logging from logging import NullHandler __author__ = "Andrey Petrov (andrey.petrov@shazow.net)" __license__ = "MIT" __version__ = "1.25.8" __all__ = ( "HTTPConnectionPool", "HTTPSConnectionPool", "PoolManager", "ProxyManager", "HTTPResponse", "Retry", "Timeout", "add_stderr_logger", "connection_from_url", "disable_warnings", "encode_multipart_formdata", "get_host", "make_headers", "proxy_from_url", ) logging.getLogger(__name__).addHandler(NullHandler()) def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another package. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s")) logger.addHandler(handler) logger.setLevel(level) logger.debug("Added a stderr logging handler to logger: %s", __name__) return handler # ... Clean up. del NullHandler # All warning filters *must* be appended unless you're really certain that they # shouldn't be: otherwise, it's very hard for users to use most Python # mechanisms to silence them. # SecurityWarning's always go off by default. warnings.simplefilter("always", exceptions.SecurityWarning, append=True) # SubjectAltNameWarning's should go off once per host warnings.simplefilter("default", exceptions.SubjectAltNameWarning, append=True) # InsecurePlatformWarning's don't vary between requests, so we keep it default. warnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True) # SNIMissingWarnings should go off only once. warnings.simplefilter("default", exceptions.SNIMissingWarning, append=True) def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter("ignore", category) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/_collections.py0000644000175000017500000002505000000000000023300 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import try: from collections.abc import Mapping, MutableMapping except ImportError: from collections import Mapping, MutableMapping try: from threading import RLock except ImportError: # Platform-specific: No threads available class RLock: def __enter__(self): pass def __exit__(self, exc_type, exc_value, traceback): pass from collections import OrderedDict from .exceptions import InvalidHeader from .packages.six import iterkeys, itervalues, PY3 __all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"] _Null = object() class RecentlyUsedContainer(MutableMapping): """ Provides a thread-safe dict-like container which maintains up to ``maxsize`` keys while throwing away the least-recently-used keys beyond ``maxsize``. :param maxsize: Maximum number of recent elements to retain. :param dispose_func: Every time an item is evicted from the container, ``dispose_func(value)`` is called. Callback which will get called """ ContainerCls = OrderedDict def __init__(self, maxsize=10, dispose_func=None): self._maxsize = maxsize self.dispose_func = dispose_func self._container = self.ContainerCls() self.lock = RLock() def __getitem__(self, key): # Re-insert the item, moving it to the end of the eviction line. with self.lock: item = self._container.pop(key) self._container[key] = item return item def __setitem__(self, key, value): evicted_value = _Null with self.lock: # Possibly evict the existing value of 'key' evicted_value = self._container.get(key, _Null) self._container[key] = value # If we didn't evict an existing value, we might have to evict the # least recently used item from the beginning of the container. if len(self._container) > self._maxsize: _key, evicted_value = self._container.popitem(last=False) if self.dispose_func and evicted_value is not _Null: self.dispose_func(evicted_value) def __delitem__(self, key): with self.lock: value = self._container.pop(key) if self.dispose_func: self.dispose_func(value) def __len__(self): with self.lock: return len(self._container) def __iter__(self): raise NotImplementedError( "Iteration over this class is unlikely to be threadsafe." ) def clear(self): with self.lock: # Copy pointers to all values, then wipe the mapping values = list(itervalues(self._container)) self._container.clear() if self.dispose_func: for value in values: self.dispose_func(value) def keys(self): with self.lock: return list(iterkeys(self._container)) class HTTPHeaderDict(MutableMapping): """ :param headers: An iterable of field-value pairs. Must not contain multiple field names when compared case-insensitively. :param kwargs: Additional field-value pairs to pass in to ``dict.update``. A ``dict`` like container for storing HTTP Headers. Field names are stored and compared case-insensitively in compliance with RFC 7230. Iteration provides the first case-sensitive key seen for each case-insensitive pair. Using ``__setitem__`` syntax overwrites fields that compare equal case-insensitively in order to maintain ``dict``'s api. For fields that compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add`` in a loop. If multiple fields that are equal case-insensitively are passed to the constructor or ``.update``, the behavior is undefined and some will be lost. >>> headers = HTTPHeaderDict() >>> headers.add('Set-Cookie', 'foo=bar') >>> headers.add('set-cookie', 'baz=quxx') >>> headers['content-length'] = '7' >>> headers['SET-cookie'] 'foo=bar, baz=quxx' >>> headers['Content-Length'] '7' """ def __init__(self, headers=None, **kwargs): super(HTTPHeaderDict, self).__init__() self._container = OrderedDict() if headers is not None: if isinstance(headers, HTTPHeaderDict): self._copy_from(headers) else: self.extend(headers) if kwargs: self.extend(kwargs) def __setitem__(self, key, val): self._container[key.lower()] = [key, val] return self._container[key.lower()] def __getitem__(self, key): val = self._container[key.lower()] return ", ".join(val[1:]) def __delitem__(self, key): del self._container[key.lower()] def __contains__(self, key): return key.lower() in self._container def __eq__(self, other): if not isinstance(other, Mapping) and not hasattr(other, "keys"): return False if not isinstance(other, type(self)): other = type(self)(other) return dict((k.lower(), v) for k, v in self.itermerged()) == dict( (k.lower(), v) for k, v in other.itermerged() ) def __ne__(self, other): return not self.__eq__(other) if not PY3: # Python 2 iterkeys = MutableMapping.iterkeys itervalues = MutableMapping.itervalues __marker = object() def __len__(self): return len(self._container) def __iter__(self): # Only provide the originally cased names for vals in self._container.values(): yield vals[0] def pop(self, key, default=__marker): """D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. """ # Using the MutableMapping function directly fails due to the private marker. # Using ordinary dict.pop would expose the internal structures. # So let's reinvent the wheel. try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value def discard(self, key): try: del self[key] except KeyError: pass def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' """ key_lower = key.lower() new_vals = [key, val] # Keep the common case aka no item present as fast as possible vals = self._container.setdefault(key_lower, new_vals) if new_vals is not vals: vals.append(val) def extend(self, *args, **kwargs): """Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__ """ if len(args) > 1: raise TypeError( "extend() takes at most 1 positional " "arguments ({0} given)".format(len(args)) ) other = args[0] if len(args) >= 1 else () if isinstance(other, HTTPHeaderDict): for key, val in other.iteritems(): self.add(key, val) elif isinstance(other, Mapping): for key in other: self.add(key, other[key]) elif hasattr(other, "keys"): for key in other.keys(): self.add(key, other[key]) else: for key, value in other: self.add(key, value) for key, value in kwargs.items(): self.add(key, value) def getlist(self, key, default=__marker): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = self._container[key.lower()] except KeyError: if default is self.__marker: return [] return default else: return vals[1:] # Backwards compatibility for httplib getheaders = getlist getallmatchingheaders = getlist iget = getlist # Backwards compatibility for http.cookiejar get_all = getlist def __repr__(self): return "%s(%s)" % (type(self).__name__, dict(self.itermerged())) def _copy_from(self, other): for key in other: val = other.getlist(key) if isinstance(val, list): # Don't need to convert tuples val = list(val) self._container[key.lower()] = [key] + val def copy(self): clone = type(self)() clone._copy_from(self) return clone def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = self._container[key.lower()] for val in vals[1:]: yield vals[0], val def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = self._container[key.lower()] yield val[0], ", ".join(val[1:]) def items(self): return list(self.iteritems()) @classmethod def from_httplib(cls, message): # Python 2 """Read headers from a Python 2 httplib message object.""" # python2.7 does not expose a proper API for exporting multiheaders # efficiently. This function re-reads raw lines from the message # object and extracts the multiheaders properly. obs_fold_continued_leaders = (" ", "\t") headers = [] for line in message.headers: if line.startswith(obs_fold_continued_leaders): if not headers: # We received a header line that starts with OWS as described # in RFC-7230 S3.2.4. This indicates a multiline header, but # there exists no previous header to which we can attach it. raise InvalidHeader( "Header continuation with no previous header: %s" % line ) else: key, value = headers[-1] headers[-1] = (key, value + " " + line.strip()) continue key, value = line.split(":", 1) headers.append((key, value.strip())) return cls(headers) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/connection.py0000644000175000017500000003331200000000000022762 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import datetime import logging import os import socket from socket import error as SocketError, timeout as SocketTimeout import warnings from .packages import six from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection from .packages.six.moves.http_client import HTTPException # noqa: F401 try: # Compiled with SSL? import ssl BaseSSLError = ssl.SSLError except (ImportError, AttributeError): # Platform-specific: No SSL. ssl = None class BaseSSLError(BaseException): pass try: # Python 3: not a no-op, we're adding this to the namespace so it can be imported. ConnectionError = ConnectionError except NameError: # Python 2 class ConnectionError(Exception): pass from .exceptions import ( NewConnectionError, ConnectTimeoutError, SubjectAltNameWarning, SystemTimeWarning, ) from .packages.ssl_match_hostname import match_hostname, CertificateError from .util.ssl_ import ( resolve_cert_reqs, resolve_ssl_version, assert_fingerprint, create_urllib3_context, ssl_wrap_socket, ) from .util import connection from ._collections import HTTPHeaderDict log = logging.getLogger(__name__) port_by_scheme = {"http": 80, "https": 443} # When it comes time to update this value as a part of regular maintenance # (ie test_recent_date is failing) update it to ~6 months before the current date. RECENT_DATE = datetime.date(2019, 1, 1) class DummyConnection(object): """Used to detect a failed ConnectionCls import.""" pass class HTTPConnection(_HTTPConnection, object): """ Based on httplib.HTTPConnection but provides an extra constructor backwards-compatibility layer between older and newer Pythons. Additional keyword parameters are used to configure attributes of the connection. Accepted parameters include: - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool` - ``source_address``: Set the source address for the current connection. - ``socket_options``: Set specific options on the underlying socket. If not specified, then defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy. For example, if you wish to enable TCP Keep Alive in addition to the defaults, you might pass:: HTTPConnection.default_socket_options + [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), ] Or you may want to disable the defaults by passing an empty list (e.g., ``[]``). """ default_port = port_by_scheme["http"] #: Disable Nagle's algorithm by default. #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]`` default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] #: Whether this connection verifies the host's certificate. is_verified = False def __init__(self, *args, **kw): if not six.PY2: kw.pop("strict", None) # Pre-set source_address. self.source_address = kw.get("source_address") #: The socket options provided by the user. If no options are #: provided, we use the default options. self.socket_options = kw.pop("socket_options", self.default_socket_options) _HTTPConnection.__init__(self, *args, **kw) @property def host(self): """ Getter method to remove any trailing dots that indicate the hostname is an FQDN. In general, SSL certificates don't include the trailing dot indicating a fully-qualified domain name, and thus, they don't validate properly when checked against a domain name that includes the dot. In addition, some servers may not expect to receive the trailing dot when provided. However, the hostname with trailing dot is critical to DNS resolution; doing a lookup with the trailing dot will properly only resolve the appropriate FQDN, whereas a lookup without a trailing dot will search the system's search domain list. Thus, it's important to keep the original host around for use only in those cases where it's appropriate (i.e., when doing DNS lookup to establish the actual TCP connection across which we're going to send HTTP requests). """ return self._dns_host.rstrip(".") @host.setter def host(self, value): """ Setter for the `host` property. We assume that only urllib3 uses the _dns_host attribute; httplib itself only uses `host`, and it seems reasonable that other libraries follow suit. """ self._dns_host = value def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ extra_kw = {} if self.source_address: extra_kw["source_address"] = self.source_address if self.socket_options: extra_kw["socket_options"] = self.socket_options try: conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) return conn def _prepare_conn(self, conn): self.sock = conn # Google App Engine's httplib does not define _tunnel_host if getattr(self, "_tunnel_host", None): # TODO: Fix tunnel so it doesn't depend on self.sock state. self._tunnel() # Mark this connection as not reusable self.auto_open = 0 def connect(self): conn = self._new_conn() self._prepare_conn(conn) def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = "accept-encoding" in headers skip_host = "host" in headers self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) for header, value in headers.items(): self.putheader(header, value) if "transfer-encoding" not in headers: self.putheader("Transfer-Encoding", "chunked") self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode("utf8") len_str = hex(len(chunk))[2:] self.send(len_str.encode("utf-8")) self.send(b"\r\n") self.send(chunk) self.send(b"\r\n") # After the if clause, to always have a closed body self.send(b"0\r\n\r\n") class HTTPSConnection(HTTPConnection): default_port = port_by_scheme["https"] ssl_version = None def __init__( self, host, port=None, key_file=None, cert_file=None, key_password=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, ssl_context=None, server_hostname=None, **kw ): HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw) self.key_file = key_file self.cert_file = cert_file self.key_password = key_password self.ssl_context = ssl_context self.server_hostname = server_hostname # Required property for Google AppEngine 1.9.0 which otherwise causes # HTTPS requests to go out as HTTP. (See Issue #356) self._protocol = "https" class VerifiedHTTPSConnection(HTTPSConnection): """ Based on httplib.HTTPSConnection but wraps the socket with SSL certification. """ cert_reqs = None ca_certs = None ca_cert_dir = None ssl_version = None assert_fingerprint = None def set_cert( self, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, ): """ This method should only be called once, before the connection is used. """ # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also # have an SSLContext object in which case we'll use its verify_mode. if cert_reqs is None: if self.ssl_context is not None: cert_reqs = self.ssl_context.verify_mode else: cert_reqs = resolve_cert_reqs(None) self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.key_password = key_password self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) def connect(self): # Add certificate verification conn = self._new_conn() hostname = self.host # Google App Engine's httplib does not define _tunnel_host if getattr(self, "_tunnel_host", None): self.sock = conn # Calls self._set_hostport(), so self.host is # self._tunnel_host below. self._tunnel() # Mark this connection as not reusable self.auto_open = 0 # Override the host with the one we're requesting data from. hostname = self._tunnel_host server_hostname = hostname if self.server_hostname is not None: server_hostname = self.server_hostname is_time_off = datetime.date.today() < RECENT_DATE if is_time_off: warnings.warn( ( "System time is way off (before {0}). This will probably " "lead to SSL verification errors" ).format(RECENT_DATE), SystemTimeWarning, ) # Wrap socket using verification with the root certs in # trusted_root_certs default_ssl_context = False if self.ssl_context is None: default_ssl_context = True self.ssl_context = create_urllib3_context( ssl_version=resolve_ssl_version(self.ssl_version), cert_reqs=resolve_cert_reqs(self.cert_reqs), ) context = self.ssl_context context.verify_mode = resolve_cert_reqs(self.cert_reqs) # Try to load OS default certs if none are given. # Works well on Windows (requires Python3.4+) if ( not self.ca_certs and not self.ca_cert_dir and default_ssl_context and hasattr(context, "load_default_certs") ): context.load_default_certs() self.sock = ssl_wrap_socket( sock=conn, keyfile=self.key_file, certfile=self.cert_file, key_password=self.key_password, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, server_hostname=server_hostname, ssl_context=context, ) if self.assert_fingerprint: assert_fingerprint( self.sock.getpeercert(binary_form=True), self.assert_fingerprint ) elif ( context.verify_mode != ssl.CERT_NONE and not getattr(context, "check_hostname", False) and self.assert_hostname is not False ): # While urllib3 attempts to always turn off hostname matching from # the TLS library, this cannot always be done. So we check whether # the TLS Library still thinks it's matching hostnames. cert = self.sock.getpeercert() if not cert.get("subjectAltName", ()): warnings.warn( ( "Certificate for {0} has no `subjectAltName`, falling back to check for a " "`commonName` for now. This feature is being removed by major browsers and " "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 " "for details.)".format(hostname) ), SubjectAltNameWarning, ) _match_hostname(cert, self.assert_hostname or server_hostname) self.is_verified = ( context.verify_mode == ssl.CERT_REQUIRED or self.assert_fingerprint is not None ) def _match_hostname(cert, asserted_hostname): try: match_hostname(cert, asserted_hostname) except CertificateError as e: log.warning( "Certificate did not match expected hostname: %s. Certificate: %s", asserted_hostname, cert, ) # Add cert to exception and reraise so client code can inspect # the cert when catching the exception, if they want to e._peer_cert = cert raise if ssl: # Make a copy for testing. UnverifiedHTTPSConnection = HTTPSConnection HTTPSConnection = VerifiedHTTPSConnection else: HTTPSConnection = DummyConnection ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/connectionpool.py0000644000175000017500000010724100000000000023657 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import errno import logging import sys import warnings from socket import error as SocketError, timeout as SocketTimeout import socket from .exceptions import ( ClosedPoolError, ProtocolError, EmptyPoolError, HeaderParsingError, HostChangedError, LocationValueError, MaxRetryError, ProxyError, ReadTimeoutError, SSLError, TimeoutError, InsecureRequestWarning, NewConnectionError, ) from .packages.ssl_match_hostname import CertificateError from .packages import six from .packages.six.moves import queue from .connection import ( port_by_scheme, DummyConnection, HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection, HTTPException, BaseSSLError, ) from .request import RequestMethods from .response import HTTPResponse from .util.connection import is_connection_dropped from .util.request import set_file_position from .util.response import assert_header_parsing from .util.retry import Retry from .util.timeout import Timeout from .util.url import ( get_host, parse_url, Url, _normalize_host as normalize_host, _encode_target, ) from .util.queue import LifoQueue xrange = six.moves.xrange log = logging.getLogger(__name__) _Default = object() # Pool objects class ConnectionPool(object): """ Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. """ scheme = None QueueCls = LifoQueue def __init__(self, host, port=None): if not host: raise LocationValueError("No host specified.") self.host = _normalize_host(host, scheme=self.scheme) self._proxy_host = host.lower() self.port = port def __str__(self): return "%s(host=%r, port=%r)" % (type(self).__name__, self.host, self.port) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() # Return False to re-raise any potential exceptions return False def close(self): """ Close all pooled connections and disable the pool. """ pass # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK} class HTTPConnectionPool(ConnectionPool, RequestMethods): """ Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`httplib.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`httplib.HTTPConnection`. :param strict: Causes BadStatusLine to be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1 status line, passed into :class:`httplib.HTTPConnection`. .. note:: Only works in Python 2. This parameter is ignored in Python 3. :param timeout: Socket timeout in seconds for each individual connection. This can be a float or integer, which sets the timeout for the HTTP request, or an instance of :class:`urllib3.util.Timeout` which gives you more fine-grained control over request timeouts. After the constructor has been parsed, this is always a `urllib3.util.Timeout` object. :param maxsize: Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If ``block`` is set to False, more connections will be created but they will not be saved once they've been used. :param block: If set to True, no more than ``maxsize`` connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param retries: Retry configuration to use by default with requests in this pool. :param _proxy: Parsed proxy URL, should not be used directly, instead, see :class:`urllib3.connectionpool.ProxyManager`" :param _proxy_headers: A dictionary with proxy headers, should not be used directly, instead, see :class:`urllib3.connectionpool.ProxyManager`" :param \\**conn_kw: Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, :class:`urllib3.connection.HTTPSConnection` instances. """ scheme = "http" ConnectionCls = HTTPConnection ResponseCls = HTTPResponse def __init__( self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, **conn_kw ): ConnectionPool.__init__(self, host, port) RequestMethods.__init__(self, headers) self.strict = strict if not isinstance(timeout, Timeout): timeout = Timeout.from_float(timeout) if retries is None: retries = Retry.DEFAULT self.timeout = timeout self.retries = retries self.pool = self.QueueCls(maxsize) self.block = block self.proxy = _proxy self.proxy_headers = _proxy_headers or {} # Fill the queue up so that doing get() on it will block properly for _ in xrange(maxsize): self.pool.put(None) # These are mostly for testing and debugging purposes. self.num_connections = 0 self.num_requests = 0 self.conn_kw = conn_kw if self.proxy: # Enable Nagle's algorithm for proxies, to avoid packet fragmentation. # We cannot know if the user has added default socket options, so we cannot replace the # list. self.conn_kw.setdefault("socket_options", []) def _new_conn(self): """ Return a fresh :class:`HTTPConnection`. """ self.num_connections += 1 log.debug( "Starting new HTTP connection (%d): %s:%s", self.num_connections, self.host, self.port or "80", ) conn = self.ConnectionCls( host=self.host, port=self.port, timeout=self.timeout.connect_timeout, strict=self.strict, **self.conn_kw ) return conn def _get_conn(self, timeout=None): """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. """ conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: # self.pool is None raise ClosedPoolError(self, "Pool is closed.") except queue.Empty: if self.block: raise EmptyPoolError( self, "Pool reached maximum size and no more connections are allowed.", ) pass # Oh well, we'll create a new connection then # If this is a persistent connection, check if it got disconnected if conn and is_connection_dropped(conn): log.debug("Resetting dropped connection: %s", self.host) conn.close() if getattr(conn, "auto_open", 1) == 0: # This is a proxied connection that has been mutated by # httplib._tunnel() and cannot be reused (since it would # attempt to bypass the proxy) conn = None return conn or self._new_conn() def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. """ try: self.pool.put(conn, block=False) return # Everything is dandy, done. except AttributeError: # self.pool is None. pass except queue.Full: # This should never happen if self.block == True log.warning("Connection pool is full, discarding connection: %s", self.host) # Connection never got put back into the pool, close it. if conn: conn.close() def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ pass def _prepare_proxy(self, conn): # Nothing to do for HTTP connections. pass def _get_timeout(self, timeout): """ Helper that always returns a :class:`urllib3.util.Timeout` """ if timeout is _Default: return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: # User passed us an int/float. This is for backwards compatibility, # can be removed later return Timeout.from_float(timeout) def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) # See the above comment about EAGAIN in Python 3. In Python 2 we have # to specifically catch it and throw the timeout error if hasattr(err, "errno") and err.errno in _blocking_errnos: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) # Catch possible read timeouts thrown as SSL errors. If not the # case, rethrow the original. We need to do this because of: # http://bugs.python.org/issue10272 if "timed out" in str(err) or "did not complete (read)" in str( err ): # Python < 2.7.4 raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % timeout_value ) def _make_request( self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw ): """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. """ self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout # Trigger any extra validation we need to do. try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) raise # conn.request() calls httplib.*.request, not the method in # urllib3.request. It also calls makefile (recv) on the socket. if chunked: conn.request_chunked(method, url, **httplib_request_kw) else: conn.request(method, url, **httplib_request_kw) # Reset the timeout for the recv() on the socket read_timeout = timeout_obj.read_timeout # App Engine doesn't have a sock attr if getattr(conn, "sock", None): # In Python 3 socket.py will catch EAGAIN and return None when you # try and read into the file pointer created by http.client, which # instead raises a BadStatusLine exception. Instead of catching # the exception and assuming all BadStatusLine exceptions are read # timeouts, check for a zero timeout before making the request. if read_timeout == 0: raise ReadTimeoutError( self, url, "Read timed out. (read timeout=%s)" % read_timeout ) if read_timeout is Timeout.DEFAULT_TIMEOUT: conn.sock.settimeout(socket.getdefaulttimeout()) else: # None or a value conn.sock.settimeout(read_timeout) # Receive the response from the server try: try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 3 try: httplib_response = conn.getresponse() except BaseException as e: # Remove the TypeError from the exception chain in # Python 3 (including for exceptions like SystemExit). # Otherwise it looks like a bug in the code. six.raise_from(e, None) except (SocketTimeout, BaseSSLError, SocketError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise # AppEngine doesn't have a version attr. http_version = getattr(conn, "_http_vsn_str", "HTTP/?") log.debug( '%s://%s:%s "%s %s %s" %s %s', self.scheme, self.host, self.port, method, url, http_version, httplib_response.status, httplib_response.length, ) try: assert_header_parsing(httplib_response.msg) except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3 log.warning( "Failed to parse headers (url=%s): %s", self._absolute_url(url), hpe, exc_info=True, ) return httplib_response def _absolute_url(self, path): return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url def close(self): """ Close all pooled connections and disable the pool. """ if self.pool is None: return # Disable access to the pool old_pool, self.pool = self.pool, None try: while True: conn = old_pool.get(block=False) if conn: conn.close() except queue.Empty: pass # Done. def is_same_host(self, url): """ Check if the given ``url`` is a member of the same host as this connection pool. """ if url.startswith("/"): return True # TODO: Add optional support for socket.gethostbyname checking. scheme, host, port = get_host(url) if host is not None: host = _normalize_host(host, scheme=scheme) # Use explicit default port for comparison when none is given if self.port and not port: port = port_by_scheme.get(scheme) elif not self.port and port == port_by_scheme.get(scheme): port = None return (scheme, host, port) == (self.scheme, self.host, self.port) def urlopen( self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw ): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. :param \\**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ if headers is None: headers = self.headers if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if release_conn is None: release_conn = response_kw.get("preload_content", True) # Check host if assert_same_host and not self.is_same_host(url): raise HostChangedError(self, url, retries) # Ensure that the URL we're connecting to is properly encoded if url.startswith("/"): url = six.ensure_str(_encode_target(url)) else: url = six.ensure_str(parse_url(url).url) conn = None # Track whether `conn` needs to be released before # returning/raising/recursing. Update this variable if necessary, and # leave `release_conn` constant throughout the function. That way, if # the function recurses, the original value of `release_conn` will be # passed down into the recursive call, and its value will be respected. # # See issue #651 [1] for details. # # [1] release_this_conn = release_conn # Merge the proxy headers. Only do this in HTTP. We have to copy the # headers dict so we can safely change it without those changes being # reflected in anyone else's copy. if self.scheme == "http": headers = headers.copy() headers.update(self.proxy_headers) # Must keep the exception bound to a separate variable or else Python 3 # complains about UnboundLocalError. err = None # Keep track of whether we cleanly exited the except block. This # ensures we do proper cleanup in finally. clean_exit = False # Rewind body position, if needed. Record current position # for future rewinds in the event of a redirect/retry. body_pos = set_file_position(body, body_pos) try: # Request a connection from the queue. timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) conn.timeout = timeout_obj.connect_timeout is_new_proxy_conn = self.proxy is not None and not getattr( conn, "sock", None ) if is_new_proxy_conn: self._prepare_proxy(conn) # Make the request on the httplib connection object. httplib_response = self._make_request( conn, method, url, timeout=timeout_obj, body=body, headers=headers, chunked=chunked, ) # If we're going to release the connection in ``finally:``, then # the response doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = conn if not release_conn else None # Pass method to Response for length checking response_kw["request_method"] = method # Import httplib's response into our own wrapper object response = self.ResponseCls.from_httplib( httplib_response, pool=self, connection=response_conn, retries=retries, **response_kw ) # Everything went great! clean_exit = True except queue.Empty: # Timed out by queue. raise EmptyPoolError(self, "No pool connections are available.") except ( TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError, CertificateError, ) as e: # Discard the connection for these exceptions. It will be # replaced during the next _get_conn() call. clean_exit = False if isinstance(e, (BaseSSLError, CertificateError)): e = SSLError(e) elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy: e = ProxyError("Cannot connect to proxy.", e) elif isinstance(e, (SocketError, HTTPException)): e = ProtocolError("Connection aborted.", e) retries = retries.increment( method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] ) retries.sleep() # Keep track of the error for the retry warning. err = e finally: if not clean_exit: # We hit some kind of exception, handled or otherwise. We need # to throw the connection away unless explicitly told not to. # Close the connection, set the variable to None, and make sure # we put the None back in the pool to avoid leaking it. conn = conn and conn.close() release_this_conn = True if release_this_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warning( "Retrying (%r) after connection broken by '%r': %s", retries, err, url ) return self.urlopen( method, url, body, headers, retries, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, **response_kw ) def drain_and_release_conn(response): try: # discard any remaining response body, the connection will be # released back to the pool once the entire response is read response.read() except ( TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError, ): pass # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: method = "GET" try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: # Drain and release the connection for this response, since # we're not returning it to be released manually. drain_and_release_conn(response) raise return response # drain and return the connection to the pool before recursing drain_and_release_conn(response) retries.sleep_for_retry(response) log.debug("Redirecting %s -> %s", url, redirect_location) return self.urlopen( method, redirect_location, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, **response_kw ) # Check if we should retry the HTTP response. has_retry_after = bool(response.getheader("Retry-After")) if retries.is_retry(method, response.status, has_retry_after): try: retries = retries.increment(method, url, response=response, _pool=self) except MaxRetryError: if retries.raise_on_status: # Drain and release the connection for this response, since # we're not returning it to be released manually. drain_and_release_conn(response) raise return response # drain and return the connection to the pool before recursing drain_and_release_conn(response) retries.sleep(response) log.debug("Retry: %s", url) return self.urlopen( method, url, body, headers, retries=retries, redirect=redirect, assert_same_host=assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, chunked=chunked, body_pos=body_pos, **response_kw ) return response class HTTPSConnectionPool(HTTPConnectionPool): """ Same as :class:`.HTTPConnectionPool`, but HTTPS. When Python is compiled with the :mod:`ssl` module, then :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates, instead of :class:`.HTTPSConnection`. :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``, ``assert_hostname`` and ``host`` in this order to verify connections. If ``assert_hostname`` is False, no verification is done. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl` is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket into an SSL socket. """ scheme = "https" ConnectionCls = HTTPSConnection def __init__( self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, ssl_version=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, **conn_kw ): HTTPConnectionPool.__init__( self, host, port, strict, timeout, maxsize, block, headers, retries, _proxy, _proxy_headers, **conn_kw ) self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.key_password = key_password self.ca_certs = ca_certs self.ca_cert_dir = ca_cert_dir self.ssl_version = ssl_version self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint def _prepare_conn(self, conn): """ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used. """ if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert( key_file=self.key_file, key_password=self.key_password, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, assert_hostname=self.assert_hostname, assert_fingerprint=self.assert_fingerprint, ) conn.ssl_version = self.ssl_version return conn def _prepare_proxy(self, conn): """ Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port. """ conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers) conn.connect() def _new_conn(self): """ Return a fresh :class:`httplib.HTTPSConnection`. """ self.num_connections += 1 log.debug( "Starting new HTTPS connection (%d): %s:%s", self.num_connections, self.host, self.port or "443", ) if not self.ConnectionCls or self.ConnectionCls is DummyConnection: raise SSLError( "Can't connect to HTTPS URL because the SSL module is not available." ) actual_host = self.host actual_port = self.port if self.proxy is not None: actual_host = self.proxy.host actual_port = self.proxy.port conn = self.ConnectionCls( host=actual_host, port=actual_port, timeout=self.timeout.connect_timeout, strict=self.strict, cert_file=self.cert_file, key_file=self.key_file, key_password=self.key_password, **self.conn_kw ) return self._prepare_conn(conn) def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ super(HTTPSConnectionPool, self)._validate_conn(conn) # Force connect early to allow us to validate the connection. if not getattr(conn, "sock", None): # AppEngine might not have `.sock` conn.connect() if not conn.is_verified: warnings.warn( ( "Unverified HTTPS request is being made to host '%s'. " "Adding certificate verification is strongly advised. See: " "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" "#ssl-warnings" % conn.host ), InsecureRequestWarning, ) def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :param \\**kw: Passes additional parameters to the constructor of the appropriate :class:`.ConnectionPool`. Useful for specifying things like timeout, maxsize, headers, etc. Example:: >>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') """ scheme, host, port = get_host(url) port = port or port_by_scheme.get(scheme, 80) if scheme == "https": return HTTPSConnectionPool(host, port=port, **kw) else: return HTTPConnectionPool(host, port=port, **kw) def _normalize_host(host, scheme): """ Normalize hosts for comparisons and use with sockets. """ host = normalize_host(host, scheme) # httplib doesn't like it when we include brackets in IPv6 addresses # Specifically, if we include brackets but also pass the port then # httplib crazily doubles up the square brackets on the Host header. # Instead, we need to make sure we never pass ``None`` as the port. # However, for backward compatibility reasons we can't actually # *assert* that. See http://bugs.python.org/issue28539 if host.startswith("[") and host.endswith("]"): host = host[1:-1] return host ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/contrib/0000755000175000017500000000000000000000000021707 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/__init__.py0000644000175000017500000000000000000000000024006 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/_appengine_environ.py0000644000175000017500000000167500000000000026137 0ustar00sethmlarsonsethmlarson00000000000000""" This module provides means to detect the App Engine environment. """ import os def is_appengine(): return is_local_appengine() or is_prod_appengine() def is_appengine_sandbox(): """Reports if the app is running in the first generation sandbox. The second generation runtimes are technically still in a sandbox, but it is much less restrictive, so generally you shouldn't need to check for it. see https://cloud.google.com/appengine/docs/standard/runtimes """ return is_appengine() and os.environ["APPENGINE_RUNTIME"] == "python27" def is_local_appengine(): return "APPENGINE_RUNTIME" in os.environ and os.environ.get( "SERVER_SOFTWARE", "" ).startswith("Development/") def is_prod_appengine(): return "APPENGINE_RUNTIME" in os.environ and os.environ.get( "SERVER_SOFTWARE", "" ).startswith("Google App Engine/") def is_prod_appengine_mvms(): """Deprecated.""" return False ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/contrib/_securetransport/0000755000175000017500000000000000000000000025311 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/_securetransport/__init__.py0000644000175000017500000000000000000000000027410 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/_securetransport/bindings.py0000644000175000017500000004076600000000000027475 0ustar00sethmlarsonsethmlarson00000000000000""" This module uses ctypes to bind a whole bunch of functions and constants from SecureTransport. The goal here is to provide the low-level API to SecureTransport. These are essentially the C-level functions and constants, and they're pretty gross to work with. This code is a bastardised version of the code found in Will Bond's oscrypto library. An enormous debt is owed to him for blazing this trail for us. For that reason, this code should be considered to be covered both by urllib3's license and by oscrypto's: Copyright (c) 2015-2016 Will Bond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import platform from ctypes.util import find_library from ctypes import ( c_void_p, c_int32, c_char_p, c_size_t, c_byte, c_uint32, c_ulong, c_long, c_bool, ) from ctypes import CDLL, POINTER, CFUNCTYPE security_path = find_library("Security") if not security_path: raise ImportError("The library Security could not be found") core_foundation_path = find_library("CoreFoundation") if not core_foundation_path: raise ImportError("The library CoreFoundation could not be found") version = platform.mac_ver()[0] version_info = tuple(map(int, version.split("."))) if version_info < (10, 8): raise OSError( "Only OS X 10.8 and newer are supported, not %s.%s" % (version_info[0], version_info[1]) ) Security = CDLL(security_path, use_errno=True) CoreFoundation = CDLL(core_foundation_path, use_errno=True) Boolean = c_bool CFIndex = c_long CFStringEncoding = c_uint32 CFData = c_void_p CFString = c_void_p CFArray = c_void_p CFMutableArray = c_void_p CFDictionary = c_void_p CFError = c_void_p CFType = c_void_p CFTypeID = c_ulong CFTypeRef = POINTER(CFType) CFAllocatorRef = c_void_p OSStatus = c_int32 CFDataRef = POINTER(CFData) CFStringRef = POINTER(CFString) CFArrayRef = POINTER(CFArray) CFMutableArrayRef = POINTER(CFMutableArray) CFDictionaryRef = POINTER(CFDictionary) CFArrayCallBacks = c_void_p CFDictionaryKeyCallBacks = c_void_p CFDictionaryValueCallBacks = c_void_p SecCertificateRef = POINTER(c_void_p) SecExternalFormat = c_uint32 SecExternalItemType = c_uint32 SecIdentityRef = POINTER(c_void_p) SecItemImportExportFlags = c_uint32 SecItemImportExportKeyParameters = c_void_p SecKeychainRef = POINTER(c_void_p) SSLProtocol = c_uint32 SSLCipherSuite = c_uint32 SSLContextRef = POINTER(c_void_p) SecTrustRef = POINTER(c_void_p) SSLConnectionRef = c_uint32 SecTrustResultType = c_uint32 SecTrustOptionFlags = c_uint32 SSLProtocolSide = c_uint32 SSLConnectionType = c_uint32 SSLSessionOption = c_uint32 try: Security.SecItemImport.argtypes = [ CFDataRef, CFStringRef, POINTER(SecExternalFormat), POINTER(SecExternalItemType), SecItemImportExportFlags, POINTER(SecItemImportExportKeyParameters), SecKeychainRef, POINTER(CFArrayRef), ] Security.SecItemImport.restype = OSStatus Security.SecCertificateGetTypeID.argtypes = [] Security.SecCertificateGetTypeID.restype = CFTypeID Security.SecIdentityGetTypeID.argtypes = [] Security.SecIdentityGetTypeID.restype = CFTypeID Security.SecKeyGetTypeID.argtypes = [] Security.SecKeyGetTypeID.restype = CFTypeID Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef] Security.SecCertificateCreateWithData.restype = SecCertificateRef Security.SecCertificateCopyData.argtypes = [SecCertificateRef] Security.SecCertificateCopyData.restype = CFDataRef Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p] Security.SecCopyErrorMessageString.restype = CFStringRef Security.SecIdentityCreateWithCertificate.argtypes = [ CFTypeRef, SecCertificateRef, POINTER(SecIdentityRef), ] Security.SecIdentityCreateWithCertificate.restype = OSStatus Security.SecKeychainCreate.argtypes = [ c_char_p, c_uint32, c_void_p, Boolean, c_void_p, POINTER(SecKeychainRef), ] Security.SecKeychainCreate.restype = OSStatus Security.SecKeychainDelete.argtypes = [SecKeychainRef] Security.SecKeychainDelete.restype = OSStatus Security.SecPKCS12Import.argtypes = [ CFDataRef, CFDictionaryRef, POINTER(CFArrayRef), ] Security.SecPKCS12Import.restype = OSStatus SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t)) SSLWriteFunc = CFUNCTYPE( OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t) ) Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc] Security.SSLSetIOFuncs.restype = OSStatus Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t] Security.SSLSetPeerID.restype = OSStatus Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef] Security.SSLSetCertificate.restype = OSStatus Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean] Security.SSLSetCertificateAuthorities.restype = OSStatus Security.SSLSetConnection.argtypes = [SSLContextRef, SSLConnectionRef] Security.SSLSetConnection.restype = OSStatus Security.SSLSetPeerDomainName.argtypes = [SSLContextRef, c_char_p, c_size_t] Security.SSLSetPeerDomainName.restype = OSStatus Security.SSLHandshake.argtypes = [SSLContextRef] Security.SSLHandshake.restype = OSStatus Security.SSLRead.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)] Security.SSLRead.restype = OSStatus Security.SSLWrite.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)] Security.SSLWrite.restype = OSStatus Security.SSLClose.argtypes = [SSLContextRef] Security.SSLClose.restype = OSStatus Security.SSLGetNumberSupportedCiphers.argtypes = [SSLContextRef, POINTER(c_size_t)] Security.SSLGetNumberSupportedCiphers.restype = OSStatus Security.SSLGetSupportedCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), POINTER(c_size_t), ] Security.SSLGetSupportedCiphers.restype = OSStatus Security.SSLSetEnabledCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), c_size_t, ] Security.SSLSetEnabledCiphers.restype = OSStatus Security.SSLGetNumberEnabledCiphers.argtype = [SSLContextRef, POINTER(c_size_t)] Security.SSLGetNumberEnabledCiphers.restype = OSStatus Security.SSLGetEnabledCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), POINTER(c_size_t), ] Security.SSLGetEnabledCiphers.restype = OSStatus Security.SSLGetNegotiatedCipher.argtypes = [SSLContextRef, POINTER(SSLCipherSuite)] Security.SSLGetNegotiatedCipher.restype = OSStatus Security.SSLGetNegotiatedProtocolVersion.argtypes = [ SSLContextRef, POINTER(SSLProtocol), ] Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus Security.SSLCopyPeerTrust.argtypes = [SSLContextRef, POINTER(SecTrustRef)] Security.SSLCopyPeerTrust.restype = OSStatus Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef] Security.SecTrustSetAnchorCertificates.restype = OSStatus Security.SecTrustSetAnchorCertificatesOnly.argstypes = [SecTrustRef, Boolean] Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)] Security.SecTrustEvaluate.restype = OSStatus Security.SecTrustGetCertificateCount.argtypes = [SecTrustRef] Security.SecTrustGetCertificateCount.restype = CFIndex Security.SecTrustGetCertificateAtIndex.argtypes = [SecTrustRef, CFIndex] Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef Security.SSLCreateContext.argtypes = [ CFAllocatorRef, SSLProtocolSide, SSLConnectionType, ] Security.SSLCreateContext.restype = SSLContextRef Security.SSLSetSessionOption.argtypes = [SSLContextRef, SSLSessionOption, Boolean] Security.SSLSetSessionOption.restype = OSStatus Security.SSLSetProtocolVersionMin.argtypes = [SSLContextRef, SSLProtocol] Security.SSLSetProtocolVersionMin.restype = OSStatus Security.SSLSetProtocolVersionMax.argtypes = [SSLContextRef, SSLProtocol] Security.SSLSetProtocolVersionMax.restype = OSStatus Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p] Security.SecCopyErrorMessageString.restype = CFStringRef Security.SSLReadFunc = SSLReadFunc Security.SSLWriteFunc = SSLWriteFunc Security.SSLContextRef = SSLContextRef Security.SSLProtocol = SSLProtocol Security.SSLCipherSuite = SSLCipherSuite Security.SecIdentityRef = SecIdentityRef Security.SecKeychainRef = SecKeychainRef Security.SecTrustRef = SecTrustRef Security.SecTrustResultType = SecTrustResultType Security.SecExternalFormat = SecExternalFormat Security.OSStatus = OSStatus Security.kSecImportExportPassphrase = CFStringRef.in_dll( Security, "kSecImportExportPassphrase" ) Security.kSecImportItemIdentity = CFStringRef.in_dll( Security, "kSecImportItemIdentity" ) # CoreFoundation time! CoreFoundation.CFRetain.argtypes = [CFTypeRef] CoreFoundation.CFRetain.restype = CFTypeRef CoreFoundation.CFRelease.argtypes = [CFTypeRef] CoreFoundation.CFRelease.restype = None CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef] CoreFoundation.CFGetTypeID.restype = CFTypeID CoreFoundation.CFStringCreateWithCString.argtypes = [ CFAllocatorRef, c_char_p, CFStringEncoding, ] CoreFoundation.CFStringCreateWithCString.restype = CFStringRef CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding] CoreFoundation.CFStringGetCStringPtr.restype = c_char_p CoreFoundation.CFStringGetCString.argtypes = [ CFStringRef, c_char_p, CFIndex, CFStringEncoding, ] CoreFoundation.CFStringGetCString.restype = c_bool CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex] CoreFoundation.CFDataCreate.restype = CFDataRef CoreFoundation.CFDataGetLength.argtypes = [CFDataRef] CoreFoundation.CFDataGetLength.restype = CFIndex CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef] CoreFoundation.CFDataGetBytePtr.restype = c_void_p CoreFoundation.CFDictionaryCreate.argtypes = [ CFAllocatorRef, POINTER(CFTypeRef), POINTER(CFTypeRef), CFIndex, CFDictionaryKeyCallBacks, CFDictionaryValueCallBacks, ] CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef CoreFoundation.CFDictionaryGetValue.argtypes = [CFDictionaryRef, CFTypeRef] CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef CoreFoundation.CFArrayCreate.argtypes = [ CFAllocatorRef, POINTER(CFTypeRef), CFIndex, CFArrayCallBacks, ] CoreFoundation.CFArrayCreate.restype = CFArrayRef CoreFoundation.CFArrayCreateMutable.argtypes = [ CFAllocatorRef, CFIndex, CFArrayCallBacks, ] CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p] CoreFoundation.CFArrayAppendValue.restype = None CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef] CoreFoundation.CFArrayGetCount.restype = CFIndex CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex] CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( CoreFoundation, "kCFAllocatorDefault" ) CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( CoreFoundation, "kCFTypeArrayCallBacks" ) CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll( CoreFoundation, "kCFTypeDictionaryKeyCallBacks" ) CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll( CoreFoundation, "kCFTypeDictionaryValueCallBacks" ) CoreFoundation.CFTypeRef = CFTypeRef CoreFoundation.CFArrayRef = CFArrayRef CoreFoundation.CFStringRef = CFStringRef CoreFoundation.CFDictionaryRef = CFDictionaryRef except (AttributeError): raise ImportError("Error initializing ctypes") class CFConst(object): """ A class object that acts as essentially a namespace for CoreFoundation constants. """ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100) class SecurityConst(object): """ A class object that acts as essentially a namespace for Security constants. """ kSSLSessionOptionBreakOnServerAuth = 0 kSSLProtocol2 = 1 kSSLProtocol3 = 2 kTLSProtocol1 = 4 kTLSProtocol11 = 7 kTLSProtocol12 = 8 # SecureTransport does not support TLS 1.3 even if there's a constant for it kTLSProtocol13 = 10 kTLSProtocolMaxSupported = 999 kSSLClientSide = 1 kSSLStreamType = 0 kSecFormatPEMSequence = 10 kSecTrustResultInvalid = 0 kSecTrustResultProceed = 1 # This gap is present on purpose: this was kSecTrustResultConfirm, which # is deprecated. kSecTrustResultDeny = 3 kSecTrustResultUnspecified = 4 kSecTrustResultRecoverableTrustFailure = 5 kSecTrustResultFatalTrustFailure = 6 kSecTrustResultOtherError = 7 errSSLProtocol = -9800 errSSLWouldBlock = -9803 errSSLClosedGraceful = -9805 errSSLClosedNoNotify = -9816 errSSLClosedAbort = -9806 errSSLXCertChainInvalid = -9807 errSSLCrypto = -9809 errSSLInternal = -9810 errSSLCertExpired = -9814 errSSLCertNotYetValid = -9815 errSSLUnknownRootCert = -9812 errSSLNoRootCert = -9813 errSSLHostNameMismatch = -9843 errSSLPeerHandshakeFail = -9824 errSSLPeerUserCancelled = -9839 errSSLWeakPeerEphemeralDHKey = -9850 errSSLServerAuthCompleted = -9841 errSSLRecordOverflow = -9847 errSecVerifyFailed = -67808 errSecNoTrustSettings = -25263 errSecItemNotFound = -25300 errSecInvalidTrustSettings = -25262 # Cipher suites. We only pick the ones our default cipher string allows. # Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067 TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033 TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035 TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F TLS_AES_128_GCM_SHA256 = 0x1301 TLS_AES_256_GCM_SHA384 = 0x1302 TLS_AES_128_CCM_8_SHA256 = 0x1305 TLS_AES_128_CCM_SHA256 = 0x1304 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/_securetransport/low_level.py0000644000175000017500000002726400000000000027666 0ustar00sethmlarsonsethmlarson00000000000000""" Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. """ import base64 import ctypes import itertools import re import os import ssl import tempfile from .bindings import Security, CoreFoundation, CFConst # This regular expression is used to grab PEM data out of a PEM bundle. _PEM_CERTS_RE = re.compile( b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL ) def _cf_data_from_bytes(bytestring): """ Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. """ return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) ) def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] for t in tuples) values = (t[1] for t in tuples) cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, ) def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError("Error copying C string from CFStringRef") string = buffer.value if string is not None: string = string.decode("utf-8") return string def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == u"": output = u"OSStatus %s" % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output) def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # Normalize the PEM bundle's line endings. pem_bundle = pem_bundle.replace(b"\r\n", b"\n") der_certs = [ base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle) ] if not der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array def _is_cert(item): """ Returns True if a given CFTypeRef is a certificate. """ expected = Security.SecCertificateGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _is_identity(item): """ Returns True if a given CFTypeRef is an identity. """ expected = Security.SecIdentityGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # Unfortunately, SecKeychainCreate requires a path to a keychain. This # means we cannot use mkstemp to use a generic temporary file. Instead, # we're going to create a temporary directory and a filename to use there. # This filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode("utf-8") password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode("utf-8") # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, "rb") as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array), # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates) def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # Ok, the strategy. # # This relies on knowing that macOS will not give you a SecIdentityRef # unless you have imported a key into a keychain. This is a somewhat # artificial limitation of macOS (for example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file(keychain, file_path) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/appengine.py0000644000175000017500000002540200000000000024232 0ustar00sethmlarsonsethmlarson00000000000000""" This module provides a pool manager that uses Google App Engine's `URLFetch Service `_. Example usage:: from urllib3 import PoolManager from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox if is_appengine_sandbox(): # AppEngineManager uses AppEngine's URLFetch API behind the scenes http = AppEngineManager() else: # PoolManager uses a socket-level API behind the scenes http = PoolManager() r = http.request('GET', 'https://google.com/') There are `limitations `_ to the URLFetch service and it may not be the best choice for your application. There are three options for using urllib3 on Google App Engine: 1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is cost-effective in many circumstances as long as your usage is within the limitations. 2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets. Sockets also have `limitations and restrictions `_ and have a lower free quota than URLFetch. To use sockets, be sure to specify the following in your ``app.yaml``:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' 3. If you are using `App Engine Flexible `_, you can use the standard :class:`PoolManager` without any configuration or special environment variables. """ from __future__ import absolute_import import io import logging import warnings from ..packages.six.moves.urllib.parse import urljoin from ..exceptions import ( HTTPError, HTTPWarning, MaxRetryError, ProtocolError, TimeoutError, SSLError, ) from ..request import RequestMethods from ..response import HTTPResponse from ..util.timeout import Timeout from ..util.retry import Retry from . import _appengine_environ try: from google.appengine.api import urlfetch except ImportError: urlfetch = None log = logging.getLogger(__name__) class AppEnginePlatformWarning(HTTPWarning): pass class AppEnginePlatformError(HTTPError): pass class AppEngineManager(RequestMethods): """ Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here `_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabtyes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. """ def __init__( self, headers=None, retries=None, validate_certificate=True, urlfetch_retries=True, ): if not urlfetch: raise AppEnginePlatformError( "URLFetch is not available in this environment." ) warnings.warn( "urllib3 is using URLFetch on Google App Engine sandbox instead " "of sockets. To use sockets directly instead of URLFetch see " "https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.", AppEnginePlatformWarning, ) RequestMethods.__init__(self, headers) self.validate_certificate = validate_certificate self.urlfetch_retries = urlfetch_retries self.retries = retries or Retry.DEFAULT def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # Return False to re-raise any potential exceptions return False def urlopen( self, method, url, body=None, headers=None, retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT, **response_kw ): retries = self._get_retries(retries, redirect) try: follow_redirects = redirect and retries.redirect != 0 and retries.total response = urlfetch.fetch( url, payload=body, method=method, headers=headers or {}, allow_truncated=False, follow_redirects=self.urlfetch_retries and follow_redirects, deadline=self._get_absolute_timeout(timeout), validate_certificate=self.validate_certificate, ) except urlfetch.DeadlineExceededError as e: raise TimeoutError(self, e) except urlfetch.InvalidURLError as e: if "too large" in str(e): raise AppEnginePlatformError( "URLFetch request too large, URLFetch only " "supports requests up to 10mb in size.", e, ) raise ProtocolError(e) except urlfetch.DownloadError as e: if "Too many redirects" in str(e): raise MaxRetryError(self, url, reason=e) raise ProtocolError(e) except urlfetch.ResponseTooLargeError as e: raise AppEnginePlatformError( "URLFetch response too large, URLFetch only supports" "responses up to 32mb in size.", e, ) except urlfetch.SSLCertificateError as e: raise SSLError(e) except urlfetch.InvalidMethodError as e: raise AppEnginePlatformError( "URLFetch does not support method: %s" % method, e ) http_response = self._urlfetch_response_to_http_response( response, retries=retries, **response_kw ) # Handle redirect? redirect_location = redirect and http_response.get_redirect_location() if redirect_location: # Check for redirect response if self.urlfetch_retries and retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") else: if http_response.status == 303: method = "GET" try: retries = retries.increment( method, url, response=http_response, _pool=self ) except MaxRetryError: if retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") return http_response retries.sleep_for_retry(http_response) log.debug("Redirecting %s -> %s", url, redirect_location) redirect_url = urljoin(url, redirect_location) return self.urlopen( method, redirect_url, body, headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw ) # Check if we should retry the HTTP response. has_retry_after = bool(http_response.getheader("Retry-After")) if retries.is_retry(method, http_response.status, has_retry_after): retries = retries.increment(method, url, response=http_response, _pool=self) log.debug("Retry: %s", url) retries.sleep(http_response) return self.urlopen( method, url, body=body, headers=headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw ) return http_response def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw): if is_prod_appengine(): # Production GAE handles deflate encoding automatically, but does # not remove the encoding header. content_encoding = urlfetch_resp.headers.get("content-encoding") if content_encoding == "deflate": del urlfetch_resp.headers["content-encoding"] transfer_encoding = urlfetch_resp.headers.get("transfer-encoding") # We have a full response's content, # so let's make sure we don't report ourselves as chunked data. if transfer_encoding == "chunked": encodings = transfer_encoding.split(",") encodings.remove("chunked") urlfetch_resp.headers["transfer-encoding"] = ",".join(encodings) original_response = HTTPResponse( # In order for decoding to work, we must present the content as # a file-like object. body=io.BytesIO(urlfetch_resp.content), msg=urlfetch_resp.header_msg, headers=urlfetch_resp.headers, status=urlfetch_resp.status_code, **response_kw ) return HTTPResponse( body=io.BytesIO(urlfetch_resp.content), headers=urlfetch_resp.headers, status=urlfetch_resp.status_code, original_response=original_response, **response_kw ) def _get_absolute_timeout(self, timeout): if timeout is Timeout.DEFAULT_TIMEOUT: return None # Defer to URLFetch's default. if isinstance(timeout, Timeout): if timeout._read is not None or timeout._connect is not None: warnings.warn( "URLFetch does not support granular timeout settings, " "reverting to total or default URLFetch timeout.", AppEnginePlatformWarning, ) return timeout.total return timeout def _get_retries(self, retries, redirect): if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if retries.connect or retries.read or retries.redirect: warnings.warn( "URLFetch only supports total retries and does not " "recognize connect, read, or redirect retry parameters.", AppEnginePlatformWarning, ) return retries # Alias methods from _appengine_environ to maintain public API interface. is_appengine = _appengine_environ.is_appengine is_appengine_sandbox = _appengine_environ.is_appengine_sandbox is_local_appengine = _appengine_environ.is_local_appengine is_prod_appengine = _appengine_environ.is_prod_appengine is_prod_appengine_mvms = _appengine_environ.is_prod_appengine_mvms ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/ntlmpool.py0000644000175000017500000001010000000000000024115 0ustar00sethmlarsonsethmlarson00000000000000""" NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ from __future__ import absolute_import from logging import getLogger from ntlm import ntlm from .. import HTTPSConnectionPool from ..packages.six.moves.http_client import HTTPSConnection log = getLogger(__name__) class NTLMConnectionPool(HTTPSConnectionPool): """ Implements an NTLM authentication version of an urllib3 connection pool """ scheme = "https" def __init__(self, user, pw, authurl, *args, **kwargs): """ authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\\username format. pw is the password for the user. """ super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split("\\", 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw def _new_conn(self): # Performs the NTLM handshake that secures the connection. The socket # must be kept open while requests are performed. self.num_connections += 1 log.debug( "Starting NTLM HTTPS connection no. %d: https://%s%s", self.num_connections, self.host, self.authurl, ) headers = {"Connection": "Keep-Alive"} req_header = "Authorization" resp_header = "www-authenticate" conn = HTTPSConnection(host=self.host, port=self.port) # Send negotiation message headers[req_header] = "NTLM %s" % ntlm.create_NTLM_NEGOTIATE_MESSAGE( self.rawuser ) log.debug("Request headers: %s", headers) conn.request("GET", self.authurl, None, headers) res = conn.getresponse() reshdr = dict(res.getheaders()) log.debug("Response status: %s %s", res.status, res.reason) log.debug("Response headers: %s", reshdr) log.debug("Response data: %s [...]", res.read(100)) # Remove the reference to the socket, so that it can not be closed by # the response object (we want to keep the socket open) res.fp = None # Server should respond with a challenge message auth_header_values = reshdr[resp_header].split(", ") auth_header_value = None for s in auth_header_values: if s[:5] == "NTLM ": auth_header_value = s[5:] if auth_header_value is None: raise Exception( "Unexpected %s response header: %s" % (resp_header, reshdr[resp_header]) ) # Send authentication message ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE( auth_header_value ) auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE( ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags ) headers[req_header] = "NTLM %s" % auth_msg log.debug("Request headers: %s", headers) conn.request("GET", self.authurl, None, headers) res = conn.getresponse() log.debug("Response status: %s %s", res.status, res.reason) log.debug("Response headers: %s", dict(res.getheaders())) log.debug("Response data: %s [...]", res.read()[:100]) if res.status != 200: if res.status == 401: raise Exception("Server rejected request: wrong username or password") raise Exception("Wrong server response: %s %s" % (res.status, res.reason)) res.fp = None log.debug("Connection established") return conn def urlopen( self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, ): if headers is None: headers = {} headers["Connection"] = "Keep-Alive" return super(NTLMConnectionPool, self).urlopen( method, url, body, headers, retries, redirect, assert_same_host ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/pyopenssl.py0000644000175000017500000004004700000000000024322 0ustar00sethmlarsonsethmlarson00000000000000""" SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) """ from __future__ import absolute_import import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from cryptography.hazmat.backends.openssl.x509 import _Certificate try: from cryptography.x509 import UnsupportedExtension except ImportError: # UnsupportedExtension is gone in cryptography >= 2.1.0 class UnsupportedExtension(Exception): pass from socket import timeout, error as SocketError from io import BytesIO try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile import logging import ssl from ..packages import six import sys from .. import util __all__ = ["inject_into_urllib3", "extract_from_urllib3"] # SNI always works. HAS_SNI = True # Map from urllib3 to PyOpenSSL compatible parameter-values. _openssl_versions = { util.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, } if hasattr(ssl, "PROTOCOL_SSLv3") and hasattr(OpenSSL.SSL, "SSLv3_METHOD"): _openssl_versions[ssl.PROTOCOL_SSLv3] = OpenSSL.SSL.SSLv3_METHOD if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict((v, k) for k, v in _stdlib_to_openssl_verify.items()) # OpenSSL will only write 16K at a time SSL_WRITE_BLOCKSIZE = 16384 orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext log = logging.getLogger(__name__) def inject_into_urllib3(): "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." _validate_dependencies_met() util.SSLContext = PyOpenSSLContext util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True def extract_from_urllib3(): "Undo monkey-patching by :func:`inject_into_urllib3`." util.SSLContext = orig_util_SSLContext util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_PYOPENSSL = False util.ssl_.IS_PYOPENSSL = False def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError( "'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer." ) # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError( "'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer." ) def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. """ def idna_encode(name): """ Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. """ import idna try: for prefix in [u"*.", u"."]: if name.startswith(prefix): name = name[len(prefix) :] return prefix.encode("ascii") + idna.encode(name) return idna.encode(name) except idna.core.IDNAError: return None # Don't send IPv6 addresses through the IDNA encoder. if ":" in name: return name name = idna_encode(name) if name is None: return None elif sys.version_info >= (3, 0): name = name.decode("utf-8") return name def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except ( x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError, ) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ("DNS", name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names class WrappedSocket(object): """API-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. """ def __init__(self, connection, socket, suppress_ragged_eofs=True): self.connection = connection self.socket = socket self.suppress_ragged_eofs = suppress_ragged_eofs self._makefile_refs = 0 self._closed = False def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, *args, **kwargs): try: data = self.connection.recv(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): return b"" else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b"" else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout("The read operation timed out") else: return self.recv(*args, **kwargs) # TLS 1.3 post-handshake authentication except OpenSSL.SSL.Error as e: raise ssl.SSLError("read error: %r" % e) else: return data def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout("The read operation timed out") else: return self.recv_into(*args, **kwargs) # TLS 1.3 post-handshake authentication except OpenSSL.SSL.Error as e: raise ssl.SSLError("read error: %r" % e) def settimeout(self, timeout): return self.socket.settimeout(timeout) def _send_until_done(self, data): while True: try: return self.connection.send(data) except OpenSSL.SSL.WantWriteError: if not util.wait_for_write(self.socket, self.socket.gettimeout()): raise timeout() continue except OpenSSL.SSL.SysCallError as e: raise SocketError(str(e)) def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self._send_until_done( data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] ) total_sent += sent def shutdown(self): # FIXME rethrow compatible exceptions should we ever use this self.connection.shutdown() def close(self): if self._makefile_refs < 1: try: self._closed = True return self.connection.close() except OpenSSL.SSL.Error: return else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): x509 = self.connection.get_peer_certificate() if not x509: return x509 if binary_form: return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) return { "subject": ((("commonName", x509.get_subject().CN),),), "subjectAltName": get_subj_alt_name(x509), } def version(self): return self.connection.get_protocol_version_name() def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 makefile = backport_makefile WrappedSocket.makefile = makefile class PyOpenSSLContext(object): """ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. """ def __init__(self, protocol): self.protocol = _openssl_versions[protocol] self._ctx = OpenSSL.SSL.Context(self.protocol) self._options = 0 self.check_hostname = False @property def options(self): return self._options @options.setter def options(self, value): self._options = value self._ctx.set_options(value) @property def verify_mode(self): return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) def set_default_verify_paths(self): self._ctx.set_default_verify_paths() def set_ciphers(self, ciphers): if isinstance(ciphers, six.text_type): ciphers = ciphers.encode("utf-8") self._ctx.set_cipher_list(ciphers) def load_verify_locations(self, cafile=None, capath=None, cadata=None): if cafile is not None: cafile = cafile.encode("utf-8") if capath is not None: capath = capath.encode("utf-8") self._ctx.load_verify_locations(cafile, capath) if cadata is not None: self._ctx.load_verify_locations(BytesIO(cadata)) def load_cert_chain(self, certfile, keyfile=None, password=None): self._ctx.use_certificate_chain_file(certfile) if password is not None: if not isinstance(password, six.binary_type): password = password.encode("utf-8") self._ctx.set_passwd_cb(lambda *_: password) self._ctx.use_privatekey_file(keyfile or certfile) def wrap_socket( self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, ): cnx = OpenSSL.SSL.Connection(self._ctx, sock) if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3 server_hostname = server_hostname.encode("utf-8") if server_hostname is not None: cnx.set_tlsext_host_name(server_hostname) cnx.set_connect_state() while True: try: cnx.do_handshake() except OpenSSL.SSL.WantReadError: if not util.wait_for_read(sock, sock.gettimeout()): raise timeout("select timed out") continue except OpenSSL.SSL.Error as e: raise ssl.SSLError("bad handshake: %r" % e) break return WrappedSocket(cnx, sock) def _verify_callback(cnx, x509, err_no, err_depth, return_code): return err_no == 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/securetransport.py0000644000175000017500000007702300000000000025535 0ustar00sethmlarsonsethmlarson00000000000000""" SecureTranport support for urllib3 via ctypes. This makes platform-native TLS available to urllib3 users on macOS without the use of a compiler. This is an important feature because the Python Package Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL that ships with macOS is not capable of doing TLSv1.2. The only way to resolve this is to give macOS users an alternative solution to the problem, and that solution is to use SecureTransport. We use ctypes here because this solution must not require a compiler. That's because pip is not allowed to require a compiler either. This is not intended to be a seriously long-term solution to this problem. The hope is that PEP 543 will eventually solve this issue for us, at which point we can retire this contrib module. But in the short term, we need to solve the impending tire fire that is Python on Mac without this kind of contrib module. So...here we are. To use this module, simply import and inject it:: import urllib3.contrib.securetransport urllib3.contrib.securetransport.inject_into_urllib3() Happy TLSing! This code is a bastardised version of the code found in Will Bond's oscrypto library. An enormous debt is owed to him for blazing this trail for us. For that reason, this code should be considered to be covered both by urllib3's license and by oscrypto's: Copyright (c) 2015-2016 Will Bond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import threading import weakref from .. import util from ._securetransport.bindings import Security, SecurityConst, CoreFoundation from ._securetransport.low_level import ( _assert_no_error, _cert_array_from_pem, _temporary_keychain, _load_client_cert_chain, ) try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile __all__ = ["inject_into_urllib3", "extract_from_urllib3"] # SNI always works HAS_SNI = True orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext # This dictionary is used by the read callback to obtain a handle to the # calling wrapped socket. This is a pretty silly approach, but for now it'll # do. I feel like I should be able to smuggle a handle to the wrapped socket # directly in the SSLConnectionRef, but for now this approach will work I # guess. # # We need to lock around this structure for inserts, but we don't do it for # reads/writes in the callbacks. The reasoning here goes as follows: # # 1. It is not possible to call into the callbacks before the dictionary is # populated, so once in the callback the id must be in the dictionary. # 2. The callbacks don't mutate the dictionary, they only read from it, and # so cannot conflict with any of the insertions. # # This is good: if we had to lock in the callbacks we'd drastically slow down # the performance of this code. _connection_refs = weakref.WeakValueDictionary() _connection_ref_lock = threading.Lock() # Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over # for no better reason than we need *a* limit, and this one is right there. SSL_WRITE_BLOCKSIZE = 16384 # This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to # individual cipher suites. We need to do this because this is how # SecureTransport wants them. CIPHER_SUITES = [ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_AES_256_GCM_SHA384, SecurityConst.TLS_AES_128_GCM_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_AES_128_CCM_8_SHA256, SecurityConst.TLS_AES_128_CCM_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA, ] # Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of # TLSv1 and a high of TLSv1.2. For everything else, we pin to that version. # TLSv1 to 1.2 are supported on macOS 10.8+ _protocol_to_min_max = { util.PROTOCOL_TLS: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12) } if hasattr(ssl, "PROTOCOL_SSLv2"): _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = ( SecurityConst.kSSLProtocol2, SecurityConst.kSSLProtocol2, ) if hasattr(ssl, "PROTOCOL_SSLv3"): _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = ( SecurityConst.kSSLProtocol3, SecurityConst.kSSLProtocol3, ) if hasattr(ssl, "PROTOCOL_TLSv1"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = ( SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol1, ) if hasattr(ssl, "PROTOCOL_TLSv1_1"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = ( SecurityConst.kTLSProtocol11, SecurityConst.kTLSProtocol11, ) if hasattr(ssl, "PROTOCOL_TLSv1_2"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = ( SecurityConst.kTLSProtocol12, SecurityConst.kTLSProtocol12, ) def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.SSLContext = SecureTransportContext util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.SSLContext = orig_util_SSLContext util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, "timed out") remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, "timed out") chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal # We need to keep these two objects references alive: if they get GC'd while # in use then SecureTransport could attempt to call a function that is in freed # memory. That would be...uh...bad. Yeah, that's the word. Bad. _read_callback_pointer = Security.SSLReadFunc(_read_callback) _write_callback_pointer = Security.SSLWriteFunc(_write_callback) class WrappedSocket(object): """ API-compatibility wrapper for Python's OpenSSL wrapped socket object. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage collector of PyPy. """ def __init__(self, socket): self.socket = socket self.context = None self._makefile_refs = 0 self._closed = False self._exception = None self._keychain = None self._keychain_dir = None self._client_cert_chain = None # We save off the previously-configured timeout and then set it to # zero. This is done because we use select and friends to handle the # timeouts, but if we leave the timeout set on the lower socket then # Python will "kindly" call select on that socket again for us. Avoid # that by forcing the timeout to zero. self._timeout = self.socket.gettimeout() self.socket.settimeout(0) @contextlib.contextmanager def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ self._exception = None # We explicitly don't catch around this yield because in the unlikely # event that an exception was hit in the block we don't want to swallow # it. yield if self._exception is not None: exception, self._exception = self._exception, None self.close() raise exception def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result) def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. """ # If we disabled cert validation, just say: cool. if not verify: return # We want data in memory, so load it up. if os.path.isfile(trust_bundle): with open(trust_bundle, "rb") as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust)) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate(trust, ctypes.byref(trust_result)) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) # Ok, now we can look at what the result was. successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed, ) if trust_result.value not in successes: raise ssl.SSLError( "certificate verify failed, error code: %d" % trust_result.value ) def handshake( self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase, ): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode("utf-8") result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate(self.context, self._client_cert_chain) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, bufsiz): buffer = ctypes.create_string_buffer(bufsiz) bytes_read = self.recv_into(buffer, bufsiz) data = buffer[:bytes_read] return data def recv_into(self, buffer, nbytes=None): # Read short on EOF. if self._closed: return 0 if nbytes is None: nbytes = len(buffer) buffer = (ctypes.c_char * nbytes).from_buffer(buffer) processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLRead( self.context, buffer, nbytes, ctypes.byref(processed_bytes) ) # There are some result codes that we want to treat as "not always # errors". Specifically, those are errSSLWouldBlock, # errSSLClosedGraceful, and errSSLClosedNoNotify. if result == SecurityConst.errSSLWouldBlock: # If we didn't process any bytes, then this was just a time out. # However, we can get errSSLWouldBlock in situations when we *did* # read some data, and in those cases we should just read "short" # and return. if processed_bytes.value == 0: # Timed out, no data read. raise socket.timeout("recv timed out") elif result in ( SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify, ): # The remote peer has closed this connection. We should do so as # well. Note that we don't actually return here because in # principle this could actually be fired along with return data. # It's unlikely though. self.close() else: _assert_no_error(result) # Ok, we read and probably succeeded. We should return whatever data # was actually read. return processed_bytes.value def settimeout(self, timeout): self._timeout = timeout def gettimeout(self): return self._timeout def send(self, data): processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLWrite( self.context, data, len(data), ctypes.byref(processed_bytes) ) if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0: # Timed out raise socket.timeout("send timed out") else: _assert_no_error(result) # We sent, and probably succeeded. Tell them how much we sent. return processed_bytes.value def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self.send(data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]) total_sent += sent def shutdown(self): with self._raise_on_error(): Security.SSLClose(self.context) def close(self): # TODO: should I do clean shutdown here? Do I have to? if self._makefile_refs < 1: self._closed = True if self.context: CoreFoundation.CFRelease(self.context) self.context = None if self._client_cert_chain: CoreFoundation.CFRelease(self._client_cert_chain) self._client_cert_chain = None if self._keychain: Security.SecKeychainDelete(self._keychain) CoreFoundation.CFRelease(self._keychain) shutil.rmtree(self._keychain_dir) self._keychain = self._keychain_dir = None return self.socket.close() else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): # Urgh, annoying. # # Here's how we do this: # # 1. Call SSLCopyPeerTrust to get hold of the trust object for this # connection. # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf. # 3. To get the CN, call SecCertificateCopyCommonName and process that # string so that it's of the appropriate type. # 4. To get the SAN, we need to do something a bit more complex: # a. Call SecCertificateCopyValues to get the data, requesting # kSecOIDSubjectAltName. # b. Mess about with this dictionary to try to get the SANs out. # # This is gross. Really gross. It's going to be a few hundred LoC extra # just to repeat something that SecureTransport can *already do*. So my # operating assumption at this time is that what we want to do is # instead to just flag to urllib3 that it shouldn't do its own hostname # validation when using SecureTransport. if not binary_form: raise ValueError("SecureTransport only supports dumping binary certs") trust = Security.SecTrustRef() certdata = None der_bytes = None try: # Grab the trust store. result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust)) _assert_no_error(result) if not trust: # Probably we haven't done the handshake yet. No biggie. return None cert_count = Security.SecTrustGetCertificateCount(trust) if not cert_count: # Also a case that might happen if we haven't handshaked. # Handshook? Handshaken? return None leaf = Security.SecTrustGetCertificateAtIndex(trust, 0) assert leaf # Ok, now we want the DER bytes. certdata = Security.SecCertificateCopyData(leaf) assert certdata data_length = CoreFoundation.CFDataGetLength(certdata) data_buffer = CoreFoundation.CFDataGetBytePtr(certdata) der_bytes = ctypes.string_at(data_buffer, data_length) finally: if certdata: CoreFoundation.CFRelease(certdata) if trust: CoreFoundation.CFRelease(trust) return der_bytes def version(self): protocol = Security.SSLProtocol() result = Security.SSLGetNegotiatedProtocolVersion( self.context, ctypes.byref(protocol) ) _assert_no_error(result) if protocol.value == SecurityConst.kTLSProtocol13: raise ssl.SSLError("SecureTransport does not support TLS 1.3") elif protocol.value == SecurityConst.kTLSProtocol12: return "TLSv1.2" elif protocol.value == SecurityConst.kTLSProtocol11: return "TLSv1.1" elif protocol.value == SecurityConst.kTLSProtocol1: return "TLSv1" elif protocol.value == SecurityConst.kSSLProtocol3: return "SSLv3" elif protocol.value == SecurityConst.kSSLProtocol2: return "SSLv2" else: raise ssl.SSLError("Unknown TLS version: %r" % protocol) def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 def makefile(self, mode="r", buffering=None, *args, **kwargs): # We disable buffering with SecureTransport because it conflicts with # the buffering that ST does internally (see issue #1153 for more). buffering = 0 return backport_makefile(self, mode, buffering, *args, **kwargs) WrappedSocket.makefile = makefile class SecureTransportContext(object): """ I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. """ def __init__(self, protocol): self._min_version, self._max_version = _protocol_to_min_max[protocol] self._options = 0 self._verify = False self._trust_bundle = None self._client_cert = None self._client_key = None self._client_key_passphrase = None @property def check_hostname(self): """ SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. """ return True @check_hostname.setter def check_hostname(self, value): """ SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. """ pass @property def options(self): # TODO: Well, crap. # # So this is the bit of the code that is the most likely to cause us # trouble. Essentially we need to enumerate all of the SSL options that # users might want to use and try to see if we can sensibly translate # them, or whether we should just ignore them. return self._options @options.setter def options(self, value): # TODO: Update in line with above. self._options = value @property def verify_mode(self): return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE @verify_mode.setter def verify_mode(self, value): self._verify = True if value == ssl.CERT_REQUIRED else False def set_default_verify_paths(self): # So, this has to do something a bit weird. Specifically, what it does # is nothing. # # This means that, if we had previously had load_verify_locations # called, this does not undo that. We need to do that because it turns # out that the rest of the urllib3 code will attempt to load the # default verify paths if it hasn't been told about any paths, even if # the context itself was sometime earlier. We resolve that by just # ignoring it. pass def load_default_certs(self): return self.set_default_verify_paths() def set_ciphers(self, ciphers): # For now, we just require the default cipher string. if ciphers != util.ssl_.DEFAULT_CIPHERS: raise ValueError("SecureTransport doesn't support custom cipher strings") def load_verify_locations(self, cafile=None, capath=None, cadata=None): # OK, we only really support cadata and cafile. if capath is not None: raise ValueError("SecureTransport does not support cert directories") self._trust_bundle = cafile or cadata def load_cert_chain(self, certfile, keyfile=None, password=None): self._client_cert = certfile self._client_key = keyfile self._client_cert_passphrase = password def wrap_socket( self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, ): # So, what do we do here? Firstly, we assert some properties. This is a # stripped down shim, so there is some functionality we don't support. # See PEP 543 for the real deal. assert not server_side assert do_handshake_on_connect assert suppress_ragged_eofs # Ok, we're good to go. Now we want to create the wrapped socket object # and store it in the appropriate place. wrapped_socket = WrappedSocket(sock) # Now we can handshake wrapped_socket.handshake( server_hostname, self._verify, self._trust_bundle, self._min_version, self._max_version, self._client_cert, self._client_key, self._client_key_passphrase, ) return wrapped_socket ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/contrib/socks.py0000644000175000017500000001557400000000000023417 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- """ This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4A (``proxy_url='socks4a://...``) - SOCKS4 (``proxy_url='socks4://...``) - SOCKS5 with remote DNS (``proxy_url='socks5h://...``) - SOCKS5 with local DNS (``proxy_url='socks5://...``) - Usernames and passwords for the SOCKS proxy .. note:: It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in your ``proxy_url`` to ensure that DNS resolution is done from the remote server instead of client-side when connecting to a domain name. SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 supports IPv4, IPv6, and domain names. When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` will be sent as the ``userid`` section of the SOCKS request:: proxy_url="socks4a://@proxy-host" When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion of the ``proxy_url`` will be sent as the username/password to authenticate with the proxy:: proxy_url="socks5h://:@proxy-host" """ from __future__ import absolute_import try: import socks except ImportError: import warnings from ..exceptions import DependencyWarning warnings.warn( ( "SOCKS support in urllib3 requires the installation of optional " "dependencies: specifically, PySocks. For more information, see " "https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies" ), DependencyWarning, ) raise from socket import error as SocketError, timeout as SocketTimeout from ..connection import HTTPConnection, HTTPSConnection from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool from ..exceptions import ConnectTimeoutError, NewConnectionError from ..poolmanager import PoolManager from ..util.url import parse_url try: import ssl except ImportError: ssl = None class SOCKSConnection(HTTPConnection): """ A plain-text HTTP connection that connects via a SOCKS proxy. """ def __init__(self, *args, **kwargs): self._socks_options = kwargs.pop("_socks_options") super(SOCKSConnection, self).__init__(*args, **kwargs) def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw["source_address"] = self.source_address if self.socket_options: extra_kw["socket_options"] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options["socks_version"], proxy_addr=self._socks_options["proxy_host"], proxy_port=self._socks_options["proxy_port"], proxy_username=self._socks_options["username"], proxy_password=self._socks_options["password"], proxy_rdns=self._socks_options["rdns"], timeout=self.timeout, **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout), ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) return conn # We don't need to duplicate the Verified/Unverified distinction from # urllib3/connection.py here because the HTTPSConnection will already have been # correctly set to either the Verified or Unverified form by that module. This # means the SOCKSHTTPSConnection will automatically be the correct type. class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): pass class SOCKSHTTPConnectionPool(HTTPConnectionPool): ConnectionCls = SOCKSConnection class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): ConnectionCls = SOCKSHTTPSConnection class SOCKSProxyManager(PoolManager): """ A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. """ pool_classes_by_scheme = { "http": SOCKSHTTPConnectionPool, "https": SOCKSHTTPSConnectionPool, } def __init__( self, proxy_url, username=None, password=None, num_pools=10, headers=None, **connection_pool_kw ): parsed = parse_url(proxy_url) if username is None and password is None and parsed.auth is not None: split = parsed.auth.split(":") if len(split) == 2: username, password = split if parsed.scheme == "socks5": socks_version = socks.PROXY_TYPE_SOCKS5 rdns = False elif parsed.scheme == "socks5h": socks_version = socks.PROXY_TYPE_SOCKS5 rdns = True elif parsed.scheme == "socks4": socks_version = socks.PROXY_TYPE_SOCKS4 rdns = False elif parsed.scheme == "socks4a": socks_version = socks.PROXY_TYPE_SOCKS4 rdns = True else: raise ValueError("Unable to determine SOCKS version from %s" % proxy_url) self.proxy_url = proxy_url socks_options = { "socks_version": socks_version, "proxy_host": parsed.host, "proxy_port": parsed.port, "username": username, "password": password, "rdns": rdns, } connection_pool_kw["_socks_options"] = socks_options super(SOCKSProxyManager, self).__init__( num_pools, headers, **connection_pool_kw ) self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/exceptions.py0000644000175000017500000001471700000000000023014 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead # Base Exceptions class HTTPError(Exception): "Base exception used by this module." pass class HTTPWarning(Warning): "Base warning used by this module." pass class PoolError(HTTPError): "Base exception for errors caused within a pool." def __init__(self, pool, message): self.pool = pool HTTPError.__init__(self, "%s: %s" % (pool, message)) def __reduce__(self): # For pickling purposes. return self.__class__, (None, None) class RequestError(PoolError): "Base exception for PoolErrors that have associated URLs." def __init__(self, pool, url, message): self.url = url PoolError.__init__(self, pool, message) def __reduce__(self): # For pickling purposes. return self.__class__, (None, self.url, None) class SSLError(HTTPError): "Raised when SSL certificate fails in an HTTPS connection." pass class ProxyError(HTTPError): "Raised when the connection to a proxy fails." pass class DecodeError(HTTPError): "Raised when automatic decoding based on Content-Type fails." pass class ProtocolError(HTTPError): "Raised when something unexpected happens mid-request/response." pass #: Renamed to ProtocolError but aliased for backwards compatibility. ConnectionError = ProtocolError # Leaf Exceptions class MaxRetryError(RequestError): """Raised when the maximum number of retries is exceeded. :param pool: The connection pool :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` :param string url: The requested Url :param exceptions.Exception reason: The underlying error """ def __init__(self, pool, url, reason=None): self.reason = reason message = "Max retries exceeded with url: %s (Caused by %r)" % (url, reason) RequestError.__init__(self, pool, url, message) class HostChangedError(RequestError): "Raised when an existing pool gets a request for a foreign host." def __init__(self, pool, url, retries=3): message = "Tried to open a foreign host with url: %s" % url RequestError.__init__(self, pool, url, message) self.retries = retries class TimeoutStateError(HTTPError): """ Raised when passing an invalid state to a timeout """ pass class TimeoutError(HTTPError): """ Raised when a socket timeout error occurs. Catching this error will catch both :exc:`ReadTimeoutErrors ` and :exc:`ConnectTimeoutErrors `. """ pass class ReadTimeoutError(TimeoutError, RequestError): "Raised when a socket timeout occurs while receiving data from a server" pass # This timeout error does not have a URL attached and needs to inherit from the # base HTTPError class ConnectTimeoutError(TimeoutError): "Raised when a socket timeout occurs while connecting to a server" pass class NewConnectionError(ConnectTimeoutError, PoolError): "Raised when we fail to establish a new connection. Usually ECONNREFUSED." pass class EmptyPoolError(PoolError): "Raised when a pool runs out of connections and no more are allowed." pass class ClosedPoolError(PoolError): "Raised when a request enters a pool after the pool has been closed." pass class LocationValueError(ValueError, HTTPError): "Raised when there is something wrong with a given URL input." pass class LocationParseError(LocationValueError): "Raised when get_host or similar fails to parse the URL input." def __init__(self, location): message = "Failed to parse: %s" % location HTTPError.__init__(self, message) self.location = location class ResponseError(HTTPError): "Used as a container for an error reason supplied in a MaxRetryError." GENERIC_ERROR = "too many error responses" SPECIFIC_ERROR = "too many {status_code} error responses" class SecurityWarning(HTTPWarning): "Warned when performing security reducing actions" pass class SubjectAltNameWarning(SecurityWarning): "Warned when connecting to a host with a certificate missing a SAN." pass class InsecureRequestWarning(SecurityWarning): "Warned when making an unverified HTTPS request." pass class SystemTimeWarning(SecurityWarning): "Warned when system time is suspected to be wrong" pass class InsecurePlatformWarning(SecurityWarning): "Warned when certain SSL configuration is not available on a platform." pass class SNIMissingWarning(HTTPWarning): "Warned when making a HTTPS request without SNI available." pass class DependencyWarning(HTTPWarning): """ Warned when an attempt is made to import a module with missing optional dependencies. """ pass class ResponseNotChunked(ProtocolError, ValueError): "Response needs to be chunked in order to read it as chunks." pass class BodyNotHttplibCompatible(HTTPError): """ Body should be httplib.HTTPResponse like (have an fp attribute which returns raw chunks) for read_chunked(). """ pass class IncompleteRead(HTTPError, httplib_IncompleteRead): """ Response length doesn't match expected Content-Length Subclass of http_client.IncompleteRead to allow int value for `partial` to avoid creating large objects on streamed reads. """ def __init__(self, partial, expected): super(IncompleteRead, self).__init__(partial, expected) def __repr__(self): return "IncompleteRead(%i bytes read, %i more expected)" % ( self.partial, self.expected, ) class InvalidHeader(HTTPError): "The header provided was somehow invalid." pass class ProxySchemeUnknown(AssertionError, ValueError): "ProxyManager does not support the supplied scheme" # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. def __init__(self, scheme): message = "Not supported proxy scheme %s" % scheme super(ProxySchemeUnknown, self).__init__(message) class HeaderParsingError(HTTPError): "Raised by assert_header_parsing, but we convert it to a log.warning statement." def __init__(self, defects, unparsed_data): message = "%s, unparsed data: %r" % (defects or "Unknown", unparsed_data) super(HeaderParsingError, self).__init__(message) class UnrewindableBodyError(HTTPError): "urllib3 encountered an error when trying to rewind a body" pass ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/fields.py0000644000175000017500000002055100000000000022072 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import email.utils import mimetypes import re from .packages import six def guess_content_type(filename, default="application/octet-stream"): """ Guess the "Content-Type" of a file. :param filename: The filename to guess the "Content-Type" of using :mod:`mimetypes`. :param default: If no "Content-Type" can be guessed, default to `default`. """ if filename: return mimetypes.guess_type(filename)[0] or default return default def format_header_param_rfc2231(name, value): """ Helper function to format and quote a single header parameter using the strategy defined in RFC 2231. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows RFC 2388 Section 4.4. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as ``bytes`` or `str``. :ret: An RFC-2231-formatted unicode string. """ if isinstance(value, six.binary_type): value = value.decode("utf-8") if not any(ch in value for ch in '"\\\r\n'): result = u'%s="%s"' % (name, value) try: result.encode("ascii") except (UnicodeEncodeError, UnicodeDecodeError): pass else: return result if six.PY2: # Python 2: value = value.encode("utf-8") # encode_rfc2231 accepts an encoded string and returns an ascii-encoded # string in Python 2 but accepts and returns unicode strings in Python 3 value = email.utils.encode_rfc2231(value, "utf-8") value = "%s*=%s" % (name, value) if six.PY2: # Python 2: value = value.decode("utf-8") return value _HTML5_REPLACEMENTS = { u"\u0022": u"%22", # Replace "\" with "\\". u"\u005C": u"\u005C\u005C", u"\u005C": u"\u005C\u005C", } # All control characters from 0x00 to 0x1F *except* 0x1B. _HTML5_REPLACEMENTS.update( { six.unichr(cc): u"%{:02X}".format(cc) for cc in range(0x00, 0x1F + 1) if cc not in (0x1B,) } ) def _replace_multiple(value, needles_and_replacements): def replacer(match): return needles_and_replacements[match.group(0)] pattern = re.compile( r"|".join([re.escape(needle) for needle in needles_and_replacements.keys()]) ) result = pattern.sub(replacer, value) return result def format_header_param_html5(name, value): """ Helper function to format and quote a single header parameter using the HTML5 strategy. Particularly useful for header parameters which might contain non-ASCII values, like file names. This follows the `HTML5 Working Draft Section 4.10.22.7`_ and matches the behavior of curl and modern browsers. .. _HTML5 Working Draft Section 4.10.22.7: https://w3c.github.io/html/sec-forms.html#multipart-form-data :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as ``bytes`` or `str``. :ret: A unicode string, stripped of troublesome characters. """ if isinstance(value, six.binary_type): value = value.decode("utf-8") value = _replace_multiple(value, _HTML5_REPLACEMENTS) return u'%s="%s"' % (name, value) # For backwards-compatibility. format_header_param = format_header_param_html5 class RequestField(object): """ A data container for request body parameters. :param name: The name of this request field. Must be unicode. :param data: The data/value body. :param filename: An optional filename of the request field. Must be unicode. :param headers: An optional dict-like object of headers to initially use for the field. :param header_formatter: An optional callable that is used to encode and format the headers. By default, this is :func:`format_header_param_html5`. """ def __init__( self, name, data, filename=None, headers=None, header_formatter=format_header_param_html5, ): self._name = name self._filename = filename self.data = data self.headers = {} if headers: self.headers = dict(headers) self.header_formatter = header_formatter @classmethod def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5): """ A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', Field names and filenames must be unicode. """ if isinstance(value, tuple): if len(value) == 3: filename, data, content_type = value else: filename, data = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_param = cls( fieldname, data, filename=filename, header_formatter=header_formatter ) request_param.make_multipart(content_type=content_type) return request_param def _render_part(self, name, value): """ Overridable helper function to format a single header parameter. By default, this calls ``self.header_formatter``. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string. """ return self.header_formatter(name, value) def _render_parts(self, header_parts): """ Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., 'Content-Disposition' fields. :param header_parts: A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`. """ parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for name, value in iterable: if value is not None: parts.append(self._render_part(name, value)) return u"; ".join(parts) def render_headers(self): """ Renders the headers for this request field. """ lines = [] sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append(u"%s: %s" % (sort_key, self.headers[sort_key])) for header_name, header_value in self.headers.items(): if header_name not in sort_keys: if header_value: lines.append(u"%s: %s" % (header_name, header_value)) lines.append(u"\r\n") return u"\r\n".join(lines) def make_multipart( self, content_disposition=None, content_type=None, content_location=None ): """ Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The 'Content-Type' of the request body. :param content_location: The 'Content-Location' of the request body. """ self.headers["Content-Disposition"] = content_disposition or u"form-data" self.headers["Content-Disposition"] += u"; ".join( [ u"", self._render_parts( ((u"name", self._name), (u"filename", self._filename)) ), ] ) self.headers["Content-Type"] = content_type self.headers["Content-Location"] = content_location ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/filepost.py0000644000175000017500000000461000000000000022447 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import binascii import codecs import os from io import BytesIO from .packages import six from .packages.six import b from .fields import RequestField writer = codecs.lookup("utf-8")[3] def choose_boundary(): """ Our embarrassingly-simple replacement for mimetools.choose_boundary. """ boundary = binascii.hexlify(os.urandom(16)) if not six.PY2: boundary = boundary.decode("ascii") return boundary def iter_field_objects(fields): """ Iterate over fields. Supports list of (k, v) tuples and dicts, and lists of :class:`~urllib3.fields.RequestField`. """ if isinstance(fields, dict): i = six.iteritems(fields) else: i = iter(fields) for field in i: if isinstance(field, RequestField): yield field else: yield RequestField.from_tuples(*field) def iter_fields(fields): """ .. deprecated:: 1.6 Iterate over fields. The addition of :class:`~urllib3.fields.RequestField` makes this function obsolete. Instead, use :func:`iter_field_objects`, which returns :class:`~urllib3.fields.RequestField` objects. Supports list of (k, v) tuples and dicts. """ if isinstance(fields, dict): return ((k, v) for k, v in six.iteritems(fields)) return ((k, v) for k, v in fields) def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`urllib3.filepost.choose_boundary`. """ body = BytesIO() if boundary is None: boundary = choose_boundary() for field in iter_field_objects(fields): body.write(b("--%s\r\n" % (boundary))) writer(body).write(field.render_headers()) data = field.data if isinstance(data, int): data = str(data) # Backwards compatibility if isinstance(data, six.text_type): writer(body).write(data) else: body.write(data) body.write(b"\r\n") body.write(b("--%s--\r\n" % (boundary))) content_type = str("multipart/form-data; boundary=%s" % boundary) return body.getvalue(), content_type ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/packages/0000755000175000017500000000000000000000000022025 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/packages/__init__.py0000644000175000017500000000015400000000000024136 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import from . import ssl_match_hostname __all__ = ("ssl_match_hostname",) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/packages/backports/0000755000175000017500000000000000000000000024015 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/packages/backports/__init__.py0000644000175000017500000000000000000000000026114 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/packages/backports/makefile.py0000644000175000017500000000261200000000000026145 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- """ backports.makefile ~~~~~~~~~~~~~~~~~~ Backports the Python 3 ``socket.makefile`` method for use with anything that wants to create a "fake" socket object. """ import io from socket import SocketIO def backport_makefile( self, mode="r", buffering=None, encoding=None, errors=None, newline=None ): """ Backport of ``socket.makefile`` from Python 3.5. """ if not set(mode) <= {"r", "w", "b"}: raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,)) writing = "w" in mode reading = "r" in mode or not writing assert reading or writing binary = "b" in mode rawmode = "" if reading: rawmode += "r" if writing: rawmode += "w" raw = SocketIO(self, rawmode) self._makefile_refs += 1 if buffering is None: buffering = -1 if buffering < 0: buffering = io.DEFAULT_BUFFER_SIZE if buffering == 0: if not binary: raise ValueError("unbuffered streams must be binary") return raw if reading and writing: buffer = io.BufferedRWPair(raw, raw, buffering) elif reading: buffer = io.BufferedReader(raw, buffering) else: assert writing buffer = io.BufferedWriter(raw, buffering) if binary: return buffer text = io.TextIOWrapper(buffer, encoding, errors, newline) text.mode = mode return text ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/packages/six.py0000644000175000017500000007743000000000000023215 0ustar00sethmlarsonsethmlarson00000000000000# Copyright (c) 2010-2019 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """Utilities for writing code that runs on Python 2 and 3""" from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson " __version__ = "1.12.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = (str,) integer_types = (int,) class_types = (type,) text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = (basestring,) integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute( "filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse" ), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("getoutput", "commands", "subprocess"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute( "reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload" ), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute( "zip_longest", "itertools", "itertools", "izip_longest", "zip_longest" ), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule( "email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart" ), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [MovedModule("winreg", "_winreg")] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute( "unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes" ), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("splitvalue", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module( Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse", ) class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module( Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error", ) class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), MovedAttribute("parse_http_list", "urllib2", "urllib.request"), MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module( Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request", ) class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module( Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response", ) class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser") ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = ( _urllib_robotparser_moved_attributes ) _importer._add_module( Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser", ) class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ["parse", "error", "request", "response", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc( get_unbound_function, """Get the function out of a possibly unbound function""" ) get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc( iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary." ) if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO del io _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): try: if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value finally: value = None tb = None else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_( """def reraise(tp, value, tb=None): try: raise tp, value, tb finally: tb = None """ ) if sys.version_info[:2] == (3, 2): exec_( """def raise_from(value, from_value): try: if from_value is None: raise value raise value from from_value finally: value = None """ ) elif sys.version_info[:2] > (3, 2): exec_( """def raise_from(value, from_value): try: raise value from from_value finally: value = None """ ) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if ( isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None ): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps( wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES, ): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, "temporary_class", (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop("__dict__", None) orig_vars.pop("__weakref__", None) if hasattr(cls, "__qualname__"): orig_vars["__qualname__"] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding="utf-8", errors="strict"): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s def ensure_text(s, encoding="utf-8", errors="strict"): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if "__str__" not in klass.__dict__: raise ValueError( "@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__ ) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode("utf-8") return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if ( type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__ ): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/packages/ssl_match_hostname/0000755000175000017500000000000000000000000025700 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/packages/ssl_match_hostname/__init__.py0000644000175000017500000000126000000000000030010 0ustar00sethmlarsonsethmlarson00000000000000import sys try: # Our match_hostname function is the same as 3.5's, so we only want to # import the match_hostname function if it's at least that good. if sys.version_info < (3, 5): raise ImportError("Fallback to vendored code") from ssl import CertificateError, match_hostname except ImportError: try: # Backport of the function from a pypi module from backports.ssl_match_hostname import CertificateError, match_hostname except ImportError: # Our vendored copy from ._implementation import CertificateError, match_hostname # Not needed, but documenting what we provide. __all__ = ("CertificateError", "match_hostname") ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/packages/ssl_match_hostname/_implementation.py0000644000175000017500000001305700000000000031444 0ustar00sethmlarsonsethmlarson00000000000000"""The match_hostname() function from Python 3.3.3, essential when using SSL.""" # Note: This file is under the PSF license as the code comes from the python # stdlib. http://docs.python.org/3/license.html import re import sys # ipaddress has been backported to 2.6+ in pypi. If it is installed on the # system, use it to handle IPAddress ServerAltnames (this was added in # python-3.5) otherwise only do DNS matching. This allows # backports.ssl_match_hostname to continue to be used in Python 2.7. try: import ipaddress except ImportError: ipaddress = None __version__ = "3.5.0.1" class CertificateError(ValueError): pass def _dnsname_match(dn, hostname, max_wildcards=1): """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/rfc6125#section-6.4.3 """ pats = [] if not dn: return False # Ported from python3-syntax: # leftmost, *remainder = dn.split(r'.') parts = dn.split(r".") leftmost = parts[0] remainder = parts[1:] wildcards = leftmost.count("*") if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( "too many wildcards in certificate DNS name: " + repr(dn) ) # speed up common case w/o wildcards if not wildcards: return dn.lower() == hostname.lower() # RFC 6125, section 6.4.3, subitem 1. # The client SHOULD NOT attempt to match a presented identifier in which # the wildcard character comprises a label other than the left-most label. if leftmost == "*": # When '*' is a fragment by itself, it matches a non-empty dotless # fragment. pats.append("[^.]+") elif leftmost.startswith("xn--") or hostname.startswith("xn--"): # RFC 6125, section 6.4.3, subitem 3. # The client SHOULD NOT attempt to match a presented identifier # where the wildcard character is embedded within an A-label or # U-label of an internationalized domain name. pats.append(re.escape(leftmost)) else: # Otherwise, '*' matches any dotless string, e.g. www* pats.append(re.escape(leftmost).replace(r"\*", "[^.]*")) # add the remaining fragments, ignore any wildcards for frag in remainder: pats.append(re.escape(frag)) pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE) return pat.match(hostname) def _to_unicode(obj): if isinstance(obj, str) and sys.version_info < (3,): obj = unicode(obj, encoding="ascii", errors="strict") return obj def _ipaddress_match(ipname, host_ip): """Exact matching of IP addresses. RFC 6125 explicitly doesn't define an algorithm for this (section 1.7.2 - "Out of Scope"). """ # OpenSSL may add a trailing newline to a subjectAltName's IP address # Divergence from upstream: ipaddress can't handle byte str ip = ipaddress.ip_address(_to_unicode(ipname).rstrip()) return ip == host_ip def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError( "empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " "CERT_OPTIONAL or CERT_REQUIRED" ) try: # Divergence from upstream: ipaddress can't handle byte str host_ip = ipaddress.ip_address(_to_unicode(hostname)) except ValueError: # Not an IP address (common case) host_ip = None except UnicodeError: # Divergence from upstream: Have to deal with ipaddress not taking # byte strings. addresses should be all ascii, so we consider it not # an ipaddress in this case host_ip = None except AttributeError: # Divergence from upstream: Make ipaddress library optional if ipaddress is None: host_ip = None else: raise dnsnames = [] san = cert.get("subjectAltName", ()) for key, value in san: if key == "DNS": if host_ip is None and _dnsname_match(value, hostname): return dnsnames.append(value) elif key == "IP Address": if host_ip is not None and _ipaddress_match(value, host_ip): return dnsnames.append(value) if not dnsnames: # The subject is only checked when there is no dNSName entry # in subjectAltName for sub in cert.get("subject", ()): for key, value in sub: # XXX according to RFC 2818, the most specific Common Name # must be used. if key == "commonName": if _dnsname_match(value, hostname): return dnsnames.append(value) if len(dnsnames) > 1: raise CertificateError( "hostname %r " "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames))) ) elif len(dnsnames) == 1: raise CertificateError("hostname %r doesn't match %r" % (hostname, dnsnames[0])) else: raise CertificateError( "no appropriate commonName or subjectAltName fields were found" ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/poolmanager.py0000644000175000017500000004123500000000000023132 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import collections import functools import logging from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool from .connectionpool import port_by_scheme from .exceptions import LocationValueError, MaxRetryError, ProxySchemeUnknown from .packages import six from .packages.six.moves.urllib.parse import urljoin from .request import RequestMethods from .util.url import parse_url from .util.retry import Retry __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ca_cert_dir", "ssl_context", "key_password", ) # All known keyword arguments that could be provided to the pool manager, its # pools, or the underlying connections. This is used to construct a pool key. _key_fields = ( "key_scheme", # str "key_host", # str "key_port", # int "key_timeout", # int or float or Timeout "key_retries", # int or Retry "key_strict", # bool "key_block", # bool "key_source_address", # str "key_key_file", # str "key_key_password", # str "key_cert_file", # str "key_cert_reqs", # str "key_ca_certs", # str "key_ssl_version", # str "key_ca_cert_dir", # str "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext "key_maxsize", # int "key_headers", # dict "key__proxy", # parsed proxy url "key__proxy_headers", # dict "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples "key__socks_options", # dict "key_assert_hostname", # bool or string "key_assert_fingerprint", # str "key_server_hostname", # str ) #: The namedtuple class used to construct keys for the connection pool. #: All custom key schemes should include the fields in this key at a minimum. PoolKey = collections.namedtuple("PoolKey", _key_fields) def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :type key_class: namedtuple :param request_context: A dictionary-like object that contain the context for a request. :type request_context: dict :return: A namedtuple that can be used as a connection pool key. :rtype: PoolKey """ # Since we mutate the dictionary, make a copy first context = request_context.copy() context["scheme"] = context["scheme"].lower() context["host"] = context["host"].lower() # These are both dictionaries and need to be transformed into frozensets for key in ("headers", "_proxy_headers", "_socks_options"): if key in context and context[key] is not None: context[key] = frozenset(context[key].items()) # The socket_options key may be a list and needs to be transformed into a # tuple. socket_opts = context.get("socket_options") if socket_opts is not None: context["socket_options"] = tuple(socket_opts) # Map the kwargs to the names in the namedtuple - this is necessary since # namedtuples can't have fields starting with '_'. for key in list(context.keys()): context["key_" + key] = context.pop(key) # Default to ``None`` for keys missing from the context for field in key_class._fields: if field not in context: context[field] = None return key_class(**context) #: A dictionary that maps a scheme to a callable that creates a pool key. #: This can be used to alter the way pool keys are constructed, if desired. #: Each PoolManager makes a copy of this dictionary so they can be configured #: globally here, or individually on the instance. key_fn_by_scheme = { "http": functools.partial(_default_key_normalizer, PoolKey), "https": functools.partial(_default_key_normalizer, PoolKey), } pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \\**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example:: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ proxy = None def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close()) # Locally set the pool classes and keys so other PoolManagers can # override them. self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port: port = port_by_scheme.get(request_context["scheme"].lower(), 80) request_context["port"] = port request_context["host"] = host return self.connection_from_context(request_context) def connection_from_context(self, request_context): """ Get a :class:`ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable. """ scheme = request_context["scheme"].lower() pool_key_constructor = self.key_fn_by_scheme[scheme] pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context) def connection_from_pool_key(self, pool_key, request_context=None): """ Get a :class:`ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields. """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type scheme = request_context["scheme"] host = request_context["host"] port = request_context["port"] pool = self._new_pool(scheme, host, port, request_context=request_context) self.pools[pool_key] = pool return pool def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool does not need to be created for the request, the provided ``pool_kwargs`` are not used. """ u = parse_url(url) return self.connection_from_host( u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs ) def _merge_pool_kwargs(self, override): """ Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary. """ base_pool_kwargs = self.connection_pool_kw.copy() if override: for key, value in override.items(): if value is None: try: del base_pool_kwargs[key] except KeyError: pass else: base_pool_kwargs[key] = value return base_pool_kwargs def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """ u = parse_url(url) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw["assert_same_host"] = False kw["redirect"] = False if "headers" not in kw: kw["headers"] = self.headers.copy() if self.proxy is not None and u.scheme == "http": response = conn.urlopen(method, url, **kw) else: response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response # Support relative URLs for redirecting. redirect_location = urljoin(url, redirect_location) # RFC 7231, Section 6.4.4 if response.status == 303: method = "GET" retries = kw.get("retries") if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) # Strip headers marked as unsafe to forward to the redirected location. # Check remove_headers_on_redirect to avoid a potential network call within # conn.is_same_host() which may use socket.gethostbyname() in the future. if retries.remove_headers_on_redirect and not conn.is_same_host( redirect_location ): headers = list(six.iterkeys(kw["headers"])) for header in headers: if header.lower() in retries.remove_headers_on_redirect: kw["headers"].pop(header, None) try: retries = retries.increment(method, url, response=response, _pool=conn) except MaxRetryError: if retries.raise_on_redirect: raise return response kw["retries"] = retries kw["redirect"] = redirect log.info("Redirecting %s -> %s", url, redirect_location) return self.urlopen(method, redirect_location, **kw) class ProxyManager(PoolManager): """ Behaves just like :class:`PoolManager`, but sends all requests through the defined proxy, using the CONNECT method for HTTPS URLs. :param proxy_url: The URL of the proxy to be used. :param proxy_headers: A dictionary containing headers that will be sent to the proxy. In case of HTTP they are being sent with each request, while in the HTTPS/CONNECT case they are sent only once. Could be used for proxy authentication. Example: >>> proxy = urllib3.ProxyManager('http://localhost:3128/') >>> r1 = proxy.request('GET', 'http://google.com/') >>> r2 = proxy.request('GET', 'http://httpbin.org/') >>> len(proxy.pools) 1 >>> r3 = proxy.request('GET', 'https://httpbin.org/') >>> r4 = proxy.request('GET', 'https://twitter.com/') >>> len(proxy.pools) 3 """ def __init__( self, proxy_url, num_pools=10, headers=None, proxy_headers=None, **connection_pool_kw ): if isinstance(proxy_url, HTTPConnectionPool): proxy_url = "%s://%s:%i" % ( proxy_url.scheme, proxy_url.host, proxy_url.port, ) proxy = parse_url(proxy_url) if not proxy.port: port = port_by_scheme.get(proxy.scheme, 80) proxy = proxy._replace(port=port) if proxy.scheme not in ("http", "https"): raise ProxySchemeUnknown(proxy.scheme) self.proxy = proxy self.proxy_headers = proxy_headers or {} connection_pool_kw["_proxy"] = self.proxy connection_pool_kw["_proxy_headers"] = self.proxy_headers super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw) def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): if scheme == "https": return super(ProxyManager, self).connection_from_host( host, port, scheme, pool_kwargs=pool_kwargs ) return super(ProxyManager, self).connection_from_host( self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs ) def _set_proxy_headers(self, url, headers=None): """ Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user. """ headers_ = {"Accept": "*/*"} netloc = parse_url(url).netloc if netloc: headers_["Host"] = netloc if headers: headers_.update(headers) return headers_ def urlopen(self, method, url, redirect=True, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." u = parse_url(url) if u.scheme == "http": # For proxied HTTPS requests, httplib sets the necessary headers # on the CONNECT to the proxy. For HTTP, we'll definitely # need to set 'Host' at the very least. headers = kw.get("headers", self.headers) kw["headers"] = self._set_proxy_headers(url, headers) return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw) def proxy_from_url(url, **kw): return ProxyManager(proxy_url=url, **kw) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/request.py0000644000175000017500000001360200000000000022313 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import from .filepost import encode_multipart_formdata from .packages.six.moves.urllib.parse import urlencode __all__ = ["RequestMethods"] class RequestMethods(object): """ Convenience mixin for classes who implement a :meth:`urlopen` method, such as :class:`~urllib3.connectionpool.HTTPConnectionPool` and :class:`~urllib3.poolmanager.PoolManager`. Provides behavior for making common types of HTTP request methods and decides which type of request field encoding to use. Specifically, :meth:`.request_encode_url` is for sending requests whose fields are encoded in the URL (such as GET, HEAD, DELETE). :meth:`.request_encode_body` is for sending requests whose fields are encoded in the *body* of the request using multipart or www-form-urlencoded (such as for POST, PUT, PATCH). :meth:`.request` is for making any kind of request, it will look up the appropriate encoding format and use one of the above two methods to make the request. Initializer parameters: :param headers: Headers to include with all requests, unless other headers are given explicitly. """ _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"} def __init__(self, headers=None): self.headers = headers or {} def urlopen( self, method, url, body=None, headers=None, encode_multipart=True, multipart_boundary=None, **kw ): # Abstract raise NotImplementedError( "Classes extending RequestMethods must implement " "their own ``urlopen`` method." ) def request(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :meth:`request_encode_url`, :meth:`request_encode_body`, or even the lowest level :meth:`urlopen`. """ method = method.upper() urlopen_kw["request_url"] = url if method in self._encode_url_methods: return self.request_encode_url( method, url, fields=fields, headers=headers, **urlopen_kw ) else: return self.request_encode_body( method, url, fields=fields, headers=headers, **urlopen_kw ) def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if headers is None: headers = self.headers extra_kw = {"headers": headers} extra_kw.update(urlopen_kw) if fields: url += "?" + urlencode(fields) return self.urlopen(method, url, **extra_kw) def request_encode_body( self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw ): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example:: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if headers is None: headers = self.headers extra_kw = {"headers": {}} if fields: if "body" in urlopen_kw: raise TypeError( "request got values for both 'fields' and 'body', can only specify one." ) if encode_multipart: body, content_type = encode_multipart_formdata( fields, boundary=multipart_boundary ) else: body, content_type = ( urlencode(fields), "application/x-www-form-urlencoded", ) extra_kw["body"] = body extra_kw["headers"] = {"Content-Type": content_type} extra_kw["headers"].update(headers) extra_kw.update(urlopen_kw) return self.urlopen(method, url, **extra_kw) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/response.py0000644000175000017500000006627100000000000022473 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import from contextlib import contextmanager import zlib import io import logging from socket import timeout as SocketTimeout from socket import error as SocketError try: import brotli except ImportError: brotli = None from ._collections import HTTPHeaderDict from .exceptions import ( BodyNotHttplibCompatible, ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked, IncompleteRead, InvalidHeader, ) from .packages.six import string_types as basestring, PY3 from .packages.six.moves import http_client as httplib from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed, is_response_to_head log = logging.getLogger(__name__) class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = b"" self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first_try: return self._obj.decompress(data) self._data += data try: decompressed = self._obj.decompress(data) if decompressed: self._first_try = False self._data = None return decompressed except zlib.error: self._first_try = False self._obj = zlib.decompressobj(-zlib.MAX_WBITS) try: return self.decompress(self._data) finally: self._data = None class GzipDecoderState(object): FIRST_MEMBER = 0 OTHER_MEMBERS = 1 SWALLOW_DATA = 2 class GzipDecoder(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) self._state = GzipDecoderState.FIRST_MEMBER def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): ret = bytearray() if self._state == GzipDecoderState.SWALLOW_DATA or not data: return bytes(ret) while True: try: ret += self._obj.decompress(data) except zlib.error: previous_state = self._state # Ignore data after the first error self._state = GzipDecoderState.SWALLOW_DATA if previous_state == GzipDecoderState.OTHER_MEMBERS: # Allow trailing garbage acceptable in other gzip clients return bytes(ret) raise data = self._obj.unused_data if not data: return bytes(ret) self._state = GzipDecoderState.OTHER_MEMBERS self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) if brotli is not None: class BrotliDecoder(object): # Supports both 'brotlipy' and 'Brotli' packages # since they share an import name. The top branches # are for 'brotlipy' and bottom branches for 'Brotli' def __init__(self): self._obj = brotli.Decompressor() def decompress(self, data): if hasattr(self._obj, "decompress"): return self._obj.decompress(data) return self._obj.process(data) def flush(self): if hasattr(self._obj, "flush"): return self._obj.flush() return b"" class MultiDecoder(object): """ From RFC7231: If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied. """ def __init__(self, modes): self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")] def flush(self): return self._decoders[0].flush() def decompress(self, data): for d in reversed(self._decoders): data = d.decompress(data) return data def _get_decoder(mode): if "," in mode: return MultiDecoder(mode) if mode == "gzip": return GzipDecoder() if brotli is not None and mode == "br": return BrotliDecoder() return DeflateDecoder() class HTTPResponse(io.IOBase): """ HTTP Response container. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param original_response: When this HTTPResponse wrapper is generated from an httplib.HTTPResponse object, it's convenient to include the original for debug purposes. It's otherwise unused. :param retries: The retries contains the last :class:`~urllib3.util.retry.Retry` that was used during the request. :param enforce_content_length: Enforce content length checking. Body returned by server must match value of Content-Length header, if present. Otherwise, raise error. """ CONTENT_DECODERS = ["gzip", "deflate"] if brotli is not None: CONTENT_DECODERS += ["br"] REDIRECT_STATUSES = [301, 302, 303, 307, 308] def __init__( self, body="", headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None, msg=None, retries=None, enforce_content_length=False, request_method=None, request_url=None, auto_close=True, ): if isinstance(headers, HTTPHeaderDict): self.headers = headers else: self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason self.strict = strict self.decode_content = decode_content self.retries = retries self.enforce_content_length = enforce_content_length self.auto_close = auto_close self._decoder = None self._body = None self._fp = None self._original_response = original_response self._fp_bytes_read = 0 self.msg = msg self._request_url = request_url if body and isinstance(body, (basestring, bytes)): self._body = body self._pool = pool self._connection = connection if hasattr(body, "read"): self._fp = body # Are we using the chunked-style of transfer encoding? self.chunked = False self.chunk_left = None tr_enc = self.headers.get("transfer-encoding", "").lower() # Don't incur the penalty of creating a list and then discarding it encodings = (enc.strip() for enc in tr_enc.split(",")) if "chunked" in encodings: self.chunked = True # Determine length of response self.length_remaining = self._init_length(request_method) # If requested, preload the body. if preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get("location") return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) @property def connection(self): return self._connection def isclosed(self): return is_fp_closed(self._fp) def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read def _init_length(self, request_method): """ Set initial length value for Response content if available. """ length = self.headers.get("content-length") if length is not None: if self.chunked: # This Response will fail with an IncompleteRead if it can't be # received as chunked. This method falls back to attempt reading # the response before raising an exception. log.warning( "Received response with both Content-Length and " "Transfer-Encoding set. This is expressly forbidden " "by RFC 7230 sec 3.3.2. Ignoring Content-Length and " "attempting to process response as Transfer-Encoding: " "chunked." ) return None try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = set([int(val) for val in length.split(",")]) if len(lengths) > 1: raise InvalidHeader( "Content-Length contained multiple " "unmatching values (%s)" % length ) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None # Convert status to int for comparison # In some cases, httplib returns a status of "_UNKNOWN" try: status = int(self.status) except ValueError: status = 0 # Check for responses that shouldn't include a body if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD": length = 0 return length def _init_decoder(self): """ Set-up the _decoder attribute if necessary. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get("content-encoding", "").lower() if self._decoder is None: if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif "," in content_encoding: encodings = [ e.strip() for e in content_encoding.split(",") if e.strip() in self.CONTENT_DECODERS ] if len(encodings): self._decoder = _get_decoder(content_encoding) DECODER_ERROR_CLASSES = (IOError, zlib.error) if brotli is not None: DECODER_ERROR_CLASSES += (brotli.error,) def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ if not decode_content: return data try: if self._decoder: data = self._decoder.decompress(data) except self.DECODER_ERROR_CLASSES as e: content_encoding = self.headers.get("content-encoding", "").lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e, ) if flush_decoder: data += self._flush_decoder() return data def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b"") return buf + self._decoder.flush() return b"" @contextmanager def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: try: yield except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, "Read timed out.") except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if "read operation timed out" not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, "Read timed out.") except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError("Connection broken: %r" % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn() def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False fp_closed = getattr(self._fp, "closed", False) with self._error_catcher(): if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() if not fp_closed else b"" flush_decoder = True else: cache_content = False data = self._fp.read(amt) if not fp_closed else b"" if ( amt != 0 and not data ): # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True if self.enforce_content_length and self.length_remaining not in ( 0, None, ): # This is an edge case that httplib failed to cover due # to concerns of backward compatibility. We're # addressing it here to make sure IncompleteRead is # raised during streaming, so all calls with incorrect # Content-Length are caught. raise IncompleteRead(self._fp_bytes_read, self.length_remaining) if data: self._fp_bytes_read += len(data) if self.length_remaining is not None: self.length_remaining -= len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data def stream(self, amt=2 ** 16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ if self.chunked and self.supports_chunked_reads(): for line in self.read_chunked(amt, decode_content=decode_content): yield line else: while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: headers = HTTPHeaderDict(headers.items()) else: # Python 2.7 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, "strict", 0) resp = ResponseCls( body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw ) return resp # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default) # Backwards compatibility for http.cookiejar def info(self): return self.headers # Overrides from io.IOBase def close(self): if not self.closed: self._fp.close() if self._connection: self._connection.close() if not self.auto_close: io.IOBase.close(self) @property def closed(self): if not self.auto_close: return io.IOBase.closed.__get__(self) elif self._fp is None: return True elif hasattr(self._fp, "isclosed"): return self._fp.isclosed() elif hasattr(self._fp, "closed"): return self._fp.closed else: return True def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError( "The file-like object this HTTPResponse is wrapped " "around has no file descriptor" ) def flush(self): if ( self._fp is not None and hasattr(self._fp, "flush") and not getattr(self._fp, "closed", False) ): return self._fp.flush() def readable(self): # This method is required for `io` module compatibility. return True def readinto(self, b): # This method is required for `io` module compatibility. temp = self.read(len(b)) if len(temp) == 0: return 0 else: b[: len(temp)] = temp return len(temp) def supports_chunked_reads(self): """ Checks if the underlying file-like object looks like a httplib.HTTPResponse object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked(). """ return hasattr(self._fp, "fp") def _update_chunk_length(self): # First, we'll figure out length of a chunk and then # we'll try to read it from socket. if self.chunk_left is not None: return line = self._fp.fp.readline() line = line.split(b";", 1)[0] try: self.chunk_left = int(line, 16) except ValueError: # Invalid chunked protocol response, abort. self.close() raise httplib.IncompleteRead(line) def _handle_chunk(self, amt): returned_chunk = None if amt is None: chunk = self._fp._safe_read(self.chunk_left) returned_chunk = chunk self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None elif amt < self.chunk_left: value = self._fp._safe_read(amt) self.chunk_left = self.chunk_left - amt returned_chunk = value elif amt == self.chunk_left: value = self._fp._safe_read(amt) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None returned_chunk = value else: # amt > self.chunk_left returned_chunk = self._fp._safe_read(self.chunk_left) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None return returned_chunk def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked( "Response is not chunked. " "Header 'transfer-encoding: chunked' is missing." ) if not self.supports_chunked_reads(): raise BodyNotHttplibCompatible( "Body should be httplib.HTTPResponse like. " "It should have have an fp attribute which returns raw chunks." ) with self._error_catcher(): # Don't bother reading the body of a HEAD request. if self._original_response and is_response_to_head(self._original_response): self._original_response.close() return # If a response is already read and closed # then return immediately. if self._fp.fp is None: return while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) decoded = self._decode( chunk, decode_content=decode_content, flush_decoder=False ) if decoded: yield decoded if decode_content: # On CPython and PyPy, we should never need to flush the # decoder. However, on Jython we *might* need to, so # lets defensively do it anyway. decoded = self._flush_decoder() if decoded: # Platform-specific: Jython. yield decoded # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b"\r\n": break # We read everything; close the "file". if self._original_response: self._original_response.close() def geturl(self): """ Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location. """ if self.retries is not None and len(self.retries.history): return self.retries.history[-1].redirect_location else: return self._request_url def __iter__(self): buffer = [] for chunk in self.stream(decode_content=True): if b"\n" in chunk: chunk = chunk.split(b"\n") yield b"".join(buffer) + chunk[0] + b"\n" for x in chunk[1:-1]: yield x + b"\n" if chunk[-1]: buffer = [chunk[-1]] else: buffer = [] else: buffer.append(chunk) if buffer: yield b"".join(buffer) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3/util/0000755000175000017500000000000000000000000021224 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/__init__.py0000644000175000017500000000201600000000000023334 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import # For backwards compatibility, provide imports that used to be here. from .connection import is_connection_dropped from .request import make_headers from .response import is_fp_closed from .ssl_ import ( SSLContext, HAS_SNI, IS_PYOPENSSL, IS_SECURETRANSPORT, assert_fingerprint, resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, PROTOCOL_TLS, ) from .timeout import current_time, Timeout from .retry import Retry from .url import get_host, parse_url, split_first, Url from .wait import wait_for_read, wait_for_write __all__ = ( "HAS_SNI", "IS_PYOPENSSL", "IS_SECURETRANSPORT", "SSLContext", "PROTOCOL_TLS", "Retry", "Timeout", "Url", "assert_fingerprint", "current_time", "is_connection_dropped", "is_fp_closed", "get_host", "parse_url", "make_headers", "resolve_cert_reqs", "resolve_ssl_version", "split_first", "ssl_wrap_socket", "wait_for_read", "wait_for_write", ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/connection.py0000644000175000017500000001103500000000000023735 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import socket from .wait import NoWayToWaitForSocketError, wait_for_read from ..contrib import _appengine_environ def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, "sock", False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True try: # Returns True if readable, which here means it's been dropped return wait_for_read(sock, timeout=0.0) except NoWayToWaitForSocketError: # Platform-specific: AppEngine return False # This function is copied from socket.py in the Python 2.7 standard # library test suite. Added to its signature is only `socket_options`. # One additional modification is that we avoid binding to IPv6 servers # discovered in DNS if the system doesn't have IPv6 functionality. def create_connection( address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None, ): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith("["): host = host.strip("[]") err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list") def _set_socket_options(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt) def allowed_gai_family(): """This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.""" family = socket.AF_INET if HAS_IPV6: family = socket.AF_UNSPEC return family def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # See https://github.com/urllib3/urllib3/issues/1446 if _appengine_environ.is_appengine_sandbox(): return False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/urllib3/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6 HAS_IPV6 = _has_ipv6("::1") ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/queue.py0000644000175000017500000000076100000000000022726 0ustar00sethmlarsonsethmlarson00000000000000import collections from ..packages import six from ..packages.six.moves import queue if six.PY2: # Queue is imported for side effects on MS Windows. See issue #229. import Queue as _unused_module_Queue # noqa: F401 class LifoQueue(queue.Queue): def _init(self, _): self.queue = collections.deque() def _qsize(self, len=len): return len(self.queue) def _put(self, item): self.queue.append(item) def _get(self): return self.queue.pop() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/request.py0000644000175000017500000000734700000000000023301 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import from base64 import b64encode from ..packages.six import b, integer_types from ..exceptions import UnrewindableBodyError ACCEPT_ENCODING = "gzip,deflate" try: import brotli as _unused_module_brotli # noqa: F401 except ImportError: pass else: ACCEPT_ENCODING += ",br" _FAILEDTELL = object() def make_headers( keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None, ): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ",".join(accept_encoding) else: accept_encoding = ACCEPT_ENCODING headers["accept-encoding"] = accept_encoding if user_agent: headers["user-agent"] = user_agent if keep_alive: headers["connection"] = "keep-alive" if basic_auth: headers["authorization"] = "Basic " + b64encode(b(basic_auth)).decode("utf-8") if proxy_basic_auth: headers["proxy-authorization"] = "Basic " + b64encode( b(proxy_basic_auth) ).decode("utf-8") if disable_cache: headers["cache-control"] = "no-cache" return headers def set_file_position(body, pos): """ If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. """ if pos is not None: rewind_body(body, pos) elif getattr(body, "tell", None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos def rewind_body(body, body_pos): """ Attempt to rewind body to a certain position. Primarily used for request redirects and retries. :param body: File-like object that supports seek. :param int pos: Position to seek to in file. """ body_seek = getattr(body, "seek", None) if body_seek is not None and isinstance(body_pos, integer_types): try: body_seek(body_pos) except (IOError, OSError): raise UnrewindableBodyError( "An error occurred when rewinding request body for redirect/retry." ) elif body_pos is _FAILEDTELL: raise UnrewindableBodyError( "Unable to record file position for rewinding " "request body during a redirect/retry." ) else: raise ValueError( "body_pos must be of type integer, instead it was %s." % type(body_pos) ) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/response.py0000644000175000017500000000501500000000000023435 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import from ..packages.six.moves import http_client as httplib from ..exceptions import HeaderParsingError def is_fp_closed(obj): """ Checks whether a given file-like object is closed. :param obj: The file-like object to check. """ try: # Check `isclosed()` first, in case Python3 doesn't set `closed`. # GH Issue #928 return obj.isclosed() except AttributeError: pass try: # Check via the official file-like-object way. return obj.closed except AttributeError: pass try: # Check if the object is a container for another file-like object that # gets released on exhaustion (e.g. HTTPResponse). return obj.fp is None except AttributeError: pass raise ValueError("Unable to determine whether fp is closed.") def assert_header_parsing(headers): """ Asserts whether all headers have been successfully parsed. Extracts encountered errors from the result of parsing headers. Only works on Python 3. :param headers: Headers to verify. :type headers: `httplib.HTTPMessage`. :raises urllib3.exceptions.HeaderParsingError: If parsing errors are found. """ # This will fail silently if we pass in the wrong kind of parameter. # To make debugging easier add an explicit check. if not isinstance(headers, httplib.HTTPMessage): raise TypeError("expected httplib.Message, got {0}.".format(type(headers))) defects = getattr(headers, "defects", None) get_payload = getattr(headers, "get_payload", None) unparsed_data = None if get_payload: # get_payload is actually email.message.Message.get_payload; # we're only interested in the result if it's not a multipart message if not headers.is_multipart(): payload = get_payload() if isinstance(payload, (bytes, str)): unparsed_data = payload if defects or unparsed_data: raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) def is_response_to_head(response): """ Checks whether the request of a response has been a HEAD-request. Handles the quirks of AppEngine. :param conn: :type conn: :class:`httplib.HTTPResponse` """ # FIXME: Can we do this somehow without accessing private httplib _method? method = response._method if isinstance(method, int): # Platform-specific: Appengine return method == 3 return method.upper() == "HEAD" ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/retry.py0000644000175000017500000003613200000000000022750 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import time import logging from collections import namedtuple from itertools import takewhile import email import re from ..exceptions import ( ConnectTimeoutError, MaxRetryError, ProtocolError, ReadTimeoutError, ResponseError, InvalidHeader, ) from ..packages import six log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple( "RequestHistory", ["method", "url", "error", "status", "redirect_location"] ) class Retry(object): """ Retry configuration. Each retry attempt will create a new Retry object with updated values, so they can be safely reused. Retries can be defined as a default for a pool:: retries = Retry(connect=5, read=2, redirect=5) http = PoolManager(retries=retries) response = http.request('GET', 'http://example.com/') Or per-request (which overrides the default for the pool):: response = http.request('GET', 'http://example.com/', retries=Retry(10)) Retries can be disabled by passing ``False``:: response = http.request('GET', 'http://example.com/', retries=False) Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless retries are disabled, in which case the causing exception will be raised. :param int total: Total number of retries to allow. Takes precedence over other counts. Set to ``None`` to remove this constraint and fall back on other counts. It's a good idea to set this to some sensibly-high value to account for unexpected edge cases and avoid infinite retry loops. Set to ``0`` to fail on the first retry. Set to ``False`` to disable and imply ``raise_on_redirect=False``. :param int connect: How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Set to ``0`` to fail on the first retry of this type. :param int read: How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Set to ``0`` to fail on the first retry of this type. :param int redirect: How many redirects to perform. Limit this to avoid infinite redirect loops. A redirect is a HTTP response with a status code 301, 302, 303, 307 or 308. Set to ``0`` to fail on the first retry of this type. Set to ``False`` to disable and imply ``raise_on_redirect=False``. :param int status: How many times to retry on bad status codes. These are retries made on responses, where status code matches ``status_forcelist``. Set to ``0`` to fail on the first retry of this type. :param iterable method_whitelist: Set of uppercased HTTP method verbs that we should retry on. By default, we only retry on methods which are considered to be idempotent (multiple requests with the same parameters end with the same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`. Set to a ``False`` value to retry on any verb. :param iterable status_forcelist: A set of integer HTTP status codes that we should force a retry on. A retry is initiated if the request method is in ``method_whitelist`` and the response status code is in ``status_forcelist``. By default, this is disabled with ``None``. :param float backoff_factor: A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). urllib3 will sleep for:: {backoff factor} * (2 ** ({number of total retries} - 1)) seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer than :attr:`Retry.BACKOFF_MAX`. By default, backoff is disabled (set to 0). :param bool raise_on_redirect: Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range. :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: whether we should raise an exception, or return a response, if status falls in ``status_forcelist`` range and retries have been exhausted. :param tuple history: The history of the request encountered during each call to :meth:`~Retry.increment`. The list is in the order the requests occurred. Each list item is of class :class:`RequestHistory`. :param bool respect_retry_after_header: Whether to respect Retry-After header on status codes defined as :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. :param iterable remove_headers_on_redirect: Sequence of headers to remove from the request when a response indicating a redirect is returned before firing off the redirected request. """ DEFAULT_METHOD_WHITELIST = frozenset( ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] ) RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) DEFAULT_REDIRECT_HEADERS_BLACKLIST = frozenset(["Authorization"]) #: Maximum backoff time. BACKOFF_MAX = 120 def __init__( self, total=10, connect=None, read=None, redirect=None, status=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True, remove_headers_on_redirect=DEFAULT_REDIRECT_HEADERS_BLACKLIST, ): self.total = total self.connect = connect self.read = read self.status = status if redirect is False or total is False: redirect = 0 raise_on_redirect = False self.redirect = redirect self.status_forcelist = status_forcelist or set() self.method_whitelist = method_whitelist self.backoff_factor = backoff_factor self.raise_on_redirect = raise_on_redirect self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header self.remove_headers_on_redirect = frozenset( [h.lower() for h in remove_headers_on_redirect] ) def new(self, **kw): params = dict( total=self.total, connect=self.connect, read=self.read, redirect=self.redirect, status=self.status, method_whitelist=self.method_whitelist, status_forcelist=self.status_forcelist, backoff_factor=self.backoff_factor, raise_on_redirect=self.raise_on_redirect, raise_on_status=self.raise_on_status, history=self.history, remove_headers_on_redirect=self.remove_headers_on_redirect, respect_retry_after_header=self.respect_retry_after_header, ) params.update(kw) return type(self)(**params) @classmethod def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r", retries, new_retries) return new_retries def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len( list( takewhile(lambda x: x.redirect_location is None, reversed(self.history)) ) ) if consecutive_errors_len <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) return min(self.BACKOFF_MAX, backoff_value) def parse_retry_after(self, retry_after): # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 if re.match(r"^\s*[0-9]+\s*$", retry_after): seconds = int(retry_after) else: retry_date_tuple = email.utils.parsedate(retry_after) if retry_date_tuple is None: raise InvalidHeader("Invalid Retry-After header: %s" % retry_after) retry_date = time.mktime(retry_date_tuple) seconds = retry_date - time.time() if seconds < 0: seconds = 0 return seconds def get_retry_after(self, response): """ Get the value of Retry-After in seconds. """ retry_after = response.getheader("Retry-After") if retry_after is None: return None return self.parse_retry_after(retry_after) def sleep_for_retry(self, response=None): retry_after = self.get_retry_after(response) if retry_after: time.sleep(retry_after) return True return False def _sleep_backoff(self): backoff = self.get_backoff_time() if backoff <= 0: return time.sleep(backoff) def sleep(self, response=None): """ Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. """ if self.respect_retry_after_header and response: slept = self.sleep_for_retry(response) if slept: return self._sleep_backoff() def _is_connection_error(self, err): """ Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ return isinstance(err, ConnectTimeoutError) def _is_read_error(self, err): """ Errors that occur after the request has been started, so we should assume that the server began processing it. """ return isinstance(err, (ReadTimeoutError, ProtocolError)) def _is_method_retryable(self, method): """ Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return True def is_retry(self, method, status_code, has_retry_after=False): """ Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header) """ if not self._is_method_retryable(method): return False if self.status_forcelist and status_code in self.status_forcelist: return True return ( self.total and self.respect_retry_after_header and has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES) ) def is_exhausted(self): """ Are we out of retries? """ retry_counts = (self.total, self.connect, self.read, self.redirect, self.status) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False return min(retry_counts) < 0 def increment( self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None, ): """ Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or None if the response was received successfully. :return: A new ``Retry`` object. """ if self.total is False and error: # Disabled, indicate to re-raise the error. raise six.reraise(type(error), error, _stacktrace) total = self.total if total is not None: total -= 1 connect = self.connect read = self.read redirect = self.redirect status_count = self.status cause = "unknown" status = None redirect_location = None if error and self._is_connection_error(error): # Connect retry? if connect is False: raise six.reraise(type(error), error, _stacktrace) elif connect is not None: connect -= 1 elif error and self._is_read_error(error): # Read retry? if read is False or not self._is_method_retryable(method): raise six.reraise(type(error), error, _stacktrace) elif read is not None: read -= 1 elif response and response.get_redirect_location(): # Redirect retry? if redirect is not None: redirect -= 1 cause = "too many redirects" redirect_location = response.get_redirect_location() status = response.status else: # Incrementing because of a server error like a 500 in # status_forcelist and a the given method is in the whitelist cause = ResponseError.GENERIC_ERROR if response and response.status: if status_count is not None: status_count -= 1 cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status) status = response.status history = self.history + ( RequestHistory(method, url, error, status, redirect_location), ) new_retry = self.new( total=total, connect=connect, read=read, redirect=redirect, status=status_count, history=history, ) if new_retry.is_exhausted(): raise MaxRetryError(_pool, url, error or ResponseError(cause)) log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) return new_retry def __repr__(self): return ( "{cls.__name__}(total={self.total}, connect={self.connect}, " "read={self.read}, redirect={self.redirect}, status={self.status})" ).format(cls=type(self), self=self) # For backwards compatibility (equivalent to pre-v1.9): Retry.DEFAULT = Retry(3) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/ssl_.py0000644000175000017500000003351300000000000022543 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import errno import warnings import hmac import sys from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from .url import IPV4_RE, BRACELESS_IPV6_ADDRZ_RE from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning from ..packages import six SSLContext = None HAS_SNI = False IS_PYOPENSSL = False IS_SECURETRANSPORT = False # Maps the length of a digest to a possible hash function producing this digest HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256} def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for l, r in zip(bytearray(a), bytearray(b)): result |= l ^ r return result == 0 _const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport) try: # Test for SSL features import ssl from ssl import wrap_socket, CERT_REQUIRED from ssl import HAS_SNI # Has SNI? except ImportError: pass try: # Platform-specific: Python 3.6 from ssl import PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: try: from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS PROTOCOL_SSLv23 = PROTOCOL_TLS except ImportError: PROTOCOL_SSLv23 = PROTOCOL_TLS = 2 try: from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION except ImportError: OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000 OP_NO_COMPRESSION = 0x20000 # A secure default. # Sources for more information on TLS ciphers: # # - https://wiki.mozilla.org/Security/Server_Side_TLS # - https://www.ssllabs.com/projects/best-practices/index.html # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ # # The general intent is: # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE), # - prefer ECDHE over DHE for better performance, # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and # security, # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common, # - disable NULL authentication, MD5 MACs, DSS, and other # insecure ciphers for security reasons. # - NOTE: TLS 1.3 cipher suites are managed through a different interface # not exposed by CPython (yet!) and are enabled by default if they're available. DEFAULT_CIPHERS = ":".join( [ "ECDHE+AESGCM", "ECDHE+CHACHA20", "DHE+AESGCM", "DHE+CHACHA20", "ECDH+AESGCM", "DH+AESGCM", "ECDH+AES", "DH+AES", "RSA+AESGCM", "RSA+AES", "!aNULL", "!eNULL", "!MD5", "!DSS", ] ) try: from ssl import SSLContext # Modern SSL? except ImportError: class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version # Use default values from a real SSLContext self.check_hostname = False self.verify_mode = ssl.CERT_NONE self.ca_certs = None self.options = 0 self.certfile = None self.keyfile = None self.ciphers = None def load_cert_chain(self, certfile, keyfile): self.certfile = certfile self.keyfile = keyfile def load_verify_locations(self, cafile=None, capath=None): self.ca_certs = cafile if capath is not None: raise SSLError("CA directories not supported in older Pythons") def set_ciphers(self, cipher_suite): self.ciphers = cipher_suite def wrap_socket(self, socket, server_hostname=None, server_side=False): warnings.warn( "A true SSLContext object is not available. This prevents " "urllib3 from configuring SSL appropriately and may cause " "certain SSL connections to fail. You can upgrade to a newer " "version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" "#ssl-warnings", InsecurePlatformWarning, ) kwargs = { "keyfile": self.keyfile, "certfile": self.certfile, "ca_certs": self.ca_certs, "cert_reqs": self.verify_mode, "ssl_version": self.protocol, "server_side": server_side, } return wrap_socket(socket, ciphers=self.ciphers, **kwargs) def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(":", "").lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError( 'Fingerprints did not match. Expected "{0}", got "{1}".'.format( fingerprint, hexlify(cert_digest) ) ) def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_REQUIRED`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_REQUIRED if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, "CERT_" + candidate) return res return candidate def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_TLS if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, "PROTOCOL_" + candidate) return res return candidate def create_urllib3_context( ssl_version=None, cert_reqs=None, options=None, ciphers=None ): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or PROTOCOL_TLS) context.set_ciphers(ciphers or DEFAULT_CIPHERS) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is # necessary for conditional client cert authentication with TLS 1.3. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older # versions of Python. We only enable on Python 3.7.4+ or if certificate # verification is enabled to work around Python issue #37428 # See: https://bugs.python.org/issue37428 if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr( context, "post_handshake_auth", None ) is not None: context.post_handshake_auth = True context.verify_mode = cert_reqs if ( getattr(context, "check_hostname", None) is not None ): # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir: try: context.load_verify_locations(ca_certs, ca_cert_dir) except IOError as e: # Platform-specific: Python 2.7 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise elif ssl_context is None and hasattr(context, "load_default_certs"): # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 # We shouldn't warn the user if SNI isn't available but we would # not be using SNI anyways due to IP address for server_hostname. if ( server_hostname is not None and not is_ipaddress(server_hostname) ) or IS_SECURETRANSPORT: if HAS_SNI and server_hostname is not None: return context.wrap_socket(sock, server_hostname=server_hostname) warnings.warn( "An HTTPS request has been made, but the SNI (Server Name " "Indication) extension to TLS is not available on this platform. " "This may cause the server to present an incorrect TLS " "certificate, which can cause validation failures. You can upgrade to " "a newer version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/latest/advanced-usage.html" "#ssl-warnings", SNIMissingWarning, ) return context.wrap_socket(sock) def is_ipaddress(hostname): """Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise. """ if not six.PY2 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode("ascii") return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname)) def _is_key_file_encrypted(key_file): """Detects if a key file is encrypted or not.""" with open(key_file, "r") as f: for line in f: # Look for Proc-Type: 4,ENCRYPTED if "ENCRYPTED" in line: return True return False ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/timeout.py0000644000175000017500000002321700000000000023271 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import # The default socket timeout, used by httplib to indicate that no timeout was # specified by the user from socket import _GLOBAL_DEFAULT_TIMEOUT import time from ..exceptions import TimeoutStateError # A sentinel value to indicate that no timeout was specified by the user in # urllib3 _Default = object() # Use time.monotonic if available. current_time = getattr(time, "monotonic", time.time) class Timeout(object): """ Timeout configuration. Timeouts can be defined as a default for a pool:: timeout = Timeout(connect=2.0, read=7.0) http = PoolManager(timeout=timeout) response = http.request('GET', 'http://example.com/') Or per-request (which overrides the default for the pool):: response = http.request('GET', 'http://example.com/', timeout=Timeout(10)) Timeouts can be disabled by setting all the parameters to ``None``:: no_timeout = Timeout(connect=None, read=None) response = http.request('GET', 'http://example.com/, timeout=no_timeout) :param total: This combines the connect and read timeouts into one; the read timeout will be set to the time leftover from the connect attempt. In the event that both a connect timeout and a total are specified, or a read timeout and a total are specified, the shorter timeout will be applied. Defaults to None. :type total: integer, float, or None :param connect: The maximum amount of time (in seconds) to wait for a connection attempt to a server to succeed. Omitting the parameter will default the connect timeout to the system default, probably `the global default timeout in socket.py `_. None will set an infinite timeout for connection attempts. :type connect: integer, float, or None :param read: The maximum amount of time (in seconds) to wait between consecutive read operations for a response from the server. Omitting the parameter will default the read timeout to the system default, probably `the global default timeout in socket.py `_. None will set an infinite timeout. :type read: integer, float, or None .. note:: Many factors can affect the total amount of time for urllib3 to return an HTTP response. For example, Python's DNS resolver does not obey the timeout specified on the socket. Other factors that can affect total request time include high CPU load, high swap, the program running at a low priority level, or other behaviors. In addition, the read and total timeouts only measure the time between read operations on the socket connecting the client and the server, not the total amount of time for the request to return a complete response. For most requests, the timeout is raised because the server has not sent the first byte in the specified time. This is not always the case; if a server streams one byte every fifteen seconds, a timeout of 20 seconds will not trigger, even though the request will take several minutes to complete. If your goal is to cut off any request after a set amount of wall clock time, consider having a second "watcher" thread to cut off a slow request. """ #: A sentinel object representing the default timeout value DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT def __init__(self, total=None, connect=_Default, read=_Default): self._connect = self._validate_timeout(connect, "connect") self._read = self._validate_timeout(read, "read") self.total = self._validate_timeout(total, "total") self._start_connect = None def __str__(self): return "%s(connect=%r, read=%r, total=%r)" % ( type(self).__name__, self._connect, self._read, self.total, ) @classmethod def _validate_timeout(cls, value, name): """ Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it is a numeric value less than or equal to zero, or the type is not an integer, float, or None. """ if value is _Default: return cls.DEFAULT_TIMEOUT if value is None or value is cls.DEFAULT_TIMEOUT: return value if isinstance(value, bool): raise ValueError( "Timeout cannot be a boolean value. It must " "be an int, float or None." ) try: float(value) except (TypeError, ValueError): raise ValueError( "Timeout value %s was %s, but it must be an " "int, float or None." % (name, value) ) try: if value <= 0: raise ValueError( "Attempted to set %s timeout to %s, but the " "timeout cannot be set to a value less " "than or equal to 0." % (name, value) ) except TypeError: # Python 3 raise ValueError( "Timeout value %s was %s, but it must be an " "int, float or None." % (name, value) ) return value @classmethod def from_float(cls, timeout): """ Create a new Timeout from a legacy timeout value. The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value. :type timeout: integer, float, sentinel default object, or None :return: Timeout object :rtype: :class:`Timeout` """ return Timeout(read=timeout, connect=timeout) def clone(self): """ Create a copy of the timeout object Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured. :return: a copy of the timeout object :rtype: :class:`Timeout` """ # We can't use copy.deepcopy because that will also create a new object # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to # detect the user default. return Timeout(connect=self._connect, read=self._read, total=self.total) def start_connect(self): """ Start the timeout clock, used during a connect() attempt :raises urllib3.exceptions.TimeoutStateError: if you attempt to start a timer that has been started already. """ if self._start_connect is not None: raise TimeoutStateError("Timeout timer has already been started.") self._start_connect = current_time() return self._start_connect def get_connect_duration(self): """ Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time in seconds. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn't been started. """ if self._start_connect is None: raise TimeoutStateError( "Can't get connect duration for timer that has not started." ) return current_time() - self._start_connect @property def connect_timeout(self): """ Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None """ if self.total is None: return self._connect if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: return self.total return min(self._connect, self.total) @property def read_timeout(self): """ Get the value for the read timeout. This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately. If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be raised. :return: Value to use for the read timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect` has not yet been called on this object. """ if ( self.total is not None and self.total is not self.DEFAULT_TIMEOUT and self._read is not None and self._read is not self.DEFAULT_TIMEOUT ): # In case the connect timeout has not yet been established. if self._start_connect is None: return self._read return max(0, min(self.total - self.get_connect_duration(), self._read)) elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT: return max(0, self.total - self.get_connect_duration()) else: return self._read ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/url.py0000644000175000017500000003321200000000000022401 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import re from collections import namedtuple from ..exceptions import LocationParseError from ..packages import six url_attrs = ["scheme", "auth", "host", "port", "path", "query", "fragment"] # We only want to normalize urls with an HTTP(S) scheme. # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ("http", "https", None) # Almost all of these patterns were derived from the # 'rfc3986' module: https://github.com/python-hyper/rfc3986 PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}") SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)") URI_RE = re.compile( r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?" r"(?://([^/?#]*))?" r"([^?#]*)" r"(?:\?([^#]*))?" r"(?:#(.*))?$", re.UNICODE | re.DOTALL, ) IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}" HEX_PAT = "[0-9A-Fa-f]{1,4}" LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=HEX_PAT, ipv4=IPV4_PAT) _subs = {"hex": HEX_PAT, "ls32": LS32_PAT} _variations = [ # 6( h16 ":" ) ls32 "(?:%(hex)s:){6}%(ls32)s", # "::" 5( h16 ":" ) ls32 "::(?:%(hex)s:){5}%(ls32)s", # [ h16 ] "::" 4( h16 ":" ) ls32 "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s", # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s", # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s", # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s", # [ *4( h16 ":" ) h16 ] "::" ls32 "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s", # [ *5( h16 ":" ) h16 ] "::" h16 "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s", # [ *6( h16 ":" ) h16 ] "::" "(?:(?:%(hex)s:){0,6}%(hex)s)?::", ] UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._!\-~" IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")" ZONE_ID_PAT = "(?:%25|%)(?:[" + UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+" IPV6_ADDRZ_PAT = r"\[" + IPV6_PAT + r"(?:" + ZONE_ID_PAT + r")?\]" REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*" TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$") IPV4_RE = re.compile("^" + IPV4_PAT + "$") IPV6_RE = re.compile("^" + IPV6_PAT + "$") IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT + "$") BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$") ZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$") SUBAUTHORITY_PAT = (u"^(?:(.*)@)?(%s|%s|%s)(?::([0-9]{0,5}))?$") % ( REG_NAME_PAT, IPV4_PAT, IPV6_ADDRZ_PAT, ) SUBAUTHORITY_RE = re.compile(SUBAUTHORITY_PAT, re.UNICODE | re.DOTALL) UNRESERVED_CHARS = set( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~" ) SUB_DELIM_CHARS = set("!$&'()*+,;=") USERINFO_CHARS = UNRESERVED_CHARS | SUB_DELIM_CHARS | {":"} PATH_CHARS = USERINFO_CHARS | {"@", "/"} QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {"?"} class Url(namedtuple("Url", url_attrs)): """ Data structure for representing an HTTP URL. Used as a return value for :func:`parse_url`. Both the scheme and host are normalized as they are both case-insensitive according to RFC 3986. """ __slots__ = () def __new__( cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None, ): if path and not path.startswith("/"): path = "/" + path if scheme is not None: scheme = scheme.lower() return super(Url, cls).__new__( cls, scheme, auth, host, port, path, query, fragment ) @property def hostname(self): """For backwards-compatibility with urlparse. We're nice like that.""" return self.host @property def request_uri(self): """Absolute path including the query string.""" uri = self.path or "/" if self.query is not None: uri += "?" + self.query return uri @property def netloc(self): """Network location including host and port""" if self.port: return "%s:%d" % (self.host, self.port) return self.host @property def url(self): """ Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url('http://google.com/mail/') >>> U.url 'http://google.com/mail/' >>> Url('http', 'username:password', 'host.com', 80, ... '/path', 'query', 'fragment').url 'http://username:password@host.com:80/path?query#fragment' """ scheme, auth, host, port, path, query, fragment = self url = u"" # We use "is not None" we want things to happen with empty strings (or 0 port) if scheme is not None: url += scheme + u"://" if auth is not None: url += auth + u"@" if host is not None: url += host if port is not None: url += u":" + str(port) if path is not None: url += path if query is not None: url += u"?" + query if fragment is not None: url += u"#" + fragment return url def __str__(self): return self.url def split_first(s, delims): """ .. deprecated:: 1.25 Given a string and an iterable of delimiters, split on the first found delimiter. Return two split parts and the matched delimiter. If not found, then the first part is the full input string. Example:: >>> split_first('foo/bar?baz', '?/=') ('foo', 'bar?baz', '/') >>> split_first('foo/bar?baz', '123') ('foo/bar?baz', '', None) Scales linearly with number of delims. Not ideal for large number of delims. """ min_idx = None min_delim = None for d in delims: idx = s.find(d) if idx < 0: continue if min_idx is None or idx < min_idx: min_idx = idx min_delim = d if min_idx is None or min_idx < 0: return s, "", None return s[:min_idx], s[min_idx + 1 :], min_delim def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"): """Percent-encodes a URI component without reapplying onto an already percent-encoded component. """ if component is None: return component component = six.ensure_text(component) # Normalize existing percent-encoded bytes. # Try to see if the component we're encoding is already percent-encoded # so we can skip all '%' characters but still encode all others. component, percent_encodings = PERCENT_RE.subn( lambda match: match.group(0).upper(), component ) uri_bytes = component.encode("utf-8", "surrogatepass") is_percent_encoded = percent_encodings == uri_bytes.count(b"%") encoded_component = bytearray() for i in range(0, len(uri_bytes)): # Will return a single character bytestring on both Python 2 & 3 byte = uri_bytes[i : i + 1] byte_ord = ord(byte) if (is_percent_encoded and byte == b"%") or ( byte_ord < 128 and byte.decode() in allowed_chars ): encoded_component += byte continue encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper())) return encoded_component.decode(encoding) def _remove_path_dot_segments(path): # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code segments = path.split("/") # Turn the path into a list of segments output = [] # Initialize the variable to use to store output for segment in segments: # '.' is the current directory, so ignore it, it is superfluous if segment == ".": continue # Anything other than '..', should be appended to the output elif segment != "..": output.append(segment) # In this case segment == '..', if we can, we should pop the last # element elif output: output.pop() # If the path starts with '/' and the output is empty or the first string # is non-empty if path.startswith("/") and (not output or output[0]): output.insert(0, "") # If the path starts with '/.' or '/..' ensure we add one more empty # string to add a trailing '/' if path.endswith(("/.", "/..")): output.append("") return "/".join(output) def _normalize_host(host, scheme): if host: if isinstance(host, six.binary_type): host = six.ensure_str(host) if scheme in NORMALIZABLE_SCHEMES: is_ipv6 = IPV6_ADDRZ_RE.match(host) if is_ipv6: match = ZONE_ID_RE.search(host) if match: start, end = match.span(1) zone_id = host[start:end] if zone_id.startswith("%25") and zone_id != "%25": zone_id = zone_id[3:] else: zone_id = zone_id[1:] zone_id = "%" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS) return host[:start].lower() + zone_id + host[end:] else: return host.lower() elif not IPV4_RE.match(host): return six.ensure_str( b".".join([_idna_encode(label) for label in host.split(".")]) ) return host def _idna_encode(name): if name and any([ord(x) > 128 for x in name]): try: import idna except ImportError: six.raise_from( LocationParseError("Unable to parse URL without the 'idna' module"), None, ) try: return idna.encode(name.lower(), strict=True, std3_rules=True) except idna.IDNAError: six.raise_from( LocationParseError(u"Name '%s' is not a valid IDNA label" % name), None ) return name.lower().encode("ascii") def _encode_target(target): """Percent-encodes a request target so that there are no invalid characters""" path, query = TARGET_RE.match(target).groups() target = _encode_invalid_chars(path, PATH_CHARS) query = _encode_invalid_chars(query, QUERY_CHARS) if query is not None: target += "?" + query return target def parse_url(url): """ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 compliant. The parser logic and helper functions are based heavily on work done in the ``rfc3986`` module. :param str url: URL to parse into a :class:`.Url` namedtuple. Partly backwards-compatible with :mod:`urlparse`. Example:: >>> parse_url('http://google.com/mail/') Url(scheme='http', host='google.com', port=None, path='/mail/', ...) >>> parse_url('google.com:80') Url(scheme=None, host='google.com', port=80, path=None, ...) >>> parse_url('/foo?bar') Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...) """ if not url: # Empty return Url() source_url = url if not SCHEME_RE.search(url): url = "//" + url try: scheme, authority, path, query, fragment = URI_RE.match(url).groups() normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES if scheme: scheme = scheme.lower() if authority: auth, host, port = SUBAUTHORITY_RE.match(authority).groups() if auth and normalize_uri: auth = _encode_invalid_chars(auth, USERINFO_CHARS) if port == "": port = None else: auth, host, port = None, None, None if port is not None: port = int(port) if not (0 <= port <= 65535): raise LocationParseError(url) host = _normalize_host(host, scheme) if normalize_uri and path: path = _remove_path_dot_segments(path) path = _encode_invalid_chars(path, PATH_CHARS) if normalize_uri and query: query = _encode_invalid_chars(query, QUERY_CHARS) if normalize_uri and fragment: fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS) except (ValueError, AttributeError): return six.raise_from(LocationParseError(source_url), None) # For the sake of backwards compatibility we put empty # string values for path if there are any defined values # beyond the path in the URL. # TODO: Remove this when we break backwards compatibility. if not path: if query is not None or fragment is not None: path = "" else: path = None # Ensure that each part of the URL is a `str` for # backwards compatibility. if isinstance(url, six.text_type): ensure_func = six.ensure_text else: ensure_func = six.ensure_str def ensure_type(x): return x if x is None else ensure_func(x) return Url( scheme=ensure_type(scheme), auth=ensure_type(auth), host=ensure_type(host), port=port, path=ensure_type(path), query=ensure_type(query), fragment=ensure_type(fragment), ) def get_host(url): """ Deprecated. Use :func:`parse_url` instead. """ p = parse_url(url) return p.scheme or "http", p.hostname, p.port ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/src/urllib3/util/wait.py0000644000175000017500000001243600000000000022550 0ustar00sethmlarsonsethmlarson00000000000000import errno from functools import partial import select import sys try: from time import monotonic except ImportError: from time import time as monotonic __all__ = ["NoWayToWaitForSocketError", "wait_for_read", "wait_for_write"] class NoWayToWaitForSocketError(Exception): pass # How should we wait on sockets? # # There are two types of APIs you can use for waiting on sockets: the fancy # modern stateful APIs like epoll/kqueue, and the older stateless APIs like # select/poll. The stateful APIs are more efficient when you have a lots of # sockets to keep track of, because you can set them up once and then use them # lots of times. But we only ever want to wait on a single socket at a time # and don't want to keep track of state, so the stateless APIs are actually # more efficient. So we want to use select() or poll(). # # Now, how do we choose between select() and poll()? On traditional Unixes, # select() has a strange calling convention that makes it slow, or fail # altogether, for high-numbered file descriptors. The point of poll() is to fix # that, so on Unixes, we prefer poll(). # # On Windows, there is no poll() (or at least Python doesn't provide a wrapper # for it), but that's OK, because on Windows, select() doesn't have this # strange calling convention; plain select() works fine. # # So: on Windows we use select(), and everywhere else we use poll(). We also # fall back to select() in case poll() is somehow broken or missing. if sys.version_info >= (3, 5): # Modern Python, that retries syscalls by default def _retry_on_intr(fn, timeout): return fn(timeout) else: # Old and broken Pythons. def _retry_on_intr(fn, timeout): if timeout is None: deadline = float("inf") else: deadline = monotonic() + timeout while True: try: return fn(timeout) # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7 except (OSError, select.error) as e: # 'e.args[0]' incantation works for both OSError and select.error if e.args[0] != errno.EINTR: raise else: timeout = deadline - monotonic() if timeout < 0: timeout = 0 if timeout == float("inf"): timeout = None continue def select_wait_for_socket(sock, read=False, write=False, timeout=None): if not read and not write: raise RuntimeError("must specify at least one of read=True, write=True") rcheck = [] wcheck = [] if read: rcheck.append(sock) if write: wcheck.append(sock) # When doing a non-blocking connect, most systems signal success by # marking the socket writable. Windows, though, signals success by marked # it as "exceptional". We paper over the difference by checking the write # sockets for both conditions. (The stdlib selectors module does the same # thing.) fn = partial(select.select, rcheck, wcheck, wcheck) rready, wready, xready = _retry_on_intr(fn, timeout) return bool(rready or wready or xready) def poll_wait_for_socket(sock, read=False, write=False, timeout=None): if not read and not write: raise RuntimeError("must specify at least one of read=True, write=True") mask = 0 if read: mask |= select.POLLIN if write: mask |= select.POLLOUT poll_obj = select.poll() poll_obj.register(sock, mask) # For some reason, poll() takes timeout in milliseconds def do_poll(t): if t is not None: t *= 1000 return poll_obj.poll(t) return bool(_retry_on_intr(do_poll, timeout)) def null_wait_for_socket(*args, **kwargs): raise NoWayToWaitForSocketError("no select-equivalent available") def _have_working_poll(): # Apparently some systems have a select.poll that fails as soon as you try # to use it, either due to strange configuration or broken monkeypatching # from libraries like eventlet/greenlet. try: poll_obj = select.poll() _retry_on_intr(poll_obj.poll, 0) except (AttributeError, OSError): return False else: return True def wait_for_socket(*args, **kwargs): # We delay choosing which implementation to use until the first time we're # called. We could do it at import time, but then we might make the wrong # decision if someone goes wild with monkeypatching select.poll after # we're imported. global wait_for_socket if _have_working_poll(): wait_for_socket = poll_wait_for_socket elif hasattr(select, "select"): wait_for_socket = select_wait_for_socket else: # Platform-specific: Appengine. wait_for_socket = null_wait_for_socket return wait_for_socket(*args, **kwargs) def wait_for_read(sock, timeout=None): """ Waits for reading to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired. """ return wait_for_socket(sock, read=True, timeout=timeout) def wait_for_write(sock, timeout=None): """ Waits for writing to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired. """ return wait_for_socket(sock, write=True, timeout=timeout) ././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1579639273.8978639 urllib3-1.25.8/src/urllib3.egg-info/0000755000175000017500000000000000000000000021741 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639273.0 urllib3-1.25.8/src/urllib3.egg-info/PKG-INFO0000644000175000017500000013601400000000000023043 0ustar00sethmlarsonsethmlarson00000000000000Metadata-Version: 2.1 Name: urllib3 Version: 1.25.8 Summary: HTTP library with thread-safe connection pooling, file post, and more. Home-page: https://urllib3.readthedocs.io/ Author: Andrey Petrov Author-email: andrey.petrov@shazow.net License: MIT Project-URL: Documentation, https://urllib3.readthedocs.io/ Project-URL: Code, https://github.com/urllib3/urllib3 Project-URL: Issue tracker, https://github.com/urllib3/urllib3/issues Description: urllib3 ======= urllib3 is a powerful, *sanity-friendly* HTTP client for Python. Much of the Python ecosystem already uses urllib3 and you should too. urllib3 brings many critical features that are missing from the Python standard libraries: - Thread safety. - Connection pooling. - Client-side SSL/TLS verification. - File uploads with multipart encoding. - Helpers for retrying requests and dealing with HTTP redirects. - Support for gzip, deflate, and brotli encoding. - Proxy support for HTTP and SOCKS. - 100% test coverage. urllib3 is powerful and easy to use:: >>> import urllib3 >>> http = urllib3.PoolManager() >>> r = http.request('GET', 'http://httpbin.org/robots.txt') >>> r.status 200 >>> r.data 'User-agent: *\nDisallow: /deny\n' Installing ---------- urllib3 can be installed with `pip `_:: $ pip install urllib3 Alternatively, you can grab the latest source code from `GitHub `_:: $ git clone git://github.com/urllib3/urllib3.git $ python setup.py install Documentation ------------- urllib3 has usage and reference documentation at `urllib3.readthedocs.io `_. Contributing ------------ urllib3 happily accepts contributions. Please see our `contributing documentation `_ for some tips on getting started. Security Disclosures -------------------- To report a security vulnerability, please use the `Tidelift security contact `_. Tidelift will coordinate the fix and disclosure with maintainers. Maintainers ----------- - `@sethmlarson `_ (Seth M. Larson) - `@pquentin `_ (Quentin Pradet) - `@theacodes `_ (Thea Flowers) - `@haikuginger `_ (Jess Shapiro) - `@lukasa `_ (Cory Benfield) - `@sigmavirus24 `_ (Ian Stapleton Cordasco) - `@shazow `_ (Andrey Petrov) 👋 Sponsorship ----------- .. |tideliftlogo| image:: https://nedbatchelder.com/pix/Tidelift_Logos_RGB_Tidelift_Shorthand_On-White_small.png :width: 75 :alt: Tidelift .. list-table:: :widths: 10 100 * - |tideliftlogo| - Professional support for urllib3 is available as part of the `Tidelift Subscription`_. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools. .. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-urllib3?utm_source=pypi-urllib3&utm_medium=referral&utm_campaign=readme If your company benefits from this library, please consider `sponsoring its development `_. Sponsors include: - Abbott (2018-2019), sponsored `@sethmlarson `_'s work on urllib3. - Google Cloud Platform (2018-2019), sponsored `@theacodes `_'s work on urllib3. - Akamai (2017-2018), sponsored `@haikuginger `_'s work on urllib3 - Hewlett Packard Enterprise (2016-2017), sponsored `@Lukasa’s `_ work on urllib3. Changes ======= 1.25.8 (2020-01-20) ------------------- * Drop support for EOL Python 3.4 (Pull #1774) * Optimize _encode_invalid_chars (Pull #1787) 1.25.7 (2019-11-11) ------------------- * Preserve ``chunked`` parameter on retries (Pull #1715, Pull #1734) * Allow unset ``SERVER_SOFTWARE`` in App Engine (Pull #1704, Issue #1470) * Fix issue where URL fragment was sent within the request target. (Pull #1732) * Fix issue where an empty query section in a URL would fail to parse. (Pull #1732) * Remove TLS 1.3 support in SecureTransport due to Apple removing support (Pull #1703) 1.25.6 (2019-09-24) ------------------- * Fix issue where tilde (``~``) characters were incorrectly percent-encoded in the path. (Pull #1692) 1.25.5 (2019-09-19) ------------------- * Add mitigation for BPO-37428 affecting Python <3.7.4 and OpenSSL 1.1.1+ which caused certificate verification to be enabled when using ``cert_reqs=CERT_NONE``. (Issue #1682) 1.25.4 (2019-09-19) ------------------- * Propagate Retry-After header settings to subsequent retries. (Pull #1607) * Fix edge case where Retry-After header was still respected even when explicitly opted out of. (Pull #1607) * Remove dependency on ``rfc3986`` for URL parsing. * Fix issue where URLs containing invalid characters within ``Url.auth`` would raise an exception instead of percent-encoding those characters. * Add support for ``HTTPResponse.auto_close = False`` which makes HTTP responses work well with BufferedReaders and other ``io`` module features. (Pull #1652) * Percent-encode invalid characters in URL for ``HTTPConnectionPool.request()`` (Pull #1673) 1.25.3 (2019-05-23) ------------------- * Change ``HTTPSConnection`` to load system CA certificates when ``ca_certs``, ``ca_cert_dir``, and ``ssl_context`` are unspecified. (Pull #1608, Issue #1603) * Upgrade bundled rfc3986 to v1.3.2. (Pull #1609, Issue #1605) 1.25.2 (2019-04-28) ------------------- * Change ``is_ipaddress`` to not detect IPvFuture addresses. (Pull #1583) * Change ``parse_url`` to percent-encode invalid characters within the path, query, and target components. (Pull #1586) 1.25.1 (2019-04-24) ------------------- * Add support for Google's ``Brotli`` package. (Pull #1572, Pull #1579) * Upgrade bundled rfc3986 to v1.3.1 (Pull #1578) 1.25 (2019-04-22) ----------------- * Require and validate certificates by default when using HTTPS (Pull #1507) * Upgraded ``urllib3.utils.parse_url()`` to be RFC 3986 compliant. (Pull #1487) * Added support for ``key_password`` for ``HTTPSConnectionPool`` to use encrypted ``key_file`` without creating your own ``SSLContext`` object. (Pull #1489) * Add TLSv1.3 support to CPython, pyOpenSSL, and SecureTransport ``SSLContext`` implementations. (Pull #1496) * Switched the default multipart header encoder from RFC 2231 to HTML 5 working draft. (Issue #303, PR #1492) * Fixed issue where OpenSSL would block if an encrypted client private key was given and no password was given. Instead an ``SSLError`` is raised. (Pull #1489) * Added support for Brotli content encoding. It is enabled automatically if ``brotlipy`` package is installed which can be requested with ``urllib3[brotli]`` extra. (Pull #1532) * Drop ciphers using DSS key exchange from default TLS cipher suites. Improve default ciphers when using SecureTransport. (Pull #1496) * Implemented a more efficient ``HTTPResponse.__iter__()`` method. (Issue #1483) 1.24.3 (2019-05-01) ------------------- * Apply fix for CVE-2019-9740. (Pull #1591) 1.24.2 (2019-04-17) ------------------- * Don't load system certificates by default when any other ``ca_certs``, ``ca_certs_dir`` or ``ssl_context`` parameters are specified. * Remove Authorization header regardless of case when redirecting to cross-site. (Issue #1510) * Add support for IPv6 addresses in subjectAltName section of certificates. (Issue #1269) 1.24.1 (2018-11-02) ------------------- * Remove quadratic behavior within ``GzipDecoder.decompress()`` (Issue #1467) * Restored functionality of ``ciphers`` parameter for ``create_urllib3_context()``. (Issue #1462) 1.24 (2018-10-16) ----------------- * Allow key_server_hostname to be specified when initializing a PoolManager to allow custom SNI to be overridden. (Pull #1449) * Test against Python 3.7 on AppVeyor. (Pull #1453) * Early-out ipv6 checks when running on App Engine. (Pull #1450) * Change ambiguous description of backoff_factor (Pull #1436) * Add ability to handle multiple Content-Encodings (Issue #1441 and Pull #1442) * Skip DNS names that can't be idna-decoded when using pyOpenSSL (Issue #1405). * Add a server_hostname parameter to HTTPSConnection which allows for overriding the SNI hostname sent in the handshake. (Pull #1397) * Drop support for EOL Python 2.6 (Pull #1429 and Pull #1430) * Fixed bug where responses with header Content-Type: message/* erroneously raised HeaderParsingError, resulting in a warning being logged. (Pull #1439) * Move urllib3 to src/urllib3 (Pull #1409) 1.23 (2018-06-04) ----------------- * Allow providing a list of headers to strip from requests when redirecting to a different host. Defaults to the ``Authorization`` header. Different headers can be set via ``Retry.remove_headers_on_redirect``. (Issue #1316) * Fix ``util.selectors._fileobj_to_fd`` to accept ``long`` (Issue #1247). * Dropped Python 3.3 support. (Pull #1242) * Put the connection back in the pool when calling stream() or read_chunked() on a chunked HEAD response. (Issue #1234) * Fixed pyOpenSSL-specific ssl client authentication issue when clients attempted to auth via certificate + chain (Issue #1060) * Add the port to the connectionpool connect print (Pull #1251) * Don't use the ``uuid`` module to create multipart data boundaries. (Pull #1380) * ``read_chunked()`` on a closed response returns no chunks. (Issue #1088) * Add Python 2.6 support to ``contrib.securetransport`` (Pull #1359) * Added support for auth info in url for SOCKS proxy (Pull #1363) 1.22 (2017-07-20) ----------------- * Fixed missing brackets in ``HTTP CONNECT`` when connecting to IPv6 address via IPv6 proxy. (Issue #1222) * Made the connection pool retry on ``SSLError``. The original ``SSLError`` is available on ``MaxRetryError.reason``. (Issue #1112) * Drain and release connection before recursing on retry/redirect. Fixes deadlocks with a blocking connectionpool. (Issue #1167) * Fixed compatibility for cookiejar. (Issue #1229) * pyopenssl: Use vendored version of ``six``. (Issue #1231) 1.21.1 (2017-05-02) ------------------- * Fixed SecureTransport issue that would cause long delays in response body delivery. (Pull #1154) * Fixed regression in 1.21 that threw exceptions when users passed the ``socket_options`` flag to the ``PoolManager``. (Issue #1165) * Fixed regression in 1.21 that threw exceptions when users passed the ``assert_hostname`` or ``assert_fingerprint`` flag to the ``PoolManager``. (Pull #1157) 1.21 (2017-04-25) ----------------- * Improved performance of certain selector system calls on Python 3.5 and later. (Pull #1095) * Resolved issue where the PyOpenSSL backend would not wrap SysCallError exceptions appropriately when sending data. (Pull #1125) * Selectors now detects a monkey-patched select module after import for modules that patch the select module like eventlet, greenlet. (Pull #1128) * Reduced memory consumption when streaming zlib-compressed responses (as opposed to raw deflate streams). (Pull #1129) * Connection pools now use the entire request context when constructing the pool key. (Pull #1016) * ``PoolManager.connection_from_*`` methods now accept a new keyword argument, ``pool_kwargs``, which are merged with the existing ``connection_pool_kw``. (Pull #1016) * Add retry counter for ``status_forcelist``. (Issue #1147) * Added ``contrib`` module for using SecureTransport on macOS: ``urllib3.contrib.securetransport``. (Pull #1122) * urllib3 now only normalizes the case of ``http://`` and ``https://`` schemes: for schemes it does not recognise, it assumes they are case-sensitive and leaves them unchanged. (Issue #1080) 1.20 (2017-01-19) ----------------- * Added support for waiting for I/O using selectors other than select, improving urllib3's behaviour with large numbers of concurrent connections. (Pull #1001) * Updated the date for the system clock check. (Issue #1005) * ConnectionPools now correctly consider hostnames to be case-insensitive. (Issue #1032) * Outdated versions of PyOpenSSL now cause the PyOpenSSL contrib module to fail when it is injected, rather than at first use. (Pull #1063) * Outdated versions of cryptography now cause the PyOpenSSL contrib module to fail when it is injected, rather than at first use. (Issue #1044) * Automatically attempt to rewind a file-like body object when a request is retried or redirected. (Pull #1039) * Fix some bugs that occur when modules incautiously patch the queue module. (Pull #1061) * Prevent retries from occurring on read timeouts for which the request method was not in the method whitelist. (Issue #1059) * Changed the PyOpenSSL contrib module to lazily load idna to avoid unnecessarily bloating the memory of programs that don't need it. (Pull #1076) * Add support for IPv6 literals with zone identifiers. (Pull #1013) * Added support for socks5h:// and socks4a:// schemes when working with SOCKS proxies, and controlled remote DNS appropriately. (Issue #1035) 1.19.1 (2016-11-16) ------------------- * Fixed AppEngine import that didn't function on Python 3.5. (Pull #1025) 1.19 (2016-11-03) ----------------- * urllib3 now respects Retry-After headers on 413, 429, and 503 responses when using the default retry logic. (Pull #955) * Remove markers from setup.py to assist ancient setuptools versions. (Issue #986) * Disallow superscripts and other integerish things in URL ports. (Issue #989) * Allow urllib3's HTTPResponse.stream() method to continue to work with non-httplib underlying FPs. (Pull #990) * Empty filenames in multipart headers are now emitted as such, rather than being suppressed. (Issue #1015) * Prefer user-supplied Host headers on chunked uploads. (Issue #1009) 1.18.1 (2016-10-27) ------------------- * CVE-2016-9015. Users who are using urllib3 version 1.17 or 1.18 along with PyOpenSSL injection and OpenSSL 1.1.0 *must* upgrade to this version. This release fixes a vulnerability whereby urllib3 in the above configuration would silently fail to validate TLS certificates due to erroneously setting invalid flags in OpenSSL's ``SSL_CTX_set_verify`` function. These erroneous flags do not cause a problem in OpenSSL versions before 1.1.0, which interprets the presence of any flag as requesting certificate validation. There is no PR for this patch, as it was prepared for simultaneous disclosure and release. The master branch received the same fix in PR #1010. 1.18 (2016-09-26) ----------------- * Fixed incorrect message for IncompleteRead exception. (PR #973) * Accept ``iPAddress`` subject alternative name fields in TLS certificates. (Issue #258) * Fixed consistency of ``HTTPResponse.closed`` between Python 2 and 3. (Issue #977) * Fixed handling of wildcard certificates when using PyOpenSSL. (Issue #979) 1.17 (2016-09-06) ----------------- * Accept ``SSLContext`` objects for use in SSL/TLS negotiation. (Issue #835) * ConnectionPool debug log now includes scheme, host, and port. (Issue #897) * Substantially refactored documentation. (Issue #887) * Used URLFetch default timeout on AppEngine, rather than hardcoding our own. (Issue #858) * Normalize the scheme and host in the URL parser (Issue #833) * ``HTTPResponse`` contains the last ``Retry`` object, which now also contains retries history. (Issue #848) * Timeout can no longer be set as boolean, and must be greater than zero. (PR #924) * Removed pyasn1 and ndg-httpsclient from dependencies used for PyOpenSSL. We now use cryptography and idna, both of which are already dependencies of PyOpenSSL. (PR #930) * Fixed infinite loop in ``stream`` when amt=None. (Issue #928) * Try to use the operating system's certificates when we are using an ``SSLContext``. (PR #941) * Updated cipher suite list to allow ChaCha20+Poly1305. AES-GCM is preferred to ChaCha20, but ChaCha20 is then preferred to everything else. (PR #947) * Updated cipher suite list to remove 3DES-based cipher suites. (PR #958) * Removed the cipher suite fallback to allow HIGH ciphers. (PR #958) * Implemented ``length_remaining`` to determine remaining content to be read. (PR #949) * Implemented ``enforce_content_length`` to enable exceptions when incomplete data chunks are received. (PR #949) * Dropped connection start, dropped connection reset, redirect, forced retry, and new HTTPS connection log levels to DEBUG, from INFO. (PR #967) 1.16 (2016-06-11) ----------------- * Disable IPv6 DNS when IPv6 connections are not possible. (Issue #840) * Provide ``key_fn_by_scheme`` pool keying mechanism that can be overridden. (Issue #830) * Normalize scheme and host to lowercase for pool keys, and include ``source_address``. (Issue #830) * Cleaner exception chain in Python 3 for ``_make_request``. (Issue #861) * Fixed installing ``urllib3[socks]`` extra. (Issue #864) * Fixed signature of ``ConnectionPool.close`` so it can actually safely be called by subclasses. (Issue #873) * Retain ``release_conn`` state across retries. (Issues #651, #866) * Add customizable ``HTTPConnectionPool.ResponseCls``, which defaults to ``HTTPResponse`` but can be replaced with a subclass. (Issue #879) 1.15.1 (2016-04-11) ------------------- * Fix packaging to include backports module. (Issue #841) 1.15 (2016-04-06) ----------------- * Added Retry(raise_on_status=False). (Issue #720) * Always use setuptools, no more distutils fallback. (Issue #785) * Dropped support for Python 3.2. (Issue #786) * Chunked transfer encoding when requesting with ``chunked=True``. (Issue #790) * Fixed regression with IPv6 port parsing. (Issue #801) * Append SNIMissingWarning messages to allow users to specify it in the PYTHONWARNINGS environment variable. (Issue #816) * Handle unicode headers in Py2. (Issue #818) * Log certificate when there is a hostname mismatch. (Issue #820) * Preserve order of request/response headers. (Issue #821) 1.14 (2015-12-29) ----------------- * contrib: SOCKS proxy support! (Issue #762) * Fixed AppEngine handling of transfer-encoding header and bug in Timeout defaults checking. (Issue #763) 1.13.1 (2015-12-18) ------------------- * Fixed regression in IPv6 + SSL for match_hostname. (Issue #761) 1.13 (2015-12-14) ----------------- * Fixed ``pip install urllib3[secure]`` on modern pip. (Issue #706) * pyopenssl: Fixed SSL3_WRITE_PENDING error. (Issue #717) * pyopenssl: Support for TLSv1.1 and TLSv1.2. (Issue #696) * Close connections more defensively on exception. (Issue #734) * Adjusted ``read_chunked`` to handle gzipped, chunk-encoded bodies without repeatedly flushing the decoder, to function better on Jython. (Issue #743) * Accept ``ca_cert_dir`` for SSL-related PoolManager configuration. (Issue #758) 1.12 (2015-09-03) ----------------- * Rely on ``six`` for importing ``httplib`` to work around conflicts with other Python 3 shims. (Issue #688) * Add support for directories of certificate authorities, as supported by OpenSSL. (Issue #701) * New exception: ``NewConnectionError``, raised when we fail to establish a new connection, usually ``ECONNREFUSED`` socket error. 1.11 (2015-07-21) ----------------- * When ``ca_certs`` is given, ``cert_reqs`` defaults to ``'CERT_REQUIRED'``. (Issue #650) * ``pip install urllib3[secure]`` will install Certifi and PyOpenSSL as dependencies. (Issue #678) * Made ``HTTPHeaderDict`` usable as a ``headers`` input value (Issues #632, #679) * Added `urllib3.contrib.appengine `_ which has an ``AppEngineManager`` for using ``URLFetch`` in a Google AppEngine environment. (Issue #664) * Dev: Added test suite for AppEngine. (Issue #631) * Fix performance regression when using PyOpenSSL. (Issue #626) * Passing incorrect scheme (e.g. ``foo://``) will raise ``ValueError`` instead of ``AssertionError`` (backwards compatible for now, but please migrate). (Issue #640) * Fix pools not getting replenished when an error occurs during a request using ``release_conn=False``. (Issue #644) * Fix pool-default headers not applying for url-encoded requests like GET. (Issue #657) * log.warning in Python 3 when headers are skipped due to parsing errors. (Issue #642) * Close and discard connections if an error occurs during read. (Issue #660) * Fix host parsing for IPv6 proxies. (Issue #668) * Separate warning type SubjectAltNameWarning, now issued once per host. (Issue #671) * Fix ``httplib.IncompleteRead`` not getting converted to ``ProtocolError`` when using ``HTTPResponse.stream()`` (Issue #674) 1.10.4 (2015-05-03) ------------------- * Migrate tests to Tornado 4. (Issue #594) * Append default warning configuration rather than overwrite. (Issue #603) * Fix streaming decoding regression. (Issue #595) * Fix chunked requests losing state across keep-alive connections. (Issue #599) * Fix hanging when chunked HEAD response has no body. (Issue #605) 1.10.3 (2015-04-21) ------------------- * Emit ``InsecurePlatformWarning`` when SSLContext object is missing. (Issue #558) * Fix regression of duplicate header keys being discarded. (Issue #563) * ``Response.stream()`` returns a generator for chunked responses. (Issue #560) * Set upper-bound timeout when waiting for a socket in PyOpenSSL. (Issue #585) * Work on platforms without `ssl` module for plain HTTP requests. (Issue #587) * Stop relying on the stdlib's default cipher list. (Issue #588) 1.10.2 (2015-02-25) ------------------- * Fix file descriptor leakage on retries. (Issue #548) * Removed RC4 from default cipher list. (Issue #551) * Header performance improvements. (Issue #544) * Fix PoolManager not obeying redirect retry settings. (Issue #553) 1.10.1 (2015-02-10) ------------------- * Pools can be used as context managers. (Issue #545) * Don't re-use connections which experienced an SSLError. (Issue #529) * Don't fail when gzip decoding an empty stream. (Issue #535) * Add sha256 support for fingerprint verification. (Issue #540) * Fixed handling of header values containing commas. (Issue #533) 1.10 (2014-12-14) ----------------- * Disabled SSLv3. (Issue #473) * Add ``Url.url`` property to return the composed url string. (Issue #394) * Fixed PyOpenSSL + gevent ``WantWriteError``. (Issue #412) * ``MaxRetryError.reason`` will always be an exception, not string. (Issue #481) * Fixed SSL-related timeouts not being detected as timeouts. (Issue #492) * Py3: Use ``ssl.create_default_context()`` when available. (Issue #473) * Emit ``InsecureRequestWarning`` for *every* insecure HTTPS request. (Issue #496) * Emit ``SecurityWarning`` when certificate has no ``subjectAltName``. (Issue #499) * Close and discard sockets which experienced SSL-related errors. (Issue #501) * Handle ``body`` param in ``.request(...)``. (Issue #513) * Respect timeout with HTTPS proxy. (Issue #505) * PyOpenSSL: Handle ZeroReturnError exception. (Issue #520) 1.9.1 (2014-09-13) ------------------ * Apply socket arguments before binding. (Issue #427) * More careful checks if fp-like object is closed. (Issue #435) * Fixed packaging issues of some development-related files not getting included. (Issue #440) * Allow performing *only* fingerprint verification. (Issue #444) * Emit ``SecurityWarning`` if system clock is waaay off. (Issue #445) * Fixed PyOpenSSL compatibility with PyPy. (Issue #450) * Fixed ``BrokenPipeError`` and ``ConnectionError`` handling in Py3. (Issue #443) 1.9 (2014-07-04) ---------------- * Shuffled around development-related files. If you're maintaining a distro package of urllib3, you may need to tweak things. (Issue #415) * Unverified HTTPS requests will trigger a warning on the first request. See our new `security documentation `_ for details. (Issue #426) * New retry logic and ``urllib3.util.retry.Retry`` configuration object. (Issue #326) * All raised exceptions should now wrapped in a ``urllib3.exceptions.HTTPException``-extending exception. (Issue #326) * All errors during a retry-enabled request should be wrapped in ``urllib3.exceptions.MaxRetryError``, including timeout-related exceptions which were previously exempt. Underlying error is accessible from the ``.reason`` property. (Issue #326) * ``urllib3.exceptions.ConnectionError`` renamed to ``urllib3.exceptions.ProtocolError``. (Issue #326) * Errors during response read (such as IncompleteRead) are now wrapped in ``urllib3.exceptions.ProtocolError``. (Issue #418) * Requesting an empty host will raise ``urllib3.exceptions.LocationValueError``. (Issue #417) * Catch read timeouts over SSL connections as ``urllib3.exceptions.ReadTimeoutError``. (Issue #419) * Apply socket arguments before connecting. (Issue #427) 1.8.3 (2014-06-23) ------------------ * Fix TLS verification when using a proxy in Python 3.4.1. (Issue #385) * Add ``disable_cache`` option to ``urllib3.util.make_headers``. (Issue #393) * Wrap ``socket.timeout`` exception with ``urllib3.exceptions.ReadTimeoutError``. (Issue #399) * Fixed proxy-related bug where connections were being reused incorrectly. (Issues #366, #369) * Added ``socket_options`` keyword parameter which allows to define ``setsockopt`` configuration of new sockets. (Issue #397) * Removed ``HTTPConnection.tcp_nodelay`` in favor of ``HTTPConnection.default_socket_options``. (Issue #397) * Fixed ``TypeError`` bug in Python 2.6.4. (Issue #411) 1.8.2 (2014-04-17) ------------------ * Fix ``urllib3.util`` not being included in the package. 1.8.1 (2014-04-17) ------------------ * Fix AppEngine bug of HTTPS requests going out as HTTP. (Issue #356) * Don't install ``dummyserver`` into ``site-packages`` as it's only needed for the test suite. (Issue #362) * Added support for specifying ``source_address``. (Issue #352) 1.8 (2014-03-04) ---------------- * Improved url parsing in ``urllib3.util.parse_url`` (properly parse '@' in username, and blank ports like 'hostname:'). * New ``urllib3.connection`` module which contains all the HTTPConnection objects. * Several ``urllib3.util.Timeout``-related fixes. Also changed constructor signature to a more sensible order. [Backwards incompatible] (Issues #252, #262, #263) * Use ``backports.ssl_match_hostname`` if it's installed. (Issue #274) * Added ``.tell()`` method to ``urllib3.response.HTTPResponse`` which returns the number of bytes read so far. (Issue #277) * Support for platforms without threading. (Issue #289) * Expand default-port comparison in ``HTTPConnectionPool.is_same_host`` to allow a pool with no specified port to be considered equal to to an HTTP/HTTPS url with port 80/443 explicitly provided. (Issue #305) * Improved default SSL/TLS settings to avoid vulnerabilities. (Issue #309) * Fixed ``urllib3.poolmanager.ProxyManager`` not retrying on connect errors. (Issue #310) * Disable Nagle's Algorithm on the socket for non-proxies. A subset of requests will send the entire HTTP request ~200 milliseconds faster; however, some of the resulting TCP packets will be smaller. (Issue #254) * Increased maximum number of SubjectAltNames in ``urllib3.contrib.pyopenssl`` from the default 64 to 1024 in a single certificate. (Issue #318) * Headers are now passed and stored as a custom ``urllib3.collections_.HTTPHeaderDict`` object rather than a plain ``dict``. (Issue #329, #333) * Headers no longer lose their case on Python 3. (Issue #236) * ``urllib3.contrib.pyopenssl`` now uses the operating system's default CA certificates on inject. (Issue #332) * Requests with ``retries=False`` will immediately raise any exceptions without wrapping them in ``MaxRetryError``. (Issue #348) * Fixed open socket leak with SSL-related failures. (Issue #344, #348) 1.7.1 (2013-09-25) ------------------ * Added granular timeout support with new ``urllib3.util.Timeout`` class. (Issue #231) * Fixed Python 3.4 support. (Issue #238) 1.7 (2013-08-14) ---------------- * More exceptions are now pickle-able, with tests. (Issue #174) * Fixed redirecting with relative URLs in Location header. (Issue #178) * Support for relative urls in ``Location: ...`` header. (Issue #179) * ``urllib3.response.HTTPResponse`` now inherits from ``io.IOBase`` for bonus file-like functionality. (Issue #187) * Passing ``assert_hostname=False`` when creating a HTTPSConnectionPool will skip hostname verification for SSL connections. (Issue #194) * New method ``urllib3.response.HTTPResponse.stream(...)`` which acts as a generator wrapped around ``.read(...)``. (Issue #198) * IPv6 url parsing enforces brackets around the hostname. (Issue #199) * Fixed thread race condition in ``urllib3.poolmanager.PoolManager.connection_from_host(...)`` (Issue #204) * ``ProxyManager`` requests now include non-default port in ``Host: ...`` header. (Issue #217) * Added HTTPS proxy support in ``ProxyManager``. (Issue #170 #139) * New ``RequestField`` object can be passed to the ``fields=...`` param which can specify headers. (Issue #220) * Raise ``urllib3.exceptions.ProxyError`` when connecting to proxy fails. (Issue #221) * Use international headers when posting file names. (Issue #119) * Improved IPv6 support. (Issue #203) 1.6 (2013-04-25) ---------------- * Contrib: Optional SNI support for Py2 using PyOpenSSL. (Issue #156) * ``ProxyManager`` automatically adds ``Host: ...`` header if not given. * Improved SSL-related code. ``cert_req`` now optionally takes a string like "REQUIRED" or "NONE". Same with ``ssl_version`` takes strings like "SSLv23" The string values reflect the suffix of the respective constant variable. (Issue #130) * Vendored ``socksipy`` now based on Anorov's fork which handles unexpectedly closed proxy connections and larger read buffers. (Issue #135) * Ensure the connection is closed if no data is received, fixes connection leak on some platforms. (Issue #133) * Added SNI support for SSL/TLS connections on Py32+. (Issue #89) * Tests fixed to be compatible with Py26 again. (Issue #125) * Added ability to choose SSL version by passing an ``ssl.PROTOCOL_*`` constant to the ``ssl_version`` parameter of ``HTTPSConnectionPool``. (Issue #109) * Allow an explicit content type to be specified when encoding file fields. (Issue #126) * Exceptions are now pickleable, with tests. (Issue #101) * Fixed default headers not getting passed in some cases. (Issue #99) * Treat "content-encoding" header value as case-insensitive, per RFC 2616 Section 3.5. (Issue #110) * "Connection Refused" SocketErrors will get retried rather than raised. (Issue #92) * Updated vendored ``six``, no longer overrides the global ``six`` module namespace. (Issue #113) * ``urllib3.exceptions.MaxRetryError`` contains a ``reason`` property holding the exception that prompted the final retry. If ``reason is None`` then it was due to a redirect. (Issue #92, #114) * Fixed ``PoolManager.urlopen()`` from not redirecting more than once. (Issue #149) * Don't assume ``Content-Type: text/plain`` for multi-part encoding parameters that are not files. (Issue #111) * Pass `strict` param down to ``httplib.HTTPConnection``. (Issue #122) * Added mechanism to verify SSL certificates by fingerprint (md5, sha1) or against an arbitrary hostname (when connecting by IP or for misconfigured servers). (Issue #140) * Streaming decompression support. (Issue #159) 1.5 (2012-08-02) ---------------- * Added ``urllib3.add_stderr_logger()`` for quickly enabling STDERR debug logging in urllib3. * Native full URL parsing (including auth, path, query, fragment) available in ``urllib3.util.parse_url(url)``. * Built-in redirect will switch method to 'GET' if status code is 303. (Issue #11) * ``urllib3.PoolManager`` strips the scheme and host before sending the request uri. (Issue #8) * New ``urllib3.exceptions.DecodeError`` exception for when automatic decoding, based on the Content-Type header, fails. * Fixed bug with pool depletion and leaking connections (Issue #76). Added explicit connection closing on pool eviction. Added ``urllib3.PoolManager.clear()``. * 99% -> 100% unit test coverage. 1.4 (2012-06-16) ---------------- * Minor AppEngine-related fixes. * Switched from ``mimetools.choose_boundary`` to ``uuid.uuid4()``. * Improved url parsing. (Issue #73) * IPv6 url support. (Issue #72) 1.3 (2012-03-25) ---------------- * Removed pre-1.0 deprecated API. * Refactored helpers into a ``urllib3.util`` submodule. * Fixed multipart encoding to support list-of-tuples for keys with multiple values. (Issue #48) * Fixed multiple Set-Cookie headers in response not getting merged properly in Python 3. (Issue #53) * AppEngine support with Py27. (Issue #61) * Minor ``encode_multipart_formdata`` fixes related to Python 3 strings vs bytes. 1.2.2 (2012-02-06) ------------------ * Fixed packaging bug of not shipping ``test-requirements.txt``. (Issue #47) 1.2.1 (2012-02-05) ------------------ * Fixed another bug related to when ``ssl`` module is not available. (Issue #41) * Location parsing errors now raise ``urllib3.exceptions.LocationParseError`` which inherits from ``ValueError``. 1.2 (2012-01-29) ---------------- * Added Python 3 support (tested on 3.2.2) * Dropped Python 2.5 support (tested on 2.6.7, 2.7.2) * Use ``select.poll`` instead of ``select.select`` for platforms that support it. * Use ``Queue.LifoQueue`` instead of ``Queue.Queue`` for more aggressive connection reusing. Configurable by overriding ``ConnectionPool.QueueCls``. * Fixed ``ImportError`` during install when ``ssl`` module is not available. (Issue #41) * Fixed ``PoolManager`` redirects between schemes (such as HTTP -> HTTPS) not completing properly. (Issue #28, uncovered by Issue #10 in v1.1) * Ported ``dummyserver`` to use ``tornado`` instead of ``webob`` + ``eventlet``. Removed extraneous unsupported dummyserver testing backends. Added socket-level tests. * More tests. Achievement Unlocked: 99% Coverage. 1.1 (2012-01-07) ---------------- * Refactored ``dummyserver`` to its own root namespace module (used for testing). * Added hostname verification for ``VerifiedHTTPSConnection`` by vendoring in Py32's ``ssl_match_hostname``. (Issue #25) * Fixed cross-host HTTP redirects when using ``PoolManager``. (Issue #10) * Fixed ``decode_content`` being ignored when set through ``urlopen``. (Issue #27) * Fixed timeout-related bugs. (Issues #17, #23) 1.0.2 (2011-11-04) ------------------ * Fixed typo in ``VerifiedHTTPSConnection`` which would only present as a bug if you're using the object manually. (Thanks pyos) * Made RecentlyUsedContainer (and consequently PoolManager) more thread-safe by wrapping the access log in a mutex. (Thanks @christer) * Made RecentlyUsedContainer more dict-like (corrected ``__delitem__`` and ``__getitem__`` behaviour), with tests. Shouldn't affect core urllib3 code. 1.0.1 (2011-10-10) ------------------ * Fixed a bug where the same connection would get returned into the pool twice, causing extraneous "HttpConnectionPool is full" log warnings. 1.0 (2011-10-08) ---------------- * Added ``PoolManager`` with LRU expiration of connections (tested and documented). * Added ``ProxyManager`` (needs tests, docs, and confirmation that it works with HTTPS proxies). * Added optional partial-read support for responses when ``preload_content=False``. You can now make requests and just read the headers without loading the content. * Made response decoding optional (default on, same as before). * Added optional explicit boundary string for ``encode_multipart_formdata``. * Convenience request methods are now inherited from ``RequestMethods``. Old helpers like ``get_url`` and ``post_url`` should be abandoned in favour of the new ``request(method, url, ...)``. * Refactored code to be even more decoupled, reusable, and extendable. * License header added to ``.py`` files. * Embiggened the documentation: Lots of Sphinx-friendly docstrings in the code and docs in ``docs/`` and on https://urllib3.readthedocs.io/. * Embettered all the things! * Started writing this file. 0.4.1 (2011-07-17) ------------------ * Minor bug fixes, code cleanup. 0.4 (2011-03-01) ---------------- * Better unicode support. * Added ``VerifiedHTTPSConnection``. * Added ``NTLMConnectionPool`` in contrib. * Minor improvements. 0.3.1 (2010-07-13) ------------------ * Added ``assert_host_name`` optional parameter. Now compatible with proxies. 0.3 (2009-12-10) ---------------- * Added HTTPS support. * Minor bug fixes. * Refactored, broken backwards compatibility with 0.2. * API to be treated as stable from this version forward. 0.2 (2008-11-17) ---------------- * Added unit tests. * Bug fixes. 0.1 (2008-11-16) ---------------- * First release. Keywords: urllib httplib threadsafe filepost http https ssl pooling Platform: UNKNOWN Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Software Development :: Libraries Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4 Provides-Extra: secure Provides-Extra: brotli Provides-Extra: socks ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639273.0 urllib3-1.25.8/src/urllib3.egg-info/SOURCES.txt0000644000175000017500000000660500000000000023634 0ustar00sethmlarsonsethmlarson00000000000000CHANGES.rst CONTRIBUTORS.txt LICENSE.txt MANIFEST.in README.rst dev-requirements.txt setup.cfg setup.py docs/Makefile docs/advanced-usage.rst docs/conf.py docs/contributing.rst docs/index.rst docs/make.bat docs/requirements.txt docs/user-guide.rst docs/_templates/fonts.html docs/images/banner.svg docs/images/demo-button.png docs/images/learn-more-button.png docs/images/logo.png docs/images/logo.svg docs/reference/index.rst docs/reference/urllib3.contrib.rst docs/reference/urllib3.util.rst dummyserver/__init__.py dummyserver/handlers.py dummyserver/proxy.py dummyserver/server.py dummyserver/testcase.py dummyserver/certs/README.rst dummyserver/certs/cacert.key dummyserver/certs/cacert.pem dummyserver/certs/client_bad.pem dummyserver/certs/client_intermediate.pem dummyserver/certs/client_password.key dummyserver/certs/server.combined.pem dummyserver/certs/server.crt dummyserver/certs/server.csr dummyserver/certs/server.key dummyserver/certs/server.key.org dummyserver/certs/server_password.key src/urllib3/__init__.py src/urllib3/_collections.py src/urllib3/connection.py src/urllib3/connectionpool.py src/urllib3/exceptions.py src/urllib3/fields.py src/urllib3/filepost.py src/urllib3/poolmanager.py src/urllib3/request.py src/urllib3/response.py src/urllib3.egg-info/PKG-INFO src/urllib3.egg-info/SOURCES.txt src/urllib3.egg-info/dependency_links.txt src/urllib3.egg-info/requires.txt src/urllib3.egg-info/top_level.txt src/urllib3/contrib/__init__.py src/urllib3/contrib/_appengine_environ.py src/urllib3/contrib/appengine.py src/urllib3/contrib/ntlmpool.py src/urllib3/contrib/pyopenssl.py src/urllib3/contrib/securetransport.py src/urllib3/contrib/socks.py src/urllib3/contrib/_securetransport/__init__.py src/urllib3/contrib/_securetransport/bindings.py src/urllib3/contrib/_securetransport/low_level.py src/urllib3/packages/__init__.py src/urllib3/packages/six.py src/urllib3/packages/backports/__init__.py src/urllib3/packages/backports/makefile.py src/urllib3/packages/ssl_match_hostname/__init__.py src/urllib3/packages/ssl_match_hostname/_implementation.py src/urllib3/util/__init__.py src/urllib3/util/connection.py src/urllib3/util/queue.py src/urllib3/util/request.py src/urllib3/util/response.py src/urllib3/util/retry.py src/urllib3/util/ssl_.py src/urllib3/util/timeout.py src/urllib3/util/url.py src/urllib3/util/wait.py test/__init__.py test/benchmark.py test/conftest.py test/port_helpers.py test/socketpair_helper.py test/test_collections.py test/test_compatibility.py test/test_connection.py test/test_connectionpool.py test/test_exceptions.py test/test_fields.py test/test_filepost.py test/test_no_ssl.py test/test_poolmanager.py test/test_proxymanager.py test/test_queue_monkeypatch.py test/test_response.py test/test_retry.py test/test_ssl.py test/test_util.py test/test_wait.py test/appengine/__init__.py test/appengine/conftest.py test/appengine/test_gae_manager.py test/appengine/test_urlfetch.py test/contrib/__init__.py test/contrib/duplicate_san.pem test/contrib/test_pyopenssl.py test/contrib/test_pyopenssl_dependencies.py test/contrib/test_securetransport.py test/contrib/test_socks.py test/with_dummyserver/__init__.py test/with_dummyserver/test_chunked_transfer.py test/with_dummyserver/test_connectionpool.py test/with_dummyserver/test_https.py test/with_dummyserver/test_no_ssl.py test/with_dummyserver/test_poolmanager.py test/with_dummyserver/test_proxy_poolmanager.py test/with_dummyserver/test_socketlevel.py././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639273.0 urllib3-1.25.8/src/urllib3.egg-info/dependency_links.txt0000644000175000017500000000000100000000000026007 0ustar00sethmlarsonsethmlarson00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639273.0 urllib3-1.25.8/src/urllib3.egg-info/requires.txt0000644000175000017500000000025500000000000024343 0ustar00sethmlarsonsethmlarson00000000000000 [brotli] brotlipy>=0.6.0 [secure] pyOpenSSL>=0.14 cryptography>=1.3.4 idna>=2.0.0 certifi [secure:python_version == "2.7"] ipaddress [socks] PySocks!=1.5.7,<2.0,>=1.5.6 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639273.0 urllib3-1.25.8/src/urllib3.egg-info/top_level.txt0000644000175000017500000000001000000000000024462 0ustar00sethmlarsonsethmlarson00000000000000urllib3 ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/test/0000755000175000017500000000000000000000000017063 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/__init__.py0000644000175000017500000001666200000000000021207 0ustar00sethmlarsonsethmlarson00000000000000import warnings import sys import errno import logging import socket import ssl import os import platform import pytest try: import brotli except ImportError: brotli = None from urllib3.exceptions import HTTPWarning from urllib3.packages import six from urllib3.util import ssl_ # We need a host that will not immediately close the connection with a TCP # Reset. SO suggests this hostname TARPIT_HOST = "10.255.255.1" # (Arguments for socket, is it IPv6 address?) VALID_SOURCE_ADDRESSES = [(("::1", 0), True), (("127.0.0.1", 0), False)] # RFC 5737: 192.0.2.0/24 is for testing only. # RFC 3849: 2001:db8::/32 is for documentation only. INVALID_SOURCE_ADDRESSES = [("192.0.2.255", 0), ("2001:db8::1", 0)] # We use timeouts in three different ways in our tests # # 1. To make sure that the operation timeouts, we can use a short timeout. # 2. To make sure that the test does not hang even if the operation should succeed, we # want to use a long timeout, even more so on CI where tests can be really slow # 3. To test our timeout logic by using two different values, eg. by using different # values at the pool level and at the request level. SHORT_TIMEOUT = 0.001 LONG_TIMEOUT = 0.5 if os.environ.get("CI") else 0.01 def clear_warnings(cls=HTTPWarning): new_filters = [] for f in warnings.filters: if issubclass(f[2], cls): continue new_filters.append(f) warnings.filters[:] = new_filters def setUp(): clear_warnings() warnings.simplefilter("ignore", HTTPWarning) def onlyPy279OrNewer(test): """Skips this test unless you are on Python 2.7.9 or later.""" @six.wraps(test) def wrapper(*args, **kwargs): msg = "{name} requires Python 2.7.9+ to run".format(name=test.__name__) if sys.version_info < (2, 7, 9): pytest.skip(msg) return test(*args, **kwargs) return wrapper def onlyPy2(test): """Skips this test unless you are on Python 2.x""" @six.wraps(test) def wrapper(*args, **kwargs): msg = "{name} requires Python 2.x to run".format(name=test.__name__) if not six.PY2: pytest.skip(msg) return test(*args, **kwargs) return wrapper def onlyPy3(test): """Skips this test unless you are on Python3.x""" @six.wraps(test) def wrapper(*args, **kwargs): msg = "{name} requires Python3.x to run".format(name=test.__name__) if six.PY2: pytest.skip(msg) return test(*args, **kwargs) return wrapper def notPyPy2(test): """Skips this test on PyPy2""" @six.wraps(test) def wrapper(*args, **kwargs): # https://github.com/testing-cabal/mock/issues/438 msg = "{} fails with PyPy 2 dues to funcsigs bugs".format(test.__name__) if platform.python_implementation() == "PyPy" and sys.version_info[0] == 2: pytest.xfail(msg) return test(*args, **kwargs) return wrapper def onlyBrotlipy(): return pytest.mark.skipif(brotli is None, reason="only run if brotlipy is present") def notBrotlipy(): return pytest.mark.skipif( brotli is not None, reason="only run if brotlipy is absent" ) def notSecureTransport(test): """Skips this test when SecureTransport is in use.""" @six.wraps(test) def wrapper(*args, **kwargs): msg = "{name} does not run with SecureTransport".format(name=test.__name__) if ssl_.IS_SECURETRANSPORT: pytest.skip(msg) return test(*args, **kwargs) return wrapper def notOpenSSL098(test): """Skips this test for Python 3.5 macOS python.org distribution""" @six.wraps(test) def wrapper(*args, **kwargs): is_stdlib_ssl = not ssl_.IS_SECURETRANSPORT and not ssl_.IS_PYOPENSSL if is_stdlib_ssl and ssl.OPENSSL_VERSION == "OpenSSL 0.9.8zh 14 Jan 2016": pytest.xfail("{name} fails with OpenSSL 0.9.8zh".format(name=test.__name__)) return test(*args, **kwargs) return wrapper _requires_network_has_route = None def requires_network(test): """Helps you skip tests that require the network""" def _is_unreachable_err(err): return getattr(err, "errno", None) in ( errno.ENETUNREACH, errno.EHOSTUNREACH, # For OSX ) def _has_route(): try: sock = socket.create_connection((TARPIT_HOST, 80), 0.0001) sock.close() return True except socket.timeout: return True except socket.error as e: if _is_unreachable_err(e): return False else: raise @six.wraps(test) def wrapper(*args, **kwargs): global _requires_network_has_route if _requires_network_has_route is None: _requires_network_has_route = _has_route() if _requires_network_has_route: return test(*args, **kwargs) else: msg = "Can't run {name} because the network is unreachable".format( name=test.__name__ ) pytest.skip(msg) return wrapper def requires_ssl_context_keyfile_password(test): @six.wraps(test) def wrapper(*args, **kwargs): if ( not ssl_.IS_PYOPENSSL and sys.version_info < (2, 7, 9) ) or ssl_.IS_SECURETRANSPORT: pytest.skip( "%s requires password parameter for " "SSLContext.load_cert_chain()" % test.__name__ ) return test(*args, **kwargs) return wrapper def fails_on_travis_gce(test): """Expect the test to fail on Google Compute Engine instances for Travis. Travis uses GCE for its sudo: enabled builds. Reason for this decorator: https://github.com/urllib3/urllib3/pull/1475#issuecomment-440788064 """ @six.wraps(test) def wrapper(*args, **kwargs): if os.environ.get("TRAVIS_INFRA") in ("gce", "unknown"): pytest.xfail("%s is expected to fail on Travis GCE builds" % test.__name__) return test(*args, **kwargs) return wrapper def requiresTLSv1(): """Test requires TLSv1 available""" return pytest.mark.skipif( not hasattr(ssl, "PROTOCOL_TLSv1"), reason="Test requires TLSv1" ) def requiresTLSv1_1(): """Test requires TLSv1.1 available""" return pytest.mark.skipif( not hasattr(ssl, "PROTOCOL_TLSv1_1"), reason="Test requires TLSv1.1" ) def requiresTLSv1_2(): """Test requires TLSv1.2 available""" return pytest.mark.skipif( not hasattr(ssl, "PROTOCOL_TLSv1_2"), reason="Test requires TLSv1.2" ) def requiresTLSv1_3(): """Test requires TLSv1.3 available""" return pytest.mark.skipif( not getattr(ssl, "HAS_TLSv1_3", False), reason="Test requires TLSv1.3" ) class _ListHandler(logging.Handler): def __init__(self): super(_ListHandler, self).__init__() self.records = [] def emit(self, record): self.records.append(record) class LogRecorder(object): def __init__(self, target=logging.root): super(LogRecorder, self).__init__() self._target = target self._handler = _ListHandler() @property def records(self): return self._handler.records def install(self): self._target.addHandler(self._handler) def uninstall(self): self._target.removeHandler(self._handler) def __enter__(self): self.install() return self.records def __exit__(self, exc_type, exc_value, traceback): self.uninstall() return False ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/test/appengine/0000755000175000017500000000000000000000000021031 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/appengine/__init__.py0000644000175000017500000000000000000000000023130 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/appengine/conftest.py0000644000175000017500000000427100000000000023234 0ustar00sethmlarsonsethmlarson00000000000000# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys # Import py.test hooks and fixtures for App Engine try: from gcp_devrel.testing.appengine import ( pytest_configure, pytest_runtest_call, testbed, ) except ImportError: pass import pytest import six __all__ = [ "pytest_configure", "pytest_runtest_call", "pytest_ignore_collect", "testbed", "sandbox", ] @pytest.fixture def sandbox(testbed): """ Enables parts of the GAE sandbox that are relevant. Inserts the stub module import hook which causes the usage of appengine-specific httplib, httplib2, socket, etc. """ try: from google.appengine.tools.devappserver2.python import sandbox except ImportError: from google.appengine.tools.devappserver2.python.runtime import sandbox for name in list(sys.modules): if name in sandbox.dist27.MODULE_OVERRIDES: del sys.modules[name] sys.meta_path.insert(0, sandbox.StubModuleImportHook()) sys.path_importer_cache = {} yield testbed sys.meta_path = [ x for x in sys.meta_path if not isinstance(x, sandbox.StubModuleImportHook) ] sys.path_importer_cache = {} # Delete any instances of sandboxed modules. for name in list(sys.modules): if name in sandbox.dist27.MODULE_OVERRIDES: del sys.modules[name] def pytest_ignore_collect(path, config): """Skip App Engine tests in python 3 or if no SDK is available.""" if "appengine" in str(path): if not six.PY2: return True if not os.environ.get("GAE_SDK_PATH"): return True return False ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/appengine/test_gae_manager.py0000644000175000017500000001466200000000000024701 0ustar00sethmlarsonsethmlarson00000000000000import dummyserver.testcase import pytest from urllib3.contrib import appengine import urllib3.exceptions import urllib3.util.url import urllib3.util.retry from test.with_dummyserver import test_connectionpool from test import SHORT_TIMEOUT # This class is used so we can re-use the tests from the connection pool. # It proxies all requests to the manager. class MockPool(object): def __init__(self, host, port, manager, scheme="http"): self.host = host self.port = port self.manager = manager self.scheme = scheme def request(self, method, url, *args, **kwargs): url = self._absolute_url(url) return self.manager.request(method, url, *args, **kwargs) def urlopen(self, method, url, *args, **kwargs): url = self._absolute_url(url) return self.manager.urlopen(method, url, *args, **kwargs) def _absolute_url(self, path): return urllib3.util.url.Url( scheme=self.scheme, host=self.host, port=self.port, path=path ).url # Note that this doesn't run in the sandbox, it only runs with the URLFetch # API stub enabled. There's no need to enable the sandbox as we know for a fact # that URLFetch is used by the connection manager. @pytest.mark.usefixtures("testbed") class TestGAEConnectionManager(test_connectionpool.TestConnectionPool): def setup_method(self, method): self.manager = appengine.AppEngineManager() self.pool = MockPool(self.host, self.port, self.manager) # Tests specific to AppEngineManager def test_exceptions(self): # DeadlineExceededError -> TimeoutError with pytest.raises(urllib3.exceptions.TimeoutError): self.pool.request( "GET", "/sleep?seconds={}".format(5 * SHORT_TIMEOUT), timeout=SHORT_TIMEOUT, ) # InvalidURLError -> ProtocolError with pytest.raises(urllib3.exceptions.ProtocolError): self.manager.request("GET", "ftp://invalid/url") # DownloadError -> ProtocolError with pytest.raises(urllib3.exceptions.ProtocolError): self.manager.request("GET", "http://0.0.0.0") # ResponseTooLargeError -> AppEnginePlatformError with pytest.raises(appengine.AppEnginePlatformError): self.pool.request( "GET", "/nbytes?length=33554433" ) # One byte over 32 megabtyes. # URLFetch reports the request too large error as a InvalidURLError, # which maps to a AppEnginePlatformError. body = b"1" * 10485761 # One byte over 10 megabytes. with pytest.raises(appengine.AppEnginePlatformError): self.manager.request("POST", "/", body=body) # Re-used tests below this line. # Subsumed tests test_timeout_float = None # Covered by test_exceptions. # Non-applicable tests test_conn_closed = None test_nagle = None test_socket_options = None test_disable_default_socket_options = None test_defaults_are_applied = None test_tunnel = None test_keepalive = None test_keepalive_close = None test_connection_count = None test_connection_count_bigpool = None test_for_double_release = None test_release_conn_parameter = None test_stream_keepalive = None test_cleanup_on_connection_error = None test_read_chunked_short_circuit = None test_read_chunked_on_closed_response = None # Tests that should likely be modified for appengine specific stuff test_timeout = None test_connect_timeout = None test_connection_error_retries = None test_total_timeout = None test_none_total_applies_connect = None test_timeout_success = None test_source_address_error = None test_bad_connect = None test_partial_response = None test_dns_error = None @pytest.mark.usefixtures("testbed") class TestGAEConnectionManagerWithSSL(dummyserver.testcase.HTTPSDummyServerTestCase): def setup_method(self, method): self.manager = appengine.AppEngineManager() self.pool = MockPool(self.host, self.port, self.manager, "https") def test_exceptions(self): # SSLCertificateError -> SSLError # SSLError is raised with dummyserver because URLFetch doesn't allow # self-signed certs. with pytest.raises(urllib3.exceptions.SSLError): self.pool.request("GET", "/") @pytest.mark.usefixtures("testbed") class TestGAERetry(test_connectionpool.TestRetry): def setup_method(self, method): self.manager = appengine.AppEngineManager() self.pool = MockPool(self.host, self.port, self.manager) def test_default_method_whitelist_retried(self): """ urllib3 should retry methods in the default method whitelist """ retry = urllib3.util.retry.Retry(total=1, status_forcelist=[418]) # Use HEAD instead of OPTIONS, as URLFetch doesn't support OPTIONS resp = self.pool.request( "HEAD", "/successful_retry", headers={"test-name": "test_default_whitelist"}, retries=retry, ) assert resp.status == 200 def test_retry_return_in_response(self): headers = {"test-name": "test_retry_return_in_response"} retry = urllib3.util.retry.Retry(total=2, status_forcelist=[418]) resp = self.pool.request( "GET", "/successful_retry", headers=headers, retries=retry ) assert resp.status == 200 assert resp.retries.total == 1 # URLFetch use absolute urls. assert resp.retries.history == ( urllib3.util.retry.RequestHistory( "GET", self.pool._absolute_url("/successful_retry"), None, 418, None ), ) # test_max_retry = None # test_disabled_retry = None # We don't need these tests because URLFetch resolves its own redirects. test_retry_redirect_history = None test_multi_redirect_history = None @pytest.mark.usefixtures("testbed") class TestGAERetryAfter(test_connectionpool.TestRetryAfter): def setup_method(self, method): # Disable urlfetch which doesn't respect Retry-After header. self.manager = appengine.AppEngineManager(urlfetch_retries=False) self.pool = MockPool(self.host, self.port, self.manager) def test_gae_environ(): assert not appengine.is_appengine() assert not appengine.is_appengine_sandbox() assert not appengine.is_local_appengine() assert not appengine.is_prod_appengine() assert not appengine.is_prod_appengine_mvms() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/appengine/test_urlfetch.py0000644000175000017500000000452000000000000024257 0ustar00sethmlarsonsethmlarson00000000000000"""These tests ensure that when running in App Engine standard with the App Engine sandbox enabled that urllib3 appropriately uses the App Engine-patched version of httplib to make requests.""" import httplib import StringIO from mock import patch import pytest from ..test_no_ssl import TestWithoutSSL class MockResponse(object): def __init__(self, content, status_code, content_was_truncated, final_url, headers): self.content = content self.status_code = status_code self.content_was_truncated = content_was_truncated self.final_url = final_url self.header_msg = httplib.HTTPMessage( StringIO.StringIO( "".join(["%s: %s\n" % (k, v) for k, v in headers.iteritems()] + ["\n"]) ) ) self.headers = headers @pytest.mark.usefixtures("sandbox") class TestHTTP(TestWithoutSSL): def test_urlfetch_called_with_http(self): """Check that URLFetch is used to fetch non-https resources.""" resp = MockResponse( "OK", 200, False, "http://www.google.com", {"content-type": "text/plain"} ) fetch_patch = patch("google.appengine.api.urlfetch.fetch", return_value=resp) with fetch_patch as fetch_mock: import urllib3 pool = urllib3.HTTPConnectionPool("www.google.com", "80") r = pool.request("GET", "/") assert r.status == 200, r.data assert fetch_mock.call_count == 1 @pytest.mark.usefixtures("sandbox") class TestHTTPS(object): @pytest.mark.xfail( reason="This is not yet supported by urlfetch, presence of the ssl " "module will bypass urlfetch." ) def test_urlfetch_called_with_https(self): """ Check that URLFetch is used when fetching https resources """ resp = MockResponse( "OK", 200, False, "https://www.google.com", {"content-type": "text/plain"} ) fetch_patch = patch("google.appengine.api.urlfetch.fetch", return_value=resp) with fetch_patch as fetch_mock: import urllib3 pool = urllib3.HTTPSConnectionPool("www.google.com", "443") pool.ConnectionCls = urllib3.connection.UnverifiedHTTPSConnection r = pool.request("GET", "/") assert r.status == 200, r.data assert fetch_mock.call_count == 1 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/benchmark.py0000644000175000017500000000404600000000000021373 0ustar00sethmlarsonsethmlarson00000000000000#!/usr/bin/env python """ Really simple rudimentary benchmark to compare ConnectionPool versus standard urllib to demonstrate the usefulness of connection re-using. """ from __future__ import print_function import sys import time import urllib sys.path.append("../") import urllib3 # noqa: E402 # URLs to download. Doesn't matter as long as they're from the same host, so we # can take advantage of connection re-using. TO_DOWNLOAD = [ "http://code.google.com/apis/apps/", "http://code.google.com/apis/base/", "http://code.google.com/apis/blogger/", "http://code.google.com/apis/calendar/", "http://code.google.com/apis/codesearch/", "http://code.google.com/apis/contact/", "http://code.google.com/apis/books/", "http://code.google.com/apis/documents/", "http://code.google.com/apis/finance/", "http://code.google.com/apis/health/", "http://code.google.com/apis/notebook/", "http://code.google.com/apis/picasaweb/", "http://code.google.com/apis/spreadsheets/", "http://code.google.com/apis/webmastertools/", "http://code.google.com/apis/youtube/", ] def urllib_get(url_list): assert url_list for url in url_list: now = time.time() urllib.urlopen(url) elapsed = time.time() - now print("Got in %0.3f: %s" % (elapsed, url)) def pool_get(url_list): assert url_list pool = urllib3.PoolManager() for url in url_list: now = time.time() pool.request("GET", url, assert_same_host=False) elapsed = time.time() - now print("Got in %0.3fs: %s" % (elapsed, url)) if __name__ == "__main__": print("Running pool_get ...") now = time.time() pool_get(TO_DOWNLOAD) pool_elapsed = time.time() - now print("Running urllib_get ...") now = time.time() urllib_get(TO_DOWNLOAD) urllib_elapsed = time.time() - now print("Completed pool_get in %0.3fs" % pool_elapsed) print("Completed urllib_get in %0.3fs" % urllib_elapsed) """ Example results: Completed pool_get in 1.163s Completed urllib_get in 2.318s """ ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/conftest.py0000644000175000017500000000767300000000000021277 0ustar00sethmlarsonsethmlarson00000000000000import collections import contextlib import threading import platform import sys import pytest import trustme from tornado import web, ioloop from dummyserver.handlers import TestingApp from dummyserver.server import run_tornado_app from dummyserver.server import ( DEFAULT_CA, DEFAULT_CA_KEY, CLIENT_INTERMEDIATE_PEM, CLIENT_NO_INTERMEDIATE_PEM, CLIENT_INTERMEDIATE_KEY, HAS_IPV6, ) # The Python 3.8+ default loop on Windows breaks Tornado @pytest.fixture(scope="session", autouse=True) def configure_windows_event_loop(): if sys.version_info >= (3, 8) and platform.system() == "Windows": import asyncio asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) @pytest.fixture(scope="session") def certs_dir(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs") # Start from existing root CA as we don't want to change the server certificate yet with open(DEFAULT_CA, "rb") as crt, open(DEFAULT_CA_KEY, "rb") as key: root_ca = trustme.CA.from_pem(crt.read(), key.read()) # client cert chain intermediate_ca = root_ca.create_child_ca() cert = intermediate_ca.issue_cert(u"example.com") cert.private_key_pem.write_to_path(str(tmpdir / CLIENT_INTERMEDIATE_KEY)) # Write the client cert and the intermediate CA client_cert = str(tmpdir / CLIENT_INTERMEDIATE_PEM) cert.cert_chain_pems[0].write_to_path(client_cert) cert.cert_chain_pems[1].write_to_path(client_cert, append=True) # Write only the client cert cert.cert_chain_pems[0].write_to_path(str(tmpdir / CLIENT_NO_INTERMEDIATE_PEM)) yield tmpdir ServerConfig = collections.namedtuple("ServerConfig", ["host", "port", "ca_certs"]) @contextlib.contextmanager def run_server_in_thread(scheme, host, tmpdir, ca, server_cert): ca_cert_path = str(tmpdir / "ca.pem") server_cert_path = str(tmpdir / "server.pem") server_key_path = str(tmpdir / "server.key") ca.cert_pem.write_to_path(ca_cert_path) server_cert.private_key_pem.write_to_path(server_key_path) server_cert.cert_chain_pems[0].write_to_path(server_cert_path) server_certs = {"keyfile": server_key_path, "certfile": server_cert_path} io_loop = ioloop.IOLoop.current() app = web.Application([(r".*", TestingApp)]) server, port = run_tornado_app(app, io_loop, server_certs, scheme, host) server_thread = threading.Thread(target=io_loop.start) server_thread.start() yield ServerConfig(host, port, ca_cert_path) io_loop.add_callback(server.stop) io_loop.add_callback(io_loop.stop) server_thread.join() @pytest.fixture def no_san_server(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs") ca = trustme.CA() # only common name, no subject alternative names server_cert = ca.issue_cert(common_name=u"localhost") with run_server_in_thread("https", "localhost", tmpdir, ca, server_cert) as cfg: yield cfg @pytest.fixture def ip_san_server(tmp_path_factory): tmpdir = tmp_path_factory.mktemp("certs") ca = trustme.CA() # IP address in Subject Alternative Name server_cert = ca.issue_cert(u"127.0.0.1") with run_server_in_thread("https", "127.0.0.1", tmpdir, ca, server_cert) as cfg: yield cfg @pytest.fixture def ipv6_addr_server(tmp_path_factory): if not HAS_IPV6: pytest.skip("Only runs on IPv6 systems") tmpdir = tmp_path_factory.mktemp("certs") ca = trustme.CA() # IP address in Common Name server_cert = ca.issue_cert(common_name=u"::1") with run_server_in_thread("https", "::1", tmpdir, ca, server_cert) as cfg: yield cfg @pytest.fixture def ipv6_san_server(tmp_path_factory): if not HAS_IPV6: pytest.skip("Only runs on IPv6 systems") tmpdir = tmp_path_factory.mktemp("certs") ca = trustme.CA() # IP address in Subject Alternative Name server_cert = ca.issue_cert(u"::1") with run_server_in_thread("https", "::1", tmpdir, ca, server_cert) as cfg: yield cfg ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/test/contrib/0000755000175000017500000000000000000000000020523 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/contrib/__init__.py0000644000175000017500000000000000000000000022622 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/contrib/duplicate_san.pem0000644000175000017500000000235100000000000024042 0ustar00sethmlarsonsethmlarson00000000000000-----BEGIN CERTIFICATE----- MIIDcjCCAlqgAwIBAgICAwkwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCVVMx DjAMBgNVBAgMBVRleGFzMQ8wDQYDVQQHDAZBdXN0aW4xDTALBgNVBAoMBFB5Q0Ex GDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAeFw0wMjAxMDExMjAxMDBaFw0zMDEy MzEwODMwMDBaMFcxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEPMA0GA1UE BwwGQXVzdGluMQ0wCwYDVQQKDARQeUNBMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHku aW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDBevx+d0dMqlqoMDYV ij/797UhaFG6IjDl1qv8wcbP71npI+oTMLxZO3OAKrYIpuSjMGUjoxFrpao5ZhRR dOE7bEnpt4Bi5EnXLvsQ/UnpH6CLltBR54Lp9avFtab3mEgnrbjnPaAPIrLv3Nt2 6rRu2tmO1lZidD/cbA4zal0M26p9wp5TY14kyHpbLEIVloBjzetoqXK6u8Hjz/AP uagONypNDCySDR6M7jM85HDcLoFFrbBb8pruHSTxQejMeEmJxYf8b7rNl58/IWPB 1ymbNlvHL/4oSOlnrtHkjcxRWzpQ7U3gT9BThGyhCiI7EMyEHMgP3r7kTzEUwT6I avWDAgMBAAGjSDBGMAwGA1UdEwEB/wQCMAAwGgYDVR0RBBMwEYIPY3J5cHRvZ3Jh cGh5LmlvMBoGA1UdEQQTMBGCD2NyeXB0b2dyYXBoeS5pbzANBgkqhkiG9w0BAQUF AAOCAQEAAzAU5U814RrWYHiRQKDBu0710/ch5Q7z9fuJx7JWcX9pr152vCiPas4D s2YWZS6sNFh6g8h4AaDXjScNar15s2WWmWV3tS5InI9eFxn4TBHSjH4a/Lxa1W0V RA1XWNZZjm7Y9psRKjwiJmnK4Lm0Xk3KWMa03SlOpXNMTCQ/7vQX54zvlnynpo2E +pN6M28rbuA5SXkMRVv77W9kYZITAPqVLI99fSA8xaYW6NpyPtWPFSGbTwmt+U9w h/Acs8RYAR5NaS/aCELTqjsKjQmZAHlmxzbMo0ueqBUyQlOFX+G7TzBW1NFrSJNj 1TbuzMOELwTO7/l+m112lNpSWiP+UQ== -----END CERTIFICATE----- ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/contrib/test_pyopenssl.py0000644000175000017500000000525200000000000024174 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- import os import mock import pytest try: from urllib3.contrib.pyopenssl import _dnsname_to_stdlib, get_subj_alt_name from cryptography import x509 from OpenSSL.crypto import FILETYPE_PEM, load_certificate except ImportError: pass def setup_module(): try: from urllib3.contrib.pyopenssl import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip("Could not import PyOpenSSL: %r" % e) def teardown_module(): try: from urllib3.contrib.pyopenssl import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import ( # noqa: F401 TestHTTPS, TestHTTPS_TLSv1, TestHTTPS_TLSv1_1, TestHTTPS_TLSv1_2, TestHTTPS_TLSv1_3, TestHTTPS_IPSAN, TestHTTPS_IPv6Addr, TestHTTPS_NoSAN, TestHTTPS_IPV6SAN, ) from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts, ) class TestPyOpenSSLHelpers(object): """ Tests for PyOpenSSL helper functions. """ def test_dnsname_to_stdlib_simple(self): """ We can convert a dnsname to a native string when the domain is simple. """ name = u"उदाहरण.परीक" expected_result = "xn--p1b6ci4b4b3a.xn--11b5bs8d" assert _dnsname_to_stdlib(name) == expected_result def test_dnsname_to_stdlib_leading_period(self): """ If there is a . in front of the domain name we correctly encode it. """ name = u".उदाहरण.परीक" expected_result = ".xn--p1b6ci4b4b3a.xn--11b5bs8d" assert _dnsname_to_stdlib(name) == expected_result def test_dnsname_to_stdlib_leading_splat(self): """ If there's a wildcard character in the front of the string we handle it appropriately. """ name = u"*.उदाहरण.परीक" expected_result = "*.xn--p1b6ci4b4b3a.xn--11b5bs8d" assert _dnsname_to_stdlib(name) == expected_result @mock.patch("urllib3.contrib.pyopenssl.log.warning") def test_get_subj_alt_name(self, mock_warning): """ If a certificate has two subject alternative names, cryptography raises an x509.DuplicateExtension exception. """ path = os.path.join(os.path.dirname(__file__), "duplicate_san.pem") with open(path, "r") as fp: cert = load_certificate(FILETYPE_PEM, fp.read()) assert get_subj_alt_name(cert) == [] assert mock_warning.call_count == 1 assert isinstance(mock_warning.call_args[0][1], x509.DuplicateExtension) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/contrib/test_pyopenssl_dependencies.py0000644000175000017500000000362700000000000026706 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- import pytest from mock import patch, Mock try: from urllib3.contrib.pyopenssl import inject_into_urllib3, extract_from_urllib3 except ImportError: pass def setup_module(): try: from urllib3.contrib.pyopenssl import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip("Could not import PyOpenSSL: %r" % e) def teardown_module(): try: from urllib3.contrib.pyopenssl import extract_from_urllib3 extract_from_urllib3() except ImportError: pass class TestPyOpenSSLInjection(object): """ Tests for error handling in pyopenssl's 'inject_into urllib3' """ def test_inject_validate_fail_cryptography(self): """ Injection should not be supported if cryptography is too old. """ try: with patch("cryptography.x509.extensions.Extensions") as mock: del mock.get_extension_for_class with pytest.raises(ImportError): inject_into_urllib3() finally: # `inject_into_urllib3` is not supposed to succeed. # If it does, this test should fail, but we need to # clean up so that subsequent tests are unaffected. extract_from_urllib3() def test_inject_validate_fail_pyopenssl(self): """ Injection should not be supported if pyOpenSSL is too old. """ try: return_val = Mock() del return_val._x509 with patch("OpenSSL.crypto.X509", return_value=return_val): with pytest.raises(ImportError): inject_into_urllib3() finally: # `inject_into_urllib3` is not supposed to succeed. # If it does, this test should fail, but we need to # clean up so that subsequent tests are unaffected. extract_from_urllib3() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/contrib/test_securetransport.py0000644000175000017500000000224300000000000025400 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass pytestmark = pytest.mark.skip() def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip("Could not import SecureTransport: %r" % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass # SecureTransport does not support TLSv1.3 # https://github.com/urllib3/urllib3/issues/1674 from ..with_dummyserver.test_https import ( # noqa: F401 TestHTTPS, TestHTTPS_TLSv1, TestHTTPS_TLSv1_1, TestHTTPS_TLSv1_2, ) from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts, ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"") ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/contrib/test_socks.py0000644000175000017500000005342100000000000023263 0ustar00sethmlarsonsethmlarson00000000000000import threading import socket from urllib3.contrib import socks from urllib3.exceptions import ConnectTimeoutError, NewConnectionError from dummyserver.server import DEFAULT_CERTS, DEFAULT_CA from dummyserver.testcase import IPV4SocketDummyServerTestCase import pytest from test import SHORT_TIMEOUT try: import ssl from urllib3.util import ssl_ as better_ssl HAS_SSL = True except ImportError: ssl = None better_ssl = None HAS_SSL = False SOCKS_NEGOTIATION_NONE = b"\x00" SOCKS_NEGOTIATION_PASSWORD = b"\x02" SOCKS_VERSION_SOCKS4 = b"\x04" SOCKS_VERSION_SOCKS5 = b"\x05" def _get_free_port(host): """ Gets a free port by opening a socket, binding it, checking the assigned port, and then closing it. """ s = socket.socket() s.bind((host, 0)) port = s.getsockname()[1] s.close() return port def _read_exactly(sock, amt): """ Read *exactly* ``amt`` bytes from the socket ``sock``. """ data = b"" while amt > 0: chunk = sock.recv(amt) data += chunk amt -= len(chunk) return data def _read_until(sock, char): """ Read from the socket until the character is received. """ chunks = [] while True: chunk = sock.recv(1) chunks.append(chunk) if chunk == char: break return b"".join(chunks) def _address_from_socket(sock): """ Returns the address from the SOCKS socket """ addr_type = sock.recv(1) if addr_type == b"\x01": ipv4_addr = _read_exactly(sock, 4) return socket.inet_ntoa(ipv4_addr) elif addr_type == b"\x04": ipv6_addr = _read_exactly(sock, 16) return socket.inet_ntop(socket.AF_INET6, ipv6_addr) elif addr_type == b"\x03": addr_len = ord(sock.recv(1)) return _read_exactly(sock, addr_len) else: raise RuntimeError("Unexpected addr type: %r" % addr_type) def handle_socks5_negotiation(sock, negotiate, username=None, password=None): """ Handle the SOCKS5 handshake. Returns a generator object that allows us to break the handshake into steps so that the test code can intervene at certain useful points. """ received_version = sock.recv(1) assert received_version == SOCKS_VERSION_SOCKS5 nmethods = ord(sock.recv(1)) methods = _read_exactly(sock, nmethods) if negotiate: assert SOCKS_NEGOTIATION_PASSWORD in methods send_data = SOCKS_VERSION_SOCKS5 + SOCKS_NEGOTIATION_PASSWORD sock.sendall(send_data) # This is the password negotiation. negotiation_version = sock.recv(1) assert negotiation_version == b"\x01" ulen = ord(sock.recv(1)) provided_username = _read_exactly(sock, ulen) plen = ord(sock.recv(1)) provided_password = _read_exactly(sock, plen) if username == provided_username and password == provided_password: sock.sendall(b"\x01\x00") else: sock.sendall(b"\x01\x01") sock.close() yield False return else: assert SOCKS_NEGOTIATION_NONE in methods send_data = SOCKS_VERSION_SOCKS5 + SOCKS_NEGOTIATION_NONE sock.sendall(send_data) # Client sends where they want to go. received_version = sock.recv(1) command = sock.recv(1) reserved = sock.recv(1) addr = _address_from_socket(sock) port = _read_exactly(sock, 2) port = (ord(port[0:1]) << 8) + (ord(port[1:2])) # Check some basic stuff. assert received_version == SOCKS_VERSION_SOCKS5 assert command == b"\x01" # Only support connect, not bind. assert reserved == b"\x00" # Yield the address port tuple. succeed = yield addr, port if succeed: # Hard-coded response for now. response = SOCKS_VERSION_SOCKS5 + b"\x00\x00\x01\x7f\x00\x00\x01\xea\x60" else: # Hard-coded response for now. response = SOCKS_VERSION_SOCKS5 + b"\x01\00" sock.sendall(response) yield True # Avoid StopIteration exceptions getting fired. def handle_socks4_negotiation(sock, username=None): """ Handle the SOCKS4 handshake. Returns a generator object that allows us to break the handshake into steps so that the test code can intervene at certain useful points. """ received_version = sock.recv(1) command = sock.recv(1) port = _read_exactly(sock, 2) port = (ord(port[0:1]) << 8) + (ord(port[1:2])) addr = _read_exactly(sock, 4) provided_username = _read_until(sock, b"\x00")[:-1] # Strip trailing null. if addr == b"\x00\x00\x00\x01": # Magic string: means DNS name. addr = _read_until(sock, b"\x00")[:-1] # Strip trailing null. else: addr = socket.inet_ntoa(addr) # Check some basic stuff. assert received_version == SOCKS_VERSION_SOCKS4 assert command == b"\x01" # Only support connect, not bind. if username is not None and username != provided_username: sock.sendall(b"\x00\x5d\x00\x00\x00\x00\x00\x00") sock.close() yield False return # Yield the address port tuple. succeed = yield addr, port if succeed: response = b"\x00\x5a\xea\x60\x7f\x00\x00\x01" else: response = b"\x00\x5b\x00\x00\x00\x00\x00\x00" sock.sendall(response) yield True # Avoid StopIteration exceptions getting fired. class TestSOCKSProxyManager(object): def test_invalid_socks_version_is_valueerror(self): with pytest.raises(ValueError) as e: socks.SOCKSProxyManager(proxy_url="http://example.org") assert "Unable to determine SOCKS version" in e.value.args[0] class TestSocks5Proxy(IPV4SocketDummyServerTestCase): """ Test the SOCKS proxy in SOCKS5 mode. """ def test_basic_request(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation(sock, negotiate=False) addr, port = next(handler) assert addr == "16.17.18.19" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks5://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://16.17.18.19") assert response.status == 200 assert response.data == b"" assert response.headers["Server"] == "SocksTestServer" def test_local_dns(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation(sock, negotiate=False) addr, port = next(handler) assert addr in ["127.0.0.1", "::1"] assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks5://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://localhost") assert response.status == 200 assert response.data == b"" assert response.headers["Server"] == "SocksTestServer" def test_correct_header_line(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation(sock, negotiate=False) addr, port = next(handler) assert addr == b"example.com" assert port == 80 handler.send(True) buf = b"" while True: buf += sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break assert buf.startswith(b"GET / HTTP/1.1") assert b"Host: example.com" in buf sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks5h://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://example.com") assert response.status == 200 def test_connection_timeouts(self): event = threading.Event() def request_handler(listener): event.wait() self._start_server(request_handler) proxy_url = "socks5h://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: with pytest.raises(ConnectTimeoutError): pm.request( "GET", "http://example.com", timeout=SHORT_TIMEOUT, retries=False ) event.set() def test_connection_failure(self): event = threading.Event() def request_handler(listener): listener.close() event.set() self._start_server(request_handler) proxy_url = "socks5h://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: event.wait() with pytest.raises(NewConnectionError): pm.request("GET", "http://example.com", retries=False) def test_proxy_rejection(self): evt = threading.Event() def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation(sock, negotiate=False) addr, port = next(handler) handler.send(False) evt.wait() sock.close() self._start_server(request_handler) proxy_url = "socks5h://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: with pytest.raises(NewConnectionError): pm.request("GET", "http://example.com", retries=False) evt.set() def test_socks_with_password(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation( sock, negotiate=True, username=b"user", password=b"pass" ) addr, port = next(handler) assert addr == "16.17.18.19" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks5://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url, username="user", password="pass") as pm: response = pm.request("GET", "http://16.17.18.19") assert response.status == 200 assert response.data == b"" assert response.headers["Server"] == "SocksTestServer" def test_socks_with_auth_in_url(self): """ Test when we have auth info in url, i.e. socks5://user:pass@host:port and no username/password as params """ def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation( sock, negotiate=True, username=b"user", password=b"pass" ) addr, port = next(handler) assert addr == "16.17.18.19" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks5://user:pass@%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://16.17.18.19") assert response.status == 200 assert response.data == b"" assert response.headers["Server"] == "SocksTestServer" def test_socks_with_invalid_password(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation( sock, negotiate=True, username=b"user", password=b"pass" ) next(handler) self._start_server(request_handler) proxy_url = "socks5h://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager( proxy_url, username="user", password="badpass" ) as pm: with pytest.raises(NewConnectionError) as e: pm.request("GET", "http://example.com", retries=False) assert "SOCKS5 authentication failed" in str(e.value) def test_source_address_works(self): expected_port = _get_free_port(self.host) def request_handler(listener): sock = listener.accept()[0] assert sock.getpeername()[0] == "127.0.0.1" assert sock.getpeername()[1] == expected_port handler = handle_socks5_negotiation(sock, negotiate=False) addr, port = next(handler) assert addr == "16.17.18.19" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks5://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager( proxy_url, source_address=("127.0.0.1", expected_port) ) as pm: response = pm.request("GET", "http://16.17.18.19") assert response.status == 200 class TestSOCKS4Proxy(IPV4SocketDummyServerTestCase): """ Test the SOCKS proxy in SOCKS4 mode. Has relatively fewer tests than the SOCKS5 case, mostly because once the negotiation is done the two cases behave identically. """ def test_basic_request(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks4_negotiation(sock) addr, port = next(handler) assert addr == "16.17.18.19" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks4://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://16.17.18.19") assert response.status == 200 assert response.headers["Server"] == "SocksTestServer" assert response.data == b"" def test_local_dns(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks4_negotiation(sock) addr, port = next(handler) assert addr == "127.0.0.1" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks4://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://localhost") assert response.status == 200 assert response.headers["Server"] == "SocksTestServer" assert response.data == b"" def test_correct_header_line(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks4_negotiation(sock) addr, port = next(handler) assert addr == b"example.com" assert port == 80 handler.send(True) buf = b"" while True: buf += sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break assert buf.startswith(b"GET / HTTP/1.1") assert b"Host: example.com" in buf sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks4a://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: response = pm.request("GET", "http://example.com") assert response.status == 200 def test_proxy_rejection(self): evt = threading.Event() def request_handler(listener): sock = listener.accept()[0] handler = handle_socks4_negotiation(sock) addr, port = next(handler) handler.send(False) evt.wait() sock.close() self._start_server(request_handler) proxy_url = "socks4a://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url) as pm: with pytest.raises(NewConnectionError): pm.request("GET", "http://example.com", retries=False) evt.set() def test_socks4_with_username(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks4_negotiation(sock, username=b"user") addr, port = next(handler) assert addr == "16.17.18.19" assert port == 80 handler.send(True) while True: buf = sock.recv(65535) if buf.endswith(b"\r\n\r\n"): break sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(request_handler) proxy_url = "socks4://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url, username="user") as pm: response = pm.request("GET", "http://16.17.18.19") assert response.status == 200 assert response.data == b"" assert response.headers["Server"] == "SocksTestServer" def test_socks_with_invalid_username(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks4_negotiation(sock, username=b"user") next(handler) self._start_server(request_handler) proxy_url = "socks4a://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url, username="baduser") as pm: with pytest.raises(NewConnectionError) as e: pm.request("GET", "http://example.com", retries=False) assert "different user-ids" in str(e.value) class TestSOCKSWithTLS(IPV4SocketDummyServerTestCase): """ Test that TLS behaves properly for SOCKS proxies. """ @pytest.mark.skipif(not HAS_SSL, reason="No TLS available") def test_basic_request(self): def request_handler(listener): sock = listener.accept()[0] handler = handle_socks5_negotiation(sock, negotiate=False) addr, port = next(handler) assert addr == b"localhost" assert port == 443 handler.send(True) # Wrap in TLS context = better_ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.load_cert_chain(DEFAULT_CERTS["certfile"], DEFAULT_CERTS["keyfile"]) tls = context.wrap_socket(sock, server_side=True) buf = b"" while True: buf += tls.recv(65535) if buf.endswith(b"\r\n\r\n"): break assert buf.startswith(b"GET / HTTP/1.1\r\n") tls.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: SocksTestServer\r\n" b"Content-Length: 0\r\n" b"\r\n" ) tls.close() sock.close() self._start_server(request_handler) proxy_url = "socks5h://%s:%s" % (self.host, self.port) with socks.SOCKSProxyManager(proxy_url, ca_certs=DEFAULT_CA) as pm: response = pm.request("GET", "https://localhost") assert response.status == 200 assert response.data == b"" assert response.headers["Server"] == "SocksTestServer" ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/port_helpers.py0000644000175000017500000001317000000000000022145 0ustar00sethmlarsonsethmlarson00000000000000# These helpers are copied from test_support.py in the Python 2.7 standard # library test suite. import socket # Don't use "localhost", since resolving it uses the DNS under recent # Windows versions (see issue #18792). HOST = "127.0.0.1" HOSTv6 = "::1" def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM): """Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned. Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl's s_server mode). Always prefer bind_port() over find_unused_port() where possible. Hard coded ports should *NEVER* be used. As soon as a server socket is bound to a hard coded port, the ability to run multiple instances of the test simultaneously on the same host is compromised, which makes the test a ticking time bomb in a buildbot environment. On Unix buildbots, this may simply manifest as a failed test, which can be recovered from without intervention in most cases, but on Windows, the entire python process can completely and utterly wedge, requiring someone to log in to the buildbot and manually kill the affected process. (This is easy to reproduce on Windows, unfortunately, and can be traced to the SO_REUSEADDR socket option having different semantics on Windows versus Unix/Linux. On Unix, you can't have two AF_INET SOCK_STREAM sockets bind, listen and then accept connections on identical host/ports. An EADDRINUSE socket.error will be raised at some point (depending on the platform and the order bind and listen were called on each socket). However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE will ever be raised when attempting to bind two identical host/ports. When accept() is called on each socket, the second caller's process will steal the port from the first caller, leaving them both in an awkwardly wedged state where they'll no longer respond to any signals or graceful kills, and must be forcibly killed via OpenProcess()/TerminateProcess(). The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option instead of SO_REUSEADDR, which effectively affords the same semantics as SO_REUSEADDR on Unix. Given the propensity of Unix developers in the Open Source world compared to Windows ones, this is a common mistake. A quick look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when openssl.exe is called with the 's_server' option, for example. See http://bugs.python.org/issue2550 for more info. The following site also has a very thorough description about the implications of both REUSEADDR and EXCLUSIVEADDRUSE on Windows: http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx) XXX: although this approach is a vast improvement on previous attempts to elicit unused ports, it rests heavily on the assumption that the ephemeral port returned to us by the OS won't immediately be dished back out to some other process when we close and delete our temporary socket but before our calling code has a chance to bind the returned port. We can deal with this issue if/when we come across it.""" tempsock = socket.socket(family, socktype) port = bind_port(tempsock) tempsock.close() del tempsock return port def bind_port(sock, host=HOST): """Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should *never* set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets. Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from bind()'ing to our host/port for the duration of the test. """ if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM: if hasattr(socket, "SO_REUSEADDR"): if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1: raise ValueError( "tests should never set the SO_REUSEADDR " "socket option on TCP/IP sockets!" ) if hasattr(socket, "SO_REUSEPORT"): if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1: raise ValueError( "tests should never set the SO_REUSEPORT " "socket option on TCP/IP sockets!" ) if hasattr(socket, "SO_EXCLUSIVEADDRUSE"): sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) sock.bind((host, 0)) port = sock.getsockname()[1] return port ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/socketpair_helper.py0000644000175000017500000000456600000000000023153 0ustar00sethmlarsonsethmlarson00000000000000import socket # Figuring out what errors could come out of a socket. There are three # different situations. Python 3 post-PEP3151 will define and use # BlockingIOError and InterruptedError from sockets. For Python pre-PEP3151 # both OSError and socket.error can be raised except on Windows where # WindowsError can also be raised. We want to catch all of these possible # exceptions so we catch WindowsError if it's defined. try: _CONNECT_ERROR = (BlockingIOError, InterruptedError) except NameError: try: _CONNECT_ERROR = (WindowsError, OSError, socket.error) # noqa: F821 except NameError: _CONNECT_ERROR = (OSError, socket.error) if hasattr(socket, "socketpair"): # Since Python 3.5, socket.socketpair() is now also available on Windows socketpair = socket.socketpair else: # Replacement for socket.socketpair() def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): """A socket pair usable as a self-pipe, for Windows. Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain. """ if family == socket.AF_INET: host = "127.0.0.1" elif family == socket.AF_INET6: host = "::1" else: raise ValueError( "Only AF_INET and AF_INET6 socket address families are supported" ) if type != socket.SOCK_STREAM: raise ValueError("Only SOCK_STREAM socket type is supported") if proto != 0: raise ValueError("Only protocol zero is supported") # We create a connected TCP socket. Note the trick with setblocking(0) # that prevents us from having to create a thread. lsock = socket.socket(family, type, proto) try: lsock.bind((host, 0)) lsock.listen(1) # On IPv6, ignore flow_info and scope_id addr, port = lsock.getsockname()[:2] csock = socket.socket(family, type, proto) try: csock.setblocking(False) try: csock.connect((addr, port)) except _CONNECT_ERROR: pass csock.setblocking(True) ssock, _ = lsock.accept() except Exception: csock.close() raise finally: lsock.close() return (ssock, csock) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_collections.py0000644000175000017500000002457000000000000023022 0ustar00sethmlarsonsethmlarson00000000000000from urllib3._collections import HTTPHeaderDict, RecentlyUsedContainer as Container import pytest from urllib3.exceptions import InvalidHeader from urllib3.packages import six xrange = six.moves.xrange class TestLRUContainer(object): def test_maxsize(self): d = Container(5) for i in xrange(5): d[i] = str(i) assert len(d) == 5 for i in xrange(5): assert d[i] == str(i) d[i + 1] = str(i + 1) assert len(d) == 5 assert 0 not in d assert (i + 1) in d def test_expire(self): d = Container(5) for i in xrange(5): d[i] = str(i) for i in xrange(5): d.get(0) # Add one more entry d[5] = "5" # Check state assert list(d.keys()) == [2, 3, 4, 0, 5] def test_same_key(self): d = Container(5) for i in xrange(10): d["foo"] = i assert list(d.keys()) == ["foo"] assert len(d) == 1 def test_access_ordering(self): d = Container(5) for i in xrange(10): d[i] = True # Keys should be ordered by access time assert list(d.keys()) == [5, 6, 7, 8, 9] new_order = [7, 8, 6, 9, 5] for k in new_order: d[k] assert list(d.keys()) == new_order def test_delete(self): d = Container(5) for i in xrange(5): d[i] = True del d[0] assert 0 not in d d.pop(1) assert 1 not in d d.pop(1, None) def test_get(self): d = Container(5) for i in xrange(5): d[i] = True r = d.get(4) assert r is True r = d.get(5) assert r is None r = d.get(5, 42) assert r == 42 with pytest.raises(KeyError): d[5] def test_disposal(self): evicted_items = [] def dispose_func(arg): # Save the evicted datum for inspection evicted_items.append(arg) d = Container(5, dispose_func=dispose_func) for i in xrange(5): d[i] = i assert list(d.keys()) == list(xrange(5)) assert evicted_items == [] # Nothing disposed d[5] = 5 assert list(d.keys()) == list(xrange(1, 6)) assert evicted_items == [0] del d[1] assert evicted_items == [0, 1] d.clear() assert evicted_items == [0, 1, 2, 3, 4, 5] def test_iter(self): d = Container() with pytest.raises(NotImplementedError): d.__iter__() class NonMappingHeaderContainer(object): def __init__(self, **kwargs): self._data = {} self._data.update(kwargs) def keys(self): return self._data.keys() def __getitem__(self, key): return self._data[key] @pytest.fixture() def d(): header_dict = HTTPHeaderDict(Cookie="foo") header_dict.add("cookie", "bar") return header_dict class TestHTTPHeaderDict(object): def test_create_from_kwargs(self): h = HTTPHeaderDict(ab=1, cd=2, ef=3, gh=4) assert len(h) == 4 assert "ab" in h def test_create_from_dict(self): h = HTTPHeaderDict(dict(ab=1, cd=2, ef=3, gh=4)) assert len(h) == 4 assert "ab" in h def test_create_from_iterator(self): teststr = "urllib3ontherocks" h = HTTPHeaderDict((c, c * 5) for c in teststr) assert len(h) == len(set(teststr)) def test_create_from_list(self): headers = [ ("ab", "A"), ("cd", "B"), ("cookie", "C"), ("cookie", "D"), ("cookie", "E"), ] h = HTTPHeaderDict(headers) assert len(h) == 3 assert "ab" in h clist = h.getlist("cookie") assert len(clist) == 3 assert clist[0] == "C" assert clist[-1] == "E" def test_create_from_headerdict(self): headers = [ ("ab", "A"), ("cd", "B"), ("cookie", "C"), ("cookie", "D"), ("cookie", "E"), ] org = HTTPHeaderDict(headers) h = HTTPHeaderDict(org) assert len(h) == 3 assert "ab" in h clist = h.getlist("cookie") assert len(clist) == 3 assert clist[0] == "C" assert clist[-1] == "E" assert h is not org assert h == org def test_setitem(self, d): d["Cookie"] = "foo" assert d["cookie"] == "foo" d["cookie"] = "with, comma" assert d.getlist("cookie") == ["with, comma"] def test_update(self, d): d.update(dict(Cookie="foo")) assert d["cookie"] == "foo" d.update(dict(cookie="with, comma")) assert d.getlist("cookie") == ["with, comma"] def test_delitem(self, d): del d["cookie"] assert "cookie" not in d assert "COOKIE" not in d def test_add_well_known_multiheader(self, d): d.add("COOKIE", "asdf") assert d.getlist("cookie") == ["foo", "bar", "asdf"] assert d["cookie"] == "foo, bar, asdf" def test_add_comma_separated_multiheader(self, d): d.add("bar", "foo") d.add("BAR", "bar") d.add("Bar", "asdf") assert d.getlist("bar") == ["foo", "bar", "asdf"] assert d["bar"] == "foo, bar, asdf" def test_extend_from_list(self, d): d.extend([("set-cookie", "100"), ("set-cookie", "200"), ("set-cookie", "300")]) assert d["set-cookie"] == "100, 200, 300" def test_extend_from_dict(self, d): d.extend(dict(cookie="asdf"), b="100") assert d["cookie"] == "foo, bar, asdf" assert d["b"] == "100" d.add("cookie", "with, comma") assert d.getlist("cookie") == ["foo", "bar", "asdf", "with, comma"] def test_extend_from_container(self, d): h = NonMappingHeaderContainer(Cookie="foo", e="foofoo") d.extend(h) assert d["cookie"] == "foo, bar, foo" assert d["e"] == "foofoo" assert len(d) == 2 def test_extend_from_headerdict(self, d): h = HTTPHeaderDict(Cookie="foo", e="foofoo") d.extend(h) assert d["cookie"] == "foo, bar, foo" assert d["e"] == "foofoo" assert len(d) == 2 @pytest.mark.parametrize("args", [(1, 2), (1, 2, 3, 4, 5)]) def test_extend_with_wrong_number_of_args_is_typeerror(self, d, args): with pytest.raises(TypeError) as err: d.extend(*args) assert "extend() takes at most 1 positional arguments" in err.value.args[0] def test_copy(self, d): h = d.copy() assert d is not h assert d == h def test_getlist(self, d): assert d.getlist("cookie") == ["foo", "bar"] assert d.getlist("Cookie") == ["foo", "bar"] assert d.getlist("b") == [] d.add("b", "asdf") assert d.getlist("b") == ["asdf"] def test_getlist_after_copy(self, d): assert d.getlist("cookie") == HTTPHeaderDict(d).getlist("cookie") def test_equal(self, d): b = HTTPHeaderDict(cookie="foo, bar") c = NonMappingHeaderContainer(cookie="foo, bar") assert d == b assert d == c assert d != 2 def test_not_equal(self, d): b = HTTPHeaderDict(cookie="foo, bar") c = NonMappingHeaderContainer(cookie="foo, bar") assert not (d != b) assert not (d != c) assert d != 2 def test_pop(self, d): key = "Cookie" a = d[key] b = d.pop(key) assert a == b assert key not in d with pytest.raises(KeyError): d.pop(key) dummy = object() assert dummy is d.pop(key, dummy) def test_discard(self, d): d.discard("cookie") assert "cookie" not in d d.discard("cookie") def test_len(self, d): assert len(d) == 1 d.add("cookie", "bla") d.add("asdf", "foo") # len determined by unique fieldnames assert len(d) == 2 def test_repr(self, d): rep = "HTTPHeaderDict({'Cookie': 'foo, bar'})" assert repr(d) == rep def test_items(self, d): items = d.items() assert len(items) == 2 assert items[0][0] == "Cookie" assert items[0][1] == "foo" assert items[1][0] == "Cookie" assert items[1][1] == "bar" def test_dict_conversion(self, d): # Also tested in connectionpool, needs to preserve case hdict = { "Content-Length": "0", "Content-type": "text/plain", "Server": "TornadoServer/1.2.3", } h = dict(HTTPHeaderDict(hdict).items()) assert hdict == h assert hdict == dict(HTTPHeaderDict(hdict)) def test_string_enforcement(self, d): # This currently throws AttributeError on key.lower(), should # probably be something nicer with pytest.raises(Exception): d[3] = 5 with pytest.raises(Exception): d.add(3, 4) with pytest.raises(Exception): del d[3] with pytest.raises(Exception): HTTPHeaderDict({3: 3}) @pytest.mark.skipif( not six.PY2, reason="python3 has a different internal header implementation" ) def test_from_httplib_py2(self): msg = """ Server: nginx Content-Type: text/html; charset=windows-1251 Connection: keep-alive X-Some-Multiline: asdf asdf\t \t asdf Set-Cookie: bb_lastvisit=1348253375; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/ Set-Cookie: bb_lastactivity=0; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/ www-authenticate: asdf www-authenticate: bla """ buffer = six.moves.StringIO(msg.lstrip().replace("\n", "\r\n")) msg = six.moves.http_client.HTTPMessage(buffer) d = HTTPHeaderDict.from_httplib(msg) assert d["server"] == "nginx" cookies = d.getlist("set-cookie") assert len(cookies) == 2 assert cookies[0].startswith("bb_lastvisit") assert cookies[1].startswith("bb_lastactivity") assert d["x-some-multiline"] == "asdf asdf asdf" assert d["www-authenticate"] == "asdf, bla" assert d.getlist("www-authenticate") == ["asdf", "bla"] with_invalid_multiline = """\tthis-is-not-a-header: but it has a pretend value Authorization: Bearer 123 """ buffer = six.moves.StringIO(with_invalid_multiline.replace("\n", "\r\n")) msg = six.moves.http_client.HTTPMessage(buffer) with pytest.raises(InvalidHeader): HTTPHeaderDict.from_httplib(msg) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_compatibility.py0000644000175000017500000000270700000000000023353 0ustar00sethmlarsonsethmlarson00000000000000import warnings import pytest from urllib3.connection import HTTPConnection from urllib3.response import HTTPResponse from urllib3.packages.six.moves import http_cookiejar, urllib class TestVersionCompatibility(object): def test_connection_strict(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # strict=True is deprecated in Py33+ HTTPConnection("localhost", 12345, strict=True) if w: pytest.fail( "HTTPConnection raised warning on strict=True: %r" % w[0].message ) def test_connection_source_address(self): try: # source_address does not exist in Py26- HTTPConnection("localhost", 12345, source_address="127.0.0.1") except TypeError as e: pytest.fail("HTTPConnection raised TypeError on source_address: %r" % e) class TestCookiejar(object): def test_extract(self): request = urllib.request.Request("http://google.com") cookiejar = http_cookiejar.CookieJar() response = HTTPResponse() cookies = [ "sessionhash=abcabcabcabcab; path=/; HttpOnly", "lastvisit=1348253375; expires=Sat, 21-Sep-2050 18:49:35 GMT; path=/", ] for c in cookies: response.headers.add("set-cookie", c) cookiejar.extract_cookies(response, request) assert len(cookiejar) == len(cookies) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_connection.py0000644000175000017500000000350400000000000022635 0ustar00sethmlarsonsethmlarson00000000000000import datetime import mock import pytest from urllib3.connection import CertificateError, _match_hostname, RECENT_DATE class TestConnection(object): """ Tests in this suite should not make any network requests or connections. """ def test_match_hostname_no_cert(self): cert = None asserted_hostname = "foo" with pytest.raises(ValueError): _match_hostname(cert, asserted_hostname) def test_match_hostname_empty_cert(self): cert = {} asserted_hostname = "foo" with pytest.raises(ValueError): _match_hostname(cert, asserted_hostname) def test_match_hostname_match(self): cert = {"subjectAltName": [("DNS", "foo")]} asserted_hostname = "foo" _match_hostname(cert, asserted_hostname) def test_match_hostname_mismatch(self): cert = {"subjectAltName": [("DNS", "foo")]} asserted_hostname = "bar" try: with mock.patch("urllib3.connection.log.warning") as mock_log: _match_hostname(cert, asserted_hostname) except CertificateError as e: assert "hostname 'bar' doesn't match 'foo'" in str(e) mock_log.assert_called_once_with( "Certificate did not match expected hostname: %s. Certificate: %s", "bar", {"subjectAltName": [("DNS", "foo")]}, ) assert e._peer_cert == cert def test_recent_date(self): # This test is to make sure that the RECENT_DATE value # doesn't get too far behind what the current date is. # When this test fails update urllib3.connection.RECENT_DATE # according to the rules defined in that file. two_years = datetime.timedelta(days=365 * 2) assert RECENT_DATE > (datetime.datetime.today() - two_years).date() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_connectionpool.py0000644000175000017500000004352200000000000023533 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import ssl import pytest from urllib3.connectionpool import ( connection_from_url, HTTPConnection, HTTPConnectionPool, HTTPSConnectionPool, ) from urllib3.response import httplib, HTTPResponse from urllib3.util.timeout import Timeout from urllib3.packages.six.moves.http_client import HTTPException from urllib3.packages.six.moves.queue import Empty from urllib3.packages.ssl_match_hostname import CertificateError from urllib3.exceptions import ( ClosedPoolError, EmptyPoolError, HostChangedError, LocationValueError, MaxRetryError, ProtocolError, SSLError, TimeoutError, ) from urllib3._collections import HTTPHeaderDict from .test_response import MockChunkedEncodingResponse, MockSock from socket import error as SocketError from ssl import SSLError as BaseSSLError from dummyserver.server import DEFAULT_CA from test import SHORT_TIMEOUT class HTTPUnixConnection(HTTPConnection): def __init__(self, host, timeout=60, **kwargs): super(HTTPUnixConnection, self).__init__("localhost") self.unix_socket = host self.timeout = timeout self.sock = None class HTTPUnixConnectionPool(HTTPConnectionPool): scheme = "http+unix" ConnectionCls = HTTPUnixConnection class TestConnectionPool(object): """ Tests in this suite should exercise the ConnectionPool functionality without actually making any network requests or connections. """ @pytest.mark.parametrize( "a, b", [ ("http://google.com/", "/"), ("http://google.com/", "http://google.com/"), ("http://google.com/", "http://google.com"), ("http://google.com/", "http://google.com/abra/cadabra"), ("http://google.com:42/", "http://google.com:42/abracadabra"), # Test comparison using default ports ("http://google.com:80/", "http://google.com/abracadabra"), ("http://google.com/", "http://google.com:80/abracadabra"), ("https://google.com:443/", "https://google.com/abracadabra"), ("https://google.com/", "https://google.com:443/abracadabra"), ( "http://[2607:f8b0:4005:805::200e%25eth0]/", "http://[2607:f8b0:4005:805::200e%eth0]/", ), ( "https://[2607:f8b0:4005:805::200e%25eth0]:443/", "https://[2607:f8b0:4005:805::200e%eth0]:443/", ), ("http://[::1]/", "http://[::1]"), ( "http://[2001:558:fc00:200:f816:3eff:fef9:b954%lo]/", "http://[2001:558:fc00:200:f816:3eff:fef9:b954%25lo]", ), ], ) def test_same_host(self, a, b): with connection_from_url(a) as c: assert c.is_same_host(b) @pytest.mark.parametrize( "a, b", [ ("https://google.com/", "http://google.com/"), ("http://google.com/", "https://google.com/"), ("http://yahoo.com/", "http://google.com/"), ("http://google.com:42", "https://google.com/abracadabra"), ("http://google.com", "https://google.net/"), # Test comparison with default ports ("http://google.com:42", "http://google.com"), ("https://google.com:42", "https://google.com"), ("http://google.com:443", "http://google.com"), ("https://google.com:80", "https://google.com"), ("http://google.com:443", "https://google.com"), ("https://google.com:80", "http://google.com"), ("https://google.com:443", "http://google.com"), ("http://google.com:80", "https://google.com"), # Zone identifiers are unique connection end points and should # never be equivalent. ("http://[dead::beef]", "https://[dead::beef%en5]/"), ], ) def test_not_same_host(self, a, b): with connection_from_url(a) as c: assert not c.is_same_host(b) with connection_from_url(b) as c: assert not c.is_same_host(a) @pytest.mark.parametrize( "a, b", [ ("google.com", "/"), ("google.com", "http://google.com/"), ("google.com", "http://google.com"), ("google.com", "http://google.com/abra/cadabra"), # Test comparison using default ports ("google.com", "http://google.com:80/abracadabra"), ], ) def test_same_host_no_port_http(self, a, b): # This test was introduced in #801 to deal with the fact that urllib3 # never initializes ConnectionPool objects with port=None. with HTTPConnectionPool(a) as c: assert c.is_same_host(b) @pytest.mark.parametrize( "a, b", [ ("google.com", "/"), ("google.com", "https://google.com/"), ("google.com", "https://google.com"), ("google.com", "https://google.com/abra/cadabra"), # Test comparison using default ports ("google.com", "https://google.com:443/abracadabra"), ], ) def test_same_host_no_port_https(self, a, b): # This test was introduced in #801 to deal with the fact that urllib3 # never initializes ConnectionPool objects with port=None. with HTTPSConnectionPool(a) as c: assert c.is_same_host(b) @pytest.mark.parametrize( "a, b", [ ("google.com", "https://google.com/"), ("yahoo.com", "http://google.com/"), ("google.com", "https://google.net/"), ("google.com", "http://google.com./"), ], ) def test_not_same_host_no_port_http(self, a, b): with HTTPConnectionPool(a) as c: assert not c.is_same_host(b) with HTTPConnectionPool(b) as c: assert not c.is_same_host(a) @pytest.mark.parametrize( "a, b", [ ("google.com", "http://google.com/"), ("yahoo.com", "https://google.com/"), ("google.com", "https://google.net/"), ("google.com", "https://google.com./"), ], ) def test_not_same_host_no_port_https(self, a, b): with HTTPSConnectionPool(a) as c: assert not c.is_same_host(b) with HTTPSConnectionPool(b) as c: assert not c.is_same_host(a) @pytest.mark.parametrize( "a, b", [ ("%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Fvar%2Frun%2Fdocker.sock"), ("%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Fvar%2Frun%2Fdocker.sock/"), ( "%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Fvar%2Frun%2Fdocker.sock/abracadabra", ), ("%2Ftmp%2FTEST.sock", "http+unix://%2Ftmp%2FTEST.sock"), ("%2Ftmp%2FTEST.sock", "http+unix://%2Ftmp%2FTEST.sock/"), ("%2Ftmp%2FTEST.sock", "http+unix://%2Ftmp%2FTEST.sock/abracadabra"), ], ) def test_same_host_custom_protocol(self, a, b): with HTTPUnixConnectionPool(a) as c: assert c.is_same_host(b) @pytest.mark.parametrize( "a, b", [ ("%2Ftmp%2Ftest.sock", "http+unix://%2Ftmp%2FTEST.sock"), ("%2Ftmp%2Ftest.sock", "http+unix://%2Ftmp%2FTEST.sock/"), ("%2Ftmp%2Ftest.sock", "http+unix://%2Ftmp%2FTEST.sock/abracadabra"), ("%2Fvar%2Frun%2Fdocker.sock", "http+unix://%2Ftmp%2FTEST.sock"), ], ) def test_not_same_host_custom_protocol(self, a, b): with HTTPUnixConnectionPool(a) as c: assert not c.is_same_host(b) def test_max_connections(self): with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: pool._get_conn(timeout=SHORT_TIMEOUT) with pytest.raises(EmptyPoolError): pool._get_conn(timeout=SHORT_TIMEOUT) with pytest.raises(EmptyPoolError): pool.request("GET", "/", pool_timeout=SHORT_TIMEOUT) assert pool.num_connections == 1 def test_pool_edgecases(self): with HTTPConnectionPool(host="localhost", maxsize=1, block=False) as pool: conn1 = pool._get_conn() conn2 = pool._get_conn() # New because block=False pool._put_conn(conn1) pool._put_conn(conn2) # Should be discarded assert conn1 == pool._get_conn() assert conn2 != pool._get_conn() assert pool.num_connections == 3 def test_exception_str(self): assert ( str(EmptyPoolError(HTTPConnectionPool(host="localhost"), "Test.")) == "HTTPConnectionPool(host='localhost', port=None): Test." ) def test_retry_exception_str(self): assert ( str(MaxRetryError(HTTPConnectionPool(host="localhost"), "Test.", None)) == "HTTPConnectionPool(host='localhost', port=None): " "Max retries exceeded with url: Test. (Caused by None)" ) err = SocketError("Test") # using err.__class__ here, as socket.error is an alias for OSError # since Py3.3 and gets printed as this assert ( str(MaxRetryError(HTTPConnectionPool(host="localhost"), "Test.", err)) == "HTTPConnectionPool(host='localhost', port=None): " "Max retries exceeded with url: Test. " "(Caused by %r)" % err ) def test_pool_size(self): POOL_SIZE = 1 with HTTPConnectionPool( host="localhost", maxsize=POOL_SIZE, block=True ) as pool: def _raise(ex): raise ex() def _test(exception, expect, reason=None): pool._make_request = lambda *args, **kwargs: _raise(exception) with pytest.raises(expect) as excinfo: pool.request("GET", "/") if reason is not None: assert isinstance(excinfo.value.reason, reason) assert pool.pool.qsize() == POOL_SIZE # Make sure that all of the exceptions return the connection # to the pool _test(Empty, EmptyPoolError) _test(BaseSSLError, MaxRetryError, SSLError) _test(CertificateError, MaxRetryError, SSLError) # The pool should never be empty, and with these two exceptions # being raised, a retry will be triggered, but that retry will # fail, eventually raising MaxRetryError, not EmptyPoolError # See: https://github.com/urllib3/urllib3/issues/76 pool._make_request = lambda *args, **kwargs: _raise(HTTPException) with pytest.raises(MaxRetryError): pool.request("GET", "/", retries=1, pool_timeout=SHORT_TIMEOUT) assert pool.pool.qsize() == POOL_SIZE def test_assert_same_host(self): with connection_from_url("http://google.com:80") as c: with pytest.raises(HostChangedError): c.request("GET", "http://yahoo.com:80", assert_same_host=True) def test_pool_close(self): pool = connection_from_url("http://google.com:80") # Populate with some connections conn1 = pool._get_conn() conn2 = pool._get_conn() conn3 = pool._get_conn() pool._put_conn(conn1) pool._put_conn(conn2) old_pool_queue = pool.pool pool.close() assert pool.pool is None with pytest.raises(ClosedPoolError): pool._get_conn() pool._put_conn(conn3) with pytest.raises(ClosedPoolError): pool._get_conn() with pytest.raises(Empty): old_pool_queue.get(block=False) def test_pool_close_twice(self): pool = connection_from_url("http://google.com:80") # Populate with some connections conn1 = pool._get_conn() conn2 = pool._get_conn() pool._put_conn(conn1) pool._put_conn(conn2) pool.close() assert pool.pool is None try: pool.close() except AttributeError: pytest.fail("Pool of the ConnectionPool is None and has no attribute get.") def test_pool_timeouts(self): with HTTPConnectionPool(host="localhost") as pool: conn = pool._new_conn() assert conn.__class__ == HTTPConnection assert pool.timeout.__class__ == Timeout assert pool.timeout._read == Timeout.DEFAULT_TIMEOUT assert pool.timeout._connect == Timeout.DEFAULT_TIMEOUT assert pool.timeout.total is None pool = HTTPConnectionPool(host="localhost", timeout=SHORT_TIMEOUT) assert pool.timeout._read == SHORT_TIMEOUT assert pool.timeout._connect == SHORT_TIMEOUT assert pool.timeout.total is None def test_no_host(self): with pytest.raises(LocationValueError): HTTPConnectionPool(None) def test_contextmanager(self): with connection_from_url("http://google.com:80") as pool: # Populate with some connections conn1 = pool._get_conn() conn2 = pool._get_conn() conn3 = pool._get_conn() pool._put_conn(conn1) pool._put_conn(conn2) old_pool_queue = pool.pool assert pool.pool is None with pytest.raises(ClosedPoolError): pool._get_conn() pool._put_conn(conn3) with pytest.raises(ClosedPoolError): pool._get_conn() with pytest.raises(Empty): old_pool_queue.get(block=False) def test_absolute_url(self): with connection_from_url("http://google.com:80") as c: assert "http://google.com:80/path?query=foo" == c._absolute_url( "path?query=foo" ) def test_ca_certs_default_cert_required(self): with connection_from_url("https://google.com:80", ca_certs=DEFAULT_CA) as pool: conn = pool._get_conn() assert conn.cert_reqs == ssl.CERT_REQUIRED def test_cleanup_on_extreme_connection_error(self): """ This test validates that we clean up properly even on exceptions that we'd not otherwise catch, i.e. those that inherit from BaseException like KeyboardInterrupt or gevent.Timeout. See #805 for more details. """ class RealBad(BaseException): pass def kaboom(*args, **kwargs): raise RealBad() with connection_from_url("http://localhost:80") as c: c._make_request = kaboom initial_pool_size = c.pool.qsize() try: # We need to release_conn this way or we'd put it away # regardless. c.urlopen("GET", "/", release_conn=False) except RealBad: pass new_pool_size = c.pool.qsize() assert initial_pool_size == new_pool_size def test_release_conn_param_is_respected_after_http_error_retry(self): """For successful ```urlopen(release_conn=False)```, the connection isn't released, even after a retry. This is a regression test for issue #651 [1], where the connection would be released if the initial request failed, even if a retry succeeded. [1] """ class _raise_once_make_request_function(object): """Callable that can mimic `_make_request()`. Raises the given exception on its first call, but returns a successful response on subsequent calls. """ def __init__(self, ex): super(_raise_once_make_request_function, self).__init__() self._ex = ex def __call__(self, *args, **kwargs): if self._ex: ex, self._ex = self._ex, None raise ex() response = httplib.HTTPResponse(MockSock) response.fp = MockChunkedEncodingResponse([b"f", b"o", b"o"]) response.headers = response.msg = HTTPHeaderDict() return response def _test(exception): with HTTPConnectionPool(host="localhost", maxsize=1, block=True) as pool: # Verify that the request succeeds after two attempts, and that the # connection is left on the response object, instead of being # released back into the pool. pool._make_request = _raise_once_make_request_function(exception) response = pool.urlopen( "GET", "/", retries=1, release_conn=False, preload_content=False, chunked=True, ) assert pool.pool.qsize() == 0 assert pool.num_connections == 2 assert response.connection is not None response.release_conn() assert pool.pool.qsize() == 1 assert response.connection is None # Run the test case for all the retriable exceptions. _test(TimeoutError) _test(HTTPException) _test(SocketError) _test(ProtocolError) def test_custom_http_response_class(self): class CustomHTTPResponse(HTTPResponse): pass class CustomConnectionPool(HTTPConnectionPool): ResponseCls = CustomHTTPResponse def _make_request(self, *args, **kwargs): httplib_response = httplib.HTTPResponse(MockSock) httplib_response.fp = MockChunkedEncodingResponse([b"f", b"o", b"o"]) httplib_response.headers = httplib_response.msg = HTTPHeaderDict() return httplib_response with CustomConnectionPool(host="localhost", maxsize=1, block=True) as pool: response = pool.request( "GET", "/", retries=False, chunked=True, preload_content=False ) assert isinstance(response, CustomHTTPResponse) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_exceptions.py0000644000175000017500000000257700000000000022670 0ustar00sethmlarsonsethmlarson00000000000000import pickle import pytest from urllib3.exceptions import ( HTTPError, MaxRetryError, LocationParseError, ClosedPoolError, EmptyPoolError, HostChangedError, ReadTimeoutError, ConnectTimeoutError, HeaderParsingError, ) from urllib3.connectionpool import HTTPConnectionPool class TestPickle(object): @pytest.mark.parametrize( "exception", [ HTTPError(None), MaxRetryError(None, None, None), LocationParseError(None), ConnectTimeoutError(None), HTTPError("foo"), HTTPError("foo", IOError("foo")), MaxRetryError(HTTPConnectionPool("localhost"), "/", None), LocationParseError("fake location"), ClosedPoolError(HTTPConnectionPool("localhost"), None), EmptyPoolError(HTTPConnectionPool("localhost"), None), HostChangedError(HTTPConnectionPool("localhost"), "/", None), ReadTimeoutError(HTTPConnectionPool("localhost"), "/", None), ], ) def test_exceptions(self, exception): result = pickle.loads(pickle.dumps(exception)) assert isinstance(result, type(exception)) class TestFormat(object): def test_header_parsing_errors(self): hpe = HeaderParsingError("defects", "unparsed_data") assert "defects" in str(hpe) assert "unparsed_data" in str(hpe) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_fields.py0000644000175000017500000001016000000000000021740 0ustar00sethmlarsonsethmlarson00000000000000import pytest from urllib3.fields import format_header_param_rfc2231, guess_content_type, RequestField from urllib3.packages.six import u class TestRequestField(object): @pytest.mark.parametrize( "filename, content_types", [ ("image.jpg", ["image/jpeg", "image/pjpeg"]), ("notsure", ["application/octet-stream"]), (None, ["application/octet-stream"]), ], ) def test_guess_content_type(self, filename, content_types): assert guess_content_type(filename) in content_types def test_create(self): simple_field = RequestField("somename", "data") assert simple_field.render_headers() == "\r\n" filename_field = RequestField("somename", "data", filename="somefile.txt") assert filename_field.render_headers() == "\r\n" headers_field = RequestField("somename", "data", headers={"Content-Length": 4}) assert headers_field.render_headers() == "Content-Length: 4\r\n\r\n" def test_make_multipart(self): field = RequestField("somename", "data") field.make_multipart(content_type="image/jpg", content_location="/test") assert ( field.render_headers() == 'Content-Disposition: form-data; name="somename"\r\n' "Content-Type: image/jpg\r\n" "Content-Location: /test\r\n" "\r\n" ) def test_make_multipart_empty_filename(self): field = RequestField("somename", "data", "") field.make_multipart(content_type="application/octet-stream") assert ( field.render_headers() == 'Content-Disposition: form-data; name="somename"; filename=""\r\n' "Content-Type: application/octet-stream\r\n" "\r\n" ) def test_render_parts(self): field = RequestField("somename", "data") parts = field._render_parts({"name": "value", "filename": "value"}) assert 'name="value"' in parts assert 'filename="value"' in parts parts = field._render_parts([("name", "value"), ("filename", "value")]) assert parts == 'name="value"; filename="value"' def test_render_part_rfc2231_unicode(self): field = RequestField( "somename", "data", header_formatter=format_header_param_rfc2231 ) param = field._render_part("filename", u("n\u00e4me")) assert param == "filename*=utf-8''n%C3%A4me" def test_render_part_rfc2231_ascii(self): field = RequestField( "somename", "data", header_formatter=format_header_param_rfc2231 ) param = field._render_part("filename", b"name") assert param == 'filename="name"' def test_render_part_html5_unicode(self): field = RequestField("somename", "data") param = field._render_part("filename", u("n\u00e4me")) assert param == u('filename="n\u00e4me"') def test_render_part_html5_ascii(self): field = RequestField("somename", "data") param = field._render_part("filename", b"name") assert param == 'filename="name"' def test_render_part_html5_unicode_escape(self): field = RequestField("somename", "data") param = field._render_part("filename", u("hello\\world\u0022")) assert param == u('filename="hello\\\\world%22"') def test_render_part_html5_unicode_with_control_character(self): field = RequestField("somename", "data") param = field._render_part("filename", u("hello\x1A\x1B\x1C")) assert param == u('filename="hello%1A\x1B%1C"') def test_from_tuples_rfc2231(self): field = RequestField.from_tuples( u("fieldname"), (u("filen\u00e4me"), "data"), header_formatter=format_header_param_rfc2231, ) cd = field.headers["Content-Disposition"] assert cd == u("form-data; name=\"fieldname\"; filename*=utf-8''filen%C3%A4me") def test_from_tuples_html5(self): field = RequestField.from_tuples(u("fieldname"), (u("filen\u00e4me"), "data")) cd = field.headers["Content-Disposition"] assert cd == u('form-data; name="fieldname"; filename="filen\u00e4me"') ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_filepost.py0000644000175000017500000001001400000000000022315 0ustar00sethmlarsonsethmlarson00000000000000import pytest from urllib3.filepost import encode_multipart_formdata, iter_fields from urllib3.fields import RequestField from urllib3.packages.six import b, u BOUNDARY = "!! test boundary !!" class TestIterfields(object): def test_dict(self): for fieldname, value in iter_fields(dict(a="b")): assert (fieldname, value) == ("a", "b") assert list(sorted(iter_fields(dict(a="b", c="d")))) == [("a", "b"), ("c", "d")] def test_tuple_list(self): for fieldname, value in iter_fields([("a", "b")]): assert (fieldname, value) == ("a", "b") assert list(iter_fields([("a", "b"), ("c", "d")])) == [("a", "b"), ("c", "d")] class TestMultipartEncoding(object): @pytest.mark.parametrize( "fields", [dict(k="v", k2="v2"), [("k", "v"), ("k2", "v2")]] ) def test_input_datastructures(self, fields): encoded, _ = encode_multipart_formdata(fields, boundary=BOUNDARY) assert encoded.count(b(BOUNDARY)) == 3 @pytest.mark.parametrize( "fields", [ [("k", "v"), ("k2", "v2")], [("k", b"v"), (u("k2"), b"v2")], [("k", b"v"), (u("k2"), "v2")], ], ) def test_field_encoding(self, fields): encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY) expected = ( b"--" + b(BOUNDARY) + b"\r\n" b'Content-Disposition: form-data; name="k"\r\n' b"\r\n" b"v\r\n" b"--" + b(BOUNDARY) + b"\r\n" b'Content-Disposition: form-data; name="k2"\r\n' b"\r\n" b"v2\r\n" b"--" + b(BOUNDARY) + b"--\r\n" ) assert encoded == expected assert content_type == "multipart/form-data; boundary=" + str(BOUNDARY) def test_filename(self): fields = [("k", ("somename", b"v"))] encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY) expected = ( b"--" + b(BOUNDARY) + b"\r\n" b'Content-Disposition: form-data; name="k"; filename="somename"\r\n' b"Content-Type: application/octet-stream\r\n" b"\r\n" b"v\r\n" b"--" + b(BOUNDARY) + b"--\r\n" ) assert encoded == expected assert content_type == "multipart/form-data; boundary=" + str(BOUNDARY) def test_textplain(self): fields = [("k", ("somefile.txt", b"v"))] encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY) expected = ( b"--" + b(BOUNDARY) + b"\r\n" b'Content-Disposition: form-data; name="k"; filename="somefile.txt"\r\n' b"Content-Type: text/plain\r\n" b"\r\n" b"v\r\n" b"--" + b(BOUNDARY) + b"--\r\n" ) assert encoded == expected assert content_type == "multipart/form-data; boundary=" + str(BOUNDARY) def test_explicit(self): fields = [("k", ("somefile.txt", b"v", "image/jpeg"))] encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY) expected = ( b"--" + b(BOUNDARY) + b"\r\n" b'Content-Disposition: form-data; name="k"; filename="somefile.txt"\r\n' b"Content-Type: image/jpeg\r\n" b"\r\n" b"v\r\n" b"--" + b(BOUNDARY) + b"--\r\n" ) assert encoded == expected assert content_type == "multipart/form-data; boundary=" + str(BOUNDARY) def test_request_fields(self): fields = [ RequestField( "k", b"v", filename="somefile.txt", headers={"Content-Type": "image/jpeg"}, ) ] encoded, content_type = encode_multipart_formdata(fields, boundary=BOUNDARY) expected = ( b"--" + b(BOUNDARY) + b"\r\n" b"Content-Type: image/jpeg\r\n" b"\r\n" b"v\r\n" b"--" + b(BOUNDARY) + b"--\r\n" ) assert encoded == expected ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_no_ssl.py0000644000175000017500000000426600000000000022001 0ustar00sethmlarsonsethmlarson00000000000000""" Test what happens if Python was built without SSL * Everything that does not involve HTTPS should still work * HTTPS requests must fail with an error that points at the ssl module """ import sys import pytest class ImportBlocker(object): """ Block Imports To be placed on ``sys.meta_path``. This ensures that the modules specified cannot be imported, even if they are a builtin. """ def __init__(self, *namestoblock): self.namestoblock = namestoblock def find_module(self, fullname, path=None): if fullname in self.namestoblock: return self return None def load_module(self, fullname): raise ImportError("import of {0} is blocked".format(fullname)) class ModuleStash(object): """ Stashes away previously imported modules If we reimport a module the data from coverage is lost, so we reuse the old modules """ def __init__(self, namespace, modules=sys.modules): self.namespace = namespace self.modules = modules self._data = {} def stash(self): self._data[self.namespace] = self.modules.pop(self.namespace, None) for module in list(self.modules.keys()): if module.startswith(self.namespace + "."): self._data[module] = self.modules.pop(module) def pop(self): self.modules.pop(self.namespace, None) for module in list(self.modules.keys()): if module.startswith(self.namespace + "."): self.modules.pop(module) self.modules.update(self._data) ssl_blocker = ImportBlocker("ssl", "_ssl") module_stash = ModuleStash("urllib3") class TestWithoutSSL(object): @classmethod def setup_class(cls): sys.modules.pop("ssl", None) sys.modules.pop("_ssl", None) module_stash.stash() sys.meta_path.insert(0, ssl_blocker) def teardown_class(cls): sys.meta_path.remove(ssl_blocker) module_stash.pop() class TestImportWithoutSSL(TestWithoutSSL): def test_cannot_import_ssl(self): with pytest.raises(ImportError): import ssl # noqa: F401 def test_import_urllib3(self): import urllib3 # noqa: F401 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_poolmanager.py0000644000175000017500000003251000000000000023001 0ustar00sethmlarsonsethmlarson00000000000000import socket import pytest from urllib3.poolmanager import PoolKey, key_fn_by_scheme, PoolManager from urllib3 import connection_from_url from urllib3.exceptions import ClosedPoolError, LocationValueError from urllib3.util import retry, timeout class TestPoolManager(object): def test_same_url(self): # Convince ourselves that normally we don't get the same object conn1 = connection_from_url("http://localhost:8081/foo") conn2 = connection_from_url("http://localhost:8081/bar") assert conn1 != conn2 # Now try again using the PoolManager p = PoolManager(1) conn1 = p.connection_from_url("http://localhost:8081/foo") conn2 = p.connection_from_url("http://localhost:8081/bar") assert conn1 == conn2 # Ensure that FQDNs are handled separately from relative domains p = PoolManager(2) conn1 = p.connection_from_url("http://localhost.:8081/foo") conn2 = p.connection_from_url("http://localhost:8081/bar") assert conn1 != conn2 def test_many_urls(self): urls = [ "http://localhost:8081/foo", "http://www.google.com/mail", "http://localhost:8081/bar", "https://www.google.com/", "https://www.google.com/mail", "http://yahoo.com", "http://bing.com", "http://yahoo.com/", ] connections = set() p = PoolManager(10) for url in urls: conn = p.connection_from_url(url) connections.add(conn) assert len(connections) == 5 def test_manager_clear(self): p = PoolManager(5) conn_pool = p.connection_from_url("http://google.com") assert len(p.pools) == 1 conn = conn_pool._get_conn() p.clear() assert len(p.pools) == 0 with pytest.raises(ClosedPoolError): conn_pool._get_conn() conn_pool._put_conn(conn) with pytest.raises(ClosedPoolError): conn_pool._get_conn() assert len(p.pools) == 0 @pytest.mark.parametrize("url", ["http://@", None]) def test_nohost(self, url): p = PoolManager(5) with pytest.raises(LocationValueError): p.connection_from_url(url=url) def test_contextmanager(self): with PoolManager(1) as p: conn_pool = p.connection_from_url("http://google.com") assert len(p.pools) == 1 conn = conn_pool._get_conn() assert len(p.pools) == 0 with pytest.raises(ClosedPoolError): conn_pool._get_conn() conn_pool._put_conn(conn) with pytest.raises(ClosedPoolError): conn_pool._get_conn() assert len(p.pools) == 0 def test_http_pool_key_fields(self): """Assert the HTTPPoolKey fields are honored when selecting a pool.""" connection_pool_kw = { "timeout": timeout.Timeout(3.14), "retries": retry.Retry(total=6, connect=2), "block": True, "strict": True, "source_address": "127.0.0.1", } p = PoolManager() conn_pools = [ p.connection_from_url("http://example.com/"), p.connection_from_url("http://example.com:8000/"), p.connection_from_url("http://other.example.com/"), ] for key, value in connection_pool_kw.items(): p.connection_pool_kw[key] = value conn_pools.append(p.connection_from_url("http://example.com/")) assert all( x is not y for i, x in enumerate(conn_pools) for j, y in enumerate(conn_pools) if i != j ) assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_https_pool_key_fields(self): """Assert the HTTPSPoolKey fields are honored when selecting a pool.""" connection_pool_kw = { "timeout": timeout.Timeout(3.14), "retries": retry.Retry(total=6, connect=2), "block": True, "strict": True, "source_address": "127.0.0.1", "key_file": "/root/totally_legit.key", "cert_file": "/root/totally_legit.crt", "cert_reqs": "CERT_REQUIRED", "ca_certs": "/root/path_to_pem", "ssl_version": "SSLv23_METHOD", } p = PoolManager() conn_pools = [ p.connection_from_url("https://example.com/"), p.connection_from_url("https://example.com:4333/"), p.connection_from_url("https://other.example.com/"), ] # Asking for a connection pool with the same key should give us an # existing pool. dup_pools = [] for key, value in connection_pool_kw.items(): p.connection_pool_kw[key] = value conn_pools.append(p.connection_from_url("https://example.com/")) dup_pools.append(p.connection_from_url("https://example.com/")) assert all( x is not y for i, x in enumerate(conn_pools) for j, y in enumerate(conn_pools) if i != j ) assert all(pool in conn_pools for pool in dup_pools) assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_default_pool_key_funcs_copy(self): """Assert each PoolManager gets a copy of ``pool_keys_by_scheme``.""" p = PoolManager() assert p.key_fn_by_scheme == p.key_fn_by_scheme assert p.key_fn_by_scheme is not key_fn_by_scheme def test_pools_keyed_with_from_host(self): """Assert pools are still keyed correctly with connection_from_host.""" ssl_kw = { "key_file": "/root/totally_legit.key", "cert_file": "/root/totally_legit.crt", "cert_reqs": "CERT_REQUIRED", "ca_certs": "/root/path_to_pem", "ssl_version": "SSLv23_METHOD", } p = PoolManager(5, **ssl_kw) conns = [p.connection_from_host("example.com", 443, scheme="https")] for k in ssl_kw: p.connection_pool_kw[k] = "newval" conns.append(p.connection_from_host("example.com", 443, scheme="https")) assert all( x is not y for i, x in enumerate(conns) for j, y in enumerate(conns) if i != j ) def test_https_connection_from_url_case_insensitive(self): """Assert scheme case is ignored when pooling HTTPS connections.""" p = PoolManager() pool = p.connection_from_url("https://example.com/") other_pool = p.connection_from_url("HTTPS://EXAMPLE.COM/") assert 1 == len(p.pools) assert pool is other_pool assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_https_connection_from_host_case_insensitive(self): """Assert scheme case is ignored when getting the https key class.""" p = PoolManager() pool = p.connection_from_host("example.com", scheme="https") other_pool = p.connection_from_host("EXAMPLE.COM", scheme="HTTPS") assert 1 == len(p.pools) assert pool is other_pool assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_https_connection_from_context_case_insensitive(self): """Assert scheme case is ignored when getting the https key class.""" p = PoolManager() context = {"scheme": "https", "host": "example.com", "port": "443"} other_context = {"scheme": "HTTPS", "host": "EXAMPLE.COM", "port": "443"} pool = p.connection_from_context(context) other_pool = p.connection_from_context(other_context) assert 1 == len(p.pools) assert pool is other_pool assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_http_connection_from_url_case_insensitive(self): """Assert scheme case is ignored when pooling HTTP connections.""" p = PoolManager() pool = p.connection_from_url("http://example.com/") other_pool = p.connection_from_url("HTTP://EXAMPLE.COM/") assert 1 == len(p.pools) assert pool is other_pool assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_http_connection_from_host_case_insensitive(self): """Assert scheme case is ignored when getting the https key class.""" p = PoolManager() pool = p.connection_from_host("example.com", scheme="http") other_pool = p.connection_from_host("EXAMPLE.COM", scheme="HTTP") assert 1 == len(p.pools) assert pool is other_pool assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_assert_hostname_and_fingerprint_flag(self): """Assert that pool manager can accept hostname and fingerprint flags.""" fingerprint = "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A" p = PoolManager(assert_hostname=True, assert_fingerprint=fingerprint) pool = p.connection_from_url("https://example.com/") assert 1 == len(p.pools) assert pool.assert_hostname assert fingerprint == pool.assert_fingerprint def test_http_connection_from_context_case_insensitive(self): """Assert scheme case is ignored when getting the https key class.""" p = PoolManager() context = {"scheme": "http", "host": "example.com", "port": "8080"} other_context = {"scheme": "HTTP", "host": "EXAMPLE.COM", "port": "8080"} pool = p.connection_from_context(context) other_pool = p.connection_from_context(other_context) assert 1 == len(p.pools) assert pool is other_pool assert all(isinstance(key, PoolKey) for key in p.pools.keys()) def test_custom_pool_key(self): """Assert it is possible to define a custom key function.""" p = PoolManager(10) p.key_fn_by_scheme["http"] = lambda x: tuple(x["key"]) pool1 = p.connection_from_url( "http://example.com", pool_kwargs={"key": "value"} ) pool2 = p.connection_from_url( "http://example.com", pool_kwargs={"key": "other"} ) pool3 = p.connection_from_url( "http://example.com", pool_kwargs={"key": "value", "x": "y"} ) assert 2 == len(p.pools) assert pool1 is pool3 assert pool1 is not pool2 def test_override_pool_kwargs_url(self): """Assert overriding pool kwargs works with connection_from_url.""" p = PoolManager(strict=True) pool_kwargs = {"strict": False, "retries": 100, "block": True} default_pool = p.connection_from_url("http://example.com/") override_pool = p.connection_from_url( "http://example.com/", pool_kwargs=pool_kwargs ) assert default_pool.strict assert retry.Retry.DEFAULT == default_pool.retries assert not default_pool.block assert not override_pool.strict assert 100 == override_pool.retries assert override_pool.block def test_override_pool_kwargs_host(self): """Assert overriding pool kwargs works with connection_from_host""" p = PoolManager(strict=True) pool_kwargs = {"strict": False, "retries": 100, "block": True} default_pool = p.connection_from_host("example.com", scheme="http") override_pool = p.connection_from_host( "example.com", scheme="http", pool_kwargs=pool_kwargs ) assert default_pool.strict assert retry.Retry.DEFAULT == default_pool.retries assert not default_pool.block assert not override_pool.strict assert 100 == override_pool.retries assert override_pool.block def test_pool_kwargs_socket_options(self): """Assert passing socket options works with connection_from_host""" p = PoolManager(socket_options=[]) override_opts = [ (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1), (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1), ] pool_kwargs = {"socket_options": override_opts} default_pool = p.connection_from_host("example.com", scheme="http") override_pool = p.connection_from_host( "example.com", scheme="http", pool_kwargs=pool_kwargs ) assert default_pool.conn_kw["socket_options"] == [] assert override_pool.conn_kw["socket_options"] == override_opts def test_merge_pool_kwargs(self): """Assert _merge_pool_kwargs works in the happy case""" p = PoolManager(strict=True) merged = p._merge_pool_kwargs({"new_key": "value"}) assert {"strict": True, "new_key": "value"} == merged def test_merge_pool_kwargs_none(self): """Assert false-y values to _merge_pool_kwargs result in defaults""" p = PoolManager(strict=True) merged = p._merge_pool_kwargs({}) assert p.connection_pool_kw == merged merged = p._merge_pool_kwargs(None) assert p.connection_pool_kw == merged def test_merge_pool_kwargs_remove_key(self): """Assert keys can be removed with _merge_pool_kwargs""" p = PoolManager(strict=True) merged = p._merge_pool_kwargs({"strict": None}) assert "strict" not in merged def test_merge_pool_kwargs_invalid_key(self): """Assert removing invalid keys with _merge_pool_kwargs doesn't break""" p = PoolManager(strict=True) merged = p._merge_pool_kwargs({"invalid_key": None}) assert p.connection_pool_kw == merged ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_proxymanager.py0000644000175000017500000000314700000000000023215 0ustar00sethmlarsonsethmlarson00000000000000import pytest from urllib3.poolmanager import ProxyManager class TestProxyManager(object): def test_proxy_headers(self): url = "http://pypi.org/project/urllib3/" with ProxyManager("http://something:1234") as p: # Verify default headers default_headers = {"Accept": "*/*", "Host": "pypi.org"} headers = p._set_proxy_headers(url) assert headers == default_headers # Verify default headers don't overwrite provided headers provided_headers = { "Accept": "application/json", "custom": "header", "Host": "test.python.org", } headers = p._set_proxy_headers(url, provided_headers) assert headers == provided_headers # Verify proxy with nonstandard port provided_headers = {"Accept": "application/json"} expected_headers = provided_headers.copy() expected_headers.update({"Host": "pypi.org:8080"}) url_with_port = "http://pypi.org:8080/project/urllib3/" headers = p._set_proxy_headers(url_with_port, provided_headers) assert headers == expected_headers def test_default_port(self): with ProxyManager("http://something") as p: assert p.proxy.port == 80 with ProxyManager("https://something") as p: assert p.proxy.port == 443 def test_invalid_scheme(self): with pytest.raises(AssertionError): ProxyManager("invalid://host/p") with pytest.raises(ValueError): ProxyManager("invalid://host/p") ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_queue_monkeypatch.py0000644000175000017500000000143100000000000024221 0ustar00sethmlarsonsethmlarson00000000000000from __future__ import absolute_import import mock import pytest from urllib3 import HTTPConnectionPool from urllib3.exceptions import EmptyPoolError from urllib3.packages.six.moves import queue class BadError(Exception): """ This should not be raised. """ pass class TestMonkeypatchResistance(object): """ Test that connection pool works even with a monkey patched Queue module, see obspy/obspy#1599, psf/requests#3742, urllib3/urllib3#1061. """ def test_queue_monkeypatching(self): with mock.patch.object(queue, "Empty", BadError): with HTTPConnectionPool(host="localhost", block=True) as http: http._get_conn() with pytest.raises(EmptyPoolError): http._get_conn(timeout=0) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_response.py0000644000175000017500000007706500000000000022351 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- import re import socket import zlib from io import BytesIO, BufferedReader, TextIOWrapper import pytest import mock import six from urllib3.response import HTTPResponse, brotli from urllib3.exceptions import ( DecodeError, ResponseNotChunked, ProtocolError, InvalidHeader, ) from urllib3.packages.six.moves import http_client as httplib from urllib3.util.retry import Retry, RequestHistory from urllib3.util.response import is_fp_closed from test import onlyBrotlipy from base64 import b64decode # A known random (i.e, not-too-compressible) payload generated with: # "".join(random.choice(string.printable) for i in xrange(512)) # .encode("zlib").encode("base64") # Randomness in tests == bad, and fixing a seed may not be sufficient. ZLIB_PAYLOAD = b64decode( b"""\ eJwFweuaoQAAANDfineQhiKLUiaiCzvuTEmNNlJGiL5QhnGpZ99z8luQfe1AHoMioB+QSWHQu/L+ lzd7W5CipqYmeVTBjdgSATdg4l4Z2zhikbuF+EKn69Q0DTpdmNJz8S33odfJoVEexw/l2SS9nFdi pis7KOwXzfSqarSo9uJYgbDGrs1VNnQpT9f8zAorhYCEZronZQF9DuDFfNK3Hecc+WHLnZLQptwk nufw8S9I43sEwxsT71BiqedHo0QeIrFE01F/4atVFXuJs2yxIOak3bvtXjUKAA6OKnQJ/nNvDGKZ Khe5TF36JbnKVjdcL1EUNpwrWVfQpFYJ/WWm2b74qNeSZeQv5/xBhRdOmKTJFYgO96PwrHBlsnLn a3l0LwJsloWpMbzByU5WLbRE6X5INFqjQOtIwYz5BAlhkn+kVqJvWM5vBlfrwP42ifonM5yF4ciJ auHVks62997mNGOsM7WXNG3P98dBHPo2NhbTvHleL0BI5dus2JY81MUOnK3SGWLH8HeWPa1t5KcW S5moAj5HexY/g/F8TctpxwsvyZp38dXeLDjSQvEQIkF7XR3YXbeZgKk3V34KGCPOAeeuQDIgyVhV nP4HF2uWHA==""" ) @pytest.fixture def sock(): s = socket.socket() yield s s.close() class TestLegacyResponse(object): def test_getheaders(self): headers = {"host": "example.com"} r = HTTPResponse(headers=headers) assert r.getheaders() == headers def test_getheader(self): headers = {"host": "example.com"} r = HTTPResponse(headers=headers) assert r.getheader("host") == "example.com" class TestResponse(object): def test_cache_content(self): r = HTTPResponse("foo") assert r.data == "foo" assert r._body == "foo" def test_default(self): r = HTTPResponse() assert r.data is None def test_none(self): r = HTTPResponse(None) assert r.data is None def test_preload(self): fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=True) assert fp.tell() == len(b"foo") assert r.data == b"foo" def test_no_preload(self): fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert fp.tell() == 0 assert r.data == b"foo" assert fp.tell() == len(b"foo") def test_decode_bad_data(self): fp = BytesIO(b"\x00" * 10) with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "deflate"}) def test_reference_read(self): fp = BytesIO(b"foo") r = HTTPResponse(fp, preload_content=False) assert r.read(1) == b"f" assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" def test_decode_deflate(self): data = zlib.compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "deflate"}) assert r.data == b"foo" def test_decode_deflate_case_insensitve(self): data = zlib.compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "DeFlAtE"}) assert r.data == b"foo" def test_chunked_decoding_deflate(self): data = zlib.compress(b"foo") fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert r.read(3) == b"" # Buffer in case we need to switch to the raw stream assert r._decoder._data is not None assert r.read(1) == b"f" # Now that we've decoded data, we just stream through the decoder assert r._decoder._data is None assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" def test_chunked_decoding_deflate2(self): compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) assert r.read(1) == b"" assert r.read(1) == b"f" # Once we've decoded data, we just stream to the decoder; no buffering assert r._decoder._data is None assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" def test_chunked_decoding_gzip(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) assert r.read(11) == b"" assert r.read(1) == b"f" assert r.read(2) == b"oo" assert r.read() == b"" assert r.read() == b"" def test_decode_gzip_multi_member(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() data = data * 3 fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "gzip"}) assert r.data == b"foofoofoo" def test_decode_gzip_error(self): fp = BytesIO(b"foo") with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "gzip"}) def test_decode_gzip_swallow_garbage(self): # When data comes from multiple calls to read(), data after # the first zlib error (here triggered by garbage) should be # ignored. compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() data = data * 3 + b"foo" fp = BytesIO(data) r = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) ret = b"" for _ in range(100): ret += r.read(1) if r.closed: break assert ret == b"foofoofoo" def test_chunked_decoding_gzip_swallow_garbage(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() data = data * 3 + b"foo" fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "gzip"}) assert r.data == b"foofoofoo" @onlyBrotlipy() def test_decode_brotli(self): data = brotli.compress(b"foo") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "br"}) assert r.data == b"foo" @onlyBrotlipy() def test_chunked_decoding_brotli(self): data = brotli.compress(b"foobarbaz") fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "br"}, preload_content=False) ret = b"" for _ in range(100): ret += r.read(1) if r.closed: break assert ret == b"foobarbaz" @onlyBrotlipy() def test_decode_brotli_error(self): fp = BytesIO(b"foo") with pytest.raises(DecodeError): HTTPResponse(fp, headers={"content-encoding": "br"}) def test_multi_decoding_deflate_deflate(self): data = zlib.compress(zlib.compress(b"foo")) fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "deflate, deflate"}) assert r.data == b"foo" def test_multi_decoding_deflate_gzip(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(zlib.compress(b"foo")) data += compress.flush() fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "deflate, gzip"}) assert r.data == b"foo" def test_multi_decoding_gzip_gzip(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(data) data += compress.flush() fp = BytesIO(data) r = HTTPResponse(fp, headers={"content-encoding": "gzip, gzip"}) assert r.data == b"foo" def test_body_blob(self): resp = HTTPResponse(b"foo") assert resp.data == b"foo" assert resp.closed def test_io(self, sock): fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) assert not resp.closed assert resp.readable() assert not resp.writable() with pytest.raises(IOError): resp.fileno() resp.close() assert resp.closed # Try closing with an `httplib.HTTPResponse`, because it has an # `isclosed` method. try: hlr = httplib.HTTPResponse(sock) resp2 = HTTPResponse(hlr, preload_content=False) assert not resp2.closed resp2.close() assert resp2.closed finally: hlr.close() # also try when only data is present. resp3 = HTTPResponse("foodata") with pytest.raises(IOError): resp3.fileno() resp3._fp = 2 # A corner case where _fp is present but doesn't have `closed`, # `isclosed`, or `fileno`. Unlikely, but possible. assert resp3.closed with pytest.raises(IOError): resp3.fileno() def test_io_closed_consistently(self, sock): try: hlr = httplib.HTTPResponse(sock) hlr.fp = BytesIO(b"foo") hlr.chunked = 0 hlr.length = 3 with HTTPResponse(hlr, preload_content=False) as resp: assert not resp.closed assert not resp._fp.isclosed() assert not is_fp_closed(resp._fp) assert not resp.isclosed() resp.read() assert resp.closed assert resp._fp.isclosed() assert is_fp_closed(resp._fp) assert resp.isclosed() finally: hlr.close() def test_io_bufferedreader(self): fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) br = BufferedReader(resp) assert br.read() == b"foo" br.close() assert resp.closed # HTTPResponse.read() by default closes the response # https://github.com/urllib3/urllib3/issues/1305 fp = BytesIO(b"hello\nworld") resp = HTTPResponse(fp, preload_content=False) with pytest.raises(ValueError) as ctx: list(BufferedReader(resp)) assert str(ctx.value) == "readline of closed file" b = b"fooandahalf" fp = BytesIO(b) resp = HTTPResponse(fp, preload_content=False) br = BufferedReader(resp, 5) br.read(1) # sets up the buffer, reading 5 assert len(fp.read()) == (len(b) - 5) # This is necessary to make sure the "no bytes left" part of `readinto` # gets tested. while not br.closed: br.read(5) def test_io_not_autoclose_bufferedreader(self): fp = BytesIO(b"hello\nworld") resp = HTTPResponse(fp, preload_content=False, auto_close=False) reader = BufferedReader(resp) assert list(reader) == [b"hello\n", b"world"] assert not reader.closed assert not resp.closed with pytest.raises(StopIteration): next(reader) reader.close() assert reader.closed assert resp.closed with pytest.raises(ValueError) as ctx: next(reader) assert str(ctx.value) == "readline of closed file" def test_io_textiowrapper(self): fp = BytesIO(b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f") resp = HTTPResponse(fp, preload_content=False) br = TextIOWrapper(resp, encoding="utf8") assert br.read() == u"äöüß" br.close() assert resp.closed # HTTPResponse.read() by default closes the response # https://github.com/urllib3/urllib3/issues/1305 fp = BytesIO( b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\n\xce\xb1\xce\xb2\xce\xb3\xce\xb4" ) resp = HTTPResponse(fp, preload_content=False) with pytest.raises(ValueError) as ctx: if six.PY2: # py2's implementation of TextIOWrapper requires `read1` # method which is provided by `BufferedReader` wrapper resp = BufferedReader(resp) list(TextIOWrapper(resp)) assert re.match("I/O operation on closed file.?", str(ctx.value)) def test_io_not_autoclose_textiowrapper(self): fp = BytesIO( b"\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\n\xce\xb1\xce\xb2\xce\xb3\xce\xb4" ) resp = HTTPResponse(fp, preload_content=False, auto_close=False) if six.PY2: # py2's implementation of TextIOWrapper requires `read1` # method which is provided by `BufferedReader` wrapper resp = BufferedReader(resp) reader = TextIOWrapper(resp, encoding="utf8") assert list(reader) == [u"äöüß\n", u"αβγδ"] assert not reader.closed assert not resp.closed with pytest.raises(StopIteration): next(reader) reader.close() assert reader.closed assert resp.closed with pytest.raises(ValueError) as ctx: next(reader) assert re.match("I/O operation on closed file.?", str(ctx.value)) def test_streaming(self): fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2, decode_content=False) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_streaming_tell(self): fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2, decode_content=False) position = 0 position += len(next(stream)) assert 2 == position assert position == resp.tell() position += len(next(stream)) assert 3 == position assert position == resp.tell() with pytest.raises(StopIteration): next(stream) def test_gzipped_streaming(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) stream = resp.stream(2) assert next(stream) == b"f" assert next(stream) == b"oo" with pytest.raises(StopIteration): next(stream) def test_gzipped_streaming_tell(self): compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) uncompressed_data = b"foo" data = compress.compress(uncompressed_data) data += compress.flush() fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "gzip"}, preload_content=False ) stream = resp.stream() # Read everything payload = next(stream) assert payload == uncompressed_data assert len(data) == resp.tell() with pytest.raises(StopIteration): next(stream) def test_deflate_streaming_tell_intermediate_point(self): # Ensure that ``tell()`` returns the correct number of bytes when # part-way through streaming compressed content. NUMBER_OF_READS = 10 class MockCompressedDataReading(BytesIO): """ A BytesIO-like reader returning ``payload`` in ``NUMBER_OF_READS`` calls to ``read``. """ def __init__(self, payload, payload_part_size): self.payloads = [ payload[i * payload_part_size : (i + 1) * payload_part_size] for i in range(NUMBER_OF_READS + 1) ] assert b"".join(self.payloads) == payload def read(self, _): # Amount is unused. if len(self.payloads) > 0: return self.payloads.pop(0) return b"" uncompressed_data = zlib.decompress(ZLIB_PAYLOAD) payload_part_size = len(ZLIB_PAYLOAD) // NUMBER_OF_READS fp = MockCompressedDataReading(ZLIB_PAYLOAD, payload_part_size) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) stream = resp.stream() parts_positions = [(part, resp.tell()) for part in stream] end_of_stream = resp.tell() with pytest.raises(StopIteration): next(stream) parts, positions = zip(*parts_positions) # Check that the payload is equal to the uncompressed data payload = b"".join(parts) assert uncompressed_data == payload # Check that the positions in the stream are correct expected = [(i + 1) * payload_part_size for i in range(NUMBER_OF_READS)] assert expected == list(positions) # Check that the end of the stream is in the correct place assert len(ZLIB_PAYLOAD) == end_of_stream def test_deflate_streaming(self): data = zlib.compress(b"foo") fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) stream = resp.stream(2) assert next(stream) == b"f" assert next(stream) == b"oo" with pytest.raises(StopIteration): next(stream) def test_deflate2_streaming(self): compress = zlib.compressobj(6, zlib.DEFLATED, -zlib.MAX_WBITS) data = compress.compress(b"foo") data += compress.flush() fp = BytesIO(data) resp = HTTPResponse( fp, headers={"content-encoding": "deflate"}, preload_content=False ) stream = resp.stream(2) assert next(stream) == b"f" assert next(stream) == b"oo" with pytest.raises(StopIteration): next(stream) def test_empty_stream(self): fp = BytesIO(b"") resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2, decode_content=False) with pytest.raises(StopIteration): next(stream) def test_length_no_header(self): fp = BytesIO(b"12345") resp = HTTPResponse(fp, preload_content=False) assert resp.length_remaining is None def test_length_w_valid_header(self): headers = {"content-length": "5"} fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) assert resp.length_remaining == 5 def test_length_w_bad_header(self): garbage = {"content-length": "foo"} fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=garbage, preload_content=False) assert resp.length_remaining is None garbage["content-length"] = "-10" resp = HTTPResponse(fp, headers=garbage, preload_content=False) assert resp.length_remaining is None def test_length_when_chunked(self): # This is expressly forbidden in RFC 7230 sec 3.3.2 # We fall back to chunked in this case and try to # handle response ignoring content length. headers = {"content-length": "5", "transfer-encoding": "chunked"} fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) assert resp.length_remaining is None def test_length_with_multiple_content_lengths(self): headers = {"content-length": "5, 5, 5"} garbage = {"content-length": "5, 42"} fp = BytesIO(b"abcde") resp = HTTPResponse(fp, headers=headers, preload_content=False) assert resp.length_remaining == 5 with pytest.raises(InvalidHeader): HTTPResponse(fp, headers=garbage, preload_content=False) def test_length_after_read(self): headers = {"content-length": "5"} # Test no defined length fp = BytesIO(b"12345") resp = HTTPResponse(fp, preload_content=False) resp.read() assert resp.length_remaining is None # Test our update from content-length fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) resp.read() assert resp.length_remaining == 0 # Test partial read fp = BytesIO(b"12345") resp = HTTPResponse(fp, headers=headers, preload_content=False) data = resp.stream(2) next(data) assert resp.length_remaining == 3 def test_mock_httpresponse_stream(self): # Mock out a HTTP Request that does enough to make it through urllib3's # read() and close() calls, and also exhausts and underlying file # object. class MockHTTPRequest(object): self.fp = None def read(self, amt): data = self.fp.read(amt) if not data: self.fp = None return data def close(self): self.fp = None bio = BytesIO(b"foo") fp = MockHTTPRequest() fp.fp = bio resp = HTTPResponse(fp, preload_content=False) stream = resp.stream(2) assert next(stream) == b"fo" assert next(stream) == b"o" with pytest.raises(StopIteration): next(stream) def test_mock_transfer_encoding_chunked(self): stream = [b"fo", b"o", b"bar"] fp = MockChunkedEncodingResponse(stream) r = httplib.HTTPResponse(MockSock) r.fp = fp resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) for i, c in enumerate(resp.stream()): assert c == stream[i] def test_mock_gzipped_transfer_encoding_chunked_decoded(self): """Show that we can decode the gizpped and chunked body.""" def stream(): # Set up a generator to chunk the gzipped body compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foobar") data += compress.flush() for i in range(0, len(data), 2): yield data[i : i + 2] fp = MockChunkedEncodingResponse(list(stream())) r = httplib.HTTPResponse(MockSock) r.fp = fp headers = {"transfer-encoding": "chunked", "content-encoding": "gzip"} resp = HTTPResponse(r, preload_content=False, headers=headers) data = b"" for c in resp.stream(decode_content=True): data += c assert b"foobar" == data def test_mock_transfer_encoding_chunked_custom_read(self): stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedEncodingResponse(stream) r = httplib.HTTPResponse(MockSock) r.fp = fp r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) expected_response = [b"fo", b"oo", b"o", b"bb", b"bb", b"aa", b"aa", b"ar"] response = list(resp.read_chunked(2)) assert expected_response == response def test_mock_transfer_encoding_chunked_unlmtd_read(self): stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedEncodingResponse(stream) r = httplib.HTTPResponse(MockSock) r.fp = fp r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) assert stream == list(resp.read_chunked()) def test_read_not_chunked_response_as_chunks(self): fp = BytesIO(b"foo") resp = HTTPResponse(fp, preload_content=False) r = resp.read_chunked() with pytest.raises(ResponseNotChunked): next(r) def test_invalid_chunks(self): stream = [b"foooo", b"bbbbaaaaar"] fp = MockChunkedInvalidEncoding(stream) r = httplib.HTTPResponse(MockSock) r.fp = fp r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) with pytest.raises(ProtocolError): next(resp.read_chunked()) def test_chunked_response_without_crlf_on_end(self): stream = [b"foo", b"bar", b"baz"] fp = MockChunkedEncodingWithoutCRLFOnEnd(stream) r = httplib.HTTPResponse(MockSock) r.fp = fp r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) assert stream == list(resp.stream()) def test_chunked_response_with_extensions(self): stream = [b"foo", b"bar"] fp = MockChunkedEncodingWithExtensions(stream) r = httplib.HTTPResponse(MockSock) r.fp = fp r.chunked = True r.chunk_left = None resp = HTTPResponse( r, preload_content=False, headers={"transfer-encoding": "chunked"} ) assert stream == list(resp.stream()) def test_chunked_head_response(self): r = httplib.HTTPResponse(MockSock, method="HEAD") r.chunked = True r.chunk_left = None resp = HTTPResponse( "", preload_content=False, headers={"transfer-encoding": "chunked"}, original_response=r, ) assert resp.chunked is True resp.supports_chunked_reads = lambda: True resp.release_conn = mock.Mock() for _ in resp.stream(): continue resp.release_conn.assert_called_once_with() def test_get_case_insensitive_headers(self): headers = {"host": "example.com"} r = HTTPResponse(headers=headers) assert r.headers.get("host") == "example.com" assert r.headers.get("Host") == "example.com" def test_retries(self): fp = BytesIO(b"") resp = HTTPResponse(fp) assert resp.retries is None retry = Retry() resp = HTTPResponse(fp, retries=retry) assert resp.retries == retry def test_geturl(self): fp = BytesIO(b"") request_url = "https://example.com" resp = HTTPResponse(fp, request_url=request_url) assert resp.geturl() == request_url def test_geturl_retries(self): fp = BytesIO(b"") resp = HTTPResponse(fp, request_url="http://example.com") request_histories = [ RequestHistory( method="GET", url="http://example.com", error=None, status=301, redirect_location="https://example.com/", ), RequestHistory( method="GET", url="https://example.com/", error=None, status=301, redirect_location="https://www.example.com", ), ] retry = Retry(history=request_histories) resp = HTTPResponse(fp, retries=retry) assert resp.geturl() == "https://www.example.com" @pytest.mark.parametrize( ["payload", "expected_stream"], [ (b"", []), (b"\n", [b"\n"]), (b"\n\n\n", [b"\n", b"\n", b"\n"]), (b"abc\ndef", [b"abc\n", b"def"]), (b"Hello\nworld\n\n\n!", [b"Hello\n", b"world\n", b"\n", b"\n", b"!"]), ], ) def test__iter__(self, payload, expected_stream): actual_stream = [] for chunk in HTTPResponse(BytesIO(payload), preload_content=False): actual_stream.append(chunk) assert actual_stream == expected_stream def test__iter__decode_content(self): def stream(): # Set up a generator to chunk the gzipped body compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) data = compress.compress(b"foo\nbar") data += compress.flush() for i in range(0, len(data), 2): yield data[i : i + 2] fp = MockChunkedEncodingResponse(list(stream())) r = httplib.HTTPResponse(MockSock) r.fp = fp headers = {"transfer-encoding": "chunked", "content-encoding": "gzip"} resp = HTTPResponse(r, preload_content=False, headers=headers) data = b"" for c in resp: data += c assert b"foo\nbar" == data class MockChunkedEncodingResponse(object): def __init__(self, content): """ content: collection of str, each str is a chunk in response """ self.content = content self.index = 0 # This class iterates over self.content. self.closed = False self.cur_chunk = b"" self.chunks_exhausted = False @staticmethod def _encode_chunk(chunk): # In the general case, we can't decode the chunk to unicode length = "%X\r\n" % len(chunk) return length.encode() + chunk + b"\r\n" def _pop_new_chunk(self): if self.chunks_exhausted: return b"" try: chunk = self.content[self.index] except IndexError: chunk = b"" self.chunks_exhausted = True else: self.index += 1 chunk = self._encode_chunk(chunk) if not isinstance(chunk, bytes): chunk = chunk.encode() return chunk def pop_current_chunk(self, amt=-1, till_crlf=False): if amt > 0 and till_crlf: raise ValueError("Can't specify amt and till_crlf.") if len(self.cur_chunk) <= 0: self.cur_chunk = self._pop_new_chunk() if till_crlf: try: i = self.cur_chunk.index(b"\r\n") except ValueError: # No CRLF in current chunk -- probably caused by encoder. self.cur_chunk = b"" return b"" else: chunk_part = self.cur_chunk[: i + 2] self.cur_chunk = self.cur_chunk[i + 2 :] return chunk_part elif amt <= -1: chunk_part = self.cur_chunk self.cur_chunk = b"" return chunk_part else: try: chunk_part = self.cur_chunk[:amt] except IndexError: chunk_part = self.cur_chunk self.cur_chunk = b"" else: self.cur_chunk = self.cur_chunk[amt:] return chunk_part def readline(self): return self.pop_current_chunk(till_crlf=True) def read(self, amt=-1): return self.pop_current_chunk(amt) def flush(self): # Python 3 wants this method. pass def close(self): self.closed = True class MockChunkedInvalidEncoding(MockChunkedEncodingResponse): def _encode_chunk(self, chunk): return "ZZZ\r\n%s\r\n" % chunk.decode() class MockChunkedEncodingWithoutCRLFOnEnd(MockChunkedEncodingResponse): def _encode_chunk(self, chunk): return "%X\r\n%s%s" % ( len(chunk), chunk.decode(), "\r\n" if len(chunk) > 0 else "", ) class MockChunkedEncodingWithExtensions(MockChunkedEncodingResponse): def _encode_chunk(self, chunk): return "%X;asd=qwe\r\n%s\r\n" % (len(chunk), chunk.decode()) class MockSock(object): @classmethod def makefile(cls, *args, **kwargs): return ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_retry.py0000644000175000017500000003254300000000000021650 0ustar00sethmlarsonsethmlarson00000000000000import datetime import mock import pytest import time from urllib3.response import HTTPResponse from urllib3.packages import six from urllib3.packages.six.moves import xrange from urllib3.util.retry import Retry, RequestHistory from urllib3.exceptions import ( ConnectTimeoutError, InvalidHeader, MaxRetryError, ReadTimeoutError, ResponseError, ) class TestRetry(object): def test_string(self): """ Retry string representation looks the way we expect """ retry = Retry() assert ( str(retry) == "Retry(total=10, connect=None, read=None, redirect=None, status=None)" ) for _ in range(3): retry = retry.increment(method="GET") assert ( str(retry) == "Retry(total=7, connect=None, read=None, redirect=None, status=None)" ) def test_retry_both_specified(self): """Total can win if it's lower than the connect value""" error = ConnectTimeoutError() retry = Retry(connect=3, total=2) retry = retry.increment(error=error) retry = retry.increment(error=error) with pytest.raises(MaxRetryError) as e: retry.increment(error=error) assert e.value.reason == error def test_retry_higher_total_loses(self): """ A lower connect timeout than the total is honored """ error = ConnectTimeoutError() retry = Retry(connect=2, total=3) retry = retry.increment(error=error) retry = retry.increment(error=error) with pytest.raises(MaxRetryError): retry.increment(error=error) def test_retry_higher_total_loses_vs_read(self): """ A lower read timeout than the total is honored """ error = ReadTimeoutError(None, "/", "read timed out") retry = Retry(read=2, total=3) retry = retry.increment(method="GET", error=error) retry = retry.increment(method="GET", error=error) with pytest.raises(MaxRetryError): retry.increment(method="GET", error=error) def test_retry_total_none(self): """ if Total is none, connect error should take precedence """ error = ConnectTimeoutError() retry = Retry(connect=2, total=None) retry = retry.increment(error=error) retry = retry.increment(error=error) with pytest.raises(MaxRetryError) as e: retry.increment(error=error) assert e.value.reason == error error = ReadTimeoutError(None, "/", "read timed out") retry = Retry(connect=2, total=None) retry = retry.increment(method="GET", error=error) retry = retry.increment(method="GET", error=error) retry = retry.increment(method="GET", error=error) assert not retry.is_exhausted() def test_retry_default(self): """ If no value is specified, should retry connects 3 times """ retry = Retry() assert retry.total == 10 assert retry.connect is None assert retry.read is None assert retry.redirect is None error = ConnectTimeoutError() retry = Retry(connect=1) retry = retry.increment(error=error) with pytest.raises(MaxRetryError): retry.increment(error=error) retry = Retry(connect=1) retry = retry.increment(error=error) assert not retry.is_exhausted() assert Retry(0).raise_on_redirect assert not Retry(False).raise_on_redirect def test_retry_read_zero(self): """ No second chances on read timeouts, by default """ error = ReadTimeoutError(None, "/", "read timed out") retry = Retry(read=0) with pytest.raises(MaxRetryError) as e: retry.increment(method="GET", error=error) assert e.value.reason == error def test_status_counter(self): resp = HTTPResponse(status=400) retry = Retry(status=2) retry = retry.increment(response=resp) retry = retry.increment(response=resp) with pytest.raises(MaxRetryError) as e: retry.increment(response=resp) assert str(e.value.reason) == ResponseError.SPECIFIC_ERROR.format( status_code=400 ) def test_backoff(self): """ Backoff is computed correctly """ max_backoff = Retry.BACKOFF_MAX retry = Retry(total=100, backoff_factor=0.2) assert retry.get_backoff_time() == 0 # First request retry = retry.increment(method="GET") assert retry.get_backoff_time() == 0 # First retry retry = retry.increment(method="GET") assert retry.backoff_factor == 0.2 assert retry.total == 98 assert retry.get_backoff_time() == 0.4 # Start backoff retry = retry.increment(method="GET") assert retry.get_backoff_time() == 0.8 retry = retry.increment(method="GET") assert retry.get_backoff_time() == 1.6 for _ in xrange(10): retry = retry.increment(method="GET") assert retry.get_backoff_time() == max_backoff def test_zero_backoff(self): retry = Retry() assert retry.get_backoff_time() == 0 retry = retry.increment(method="GET") retry = retry.increment(method="GET") assert retry.get_backoff_time() == 0 def test_backoff_reset_after_redirect(self): retry = Retry(total=100, redirect=5, backoff_factor=0.2) retry = retry.increment(method="GET") retry = retry.increment(method="GET") assert retry.get_backoff_time() == 0.4 redirect_response = HTTPResponse(status=302, headers={"location": "test"}) retry = retry.increment(method="GET", response=redirect_response) assert retry.get_backoff_time() == 0 retry = retry.increment(method="GET") retry = retry.increment(method="GET") assert retry.get_backoff_time() == 0.4 def test_sleep(self): # sleep a very small amount of time so our code coverage is happy retry = Retry(backoff_factor=0.0001) retry = retry.increment(method="GET") retry = retry.increment(method="GET") retry.sleep() def test_status_forcelist(self): retry = Retry(status_forcelist=xrange(500, 600)) assert not retry.is_retry("GET", status_code=200) assert not retry.is_retry("GET", status_code=400) assert retry.is_retry("GET", status_code=500) retry = Retry(total=1, status_forcelist=[418]) assert not retry.is_retry("GET", status_code=400) assert retry.is_retry("GET", status_code=418) # String status codes are not matched. retry = Retry(total=1, status_forcelist=["418"]) assert not retry.is_retry("GET", status_code=418) def test_method_whitelist_with_status_forcelist(self): # Falsey method_whitelist means to retry on any method. retry = Retry(status_forcelist=[500], method_whitelist=None) assert retry.is_retry("GET", status_code=500) assert retry.is_retry("POST", status_code=500) # Criteria of method_whitelist and status_forcelist are ANDed. retry = Retry(status_forcelist=[500], method_whitelist=["POST"]) assert not retry.is_retry("GET", status_code=500) assert retry.is_retry("POST", status_code=500) def test_exhausted(self): assert not Retry(0).is_exhausted() assert Retry(-1).is_exhausted() assert Retry(1).increment(method="GET").total == 0 @pytest.mark.parametrize("total", [-1, 0]) def test_disabled(self, total): with pytest.raises(MaxRetryError): Retry(total).increment(method="GET") def test_error_message(self): retry = Retry(total=0) with pytest.raises(MaxRetryError) as e: retry = retry.increment( method="GET", error=ReadTimeoutError(None, "/", "read timed out") ) assert "Caused by redirect" not in str(e.value) assert str(e.value.reason) == "None: read timed out" retry = Retry(total=1) with pytest.raises(MaxRetryError) as e: retry = retry.increment("POST", "/") retry = retry.increment("POST", "/") assert "Caused by redirect" not in str(e.value) assert isinstance(e.value.reason, ResponseError) assert str(e.value.reason) == ResponseError.GENERIC_ERROR retry = Retry(total=1) response = HTTPResponse(status=500) with pytest.raises(MaxRetryError) as e: retry = retry.increment("POST", "/", response=response) retry = retry.increment("POST", "/", response=response) assert "Caused by redirect" not in str(e.value) msg = ResponseError.SPECIFIC_ERROR.format(status_code=500) assert str(e.value.reason) == msg retry = Retry(connect=1) with pytest.raises(MaxRetryError) as e: retry = retry.increment(error=ConnectTimeoutError("conntimeout")) retry = retry.increment(error=ConnectTimeoutError("conntimeout")) assert "Caused by redirect" not in str(e.value) assert str(e.value.reason) == "conntimeout" def test_history(self): retry = Retry(total=10, method_whitelist=frozenset(["GET", "POST"])) assert retry.history == tuple() connection_error = ConnectTimeoutError("conntimeout") retry = retry.increment("GET", "/test1", None, connection_error) history = (RequestHistory("GET", "/test1", connection_error, None, None),) assert retry.history == history read_error = ReadTimeoutError(None, "/test2", "read timed out") retry = retry.increment("POST", "/test2", None, read_error) history = ( RequestHistory("GET", "/test1", connection_error, None, None), RequestHistory("POST", "/test2", read_error, None, None), ) assert retry.history == history response = HTTPResponse(status=500) retry = retry.increment("GET", "/test3", response, None) history = ( RequestHistory("GET", "/test1", connection_error, None, None), RequestHistory("POST", "/test2", read_error, None, None), RequestHistory("GET", "/test3", None, 500, None), ) assert retry.history == history def test_retry_method_not_in_whitelist(self): error = ReadTimeoutError(None, "/", "read timed out") retry = Retry() with pytest.raises(ReadTimeoutError): retry.increment(method="POST", error=error) def test_retry_default_remove_headers_on_redirect(self): retry = Retry() assert list(retry.remove_headers_on_redirect) == ["authorization"] def test_retry_set_remove_headers_on_redirect(self): retry = Retry(remove_headers_on_redirect=["X-API-Secret"]) assert list(retry.remove_headers_on_redirect) == ["x-api-secret"] @pytest.mark.parametrize("value", ["-1", "+1", "1.0", six.u("\xb2")]) # \xb2 = ^2 def test_parse_retry_after_invalid(self, value): retry = Retry() with pytest.raises(InvalidHeader): retry.parse_retry_after(value) @pytest.mark.parametrize( "value, expected", [("0", 0), ("1000", 1000), ("\t42 ", 42)] ) def test_parse_retry_after(self, value, expected): retry = Retry() assert retry.parse_retry_after(value) == expected @pytest.mark.parametrize("respect_retry_after_header", [True, False]) def test_respect_retry_after_header_propagated(self, respect_retry_after_header): retry = Retry(respect_retry_after_header=respect_retry_after_header) new_retry = retry.new() assert new_retry.respect_retry_after_header == respect_retry_after_header @pytest.mark.parametrize( "retry_after_header,respect_retry_after_header,sleep_duration", [ ("3600", True, 3600), ("3600", False, None), # Will sleep due to header is 1 hour in future ("Mon, 3 Jun 2019 12:00:00 UTC", True, 3600), # Won't sleep due to not respecting header ("Mon, 3 Jun 2019 12:00:00 UTC", False, None), # Won't sleep due to current time reached ("Mon, 3 Jun 2019 11:00:00 UTC", True, None), # Won't sleep due to current time reached + not respecting header ("Mon, 3 Jun 2019 11:00:00 UTC", False, None), ], ) def test_respect_retry_after_header_sleep( self, retry_after_header, respect_retry_after_header, sleep_duration ): retry = Retry(respect_retry_after_header=respect_retry_after_header) # Date header syntax can specify an absolute date; compare this to the # time in the parametrized inputs above. current_time = mock.MagicMock( return_value=time.mktime( datetime.datetime(year=2019, month=6, day=3, hour=11).timetuple() ) ) with mock.patch("time.sleep") as sleep_mock, mock.patch( "time.time", current_time ): # for the default behavior, it must be in RETRY_AFTER_STATUS_CODES response = HTTPResponse( status=503, headers={"Retry-After": retry_after_header} ) retry.sleep(response) # The expected behavior is that we'll only sleep if respecting # this header (since we won't have any backoff sleep attempts) if respect_retry_after_header and sleep_duration is not None: sleep_mock.assert_called_with(sleep_duration) else: sleep_mock.assert_not_called() ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_ssl.py0000644000175000017500000001127700000000000021305 0ustar00sethmlarsonsethmlarson00000000000000import mock import pytest from urllib3.util import ssl_ from urllib3.exceptions import SNIMissingWarning from test import notPyPy2 @pytest.mark.parametrize( "addr", [ # IPv6 "::1", "::", "FE80::8939:7684:D84b:a5A4%251", # IPv4 "127.0.0.1", "8.8.8.8", b"127.0.0.1", # IPv6 w/ Zone IDs "FE80::8939:7684:D84b:a5A4%251", b"FE80::8939:7684:D84b:a5A4%251", "FE80::8939:7684:D84b:a5A4%19", b"FE80::8939:7684:D84b:a5A4%19", ], ) def test_is_ipaddress_true(addr): assert ssl_.is_ipaddress(addr) @pytest.mark.parametrize( "addr", [ "www.python.org", b"www.python.org", "v2.sg.media-imdb.com", b"v2.sg.media-imdb.com", ], ) def test_is_ipaddress_false(addr): assert not ssl_.is_ipaddress(addr) @pytest.mark.parametrize( ["has_sni", "server_hostname", "uses_sni"], [ (True, "127.0.0.1", False), (False, "www.python.org", False), (False, "0.0.0.0", False), (True, "www.google.com", True), (True, None, False), (False, None, False), ], ) def test_context_sni_with_ip_address(monkeypatch, has_sni, server_hostname, uses_sni): monkeypatch.setattr(ssl_, "HAS_SNI", has_sni) sock = mock.Mock() context = mock.create_autospec(ssl_.SSLContext) ssl_.ssl_wrap_socket(sock, server_hostname=server_hostname, ssl_context=context) if uses_sni: context.wrap_socket.assert_called_with(sock, server_hostname=server_hostname) else: context.wrap_socket.assert_called_with(sock) @pytest.mark.parametrize( ["has_sni", "server_hostname", "should_warn"], [ (True, "www.google.com", False), (True, "127.0.0.1", False), (False, "127.0.0.1", False), (False, "www.google.com", True), (True, None, False), (False, None, False), ], ) def test_sni_missing_warning_with_ip_addresses( monkeypatch, has_sni, server_hostname, should_warn ): monkeypatch.setattr(ssl_, "HAS_SNI", has_sni) sock = mock.Mock() context = mock.create_autospec(ssl_.SSLContext) with mock.patch("warnings.warn") as warn: ssl_.ssl_wrap_socket(sock, server_hostname=server_hostname, ssl_context=context) if should_warn: assert warn.call_count >= 1 warnings = [call[0][1] for call in warn.call_args_list] assert SNIMissingWarning in warnings else: assert warn.call_count == 0 @pytest.mark.parametrize( ["ciphers", "expected_ciphers"], [ (None, ssl_.DEFAULT_CIPHERS), ("ECDH+AESGCM:ECDH+CHACHA20", "ECDH+AESGCM:ECDH+CHACHA20"), ], ) def test_create_urllib3_context_set_ciphers(monkeypatch, ciphers, expected_ciphers): context = mock.create_autospec(ssl_.SSLContext) context.set_ciphers = mock.Mock() context.options = 0 monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context) assert ssl_.create_urllib3_context(ciphers=ciphers) is context assert context.set_ciphers.call_count == 1 assert context.set_ciphers.call_args == mock.call(expected_ciphers) def test_wrap_socket_given_context_no_load_default_certs(): context = mock.create_autospec(ssl_.SSLContext) context.load_default_certs = mock.Mock() sock = mock.Mock() ssl_.ssl_wrap_socket(sock, ssl_context=context) context.load_default_certs.assert_not_called() @notPyPy2 def test_wrap_socket_given_ca_certs_no_load_default_certs(monkeypatch): context = mock.create_autospec(ssl_.SSLContext) context.load_default_certs = mock.Mock() context.options = 0 monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context) sock = mock.Mock() ssl_.ssl_wrap_socket(sock, ca_certs="/tmp/fake-file") context.load_default_certs.assert_not_called() context.load_verify_locations.assert_called_with("/tmp/fake-file", None) def test_wrap_socket_default_loads_default_certs(monkeypatch): context = mock.create_autospec(ssl_.SSLContext) context.load_default_certs = mock.Mock() context.options = 0 monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context) sock = mock.Mock() ssl_.ssl_wrap_socket(sock) context.load_default_certs.assert_called_with() @pytest.mark.parametrize( ["pha", "expected_pha"], [(None, None), (False, True), (True, True)] ) def test_create_urllib3_context_pha(monkeypatch, pha, expected_pha): context = mock.create_autospec(ssl_.SSLContext) context.set_ciphers = mock.Mock() context.options = 0 context.post_handshake_auth = pha monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context) assert ssl_.create_urllib3_context() is context assert context.post_handshake_auth == expected_pha ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_util.py0000644000175000017500000007272400000000000021465 0ustar00sethmlarsonsethmlarson00000000000000# coding: utf-8 import hashlib import warnings import logging import io import ssl import socket from itertools import chain from mock import patch, Mock import pytest from urllib3 import add_stderr_logger, disable_warnings from urllib3.util.request import make_headers, rewind_body, _FAILEDTELL from urllib3.util.response import assert_header_parsing from urllib3.util.timeout import Timeout from urllib3.util.url import get_host, parse_url, split_first, Url from urllib3.util.ssl_ import ( resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, _const_compare_digest_backport, ) from urllib3.exceptions import ( LocationParseError, TimeoutStateError, InsecureRequestWarning, SNIMissingWarning, UnrewindableBodyError, ) from urllib3.util.connection import allowed_gai_family, _has_ipv6 from urllib3.util import is_fp_closed, ssl_ from urllib3.packages import six from . import clear_warnings from test import onlyPy3, onlyPy2, onlyBrotlipy, notBrotlipy # This number represents a time in seconds, it doesn't mean anything in # isolation. Setting to a high-ish value to avoid conflicts with the smaller # numbers used for timeouts TIMEOUT_EPOCH = 1000 class TestUtil(object): url_host_map = [ # Hosts ("http://google.com/mail", ("http", "google.com", None)), ("http://google.com/mail/", ("http", "google.com", None)), ("google.com/mail", ("http", "google.com", None)), ("http://google.com/", ("http", "google.com", None)), ("http://google.com", ("http", "google.com", None)), ("http://www.google.com", ("http", "www.google.com", None)), ("http://mail.google.com", ("http", "mail.google.com", None)), ("http://google.com:8000/mail/", ("http", "google.com", 8000)), ("http://google.com:8000", ("http", "google.com", 8000)), ("https://google.com", ("https", "google.com", None)), ("https://google.com:8000", ("https", "google.com", 8000)), ("http://user:password@127.0.0.1:1234", ("http", "127.0.0.1", 1234)), ("http://google.com/foo=http://bar:42/baz", ("http", "google.com", None)), ("http://google.com?foo=http://bar:42/baz", ("http", "google.com", None)), ("http://google.com#foo=http://bar:42/baz", ("http", "google.com", None)), # IPv4 ("173.194.35.7", ("http", "173.194.35.7", None)), ("http://173.194.35.7", ("http", "173.194.35.7", None)), ("http://173.194.35.7/test", ("http", "173.194.35.7", None)), ("http://173.194.35.7:80", ("http", "173.194.35.7", 80)), ("http://173.194.35.7:80/test", ("http", "173.194.35.7", 80)), # IPv6 ("[2a00:1450:4001:c01::67]", ("http", "[2a00:1450:4001:c01::67]", None)), ("http://[2a00:1450:4001:c01::67]", ("http", "[2a00:1450:4001:c01::67]", None)), ( "http://[2a00:1450:4001:c01::67]/test", ("http", "[2a00:1450:4001:c01::67]", None), ), ( "http://[2a00:1450:4001:c01::67]:80", ("http", "[2a00:1450:4001:c01::67]", 80), ), ( "http://[2a00:1450:4001:c01::67]:80/test", ("http", "[2a00:1450:4001:c01::67]", 80), ), # More IPv6 from http://www.ietf.org/rfc/rfc2732.txt ( "http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:8000/index.html", ("http", "[fedc:ba98:7654:3210:fedc:ba98:7654:3210]", 8000), ), ( "http://[1080:0:0:0:8:800:200c:417a]/index.html", ("http", "[1080:0:0:0:8:800:200c:417a]", None), ), ("http://[3ffe:2a00:100:7031::1]", ("http", "[3ffe:2a00:100:7031::1]", None)), ( "http://[1080::8:800:200c:417a]/foo", ("http", "[1080::8:800:200c:417a]", None), ), ("http://[::192.9.5.5]/ipng", ("http", "[::192.9.5.5]", None)), ( "http://[::ffff:129.144.52.38]:42/index.html", ("http", "[::ffff:129.144.52.38]", 42), ), ( "http://[2010:836b:4179::836b:4179]", ("http", "[2010:836b:4179::836b:4179]", None), ), # Hosts ("HTTP://GOOGLE.COM/mail/", ("http", "google.com", None)), ("GOogle.COM/mail", ("http", "google.com", None)), ("HTTP://GoOgLe.CoM:8000/mail/", ("http", "google.com", 8000)), ("HTTP://user:password@EXAMPLE.COM:1234", ("http", "example.com", 1234)), ("173.194.35.7", ("http", "173.194.35.7", None)), ("HTTP://173.194.35.7", ("http", "173.194.35.7", None)), ( "HTTP://[2a00:1450:4001:c01::67]:80/test", ("http", "[2a00:1450:4001:c01::67]", 80), ), ( "HTTP://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8000/index.html", ("http", "[fedc:ba98:7654:3210:fedc:ba98:7654:3210]", 8000), ), ( "HTTPS://[1080:0:0:0:8:800:200c:417A]/index.html", ("https", "[1080:0:0:0:8:800:200c:417a]", None), ), ("abOut://eXamPlE.com?info=1", ("about", "eXamPlE.com", None)), ( "http+UNIX://%2fvar%2frun%2fSOCKET/path", ("http+unix", "%2fvar%2frun%2fSOCKET", None), ), ] @pytest.mark.parametrize("url, expected_host", url_host_map) def test_get_host(self, url, expected_host): returned_host = get_host(url) assert returned_host == expected_host # TODO: Add more tests @pytest.mark.parametrize( "location", [ "http://google.com:foo", "http://::1/", "http://::1:80/", "http://google.com:-80", six.u("http://google.com:\xb2\xb2"), # \xb2 = ^2 ], ) def test_invalid_host(self, location): with pytest.raises(LocationParseError): get_host(location) @pytest.mark.parametrize( "url", [ # Invalid IDNA labels u"http://\uD7FF.com", u"http://❤️", # Unicode surrogates u"http://\uD800.com", u"http://\uDC00.com", ], ) def test_invalid_url(self, url): with pytest.raises(LocationParseError): parse_url(url) @pytest.mark.parametrize( "url, expected_normalized_url", [ ("HTTP://GOOGLE.COM/MAIL/", "http://google.com/MAIL/"), ( "http://user@domain.com:password@example.com/~tilde@?@", "http://user%40domain.com:password@example.com/~tilde@?@", ), ( "HTTP://JeremyCline:Hunter2@Example.com:8080/", "http://JeremyCline:Hunter2@example.com:8080/", ), ("HTTPS://Example.Com/?Key=Value", "https://example.com/?Key=Value"), ("Https://Example.Com/#Fragment", "https://example.com/#Fragment"), ("[::1%25]", "[::1%25]"), ("[::Ff%etH0%Ff]/%ab%Af", "[::ff%etH0%FF]/%AB%AF"), ( "http://user:pass@[AaAa::Ff%25etH0%Ff]/%ab%Af", "http://user:pass@[aaaa::ff%etH0%FF]/%AB%AF", ), # Invalid characters for the query/fragment getting encoded ( 'http://google.com/p[]?parameter[]="hello"#fragment#', "http://google.com/p%5B%5D?parameter%5B%5D=%22hello%22#fragment%23", ), # Percent encoding isn't applied twice despite '%' being invalid # but the percent encoding is still normalized. ( "http://google.com/p%5B%5d?parameter%5b%5D=%22hello%22#fragment%23", "http://google.com/p%5B%5D?parameter%5B%5D=%22hello%22#fragment%23", ), ], ) def test_parse_url_normalization(self, url, expected_normalized_url): """Assert parse_url normalizes the scheme/host, and only the scheme/host""" actual_normalized_url = parse_url(url).url assert actual_normalized_url == expected_normalized_url @pytest.mark.parametrize("char", [chr(i) for i in range(0x00, 0x21)] + ["\x7F"]) def test_control_characters_are_percent_encoded(self, char): percent_char = "%" + (hex(ord(char))[2:].zfill(2).upper()) url = parse_url( "http://user{0}@example.com/path{0}?query{0}#fragment{0}".format(char) ) assert url == Url( "http", auth="user" + percent_char, host="example.com", path="/path" + percent_char, query="query" + percent_char, fragment="fragment" + percent_char, ) parse_url_host_map = [ ("http://google.com/mail", Url("http", host="google.com", path="/mail")), ("http://google.com/mail/", Url("http", host="google.com", path="/mail/")), ("http://google.com/mail", Url("http", host="google.com", path="mail")), ("google.com/mail", Url(host="google.com", path="/mail")), ("http://google.com/", Url("http", host="google.com", path="/")), ("http://google.com", Url("http", host="google.com")), ("http://google.com?foo", Url("http", host="google.com", path="", query="foo")), # Path/query/fragment ("", Url()), ("/", Url(path="/")), ("#?/!google.com/?foo", Url(path="", fragment="?/!google.com/?foo")), ("/foo", Url(path="/foo")), ("/foo?bar=baz", Url(path="/foo", query="bar=baz")), ( "/foo?bar=baz#banana?apple/orange", Url(path="/foo", query="bar=baz", fragment="banana?apple/orange"), ), ( "/redirect?target=http://localhost:61020/", Url(path="redirect", query="target=http://localhost:61020/"), ), # Port ("http://google.com/", Url("http", host="google.com", path="/")), ("http://google.com:80/", Url("http", host="google.com", port=80, path="/")), ("http://google.com:80", Url("http", host="google.com", port=80)), # Auth ( "http://foo:bar@localhost/", Url("http", auth="foo:bar", host="localhost", path="/"), ), ("http://foo@localhost/", Url("http", auth="foo", host="localhost", path="/")), ( "http://foo:bar@localhost/", Url("http", auth="foo:bar", host="localhost", path="/"), ), # Unicode type (Python 2.x) ( u"http://foo:bar@localhost/", Url(u"http", auth=u"foo:bar", host=u"localhost", path=u"/"), ), ( "http://foo:bar@localhost/", Url("http", auth="foo:bar", host="localhost", path="/"), ), ] non_round_tripping_parse_url_host_map = [ # Path/query/fragment ("?", Url(path="", query="")), ("#", Url(path="", fragment="")), # Path normalization ("/abc/../def", Url(path="/def")), # Empty Port ("http://google.com:", Url("http", host="google.com")), ("http://google.com:/", Url("http", host="google.com", path="/")), # Uppercase IRI ( u"http://Königsgäßchen.de/straße", Url("http", host="xn--knigsgchen-b4a3dun.de", path="/stra%C3%9Fe"), ), # Percent-encode in userinfo ( u"http://user@email.com:password@example.com/", Url("http", auth="user%40email.com:password", host="example.com", path="/"), ), ( u'http://user":quoted@example.com/', Url("http", auth="user%22:quoted", host="example.com", path="/"), ), # Unicode Surrogates (u"http://google.com/\uD800", Url("http", host="google.com", path="%ED%A0%80")), ( u"http://google.com?q=\uDC00", Url("http", host="google.com", path="", query="q=%ED%B0%80"), ), ( u"http://google.com#\uDC00", Url("http", host="google.com", path="", fragment="%ED%B0%80"), ), ] @pytest.mark.parametrize( "url, expected_url", chain(parse_url_host_map, non_round_tripping_parse_url_host_map), ) def test_parse_url(self, url, expected_url): returned_url = parse_url(url) assert returned_url == expected_url @pytest.mark.parametrize("url, expected_url", parse_url_host_map) def test_unparse_url(self, url, expected_url): assert url == expected_url.url @pytest.mark.parametrize( ["url", "expected_url"], [ # RFC 3986 5.2.4 ("/abc/../def", Url(path="/def")), ("/..", Url(path="/")), ("/./abc/./def/", Url(path="/abc/def/")), ("/.", Url(path="/")), ("/./", Url(path="/")), ("/abc/./.././d/././e/.././f/./../../ghi", Url(path="/ghi")), ], ) def test_parse_and_normalize_url_paths(self, url, expected_url): actual_url = parse_url(url) assert actual_url == expected_url assert actual_url.url == expected_url.url def test_parse_url_invalid_IPv6(self): with pytest.raises(LocationParseError): parse_url("[::1") def test_parse_url_negative_port(self): with pytest.raises(LocationParseError): parse_url("https://www.google.com:-80/") def test_Url_str(self): U = Url("http", host="google.com") assert str(U) == U.url request_uri_map = [ ("http://google.com/mail", "/mail"), ("http://google.com/mail/", "/mail/"), ("http://google.com/", "/"), ("http://google.com", "/"), ("", "/"), ("/", "/"), ("?", "/?"), ("#", "/"), ("/foo?bar=baz", "/foo?bar=baz"), ] @pytest.mark.parametrize("url, expected_request_uri", request_uri_map) def test_request_uri(self, url, expected_request_uri): returned_url = parse_url(url) assert returned_url.request_uri == expected_request_uri url_netloc_map = [ ("http://google.com/mail", "google.com"), ("http://google.com:80/mail", "google.com:80"), ("google.com/foobar", "google.com"), ("google.com:12345", "google.com:12345"), ] @pytest.mark.parametrize("url, expected_netloc", url_netloc_map) def test_netloc(self, url, expected_netloc): assert parse_url(url).netloc == expected_netloc url_vulnerabilities = [ # urlparse doesn't follow RFC 3986 Section 3.2 ( "http://google.com#@evil.com/", Url("http", host="google.com", path="", fragment="@evil.com/"), ), # CVE-2016-5699 ( "http://127.0.0.1%0d%0aConnection%3a%20keep-alive", Url("http", host="127.0.0.1%0d%0aconnection%3a%20keep-alive"), ), # NodeJS unicode -> double dot ( u"http://google.com/\uff2e\uff2e/abc", Url("http", host="google.com", path="/%EF%BC%AE%EF%BC%AE/abc"), ), # Scheme without :// ( "javascript:a='@google.com:12345/';alert(0)", Url(scheme="javascript", path="a='@google.com:12345/';alert(0)"), ), ("//google.com/a/b/c", Url(host="google.com", path="/a/b/c")), # International URLs ( u"http://ヒ:キ@ヒ.abc.ニ/ヒ?キ#ワ", Url( u"http", host=u"xn--pdk.abc.xn--idk", auth=u"%E3%83%92:%E3%82%AD", path=u"/%E3%83%92", query=u"%E3%82%AD", fragment=u"%E3%83%AF", ), ), # Injected headers (CVE-2016-5699, CVE-2019-9740, CVE-2019-9947) ( "10.251.0.83:7777?a=1 HTTP/1.1\r\nX-injected: header", Url( host="10.251.0.83", port=7777, path="", query="a=1%20HTTP/1.1%0D%0AX-injected:%20header", ), ), ( "http://127.0.0.1:6379?\r\nSET test failure12\r\n:8080/test/?test=a", Url( scheme="http", host="127.0.0.1", port=6379, path="", query="%0D%0ASET%20test%20failure12%0D%0A:8080/test/?test=a", ), ), ] @pytest.mark.parametrize("url, expected_url", url_vulnerabilities) def test_url_vulnerabilities(self, url, expected_url): if expected_url is False: with pytest.raises(LocationParseError): parse_url(url) else: assert parse_url(url) == expected_url @onlyPy2 def test_parse_url_bytes_to_str_python_2(self): url = parse_url(b"https://www.google.com/") assert url == Url("https", host="www.google.com", path="/") assert isinstance(url.scheme, str) assert isinstance(url.host, str) assert isinstance(url.path, str) @onlyPy2 def test_parse_url_unicode_python_2(self): url = parse_url(u"https://www.google.com/") assert url == Url(u"https", host=u"www.google.com", path=u"/") assert isinstance(url.scheme, six.text_type) assert isinstance(url.host, six.text_type) assert isinstance(url.path, six.text_type) @onlyPy3 def test_parse_url_bytes_type_error_python_3(self): with pytest.raises(TypeError): parse_url(b"https://www.google.com/") @pytest.mark.parametrize( "kwargs, expected", [ pytest.param( {"accept_encoding": True}, {"accept-encoding": "gzip,deflate,br"}, marks=onlyBrotlipy(), ), pytest.param( {"accept_encoding": True}, {"accept-encoding": "gzip,deflate"}, marks=notBrotlipy(), ), ({"accept_encoding": "foo,bar"}, {"accept-encoding": "foo,bar"}), ({"accept_encoding": ["foo", "bar"]}, {"accept-encoding": "foo,bar"}), pytest.param( {"accept_encoding": True, "user_agent": "banana"}, {"accept-encoding": "gzip,deflate,br", "user-agent": "banana"}, marks=onlyBrotlipy(), ), pytest.param( {"accept_encoding": True, "user_agent": "banana"}, {"accept-encoding": "gzip,deflate", "user-agent": "banana"}, marks=notBrotlipy(), ), ({"user_agent": "banana"}, {"user-agent": "banana"}), ({"keep_alive": True}, {"connection": "keep-alive"}), ({"basic_auth": "foo:bar"}, {"authorization": "Basic Zm9vOmJhcg=="}), ( {"proxy_basic_auth": "foo:bar"}, {"proxy-authorization": "Basic Zm9vOmJhcg=="}, ), ({"disable_cache": True}, {"cache-control": "no-cache"}), ], ) def test_make_headers(self, kwargs, expected): assert make_headers(**kwargs) == expected def test_rewind_body(self): body = io.BytesIO(b"test data") assert body.read() == b"test data" # Assert the file object has been consumed assert body.read() == b"" # Rewind it back to just be b'data' rewind_body(body, 5) assert body.read() == b"data" def test_rewind_body_failed_tell(self): body = io.BytesIO(b"test data") body.read() # Consume body # Simulate failed tell() body_pos = _FAILEDTELL with pytest.raises(UnrewindableBodyError): rewind_body(body, body_pos) def test_rewind_body_bad_position(self): body = io.BytesIO(b"test data") body.read() # Consume body # Pass non-integer position with pytest.raises(ValueError): rewind_body(body, body_pos=None) with pytest.raises(ValueError): rewind_body(body, body_pos=object()) def test_rewind_body_failed_seek(self): class BadSeek: def seek(self, pos, offset=0): raise IOError with pytest.raises(UnrewindableBodyError): rewind_body(BadSeek(), body_pos=2) @pytest.mark.parametrize( "input, expected", [ (("abcd", "b"), ("a", "cd", "b")), (("abcd", "cb"), ("a", "cd", "b")), (("abcd", ""), ("abcd", "", None)), (("abcd", "a"), ("", "bcd", "a")), (("abcd", "ab"), ("", "bcd", "a")), (("abcd", "eb"), ("a", "cd", "b")), ], ) def test_split_first(self, input, expected): output = split_first(*input) assert output == expected def test_add_stderr_logger(self): handler = add_stderr_logger(level=logging.INFO) # Don't actually print debug logger = logging.getLogger("urllib3") assert handler in logger.handlers logger.debug("Testing add_stderr_logger") logger.removeHandler(handler) def test_disable_warnings(self): with warnings.catch_warnings(record=True) as w: clear_warnings() warnings.warn("This is a test.", InsecureRequestWarning) assert len(w) == 1 disable_warnings() warnings.warn("This is a test.", InsecureRequestWarning) assert len(w) == 1 def _make_time_pass(self, seconds, timeout, time_mock): """ Make some time pass for the timeout object """ time_mock.return_value = TIMEOUT_EPOCH timeout.start_connect() time_mock.return_value = TIMEOUT_EPOCH + seconds return timeout @pytest.mark.parametrize( "kwargs, message", [ ({"total": -1}, "less than"), ({"connect": 2, "total": -1}, "less than"), ({"read": -1}, "less than"), ({"connect": False}, "cannot be a boolean"), ({"read": True}, "cannot be a boolean"), ({"connect": 0}, "less than or equal"), ({"read": "foo"}, "int, float or None"), ], ) def test_invalid_timeouts(self, kwargs, message): with pytest.raises(ValueError) as e: Timeout(**kwargs) assert message in str(e.value) @patch("urllib3.util.timeout.current_time") def test_timeout(self, current_time): timeout = Timeout(total=3) # make 'no time' elapse timeout = self._make_time_pass( seconds=0, timeout=timeout, time_mock=current_time ) assert timeout.read_timeout == 3 assert timeout.connect_timeout == 3 timeout = Timeout(total=3, connect=2) assert timeout.connect_timeout == 2 timeout = Timeout() assert timeout.connect_timeout == Timeout.DEFAULT_TIMEOUT # Connect takes 5 seconds, leaving 5 seconds for read timeout = Timeout(total=10, read=7) timeout = self._make_time_pass( seconds=5, timeout=timeout, time_mock=current_time ) assert timeout.read_timeout == 5 # Connect takes 2 seconds, read timeout still 7 seconds timeout = Timeout(total=10, read=7) timeout = self._make_time_pass( seconds=2, timeout=timeout, time_mock=current_time ) assert timeout.read_timeout == 7 timeout = Timeout(total=10, read=7) assert timeout.read_timeout == 7 timeout = Timeout(total=None, read=None, connect=None) assert timeout.connect_timeout is None assert timeout.read_timeout is None assert timeout.total is None timeout = Timeout(5) assert timeout.total == 5 def test_timeout_str(self): timeout = Timeout(connect=1, read=2, total=3) assert str(timeout) == "Timeout(connect=1, read=2, total=3)" timeout = Timeout(connect=1, read=None, total=3) assert str(timeout) == "Timeout(connect=1, read=None, total=3)" @patch("urllib3.util.timeout.current_time") def test_timeout_elapsed(self, current_time): current_time.return_value = TIMEOUT_EPOCH timeout = Timeout(total=3) with pytest.raises(TimeoutStateError): timeout.get_connect_duration() timeout.start_connect() with pytest.raises(TimeoutStateError): timeout.start_connect() current_time.return_value = TIMEOUT_EPOCH + 2 assert timeout.get_connect_duration() == 2 current_time.return_value = TIMEOUT_EPOCH + 37 assert timeout.get_connect_duration() == 37 @pytest.mark.parametrize( "candidate, requirements", [ (None, ssl.CERT_REQUIRED), (ssl.CERT_NONE, ssl.CERT_NONE), (ssl.CERT_REQUIRED, ssl.CERT_REQUIRED), ("REQUIRED", ssl.CERT_REQUIRED), ("CERT_REQUIRED", ssl.CERT_REQUIRED), ], ) def test_resolve_cert_reqs(self, candidate, requirements): assert resolve_cert_reqs(candidate) == requirements @pytest.mark.parametrize( "candidate, version", [ (ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1), ("PROTOCOL_TLSv1", ssl.PROTOCOL_TLSv1), ("TLSv1", ssl.PROTOCOL_TLSv1), (ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23), ], ) def test_resolve_ssl_version(self, candidate, version): assert resolve_ssl_version(candidate) == version def test_is_fp_closed_object_supports_closed(self): class ClosedFile(object): @property def closed(self): return True assert is_fp_closed(ClosedFile()) def test_is_fp_closed_object_has_none_fp(self): class NoneFpFile(object): @property def fp(self): return None assert is_fp_closed(NoneFpFile()) def test_is_fp_closed_object_has_fp(self): class FpFile(object): @property def fp(self): return True assert not is_fp_closed(FpFile()) def test_is_fp_closed_object_has_neither_fp_nor_closed(self): class NotReallyAFile(object): pass with pytest.raises(ValueError): is_fp_closed(NotReallyAFile()) def test_ssl_wrap_socket_loads_the_cert_chain(self): socket = object() mock_context = Mock() ssl_wrap_socket( ssl_context=mock_context, sock=socket, certfile="/path/to/certfile" ) mock_context.load_cert_chain.assert_called_once_with("/path/to/certfile", None) @patch("urllib3.util.ssl_.create_urllib3_context") def test_ssl_wrap_socket_creates_new_context(self, create_urllib3_context): socket = object() ssl_wrap_socket(sock=socket, cert_reqs="CERT_REQUIRED") create_urllib3_context.assert_called_once_with( None, "CERT_REQUIRED", ciphers=None ) def test_ssl_wrap_socket_loads_verify_locations(self): socket = object() mock_context = Mock() ssl_wrap_socket(ssl_context=mock_context, ca_certs="/path/to/pem", sock=socket) mock_context.load_verify_locations.assert_called_once_with("/path/to/pem", None) def test_ssl_wrap_socket_loads_certificate_directories(self): socket = object() mock_context = Mock() ssl_wrap_socket( ssl_context=mock_context, ca_cert_dir="/path/to/pems", sock=socket ) mock_context.load_verify_locations.assert_called_once_with( None, "/path/to/pems" ) def test_ssl_wrap_socket_with_no_sni_warns(self): socket = object() mock_context = Mock() # Ugly preservation of original value HAS_SNI = ssl_.HAS_SNI ssl_.HAS_SNI = False try: with patch("warnings.warn") as warn: ssl_wrap_socket( ssl_context=mock_context, sock=socket, server_hostname="www.google.com", ) mock_context.wrap_socket.assert_called_once_with(socket) assert warn.call_count >= 1 warnings = [call[0][1] for call in warn.call_args_list] assert SNIMissingWarning in warnings finally: ssl_.HAS_SNI = HAS_SNI def test_const_compare_digest_fallback(self): target = hashlib.sha256(b"abcdef").digest() assert _const_compare_digest_backport(target, target) prefix = target[:-1] assert not _const_compare_digest_backport(target, prefix) suffix = target + b"0" assert not _const_compare_digest_backport(target, suffix) incorrect = hashlib.sha256(b"xyz").digest() assert not _const_compare_digest_backport(target, incorrect) def test_has_ipv6_disabled_on_compile(self): with patch("socket.has_ipv6", False): assert not _has_ipv6("::1") def test_has_ipv6_enabled_but_fails(self): with patch("socket.has_ipv6", True): with patch("socket.socket") as mock: instance = mock.return_value instance.bind = Mock(side_effect=Exception("No IPv6 here!")) assert not _has_ipv6("::1") def test_has_ipv6_enabled_and_working(self): with patch("socket.has_ipv6", True): with patch("socket.socket") as mock: instance = mock.return_value instance.bind.return_value = True assert _has_ipv6("::1") def test_has_ipv6_disabled_on_appengine(self): gae_patch = patch( "urllib3.contrib._appengine_environ.is_appengine_sandbox", return_value=True ) with gae_patch: assert not _has_ipv6("::1") def test_ip_family_ipv6_enabled(self): with patch("urllib3.util.connection.HAS_IPV6", True): assert allowed_gai_family() == socket.AF_UNSPEC def test_ip_family_ipv6_disabled(self): with patch("urllib3.util.connection.HAS_IPV6", False): assert allowed_gai_family() == socket.AF_INET @pytest.mark.parametrize("headers", [b"foo", None, object]) def test_assert_header_parsing_throws_typeerror_with_non_headers(self, headers): with pytest.raises(TypeError): assert_header_parsing(headers) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/test_wait.py0000644000175000017500000001253200000000000021443 0ustar00sethmlarsonsethmlarson00000000000000import signal import socket import threading try: from time import monotonic except ImportError: from time import time as monotonic import time import pytest from .socketpair_helper import socketpair from urllib3.util.wait import ( wait_for_read, wait_for_write, wait_for_socket, select_wait_for_socket, poll_wait_for_socket, _have_working_poll, ) @pytest.fixture def spair(): a, b = socketpair() yield a, b a.close() b.close() variants = [wait_for_socket, select_wait_for_socket] if _have_working_poll(): variants.append(poll_wait_for_socket) @pytest.mark.parametrize("wfs", variants) def test_wait_for_socket(wfs, spair): a, b = spair with pytest.raises(RuntimeError): wfs(a, read=False, write=False) assert not wfs(a, read=True, timeout=0) assert wfs(a, write=True, timeout=0) b.send(b"x") assert wfs(a, read=True, timeout=0) assert wfs(a, read=True, timeout=10) assert wfs(a, read=True, timeout=None) # Fill up the socket with data a.setblocking(False) try: while True: a.send(b"x" * 999999) except (OSError, socket.error): pass # Now it's not writable anymore assert not wfs(a, write=True, timeout=0) # But if we ask for read-or-write, that succeeds assert wfs(a, read=True, write=True, timeout=0) # Unless we read from it assert a.recv(1) == b"x" assert not wfs(a, read=True, write=True, timeout=0) # But if the remote peer closes the socket, then it becomes readable b.close() assert wfs(a, read=True, timeout=0) # Waiting for a socket that's actually been closed is just a bug, and # raises some kind of helpful exception (exact details depend on the # platform). with pytest.raises(Exception): wfs(b, read=True) def test_wait_for_read_write(spair): a, b = spair assert not wait_for_read(a, 0) assert wait_for_write(a, 0) b.send(b"x") assert wait_for_read(a, 0) assert wait_for_write(a, 0) # Fill up the socket with data a.setblocking(False) try: while True: a.send(b"x" * 999999) except (OSError, socket.error): pass # Now it's not writable anymore assert not wait_for_write(a, 0) @pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="need setitimer() support") @pytest.mark.parametrize("wfs", variants) def test_eintr(wfs, spair): a, b = spair interrupt_count = [0] def handler(sig, frame): assert sig == signal.SIGALRM interrupt_count[0] += 1 old_handler = signal.signal(signal.SIGALRM, handler) try: assert not wfs(a, read=True, timeout=0) start = monotonic() try: # Start delivering SIGALRM 10 times per second signal.setitimer(signal.ITIMER_REAL, 0.1, 0.1) # Sleep for 1 second (we hope!) wfs(a, read=True, timeout=1) finally: # Stop delivering SIGALRM signal.setitimer(signal.ITIMER_REAL, 0) end = monotonic() dur = end - start assert 0.9 < dur < 3 finally: signal.signal(signal.SIGALRM, old_handler) assert interrupt_count[0] > 0 @pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="need setitimer() support") @pytest.mark.parametrize("wfs", variants) def test_eintr_zero_timeout(wfs, spair): a, b = spair interrupt_count = [0] def handler(sig, frame): assert sig == signal.SIGALRM interrupt_count[0] += 1 old_handler = signal.signal(signal.SIGALRM, handler) try: assert not wfs(a, read=True, timeout=0) try: # Start delivering SIGALRM 1000 times per second, # to trigger race conditions such as # https://github.com/urllib3/urllib3/issues/1396. signal.setitimer(signal.ITIMER_REAL, 0.001, 0.001) # Hammer the system call for a while to trigger the # race. for i in range(100000): wfs(a, read=True, timeout=0) finally: # Stop delivering SIGALRM signal.setitimer(signal.ITIMER_REAL, 0) finally: signal.signal(signal.SIGALRM, old_handler) assert interrupt_count[0] > 0 @pytest.mark.skipif(not hasattr(signal, "setitimer"), reason="need setitimer() support") @pytest.mark.parametrize("wfs", variants) def test_eintr_infinite_timeout(wfs, spair): a, b = spair interrupt_count = [0] def handler(sig, frame): assert sig == signal.SIGALRM interrupt_count[0] += 1 def make_a_readable_after_one_second(): time.sleep(1) b.send(b"x") old_handler = signal.signal(signal.SIGALRM, handler) try: assert not wfs(a, read=True, timeout=0) start = monotonic() try: # Start delivering SIGALRM 10 times per second signal.setitimer(signal.ITIMER_REAL, 0.1, 0.1) # Sleep for 1 second (we hope!) thread = threading.Thread(target=make_a_readable_after_one_second) thread.start() wfs(a, read=True) finally: # Stop delivering SIGALRM signal.setitimer(signal.ITIMER_REAL, 0) thread.join() end = monotonic() dur = end - start assert 0.9 < dur < 3 finally: signal.signal(signal.SIGALRM, old_handler) assert interrupt_count[0] > 0 ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1579639273.901864 urllib3-1.25.8/test/with_dummyserver/0000755000175000017500000000000000000000000022500 5ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/__init__.py0000644000175000017500000000000000000000000024577 0ustar00sethmlarsonsethmlarson00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_chunked_transfer.py0000644000175000017500000001510000000000000027433 0ustar00sethmlarsonsethmlarson00000000000000# -*- coding: utf-8 -*- import pytest from urllib3 import HTTPConnectionPool from urllib3.util.retry import Retry from dummyserver.testcase import SocketDummyServerTestCase, consume_socket # Retry failed tests pytestmark = pytest.mark.flaky class TestChunkedTransfer(SocketDummyServerTestCase): def start_chunked_handler(self): self.buffer = b"" def socket_handler(listener): sock = listener.accept()[0] while not self.buffer.endswith(b"\r\n0\r\n\r\n"): self.buffer += sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-type: text/plain\r\n" b"Content-Length: 0\r\n" b"\r\n" ) sock.close() self._start_server(socket_handler) def test_chunks(self): self.start_chunked_handler() chunks = ["foo", "bar", "", "bazzzzzzzzzzzzzzzzzzzzzz"] with HTTPConnectionPool(self.host, self.port, retries=False) as pool: pool.urlopen("GET", "/", chunks, headers=dict(DNT="1"), chunked=True) assert b"Transfer-Encoding" in self.buffer body = self.buffer.split(b"\r\n\r\n", 1)[1] lines = body.split(b"\r\n") # Empty chunks should have been skipped, as this could not be distinguished # from terminating the transmission for i, chunk in enumerate([c for c in chunks if c]): assert lines[i * 2] == hex(len(chunk))[2:].encode("utf-8") assert lines[i * 2 + 1] == chunk.encode("utf-8") def _test_body(self, data): self.start_chunked_handler() with HTTPConnectionPool(self.host, self.port, retries=False) as pool: pool.urlopen("GET", "/", data, chunked=True) header, body = self.buffer.split(b"\r\n\r\n", 1) assert b"Transfer-Encoding: chunked" in header.split(b"\r\n") if data: bdata = data if isinstance(data, bytes) else data.encode("utf-8") assert b"\r\n" + bdata + b"\r\n" in body assert body.endswith(b"\r\n0\r\n\r\n") len_str = body.split(b"\r\n", 1)[0] stated_len = int(len_str, 16) assert stated_len == len(bdata) else: assert body == b"0\r\n\r\n" def test_bytestring_body(self): self._test_body(b"thisshouldbeonechunk\r\nasdf") def test_unicode_body(self): self._test_body(u"thisshouldbeonechunk\r\näöüß") def test_empty_body(self): self._test_body(None) def test_empty_string_body(self): self._test_body("") def test_empty_iterable_body(self): self._test_body([]) def test_removes_duplicate_host_header(self): self.start_chunked_handler() chunks = ["foo", "bar", "", "bazzzzzzzzzzzzzzzzzzzzzz"] with HTTPConnectionPool(self.host, self.port, retries=False) as pool: pool.urlopen("GET", "/", chunks, headers={"Host": "test.org"}, chunked=True) header_block = self.buffer.split(b"\r\n\r\n", 1)[0].lower() header_lines = header_block.split(b"\r\n")[1:] host_headers = [x for x in header_lines if x.startswith(b"host")] assert len(host_headers) == 1 def test_provides_default_host_header(self): self.start_chunked_handler() chunks = ["foo", "bar", "", "bazzzzzzzzzzzzzzzzzzzzzz"] with HTTPConnectionPool(self.host, self.port, retries=False) as pool: pool.urlopen("GET", "/", chunks, chunked=True) header_block = self.buffer.split(b"\r\n\r\n", 1)[0].lower() header_lines = header_block.split(b"\r\n")[1:] host_headers = [x for x in header_lines if x.startswith(b"host")] assert len(host_headers) == 1 def test_preserve_chunked_on_retry(self): self.chunked_requests = 0 def socket_handler(listener): for _ in range(2): sock = listener.accept()[0] request = consume_socket(sock) if b"Transfer-Encoding: chunked" in request.split(b"\r\n"): self.chunked_requests += 1 sock.send( b"HTTP/1.1 429 Too Many Requests\r\n" b"Content-Type: text/plain\r\n" b"Retry-After: 1\r\n" b"\r\n" ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: retries = Retry(total=1) pool.urlopen( "GET", "/", chunked=True, preload_content=False, retries=retries ) assert self.chunked_requests == 2 def test_preserve_chunked_on_redirect(self): self.chunked_requests = 0 def socket_handler(listener): for i in range(2): sock = listener.accept()[0] request = consume_socket(sock) if b"Transfer-Encoding: chunked" in request.split(b"\r\n"): self.chunked_requests += 1 if i == 0: sock.send( b"HTTP/1.1 301 Moved Permanently\r\n" b"Location: /redirect\r\n\r\n" ) else: sock.send(b"HTTP/1.1 200 OK\r\n\r\n") sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: retries = Retry(redirect=1) pool.urlopen( "GET", "/", chunked=True, preload_content=False, retries=retries ) assert self.chunked_requests == 2 def test_preserve_chunked_on_broken_connection(self): self.chunked_requests = 0 def socket_handler(listener): for i in range(2): sock = listener.accept()[0] request = consume_socket(sock) if b"Transfer-Encoding: chunked" in request.split(b"\r\n"): self.chunked_requests += 1 if i == 0: # Bad HTTP version will trigger a connection close sock.send(b"HTTP/0.5 200 OK\r\n\r\n") else: sock.send(b"HTTP/1.1 200 OK\r\n\r\n") sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: retries = Retry(read=1) pool.urlopen( "GET", "/", chunked=True, preload_content=False, retries=retries ) assert self.chunked_requests == 2 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_connectionpool.py0000644000175000017500000012346300000000000027153 0ustar00sethmlarsonsethmlarson00000000000000import io import logging import socket import sys import time import warnings import pytest import mock from .. import TARPIT_HOST, VALID_SOURCE_ADDRESSES, INVALID_SOURCE_ADDRESSES from ..port_helpers import find_unused_port from urllib3 import encode_multipart_formdata, HTTPConnectionPool from urllib3.exceptions import ( ConnectTimeoutError, EmptyPoolError, DecodeError, MaxRetryError, ReadTimeoutError, NewConnectionError, UnrewindableBodyError, ) from urllib3.packages.six import b, u from urllib3.packages.six.moves.urllib.parse import urlencode from urllib3.util.retry import Retry, RequestHistory from urllib3.util.timeout import Timeout from test import SHORT_TIMEOUT, LONG_TIMEOUT from dummyserver.testcase import HTTPDummyServerTestCase, SocketDummyServerTestCase from dummyserver.server import NoIPv6Warning, HAS_IPV6_AND_DNS from threading import Event pytestmark = pytest.mark.flaky log = logging.getLogger("urllib3.connectionpool") log.setLevel(logging.NOTSET) log.addHandler(logging.StreamHandler(sys.stdout)) def wait_for_socket(ready_event): ready_event.wait() ready_event.clear() class TestConnectionPoolTimeouts(SocketDummyServerTestCase): def test_timeout_float(self): block_event = Event() ready_event = self.start_basic_handler(block_send=block_event, num=2) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: wait_for_socket(ready_event) with pytest.raises(ReadTimeoutError): pool.request("GET", "/", timeout=SHORT_TIMEOUT) block_event.set() # Release block # Shouldn't raise this time wait_for_socket(ready_event) block_event.set() # Pre-release block pool.request("GET", "/", timeout=LONG_TIMEOUT) def test_conn_closed(self): block_event = Event() self.start_basic_handler(block_send=block_event, num=1) with HTTPConnectionPool( self.host, self.port, timeout=SHORT_TIMEOUT, retries=False ) as pool: conn = pool._get_conn() pool._put_conn(conn) try: with pytest.raises(ReadTimeoutError): pool.urlopen("GET", "/") if conn.sock: with pytest.raises(socket.error): conn.sock.recv(1024) finally: pool._put_conn(conn) block_event.set() def test_timeout(self): # Requests should time out when expected block_event = Event() ready_event = self.start_basic_handler(block_send=block_event, num=3) # Pool-global timeout short_timeout = Timeout(read=SHORT_TIMEOUT) with HTTPConnectionPool( self.host, self.port, timeout=short_timeout, retries=False ) as pool: wait_for_socket(ready_event) block_event.clear() with pytest.raises(ReadTimeoutError): pool.request("GET", "/") block_event.set() # Release request # Request-specific timeouts should raise errors with HTTPConnectionPool( self.host, self.port, timeout=short_timeout, retries=False ) as pool: wait_for_socket(ready_event) now = time.time() with pytest.raises(ReadTimeoutError): pool.request("GET", "/", timeout=LONG_TIMEOUT) delta = time.time() - now message = "timeout was pool-level SHORT_TIMEOUT rather than request-level LONG_TIMEOUT" assert delta >= LONG_TIMEOUT, message block_event.set() # Release request # Timeout passed directly to request should raise a request timeout wait_for_socket(ready_event) with pytest.raises(ReadTimeoutError): pool.request("GET", "/", timeout=SHORT_TIMEOUT) block_event.set() # Release request def test_connect_timeout(self): url = "/" host, port = TARPIT_HOST, 80 timeout = Timeout(connect=SHORT_TIMEOUT) # Pool-global timeout with HTTPConnectionPool(host, port, timeout=timeout) as pool: conn = pool._get_conn() with pytest.raises(ConnectTimeoutError): pool._make_request(conn, "GET", url) # Retries retries = Retry(connect=0) with pytest.raises(MaxRetryError): pool.request("GET", url, retries=retries) # Request-specific connection timeouts big_timeout = Timeout(read=LONG_TIMEOUT, connect=LONG_TIMEOUT) with HTTPConnectionPool(host, port, timeout=big_timeout, retries=False) as pool: conn = pool._get_conn() with pytest.raises(ConnectTimeoutError): pool._make_request(conn, "GET", url, timeout=timeout) pool._put_conn(conn) with pytest.raises(ConnectTimeoutError): pool.request("GET", url, timeout=timeout) def test_total_applies_connect(self): host, port = TARPIT_HOST, 80 timeout = Timeout(total=None, connect=SHORT_TIMEOUT) with HTTPConnectionPool(host, port, timeout=timeout) as pool: conn = pool._get_conn() try: with pytest.raises(ConnectTimeoutError): pool._make_request(conn, "GET", "/") finally: conn.close() timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT) with HTTPConnectionPool(host, port, timeout=timeout) as pool: conn = pool._get_conn() try: with pytest.raises(ConnectTimeoutError): pool._make_request(conn, "GET", "/") finally: conn.close() def test_total_timeout(self): block_event = Event() ready_event = self.start_basic_handler(block_send=block_event, num=2) wait_for_socket(ready_event) # This will get the socket to raise an EAGAIN on the read timeout = Timeout(connect=3, read=SHORT_TIMEOUT) with HTTPConnectionPool( self.host, self.port, timeout=timeout, retries=False ) as pool: with pytest.raises(ReadTimeoutError): pool.request("GET", "/") block_event.set() wait_for_socket(ready_event) block_event.clear() # The connect should succeed and this should hit the read timeout timeout = Timeout(connect=3, read=5, total=SHORT_TIMEOUT) with HTTPConnectionPool( self.host, self.port, timeout=timeout, retries=False ) as pool: with pytest.raises(ReadTimeoutError): pool.request("GET", "/") def test_create_connection_timeout(self): self.start_basic_handler(block_send=Event(), num=0) # needed for self.port timeout = Timeout(connect=SHORT_TIMEOUT, total=LONG_TIMEOUT) with HTTPConnectionPool( TARPIT_HOST, self.port, timeout=timeout, retries=False ) as pool: conn = pool._new_conn() with pytest.raises(ConnectTimeoutError): conn.connect() class TestConnectionPool(HTTPDummyServerTestCase): def test_get(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/specific_method", fields={"method": "GET"}) assert r.status == 200, r.data def test_post_url(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("POST", "/specific_method", fields={"method": "POST"}) assert r.status == 200, r.data def test_urlopen_put(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.urlopen("PUT", "/specific_method?method=PUT") assert r.status == 200, r.data def test_wrong_specific_method(self): # To make sure the dummy server is actually returning failed responses with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/specific_method", fields={"method": "POST"}) assert r.status == 400, r.data with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("POST", "/specific_method", fields={"method": "GET"}) assert r.status == 400, r.data def test_upload(self): data = "I'm in ur multipart form-data, hazing a cheezburgr" fields = { "upload_param": "filefield", "upload_filename": "lolcat.txt", "upload_size": len(data), "filefield": ("lolcat.txt", data), } with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("POST", "/upload", fields=fields) assert r.status == 200, r.data def test_one_name_multiple_values(self): fields = [("foo", "a"), ("foo", "b")] with HTTPConnectionPool(self.host, self.port) as pool: # urlencode r = pool.request("GET", "/echo", fields=fields) assert r.data == b"foo=a&foo=b" # multipart r = pool.request("POST", "/echo", fields=fields) assert r.data.count(b'name="foo"') == 2 def test_request_method_body(self): with HTTPConnectionPool(self.host, self.port) as pool: body = b"hi" r = pool.request("POST", "/echo", body=body) assert r.data == body fields = [("hi", "hello")] with pytest.raises(TypeError): pool.request("POST", "/echo", body=body, fields=fields) def test_unicode_upload(self): fieldname = u("myfile") filename = u("\xe2\x99\xa5.txt") data = u("\xe2\x99\xa5").encode("utf8") size = len(data) fields = { u("upload_param"): fieldname, u("upload_filename"): filename, u("upload_size"): size, fieldname: (filename, data), } with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("POST", "/upload", fields=fields) assert r.status == 200, r.data def test_nagle(self): """ Test that connections have TCP_NODELAY turned on """ # This test needs to be here in order to be run. socket.create_connection actually tries # to connect to the host provided so we need a dummyserver to be running. with HTTPConnectionPool(self.host, self.port) as pool: conn = pool._get_conn() try: pool._make_request(conn, "GET", "/") tcp_nodelay_setting = conn.sock.getsockopt( socket.IPPROTO_TCP, socket.TCP_NODELAY ) assert tcp_nodelay_setting finally: conn.close() def test_socket_options(self): """Test that connections accept socket options.""" # This test needs to be here in order to be run. socket.create_connection actually tries to # connect to the host provided so we need a dummyserver to be running. with HTTPConnectionPool( self.host, self.port, socket_options=[(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)], ) as pool: s = pool._new_conn()._new_conn() # Get the socket try: using_keepalive = ( s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0 ) assert using_keepalive finally: s.close() def test_disable_default_socket_options(self): """Test that passing None disables all socket options.""" # This test needs to be here in order to be run. socket.create_connection actually tries # to connect to the host provided so we need a dummyserver to be running. with HTTPConnectionPool(self.host, self.port, socket_options=None) as pool: s = pool._new_conn()._new_conn() try: using_nagle = s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) == 0 assert using_nagle finally: s.close() def test_defaults_are_applied(self): """Test that modifying the default socket options works.""" # This test needs to be here in order to be run. socket.create_connection actually tries # to connect to the host provided so we need a dummyserver to be running. with HTTPConnectionPool(self.host, self.port) as pool: # Get the HTTPConnection instance conn = pool._new_conn() try: # Update the default socket options conn.default_socket_options += [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) ] s = conn._new_conn() nagle_disabled = ( s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) > 0 ) using_keepalive = ( s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0 ) assert nagle_disabled assert using_keepalive finally: conn.close() s.close() def test_connection_error_retries(self): """ ECONNREFUSED error should raise a connection error, with retries """ port = find_unused_port() with HTTPConnectionPool(self.host, port) as pool: with pytest.raises(MaxRetryError) as e: pool.request("GET", "/", retries=Retry(connect=3)) assert type(e.value.reason) == NewConnectionError def test_timeout_success(self): timeout = Timeout(connect=3, read=5, total=None) with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: pool.request("GET", "/") # This should not raise a "Timeout already started" error pool.request("GET", "/") with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: # This should also not raise a "Timeout already started" error pool.request("GET", "/") timeout = Timeout(total=None) with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: pool.request("GET", "/") def test_tunnel(self): # note the actual httplib.py has no tests for this functionality timeout = Timeout(total=None) with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: conn = pool._get_conn() try: conn.set_tunnel(self.host, self.port) conn._tunnel = mock.Mock(return_value=None) pool._make_request(conn, "GET", "/") conn._tunnel.assert_called_once_with() finally: conn.close() # test that it's not called when tunnel is not set timeout = Timeout(total=None) with HTTPConnectionPool(self.host, self.port, timeout=timeout) as pool: conn = pool._get_conn() try: conn._tunnel = mock.Mock(return_value=None) pool._make_request(conn, "GET", "/") assert not conn._tunnel.called finally: conn.close() def test_redirect(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/redirect", fields={"target": "/"}, redirect=False) assert r.status == 303 r = pool.request("GET", "/redirect", fields={"target": "/"}) assert r.status == 200 assert r.data == b"Dummy server!" def test_bad_connect(self): with HTTPConnectionPool("badhost.invalid", self.port) as pool: with pytest.raises(MaxRetryError) as e: pool.request("GET", "/", retries=5) assert type(e.value.reason) == NewConnectionError def test_keepalive(self): with HTTPConnectionPool(self.host, self.port, block=True, maxsize=1) as pool: r = pool.request("GET", "/keepalive?close=0") r = pool.request("GET", "/keepalive?close=0") assert r.status == 200 assert pool.num_connections == 1 assert pool.num_requests == 2 def test_keepalive_close(self): with HTTPConnectionPool( self.host, self.port, block=True, maxsize=1, timeout=2 ) as pool: r = pool.request( "GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"} ) assert pool.num_connections == 1 # The dummyserver will have responded with Connection:close, # and httplib will properly cleanup the socket. # We grab the HTTPConnection object straight from the Queue, # because _get_conn() is where the check & reset occurs # pylint: disable-msg=W0212 conn = pool.pool.get() assert conn.sock is None pool._put_conn(conn) # Now with keep-alive r = pool.request( "GET", "/keepalive?close=0", retries=0, headers={"Connection": "keep-alive"}, ) # The dummyserver responded with Connection:keep-alive, the connection # persists. conn = pool.pool.get() assert conn.sock is not None pool._put_conn(conn) # Another request asking the server to close the connection. This one # should get cleaned up for the next request. r = pool.request( "GET", "/keepalive?close=1", retries=0, headers={"Connection": "close"} ) assert r.status == 200 conn = pool.pool.get() assert conn.sock is None pool._put_conn(conn) # Next request r = pool.request("GET", "/keepalive?close=0") def test_post_with_urlencode(self): with HTTPConnectionPool(self.host, self.port) as pool: data = {"banana": "hammock", "lol": "cat"} r = pool.request("POST", "/echo", fields=data, encode_multipart=False) assert r.data.decode("utf-8") == urlencode(data) def test_post_with_multipart(self): with HTTPConnectionPool(self.host, self.port) as pool: data = {"banana": "hammock", "lol": "cat"} r = pool.request("POST", "/echo", fields=data, encode_multipart=True) body = r.data.split(b"\r\n") encoded_data = encode_multipart_formdata(data)[0] expected_body = encoded_data.split(b"\r\n") # TODO: Get rid of extra parsing stuff when you can specify # a custom boundary to encode_multipart_formdata """ We need to loop the return lines because a timestamp is attached from within encode_multipart_formdata. When the server echos back the data, it has the timestamp from when the data was encoded, which is not equivalent to when we run encode_multipart_formdata on the data again. """ for i, line in enumerate(body): if line.startswith(b"--"): continue assert body[i] == expected_body[i] def test_post_with_multipart__iter__(self): with HTTPConnectionPool(self.host, self.port) as pool: data = {"hello": "world"} r = pool.request( "POST", "/echo", fields=data, preload_content=False, multipart_boundary="boundary", encode_multipart=True, ) chunks = [chunk for chunk in r] assert chunks == [ b"--boundary\r\n", b'Content-Disposition: form-data; name="hello"\r\n', b"\r\n", b"world\r\n", b"--boundary--\r\n", ] def test_check_gzip(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request( "GET", "/encodingrequest", headers={"accept-encoding": "gzip"} ) assert r.headers.get("content-encoding") == "gzip" assert r.data == b"hello, world!" def test_check_deflate(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request( "GET", "/encodingrequest", headers={"accept-encoding": "deflate"} ) assert r.headers.get("content-encoding") == "deflate" assert r.data == b"hello, world!" def test_bad_decode(self): with HTTPConnectionPool(self.host, self.port) as pool: with pytest.raises(DecodeError): pool.request( "GET", "/encodingrequest", headers={"accept-encoding": "garbage-deflate"}, ) with pytest.raises(DecodeError): pool.request( "GET", "/encodingrequest", headers={"accept-encoding": "garbage-gzip"}, ) def test_connection_count(self): with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: pool.request("GET", "/") pool.request("GET", "/") pool.request("GET", "/") assert pool.num_connections == 1 assert pool.num_requests == 3 def test_connection_count_bigpool(self): with HTTPConnectionPool(self.host, self.port, maxsize=16) as http_pool: http_pool.request("GET", "/") http_pool.request("GET", "/") http_pool.request("GET", "/") assert http_pool.num_connections == 1 assert http_pool.num_requests == 3 def test_partial_response(self): with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: req_data = {"lol": "cat"} resp_data = urlencode(req_data).encode("utf-8") r = pool.request("GET", "/echo", fields=req_data, preload_content=False) assert r.read(5) == resp_data[:5] assert r.read() == resp_data[5:] def test_lazy_load_twice(self): # This test is sad and confusing. Need to figure out what's # going on with partial reads and socket reuse. with HTTPConnectionPool( self.host, self.port, block=True, maxsize=1, timeout=2 ) as pool: payload_size = 1024 * 2 first_chunk = 512 boundary = "foo" req_data = {"count": "a" * payload_size} resp_data = encode_multipart_formdata(req_data, boundary=boundary)[0] req2_data = {"count": "b" * payload_size} resp2_data = encode_multipart_formdata(req2_data, boundary=boundary)[0] r1 = pool.request( "POST", "/echo", fields=req_data, multipart_boundary=boundary, preload_content=False, ) assert r1.read(first_chunk) == resp_data[:first_chunk] try: r2 = pool.request( "POST", "/echo", fields=req2_data, multipart_boundary=boundary, preload_content=False, pool_timeout=0.001, ) # This branch should generally bail here, but maybe someday it will # work? Perhaps by some sort of magic. Consider it a TODO. assert r2.read(first_chunk) == resp2_data[:first_chunk] assert r1.read() == resp_data[first_chunk:] assert r2.read() == resp2_data[first_chunk:] assert pool.num_requests == 2 except EmptyPoolError: assert r1.read() == resp_data[first_chunk:] assert pool.num_requests == 1 assert pool.num_connections == 1 def test_for_double_release(self): MAXSIZE = 5 # Check default state with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool: assert pool.num_connections == 0 assert pool.pool.qsize() == MAXSIZE # Make an empty slot for testing pool.pool.get() assert pool.pool.qsize() == MAXSIZE - 1 # Check state after simple request pool.urlopen("GET", "/") assert pool.pool.qsize() == MAXSIZE - 1 # Check state without release pool.urlopen("GET", "/", preload_content=False) assert pool.pool.qsize() == MAXSIZE - 2 pool.urlopen("GET", "/") assert pool.pool.qsize() == MAXSIZE - 2 # Check state after read pool.urlopen("GET", "/").data assert pool.pool.qsize() == MAXSIZE - 2 pool.urlopen("GET", "/") assert pool.pool.qsize() == MAXSIZE - 2 def test_release_conn_parameter(self): MAXSIZE = 5 with HTTPConnectionPool(self.host, self.port, maxsize=MAXSIZE) as pool: assert pool.pool.qsize() == MAXSIZE # Make request without releasing connection pool.request("GET", "/", release_conn=False, preload_content=False) assert pool.pool.qsize() == MAXSIZE - 1 def test_dns_error(self): with HTTPConnectionPool( "thishostdoesnotexist.invalid", self.port, timeout=0.001 ) as pool: with pytest.raises(MaxRetryError): pool.request("GET", "/test", retries=2) def test_percent_encode_invalid_target_chars(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/echo_params?q=\r&k=\n \n") assert r.data == b"[('k', '\\n \\n'), ('q', '\\r')]" def test_source_address(self): for addr, is_ipv6 in VALID_SOURCE_ADDRESSES: if is_ipv6 and not HAS_IPV6_AND_DNS: warnings.warn("No IPv6 support: skipping.", NoIPv6Warning) continue with HTTPConnectionPool( self.host, self.port, source_address=addr, retries=False ) as pool: r = pool.request("GET", "/source_address") assert r.data == b(addr[0]) def test_source_address_error(self): for addr in INVALID_SOURCE_ADDRESSES: with HTTPConnectionPool( self.host, self.port, source_address=addr, retries=False ) as pool: with pytest.raises(NewConnectionError): pool.request("GET", "/source_address?{0}".format(addr)) def test_stream_keepalive(self): x = 2 with HTTPConnectionPool(self.host, self.port) as pool: for _ in range(x): response = pool.request( "GET", "/chunked", headers={"Connection": "keep-alive"}, preload_content=False, retries=False, ) for chunk in response.stream(): assert chunk == b"123" assert pool.num_connections == 1 assert pool.num_requests == x def test_read_chunked_short_circuit(self): with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/chunked", preload_content=False) response.read() with pytest.raises(StopIteration): next(response.read_chunked()) def test_read_chunked_on_closed_response(self): with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/chunked", preload_content=False) response.close() with pytest.raises(StopIteration): next(response.read_chunked()) def test_chunked_gzip(self): with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request( "GET", "/chunked_gzip", preload_content=False, decode_content=True ) assert b"123" * 4 == response.read() def test_cleanup_on_connection_error(self): """ Test that connections are recycled to the pool on connection errors where no http response is received. """ poolsize = 3 with HTTPConnectionPool( self.host, self.port, maxsize=poolsize, block=True ) as http: assert http.pool.qsize() == poolsize # force a connection error by supplying a non-existent # url. We won't get a response for this and so the # conn won't be implicitly returned to the pool. with pytest.raises(MaxRetryError): http.request( "GET", "/redirect", fields={"target": "/"}, release_conn=False, retries=0, ) r = http.request( "GET", "/redirect", fields={"target": "/"}, release_conn=False, retries=1, ) r.release_conn() # the pool should still contain poolsize elements assert http.pool.qsize() == http.pool.maxsize def test_mixed_case_hostname(self): with HTTPConnectionPool("LoCaLhOsT", self.port) as pool: response = pool.request("GET", "http://LoCaLhOsT:%d/" % self.port) assert response.status == 200 class TestRetry(HTTPDummyServerTestCase): def test_max_retry(self): with HTTPConnectionPool(self.host, self.port) as pool: with pytest.raises(MaxRetryError): pool.request("GET", "/redirect", fields={"target": "/"}, retries=0) def test_disabled_retry(self): """ Disabled retries should disable redirect handling. """ with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/redirect", fields={"target": "/"}, retries=False) assert r.status == 303 r = pool.request( "GET", "/redirect", fields={"target": "/"}, retries=Retry(redirect=False), ) assert r.status == 303 with HTTPConnectionPool( "thishostdoesnotexist.invalid", self.port, timeout=0.001 ) as pool: with pytest.raises(NewConnectionError): pool.request("GET", "/test", retries=False) def test_read_retries(self): """ Should retry for status codes in the whitelist """ with HTTPConnectionPool(self.host, self.port) as pool: retry = Retry(read=1, status_forcelist=[418]) resp = pool.request( "GET", "/successful_retry", headers={"test-name": "test_read_retries"}, retries=retry, ) assert resp.status == 200 def test_read_total_retries(self): """ HTTP response w/ status code in the whitelist should be retried """ with HTTPConnectionPool(self.host, self.port) as pool: headers = {"test-name": "test_read_total_retries"} retry = Retry(total=1, status_forcelist=[418]) resp = pool.request( "GET", "/successful_retry", headers=headers, retries=retry ) assert resp.status == 200 def test_retries_wrong_whitelist(self): """HTTP response w/ status code not in whitelist shouldn't be retried""" with HTTPConnectionPool(self.host, self.port) as pool: retry = Retry(total=1, status_forcelist=[202]) resp = pool.request( "GET", "/successful_retry", headers={"test-name": "test_wrong_whitelist"}, retries=retry, ) assert resp.status == 418 def test_default_method_whitelist_retried(self): """ urllib3 should retry methods in the default method whitelist """ with HTTPConnectionPool(self.host, self.port) as pool: retry = Retry(total=1, status_forcelist=[418]) resp = pool.request( "OPTIONS", "/successful_retry", headers={"test-name": "test_default_whitelist"}, retries=retry, ) assert resp.status == 200 def test_retries_wrong_method_list(self): """Method not in our whitelist should not be retried, even if code matches""" with HTTPConnectionPool(self.host, self.port) as pool: headers = {"test-name": "test_wrong_method_whitelist"} retry = Retry(total=1, status_forcelist=[418], method_whitelist=["POST"]) resp = pool.request( "GET", "/successful_retry", headers=headers, retries=retry ) assert resp.status == 418 def test_read_retries_unsuccessful(self): with HTTPConnectionPool(self.host, self.port) as pool: headers = {"test-name": "test_read_retries_unsuccessful"} resp = pool.request("GET", "/successful_retry", headers=headers, retries=1) assert resp.status == 418 def test_retry_reuse_safe(self): """ It should be possible to reuse a Retry object across requests """ with HTTPConnectionPool(self.host, self.port) as pool: headers = {"test-name": "test_retry_safe"} retry = Retry(total=1, status_forcelist=[418]) resp = pool.request( "GET", "/successful_retry", headers=headers, retries=retry ) assert resp.status == 200 with HTTPConnectionPool(self.host, self.port) as pool: resp = pool.request( "GET", "/successful_retry", headers=headers, retries=retry ) assert resp.status == 200 def test_retry_return_in_response(self): with HTTPConnectionPool(self.host, self.port) as pool: headers = {"test-name": "test_retry_return_in_response"} retry = Retry(total=2, status_forcelist=[418]) resp = pool.request( "GET", "/successful_retry", headers=headers, retries=retry ) assert resp.status == 200 assert resp.retries.total == 1 assert resp.retries.history == ( RequestHistory("GET", "/successful_retry", None, 418, None), ) def test_retry_redirect_history(self): with HTTPConnectionPool(self.host, self.port) as pool: resp = pool.request("GET", "/redirect", fields={"target": "/"}) assert resp.status == 200 assert resp.retries.history == ( RequestHistory("GET", "/redirect?target=%2F", None, 303, "/"), ) def test_multi_redirect_history(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request( "GET", "/multi_redirect", fields={"redirect_codes": "303,302,200"}, redirect=False, ) assert r.status == 303 assert r.retries.history == tuple() with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request( "GET", "/multi_redirect", retries=10, fields={"redirect_codes": "303,302,301,307,302,200"}, ) assert r.status == 200 assert r.data == b"Done redirecting" expected = [ (303, "/multi_redirect?redirect_codes=302,301,307,302,200"), (302, "/multi_redirect?redirect_codes=301,307,302,200"), (301, "/multi_redirect?redirect_codes=307,302,200"), (307, "/multi_redirect?redirect_codes=302,200"), (302, "/multi_redirect?redirect_codes=200"), ] actual = [ (history.status, history.redirect_location) for history in r.retries.history ] assert actual == expected class TestRetryAfter(HTTPDummyServerTestCase): def test_retry_after(self): # Request twice in a second to get a 429 response. with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request( "GET", "/retry_after", fields={"status": "429 Too Many Requests"}, retries=False, ) r = pool.request( "GET", "/retry_after", fields={"status": "429 Too Many Requests"}, retries=False, ) assert r.status == 429 r = pool.request( "GET", "/retry_after", fields={"status": "429 Too Many Requests"}, retries=True, ) assert r.status == 200 # Request twice in a second to get a 503 response. r = pool.request( "GET", "/retry_after", fields={"status": "503 Service Unavailable"}, retries=False, ) r = pool.request( "GET", "/retry_after", fields={"status": "503 Service Unavailable"}, retries=False, ) assert r.status == 503 r = pool.request( "GET", "/retry_after", fields={"status": "503 Service Unavailable"}, retries=True, ) assert r.status == 200 # Ignore Retry-After header on status which is not defined in # Retry.RETRY_AFTER_STATUS_CODES. r = pool.request( "GET", "/retry_after", fields={"status": "418 I'm a teapot"}, retries=True, ) assert r.status == 418 def test_redirect_after(self): with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/redirect_after", retries=False) assert r.status == 303 t = time.time() r = pool.request("GET", "/redirect_after") assert r.status == 200 delta = time.time() - t assert delta >= 1 t = time.time() timestamp = t + 2 r = pool.request("GET", "/redirect_after?date=" + str(timestamp)) assert r.status == 200 delta = time.time() - t assert delta >= 1 # Retry-After is past t = time.time() timestamp = t - 1 r = pool.request("GET", "/redirect_after?date=" + str(timestamp)) delta = time.time() - t assert r.status == 200 assert delta < 1 class TestFileBodiesOnRetryOrRedirect(HTTPDummyServerTestCase): def test_retries_put_filehandle(self): """HTTP PUT retry with a file-like object should not timeout""" with HTTPConnectionPool(self.host, self.port, timeout=0.1) as pool: retry = Retry(total=3, status_forcelist=[418]) # httplib reads in 8k chunks; use a larger content length content_length = 65535 data = b"A" * content_length uploaded_file = io.BytesIO(data) headers = { "test-name": "test_retries_put_filehandle", "Content-Length": str(content_length), } resp = pool.urlopen( "PUT", "/successful_retry", headers=headers, retries=retry, body=uploaded_file, assert_same_host=False, redirect=False, ) assert resp.status == 200 def test_redirect_put_file(self): """PUT with file object should work with a redirection response""" with HTTPConnectionPool(self.host, self.port, timeout=0.1) as pool: retry = Retry(total=3, status_forcelist=[418]) # httplib reads in 8k chunks; use a larger content length content_length = 65535 data = b"A" * content_length uploaded_file = io.BytesIO(data) headers = { "test-name": "test_redirect_put_file", "Content-Length": str(content_length), } url = "/redirect?target=/echo&status=307" resp = pool.urlopen( "PUT", url, headers=headers, retries=retry, body=uploaded_file, assert_same_host=False, redirect=True, ) assert resp.status == 200 assert resp.data == data def test_redirect_with_failed_tell(self): """Abort request if failed to get a position from tell()""" class BadTellObject(io.BytesIO): def tell(self): raise IOError body = BadTellObject(b"the data") url = "/redirect?target=/successful_retry" # httplib uses fileno if Content-Length isn't supplied, # which is unsupported by BytesIO. headers = {"Content-Length": "8"} with HTTPConnectionPool(self.host, self.port, timeout=0.1) as pool: with pytest.raises(UnrewindableBodyError) as e: pool.urlopen("PUT", url, headers=headers, body=body) assert "Unable to record file position for" in str(e.value) class TestRetryPoolSize(HTTPDummyServerTestCase): def test_pool_size_retry(self): retries = Retry(total=1, raise_on_status=False, status_forcelist=[404]) with HTTPConnectionPool( self.host, self.port, maxsize=10, retries=retries, block=True ) as pool: pool.urlopen("GET", "/not_found", preload_content=False) assert pool.num_connections == 1 class TestRedirectPoolSize(HTTPDummyServerTestCase): def test_pool_size_redirect(self): retries = Retry( total=1, raise_on_status=False, status_forcelist=[404], redirect=True ) with HTTPConnectionPool( self.host, self.port, maxsize=10, retries=retries, block=True ) as pool: pool.urlopen("GET", "/redirect", preload_content=False) assert pool.num_connections == 1 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_https.py0000644000175000017500000006726100000000000025267 0ustar00sethmlarsonsethmlarson00000000000000import datetime import json import logging import ssl import sys import shutil import warnings import mock import pytest from dummyserver.testcase import HTTPSDummyServerTestCase from dummyserver.server import ( CLIENT_CERT, CLIENT_INTERMEDIATE_PEM, CLIENT_NO_INTERMEDIATE_PEM, CLIENT_INTERMEDIATE_KEY, DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, PASSWORD_CLIENT_KEYFILE, ) from test import ( onlyPy279OrNewer, notSecureTransport, notOpenSSL098, requires_network, requires_ssl_context_keyfile_password, fails_on_travis_gce, requiresTLSv1, requiresTLSv1_1, requiresTLSv1_2, requiresTLSv1_3, TARPIT_HOST, SHORT_TIMEOUT, LONG_TIMEOUT, ) from urllib3 import HTTPSConnectionPool from urllib3.connection import VerifiedHTTPSConnection, RECENT_DATE from urllib3.exceptions import ( SSLError, ConnectTimeoutError, InsecureRequestWarning, SystemTimeWarning, InsecurePlatformWarning, MaxRetryError, ProtocolError, ) from urllib3.packages import six from urllib3.util.timeout import Timeout import urllib3.util as util # Retry failed tests pytestmark = pytest.mark.flaky ResourceWarning = getattr( six.moves.builtins, "ResourceWarning", type("ResourceWarning", (), {}) ) log = logging.getLogger("urllib3.connectionpool") log.setLevel(logging.NOTSET) log.addHandler(logging.StreamHandler(sys.stdout)) TLSv1_CERTS = DEFAULT_CERTS.copy() TLSv1_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLSv1", None) TLSv1_1_CERTS = DEFAULT_CERTS.copy() TLSv1_1_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLSv1_1", None) TLSv1_2_CERTS = DEFAULT_CERTS.copy() TLSv1_2_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLSv1_2", None) TLSv1_3_CERTS = DEFAULT_CERTS.copy() TLSv1_3_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLS", None) class TestHTTPS(HTTPSDummyServerTestCase): tls_protocol_name = None def test_simple(self): with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as https_pool: r = https_pool.request("GET", "/") assert r.status == 200, r.data @fails_on_travis_gce def test_dotted_fqdn(self): with HTTPSConnectionPool( self.host + ".", self.port, ca_certs=DEFAULT_CA ) as pool: r = pool.request("GET", "/") assert r.status == 200, r.data def test_client_intermediate(self, certs_dir): """Check that certificate chains work well with client certs We generate an intermediate CA from the root CA, and issue a client certificate from that intermediate CA. Since the server only knows about the root CA, we need to send it the certificate *and* the intermediate CA, so that it can check the whole chain. """ with HTTPSConnectionPool( self.host, self.port, key_file=str(certs_dir / CLIENT_INTERMEDIATE_KEY), cert_file=str(certs_dir / CLIENT_INTERMEDIATE_PEM), ca_certs=DEFAULT_CA, ) as https_pool: r = https_pool.request("GET", "/certificate") subject = json.loads(r.data.decode("utf-8")) assert subject["organizationalUnitName"].startswith("Testing cert") def test_client_no_intermediate(self, certs_dir): """Check that missing links in certificate chains indeed break The only difference with test_client_intermediate is that we don't send the intermediate CA to the server, only the client cert. """ with HTTPSConnectionPool( self.host, self.port, cert_file=str(certs_dir / CLIENT_NO_INTERMEDIATE_PEM), key_file=str(certs_dir / CLIENT_INTERMEDIATE_KEY), ca_certs=DEFAULT_CA, ) as https_pool: try: https_pool.request("GET", "/certificate", retries=False) except SSLError as e: if not ( "alert unknown ca" in str(e) or "invalid certificate chain" in str(e) or "unknown Cert Authority" in str(e) or # https://github.com/urllib3/urllib3/issues/1422 "connection closed via error" in str(e) or "WSAECONNRESET" in str(e) ): raise except ProtocolError as e: if not ( "An existing connection was forcibly closed by the remote host" in str(e) # Python 3.7.4+ or "WSAECONNRESET" in str(e) # Windows or "EPIPE" in str(e) # macOS or "ECONNRESET" in str(e) # OpenSSL ): raise @requires_ssl_context_keyfile_password def test_client_key_password(self): with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA, key_file=PASSWORD_CLIENT_KEYFILE, cert_file=CLIENT_CERT, key_password="letmein", ) as https_pool: r = https_pool.request("GET", "/certificate") subject = json.loads(r.data.decode("utf-8")) assert subject["organizationalUnitName"].startswith("Testing server cert") @requires_ssl_context_keyfile_password def test_client_encrypted_key_requires_password(self): with HTTPSConnectionPool( self.host, self.port, key_file=PASSWORD_CLIENT_KEYFILE, cert_file=CLIENT_CERT, key_password=None, ) as https_pool: with pytest.raises(MaxRetryError) as e: https_pool.request("GET", "/certificate") assert "password is required" in str(e.value) assert isinstance(e.value.reason, SSLError) def test_verified(self): with HTTPSConnectionPool( self.host, self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: conn = https_pool._new_conn() assert conn.__class__ == VerifiedHTTPSConnection with mock.patch("warnings.warn") as warn: r = https_pool.request("GET", "/") assert r.status == 200 # Modern versions of Python, or systems using PyOpenSSL, don't # emit warnings. if ( sys.version_info >= (2, 7, 9) or util.IS_PYOPENSSL or util.IS_SECURETRANSPORT ): assert not warn.called, warn.call_args_list else: assert warn.called if util.HAS_SNI: call = warn.call_args_list[0] else: call = warn.call_args_list[1] error = call[0][1] assert error == InsecurePlatformWarning def test_verified_with_context(self): ctx = util.ssl_.create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED) ctx.load_verify_locations(cafile=DEFAULT_CA) with HTTPSConnectionPool(self.host, self.port, ssl_context=ctx) as https_pool: conn = https_pool._new_conn() assert conn.__class__ == VerifiedHTTPSConnection with mock.patch("warnings.warn") as warn: r = https_pool.request("GET", "/") assert r.status == 200 # Modern versions of Python, or systems using PyOpenSSL, don't # emit warnings. if ( sys.version_info >= (2, 7, 9) or util.IS_PYOPENSSL or util.IS_SECURETRANSPORT ): assert not warn.called, warn.call_args_list else: assert warn.called if util.HAS_SNI: call = warn.call_args_list[0] else: call = warn.call_args_list[1] error = call[0][1] assert error == InsecurePlatformWarning def test_context_combines_with_ca_certs(self): ctx = util.ssl_.create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED) with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA, ssl_context=ctx ) as https_pool: conn = https_pool._new_conn() assert conn.__class__ == VerifiedHTTPSConnection with mock.patch("warnings.warn") as warn: r = https_pool.request("GET", "/") assert r.status == 200 # Modern versions of Python, or systems using PyOpenSSL, don't # emit warnings. if ( sys.version_info >= (2, 7, 9) or util.IS_PYOPENSSL or util.IS_SECURETRANSPORT ): assert not warn.called, warn.call_args_list else: assert warn.called if util.HAS_SNI: call = warn.call_args_list[0] else: call = warn.call_args_list[1] error = call[0][1] assert error == InsecurePlatformWarning @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories @notOpenSSL098 # OpenSSL 0.9.8 does not support cert directories def test_ca_dir_verified(self, tmpdir): # OpenSSL looks up certificates by the hash for their name, see c_rehash # TODO infer the bytes using `cryptography.x509.Name.public_bytes`. # https://github.com/pyca/cryptography/pull/3236 shutil.copyfile(DEFAULT_CA, str(tmpdir / "b6b9ccf9.0")) with HTTPSConnectionPool( self.host, self.port, cert_reqs="CERT_REQUIRED", ca_cert_dir=str(tmpdir) ) as https_pool: conn = https_pool._new_conn() assert conn.__class__ == VerifiedHTTPSConnection with mock.patch("warnings.warn") as warn: r = https_pool.request("GET", "/") assert r.status == 200 assert not warn.called, warn.call_args_list def test_invalid_common_name(self): with HTTPSConnectionPool( "127.0.0.1", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: with pytest.raises(MaxRetryError) as e: https_pool.request("GET", "/") assert isinstance(e.value.reason, SSLError) assert "doesn't match" in str( e.value.reason ) or "certificate verify failed" in str(e.value.reason) def test_verified_with_bad_ca_certs(self): with HTTPSConnectionPool( self.host, self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA_BAD ) as https_pool: with pytest.raises(MaxRetryError) as e: https_pool.request("GET", "/") assert isinstance(e.value.reason, SSLError) assert "certificate verify failed" in str(e.value.reason), ( "Expected 'certificate verify failed', instead got: %r" % e.value.reason ) def test_verified_without_ca_certs(self): # default is cert_reqs=None which is ssl.CERT_NONE with HTTPSConnectionPool( self.host, self.port, cert_reqs="CERT_REQUIRED" ) as https_pool: with pytest.raises(MaxRetryError) as e: https_pool.request("GET", "/") assert isinstance(e.value.reason, SSLError) # there is a different error message depending on whether or # not pyopenssl is injected assert ( "No root certificates specified" in str(e.value.reason) # PyPy sometimes uses all-caps here or "certificate verify failed" in str(e.value.reason).lower() or "invalid certificate chain" in str(e.value.reason) ), ( "Expected 'No root certificates specified', " "'certificate verify failed', or " "'invalid certificate chain', " "instead got: %r" % e.value.reason ) def test_no_ssl(self): with HTTPSConnectionPool(self.host, self.port) as pool: pool.ConnectionCls = None with pytest.raises(SSLError): pool._new_conn() with pytest.raises(MaxRetryError) as cm: pool.request("GET", "/", retries=0) assert isinstance(cm.value.reason, SSLError) def test_unverified_ssl(self): """ Test that bare HTTPSConnection can connect, make requests """ with HTTPSConnectionPool(self.host, self.port, cert_reqs=ssl.CERT_NONE) as pool: with mock.patch("warnings.warn") as warn: r = pool.request("GET", "/") assert r.status == 200 assert warn.called # Modern versions of Python, or systems using PyOpenSSL, only emit # the unverified warning. Older systems may also emit other # warnings, which we want to ignore here. calls = warn.call_args_list assert InsecureRequestWarning in [x[0][1] for x in calls] def test_ssl_unverified_with_ca_certs(self): with HTTPSConnectionPool( self.host, self.port, cert_reqs="CERT_NONE", ca_certs=DEFAULT_CA_BAD ) as pool: with mock.patch("warnings.warn") as warn: r = pool.request("GET", "/") assert r.status == 200 assert warn.called # Modern versions of Python, or systems using PyOpenSSL, only emit # the unverified warning. Older systems may also emit other # warnings, which we want to ignore here. calls = warn.call_args_list if ( sys.version_info >= (2, 7, 9) or util.IS_PYOPENSSL or util.IS_SECURETRANSPORT ): category = calls[0][0][1] elif util.HAS_SNI: category = calls[1][0][1] else: category = calls[2][0][1] assert category == InsecureRequestWarning def test_assert_hostname_false(self): with HTTPSConnectionPool( "localhost", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_hostname = False https_pool.request("GET", "/") def test_assert_specific_hostname(self): with HTTPSConnectionPool( "localhost", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_hostname = "localhost" https_pool.request("GET", "/") def test_server_hostname(self): with HTTPSConnectionPool( "127.0.0.1", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA, server_hostname="localhost", ) as https_pool: conn = https_pool._new_conn() conn.request("GET", "/") # Assert the wrapping socket is using the passed-through SNI name. # pyopenssl doesn't let you pull the server_hostname back off the # socket, so only add this assertion if the attribute is there (i.e. # the python ssl module). if hasattr(conn.sock, "server_hostname"): assert conn.sock.server_hostname == "localhost" def test_assert_fingerprint_md5(self): with HTTPSConnectionPool( "localhost", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_fingerprint = ( "F2:06:5A:42:10:3F:45:1C:17:FE:E6:07:1E:8A:86:E5" ) https_pool.request("GET", "/") def test_assert_fingerprint_sha1(self): with HTTPSConnectionPool( "localhost", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_fingerprint = ( "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A" ) https_pool.request("GET", "/") def test_assert_fingerprint_sha256(self): with HTTPSConnectionPool( "localhost", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_fingerprint = ( "C5:4D:0B:83:84:89:2E:AE:B4:58:BB:12:" "F7:A6:C4:76:05:03:88:D8:57:65:51:F3:" "1E:60:B0:8B:70:18:64:E6" ) https_pool.request("GET", "/") def test_assert_invalid_fingerprint(self): with HTTPSConnectionPool( "127.0.0.1", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_fingerprint = ( "AA:AA:AA:AA:AA:AAAA:AA:AAAA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA" ) def _test_request(pool): with pytest.raises(MaxRetryError) as cm: pool.request("GET", "/", retries=0) assert isinstance(cm.value.reason, SSLError) _test_request(https_pool) https_pool._get_conn() # Uneven length https_pool.assert_fingerprint = "AA:A" _test_request(https_pool) https_pool._get_conn() # Invalid length https_pool.assert_fingerprint = "AA" _test_request(https_pool) def test_verify_none_and_bad_fingerprint(self): with HTTPSConnectionPool( "127.0.0.1", self.port, cert_reqs="CERT_NONE", ca_certs=DEFAULT_CA_BAD ) as https_pool: https_pool.assert_fingerprint = ( "AA:AA:AA:AA:AA:AAAA:AA:AAAA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA" ) with pytest.raises(MaxRetryError) as cm: https_pool.request("GET", "/", retries=0) assert isinstance(cm.value.reason, SSLError) def test_verify_none_and_good_fingerprint(self): with HTTPSConnectionPool( "127.0.0.1", self.port, cert_reqs="CERT_NONE", ca_certs=DEFAULT_CA_BAD ) as https_pool: https_pool.assert_fingerprint = ( "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A" ) https_pool.request("GET", "/") @notSecureTransport def test_good_fingerprint_and_hostname_mismatch(self): # This test doesn't run with SecureTransport because we don't turn off # hostname validation without turning off all validation, which this # test doesn't do (deliberately). We should revisit this if we make # new decisions. with HTTPSConnectionPool( "127.0.0.1", self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA ) as https_pool: https_pool.assert_fingerprint = ( "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A" ) https_pool.request("GET", "/") @requires_network def test_https_timeout(self): timeout = Timeout(total=None, connect=SHORT_TIMEOUT) with HTTPSConnectionPool( TARPIT_HOST, self.port, timeout=timeout, retries=False, cert_reqs="CERT_REQUIRED", ) as https_pool: with pytest.raises(ConnectTimeoutError): https_pool.request("GET", "/") timeout = Timeout(read=0.01) with HTTPSConnectionPool( self.host, self.port, timeout=timeout, retries=False, cert_reqs="CERT_REQUIRED", ) as https_pool: https_pool.ca_certs = DEFAULT_CA https_pool.assert_fingerprint = ( "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A" ) timeout = Timeout(total=None) with HTTPSConnectionPool( self.host, self.port, timeout=timeout, cert_reqs="CERT_NONE" ) as https_pool: https_pool.request("GET", "/") def test_tunnel(self): """ test the _tunnel behavior """ timeout = Timeout(total=None) with HTTPSConnectionPool( self.host, self.port, timeout=timeout, cert_reqs="CERT_NONE" ) as https_pool: conn = https_pool._new_conn() try: conn.set_tunnel(self.host, self.port) conn._tunnel = mock.Mock() https_pool._make_request(conn, "GET", "/") conn._tunnel.assert_called_once_with() finally: conn.close() @requires_network def test_enhanced_timeout(self): with HTTPSConnectionPool( TARPIT_HOST, self.port, timeout=Timeout(connect=SHORT_TIMEOUT), retries=False, cert_reqs="CERT_REQUIRED", ) as https_pool: conn = https_pool._new_conn() try: with pytest.raises(ConnectTimeoutError): https_pool.request("GET", "/") with pytest.raises(ConnectTimeoutError): https_pool._make_request(conn, "GET", "/") finally: conn.close() with HTTPSConnectionPool( TARPIT_HOST, self.port, timeout=Timeout(connect=LONG_TIMEOUT), retries=False, cert_reqs="CERT_REQUIRED", ) as https_pool: with pytest.raises(ConnectTimeoutError): https_pool.request("GET", "/", timeout=Timeout(connect=SHORT_TIMEOUT)) with HTTPSConnectionPool( TARPIT_HOST, self.port, timeout=Timeout(total=None), retries=False, cert_reqs="CERT_REQUIRED", ) as https_pool: conn = https_pool._new_conn() try: with pytest.raises(ConnectTimeoutError): https_pool.request( "GET", "/", timeout=Timeout(total=None, connect=SHORT_TIMEOUT) ) finally: conn.close() def test_enhanced_ssl_connection(self): fingerprint = "92:81:FE:85:F7:0C:26:60:EC:D6:B3:BF:93:CF:F9:71:CC:07:7D:0A" with HTTPSConnectionPool( self.host, self.port, cert_reqs="CERT_REQUIRED", ca_certs=DEFAULT_CA, assert_fingerprint=fingerprint, ) as https_pool: r = https_pool.request("GET", "/") assert r.status == 200 @onlyPy279OrNewer def test_ssl_correct_system_time(self): with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as https_pool: https_pool.cert_reqs = "CERT_REQUIRED" https_pool.ca_certs = DEFAULT_CA w = self._request_without_resource_warnings("GET", "/") assert [] == w @onlyPy279OrNewer def test_ssl_wrong_system_time(self): with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as https_pool: https_pool.cert_reqs = "CERT_REQUIRED" https_pool.ca_certs = DEFAULT_CA with mock.patch("urllib3.connection.datetime") as mock_date: mock_date.date.today.return_value = datetime.date(1970, 1, 1) w = self._request_without_resource_warnings("GET", "/") assert len(w) == 1 warning = w[0] assert SystemTimeWarning == warning.category assert str(RECENT_DATE) in warning.message.args[0] def _request_without_resource_warnings(self, method, url): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as https_pool: https_pool.request(method, url) return [x for x in w if not isinstance(x.message, ResourceWarning)] def test_set_ssl_version_to_tls_version(self): if self.tls_protocol_name is None: pytest.skip("Skipping base test class") with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as https_pool: https_pool.ssl_version = self.certs["ssl_version"] r = https_pool.request("GET", "/") assert r.status == 200, r.data def test_set_cert_default_cert_required(self): conn = VerifiedHTTPSConnection(self.host, self.port) conn.set_cert() assert conn.cert_reqs == ssl.CERT_REQUIRED def test_tls_protocol_name_of_socket(self): if self.tls_protocol_name is None: pytest.skip("Skipping base test class") with HTTPSConnectionPool( self.host, self.port, ca_certs=DEFAULT_CA ) as https_pool: conn = https_pool._get_conn() try: conn.connect() if not hasattr(conn.sock, "version"): pytest.skip("SSLSocket.version() not available") assert conn.sock.version() == self.tls_protocol_name finally: conn.close() @requiresTLSv1() class TestHTTPS_TLSv1(TestHTTPS): tls_protocol_name = "TLSv1" certs = TLSv1_CERTS @requiresTLSv1_1() class TestHTTPS_TLSv1_1(TestHTTPS): tls_protocol_name = "TLSv1.1" certs = TLSv1_1_CERTS @requiresTLSv1_2() class TestHTTPS_TLSv1_2(TestHTTPS): tls_protocol_name = "TLSv1.2" certs = TLSv1_2_CERTS @requiresTLSv1_3() class TestHTTPS_TLSv1_3(TestHTTPS): tls_protocol_name = "TLSv1.3" certs = TLSv1_3_CERTS class TestHTTPS_NoSAN: def test_warning_for_certs_without_a_san(self, no_san_server): """Ensure that a warning is raised when the cert from the server has no Subject Alternative Name.""" with mock.patch("warnings.warn") as warn: with HTTPSConnectionPool( no_san_server.host, no_san_server.port, cert_reqs="CERT_REQUIRED", ca_certs=no_san_server.ca_certs, ) as https_pool: r = https_pool.request("GET", "/") assert r.status == 200 assert warn.called class TestHTTPS_IPSAN: def test_can_validate_ip_san(self, ip_san_server): """Ensure that urllib3 can validate SANs with IP addresses in them.""" try: import ipaddress # noqa: F401 except ImportError: pytest.skip("Only runs on systems with an ipaddress module") with HTTPSConnectionPool( ip_san_server.host, ip_san_server.port, cert_reqs="CERT_REQUIRED", ca_certs=ip_san_server.ca_certs, ) as https_pool: r = https_pool.request("GET", "/") assert r.status == 200 class TestHTTPS_IPv6Addr: def test_strip_square_brackets_before_validating(self, ipv6_addr_server): """Test that the fix for #760 works.""" with HTTPSConnectionPool( "[::1]", ipv6_addr_server.port, cert_reqs="CERT_REQUIRED", ca_certs=ipv6_addr_server.ca_certs, ) as https_pool: r = https_pool.request("GET", "/") assert r.status == 200 class TestHTTPS_IPV6SAN: def test_can_validate_ipv6_san(self, ipv6_san_server): """Ensure that urllib3 can validate SANs with IPv6 addresses in them.""" try: import ipaddress # noqa: F401 except ImportError: pytest.skip("Only runs on systems with an ipaddress module") with HTTPSConnectionPool( "[::1]", ipv6_san_server.port, cert_reqs="CERT_REQUIRED", ca_certs=ipv6_san_server.ca_certs, ) as https_pool: r = https_pool.request("GET", "/") assert r.status == 200 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_no_ssl.py0000644000175000017500000000172400000000000025412 0ustar00sethmlarsonsethmlarson00000000000000""" Test connections without the builtin ssl module Note: Import urllib3 inside the test functions to get the importblocker to work """ import pytest from ..test_no_ssl import TestWithoutSSL from dummyserver.testcase import HTTPDummyServerTestCase, HTTPSDummyServerTestCase import urllib3 # Retry failed tests pytestmark = pytest.mark.flaky class TestHTTPWithoutSSL(HTTPDummyServerTestCase, TestWithoutSSL): def test_simple(self): with urllib3.HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/") assert r.status == 200, r.data class TestHTTPSWithoutSSL(HTTPSDummyServerTestCase, TestWithoutSSL): def test_simple(self): with urllib3.HTTPSConnectionPool( self.host, self.port, cert_reqs="NONE" ) as pool: try: pool.request("GET", "/") except urllib3.exceptions.SSLError as e: assert "SSL module is not available" in str(e) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_poolmanager.py0000644000175000017500000002736500000000000026432 0ustar00sethmlarsonsethmlarson00000000000000import json import pytest from dummyserver.server import HAS_IPV6 from dummyserver.testcase import HTTPDummyServerTestCase, IPv6HTTPDummyServerTestCase from urllib3.poolmanager import PoolManager from urllib3.connectionpool import port_by_scheme from urllib3.exceptions import MaxRetryError from urllib3.util.retry import Retry from test import LONG_TIMEOUT # Retry failed tests pytestmark = pytest.mark.flaky class TestPoolManager(HTTPDummyServerTestCase): @classmethod def setup_class(cls): super(TestPoolManager, cls).setup_class() cls.base_url = "http://%s:%d" % (cls.host, cls.port) cls.base_url_alt = "http://%s:%d" % (cls.host_alt, cls.port) def test_redirect(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/" % self.base_url}, redirect=False, ) assert r.status == 303 r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/" % self.base_url}, ) assert r.status == 200 assert r.data == b"Dummy server!" def test_redirect_twice(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/redirect" % self.base_url}, redirect=False, ) assert r.status == 303 r = http.request( "GET", "%s/redirect" % self.base_url, fields={ "target": "%s/redirect?target=%s/" % (self.base_url, self.base_url) }, ) assert r.status == 200 assert r.data == b"Dummy server!" def test_redirect_to_relative_url(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "/redirect"}, redirect=False, ) assert r.status == 303 r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "/redirect"} ) assert r.status == 200 assert r.data == b"Dummy server!" def test_cross_host_redirect(self): with PoolManager() as http: cross_host_location = "%s/echo?a=b" % self.base_url_alt with pytest.raises(MaxRetryError): http.request( "GET", "%s/redirect" % self.base_url, fields={"target": cross_host_location}, timeout=LONG_TIMEOUT, retries=0, ) r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/echo?a=b" % self.base_url_alt}, timeout=LONG_TIMEOUT, retries=1, ) assert r._pool.host == self.host_alt def test_too_many_redirects(self): with PoolManager() as http: with pytest.raises(MaxRetryError): http.request( "GET", "%s/redirect" % self.base_url, fields={ "target": "%s/redirect?target=%s/" % (self.base_url, self.base_url) }, retries=1, ) with pytest.raises(MaxRetryError): http.request( "GET", "%s/redirect" % self.base_url, fields={ "target": "%s/redirect?target=%s/" % (self.base_url, self.base_url) }, retries=Retry(total=None, redirect=1), ) def test_redirect_cross_host_remove_headers(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/headers" % self.base_url_alt}, headers={"Authorization": "foo"}, ) assert r.status == 200 data = json.loads(r.data.decode("utf-8")) assert "Authorization" not in data r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/headers" % self.base_url_alt}, headers={"authorization": "foo"}, ) assert r.status == 200 data = json.loads(r.data.decode("utf-8")) assert "authorization" not in data assert "Authorization" not in data def test_redirect_cross_host_no_remove_headers(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/headers" % self.base_url_alt}, headers={"Authorization": "foo"}, retries=Retry(remove_headers_on_redirect=[]), ) assert r.status == 200 data = json.loads(r.data.decode("utf-8")) assert data["Authorization"] == "foo" def test_redirect_cross_host_set_removed_headers(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/headers" % self.base_url_alt}, headers={"X-API-Secret": "foo", "Authorization": "bar"}, retries=Retry(remove_headers_on_redirect=["X-API-Secret"]), ) assert r.status == 200 data = json.loads(r.data.decode("utf-8")) assert "X-API-Secret" not in data assert data["Authorization"] == "bar" r = http.request( "GET", "%s/redirect" % self.base_url, fields={"target": "%s/headers" % self.base_url_alt}, headers={"x-api-secret": "foo", "authorization": "bar"}, retries=Retry(remove_headers_on_redirect=["X-API-Secret"]), ) assert r.status == 200 data = json.loads(r.data.decode("utf-8")) assert "x-api-secret" not in data assert "X-API-Secret" not in data assert data["Authorization"] == "bar" def test_raise_on_redirect(self): with PoolManager() as http: r = http.request( "GET", "%s/redirect" % self.base_url, fields={ "target": "%s/redirect?target=%s/" % (self.base_url, self.base_url) }, retries=Retry(total=None, redirect=1, raise_on_redirect=False), ) assert r.status == 303 def test_raise_on_status(self): with PoolManager() as http: with pytest.raises(MaxRetryError): # the default is to raise r = http.request( "GET", "%s/status" % self.base_url, fields={"status": "500 Internal Server Error"}, retries=Retry(total=1, status_forcelist=range(500, 600)), ) with pytest.raises(MaxRetryError): # raise explicitly r = http.request( "GET", "%s/status" % self.base_url, fields={"status": "500 Internal Server Error"}, retries=Retry( total=1, status_forcelist=range(500, 600), raise_on_status=True ), ) # don't raise r = http.request( "GET", "%s/status" % self.base_url, fields={"status": "500 Internal Server Error"}, retries=Retry( total=1, status_forcelist=range(500, 600), raise_on_status=False ), ) assert r.status == 500 def test_missing_port(self): # Can a URL that lacks an explicit port like ':80' succeed, or # will all such URLs fail with an error? with PoolManager() as http: # By globally adjusting `port_by_scheme` we pretend for a moment # that HTTP's default port is not 80, but is the port at which # our test server happens to be listening. port_by_scheme["http"] = self.port try: r = http.request("GET", "http://%s/" % self.host, retries=0) finally: port_by_scheme["http"] = 80 assert r.status == 200 assert r.data == b"Dummy server!" def test_headers(self): with PoolManager(headers={"Foo": "bar"}) as http: r = http.request("GET", "%s/headers" % self.base_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" r = http.request("POST", "%s/headers" % self.base_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" r = http.request_encode_url("GET", "%s/headers" % self.base_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" r = http.request_encode_body("POST", "%s/headers" % self.base_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" r = http.request_encode_url( "GET", "%s/headers" % self.base_url, headers={"Baz": "quux"} ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") is None assert returned_headers.get("Baz") == "quux" r = http.request_encode_body( "GET", "%s/headers" % self.base_url, headers={"Baz": "quux"} ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") is None assert returned_headers.get("Baz") == "quux" def test_http_with_ssl_keywords(self): with PoolManager(ca_certs="REQUIRED") as http: r = http.request("GET", "http://%s:%s/" % (self.host, self.port)) assert r.status == 200 def test_http_with_ca_cert_dir(self): with PoolManager(ca_certs="REQUIRED", ca_cert_dir="/nosuchdir") as http: r = http.request("GET", "http://%s:%s/" % (self.host, self.port)) assert r.status == 200 @pytest.mark.parametrize( ["target", "expected_target"], [ ("/echo_uri?q=1#fragment", b"/echo_uri?q=1"), ("/echo_uri?#", b"/echo_uri?"), ("/echo_uri#?", b"/echo_uri"), ("/echo_uri#?#", b"/echo_uri"), ("/echo_uri??#", b"/echo_uri??"), ("/echo_uri?%3f#", b"/echo_uri?%3F"), ("/echo_uri?%3F#", b"/echo_uri?%3F"), ("/echo_uri?[]", b"/echo_uri?%5B%5D"), ], ) def test_encode_http_target(self, target, expected_target): with PoolManager() as http: url = "http://%s:%d%s" % (self.host, self.port, target) r = http.request("GET", url) assert r.data == expected_target @pytest.mark.skipif(not HAS_IPV6, reason="IPv6 is not supported on this system") class TestIPv6PoolManager(IPv6HTTPDummyServerTestCase): @classmethod def setup_class(cls): super(TestIPv6PoolManager, cls).setup_class() cls.base_url = "http://[%s]:%d" % (cls.host, cls.port) def test_ipv6(self): with PoolManager() as http: http.request("GET", self.base_url) ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_proxy_poolmanager.py0000644000175000017500000003446300000000000027670 0ustar00sethmlarsonsethmlarson00000000000000import json import socket import pytest from dummyserver.testcase import HTTPDummyProxyTestCase, IPv6HTTPDummyProxyTestCase from dummyserver.server import ( DEFAULT_CA, DEFAULT_CA_BAD, HAS_IPV6, get_unreachable_address, ) from .. import TARPIT_HOST, requires_network from urllib3._collections import HTTPHeaderDict from urllib3.poolmanager import proxy_from_url, ProxyManager from urllib3.exceptions import MaxRetryError, SSLError, ProxyError, ConnectTimeoutError from urllib3.connectionpool import connection_from_url, VerifiedHTTPSConnection from test import SHORT_TIMEOUT, LONG_TIMEOUT # Retry failed tests pytestmark = pytest.mark.flaky class TestHTTPProxyManager(HTTPDummyProxyTestCase): @classmethod def setup_class(cls): super(TestHTTPProxyManager, cls).setup_class() cls.http_url = "http://%s:%d" % (cls.http_host, cls.http_port) cls.http_url_alt = "http://%s:%d" % (cls.http_host_alt, cls.http_port) cls.https_url = "https://%s:%d" % (cls.https_host, cls.https_port) cls.https_url_alt = "https://%s:%d" % (cls.https_host_alt, cls.https_port) cls.proxy_url = "http://%s:%d" % (cls.proxy_host, cls.proxy_port) def test_basic_proxy(self): with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: r = http.request("GET", "%s/" % self.http_url) assert r.status == 200 r = http.request("GET", "%s/" % self.https_url) assert r.status == 200 def test_nagle_proxy(self): """ Test that proxy connections do not have TCP_NODELAY turned on """ with ProxyManager(self.proxy_url) as http: hc2 = http.connection_from_host(self.http_host, self.http_port) conn = hc2._get_conn() try: hc2._make_request(conn, "GET", "/") tcp_nodelay_setting = conn.sock.getsockopt( socket.IPPROTO_TCP, socket.TCP_NODELAY ) assert tcp_nodelay_setting == 0, ( "Expected TCP_NODELAY for proxies to be set " "to zero, instead was %s" % tcp_nodelay_setting ) finally: conn.close() def test_proxy_conn_fail(self): host, port = get_unreachable_address() with proxy_from_url( "http://%s:%s/" % (host, port), retries=1, timeout=LONG_TIMEOUT ) as http: with pytest.raises(MaxRetryError): http.request("GET", "%s/" % self.https_url) with pytest.raises(MaxRetryError): http.request("GET", "%s/" % self.http_url) with pytest.raises(MaxRetryError) as e: http.request("GET", "%s/" % self.http_url) assert type(e.value.reason) == ProxyError def test_oldapi(self): with ProxyManager( connection_from_url(self.proxy_url), ca_certs=DEFAULT_CA ) as http: r = http.request("GET", "%s/" % self.http_url) assert r.status == 200 r = http.request("GET", "%s/" % self.https_url) assert r.status == 200 def test_proxy_verified(self): with proxy_from_url( self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA_BAD ) as http: https_pool = http._new_pool("https", self.https_host, self.https_port) with pytest.raises(MaxRetryError) as e: https_pool.request("GET", "/", retries=0) assert isinstance(e.value.reason, SSLError) assert "certificate verify failed" in str(e.value.reason), ( "Expected 'certificate verify failed', instead got: %r" % e.value.reason ) http = proxy_from_url( self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA ) https_pool = http._new_pool("https", self.https_host, self.https_port) conn = https_pool._new_conn() assert conn.__class__ == VerifiedHTTPSConnection https_pool.request("GET", "/") # Should succeed without exceptions. http = proxy_from_url( self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA ) https_fail_pool = http._new_pool("https", "127.0.0.1", self.https_port) with pytest.raises(MaxRetryError) as e: https_fail_pool.request("GET", "/", retries=0) assert isinstance(e.value.reason, SSLError) assert "doesn't match" in str(e.value.reason) def test_redirect(self): with proxy_from_url(self.proxy_url) as http: r = http.request( "GET", "%s/redirect" % self.http_url, fields={"target": "%s/" % self.http_url}, redirect=False, ) assert r.status == 303 r = http.request( "GET", "%s/redirect" % self.http_url, fields={"target": "%s/" % self.http_url}, ) assert r.status == 200 assert r.data == b"Dummy server!" def test_cross_host_redirect(self): with proxy_from_url(self.proxy_url) as http: cross_host_location = "%s/echo?a=b" % self.http_url_alt with pytest.raises(MaxRetryError): http.request( "GET", "%s/redirect" % self.http_url, fields={"target": cross_host_location}, retries=0, ) r = http.request( "GET", "%s/redirect" % self.http_url, fields={"target": "%s/echo?a=b" % self.http_url_alt}, retries=1, ) assert r._pool.host != self.http_host_alt def test_cross_protocol_redirect(self): with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: cross_protocol_location = "%s/echo?a=b" % self.https_url with pytest.raises(MaxRetryError): http.request( "GET", "%s/redirect" % self.http_url, fields={"target": cross_protocol_location}, retries=0, ) r = http.request( "GET", "%s/redirect" % self.http_url, fields={"target": "%s/echo?a=b" % self.https_url}, retries=1, ) assert r._pool.host == self.https_host def test_headers(self): with proxy_from_url( self.proxy_url, headers={"Foo": "bar"}, proxy_headers={"Hickory": "dickory"}, ca_certs=DEFAULT_CA, ) as http: r = http.request_encode_url("GET", "%s/headers" % self.http_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" assert returned_headers.get("Hickory") == "dickory" assert returned_headers.get("Host") == "%s:%s" % ( self.http_host, self.http_port, ) r = http.request_encode_url("GET", "%s/headers" % self.http_url_alt) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" assert returned_headers.get("Hickory") == "dickory" assert returned_headers.get("Host") == "%s:%s" % ( self.http_host_alt, self.http_port, ) r = http.request_encode_url("GET", "%s/headers" % self.https_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" assert returned_headers.get("Hickory") is None assert returned_headers.get("Host") == "%s:%s" % ( self.https_host, self.https_port, ) r = http.request_encode_body("POST", "%s/headers" % self.http_url) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" assert returned_headers.get("Hickory") == "dickory" assert returned_headers.get("Host") == "%s:%s" % ( self.http_host, self.http_port, ) r = http.request_encode_url( "GET", "%s/headers" % self.http_url, headers={"Baz": "quux"} ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") is None assert returned_headers.get("Baz") == "quux" assert returned_headers.get("Hickory") == "dickory" assert returned_headers.get("Host") == "%s:%s" % ( self.http_host, self.http_port, ) r = http.request_encode_url( "GET", "%s/headers" % self.https_url, headers={"Baz": "quux"} ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") is None assert returned_headers.get("Baz") == "quux" assert returned_headers.get("Hickory") is None assert returned_headers.get("Host") == "%s:%s" % ( self.https_host, self.https_port, ) r = http.request_encode_body( "GET", "%s/headers" % self.http_url, headers={"Baz": "quux"} ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") is None assert returned_headers.get("Baz") == "quux" assert returned_headers.get("Hickory") == "dickory" assert returned_headers.get("Host") == "%s:%s" % ( self.http_host, self.http_port, ) r = http.request_encode_body( "GET", "%s/headers" % self.https_url, headers={"Baz": "quux"} ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") is None assert returned_headers.get("Baz") == "quux" assert returned_headers.get("Hickory") is None assert returned_headers.get("Host") == "%s:%s" % ( self.https_host, self.https_port, ) def test_headerdict(self): default_headers = HTTPHeaderDict(a="b") proxy_headers = HTTPHeaderDict() proxy_headers.add("foo", "bar") with proxy_from_url( self.proxy_url, headers=default_headers, proxy_headers=proxy_headers ) as http: request_headers = HTTPHeaderDict(baz="quux") r = http.request( "GET", "%s/headers" % self.http_url, headers=request_headers ) returned_headers = json.loads(r.data.decode()) assert returned_headers.get("Foo") == "bar" assert returned_headers.get("Baz") == "quux" def test_proxy_pooling(self): with proxy_from_url(self.proxy_url, cert_reqs="NONE") as http: for x in range(2): http.urlopen("GET", self.http_url) assert len(http.pools) == 1 for x in range(2): http.urlopen("GET", self.http_url_alt) assert len(http.pools) == 1 for x in range(2): http.urlopen("GET", self.https_url) assert len(http.pools) == 2 for x in range(2): http.urlopen("GET", self.https_url_alt) assert len(http.pools) == 3 def test_proxy_pooling_ext(self): with proxy_from_url(self.proxy_url) as http: hc1 = http.connection_from_url(self.http_url) hc2 = http.connection_from_host(self.http_host, self.http_port) hc3 = http.connection_from_url(self.http_url_alt) hc4 = http.connection_from_host(self.http_host_alt, self.http_port) assert hc1 == hc2 assert hc2 == hc3 assert hc3 == hc4 sc1 = http.connection_from_url(self.https_url) sc2 = http.connection_from_host( self.https_host, self.https_port, scheme="https" ) sc3 = http.connection_from_url(self.https_url_alt) sc4 = http.connection_from_host( self.https_host_alt, self.https_port, scheme="https" ) assert sc1 == sc2 assert sc2 != sc3 assert sc3 == sc4 @pytest.mark.timeout(0.5) @requires_network def test_https_proxy_timeout(self): with proxy_from_url("https://{host}".format(host=TARPIT_HOST)) as https: with pytest.raises(MaxRetryError) as e: https.request("GET", self.http_url, timeout=SHORT_TIMEOUT) assert type(e.value.reason) == ConnectTimeoutError @pytest.mark.timeout(0.5) @requires_network def test_https_proxy_pool_timeout(self): with proxy_from_url( "https://{host}".format(host=TARPIT_HOST), timeout=SHORT_TIMEOUT ) as https: with pytest.raises(MaxRetryError) as e: https.request("GET", self.http_url) assert type(e.value.reason) == ConnectTimeoutError def test_scheme_host_case_insensitive(self): """Assert that upper-case schemes and hosts are normalized.""" with proxy_from_url(self.proxy_url.upper(), ca_certs=DEFAULT_CA) as http: r = http.request("GET", "%s/" % self.http_url.upper()) assert r.status == 200 r = http.request("GET", "%s/" % self.https_url.upper()) assert r.status == 200 @pytest.mark.skipif(not HAS_IPV6, reason="Only runs on IPv6 systems") class TestIPv6HTTPProxyManager(IPv6HTTPDummyProxyTestCase): @classmethod def setup_class(cls): HTTPDummyProxyTestCase.setup_class() cls.http_url = "http://%s:%d" % (cls.http_host, cls.http_port) cls.http_url_alt = "http://%s:%d" % (cls.http_host_alt, cls.http_port) cls.https_url = "https://%s:%d" % (cls.https_host, cls.https_port) cls.https_url_alt = "https://%s:%d" % (cls.https_host_alt, cls.https_port) cls.proxy_url = "http://[%s]:%d" % (cls.proxy_host, cls.proxy_port) def test_basic_ipv6_proxy(self): with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: r = http.request("GET", "%s/" % self.http_url) assert r.status == 200 r = http.request("GET", "%s/" % self.https_url) assert r.status == 200 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1579639008.0 urllib3-1.25.8/test/with_dummyserver/test_socketlevel.py0000644000175000017500000016313700000000000026444 0ustar00sethmlarsonsethmlarson00000000000000# TODO: Break this module up into pieces. Maybe group by functionality tested # rather than the socket level-ness of it. from urllib3 import HTTPConnectionPool, HTTPSConnectionPool from urllib3.poolmanager import proxy_from_url from urllib3.exceptions import ( MaxRetryError, ProxyError, ReadTimeoutError, SSLError, ProtocolError, ) from urllib3.response import httplib from urllib3.util.ssl_ import HAS_SNI from urllib3.util import ssl_ from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND_KEY, PASSWORD_KEYFILE, get_unreachable_address, ) from .. import onlyPy3, LogRecorder try: from mimetools import Message as MimeToolMessage except ImportError: class MimeToolMessage(object): pass from collections import OrderedDict from threading import Event import select import socket import ssl import mock import pytest from test import ( fails_on_travis_gce, requires_ssl_context_keyfile_password, SHORT_TIMEOUT, LONG_TIMEOUT, notPyPy2, ) # Retry failed tests pytestmark = pytest.mark.flaky class TestCookies(SocketDummyServerTestCase): def test_multi_setcookie(self): def multicookie_response_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" b"Set-Cookie: foo=1\r\n" b"Set-Cookie: bar=1\r\n" b"\r\n" ) sock.close() self._start_server(multicookie_response_handler) with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/", retries=0) assert r.headers == {"set-cookie": "foo=1, bar=1"} assert r.headers.getlist("set-cookie") == ["foo=1", "bar=1"] class TestSNI(SocketDummyServerTestCase): @pytest.mark.skipif(not HAS_SNI, reason="SNI-support not available") def test_hostname_in_first_request_packet(self): done_receiving = Event() self.buf = b"" def socket_handler(listener): sock = listener.accept()[0] self.buf = sock.recv(65536) # We only accept one packet done_receiving.set() # let the test know it can proceed sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: try: pool.request("GET", "/", retries=0) except MaxRetryError: # We are violating the protocol pass done_receiving.wait() assert ( self.host.encode("ascii") in self.buf ), "missing hostname in SSL handshake" class TestClientCerts(SocketDummyServerTestCase): """ Tests for client certificate support. """ def _wrap_in_ssl(self, sock): """ Given a single socket, wraps it in TLS. """ return ssl.wrap_socket( sock, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=DEFAULT_CA, certfile=DEFAULT_CERTS["certfile"], keyfile=DEFAULT_CERTS["keyfile"], server_side=True, ) def test_client_certs_two_files(self): """ Having a client cert in a separate file to its associated key works properly. """ done_receiving = Event() client_certs = [] def socket_handler(listener): sock = listener.accept()[0] sock = self._wrap_in_ssl(sock) client_certs.append(sock.getpeercert()) data = b"" while not data.endswith(b"\r\n\r\n"): data += sock.recv(8192) sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: testsocket\r\n" b"Connection: close\r\n" b"Content-Length: 6\r\n" b"\r\n" b"Valid!" ) done_receiving.wait(5) sock.close() self._start_server(socket_handler) with HTTPSConnectionPool( self.host, self.port, cert_file=DEFAULT_CERTS["certfile"], key_file=DEFAULT_CERTS["keyfile"], cert_reqs="REQUIRED", ca_certs=DEFAULT_CA, ) as pool: pool.request("GET", "/", retries=0) done_receiving.set() assert len(client_certs) == 1 def test_client_certs_one_file(self): """ Having a client cert and its associated private key in just one file works properly. """ done_receiving = Event() client_certs = [] def socket_handler(listener): sock = listener.accept()[0] sock = self._wrap_in_ssl(sock) client_certs.append(sock.getpeercert()) data = b"" while not data.endswith(b"\r\n\r\n"): data += sock.recv(8192) sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: testsocket\r\n" b"Connection: close\r\n" b"Content-Length: 6\r\n" b"\r\n" b"Valid!" ) done_receiving.wait(5) sock.close() self._start_server(socket_handler) with HTTPSConnectionPool( self.host, self.port, cert_file=COMBINED_CERT_AND_KEY, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA, ) as pool: pool.request("GET", "/", retries=0) done_receiving.set() assert len(client_certs) == 1 def test_missing_client_certs_raises_error(self): """ Having client certs not be present causes an error. """ done_receiving = Event() def socket_handler(listener): sock = listener.accept()[0] try: self._wrap_in_ssl(sock) except ssl.SSLError: pass done_receiving.wait(5) sock.close() self._start_server(socket_handler) with HTTPSConnectionPool( self.host, self.port, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA ) as pool: with pytest.raises(MaxRetryError): pool.request("GET", "/", retries=0) done_receiving.set() done_receiving.set() @requires_ssl_context_keyfile_password def test_client_cert_with_string_password(self): self.run_client_cert_with_password_test(u"letmein") @requires_ssl_context_keyfile_password def test_client_cert_with_bytes_password(self): self.run_client_cert_with_password_test(b"letmein") def run_client_cert_with_password_test(self, password): """ Tests client certificate password functionality """ done_receiving = Event() client_certs = [] def socket_handler(listener): sock = listener.accept()[0] sock = self._wrap_in_ssl(sock) client_certs.append(sock.getpeercert()) data = b"" while not data.endswith(b"\r\n\r\n"): data += sock.recv(8192) sock.sendall( b"HTTP/1.1 200 OK\r\n" b"Server: testsocket\r\n" b"Connection: close\r\n" b"Content-Length: 6\r\n" b"\r\n" b"Valid!" ) done_receiving.wait(5) sock.close() self._start_server(socket_handler) ssl_context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23) ssl_context.load_cert_chain( certfile=DEFAULT_CERTS["certfile"], keyfile=PASSWORD_KEYFILE, password=password, ) with HTTPSConnectionPool( self.host, self.port, ssl_context=ssl_context, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA, ) as pool: pool.request("GET", "/", retries=0) done_receiving.set() assert len(client_certs) == 1 @requires_ssl_context_keyfile_password def test_load_keyfile_with_invalid_password(self): context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23) # Different error is raised depending on context. if ssl_.IS_PYOPENSSL: from OpenSSL.SSL import Error expected_error = Error else: expected_error = ssl.SSLError with pytest.raises(expected_error): context.load_cert_chain( certfile=DEFAULT_CERTS["certfile"], keyfile=PASSWORD_KEYFILE, password=b"letmei", ) class TestSocketClosing(SocketDummyServerTestCase): def test_recovery_when_server_closes_connection(self): # Does the pool work seamlessly if an open connection in the # connection pool gets hung up on by the server, then reaches # the front of the queue again? done_closing = Event() def socket_handler(listener): for i in 0, 1: sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) body = "Response %d" % i sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), body) ).encode("utf-8") ) sock.close() # simulate a server timing out, closing socket done_closing.set() # let the test know it can proceed self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/", retries=0) assert response.status == 200 assert response.data == b"Response 0" done_closing.wait() # wait until the socket in our pool gets closed response = pool.request("GET", "/", retries=0) assert response.status == 200 assert response.data == b"Response 1" def test_connection_refused(self): # Does the pool retry if there is no listener on the port? host, port = get_unreachable_address() with HTTPConnectionPool(host, port, maxsize=3, block=True) as http: with pytest.raises(MaxRetryError): http.request("GET", "/", retries=0, release_conn=False) assert http.pool.qsize() == http.pool.maxsize def test_connection_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] while not sock.recv(65536).endswith(b"\r\n\r\n"): pass timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool( self.host, self.port, timeout=SHORT_TIMEOUT, retries=False, maxsize=3, block=True, ) as http: try: with pytest.raises(ReadTimeoutError): http.request("GET", "/", release_conn=False) finally: timed_out.set() assert http.pool.qsize() == http.pool.maxsize def test_read_timeout_dont_retry_method_not_in_whitelist(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] sock.recv(65536) timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool( self.host, self.port, timeout=SHORT_TIMEOUT, retries=True ) as pool: try: with pytest.raises(ReadTimeoutError): pool.request("POST", "/") finally: timed_out.set() def test_https_connection_read_timeout(self): """ Handshake timeouts should fail with a Timeout""" timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] while not sock.recv(65536): pass timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPSConnectionPool( self.host, self.port, timeout=SHORT_TIMEOUT, retries=False ) as pool: try: with pytest.raises(ReadTimeoutError): pool.request("GET", "/") finally: timed_out.set() def test_timeout_errors_cause_retries(self): def socket_handler(listener): sock_timeout = listener.accept()[0] # Wait for a second request before closing the first socket. sock = listener.accept()[0] sock_timeout.close() # Second request. buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) # Now respond immediately. body = "Response 2" sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), body) ).encode("utf-8") ) sock.close() # In situations where the main thread throws an exception, the server # thread can hang on an accept() call. This ensures everything times # out within 1 second. This should be long enough for any socket # operations in the test suite to complete default_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(1) try: self._start_server(socket_handler) t = Timeout(connect=SHORT_TIMEOUT, read=LONG_TIMEOUT) with HTTPConnectionPool(self.host, self.port, timeout=t) as pool: response = pool.request("GET", "/", retries=1) assert response.status == 200 assert response.data == b"Response 2" finally: socket.setdefaulttimeout(default_timeout) def test_delayed_body_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" body = "Hi" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" % len(body) ).encode("utf-8") ) timed_out.wait() sock.send(body.encode("utf-8")) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=Timeout(connect=1, read=LONG_TIMEOUT), ) try: with pytest.raises(ReadTimeoutError): response.read() finally: timed_out.set() def test_delayed_body_read_timeout_with_preload(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" body = "Hi" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" % len(body) ).encode("utf-8") ) timed_out.wait(5) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: try: with pytest.raises(ReadTimeoutError): timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) pool.urlopen("GET", "/", retries=False, timeout=timeout) finally: timed_out.set() def test_incomplete_response(self): body = "Response" partial_body = body[:2] def socket_handler(listener): sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) # Send partial response and close socket. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), partial_body) ).encode("utf-8") ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/", retries=0, preload_content=False) with pytest.raises(ProtocolError): response.read() def test_retry_weird_http_version(self): """ Retry class should handle httplib.BadStatusLine errors properly """ def socket_handler(listener): sock = listener.accept()[0] # First request. # Pause before responding so the first request times out. buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) # send unknown http protocol body = "bad http 0.5 response" sock.send( ( "HTTP/0.5 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), body) ).encode("utf-8") ) sock.close() # Second request. sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) # Now respond immediately. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "foo" % (len("foo")) ).encode("utf-8") ) sock.close() # Close the socket. self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: retry = Retry(read=1) response = pool.request("GET", "/", retries=retry) assert response.status == 200 assert response.data == b"foo" def test_connection_cleanup_on_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" body = "Hi" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" % len(body) ).encode("utf-8") ) timed_out.wait() sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: poolsize = pool.pool.qsize() timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=timeout ) try: with pytest.raises(ReadTimeoutError): response.read() assert poolsize == pool.pool.qsize() finally: timed_out.set() def test_connection_cleanup_on_protocol_error_during_read(self): body = "Response" partial_body = body[:2] def socket_handler(listener): sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) # Send partial response and close socket. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(body), partial_body) ).encode("utf-8") ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: poolsize = pool.pool.qsize() response = pool.request("GET", "/", retries=0, preload_content=False) with pytest.raises(ProtocolError): response.read() assert poolsize == pool.pool.qsize() def test_connection_closed_on_read_timeout_preload_false(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65535) # Send partial chunked response and then hang. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "8\r\n" "12345678\r\n" ).encode("utf-8") ) timed_out.wait(5) # Expect a new request, but keep hold of the old socket to avoid # leaking it. Because we don't want to hang this thread, we # actually use select.select to confirm that a new request is # coming in: this lets us time the thread out. rlist, _, _ = select.select([listener], [], [], 1) assert rlist new_sock = listener.accept()[0] # Consume request buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = new_sock.recv(65535) # Send complete chunked response. new_sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "8\r\n" "12345678\r\n" "0\r\n\r\n" ).encode("utf-8") ) new_sock.close() sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: # First request should fail. response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT ) try: with pytest.raises(ReadTimeoutError): response.read() finally: timed_out.set() # Second should succeed. response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT ) assert len(response.read()) == 8 def test_closing_response_actually_closes_connection(self): done_closing = Event() complete = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf = sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 0\r\n" "\r\n" ).encode("utf-8") ) # Wait for the socket to close. done_closing.wait(timeout=LONG_TIMEOUT) # Look for the empty string to show that the connection got closed. # Don't get stuck in a timeout. sock.settimeout(LONG_TIMEOUT) new_data = sock.recv(65536) assert not new_data sock.close() complete.set() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: response = pool.request("GET", "/", retries=0, preload_content=False) assert response.status == 200 response.close() done_closing.set() # wait until the socket in our pool gets closed successful = complete.wait(timeout=LONG_TIMEOUT) assert successful, "Timed out waiting for connection close" def test_release_conn_param_is_respected_after_timeout_retry(self): """For successful ```urlopen(release_conn=False)```, the connection isn't released, even after a retry. This test allows a retry: one request fails, the next request succeeds. This is a regression test for issue #651 [1], where the connection would be released if the initial request failed, even if a retry succeeded. [1] """ def socket_handler(listener): sock = listener.accept()[0] consume_socket(sock) # Close the connection, without sending any response (not even the # HTTP status line). This will trigger a `Timeout` on the client, # inside `urlopen()`. sock.close() # Expect a new request. Because we don't want to hang this thread, # we actually use select.select to confirm that a new request is # coming in: this lets us time the thread out. rlist, _, _ = select.select([listener], [], [], 5) assert rlist sock = listener.accept()[0] consume_socket(sock) # Send complete chunked response. sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "8\r\n" "12345678\r\n" "0\r\n\r\n" ).encode("utf-8") ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: # First request should fail, but the timeout and `retries=1` should # save it. response = pool.urlopen( "GET", "/", retries=1, release_conn=False, preload_content=False, timeout=Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT), ) # The connection should still be on the response object, and none # should be in the pool. We opened two though. assert pool.num_connections == 2 assert pool.pool.qsize() == 0 assert response.connection is not None # Consume the data. This should put the connection back. response.read() assert pool.pool.qsize() == 1 assert response.connection is None class TestProxyManager(SocketDummyServerTestCase): def test_simple(self): def echo_socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(buf), buf.decode("utf-8")) ).encode("utf-8") ) sock.close() self._start_server(echo_socket_handler) base_url = "http://%s:%d" % (self.host, self.port) with proxy_from_url(base_url) as proxy: r = proxy.request("GET", "http://google.com/") assert r.status == 200 # FIXME: The order of the headers is not predictable right now. We # should fix that someday (maybe when we migrate to # OrderedDict/MultiDict). assert sorted(r.data.split(b"\r\n")) == sorted( [ b"GET http://google.com/ HTTP/1.1", b"Host: google.com", b"Accept-Encoding: identity", b"Accept: */*", b"", b"", ] ) def test_headers(self): def echo_socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(buf), buf.decode("utf-8")) ).encode("utf-8") ) sock.close() self._start_server(echo_socket_handler) base_url = "http://%s:%d" % (self.host, self.port) # Define some proxy headers. proxy_headers = HTTPHeaderDict({"For The Proxy": "YEAH!"}) with proxy_from_url(base_url, proxy_headers=proxy_headers) as proxy: conn = proxy.connection_from_url("http://www.google.com/") r = conn.urlopen("GET", "http://www.google.com/", assert_same_host=False) assert r.status == 200 # FIXME: The order of the headers is not predictable right now. We # should fix that someday (maybe when we migrate to # OrderedDict/MultiDict). assert b"For The Proxy: YEAH!\r\n" in r.data def test_retries(self): close_event = Event() def echo_socket_handler(listener): sock = listener.accept()[0] # First request, which should fail sock.close() # Second request sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" "\r\n" "%s" % (len(buf), buf.decode("utf-8")) ).encode("utf-8") ) sock.close() close_event.set() self._start_server(echo_socket_handler) base_url = "http://%s:%d" % (self.host, self.port) with proxy_from_url(base_url) as proxy: conn = proxy.connection_from_url("http://www.google.com") r = conn.urlopen( "GET", "http://www.google.com", assert_same_host=False, retries=1 ) assert r.status == 200 close_event.wait(timeout=LONG_TIMEOUT) with pytest.raises(ProxyError): conn.urlopen( "GET", "http://www.google.com", assert_same_host=False, retries=False, ) def test_connect_reconn(self): def proxy_ssl_one(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) s = buf.decode("utf-8") if not s.startswith("CONNECT "): sock.send( ( "HTTP/1.1 405 Method not allowed\r\nAllow: CONNECT\r\n\r\n" ).encode("utf-8") ) sock.close() return if not s.startswith("CONNECT %s:443" % (self.host,)): sock.send(("HTTP/1.1 403 Forbidden\r\n\r\n").encode("utf-8")) sock.close() return sock.send(("HTTP/1.1 200 Connection Established\r\n\r\n").encode("utf-8")) ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) ssl_sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "Connection: close\r\n" "\r\n" "Hi" ).encode("utf-8") ) ssl_sock.close() def echo_socket_handler(listener): proxy_ssl_one(listener) proxy_ssl_one(listener) self._start_server(echo_socket_handler) base_url = "http://%s:%d" % (self.host, self.port) with proxy_from_url(base_url, ca_certs=DEFAULT_CA) as proxy: url = "https://{0}".format(self.host) conn = proxy.connection_from_url(url) r = conn.urlopen("GET", url, retries=0) assert r.status == 200 r = conn.urlopen("GET", url, retries=0) assert r.status == 200 def test_connect_ipv6_addr(self): ipv6_addr = "2001:4998:c:a06::2:4008" def echo_socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) s = buf.decode("utf-8") if s.startswith("CONNECT [%s]:443" % (ipv6_addr,)): sock.send(b"HTTP/1.1 200 Connection Established\r\n\r\n") ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) ssl_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 2\r\n" b"Connection: close\r\n" b"\r\n" b"Hi" ) ssl_sock.close() else: sock.close() self._start_server(echo_socket_handler) base_url = "http://%s:%d" % (self.host, self.port) with proxy_from_url(base_url, cert_reqs="NONE") as proxy: url = "https://[{0}]".format(ipv6_addr) conn = proxy.connection_from_url(url) try: r = conn.urlopen("GET", url, retries=0) assert r.status == 200 except MaxRetryError: self.fail("Invalid IPv6 format in HTTP CONNECT request") class TestSSL(SocketDummyServerTestCase): def test_ssl_failure_midway_through_conn(self): def socket_handler(listener): sock = listener.accept()[0] sock2 = sock.dup() ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) # Deliberately send from the non-SSL socket. sock2.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 2\r\n" "\r\n" "Hi" ).encode("utf-8") ) sock2.close() ssl_sock.close() self._start_server(socket_handler) with HTTPSConnectionPool(self.host, self.port) as pool: with pytest.raises(MaxRetryError) as cm: pool.request("GET", "/", retries=0) assert isinstance(cm.value.reason, SSLError) def test_ssl_read_timeout(self): timed_out = Event() def socket_handler(listener): sock = listener.accept()[0] ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) # Send incomplete message (note Content-Length) ssl_sock.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 10\r\n" "\r\n" "Hi-" ).encode("utf-8") ) timed_out.wait() sock.close() ssl_sock.close() self._start_server(socket_handler) with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool: response = pool.urlopen( "GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT ) try: with pytest.raises(ReadTimeoutError): response.read() finally: timed_out.set() def test_ssl_failed_fingerprint_verification(self): def socket_handler(listener): for i in range(2): sock = listener.accept()[0] ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) ssl_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 5\r\n\r\n" b"Hello" ) ssl_sock.close() sock.close() self._start_server(socket_handler) # GitHub's fingerprint. Valid, but not matching. fingerprint = "A0:C4:A7:46:00:ED:A7:2D:C0:BE:CB:9A:8C:B6:07:CA:58:EE:74:5E" def request(): pool = HTTPSConnectionPool( self.host, self.port, assert_fingerprint=fingerprint ) try: timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) response = pool.urlopen( "GET", "/", preload_content=False, retries=0, timeout=timeout ) response.read() finally: pool.close() with pytest.raises(MaxRetryError) as cm: request() assert isinstance(cm.value.reason, SSLError) # Should not hang, see https://github.com/urllib3/urllib3/issues/529 with pytest.raises(MaxRetryError): request() def test_retry_ssl_error(self): def socket_handler(listener): # first request, trigger an SSLError sock = listener.accept()[0] sock2 = sock.dup() ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) # Deliberately send from the non-SSL socket to trigger an SSLError sock2.send( ( "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: 4\r\n" "\r\n" "Fail" ).encode("utf-8") ) sock2.close() ssl_sock.close() # retried request sock = listener.accept()[0] ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) ssl_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 7\r\n\r\n" b"Success" ) ssl_sock.close() self._start_server(socket_handler) with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool: response = pool.urlopen("GET", "/", retries=1) assert response.data == b"Success" def test_ssl_load_default_certs_when_empty(self): def socket_handler(listener): sock = listener.accept()[0] ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) ssl_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 5\r\n\r\n" b"Hello" ) ssl_sock.close() sock.close() context = mock.create_autospec(ssl_.SSLContext) context.load_default_certs = mock.Mock() context.options = 0 with mock.patch("urllib3.util.ssl_.SSLContext", lambda *_, **__: context): self._start_server(socket_handler) with HTTPSConnectionPool(self.host, self.port) as pool: with pytest.raises(MaxRetryError): pool.request("GET", "/", timeout=SHORT_TIMEOUT) context.load_default_certs.assert_called_with() @notPyPy2 def test_ssl_dont_load_default_certs_when_given(self): def socket_handler(listener): sock = listener.accept()[0] ssl_sock = ssl.wrap_socket( sock, server_side=True, keyfile=DEFAULT_CERTS["keyfile"], certfile=DEFAULT_CERTS["certfile"], ca_certs=DEFAULT_CA, ) buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += ssl_sock.recv(65536) ssl_sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Type: text/plain\r\n" b"Content-Length: 5\r\n\r\n" b"Hello" ) ssl_sock.close() sock.close() context = mock.create_autospec(ssl_.SSLContext) context.load_default_certs = mock.Mock() context.options = 0 with mock.patch("urllib3.util.ssl_.SSLContext", lambda *_, **__: context): for kwargs in [ {"ca_certs": "/a"}, {"ca_cert_dir": "/a"}, {"ca_certs": "a", "ca_cert_dir": "a"}, {"ssl_context": context}, ]: self._start_server(socket_handler) with HTTPSConnectionPool(self.host, self.port, **kwargs) as pool: with pytest.raises(MaxRetryError): pool.request("GET", "/", timeout=SHORT_TIMEOUT) context.load_default_certs.assert_not_called() class TestErrorWrapping(SocketDummyServerTestCase): def test_bad_statusline(self): self.start_response_handler( b"HTTP/1.1 Omg What Is This?\r\n" b"Content-Length: 0\r\n" b"\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: with pytest.raises(ProtocolError): pool.request("GET", "/") def test_unknown_protocol(self): self.start_response_handler( b"HTTP/1000 200 OK\r\n" b"Content-Length: 0\r\n" b"\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: with pytest.raises(ProtocolError): pool.request("GET", "/") class TestHeaders(SocketDummyServerTestCase): @onlyPy3 def test_httplib_headers_case_insensitive(self): self.start_response_handler( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n" b"Content-type: text/plain\r\n" b"\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: HEADERS = {"Content-Length": "0", "Content-type": "text/plain"} r = pool.request("GET", "/") assert HEADERS == dict(r.headers.items()) # to preserve case sensitivity def test_headers_are_sent_with_the_original_case(self): headers = {"foo": "bar", "bAz": "quux"} parsed_headers = {} def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) headers_list = [header for header in buf.split(b"\r\n")[1:] if header] for header in headers_list: (key, value) = header.split(b": ") parsed_headers[key.decode("ascii")] = value.decode("ascii") sock.send( ("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n").encode("utf-8") ) sock.close() self._start_server(socket_handler) expected_headers = { "Accept-Encoding": "identity", "Host": "{0}:{1}".format(self.host, self.port), } expected_headers.update(headers) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: pool.request("GET", "/", headers=HTTPHeaderDict(headers)) assert expected_headers == parsed_headers def test_request_headers_are_sent_in_the_original_order(self): # NOTE: Probability this test gives a false negative is 1/(K!) K = 16 # NOTE: Provide headers in non-sorted order (i.e. reversed) # so that if the internal implementation tries to sort them, # a change will be detected. expected_request_headers = [ (u"X-Header-%d" % i, str(i)) for i in reversed(range(K)) ] actual_request_headers = [] def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) headers_list = [header for header in buf.split(b"\r\n")[1:] if header] for header in headers_list: (key, value) = header.split(b": ") if not key.decode("ascii").startswith(u"X-Header-"): continue actual_request_headers.append( (key.decode("ascii"), value.decode("ascii")) ) sock.send( (u"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n").encode( "ascii" ) ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: pool.request("GET", "/", headers=OrderedDict(expected_request_headers)) assert expected_request_headers == actual_request_headers @fails_on_travis_gce def test_request_host_header_ignores_fqdn_dot(self): received_headers = [] def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) for header in buf.split(b"\r\n")[1:]: if header: received_headers.append(header) sock.send( (u"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n").encode( "ascii" ) ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host + ".", self.port, retries=False) as pool: pool.request("GET", "/") self.assert_header_received( received_headers, "Host", "%s:%s" % (self.host, self.port) ) def test_response_headers_are_returned_in_the_original_order(self): # NOTE: Probability this test gives a false negative is 1/(K!) K = 16 # NOTE: Provide headers in non-sorted order (i.e. reversed) # so that if the internal implementation tries to sort them, # a change will be detected. expected_response_headers = [ ("X-Header-%d" % i, str(i)) for i in reversed(range(K)) ] def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" + b"\r\n".join( [ (k.encode("utf8") + b": " + v.encode("utf8")) for (k, v) in expected_response_headers ] ) + b"\r\n" ) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port) as pool: r = pool.request("GET", "/", retries=0) actual_response_headers = [ (k, v) for (k, v) in r.headers.items() if k.startswith("X-Header-") ] assert expected_response_headers == actual_response_headers @pytest.mark.skipif( issubclass(httplib.HTTPMessage, MimeToolMessage), reason="Header parsing errors not available", ) class TestBrokenHeaders(SocketDummyServerTestCase): def _test_broken_header_parsing(self, headers, unparsed_data_check=None): self.start_response_handler( ( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n" b"Content-type: text/plain\r\n" ) + b"\r\n".join(headers) + b"\r\n\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: with LogRecorder() as logs: pool.request("GET", "/") for record in logs: if ( "Failed to parse headers" in record.msg and pool._absolute_url("/") == record.args[0] ): if ( unparsed_data_check is None or unparsed_data_check in record.getMessage() ): return self.fail("Missing log about unparsed headers") def test_header_without_name(self): self._test_broken_header_parsing([b": Value", b"Another: Header"]) def test_header_without_name_or_value(self): self._test_broken_header_parsing([b":", b"Another: Header"]) def test_header_without_colon_or_value(self): self._test_broken_header_parsing( [b"Broken Header", b"Another: Header"], "Broken Header" ) class TestHeaderParsingContentType(SocketDummyServerTestCase): def _test_okay_header_parsing(self, header): self.start_response_handler( (b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n") + header + b"\r\n\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: with LogRecorder() as logs: pool.request("GET", "/") for record in logs: assert "Failed to parse headers" not in record.msg def test_header_text_plain(self): self._test_okay_header_parsing(b"Content-type: text/plain") def test_header_message_rfc822(self): self._test_okay_header_parsing(b"Content-type: message/rfc822") class TestHEAD(SocketDummyServerTestCase): def test_chunked_head_response_does_not_hang(self): self.start_response_handler( b"HTTP/1.1 200 OK\r\n" b"Transfer-Encoding: chunked\r\n" b"Content-type: text/plain\r\n" b"\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False) # stream will use the read_chunked method here. assert [] == list(r.stream()) def test_empty_head_response_does_not_hang(self): self.start_response_handler( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 256\r\n" b"Content-type: text/plain\r\n" b"\r\n" ) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False) # stream will use the read method here. assert [] == list(r.stream()) class TestStream(SocketDummyServerTestCase): def test_stream_none_unchunked_response_does_not_hang(self): done_event = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 12\r\n" b"Content-type: text/plain\r\n" b"\r\n" b"hello, world" ) done_event.wait(5) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port, retries=False) as pool: r = pool.request("GET", "/", timeout=LONG_TIMEOUT, preload_content=False) # Stream should read to the end. assert [b"hello, world"] == list(r.stream(None)) done_event.set() class TestBadContentLength(SocketDummyServerTestCase): def test_enforce_content_length_get(self): done_event = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 22\r\n" b"Content-type: text/plain\r\n" b"\r\n" b"hello, world" ) done_event.wait(LONG_TIMEOUT) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port, maxsize=1) as conn: # Test stream read when content length less than headers claim get_response = conn.request( "GET", url="/", preload_content=False, enforce_content_length=True ) data = get_response.stream(100) # Read "good" data before we try to read again. # This won't trigger till generator is exhausted. next(data) try: next(data) assert False except ProtocolError as e: assert "12 bytes read, 10 more expected" in str(e) done_event.set() def test_enforce_content_length_no_body(self): done_event = Event() def socket_handler(listener): sock = listener.accept()[0] buf = b"" while not buf.endswith(b"\r\n\r\n"): buf += sock.recv(65536) sock.send( b"HTTP/1.1 200 OK\r\n" b"Content-Length: 22\r\n" b"Content-type: text/plain\r\n" b"\r\n" ) done_event.wait(1) sock.close() self._start_server(socket_handler) with HTTPConnectionPool(self.host, self.port, maxsize=1) as conn: # Test stream on 0 length body head_response = conn.request( "HEAD", url="/", preload_content=False, enforce_content_length=True ) data = [chunk for chunk in head_response.stream(1)] assert len(data) == 0 done_event.set() class TestRetryPoolSizeDrainFail(SocketDummyServerTestCase): def test_pool_size_retry_drain_fail(self): def socket_handler(listener): for _ in range(2): sock = listener.accept()[0] while not sock.recv(65536).endswith(b"\r\n\r\n"): pass # send a response with an invalid content length -- this causes # a ProtocolError to raise when trying to drain the connection sock.send( b"HTTP/1.1 404 NOT FOUND\r\n" b"Content-Length: 1000\r\n" b"Content-Type: text/plain\r\n" b"\r\n" ) sock.close() self._start_server(socket_handler) retries = Retry(total=1, raise_on_status=False, status_forcelist=[404]) with HTTPConnectionPool( self.host, self.port, maxsize=10, retries=retries, block=True ) as pool: pool.urlopen("GET", "/not_found", preload_content=False) assert pool.num_connections == 1