content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
import contextlib\nimport ssl\nimport typing\nfrom ctypes import WinDLL # type: ignore\nfrom ctypes import WinError # type: ignore\nfrom ctypes import (\n POINTER,\n Structure,\n c_char_p,\n c_ulong,\n c_void_p,\n c_wchar_p,\n cast,\n create_unicode_buffer,\n pointer,\n sizeof,\n)\nfrom ctypes.wintypes import (\n BOOL,\n DWORD,\n HANDLE,\n LONG,\n LPCSTR,\n LPCVOID,\n LPCWSTR,\n LPFILETIME,\n LPSTR,\n LPWSTR,\n)\nfrom typing import TYPE_CHECKING, Any\n\nfrom ._ssl_constants import _set_ssl_context_verify_mode\n\nHCERTCHAINENGINE = HANDLE\nHCERTSTORE = HANDLE\nHCRYPTPROV_LEGACY = HANDLE\n\n\nclass CERT_CONTEXT(Structure):\n _fields_ = (\n ("dwCertEncodingType", DWORD),\n ("pbCertEncoded", c_void_p),\n ("cbCertEncoded", DWORD),\n ("pCertInfo", c_void_p),\n ("hCertStore", HCERTSTORE),\n )\n\n\nPCERT_CONTEXT = POINTER(CERT_CONTEXT)\nPCCERT_CONTEXT = POINTER(PCERT_CONTEXT)\n\n\nclass CERT_ENHKEY_USAGE(Structure):\n _fields_ = (\n ("cUsageIdentifier", DWORD),\n ("rgpszUsageIdentifier", POINTER(LPSTR)),\n )\n\n\nPCERT_ENHKEY_USAGE = POINTER(CERT_ENHKEY_USAGE)\n\n\nclass CERT_USAGE_MATCH(Structure):\n _fields_ = (\n ("dwType", DWORD),\n ("Usage", CERT_ENHKEY_USAGE),\n )\n\n\nclass CERT_CHAIN_PARA(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("RequestedUsage", CERT_USAGE_MATCH),\n ("RequestedIssuancePolicy", CERT_USAGE_MATCH),\n ("dwUrlRetrievalTimeout", DWORD),\n ("fCheckRevocationFreshnessTime", BOOL),\n ("dwRevocationFreshnessTime", DWORD),\n ("pftCacheResync", LPFILETIME),\n ("pStrongSignPara", c_void_p),\n ("dwStrongSignFlags", DWORD),\n )\n\n\nif TYPE_CHECKING:\n PCERT_CHAIN_PARA = pointer[CERT_CHAIN_PARA] # type: ignore[misc]\nelse:\n PCERT_CHAIN_PARA = POINTER(CERT_CHAIN_PARA)\n\n\nclass CERT_TRUST_STATUS(Structure):\n _fields_ = (\n ("dwErrorStatus", DWORD),\n ("dwInfoStatus", DWORD),\n )\n\n\nclass CERT_CHAIN_ELEMENT(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("pCertContext", PCERT_CONTEXT),\n ("TrustStatus", CERT_TRUST_STATUS),\n ("pRevocationInfo", c_void_p),\n ("pIssuanceUsage", PCERT_ENHKEY_USAGE),\n ("pApplicationUsage", PCERT_ENHKEY_USAGE),\n ("pwszExtendedErrorInfo", LPCWSTR),\n )\n\n\nPCERT_CHAIN_ELEMENT = POINTER(CERT_CHAIN_ELEMENT)\n\n\nclass CERT_SIMPLE_CHAIN(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("TrustStatus", CERT_TRUST_STATUS),\n ("cElement", DWORD),\n ("rgpElement", POINTER(PCERT_CHAIN_ELEMENT)),\n ("pTrustListInfo", c_void_p),\n ("fHasRevocationFreshnessTime", BOOL),\n ("dwRevocationFreshnessTime", DWORD),\n )\n\n\nPCERT_SIMPLE_CHAIN = POINTER(CERT_SIMPLE_CHAIN)\n\n\nclass CERT_CHAIN_CONTEXT(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("TrustStatus", CERT_TRUST_STATUS),\n ("cChain", DWORD),\n ("rgpChain", POINTER(PCERT_SIMPLE_CHAIN)),\n ("cLowerQualityChainContext", DWORD),\n ("rgpLowerQualityChainContext", c_void_p),\n ("fHasRevocationFreshnessTime", BOOL),\n ("dwRevocationFreshnessTime", DWORD),\n )\n\n\nPCERT_CHAIN_CONTEXT = POINTER(CERT_CHAIN_CONTEXT)\nPCCERT_CHAIN_CONTEXT = POINTER(PCERT_CHAIN_CONTEXT)\n\n\nclass SSL_EXTRA_CERT_CHAIN_POLICY_PARA(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("dwAuthType", DWORD),\n ("fdwChecks", DWORD),\n ("pwszServerName", LPCWSTR),\n )\n\n\nclass CERT_CHAIN_POLICY_PARA(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("dwFlags", DWORD),\n ("pvExtraPolicyPara", c_void_p),\n )\n\n\nPCERT_CHAIN_POLICY_PARA = POINTER(CERT_CHAIN_POLICY_PARA)\n\n\nclass CERT_CHAIN_POLICY_STATUS(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("dwError", DWORD),\n ("lChainIndex", LONG),\n ("lElementIndex", LONG),\n ("pvExtraPolicyStatus", c_void_p),\n )\n\n\nPCERT_CHAIN_POLICY_STATUS = POINTER(CERT_CHAIN_POLICY_STATUS)\n\n\nclass CERT_CHAIN_ENGINE_CONFIG(Structure):\n _fields_ = (\n ("cbSize", DWORD),\n ("hRestrictedRoot", HCERTSTORE),\n ("hRestrictedTrust", HCERTSTORE),\n ("hRestrictedOther", HCERTSTORE),\n ("cAdditionalStore", DWORD),\n ("rghAdditionalStore", c_void_p),\n ("dwFlags", DWORD),\n ("dwUrlRetrievalTimeout", DWORD),\n ("MaximumCachedCertificates", DWORD),\n ("CycleDetectionModulus", DWORD),\n ("hExclusiveRoot", HCERTSTORE),\n ("hExclusiveTrustedPeople", HCERTSTORE),\n ("dwExclusiveFlags", DWORD),\n )\n\n\nPCERT_CHAIN_ENGINE_CONFIG = POINTER(CERT_CHAIN_ENGINE_CONFIG)\nPHCERTCHAINENGINE = POINTER(HCERTCHAINENGINE)\n\nX509_ASN_ENCODING = 0x00000001\nPKCS_7_ASN_ENCODING = 0x00010000\nCERT_STORE_PROV_MEMORY = b"Memory"\nCERT_STORE_ADD_USE_EXISTING = 2\nUSAGE_MATCH_TYPE_OR = 1\nOID_PKIX_KP_SERVER_AUTH = c_char_p(b"1.3.6.1.5.5.7.3.1")\nCERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000\nCERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000\nCERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS = 0x00000007\nCERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG = 0x00000008\nCERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 0x00000010\nCERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG = 0x00000040\nCERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG = 0x00000020\nCERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG = 0x00000080\nCERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS = 0x00000F00\nCERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG = 0x00008000\nCERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG = 0x00004000\nSECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000\nAUTHTYPE_SERVER = 2\nCERT_CHAIN_POLICY_SSL = 4\nFORMAT_MESSAGE_FROM_SYSTEM = 0x00001000\nFORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200\n\n# Flags to set for SSLContext.verify_mode=CERT_NONE\nCERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS = (\n CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS\n | CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG\n | CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG\n | CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG\n | CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG\n | CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG\n | CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS\n | CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG\n | CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG\n)\n\nwincrypt = WinDLL("crypt32.dll")\nkernel32 = WinDLL("kernel32.dll")\n\n\ndef _handle_win_error(result: bool, _: Any, args: Any) -> Any:\n if not result:\n # Note, actually raises OSError after calling GetLastError and FormatMessage\n raise WinError()\n return args\n\n\nCertCreateCertificateChainEngine = wincrypt.CertCreateCertificateChainEngine\nCertCreateCertificateChainEngine.argtypes = (\n PCERT_CHAIN_ENGINE_CONFIG,\n PHCERTCHAINENGINE,\n)\nCertCreateCertificateChainEngine.errcheck = _handle_win_error\n\nCertOpenStore = wincrypt.CertOpenStore\nCertOpenStore.argtypes = (LPCSTR, DWORD, HCRYPTPROV_LEGACY, DWORD, c_void_p)\nCertOpenStore.restype = HCERTSTORE\nCertOpenStore.errcheck = _handle_win_error\n\nCertAddEncodedCertificateToStore = wincrypt.CertAddEncodedCertificateToStore\nCertAddEncodedCertificateToStore.argtypes = (\n HCERTSTORE,\n DWORD,\n c_char_p,\n DWORD,\n DWORD,\n PCCERT_CONTEXT,\n)\nCertAddEncodedCertificateToStore.restype = BOOL\n\nCertCreateCertificateContext = wincrypt.CertCreateCertificateContext\nCertCreateCertificateContext.argtypes = (DWORD, c_char_p, DWORD)\nCertCreateCertificateContext.restype = PCERT_CONTEXT\nCertCreateCertificateContext.errcheck = _handle_win_error\n\nCertGetCertificateChain = wincrypt.CertGetCertificateChain\nCertGetCertificateChain.argtypes = (\n HCERTCHAINENGINE,\n PCERT_CONTEXT,\n LPFILETIME,\n HCERTSTORE,\n PCERT_CHAIN_PARA,\n DWORD,\n c_void_p,\n PCCERT_CHAIN_CONTEXT,\n)\nCertGetCertificateChain.restype = BOOL\nCertGetCertificateChain.errcheck = _handle_win_error\n\nCertVerifyCertificateChainPolicy = wincrypt.CertVerifyCertificateChainPolicy\nCertVerifyCertificateChainPolicy.argtypes = (\n c_ulong,\n PCERT_CHAIN_CONTEXT,\n PCERT_CHAIN_POLICY_PARA,\n PCERT_CHAIN_POLICY_STATUS,\n)\nCertVerifyCertificateChainPolicy.restype = BOOL\n\nCertCloseStore = wincrypt.CertCloseStore\nCertCloseStore.argtypes = (HCERTSTORE, DWORD)\nCertCloseStore.restype = BOOL\nCertCloseStore.errcheck = _handle_win_error\n\nCertFreeCertificateChain = wincrypt.CertFreeCertificateChain\nCertFreeCertificateChain.argtypes = (PCERT_CHAIN_CONTEXT,)\n\nCertFreeCertificateContext = wincrypt.CertFreeCertificateContext\nCertFreeCertificateContext.argtypes = (PCERT_CONTEXT,)\n\nCertFreeCertificateChainEngine = wincrypt.CertFreeCertificateChainEngine\nCertFreeCertificateChainEngine.argtypes = (HCERTCHAINENGINE,)\n\nFormatMessageW = kernel32.FormatMessageW\nFormatMessageW.argtypes = (\n DWORD,\n LPCVOID,\n DWORD,\n DWORD,\n LPWSTR,\n DWORD,\n c_void_p,\n)\nFormatMessageW.restype = DWORD\n\n\ndef _verify_peercerts_impl(\n ssl_context: ssl.SSLContext,\n cert_chain: list[bytes],\n server_hostname: str | None = None,\n) -> None:\n """Verify the cert_chain from the server using Windows APIs."""\n\n # If the peer didn't send any certificates then\n # we can't do verification. Raise an error.\n if not cert_chain:\n raise ssl.SSLCertVerificationError("Peer sent no certificates to verify")\n\n pCertContext = None\n hIntermediateCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)\n try:\n # Add intermediate certs to an in-memory cert store\n for cert_bytes in cert_chain[1:]:\n CertAddEncodedCertificateToStore(\n hIntermediateCertStore,\n X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,\n cert_bytes,\n len(cert_bytes),\n CERT_STORE_ADD_USE_EXISTING,\n None,\n )\n\n # Cert context for leaf cert\n leaf_cert = cert_chain[0]\n pCertContext = CertCreateCertificateContext(\n X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, leaf_cert, len(leaf_cert)\n )\n\n # Chain params to match certs for serverAuth extended usage\n cert_enhkey_usage = CERT_ENHKEY_USAGE()\n cert_enhkey_usage.cUsageIdentifier = 1\n cert_enhkey_usage.rgpszUsageIdentifier = (c_char_p * 1)(OID_PKIX_KP_SERVER_AUTH)\n cert_usage_match = CERT_USAGE_MATCH()\n cert_usage_match.Usage = cert_enhkey_usage\n chain_params = CERT_CHAIN_PARA()\n chain_params.RequestedUsage = cert_usage_match\n chain_params.cbSize = sizeof(chain_params)\n pChainPara = pointer(chain_params)\n\n if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:\n chain_flags = CERT_CHAIN_REVOCATION_CHECK_CHAIN\n elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:\n chain_flags = CERT_CHAIN_REVOCATION_CHECK_END_CERT\n else:\n chain_flags = 0\n\n try:\n # First attempt to verify using the default Windows system trust roots\n # (default chain engine).\n _get_and_verify_cert_chain(\n ssl_context,\n None,\n hIntermediateCertStore,\n pCertContext,\n pChainPara,\n server_hostname,\n chain_flags=chain_flags,\n )\n except ssl.SSLCertVerificationError as e:\n # If that fails but custom CA certs have been added\n # to the SSLContext using load_verify_locations,\n # try verifying using a custom chain engine\n # that trusts the custom CA certs.\n custom_ca_certs: list[bytes] | None = ssl_context.get_ca_certs(\n binary_form=True\n )\n if custom_ca_certs:\n try:\n _verify_using_custom_ca_certs(\n ssl_context,\n custom_ca_certs,\n hIntermediateCertStore,\n pCertContext,\n pChainPara,\n server_hostname,\n chain_flags=chain_flags,\n )\n # Raise the original error, not the new error.\n except ssl.SSLCertVerificationError:\n raise e from None\n else:\n raise\n finally:\n CertCloseStore(hIntermediateCertStore, 0)\n if pCertContext:\n CertFreeCertificateContext(pCertContext)\n\n\ndef _get_and_verify_cert_chain(\n ssl_context: ssl.SSLContext,\n hChainEngine: HCERTCHAINENGINE | None,\n hIntermediateCertStore: HCERTSTORE,\n pPeerCertContext: c_void_p,\n pChainPara: PCERT_CHAIN_PARA, # type: ignore[valid-type]\n server_hostname: str | None,\n chain_flags: int,\n) -> None:\n ppChainContext = None\n try:\n # Get cert chain\n ppChainContext = pointer(PCERT_CHAIN_CONTEXT())\n CertGetCertificateChain(\n hChainEngine, # chain engine\n pPeerCertContext, # leaf cert context\n None, # current system time\n hIntermediateCertStore, # additional in-memory cert store\n pChainPara, # chain-building parameters\n chain_flags,\n None, # reserved\n ppChainContext, # the resulting chain context\n )\n pChainContext = ppChainContext.contents\n\n # Verify cert chain\n ssl_extra_cert_chain_policy_para = SSL_EXTRA_CERT_CHAIN_POLICY_PARA()\n ssl_extra_cert_chain_policy_para.cbSize = sizeof(\n ssl_extra_cert_chain_policy_para\n )\n ssl_extra_cert_chain_policy_para.dwAuthType = AUTHTYPE_SERVER\n ssl_extra_cert_chain_policy_para.fdwChecks = 0\n if ssl_context.check_hostname is False:\n ssl_extra_cert_chain_policy_para.fdwChecks = (\n SECURITY_FLAG_IGNORE_CERT_CN_INVALID\n )\n if server_hostname:\n ssl_extra_cert_chain_policy_para.pwszServerName = c_wchar_p(server_hostname)\n\n chain_policy = CERT_CHAIN_POLICY_PARA()\n chain_policy.pvExtraPolicyPara = cast(\n pointer(ssl_extra_cert_chain_policy_para), c_void_p\n )\n if ssl_context.verify_mode == ssl.CERT_NONE:\n chain_policy.dwFlags |= CERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS\n chain_policy.cbSize = sizeof(chain_policy)\n\n pPolicyPara = pointer(chain_policy)\n policy_status = CERT_CHAIN_POLICY_STATUS()\n policy_status.cbSize = sizeof(policy_status)\n pPolicyStatus = pointer(policy_status)\n CertVerifyCertificateChainPolicy(\n CERT_CHAIN_POLICY_SSL,\n pChainContext,\n pPolicyPara,\n pPolicyStatus,\n )\n\n # Check status\n error_code = policy_status.dwError\n if error_code:\n # Try getting a human readable message for an error code.\n error_message_buf = create_unicode_buffer(1024)\n error_message_chars = FormatMessageW(\n FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n None,\n error_code,\n 0,\n error_message_buf,\n sizeof(error_message_buf),\n None,\n )\n\n # See if we received a message for the error,\n # otherwise we use a generic error with the\n # error code and hope that it's search-able.\n if error_message_chars <= 0:\n error_message = f"Certificate chain policy error {error_code:#x} [{policy_status.lElementIndex}]"\n else:\n error_message = error_message_buf.value.strip()\n\n err = ssl.SSLCertVerificationError(error_message)\n err.verify_message = error_message\n err.verify_code = error_code\n raise err from None\n finally:\n if ppChainContext:\n CertFreeCertificateChain(ppChainContext.contents)\n\n\ndef _verify_using_custom_ca_certs(\n ssl_context: ssl.SSLContext,\n custom_ca_certs: list[bytes],\n hIntermediateCertStore: HCERTSTORE,\n pPeerCertContext: c_void_p,\n pChainPara: PCERT_CHAIN_PARA, # type: ignore[valid-type]\n server_hostname: str | None,\n chain_flags: int,\n) -> None:\n hChainEngine = None\n hRootCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)\n try:\n # Add custom CA certs to an in-memory cert store\n for cert_bytes in custom_ca_certs:\n CertAddEncodedCertificateToStore(\n hRootCertStore,\n X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,\n cert_bytes,\n len(cert_bytes),\n CERT_STORE_ADD_USE_EXISTING,\n None,\n )\n\n # Create a custom cert chain engine which exclusively trusts\n # certs from our hRootCertStore\n cert_chain_engine_config = CERT_CHAIN_ENGINE_CONFIG()\n cert_chain_engine_config.cbSize = sizeof(cert_chain_engine_config)\n cert_chain_engine_config.hExclusiveRoot = hRootCertStore\n pConfig = pointer(cert_chain_engine_config)\n phChainEngine = pointer(HCERTCHAINENGINE())\n CertCreateCertificateChainEngine(\n pConfig,\n phChainEngine,\n )\n hChainEngine = phChainEngine.contents\n\n # Get and verify a cert chain using the custom chain engine\n _get_and_verify_cert_chain(\n ssl_context,\n hChainEngine,\n hIntermediateCertStore,\n pPeerCertContext,\n pChainPara,\n server_hostname,\n chain_flags,\n )\n finally:\n if hChainEngine:\n CertFreeCertificateChainEngine(hChainEngine)\n CertCloseStore(hRootCertStore, 0)\n\n\n@contextlib.contextmanager\ndef _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:\n check_hostname = ctx.check_hostname\n verify_mode = ctx.verify_mode\n ctx.check_hostname = False\n _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)\n try:\n yield\n finally:\n ctx.check_hostname = check_hostname\n _set_ssl_context_verify_mode(ctx, verify_mode)\n | .venv\Lib\site-packages\pip\_vendor\truststore\_windows.py | _windows.py | Python | 17,993 | 0.95 | 0.079365 | 0.051653 | awesome-app | 262 | 2024-12-01T02:48:26.095285 | Apache-2.0 | false | 194d9334a603286114f408809db39fee |
"""Verify certificates using native system trust stores"""\n\nimport sys as _sys\n\nif _sys.version_info < (3, 10):\n raise ImportError("truststore requires Python 3.10 or later")\n\n# Detect Python runtimes which don't implement SSLObject.get_unverified_chain() API\n# This API only became public in Python 3.13 but was available in CPython and PyPy since 3.10.\nif _sys.version_info < (3, 13) and _sys.implementation.name not in ("cpython", "pypy"):\n try:\n import ssl as _ssl\n except ImportError:\n raise ImportError("truststore requires the 'ssl' module")\n else:\n _sslmem = _ssl.MemoryBIO()\n _sslobj = _ssl.create_default_context().wrap_bio(\n _sslmem,\n _sslmem,\n )\n try:\n while not hasattr(_sslobj, "get_unverified_chain"):\n _sslobj = _sslobj._sslobj # type: ignore[attr-defined]\n except AttributeError:\n raise ImportError(\n "truststore requires peer certificate chain APIs to be available"\n ) from None\n\n del _ssl, _sslobj, _sslmem # noqa: F821\n\nfrom ._api import SSLContext, extract_from_ssl, inject_into_ssl # noqa: E402\n\ndel _api, _sys # type: ignore[name-defined] # noqa: F821\n\n__all__ = ["SSLContext", "inject_into_ssl", "extract_from_ssl"]\n__version__ = "0.10.1"\n | .venv\Lib\site-packages\pip\_vendor\truststore\__init__.py | __init__.py | Python | 1,320 | 0.95 | 0.138889 | 0.068966 | python-kit | 986 | 2023-08-23T02:38:58.438517 | GPL-3.0 | false | 512e425f7fa3a6d2e1dbe95cef206b61 |
\n\n | .venv\Lib\site-packages\pip\_vendor\truststore\__pycache__\_api.cpython-313.pyc | _api.cpython-313.pyc | Other | 17,168 | 0.95 | 0.022599 | 0.03012 | python-kit | 112 | 2025-03-24T09:00:27.380543 | GPL-3.0 | false | 8104fc50ed597c5b74234d72b5dc0f68 |
\n\n | .venv\Lib\site-packages\pip\_vendor\truststore\__pycache__\_macos.cpython-313.pyc | _macos.cpython-313.pyc | Other | 19,305 | 0.95 | 0.03125 | 0 | awesome-app | 937 | 2024-10-21T20:52:18.782871 | Apache-2.0 | false | 8133d81ef2bdf924aa55592f7cc24305 |
\n\n | .venv\Lib\site-packages\pip\_vendor\truststore\__pycache__\_openssl.cpython-313.pyc | _openssl.cpython-313.pyc | Other | 2,292 | 0.8 | 0 | 0 | vue-tools | 311 | 2023-08-10T08:52:08.462487 | MIT | false | ecb11938bde0e39ebc950647c37f1a5a |
\n\n | .venv\Lib\site-packages\pip\_vendor\truststore\__pycache__\_ssl_constants.cpython-313.pyc | _ssl_constants.cpython-313.pyc | Other | 1,103 | 0.8 | 0 | 0 | react-lib | 99 | 2023-09-24T03:48:06.917537 | MIT | false | dfd84eec4f0714f0c68a5ed32657a7e5 |
\n\n | .venv\Lib\site-packages\pip\_vendor\truststore\__pycache__\_windows.cpython-313.pyc | _windows.cpython-313.pyc | Other | 16,249 | 0.8 | 0 | 0 | vue-tools | 439 | 2025-02-19T04:37:03.421370 | BSD-3-Clause | false | 4d79030d20a169a80d6efd333a5b63f0 |
\n\n | .venv\Lib\site-packages\pip\_vendor\truststore\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,492 | 0.95 | 0 | 0 | vue-tools | 106 | 2024-12-28T15:36:26.047797 | Apache-2.0 | false | 177ad167d278197cc3d39df888e488a4 |
from __future__ import absolute_import\n\nimport datetime\nimport logging\nimport os\nimport re\nimport socket\nimport warnings\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom .packages import six\nfrom .packages.six.moves.http_client import HTTPConnection as _HTTPConnection\nfrom .packages.six.moves.http_client import HTTPException # noqa: F401\nfrom .util.proxy import create_proxy_ssl_context\n\ntry: # Compiled with SSL?\n import ssl\n\n BaseSSLError = ssl.SSLError\nexcept (ImportError, AttributeError): # Platform-specific: No SSL.\n ssl = None\n\n class BaseSSLError(BaseException):\n pass\n\n\ntry:\n # Python 3: not a no-op, we're adding this to the namespace so it can be imported.\n ConnectionError = ConnectionError\nexcept NameError:\n # Python 2\n class ConnectionError(Exception):\n pass\n\n\ntry: # Python 3:\n # Not a no-op, we're adding this to the namespace so it can be imported.\n BrokenPipeError = BrokenPipeError\nexcept NameError: # Python 2:\n\n class BrokenPipeError(Exception):\n pass\n\n\nfrom ._collections import HTTPHeaderDict # noqa (historical, removed in v2)\nfrom ._version import __version__\nfrom .exceptions import (\n ConnectTimeoutError,\n NewConnectionError,\n SubjectAltNameWarning,\n SystemTimeWarning,\n)\nfrom .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection\nfrom .util.ssl_ import (\n assert_fingerprint,\n create_urllib3_context,\n is_ipaddress,\n resolve_cert_reqs,\n resolve_ssl_version,\n ssl_wrap_socket,\n)\nfrom .util.ssl_match_hostname import CertificateError, match_hostname\n\nlog = logging.getLogger(__name__)\n\nport_by_scheme = {"http": 80, "https": 443}\n\n# When it comes time to update this value as a part of regular maintenance\n# (ie test_recent_date is failing) update it to ~6 months before the current date.\nRECENT_DATE = datetime.date(2024, 1, 1)\n\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")\n\n\nclass HTTPConnection(_HTTPConnection, object):\n """\n Based on :class:`http.client.HTTPConnection` but provides an extra constructor\n backwards-compatibility layer between older and newer Pythons.\n\n Additional keyword parameters are used to configure attributes of the connection.\n Accepted parameters include:\n\n - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`\n - ``source_address``: Set the source address for the current connection.\n - ``socket_options``: Set specific options on the underlying socket. If not specified, then\n defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling\n Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.\n\n For example, if you wish to enable TCP Keep Alive in addition to the defaults,\n you might pass:\n\n .. code-block:: python\n\n HTTPConnection.default_socket_options + [\n (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),\n ]\n\n Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).\n """\n\n default_port = port_by_scheme["http"]\n\n #: Disable Nagle's algorithm by default.\n #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``\n default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]\n\n #: Whether this connection verifies the host's certificate.\n is_verified = False\n\n #: Whether this proxy connection (if used) verifies the proxy host's\n #: certificate.\n proxy_is_verified = None\n\n def __init__(self, *args, **kw):\n if not six.PY2:\n kw.pop("strict", None)\n\n # Pre-set source_address.\n self.source_address = kw.get("source_address")\n\n #: The socket options provided by the user. If no options are\n #: provided, we use the default options.\n self.socket_options = kw.pop("socket_options", self.default_socket_options)\n\n # Proxy options provided by the user.\n self.proxy = kw.pop("proxy", None)\n self.proxy_config = kw.pop("proxy_config", None)\n\n _HTTPConnection.__init__(self, *args, **kw)\n\n @property\n def host(self):\n """\n Getter method to remove any trailing dots that indicate the hostname is an FQDN.\n\n In general, SSL certificates don't include the trailing dot indicating a\n fully-qualified domain name, and thus, they don't validate properly when\n checked against a domain name that includes the dot. In addition, some\n servers may not expect to receive the trailing dot when provided.\n\n However, the hostname with trailing dot is critical to DNS resolution; doing a\n lookup with the trailing dot will properly only resolve the appropriate FQDN,\n whereas a lookup without a trailing dot will search the system's search domain\n list. Thus, it's important to keep the original host around for use only in\n those cases where it's appropriate (i.e., when doing DNS lookup to establish the\n actual TCP connection across which we're going to send HTTP requests).\n """\n return self._dns_host.rstrip(".")\n\n @host.setter\n def host(self, value):\n """\n Setter for the `host` property.\n\n We assume that only urllib3 uses the _dns_host attribute; httplib itself\n only uses `host`, and it seems reasonable that other libraries follow suit.\n """\n self._dns_host = value\n\n def _new_conn(self):\n """Establish a socket connection and set nodelay settings on it.\n\n :return: New socket connection.\n """\n extra_kw = {}\n if self.source_address:\n extra_kw["source_address"] = self.source_address\n\n if self.socket_options:\n extra_kw["socket_options"] = self.socket_options\n\n try:\n conn = connection.create_connection(\n (self._dns_host, self.port), self.timeout, **extra_kw\n )\n\n except SocketTimeout:\n raise ConnectTimeoutError(\n self,\n "Connection to %s timed out. (connect timeout=%s)"\n % (self.host, self.timeout),\n )\n\n except SocketError as e:\n raise NewConnectionError(\n self, "Failed to establish a new connection: %s" % e\n )\n\n return conn\n\n def _is_using_tunnel(self):\n # Google App Engine's httplib does not define _tunnel_host\n return getattr(self, "_tunnel_host", None)\n\n def _prepare_conn(self, conn):\n self.sock = conn\n if self._is_using_tunnel():\n # TODO: Fix tunnel so it doesn't depend on self.sock state.\n self._tunnel()\n # Mark this connection as not reusable\n self.auto_open = 0\n\n def connect(self):\n conn = self._new_conn()\n self._prepare_conn(conn)\n\n def putrequest(self, method, url, *args, **kwargs):\n """ """\n # Empty docstring because the indentation of CPython's implementation\n # is broken but we don't want this method in our documentation.\n match = _CONTAINS_CONTROL_CHAR_RE.search(method)\n if match:\n raise ValueError(\n "Method cannot contain non-token characters %r (found at least %r)"\n % (method, match.group())\n )\n\n return _HTTPConnection.putrequest(self, method, url, *args, **kwargs)\n\n def putheader(self, header, *values):\n """ """\n if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):\n _HTTPConnection.putheader(self, header, *values)\n elif six.ensure_str(header.lower()) not in SKIPPABLE_HEADERS:\n raise ValueError(\n "urllib3.util.SKIP_HEADER only supports '%s'"\n % ("', '".join(map(str.title, sorted(SKIPPABLE_HEADERS))),)\n )\n\n def request(self, method, url, body=None, headers=None):\n # Update the inner socket's timeout value to send the request.\n # This only triggers if the connection is re-used.\n if getattr(self, "sock", None) is not None:\n self.sock.settimeout(self.timeout)\n\n if headers is None:\n headers = {}\n else:\n # Avoid modifying the headers passed into .request()\n headers = headers.copy()\n if "user-agent" not in (six.ensure_str(k.lower()) for k in headers):\n headers["User-Agent"] = _get_default_user_agent()\n super(HTTPConnection, self).request(method, url, body=body, headers=headers)\n\n def request_chunked(self, method, url, body=None, headers=None):\n """\n Alternative to the common request method, which sends the\n body with chunked encoding and not as one block\n """\n headers = headers or {}\n header_keys = set([six.ensure_str(k.lower()) for k in headers])\n skip_accept_encoding = "accept-encoding" in header_keys\n skip_host = "host" in header_keys\n self.putrequest(\n method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host\n )\n if "user-agent" not in header_keys:\n self.putheader("User-Agent", _get_default_user_agent())\n for header, value in headers.items():\n self.putheader(header, value)\n if "transfer-encoding" not in header_keys:\n self.putheader("Transfer-Encoding", "chunked")\n self.endheaders()\n\n if body is not None:\n stringish_types = six.string_types + (bytes,)\n if isinstance(body, stringish_types):\n body = (body,)\n for chunk in body:\n if not chunk:\n continue\n if not isinstance(chunk, bytes):\n chunk = chunk.encode("utf8")\n len_str = hex(len(chunk))[2:]\n to_send = bytearray(len_str.encode())\n to_send += b"\r\n"\n to_send += chunk\n to_send += b"\r\n"\n self.send(to_send)\n\n # After the if clause, to always have a closed body\n self.send(b"0\r\n\r\n")\n\n\nclass HTTPSConnection(HTTPConnection):\n """\n Many of the parameters to this constructor are passed to the underlying SSL\n socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.\n """\n\n default_port = port_by_scheme["https"]\n\n cert_reqs = None\n ca_certs = None\n ca_cert_dir = None\n ca_cert_data = None\n ssl_version = None\n assert_fingerprint = None\n tls_in_tls_required = False\n\n def __init__(\n self,\n host,\n port=None,\n key_file=None,\n cert_file=None,\n key_password=None,\n strict=None,\n timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n ssl_context=None,\n server_hostname=None,\n **kw\n ):\n\n HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)\n\n self.key_file = key_file\n self.cert_file = cert_file\n self.key_password = key_password\n self.ssl_context = ssl_context\n self.server_hostname = server_hostname\n\n # Required property for Google AppEngine 1.9.0 which otherwise causes\n # HTTPS requests to go out as HTTP. (See Issue #356)\n self._protocol = "https"\n\n def set_cert(\n self,\n key_file=None,\n cert_file=None,\n cert_reqs=None,\n key_password=None,\n ca_certs=None,\n assert_hostname=None,\n assert_fingerprint=None,\n ca_cert_dir=None,\n ca_cert_data=None,\n ):\n """\n This method should only be called once, before the connection is used.\n """\n # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also\n # have an SSLContext object in which case we'll use its verify_mode.\n if cert_reqs is None:\n if self.ssl_context is not None:\n cert_reqs = self.ssl_context.verify_mode\n else:\n cert_reqs = resolve_cert_reqs(None)\n\n self.key_file = key_file\n self.cert_file = cert_file\n self.cert_reqs = cert_reqs\n self.key_password = key_password\n self.assert_hostname = assert_hostname\n self.assert_fingerprint = assert_fingerprint\n self.ca_certs = ca_certs and os.path.expanduser(ca_certs)\n self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)\n self.ca_cert_data = ca_cert_data\n\n def connect(self):\n # Add certificate verification\n self.sock = conn = self._new_conn()\n hostname = self.host\n tls_in_tls = False\n\n if self._is_using_tunnel():\n if self.tls_in_tls_required:\n self.sock = conn = self._connect_tls_proxy(hostname, conn)\n tls_in_tls = True\n\n # Calls self._set_hostport(), so self.host is\n # self._tunnel_host below.\n self._tunnel()\n # Mark this connection as not reusable\n self.auto_open = 0\n\n # Override the host with the one we're requesting data from.\n hostname = self._tunnel_host\n\n server_hostname = hostname\n if self.server_hostname is not None:\n server_hostname = self.server_hostname\n\n is_time_off = datetime.date.today() < RECENT_DATE\n if is_time_off:\n warnings.warn(\n (\n "System time is way off (before {0}). This will probably "\n "lead to SSL verification errors"\n ).format(RECENT_DATE),\n SystemTimeWarning,\n )\n\n # Wrap socket using verification with the root certs in\n # trusted_root_certs\n default_ssl_context = False\n if self.ssl_context is None:\n default_ssl_context = True\n self.ssl_context = create_urllib3_context(\n ssl_version=resolve_ssl_version(self.ssl_version),\n cert_reqs=resolve_cert_reqs(self.cert_reqs),\n )\n\n context = self.ssl_context\n context.verify_mode = resolve_cert_reqs(self.cert_reqs)\n\n # Try to load OS default certs if none are given.\n # Works well on Windows (requires Python3.4+)\n if (\n not self.ca_certs\n and not self.ca_cert_dir\n and not self.ca_cert_data\n and default_ssl_context\n and hasattr(context, "load_default_certs")\n ):\n context.load_default_certs()\n\n self.sock = ssl_wrap_socket(\n sock=conn,\n keyfile=self.key_file,\n certfile=self.cert_file,\n key_password=self.key_password,\n ca_certs=self.ca_certs,\n ca_cert_dir=self.ca_cert_dir,\n ca_cert_data=self.ca_cert_data,\n server_hostname=server_hostname,\n ssl_context=context,\n tls_in_tls=tls_in_tls,\n )\n\n # If we're using all defaults and the connection\n # is TLSv1 or TLSv1.1 we throw a DeprecationWarning\n # for the host.\n if (\n default_ssl_context\n and self.ssl_version is None\n and hasattr(self.sock, "version")\n and self.sock.version() in {"TLSv1", "TLSv1.1"}\n ): # Defensive:\n warnings.warn(\n "Negotiating TLSv1/TLSv1.1 by default is deprecated "\n "and will be disabled in urllib3 v2.0.0. Connecting to "\n "'%s' with '%s' can be enabled by explicitly opting-in "\n "with 'ssl_version'" % (self.host, self.sock.version()),\n DeprecationWarning,\n )\n\n if self.assert_fingerprint:\n assert_fingerprint(\n self.sock.getpeercert(binary_form=True), self.assert_fingerprint\n )\n elif (\n context.verify_mode != ssl.CERT_NONE\n and not getattr(context, "check_hostname", False)\n and self.assert_hostname is not False\n ):\n # While urllib3 attempts to always turn off hostname matching from\n # the TLS library, this cannot always be done. So we check whether\n # the TLS Library still thinks it's matching hostnames.\n cert = self.sock.getpeercert()\n if not cert.get("subjectAltName", ()):\n warnings.warn(\n (\n "Certificate for {0} has no `subjectAltName`, falling back to check for a "\n "`commonName` for now. This feature is being removed by major browsers and "\n "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "\n "for details.)".format(hostname)\n ),\n SubjectAltNameWarning,\n )\n _match_hostname(cert, self.assert_hostname or server_hostname)\n\n self.is_verified = (\n context.verify_mode == ssl.CERT_REQUIRED\n or self.assert_fingerprint is not None\n )\n\n def _connect_tls_proxy(self, hostname, conn):\n """\n Establish a TLS connection to the proxy using the provided SSL context.\n """\n proxy_config = self.proxy_config\n ssl_context = proxy_config.ssl_context\n if ssl_context:\n # If the user provided a proxy context, we assume CA and client\n # certificates have already been set\n return ssl_wrap_socket(\n sock=conn,\n server_hostname=hostname,\n ssl_context=ssl_context,\n )\n\n ssl_context = create_proxy_ssl_context(\n self.ssl_version,\n self.cert_reqs,\n self.ca_certs,\n self.ca_cert_dir,\n self.ca_cert_data,\n )\n\n # If no cert was provided, use only the default options for server\n # certificate validation\n socket = ssl_wrap_socket(\n sock=conn,\n ca_certs=self.ca_certs,\n ca_cert_dir=self.ca_cert_dir,\n ca_cert_data=self.ca_cert_data,\n server_hostname=hostname,\n ssl_context=ssl_context,\n )\n\n if ssl_context.verify_mode != ssl.CERT_NONE and not getattr(\n ssl_context, "check_hostname", False\n ):\n # While urllib3 attempts to always turn off hostname matching from\n # the TLS library, this cannot always be done. So we check whether\n # the TLS Library still thinks it's matching hostnames.\n cert = socket.getpeercert()\n if not cert.get("subjectAltName", ()):\n warnings.warn(\n (\n "Certificate for {0} has no `subjectAltName`, falling back to check for a "\n "`commonName` for now. This feature is being removed by major browsers and "\n "deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "\n "for details.)".format(hostname)\n ),\n SubjectAltNameWarning,\n )\n _match_hostname(cert, hostname)\n\n self.proxy_is_verified = ssl_context.verify_mode == ssl.CERT_REQUIRED\n return socket\n\n\ndef _match_hostname(cert, asserted_hostname):\n # Our upstream implementation of ssl.match_hostname()\n # only applies this normalization to IP addresses so it doesn't\n # match DNS SANs so we do the same thing!\n stripped_hostname = asserted_hostname.strip("u[]")\n if is_ipaddress(stripped_hostname):\n asserted_hostname = stripped_hostname\n\n try:\n match_hostname(cert, asserted_hostname)\n except CertificateError as e:\n log.warning(\n "Certificate did not match expected hostname: %s. Certificate: %s",\n asserted_hostname,\n cert,\n )\n # Add cert to exception and reraise so client code can inspect\n # the cert when catching the exception, if they want to\n e._peer_cert = cert\n raise\n\n\ndef _get_default_user_agent():\n return "python-urllib3/%s" % __version__\n\n\nclass DummyConnection(object):\n """Used to detect a failed ConnectionCls import."""\n\n pass\n\n\nif not ssl:\n HTTPSConnection = DummyConnection # noqa: F811\n\n\nVerifiedHTTPSConnection = HTTPSConnection\n | .venv\Lib\site-packages\pip\_vendor\urllib3\connection.py | connection.py | Python | 20,314 | 0.95 | 0.15035 | 0.115546 | react-lib | 631 | 2023-12-30T17:06:05.568768 | GPL-3.0 | false | f614f2f3998b040d883bfafbbaa159cd |
from __future__ import absolute_import\n\nimport errno\nimport logging\nimport re\nimport socket\nimport sys\nimport warnings\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom ._collections import HTTPHeaderDict\nfrom .connection import (\n BaseSSLError,\n BrokenPipeError,\n DummyConnection,\n HTTPConnection,\n HTTPException,\n HTTPSConnection,\n VerifiedHTTPSConnection,\n port_by_scheme,\n)\nfrom .exceptions import (\n ClosedPoolError,\n EmptyPoolError,\n HeaderParsingError,\n HostChangedError,\n InsecureRequestWarning,\n LocationValueError,\n MaxRetryError,\n NewConnectionError,\n ProtocolError,\n ProxyError,\n ReadTimeoutError,\n SSLError,\n TimeoutError,\n)\nfrom .packages import six\nfrom .packages.six.moves import queue\nfrom .request import RequestMethods\nfrom .response import HTTPResponse\nfrom .util.connection import is_connection_dropped\nfrom .util.proxy import connection_requires_http_tunnel\nfrom .util.queue import LifoQueue\nfrom .util.request import set_file_position\nfrom .util.response import assert_header_parsing\nfrom .util.retry import Retry\nfrom .util.ssl_match_hostname import CertificateError\nfrom .util.timeout import Timeout\nfrom .util.url import Url, _encode_target\nfrom .util.url import _normalize_host as normalize_host\nfrom .util.url import get_host, parse_url\n\ntry: # Platform-specific: Python 3\n import weakref\n\n weakref_finalize = weakref.finalize\nexcept AttributeError: # Platform-specific: Python 2\n from .packages.backports.weakref_finalize import weakref_finalize\n\nxrange = six.moves.xrange\n\nlog = logging.getLogger(__name__)\n\n_Default = object()\n\n\n# Pool objects\nclass ConnectionPool(object):\n """\n Base class for all connection pools, such as\n :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.\n\n .. note::\n ConnectionPool.urlopen() does not normalize or percent-encode target URIs\n which is useful if your target server doesn't support percent-encoded\n target URIs.\n """\n\n scheme = None\n QueueCls = LifoQueue\n\n def __init__(self, host, port=None):\n if not host:\n raise LocationValueError("No host specified.")\n\n self.host = _normalize_host(host, scheme=self.scheme)\n self._proxy_host = host.lower()\n self.port = port\n\n def __str__(self):\n return "%s(host=%r, port=%r)" % (type(self).__name__, self.host, self.port)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n # Return False to re-raise any potential exceptions\n return False\n\n def close(self):\n """\n Close all pooled connections and disable the pool.\n """\n pass\n\n\n# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252\n_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}\n\n\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\n """\n Thread-safe connection pool for one host.\n\n :param host:\n Host used for this HTTP Connection (e.g. "localhost"), passed into\n :class:`http.client.HTTPConnection`.\n\n :param port:\n Port used for this HTTP Connection (None is equivalent to 80), passed\n into :class:`http.client.HTTPConnection`.\n\n :param strict:\n Causes BadStatusLine to be raised if the status line can't be parsed\n as a valid HTTP/1.0 or 1.1 status line, passed into\n :class:`http.client.HTTPConnection`.\n\n .. note::\n Only works in Python 2. This parameter is ignored in Python 3.\n\n :param timeout:\n Socket timeout in seconds for each individual connection. This can\n be a float or integer, which sets the timeout for the HTTP request,\n or an instance of :class:`urllib3.util.Timeout` which gives you more\n fine-grained control over request timeouts. After the constructor has\n been parsed, this is always a `urllib3.util.Timeout` object.\n\n :param maxsize:\n Number of connections to save that can be reused. More than 1 is useful\n in multithreaded situations. If ``block`` is set to False, more\n connections will be created but they will not be saved once they've\n been used.\n\n :param block:\n If set to True, no more than ``maxsize`` connections will be used at\n a time. When no free connections are available, the call will block\n until a connection has been released. This is a useful side effect for\n particular multithreaded situations where one does not want to use more\n than maxsize connections per host to prevent flooding.\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n\n :param retries:\n Retry configuration to use by default with requests in this pool.\n\n :param _proxy:\n Parsed proxy URL, should not be used directly, instead, see\n :class:`urllib3.ProxyManager`\n\n :param _proxy_headers:\n A dictionary with proxy headers, should not be used directly,\n instead, see :class:`urllib3.ProxyManager`\n\n :param \\**conn_kw:\n Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,\n :class:`urllib3.connection.HTTPSConnection` instances.\n """\n\n scheme = "http"\n ConnectionCls = HTTPConnection\n ResponseCls = HTTPResponse\n\n def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n _proxy_config=None,\n **conn_kw\n ):\n ConnectionPool.__init__(self, host, port)\n RequestMethods.__init__(self, headers)\n\n self.strict = strict\n\n if not isinstance(timeout, Timeout):\n timeout = Timeout.from_float(timeout)\n\n if retries is None:\n retries = Retry.DEFAULT\n\n self.timeout = timeout\n self.retries = retries\n\n self.pool = self.QueueCls(maxsize)\n self.block = block\n\n self.proxy = _proxy\n self.proxy_headers = _proxy_headers or {}\n self.proxy_config = _proxy_config\n\n # Fill the queue up so that doing get() on it will block properly\n for _ in xrange(maxsize):\n self.pool.put(None)\n\n # These are mostly for testing and debugging purposes.\n self.num_connections = 0\n self.num_requests = 0\n self.conn_kw = conn_kw\n\n if self.proxy:\n # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.\n # We cannot know if the user has added default socket options, so we cannot replace the\n # list.\n self.conn_kw.setdefault("socket_options", [])\n\n self.conn_kw["proxy"] = self.proxy\n self.conn_kw["proxy_config"] = self.proxy_config\n\n # Do not pass 'self' as callback to 'finalize'.\n # Then the 'finalize' would keep an endless living (leak) to self.\n # By just passing a reference to the pool allows the garbage collector\n # to free self if nobody else has a reference to it.\n pool = self.pool\n\n # Close all the HTTPConnections in the pool before the\n # HTTPConnectionPool object is garbage collected.\n weakref_finalize(self, _close_pool_connections, pool)\n\n def _new_conn(self):\n """\n Return a fresh :class:`HTTPConnection`.\n """\n self.num_connections += 1\n log.debug(\n "Starting new HTTP connection (%d): %s:%s",\n self.num_connections,\n self.host,\n self.port or "80",\n )\n\n conn = self.ConnectionCls(\n host=self.host,\n port=self.port,\n timeout=self.timeout.connect_timeout,\n strict=self.strict,\n **self.conn_kw\n )\n return conn\n\n def _get_conn(self, timeout=None):\n """\n Get a connection. Will return a pooled connection if one is available.\n\n If no connections are available and :prop:`.block` is ``False``, then a\n fresh connection is returned.\n\n :param timeout:\n Seconds to wait before giving up and raising\n :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and\n :prop:`.block` is ``True``.\n """\n conn = None\n try:\n conn = self.pool.get(block=self.block, timeout=timeout)\n\n except AttributeError: # self.pool is None\n raise ClosedPoolError(self, "Pool is closed.")\n\n except queue.Empty:\n if self.block:\n raise EmptyPoolError(\n self,\n "Pool reached maximum size and no more connections are allowed.",\n )\n pass # Oh well, we'll create a new connection then\n\n # If this is a persistent connection, check if it got disconnected\n if conn and is_connection_dropped(conn):\n log.debug("Resetting dropped connection: %s", self.host)\n conn.close()\n if getattr(conn, "auto_open", 1) == 0:\n # This is a proxied connection that has been mutated by\n # http.client._tunnel() and cannot be reused (since it would\n # attempt to bypass the proxy)\n conn = None\n\n return conn or self._new_conn()\n\n def _put_conn(self, conn):\n """\n Put a connection back into the pool.\n\n :param conn:\n Connection object for the current host and port as returned by\n :meth:`._new_conn` or :meth:`._get_conn`.\n\n If the pool is already full, the connection is closed and discarded\n because we exceeded maxsize. If connections are discarded frequently,\n then maxsize should be increased.\n\n If the pool is closed, then the connection will be closed and discarded.\n """\n try:\n self.pool.put(conn, block=False)\n return # Everything is dandy, done.\n except AttributeError:\n # self.pool is None.\n pass\n except queue.Full:\n # This should never happen if self.block == True\n log.warning(\n "Connection pool is full, discarding connection: %s. Connection pool size: %s",\n self.host,\n self.pool.qsize(),\n )\n # Connection never got put back into the pool, close it.\n if conn:\n conn.close()\n\n def _validate_conn(self, conn):\n """\n Called right before a request is made, after the socket is created.\n """\n pass\n\n def _prepare_proxy(self, conn):\n # Nothing to do for HTTP connections.\n pass\n\n def _get_timeout(self, timeout):\n """Helper that always returns a :class:`urllib3.util.Timeout`"""\n if timeout is _Default:\n return self.timeout.clone()\n\n if isinstance(timeout, Timeout):\n return timeout.clone()\n else:\n # User passed us an int/float. This is for backwards compatibility,\n # can be removed later\n return Timeout.from_float(timeout)\n\n def _raise_timeout(self, err, url, timeout_value):\n """Is the error actually a timeout? Will raise a ReadTimeout or pass"""\n\n if isinstance(err, SocketTimeout):\n raise ReadTimeoutError(\n self, url, "Read timed out. (read timeout=%s)" % timeout_value\n )\n\n # See the above comment about EAGAIN in Python 3. In Python 2 we have\n # to specifically catch it and throw the timeout error\n if hasattr(err, "errno") and err.errno in _blocking_errnos:\n raise ReadTimeoutError(\n self, url, "Read timed out. (read timeout=%s)" % timeout_value\n )\n\n # Catch possible read timeouts thrown as SSL errors. If not the\n # case, rethrow the original. We need to do this because of:\n # http://bugs.python.org/issue10272\n if "timed out" in str(err) or "did not complete (read)" in str(\n err\n ): # Python < 2.7.4\n raise ReadTimeoutError(\n self, url, "Read timed out. (read timeout=%s)" % timeout_value\n )\n\n def _make_request(\n self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw\n ):\n """\n Perform a request on a given urllib connection object taken from our\n pool.\n\n :param conn:\n a connection from one of our connection pools\n\n :param timeout:\n Socket timeout in seconds for the request. This can be a\n float or integer, which will set the same timeout value for\n the socket connect and the socket read, or an instance of\n :class:`urllib3.util.Timeout`, which gives you more fine-grained\n control over your timeouts.\n """\n self.num_requests += 1\n\n timeout_obj = self._get_timeout(timeout)\n timeout_obj.start_connect()\n conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout)\n\n # Trigger any extra validation we need to do.\n try:\n self._validate_conn(conn)\n except (SocketTimeout, BaseSSLError) as e:\n # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.\n self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)\n raise\n\n # conn.request() calls http.client.*.request, not the method in\n # urllib3.request. It also calls makefile (recv) on the socket.\n try:\n if chunked:\n conn.request_chunked(method, url, **httplib_request_kw)\n else:\n conn.request(method, url, **httplib_request_kw)\n\n # We are swallowing BrokenPipeError (errno.EPIPE) since the server is\n # legitimately able to close the connection after sending a valid response.\n # With this behaviour, the received response is still readable.\n except BrokenPipeError:\n # Python 3\n pass\n except IOError as e:\n # Python 2 and macOS/Linux\n # EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE/ECONNRESET are needed on macOS\n # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/\n if e.errno not in {\n errno.EPIPE,\n errno.ESHUTDOWN,\n errno.EPROTOTYPE,\n errno.ECONNRESET,\n }:\n raise\n\n # Reset the timeout for the recv() on the socket\n read_timeout = timeout_obj.read_timeout\n\n # App Engine doesn't have a sock attr\n if getattr(conn, "sock", None):\n # In Python 3 socket.py will catch EAGAIN and return None when you\n # try and read into the file pointer created by http.client, which\n # instead raises a BadStatusLine exception. Instead of catching\n # the exception and assuming all BadStatusLine exceptions are read\n # timeouts, check for a zero timeout before making the request.\n if read_timeout == 0:\n raise ReadTimeoutError(\n self, url, "Read timed out. (read timeout=%s)" % read_timeout\n )\n if read_timeout is Timeout.DEFAULT_TIMEOUT:\n conn.sock.settimeout(socket.getdefaulttimeout())\n else: # None or a value\n conn.sock.settimeout(read_timeout)\n\n # Receive the response from the server\n try:\n try:\n # Python 2.7, use buffering of HTTP responses\n httplib_response = conn.getresponse(buffering=True)\n except TypeError:\n # Python 3\n try:\n httplib_response = conn.getresponse()\n except BaseException as e:\n # Remove the TypeError from the exception chain in\n # Python 3 (including for exceptions like SystemExit).\n # Otherwise it looks like a bug in the code.\n six.raise_from(e, None)\n except (SocketTimeout, BaseSSLError, SocketError) as e:\n self._raise_timeout(err=e, url=url, timeout_value=read_timeout)\n raise\n\n # AppEngine doesn't have a version attr.\n http_version = getattr(conn, "_http_vsn_str", "HTTP/?")\n log.debug(\n '%s://%s:%s "%s %s %s" %s %s',\n self.scheme,\n self.host,\n self.port,\n method,\n url,\n http_version,\n httplib_response.status,\n httplib_response.length,\n )\n\n try:\n assert_header_parsing(httplib_response.msg)\n except (HeaderParsingError, TypeError) as hpe: # Platform-specific: Python 3\n log.warning(\n "Failed to parse headers (url=%s): %s",\n self._absolute_url(url),\n hpe,\n exc_info=True,\n )\n\n return httplib_response\n\n def _absolute_url(self, path):\n return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url\n\n def close(self):\n """\n Close all pooled connections and disable the pool.\n """\n if self.pool is None:\n return\n # Disable access to the pool\n old_pool, self.pool = self.pool, None\n\n # Close all the HTTPConnections in the pool.\n _close_pool_connections(old_pool)\n\n def is_same_host(self, url):\n """\n Check if the given ``url`` is a member of the same host as this\n connection pool.\n """\n if url.startswith("/"):\n return True\n\n # TODO: Add optional support for socket.gethostbyname checking.\n scheme, host, port = get_host(url)\n if host is not None:\n host = _normalize_host(host, scheme=scheme)\n\n # Use explicit default port for comparison when none is given\n if self.port and not port:\n port = port_by_scheme.get(scheme)\n elif not self.port and port == port_by_scheme.get(scheme):\n port = None\n\n return (scheme, host, port) == (self.scheme, self.host, self.port)\n\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n retries=None,\n redirect=True,\n assert_same_host=True,\n timeout=_Default,\n pool_timeout=None,\n release_conn=None,\n chunked=False,\n body_pos=None,\n **response_kw\n ):\n """\n Get a connection from the pool and perform an HTTP request. This is the\n lowest level call for making a request, so you'll need to specify all\n the raw details.\n\n .. note::\n\n More commonly, it's appropriate to use a convenience method provided\n by :class:`.RequestMethods`, such as :meth:`request`.\n\n .. note::\n\n `release_conn` will only behave as expected if\n `preload_content=False` because we want to make\n `preload_content=False` the default behaviour someday soon without\n breaking backwards compatibility.\n\n :param method:\n HTTP request method (such as GET, POST, PUT, etc.)\n\n :param url:\n The URL to perform the request on.\n\n :param body:\n Data to send in the request body, either :class:`str`, :class:`bytes`,\n an iterable of :class:`str`/:class:`bytes`, or a file-like object.\n\n :param headers:\n Dictionary of custom headers to send, such as User-Agent,\n If-None-Match, etc. If None, pool headers are used. If provided,\n these headers completely replace any pool-specific headers.\n\n :param retries:\n Configure the number of retries to allow before raising a\n :class:`~urllib3.exceptions.MaxRetryError` exception.\n\n Pass ``None`` to retry until you receive a response. Pass a\n :class:`~urllib3.util.retry.Retry` object for fine-grained control\n over different types of retries.\n Pass an integer number to retry connection errors that many times,\n but no other types of errors. Pass zero to never retry.\n\n If ``False``, then retries are disabled and any exception is raised\n immediately. Also, instead of raising a MaxRetryError on redirects,\n the redirect response will be returned.\n\n :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.\n\n :param redirect:\n If True, automatically handle redirects (status codes 301, 302,\n 303, 307, 308). Each redirect counts as a retry. Disabling retries\n will disable redirect, too.\n\n :param assert_same_host:\n If ``True``, will make sure that the host of the pool requests is\n consistent else will raise HostChangedError. When ``False``, you can\n use the pool on an HTTP proxy and request foreign hosts.\n\n :param timeout:\n If specified, overrides the default timeout for this one\n request. It may be a float (in seconds) or an instance of\n :class:`urllib3.util.Timeout`.\n\n :param pool_timeout:\n If set and the pool is set to block=True, then this method will\n block for ``pool_timeout`` seconds and raise EmptyPoolError if no\n connection is available within the time period.\n\n :param release_conn:\n If False, then the urlopen call will not release the connection\n back into the pool once a response is received (but will release if\n you read the entire contents of the response such as when\n `preload_content=True`). This is useful if you're not preloading\n the response's content immediately. You will need to call\n ``r.release_conn()`` on the response ``r`` to return the connection\n back into the pool. If None, it takes the value of\n ``response_kw.get('preload_content', True)``.\n\n :param chunked:\n If True, urllib3 will send the body using chunked transfer\n encoding. Otherwise, urllib3 will send the body using the standard\n content-length form. Defaults to False.\n\n :param int body_pos:\n Position to seek to in file-like body in the event of a retry or\n redirect. Typically this won't need to be set because urllib3 will\n auto-populate the value when needed.\n\n :param \\**response_kw:\n Additional parameters are passed to\n :meth:`urllib3.response.HTTPResponse.from_httplib`\n """\n\n parsed_url = parse_url(url)\n destination_scheme = parsed_url.scheme\n\n if headers is None:\n headers = self.headers\n\n if not isinstance(retries, Retry):\n retries = Retry.from_int(retries, redirect=redirect, default=self.retries)\n\n if release_conn is None:\n release_conn = response_kw.get("preload_content", True)\n\n # Check host\n if assert_same_host and not self.is_same_host(url):\n raise HostChangedError(self, url, retries)\n\n # Ensure that the URL we're connecting to is properly encoded\n if url.startswith("/"):\n url = six.ensure_str(_encode_target(url))\n else:\n url = six.ensure_str(parsed_url.url)\n\n conn = None\n\n # Track whether `conn` needs to be released before\n # returning/raising/recursing. Update this variable if necessary, and\n # leave `release_conn` constant throughout the function. That way, if\n # the function recurses, the original value of `release_conn` will be\n # passed down into the recursive call, and its value will be respected.\n #\n # See issue #651 [1] for details.\n #\n # [1] <https://github.com/urllib3/urllib3/issues/651>\n release_this_conn = release_conn\n\n http_tunnel_required = connection_requires_http_tunnel(\n self.proxy, self.proxy_config, destination_scheme\n )\n\n # Merge the proxy headers. Only done when not using HTTP CONNECT. We\n # have to copy the headers dict so we can safely change it without those\n # changes being reflected in anyone else's copy.\n if not http_tunnel_required:\n headers = headers.copy()\n headers.update(self.proxy_headers)\n\n # Must keep the exception bound to a separate variable or else Python 3\n # complains about UnboundLocalError.\n err = None\n\n # Keep track of whether we cleanly exited the except block. This\n # ensures we do proper cleanup in finally.\n clean_exit = False\n\n # Rewind body position, if needed. Record current position\n # for future rewinds in the event of a redirect/retry.\n body_pos = set_file_position(body, body_pos)\n\n try:\n # Request a connection from the queue.\n timeout_obj = self._get_timeout(timeout)\n conn = self._get_conn(timeout=pool_timeout)\n\n conn.timeout = timeout_obj.connect_timeout\n\n is_new_proxy_conn = self.proxy is not None and not getattr(\n conn, "sock", None\n )\n if is_new_proxy_conn and http_tunnel_required:\n self._prepare_proxy(conn)\n\n # Make the request on the httplib connection object.\n httplib_response = self._make_request(\n conn,\n method,\n url,\n timeout=timeout_obj,\n body=body,\n headers=headers,\n chunked=chunked,\n )\n\n # If we're going to release the connection in ``finally:``, then\n # the response doesn't need to know about the connection. Otherwise\n # it will also try to release it and we'll have a double-release\n # mess.\n response_conn = conn if not release_conn else None\n\n # Pass method to Response for length checking\n response_kw["request_method"] = method\n\n # Import httplib's response into our own wrapper object\n response = self.ResponseCls.from_httplib(\n httplib_response,\n pool=self,\n connection=response_conn,\n retries=retries,\n **response_kw\n )\n\n # Everything went great!\n clean_exit = True\n\n except EmptyPoolError:\n # Didn't get a connection from the pool, no need to clean up\n clean_exit = True\n release_this_conn = False\n raise\n\n except (\n TimeoutError,\n HTTPException,\n SocketError,\n ProtocolError,\n BaseSSLError,\n SSLError,\n CertificateError,\n ) as e:\n # Discard the connection for these exceptions. It will be\n # replaced during the next _get_conn() call.\n clean_exit = False\n\n def _is_ssl_error_message_from_http_proxy(ssl_error):\n # We're trying to detect the message 'WRONG_VERSION_NUMBER' but\n # SSLErrors are kinda all over the place when it comes to the message,\n # so we try to cover our bases here!\n message = " ".join(re.split("[^a-z]", str(ssl_error).lower()))\n return (\n "wrong version number" in message\n or "unknown protocol" in message\n or "record layer failure" in message\n )\n\n # Try to detect a common user error with proxies which is to\n # set an HTTP proxy to be HTTPS when it should be 'http://'\n # (ie {'http': 'http://proxy', 'https': 'https://proxy'})\n # Instead we add a nice error message and point to a URL.\n if (\n isinstance(e, BaseSSLError)\n and self.proxy\n and _is_ssl_error_message_from_http_proxy(e)\n and conn.proxy\n and conn.proxy.scheme == "https"\n ):\n e = ProxyError(\n "Your proxy appears to only use HTTP and not HTTPS, "\n "try changing your proxy URL to be HTTP. See: "\n "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"\n "#https-proxy-error-http-proxy",\n SSLError(e),\n )\n elif isinstance(e, (BaseSSLError, CertificateError)):\n e = SSLError(e)\n elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:\n e = ProxyError("Cannot connect to proxy.", e)\n elif isinstance(e, (SocketError, HTTPException)):\n e = ProtocolError("Connection aborted.", e)\n\n retries = retries.increment(\n method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]\n )\n retries.sleep()\n\n # Keep track of the error for the retry warning.\n err = e\n\n finally:\n if not clean_exit:\n # We hit some kind of exception, handled or otherwise. We need\n # to throw the connection away unless explicitly told not to.\n # Close the connection, set the variable to None, and make sure\n # we put the None back in the pool to avoid leaking it.\n conn = conn and conn.close()\n release_this_conn = True\n\n if release_this_conn:\n # Put the connection back to be reused. If the connection is\n # expired then it will be None, which will get replaced with a\n # fresh connection during _get_conn.\n self._put_conn(conn)\n\n if not conn:\n # Try again\n log.warning(\n "Retrying (%r) after connection broken by '%r': %s", retries, err, url\n )\n return self.urlopen(\n method,\n url,\n body,\n headers,\n retries,\n redirect,\n assert_same_host,\n timeout=timeout,\n pool_timeout=pool_timeout,\n release_conn=release_conn,\n chunked=chunked,\n body_pos=body_pos,\n **response_kw\n )\n\n # Handle redirect?\n redirect_location = redirect and response.get_redirect_location()\n if redirect_location:\n if response.status == 303:\n # Change the method according to RFC 9110, Section 15.4.4.\n method = "GET"\n # And lose the body not to transfer anything sensitive.\n body = None\n headers = HTTPHeaderDict(headers)._prepare_for_method_change()\n\n try:\n retries = retries.increment(method, url, response=response, _pool=self)\n except MaxRetryError:\n if retries.raise_on_redirect:\n response.drain_conn()\n raise\n return response\n\n response.drain_conn()\n retries.sleep_for_retry(response)\n log.debug("Redirecting %s -> %s", url, redirect_location)\n return self.urlopen(\n method,\n redirect_location,\n body,\n headers,\n retries=retries,\n redirect=redirect,\n assert_same_host=assert_same_host,\n timeout=timeout,\n pool_timeout=pool_timeout,\n release_conn=release_conn,\n chunked=chunked,\n body_pos=body_pos,\n **response_kw\n )\n\n # Check if we should retry the HTTP response.\n has_retry_after = bool(response.headers.get("Retry-After"))\n if retries.is_retry(method, response.status, has_retry_after):\n try:\n retries = retries.increment(method, url, response=response, _pool=self)\n except MaxRetryError:\n if retries.raise_on_status:\n response.drain_conn()\n raise\n return response\n\n response.drain_conn()\n retries.sleep(response)\n log.debug("Retry: %s", url)\n return self.urlopen(\n method,\n url,\n body,\n headers,\n retries=retries,\n redirect=redirect,\n assert_same_host=assert_same_host,\n timeout=timeout,\n pool_timeout=pool_timeout,\n release_conn=release_conn,\n chunked=chunked,\n body_pos=body_pos,\n **response_kw\n )\n\n return response\n\n\nclass HTTPSConnectionPool(HTTPConnectionPool):\n """\n Same as :class:`.HTTPConnectionPool`, but HTTPS.\n\n :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,\n ``assert_hostname`` and ``host`` in this order to verify connections.\n If ``assert_hostname`` is False, no verification is done.\n\n The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,\n ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`\n is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade\n the connection socket into an SSL socket.\n """\n\n scheme = "https"\n ConnectionCls = HTTPSConnection\n\n def __init__(\n self,\n host,\n port=None,\n strict=False,\n timeout=Timeout.DEFAULT_TIMEOUT,\n maxsize=1,\n block=False,\n headers=None,\n retries=None,\n _proxy=None,\n _proxy_headers=None,\n key_file=None,\n cert_file=None,\n cert_reqs=None,\n key_password=None,\n ca_certs=None,\n ssl_version=None,\n assert_hostname=None,\n assert_fingerprint=None,\n ca_cert_dir=None,\n **conn_kw\n ):\n\n HTTPConnectionPool.__init__(\n self,\n host,\n port,\n strict,\n timeout,\n maxsize,\n block,\n headers,\n retries,\n _proxy,\n _proxy_headers,\n **conn_kw\n )\n\n self.key_file = key_file\n self.cert_file = cert_file\n self.cert_reqs = cert_reqs\n self.key_password = key_password\n self.ca_certs = ca_certs\n self.ca_cert_dir = ca_cert_dir\n self.ssl_version = ssl_version\n self.assert_hostname = assert_hostname\n self.assert_fingerprint = assert_fingerprint\n\n def _prepare_conn(self, conn):\n """\n Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`\n and establish the tunnel if proxy is used.\n """\n\n if isinstance(conn, VerifiedHTTPSConnection):\n conn.set_cert(\n key_file=self.key_file,\n key_password=self.key_password,\n cert_file=self.cert_file,\n cert_reqs=self.cert_reqs,\n ca_certs=self.ca_certs,\n ca_cert_dir=self.ca_cert_dir,\n assert_hostname=self.assert_hostname,\n assert_fingerprint=self.assert_fingerprint,\n )\n conn.ssl_version = self.ssl_version\n return conn\n\n def _prepare_proxy(self, conn):\n """\n Establishes a tunnel connection through HTTP CONNECT.\n\n Tunnel connection is established early because otherwise httplib would\n improperly set Host: header to proxy's IP:port.\n """\n\n conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n\n if self.proxy.scheme == "https":\n conn.tls_in_tls_required = True\n\n conn.connect()\n\n def _new_conn(self):\n """\n Return a fresh :class:`http.client.HTTPSConnection`.\n """\n self.num_connections += 1\n log.debug(\n "Starting new HTTPS connection (%d): %s:%s",\n self.num_connections,\n self.host,\n self.port or "443",\n )\n\n if not self.ConnectionCls or self.ConnectionCls is DummyConnection:\n raise SSLError(\n "Can't connect to HTTPS URL because the SSL module is not available."\n )\n\n actual_host = self.host\n actual_port = self.port\n if self.proxy is not None:\n actual_host = self.proxy.host\n actual_port = self.proxy.port\n\n conn = self.ConnectionCls(\n host=actual_host,\n port=actual_port,\n timeout=self.timeout.connect_timeout,\n strict=self.strict,\n cert_file=self.cert_file,\n key_file=self.key_file,\n key_password=self.key_password,\n **self.conn_kw\n )\n\n return self._prepare_conn(conn)\n\n def _validate_conn(self, conn):\n """\n Called right before a request is made, after the socket is created.\n """\n super(HTTPSConnectionPool, self)._validate_conn(conn)\n\n # Force connect early to allow us to validate the connection.\n if not getattr(conn, "sock", None): # AppEngine might not have `.sock`\n conn.connect()\n\n if not conn.is_verified:\n warnings.warn(\n (\n "Unverified HTTPS request is being made to host '%s'. "\n "Adding certificate verification is strongly advised. See: "\n "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"\n "#ssl-warnings" % conn.host\n ),\n InsecureRequestWarning,\n )\n\n if getattr(conn, "proxy_is_verified", None) is False:\n warnings.warn(\n (\n "Unverified HTTPS connection done to an HTTPS proxy. "\n "Adding certificate verification is strongly advised. See: "\n "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"\n "#ssl-warnings"\n ),\n InsecureRequestWarning,\n )\n\n\ndef connection_from_url(url, **kw):\n """\n Given a url, return an :class:`.ConnectionPool` instance of its host.\n\n This is a shortcut for not having to parse out the scheme, host, and port\n of the url before creating an :class:`.ConnectionPool` instance.\n\n :param url:\n Absolute URL string that must include the scheme. Port is optional.\n\n :param \\**kw:\n Passes additional parameters to the constructor of the appropriate\n :class:`.ConnectionPool`. Useful for specifying things like\n timeout, maxsize, headers, etc.\n\n Example::\n\n >>> conn = connection_from_url('http://google.com/')\n >>> r = conn.request('GET', '/')\n """\n scheme, host, port = get_host(url)\n port = port or port_by_scheme.get(scheme, 80)\n if scheme == "https":\n return HTTPSConnectionPool(host, port=port, **kw)\n else:\n return HTTPConnectionPool(host, port=port, **kw)\n\n\ndef _normalize_host(host, scheme):\n """\n Normalize hosts for comparisons and use with sockets.\n """\n\n host = normalize_host(host, scheme)\n\n # httplib doesn't like it when we include brackets in IPv6 addresses\n # Specifically, if we include brackets but also pass the port then\n # httplib crazily doubles up the square brackets on the Host header.\n # Instead, we need to make sure we never pass ``None`` as the port.\n # However, for backward compatibility reasons we can't actually\n # *assert* that. See http://bugs.python.org/issue28539\n if host.startswith("[") and host.endswith("]"):\n host = host[1:-1]\n return host\n\n\ndef _close_pool_connections(pool):\n """Drains a queue of connections and closes each one."""\n try:\n while True:\n conn = pool.get(block=False)\n if conn:\n conn.close()\n except queue.Empty:\n pass # Done.\n | .venv\Lib\site-packages\pip\_vendor\urllib3\connectionpool.py | connectionpool.py | Python | 40,408 | 0.95 | 0.162281 | 0.132568 | python-kit | 844 | 2024-05-03T02:30:04.839796 | BSD-3-Clause | false | b6fece642ce3b13ae8832dbea50054ab |
from __future__ import absolute_import\n\nfrom .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead\n\n# Base Exceptions\n\n\nclass HTTPError(Exception):\n """Base exception used by this module."""\n\n pass\n\n\nclass HTTPWarning(Warning):\n """Base warning used by this module."""\n\n pass\n\n\nclass PoolError(HTTPError):\n """Base exception for errors caused within a pool."""\n\n def __init__(self, pool, message):\n self.pool = pool\n HTTPError.__init__(self, "%s: %s" % (pool, message))\n\n def __reduce__(self):\n # For pickling purposes.\n return self.__class__, (None, None)\n\n\nclass RequestError(PoolError):\n """Base exception for PoolErrors that have associated URLs."""\n\n def __init__(self, pool, url, message):\n self.url = url\n PoolError.__init__(self, pool, message)\n\n def __reduce__(self):\n # For pickling purposes.\n return self.__class__, (None, self.url, None)\n\n\nclass SSLError(HTTPError):\n """Raised when SSL certificate fails in an HTTPS connection."""\n\n pass\n\n\nclass ProxyError(HTTPError):\n """Raised when the connection to a proxy fails."""\n\n def __init__(self, message, error, *args):\n super(ProxyError, self).__init__(message, error, *args)\n self.original_error = error\n\n\nclass DecodeError(HTTPError):\n """Raised when automatic decoding based on Content-Type fails."""\n\n pass\n\n\nclass ProtocolError(HTTPError):\n """Raised when something unexpected happens mid-request/response."""\n\n pass\n\n\n#: Renamed to ProtocolError but aliased for backwards compatibility.\nConnectionError = ProtocolError\n\n\n# Leaf Exceptions\n\n\nclass MaxRetryError(RequestError):\n """Raised when the maximum number of retries is exceeded.\n\n :param pool: The connection pool\n :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n :param string url: The requested Url\n :param exceptions.Exception reason: The underlying error\n\n """\n\n def __init__(self, pool, url, reason=None):\n self.reason = reason\n\n message = "Max retries exceeded with url: %s (Caused by %r)" % (url, reason)\n\n RequestError.__init__(self, pool, url, message)\n\n\nclass HostChangedError(RequestError):\n """Raised when an existing pool gets a request for a foreign host."""\n\n def __init__(self, pool, url, retries=3):\n message = "Tried to open a foreign host with url: %s" % url\n RequestError.__init__(self, pool, url, message)\n self.retries = retries\n\n\nclass TimeoutStateError(HTTPError):\n """Raised when passing an invalid state to a timeout"""\n\n pass\n\n\nclass TimeoutError(HTTPError):\n """Raised when a socket timeout error occurs.\n\n Catching this error will catch both :exc:`ReadTimeoutErrors\n <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.\n """\n\n pass\n\n\nclass ReadTimeoutError(TimeoutError, RequestError):\n """Raised when a socket timeout occurs while receiving data from a server"""\n\n pass\n\n\n# This timeout error does not have a URL attached and needs to inherit from the\n# base HTTPError\nclass ConnectTimeoutError(TimeoutError):\n """Raised when a socket timeout occurs while connecting to a server"""\n\n pass\n\n\nclass NewConnectionError(ConnectTimeoutError, PoolError):\n """Raised when we fail to establish a new connection. Usually ECONNREFUSED."""\n\n pass\n\n\nclass EmptyPoolError(PoolError):\n """Raised when a pool runs out of connections and no more are allowed."""\n\n pass\n\n\nclass ClosedPoolError(PoolError):\n """Raised when a request enters a pool after the pool has been closed."""\n\n pass\n\n\nclass LocationValueError(ValueError, HTTPError):\n """Raised when there is something wrong with a given URL input."""\n\n pass\n\n\nclass LocationParseError(LocationValueError):\n """Raised when get_host or similar fails to parse the URL input."""\n\n def __init__(self, location):\n message = "Failed to parse: %s" % location\n HTTPError.__init__(self, message)\n\n self.location = location\n\n\nclass URLSchemeUnknown(LocationValueError):\n """Raised when a URL input has an unsupported scheme."""\n\n def __init__(self, scheme):\n message = "Not supported URL scheme %s" % scheme\n super(URLSchemeUnknown, self).__init__(message)\n\n self.scheme = scheme\n\n\nclass ResponseError(HTTPError):\n """Used as a container for an error reason supplied in a MaxRetryError."""\n\n GENERIC_ERROR = "too many error responses"\n SPECIFIC_ERROR = "too many {status_code} error responses"\n\n\nclass SecurityWarning(HTTPWarning):\n """Warned when performing security reducing actions"""\n\n pass\n\n\nclass SubjectAltNameWarning(SecurityWarning):\n """Warned when connecting to a host with a certificate missing a SAN."""\n\n pass\n\n\nclass InsecureRequestWarning(SecurityWarning):\n """Warned when making an unverified HTTPS request."""\n\n pass\n\n\nclass SystemTimeWarning(SecurityWarning):\n """Warned when system time is suspected to be wrong"""\n\n pass\n\n\nclass InsecurePlatformWarning(SecurityWarning):\n """Warned when certain TLS/SSL configuration is not available on a platform."""\n\n pass\n\n\nclass SNIMissingWarning(HTTPWarning):\n """Warned when making a HTTPS request without SNI available."""\n\n pass\n\n\nclass DependencyWarning(HTTPWarning):\n """\n Warned when an attempt is made to import a module with missing optional\n dependencies.\n """\n\n pass\n\n\nclass ResponseNotChunked(ProtocolError, ValueError):\n """Response needs to be chunked in order to read it as chunks."""\n\n pass\n\n\nclass BodyNotHttplibCompatible(HTTPError):\n """\n Body should be :class:`http.client.HTTPResponse` like\n (have an fp attribute which returns raw chunks) for read_chunked().\n """\n\n pass\n\n\nclass IncompleteRead(HTTPError, httplib_IncompleteRead):\n """\n Response length doesn't match expected Content-Length\n\n Subclass of :class:`http.client.IncompleteRead` to allow int value\n for ``partial`` to avoid creating large objects on streamed reads.\n """\n\n def __init__(self, partial, expected):\n super(IncompleteRead, self).__init__(partial, expected)\n\n def __repr__(self):\n return "IncompleteRead(%i bytes read, %i more expected)" % (\n self.partial,\n self.expected,\n )\n\n\nclass InvalidChunkLength(HTTPError, httplib_IncompleteRead):\n """Invalid chunk length in a chunked response."""\n\n def __init__(self, response, length):\n super(InvalidChunkLength, self).__init__(\n response.tell(), response.length_remaining\n )\n self.response = response\n self.length = length\n\n def __repr__(self):\n return "InvalidChunkLength(got length %r, %i bytes read)" % (\n self.length,\n self.partial,\n )\n\n\nclass InvalidHeader(HTTPError):\n """The header provided was somehow invalid."""\n\n pass\n\n\nclass ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n """ProxyManager does not support the supplied scheme"""\n\n # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n def __init__(self, scheme):\n # 'localhost' is here because our URL parser parses\n # localhost:8080 -> scheme=localhost, remove if we fix this.\n if scheme == "localhost":\n scheme = None\n if scheme is None:\n message = "Proxy URL had no scheme, should start with http:// or https://"\n else:\n message = (\n "Proxy URL had unsupported scheme %s, should use http:// or https://"\n % scheme\n )\n super(ProxySchemeUnknown, self).__init__(message)\n\n\nclass ProxySchemeUnsupported(ValueError):\n """Fetching HTTPS resources through HTTPS proxies is unsupported"""\n\n pass\n\n\nclass HeaderParsingError(HTTPError):\n """Raised by assert_header_parsing, but we convert it to a log.warning statement."""\n\n def __init__(self, defects, unparsed_data):\n message = "%s, unparsed data: %r" % (defects or "Unknown", unparsed_data)\n super(HeaderParsingError, self).__init__(message)\n\n\nclass UnrewindableBodyError(HTTPError):\n """urllib3 encountered an error when trying to rewind a body"""\n\n pass\n | .venv\Lib\site-packages\pip\_vendor\urllib3\exceptions.py | exceptions.py | Python | 8,217 | 0.95 | 0.210526 | 0.051813 | node-utils | 661 | 2025-06-08T12:08:29.850764 | Apache-2.0 | false | 8e282c0b6583235297a2b8f5d22e36d8 |
from __future__ import absolute_import\n\nimport email.utils\nimport mimetypes\nimport re\n\nfrom .packages import six\n\n\ndef guess_content_type(filename, default="application/octet-stream"):\n """\n Guess the "Content-Type" of a file.\n\n :param filename:\n The filename to guess the "Content-Type" of using :mod:`mimetypes`.\n :param default:\n If no "Content-Type" can be guessed, default to `default`.\n """\n if filename:\n return mimetypes.guess_type(filename)[0] or default\n return default\n\n\ndef format_header_param_rfc2231(name, value):\n """\n Helper function to format and quote a single header parameter using the\n strategy defined in RFC 2231.\n\n Particularly useful for header parameters which might contain\n non-ASCII values, like file names. This follows\n `RFC 2388 Section 4.4 <https://tools.ietf.org/html/rfc2388#section-4.4>`_.\n\n :param name:\n The name of the parameter, a string expected to be ASCII only.\n :param value:\n The value of the parameter, provided as ``bytes`` or `str``.\n :ret:\n An RFC-2231-formatted unicode string.\n """\n if isinstance(value, six.binary_type):\n value = value.decode("utf-8")\n\n if not any(ch in value for ch in '"\\\r\n'):\n result = u'%s="%s"' % (name, value)\n try:\n result.encode("ascii")\n except (UnicodeEncodeError, UnicodeDecodeError):\n pass\n else:\n return result\n\n if six.PY2: # Python 2:\n value = value.encode("utf-8")\n\n # encode_rfc2231 accepts an encoded string and returns an ascii-encoded\n # string in Python 2 but accepts and returns unicode strings in Python 3\n value = email.utils.encode_rfc2231(value, "utf-8")\n value = "%s*=%s" % (name, value)\n\n if six.PY2: # Python 2:\n value = value.decode("utf-8")\n\n return value\n\n\n_HTML5_REPLACEMENTS = {\n u"\u0022": u"%22",\n # Replace "\" with "\\".\n u"\u005C": u"\u005C\u005C",\n}\n\n# All control characters from 0x00 to 0x1F *except* 0x1B.\n_HTML5_REPLACEMENTS.update(\n {\n six.unichr(cc): u"%{:02X}".format(cc)\n for cc in range(0x00, 0x1F + 1)\n if cc not in (0x1B,)\n }\n)\n\n\ndef _replace_multiple(value, needles_and_replacements):\n def replacer(match):\n return needles_and_replacements[match.group(0)]\n\n pattern = re.compile(\n r"|".join([re.escape(needle) for needle in needles_and_replacements.keys()])\n )\n\n result = pattern.sub(replacer, value)\n\n return result\n\n\ndef format_header_param_html5(name, value):\n """\n Helper function to format and quote a single header parameter using the\n HTML5 strategy.\n\n Particularly useful for header parameters which might contain\n non-ASCII values, like file names. This follows the `HTML5 Working Draft\n Section 4.10.22.7`_ and matches the behavior of curl and modern browsers.\n\n .. _HTML5 Working Draft Section 4.10.22.7:\n https://w3c.github.io/html/sec-forms.html#multipart-form-data\n\n :param name:\n The name of the parameter, a string expected to be ASCII only.\n :param value:\n The value of the parameter, provided as ``bytes`` or `str``.\n :ret:\n A unicode string, stripped of troublesome characters.\n """\n if isinstance(value, six.binary_type):\n value = value.decode("utf-8")\n\n value = _replace_multiple(value, _HTML5_REPLACEMENTS)\n\n return u'%s="%s"' % (name, value)\n\n\n# For backwards-compatibility.\nformat_header_param = format_header_param_html5\n\n\nclass RequestField(object):\n """\n A data container for request body parameters.\n\n :param name:\n The name of this request field. Must be unicode.\n :param data:\n The data/value body.\n :param filename:\n An optional filename of the request field. Must be unicode.\n :param headers:\n An optional dict-like object of headers to initially use for the field.\n :param header_formatter:\n An optional callable that is used to encode and format the headers. By\n default, this is :func:`format_header_param_html5`.\n """\n\n def __init__(\n self,\n name,\n data,\n filename=None,\n headers=None,\n header_formatter=format_header_param_html5,\n ):\n self._name = name\n self._filename = filename\n self.data = data\n self.headers = {}\n if headers:\n self.headers = dict(headers)\n self.header_formatter = header_formatter\n\n @classmethod\n def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5):\n """\n A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n Supports constructing :class:`~urllib3.fields.RequestField` from\n parameter of key/value strings AND key/filetuple. A filetuple is a\n (filename, data, MIME type) tuple where the MIME type is optional.\n For example::\n\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n\n Field names and filenames must be unicode.\n """\n if isinstance(value, tuple):\n if len(value) == 3:\n filename, data, content_type = value\n else:\n filename, data = value\n content_type = guess_content_type(filename)\n else:\n filename = None\n content_type = None\n data = value\n\n request_param = cls(\n fieldname, data, filename=filename, header_formatter=header_formatter\n )\n request_param.make_multipart(content_type=content_type)\n\n return request_param\n\n def _render_part(self, name, value):\n """\n Overridable helper function to format a single header parameter. By\n default, this calls ``self.header_formatter``.\n\n :param name:\n The name of the parameter, a string expected to be ASCII only.\n :param value:\n The value of the parameter, provided as a unicode string.\n """\n\n return self.header_formatter(name, value)\n\n def _render_parts(self, header_parts):\n """\n Helper function to format and quote a single header.\n\n Useful for single headers that are composed of multiple items. E.g.,\n 'Content-Disposition' fields.\n\n :param header_parts:\n A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format\n as `k1="v1"; k2="v2"; ...`.\n """\n parts = []\n iterable = header_parts\n if isinstance(header_parts, dict):\n iterable = header_parts.items()\n\n for name, value in iterable:\n if value is not None:\n parts.append(self._render_part(name, value))\n\n return u"; ".join(parts)\n\n def render_headers(self):\n """\n Renders the headers for this request field.\n """\n lines = []\n\n sort_keys = ["Content-Disposition", "Content-Type", "Content-Location"]\n for sort_key in sort_keys:\n if self.headers.get(sort_key, False):\n lines.append(u"%s: %s" % (sort_key, self.headers[sort_key]))\n\n for header_name, header_value in self.headers.items():\n if header_name not in sort_keys:\n if header_value:\n lines.append(u"%s: %s" % (header_name, header_value))\n\n lines.append(u"\r\n")\n return u"\r\n".join(lines)\n\n def make_multipart(\n self, content_disposition=None, content_type=None, content_location=None\n ):\n """\n Makes this request field into a multipart request field.\n\n This method overrides "Content-Disposition", "Content-Type" and\n "Content-Location" headers to the request parameter.\n\n :param content_type:\n The 'Content-Type' of the request body.\n :param content_location:\n The 'Content-Location' of the request body.\n\n """\n self.headers["Content-Disposition"] = content_disposition or u"form-data"\n self.headers["Content-Disposition"] += u"; ".join(\n [\n u"",\n self._render_parts(\n ((u"name", self._name), (u"filename", self._filename))\n ),\n ]\n )\n self.headers["Content-Type"] = content_type\n self.headers["Content-Location"] = content_location\n | .venv\Lib\site-packages\pip\_vendor\urllib3\fields.py | fields.py | Python | 8,579 | 0.95 | 0.171533 | 0.023041 | vue-tools | 875 | 2024-09-27T14:03:59.397184 | BSD-3-Clause | false | 93a2dc0508cf5901177f051f86d71c48 |
from __future__ import absolute_import\n\nimport binascii\nimport codecs\nimport os\nfrom io import BytesIO\n\nfrom .fields import RequestField\nfrom .packages import six\nfrom .packages.six import b\n\nwriter = codecs.lookup("utf-8")[3]\n\n\ndef choose_boundary():\n """\n Our embarrassingly-simple replacement for mimetools.choose_boundary.\n """\n boundary = binascii.hexlify(os.urandom(16))\n if not six.PY2:\n boundary = boundary.decode("ascii")\n return boundary\n\n\ndef iter_field_objects(fields):\n """\n Iterate over fields.\n\n Supports list of (k, v) tuples and dicts, and lists of\n :class:`~urllib3.fields.RequestField`.\n\n """\n if isinstance(fields, dict):\n i = six.iteritems(fields)\n else:\n i = iter(fields)\n\n for field in i:\n if isinstance(field, RequestField):\n yield field\n else:\n yield RequestField.from_tuples(*field)\n\n\ndef iter_fields(fields):\n """\n .. deprecated:: 1.6\n\n Iterate over fields.\n\n The addition of :class:`~urllib3.fields.RequestField` makes this function\n obsolete. Instead, use :func:`iter_field_objects`, which returns\n :class:`~urllib3.fields.RequestField` objects.\n\n Supports list of (k, v) tuples and dicts.\n """\n if isinstance(fields, dict):\n return ((k, v) for k, v in six.iteritems(fields))\n\n return ((k, v) for k, v in fields)\n\n\ndef encode_multipart_formdata(fields, boundary=None):\n """\n Encode a dictionary of ``fields`` using the multipart/form-data MIME format.\n\n :param fields:\n Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).\n\n :param boundary:\n If not specified, then a random boundary will be generated using\n :func:`urllib3.filepost.choose_boundary`.\n """\n body = BytesIO()\n if boundary is None:\n boundary = choose_boundary()\n\n for field in iter_field_objects(fields):\n body.write(b("--%s\r\n" % (boundary)))\n\n writer(body).write(field.render_headers())\n data = field.data\n\n if isinstance(data, int):\n data = str(data) # Backwards compatibility\n\n if isinstance(data, six.text_type):\n writer(body).write(data)\n else:\n body.write(data)\n\n body.write(b"\r\n")\n\n body.write(b("--%s--\r\n" % (boundary)))\n\n content_type = str("multipart/form-data; boundary=%s" % boundary)\n\n return body.getvalue(), content_type\n | .venv\Lib\site-packages\pip\_vendor\urllib3\filepost.py | filepost.py | Python | 2,440 | 0.95 | 0.214286 | 0 | awesome-app | 889 | 2023-12-01T05:40:38.421732 | Apache-2.0 | false | 2ea9f2fe3c06a4a560bc1db53881d209 |
from __future__ import absolute_import\n\nimport collections\nimport functools\nimport logging\n\nfrom ._collections import HTTPHeaderDict, RecentlyUsedContainer\nfrom .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme\nfrom .exceptions import (\n LocationValueError,\n MaxRetryError,\n ProxySchemeUnknown,\n ProxySchemeUnsupported,\n URLSchemeUnknown,\n)\nfrom .packages import six\nfrom .packages.six.moves.urllib.parse import urljoin\nfrom .request import RequestMethods\nfrom .util.proxy import connection_requires_http_tunnel\nfrom .util.retry import Retry\nfrom .util.url import parse_url\n\n__all__ = ["PoolManager", "ProxyManager", "proxy_from_url"]\n\n\nlog = logging.getLogger(__name__)\n\nSSL_KEYWORDS = (\n "key_file",\n "cert_file",\n "cert_reqs",\n "ca_certs",\n "ssl_version",\n "ca_cert_dir",\n "ssl_context",\n "key_password",\n "server_hostname",\n)\n\n# All known keyword arguments that could be provided to the pool manager, its\n# pools, or the underlying connections. This is used to construct a pool key.\n_key_fields = (\n "key_scheme", # str\n "key_host", # str\n "key_port", # int\n "key_timeout", # int or float or Timeout\n "key_retries", # int or Retry\n "key_strict", # bool\n "key_block", # bool\n "key_source_address", # str\n "key_key_file", # str\n "key_key_password", # str\n "key_cert_file", # str\n "key_cert_reqs", # str\n "key_ca_certs", # str\n "key_ssl_version", # str\n "key_ca_cert_dir", # str\n "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext\n "key_maxsize", # int\n "key_headers", # dict\n "key__proxy", # parsed proxy url\n "key__proxy_headers", # dict\n "key__proxy_config", # class\n "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples\n "key__socks_options", # dict\n "key_assert_hostname", # bool or string\n "key_assert_fingerprint", # str\n "key_server_hostname", # str\n)\n\n#: The namedtuple class used to construct keys for the connection pool.\n#: All custom key schemes should include the fields in this key at a minimum.\nPoolKey = collections.namedtuple("PoolKey", _key_fields)\n\n_proxy_config_fields = ("ssl_context", "use_forwarding_for_https")\nProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields)\n\n\ndef _default_key_normalizer(key_class, request_context):\n """\n Create a pool key out of a request context dictionary.\n\n According to RFC 3986, both the scheme and host are case-insensitive.\n Therefore, this function normalizes both before constructing the pool\n key for an HTTPS request. If you wish to change this behaviour, provide\n alternate callables to ``key_fn_by_scheme``.\n\n :param key_class:\n The class to use when constructing the key. This should be a namedtuple\n with the ``scheme`` and ``host`` keys at a minimum.\n :type key_class: namedtuple\n :param request_context:\n A dictionary-like object that contain the context for a request.\n :type request_context: dict\n\n :return: A namedtuple that can be used as a connection pool key.\n :rtype: PoolKey\n """\n # Since we mutate the dictionary, make a copy first\n context = request_context.copy()\n context["scheme"] = context["scheme"].lower()\n context["host"] = context["host"].lower()\n\n # These are both dictionaries and need to be transformed into frozensets\n for key in ("headers", "_proxy_headers", "_socks_options"):\n if key in context and context[key] is not None:\n context[key] = frozenset(context[key].items())\n\n # The socket_options key may be a list and needs to be transformed into a\n # tuple.\n socket_opts = context.get("socket_options")\n if socket_opts is not None:\n context["socket_options"] = tuple(socket_opts)\n\n # Map the kwargs to the names in the namedtuple - this is necessary since\n # namedtuples can't have fields starting with '_'.\n for key in list(context.keys()):\n context["key_" + key] = context.pop(key)\n\n # Default to ``None`` for keys missing from the context\n for field in key_class._fields:\n if field not in context:\n context[field] = None\n\n return key_class(**context)\n\n\n#: A dictionary that maps a scheme to a callable that creates a pool key.\n#: This can be used to alter the way pool keys are constructed, if desired.\n#: Each PoolManager makes a copy of this dictionary so they can be configured\n#: globally here, or individually on the instance.\nkey_fn_by_scheme = {\n "http": functools.partial(_default_key_normalizer, PoolKey),\n "https": functools.partial(_default_key_normalizer, PoolKey),\n}\n\npool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool}\n\n\nclass PoolManager(RequestMethods):\n """\n Allows for arbitrary requests while transparently keeping track of\n necessary connection pools for you.\n\n :param num_pools:\n Number of connection pools to cache before discarding the least\n recently used pool.\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n\n :param \\**connection_pool_kw:\n Additional parameters are used to create fresh\n :class:`urllib3.connectionpool.ConnectionPool` instances.\n\n Example::\n\n >>> manager = PoolManager(num_pools=2)\n >>> r = manager.request('GET', 'http://google.com/')\n >>> r = manager.request('GET', 'http://google.com/mail')\n >>> r = manager.request('GET', 'http://yahoo.com/')\n >>> len(manager.pools)\n 2\n\n """\n\n proxy = None\n proxy_config = None\n\n def __init__(self, num_pools=10, headers=None, **connection_pool_kw):\n RequestMethods.__init__(self, headers)\n self.connection_pool_kw = connection_pool_kw\n self.pools = RecentlyUsedContainer(num_pools)\n\n # Locally set the pool classes and keys so other PoolManagers can\n # override them.\n self.pool_classes_by_scheme = pool_classes_by_scheme\n self.key_fn_by_scheme = key_fn_by_scheme.copy()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.clear()\n # Return False to re-raise any potential exceptions\n return False\n\n def _new_pool(self, scheme, host, port, request_context=None):\n """\n Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and\n any additional pool keyword arguments.\n\n If ``request_context`` is provided, it is provided as keyword arguments\n to the pool class used. This method is used to actually create the\n connection pools handed out by :meth:`connection_from_url` and\n companion methods. It is intended to be overridden for customization.\n """\n pool_cls = self.pool_classes_by_scheme[scheme]\n if request_context is None:\n request_context = self.connection_pool_kw.copy()\n\n # Although the context has everything necessary to create the pool,\n # this function has historically only used the scheme, host, and port\n # in the positional args. When an API change is acceptable these can\n # be removed.\n for key in ("scheme", "host", "port"):\n request_context.pop(key, None)\n\n if scheme == "http":\n for kw in SSL_KEYWORDS:\n request_context.pop(kw, None)\n\n return pool_cls(host, port, **request_context)\n\n def clear(self):\n """\n Empty our store of pools and direct them all to close.\n\n This will not affect in-flight connections, but they will not be\n re-used after completion.\n """\n self.pools.clear()\n\n def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None):\n """\n Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.\n\n If ``port`` isn't given, it will be derived from the ``scheme`` using\n ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is\n provided, it is merged with the instance's ``connection_pool_kw``\n variable and used to create the new connection pool, if one is\n needed.\n """\n\n if not host:\n raise LocationValueError("No host specified.")\n\n request_context = self._merge_pool_kwargs(pool_kwargs)\n request_context["scheme"] = scheme or "http"\n if not port:\n port = port_by_scheme.get(request_context["scheme"].lower(), 80)\n request_context["port"] = port\n request_context["host"] = host\n\n return self.connection_from_context(request_context)\n\n def connection_from_context(self, request_context):\n """\n Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.\n\n ``request_context`` must at least contain the ``scheme`` key and its\n value must be a key in ``key_fn_by_scheme`` instance variable.\n """\n scheme = request_context["scheme"].lower()\n pool_key_constructor = self.key_fn_by_scheme.get(scheme)\n if not pool_key_constructor:\n raise URLSchemeUnknown(scheme)\n pool_key = pool_key_constructor(request_context)\n\n return self.connection_from_pool_key(pool_key, request_context=request_context)\n\n def connection_from_pool_key(self, pool_key, request_context=None):\n """\n Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.\n\n ``pool_key`` should be a namedtuple that only contains immutable\n objects. At a minimum it must have the ``scheme``, ``host``, and\n ``port`` fields.\n """\n with self.pools.lock:\n # If the scheme, host, or port doesn't match existing open\n # connections, open a new ConnectionPool.\n pool = self.pools.get(pool_key)\n if pool:\n return pool\n\n # Make a fresh ConnectionPool of the desired type\n scheme = request_context["scheme"]\n host = request_context["host"]\n port = request_context["port"]\n pool = self._new_pool(scheme, host, port, request_context=request_context)\n self.pools[pool_key] = pool\n\n return pool\n\n def connection_from_url(self, url, pool_kwargs=None):\n """\n Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n If ``pool_kwargs`` is not provided and a new pool needs to be\n constructed, ``self.connection_pool_kw`` is used to initialize\n the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n is provided, it is used instead. Note that if a new pool does not\n need to be created for the request, the provided ``pool_kwargs`` are\n not used.\n """\n u = parse_url(url)\n return self.connection_from_host(\n u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n )\n\n def _merge_pool_kwargs(self, override):\n """\n Merge a dictionary of override values for self.connection_pool_kw.\n\n This does not modify self.connection_pool_kw and returns a new dict.\n Any keys in the override dictionary with a value of ``None`` are\n removed from the merged dictionary.\n """\n base_pool_kwargs = self.connection_pool_kw.copy()\n if override:\n for key, value in override.items():\n if value is None:\n try:\n del base_pool_kwargs[key]\n except KeyError:\n pass\n else:\n base_pool_kwargs[key] = value\n return base_pool_kwargs\n\n def _proxy_requires_url_absolute_form(self, parsed_url):\n """\n Indicates if the proxy requires the complete destination URL in the\n request. Normally this is only needed when not using an HTTP CONNECT\n tunnel.\n """\n if self.proxy is None:\n return False\n\n return not connection_requires_http_tunnel(\n self.proxy, self.proxy_config, parsed_url.scheme\n )\n\n def _validate_proxy_scheme_url_selection(self, url_scheme):\n """\n Validates that were not attempting to do TLS in TLS connections on\n Python2 or with unsupported SSL implementations.\n """\n if self.proxy is None or url_scheme != "https":\n return\n\n if self.proxy.scheme != "https":\n return\n\n if six.PY2 and not self.proxy_config.use_forwarding_for_https:\n raise ProxySchemeUnsupported(\n "Contacting HTTPS destinations through HTTPS proxies "\n "'via CONNECT tunnels' is not supported in Python 2"\n )\n\n def urlopen(self, method, url, redirect=True, **kw):\n """\n Same as :meth:`urllib3.HTTPConnectionPool.urlopen`\n with custom cross-host redirect logic and only sends the request-uri\n portion of the ``url``.\n\n The given ``url`` parameter must be absolute, such that an appropriate\n :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.\n """\n u = parse_url(url)\n self._validate_proxy_scheme_url_selection(u.scheme)\n\n conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)\n\n kw["assert_same_host"] = False\n kw["redirect"] = False\n\n if "headers" not in kw:\n kw["headers"] = self.headers.copy()\n\n if self._proxy_requires_url_absolute_form(u):\n response = conn.urlopen(method, url, **kw)\n else:\n response = conn.urlopen(method, u.request_uri, **kw)\n\n redirect_location = redirect and response.get_redirect_location()\n if not redirect_location:\n return response\n\n # Support relative URLs for redirecting.\n redirect_location = urljoin(url, redirect_location)\n\n if response.status == 303:\n # Change the method according to RFC 9110, Section 15.4.4.\n method = "GET"\n # And lose the body not to transfer anything sensitive.\n kw["body"] = None\n kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change()\n\n retries = kw.get("retries")\n if not isinstance(retries, Retry):\n retries = Retry.from_int(retries, redirect=redirect)\n\n # Strip headers marked as unsafe to forward to the redirected location.\n # Check remove_headers_on_redirect to avoid a potential network call within\n # conn.is_same_host() which may use socket.gethostbyname() in the future.\n if retries.remove_headers_on_redirect and not conn.is_same_host(\n redirect_location\n ):\n headers = list(six.iterkeys(kw["headers"]))\n for header in headers:\n if header.lower() in retries.remove_headers_on_redirect:\n kw["headers"].pop(header, None)\n\n try:\n retries = retries.increment(method, url, response=response, _pool=conn)\n except MaxRetryError:\n if retries.raise_on_redirect:\n response.drain_conn()\n raise\n return response\n\n kw["retries"] = retries\n kw["redirect"] = redirect\n\n log.info("Redirecting %s -> %s", url, redirect_location)\n\n response.drain_conn()\n return self.urlopen(method, redirect_location, **kw)\n\n\nclass ProxyManager(PoolManager):\n """\n Behaves just like :class:`PoolManager`, but sends all requests through\n the defined proxy, using the CONNECT method for HTTPS URLs.\n\n :param proxy_url:\n The URL of the proxy to be used.\n\n :param proxy_headers:\n A dictionary containing headers that will be sent to the proxy. In case\n of HTTP they are being sent with each request, while in the\n HTTPS/CONNECT case they are sent only once. Could be used for proxy\n authentication.\n\n :param proxy_ssl_context:\n The proxy SSL context is used to establish the TLS connection to the\n proxy when using HTTPS proxies.\n\n :param use_forwarding_for_https:\n (Defaults to False) If set to True will forward requests to the HTTPS\n proxy to be made on behalf of the client instead of creating a TLS\n tunnel via the CONNECT method. **Enabling this flag means that request\n and response headers and content will be visible from the HTTPS proxy**\n whereas tunneling keeps request and response headers and content\n private. IP address, target hostname, SNI, and port are always visible\n to an HTTPS proxy even when this flag is disabled.\n\n Example:\n >>> proxy = urllib3.ProxyManager('http://localhost:3128/')\n >>> r1 = proxy.request('GET', 'http://google.com/')\n >>> r2 = proxy.request('GET', 'http://httpbin.org/')\n >>> len(proxy.pools)\n 1\n >>> r3 = proxy.request('GET', 'https://httpbin.org/')\n >>> r4 = proxy.request('GET', 'https://twitter.com/')\n >>> len(proxy.pools)\n 3\n\n """\n\n def __init__(\n self,\n proxy_url,\n num_pools=10,\n headers=None,\n proxy_headers=None,\n proxy_ssl_context=None,\n use_forwarding_for_https=False,\n **connection_pool_kw\n ):\n\n if isinstance(proxy_url, HTTPConnectionPool):\n proxy_url = "%s://%s:%i" % (\n proxy_url.scheme,\n proxy_url.host,\n proxy_url.port,\n )\n proxy = parse_url(proxy_url)\n\n if proxy.scheme not in ("http", "https"):\n raise ProxySchemeUnknown(proxy.scheme)\n\n if not proxy.port:\n port = port_by_scheme.get(proxy.scheme, 80)\n proxy = proxy._replace(port=port)\n\n self.proxy = proxy\n self.proxy_headers = proxy_headers or {}\n self.proxy_ssl_context = proxy_ssl_context\n self.proxy_config = ProxyConfig(proxy_ssl_context, use_forwarding_for_https)\n\n connection_pool_kw["_proxy"] = self.proxy\n connection_pool_kw["_proxy_headers"] = self.proxy_headers\n connection_pool_kw["_proxy_config"] = self.proxy_config\n\n super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw)\n\n def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None):\n if scheme == "https":\n return super(ProxyManager, self).connection_from_host(\n host, port, scheme, pool_kwargs=pool_kwargs\n )\n\n return super(ProxyManager, self).connection_from_host(\n self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs\n )\n\n def _set_proxy_headers(self, url, headers=None):\n """\n Sets headers needed by proxies: specifically, the Accept and Host\n headers. Only sets headers not provided by the user.\n """\n headers_ = {"Accept": "*/*"}\n\n netloc = parse_url(url).netloc\n if netloc:\n headers_["Host"] = netloc\n\n if headers:\n headers_.update(headers)\n return headers_\n\n def urlopen(self, method, url, redirect=True, **kw):\n "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."\n u = parse_url(url)\n if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme):\n # For connections using HTTP CONNECT, httplib sets the necessary\n # headers on the CONNECT to the proxy. If we're not using CONNECT,\n # we'll definitely need to set 'Host' at the very least.\n headers = kw.get("headers", self.headers)\n kw["headers"] = self._set_proxy_headers(url, headers)\n\n return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)\n\n\ndef proxy_from_url(url, **kw):\n return ProxyManager(proxy_url=url, **kw)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\poolmanager.py | poolmanager.py | Python | 19,990 | 0.95 | 0.172222 | 0.079909 | python-kit | 905 | 2025-01-16T12:50:04.786484 | Apache-2.0 | false | e258ab468f27d080ce2b552bcafdcbfa |
from __future__ import absolute_import\n\nimport sys\n\nfrom .filepost import encode_multipart_formdata\nfrom .packages import six\nfrom .packages.six.moves.urllib.parse import urlencode\n\n__all__ = ["RequestMethods"]\n\n\nclass RequestMethods(object):\n """\n Convenience mixin for classes who implement a :meth:`urlopen` method, such\n as :class:`urllib3.HTTPConnectionPool` and\n :class:`urllib3.PoolManager`.\n\n Provides behavior for making common types of HTTP request methods and\n decides which type of request field encoding to use.\n\n Specifically,\n\n :meth:`.request_encode_url` is for sending requests whose fields are\n encoded in the URL (such as GET, HEAD, DELETE).\n\n :meth:`.request_encode_body` is for sending requests whose fields are\n encoded in the *body* of the request using multipart or www-form-urlencoded\n (such as for POST, PUT, PATCH).\n\n :meth:`.request` is for making any kind of request, it will look up the\n appropriate encoding format and use one of the above two methods to make\n the request.\n\n Initializer parameters:\n\n :param headers:\n Headers to include with all requests, unless other headers are given\n explicitly.\n """\n\n _encode_url_methods = {"DELETE", "GET", "HEAD", "OPTIONS"}\n\n def __init__(self, headers=None):\n self.headers = headers or {}\n\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n encode_multipart=True,\n multipart_boundary=None,\n **kw\n ): # Abstract\n raise NotImplementedError(\n "Classes extending RequestMethods must implement "\n "their own ``urlopen`` method."\n )\n\n def request(self, method, url, fields=None, headers=None, **urlopen_kw):\n """\n Make a request using :meth:`urlopen` with the appropriate encoding of\n ``fields`` based on the ``method`` used.\n\n This is a convenience method that requires the least amount of manual\n effort. It can be used in most situations, while still having the\n option to drop down to more specific methods when necessary, such as\n :meth:`request_encode_url`, :meth:`request_encode_body`,\n or even the lowest level :meth:`urlopen`.\n """\n method = method.upper()\n\n urlopen_kw["request_url"] = url\n\n if method in self._encode_url_methods:\n return self.request_encode_url(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n else:\n return self.request_encode_body(\n method, url, fields=fields, headers=headers, **urlopen_kw\n )\n\n def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):\n """\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n """\n if headers is None:\n headers = self.headers\n\n extra_kw = {"headers": headers}\n extra_kw.update(urlopen_kw)\n\n if fields:\n url += "?" + urlencode(fields)\n\n return self.urlopen(method, url, **extra_kw)\n\n def request_encode_body(\n self,\n method,\n url,\n fields=None,\n headers=None,\n encode_multipart=True,\n multipart_boundary=None,\n **urlopen_kw\n ):\n """\n Make a request using :meth:`urlopen` with the ``fields`` encoded in\n the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n When ``encode_multipart=True`` (default), then\n :func:`urllib3.encode_multipart_formdata` is used to encode\n the payload with the appropriate content type. Otherwise\n :func:`urllib.parse.urlencode` is used with the\n 'application/x-www-form-urlencoded' content type.\n\n Multipart encoding must be used when posting files, and it's reasonably\n safe to use it in other times too. However, it may break request\n signing, such as with OAuth.\n\n Supports an optional ``fields`` parameter of key/value strings AND\n key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n the MIME type is optional. For example::\n\n fields = {\n 'foo': 'bar',\n 'fakefile': ('foofile.txt', 'contents of foofile'),\n 'realfile': ('barfile.txt', open('realfile').read()),\n 'typedfile': ('bazfile.bin', open('bazfile').read(),\n 'image/jpeg'),\n 'nonamefile': 'contents of nonamefile field',\n }\n\n When uploading a file, providing a filename (the first parameter of the\n tuple) is optional but recommended to best mimic behavior of browsers.\n\n Note that if ``headers`` are supplied, the 'Content-Type' header will\n be overwritten because it depends on the dynamic random boundary string\n which is used to compose the body of the request. The random boundary\n string can be explicitly set with the ``multipart_boundary`` parameter.\n """\n if headers is None:\n headers = self.headers\n\n extra_kw = {"headers": {}}\n\n if fields:\n if "body" in urlopen_kw:\n raise TypeError(\n "request got values for both 'fields' and 'body', can only specify one."\n )\n\n if encode_multipart:\n body, content_type = encode_multipart_formdata(\n fields, boundary=multipart_boundary\n )\n else:\n body, content_type = (\n urlencode(fields),\n "application/x-www-form-urlencoded",\n )\n\n extra_kw["body"] = body\n extra_kw["headers"] = {"Content-Type": content_type}\n\n extra_kw["headers"].update(headers)\n extra_kw.update(urlopen_kw)\n\n return self.urlopen(method, url, **extra_kw)\n\n\nif not six.PY2:\n\n class RequestModule(sys.modules[__name__].__class__):\n def __call__(self, *args, **kwargs):\n """\n If user tries to call this module directly urllib3 v2.x style raise an error to the user\n suggesting they may need urllib3 v2\n """\n raise TypeError(\n "'module' object is not callable\n"\n "urllib3.request() method is not supported in this release, "\n "upgrade to urllib3 v2 to use it\n"\n "see https://urllib3.readthedocs.io/en/stable/v2-migration-guide.html"\n )\n\n sys.modules[__name__].__class__ = RequestModule\n | .venv\Lib\site-packages\pip\_vendor\urllib3\request.py | request.py | Python | 6,691 | 0.95 | 0.151832 | 0.013245 | vue-tools | 493 | 2023-08-20T10:34:32.458077 | Apache-2.0 | false | ade432a79c6ddab6cec8a19ceb7726f0 |
from __future__ import absolute_import\n\nimport io\nimport logging\nimport sys\nimport warnings\nimport zlib\nfrom contextlib import contextmanager\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nbrotli = None\n\nfrom . import util\nfrom ._collections import HTTPHeaderDict\nfrom .connection import BaseSSLError, HTTPException\nfrom .exceptions import (\n BodyNotHttplibCompatible,\n DecodeError,\n HTTPError,\n IncompleteRead,\n InvalidChunkLength,\n InvalidHeader,\n ProtocolError,\n ReadTimeoutError,\n ResponseNotChunked,\n SSLError,\n)\nfrom .packages import six\nfrom .util.response import is_fp_closed, is_response_to_head\n\nlog = logging.getLogger(__name__)\n\n\nclass DeflateDecoder(object):\n def __init__(self):\n self._first_try = True\n self._data = b""\n self._obj = zlib.decompressobj()\n\n def __getattr__(self, name):\n return getattr(self._obj, name)\n\n def decompress(self, data):\n if not data:\n return data\n\n if not self._first_try:\n return self._obj.decompress(data)\n\n self._data += data\n try:\n decompressed = self._obj.decompress(data)\n if decompressed:\n self._first_try = False\n self._data = None\n return decompressed\n except zlib.error:\n self._first_try = False\n self._obj = zlib.decompressobj(-zlib.MAX_WBITS)\n try:\n return self.decompress(self._data)\n finally:\n self._data = None\n\n\nclass GzipDecoderState(object):\n\n FIRST_MEMBER = 0\n OTHER_MEMBERS = 1\n SWALLOW_DATA = 2\n\n\nclass GzipDecoder(object):\n def __init__(self):\n self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n self._state = GzipDecoderState.FIRST_MEMBER\n\n def __getattr__(self, name):\n return getattr(self._obj, name)\n\n def decompress(self, data):\n ret = bytearray()\n if self._state == GzipDecoderState.SWALLOW_DATA or not data:\n return bytes(ret)\n while True:\n try:\n ret += self._obj.decompress(data)\n except zlib.error:\n previous_state = self._state\n # Ignore data after the first error\n self._state = GzipDecoderState.SWALLOW_DATA\n if previous_state == GzipDecoderState.OTHER_MEMBERS:\n # Allow trailing garbage acceptable in other gzip clients\n return bytes(ret)\n raise\n data = self._obj.unused_data\n if not data:\n return bytes(ret)\n self._state = GzipDecoderState.OTHER_MEMBERS\n self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n\nif brotli is not None:\n\n class BrotliDecoder(object):\n # Supports both 'brotlipy' and 'Brotli' packages\n # since they share an import name. The top branches\n # are for 'brotlipy' and bottom branches for 'Brotli'\n def __init__(self):\n self._obj = brotli.Decompressor()\n if hasattr(self._obj, "decompress"):\n self.decompress = self._obj.decompress\n else:\n self.decompress = self._obj.process\n\n def flush(self):\n if hasattr(self._obj, "flush"):\n return self._obj.flush()\n return b""\n\n\nclass MultiDecoder(object):\n """\n From RFC7231:\n If one or more encodings have been applied to a representation, the\n sender that applied the encodings MUST generate a Content-Encoding\n header field that lists the content codings in the order in which\n they were applied.\n """\n\n def __init__(self, modes):\n self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")]\n\n def flush(self):\n return self._decoders[0].flush()\n\n def decompress(self, data):\n for d in reversed(self._decoders):\n data = d.decompress(data)\n return data\n\n\ndef _get_decoder(mode):\n if "," in mode:\n return MultiDecoder(mode)\n\n if mode == "gzip":\n return GzipDecoder()\n\n if brotli is not None and mode == "br":\n return BrotliDecoder()\n\n return DeflateDecoder()\n\n\nclass HTTPResponse(io.IOBase):\n """\n HTTP Response container.\n\n Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is\n loaded and decoded on-demand when the ``data`` property is accessed. This\n class is also compatible with the Python standard library's :mod:`io`\n module, and can hence be treated as a readable object in the context of that\n framework.\n\n Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:\n\n :param preload_content:\n If True, the response's body will be preloaded during construction.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n\n :param original_response:\n When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`\n object, it's convenient to include the original for debug purposes. It's\n otherwise unused.\n\n :param retries:\n The retries contains the last :class:`~urllib3.util.retry.Retry` that\n was used during the request.\n\n :param enforce_content_length:\n Enforce content length checking. Body returned by server must match\n value of Content-Length header, if present. Otherwise, raise error.\n """\n\n CONTENT_DECODERS = ["gzip", "deflate"]\n if brotli is not None:\n CONTENT_DECODERS += ["br"]\n REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n def __init__(\n self,\n body="",\n headers=None,\n status=0,\n version=0,\n reason=None,\n strict=0,\n preload_content=True,\n decode_content=True,\n original_response=None,\n pool=None,\n connection=None,\n msg=None,\n retries=None,\n enforce_content_length=False,\n request_method=None,\n request_url=None,\n auto_close=True,\n ):\n\n if isinstance(headers, HTTPHeaderDict):\n self.headers = headers\n else:\n self.headers = HTTPHeaderDict(headers)\n self.status = status\n self.version = version\n self.reason = reason\n self.strict = strict\n self.decode_content = decode_content\n self.retries = retries\n self.enforce_content_length = enforce_content_length\n self.auto_close = auto_close\n\n self._decoder = None\n self._body = None\n self._fp = None\n self._original_response = original_response\n self._fp_bytes_read = 0\n self.msg = msg\n self._request_url = request_url\n\n if body and isinstance(body, (six.string_types, bytes)):\n self._body = body\n\n self._pool = pool\n self._connection = connection\n\n if hasattr(body, "read"):\n self._fp = body\n\n # Are we using the chunked-style of transfer encoding?\n self.chunked = False\n self.chunk_left = None\n tr_enc = self.headers.get("transfer-encoding", "").lower()\n # Don't incur the penalty of creating a list and then discarding it\n encodings = (enc.strip() for enc in tr_enc.split(","))\n if "chunked" in encodings:\n self.chunked = True\n\n # Determine length of response\n self.length_remaining = self._init_length(request_method)\n\n # If requested, preload the body.\n if preload_content and not self._body:\n self._body = self.read(decode_content=decode_content)\n\n def get_redirect_location(self):\n """\n Should we redirect and where to?\n\n :returns: Truthy redirect location string if we got a redirect status\n code and valid location. ``None`` if redirect status and no\n location. ``False`` if not a redirect status code.\n """\n if self.status in self.REDIRECT_STATUSES:\n return self.headers.get("location")\n\n return False\n\n def release_conn(self):\n if not self._pool or not self._connection:\n return\n\n self._pool._put_conn(self._connection)\n self._connection = None\n\n def drain_conn(self):\n """\n Read and discard any remaining HTTP response data in the response connection.\n\n Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.\n """\n try:\n self.read()\n except (HTTPError, SocketError, BaseSSLError, HTTPException):\n pass\n\n @property\n def data(self):\n # For backwards-compat with earlier urllib3 0.4 and earlier.\n if self._body:\n return self._body\n\n if self._fp:\n return self.read(cache_content=True)\n\n @property\n def connection(self):\n return self._connection\n\n def isclosed(self):\n return is_fp_closed(self._fp)\n\n def tell(self):\n """\n Obtain the number of bytes pulled over the wire so far. May differ from\n the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``\n if bytes are encoded on the wire (e.g, compressed).\n """\n return self._fp_bytes_read\n\n def _init_length(self, request_method):\n """\n Set initial length value for Response content if available.\n """\n length = self.headers.get("content-length")\n\n if length is not None:\n if self.chunked:\n # This Response will fail with an IncompleteRead if it can't be\n # received as chunked. This method falls back to attempt reading\n # the response before raising an exception.\n log.warning(\n "Received response with both Content-Length and "\n "Transfer-Encoding set. This is expressly forbidden "\n "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "\n "attempting to process response as Transfer-Encoding: "\n "chunked."\n )\n return None\n\n try:\n # RFC 7230 section 3.3.2 specifies multiple content lengths can\n # be sent in a single Content-Length header\n # (e.g. Content-Length: 42, 42). This line ensures the values\n # are all valid ints and that as long as the `set` length is 1,\n # all values are the same. Otherwise, the header is invalid.\n lengths = set([int(val) for val in length.split(",")])\n if len(lengths) > 1:\n raise InvalidHeader(\n "Content-Length contained multiple "\n "unmatching values (%s)" % length\n )\n length = lengths.pop()\n except ValueError:\n length = None\n else:\n if length < 0:\n length = None\n\n # Convert status to int for comparison\n # In some cases, httplib returns a status of "_UNKNOWN"\n try:\n status = int(self.status)\n except ValueError:\n status = 0\n\n # Check for responses that shouldn't include a body\n if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":\n length = 0\n\n return length\n\n def _init_decoder(self):\n """\n Set-up the _decoder attribute if necessary.\n """\n # Note: content-encoding value should be case-insensitive, per RFC 7230\n # Section 3.2\n content_encoding = self.headers.get("content-encoding", "").lower()\n if self._decoder is None:\n if content_encoding in self.CONTENT_DECODERS:\n self._decoder = _get_decoder(content_encoding)\n elif "," in content_encoding:\n encodings = [\n e.strip()\n for e in content_encoding.split(",")\n if e.strip() in self.CONTENT_DECODERS\n ]\n if len(encodings):\n self._decoder = _get_decoder(content_encoding)\n\n DECODER_ERROR_CLASSES = (IOError, zlib.error)\n if brotli is not None:\n DECODER_ERROR_CLASSES += (brotli.error,)\n\n def _decode(self, data, decode_content, flush_decoder):\n """\n Decode the data passed in and potentially flush the decoder.\n """\n if not decode_content:\n return data\n\n try:\n if self._decoder:\n data = self._decoder.decompress(data)\n except self.DECODER_ERROR_CLASSES as e:\n content_encoding = self.headers.get("content-encoding", "").lower()\n raise DecodeError(\n "Received response with content-encoding: %s, but "\n "failed to decode it." % content_encoding,\n e,\n )\n if flush_decoder:\n data += self._flush_decoder()\n\n return data\n\n def _flush_decoder(self):\n """\n Flushes the decoder. Should only be called if the decoder is actually\n being used.\n """\n if self._decoder:\n buf = self._decoder.decompress(b"")\n return buf + self._decoder.flush()\n\n return b""\n\n @contextmanager\n def _error_catcher(self):\n """\n Catch low-level python exceptions, instead re-raising urllib3\n variants, so that low-level exceptions are not leaked in the\n high-level api.\n\n On exit, release the connection back to the pool.\n """\n clean_exit = False\n\n try:\n try:\n yield\n\n except SocketTimeout:\n # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but\n # there is yet no clean way to get at it from this context.\n raise ReadTimeoutError(self._pool, None, "Read timed out.")\n\n except BaseSSLError as e:\n # FIXME: Is there a better way to differentiate between SSLErrors?\n if "read operation timed out" not in str(e):\n # SSL errors related to framing/MAC get wrapped and reraised here\n raise SSLError(e)\n\n raise ReadTimeoutError(self._pool, None, "Read timed out.")\n\n except (HTTPException, SocketError) as e:\n # This includes IncompleteRead.\n raise ProtocolError("Connection broken: %r" % e, e)\n\n # If no exception is thrown, we should avoid cleaning up\n # unnecessarily.\n clean_exit = True\n finally:\n # If we didn't terminate cleanly, we need to throw away our\n # connection.\n if not clean_exit:\n # The response may not be closed but we're not going to use it\n # anymore so close it now to ensure that the connection is\n # released back to the pool.\n if self._original_response:\n self._original_response.close()\n\n # Closing the response may not actually be sufficient to close\n # everything, so if we have a hold of the connection close that\n # too.\n if self._connection:\n self._connection.close()\n\n # If we hold the original response but it's closed now, we should\n # return the connection back to the pool.\n if self._original_response and self._original_response.isclosed():\n self.release_conn()\n\n def _fp_read(self, amt):\n """\n Read a response with the thought that reading the number of bytes\n larger than can fit in a 32-bit int at a time via SSL in some\n known cases leads to an overflow error that has to be prevented\n if `amt` or `self.length_remaining` indicate that a problem may\n happen.\n\n The known cases:\n * 3.8 <= CPython < 3.9.7 because of a bug\n https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.\n * urllib3 injected with pyOpenSSL-backed SSL-support.\n * CPython < 3.10 only when `amt` does not fit 32-bit int.\n """\n assert self._fp\n c_int_max = 2 ** 31 - 1\n if (\n (\n (amt and amt > c_int_max)\n or (self.length_remaining and self.length_remaining > c_int_max)\n )\n and not util.IS_SECURETRANSPORT\n and (util.IS_PYOPENSSL or sys.version_info < (3, 10))\n ):\n buffer = io.BytesIO()\n # Besides `max_chunk_amt` being a maximum chunk size, it\n # affects memory overhead of reading a response by this\n # method in CPython.\n # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum\n # chunk size that does not lead to an overflow error, but\n # 256 MiB is a compromise.\n max_chunk_amt = 2 ** 28\n while amt is None or amt != 0:\n if amt is not None:\n chunk_amt = min(amt, max_chunk_amt)\n amt -= chunk_amt\n else:\n chunk_amt = max_chunk_amt\n data = self._fp.read(chunk_amt)\n if not data:\n break\n buffer.write(data)\n del data # to reduce peak memory usage by `max_chunk_amt`.\n return buffer.getvalue()\n else:\n # StringIO doesn't like amt=None\n return self._fp.read(amt) if amt is not None else self._fp.read()\n\n def read(self, amt=None, decode_content=None, cache_content=False):\n """\n Similar to :meth:`http.client.HTTPResponse.read`, but with two additional\n parameters: ``decode_content`` and ``cache_content``.\n\n :param amt:\n How much of the content to read. If specified, caching is skipped\n because it doesn't make sense to cache partial content as the full\n response.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n\n :param cache_content:\n If True, will save the returned data such that the same result is\n returned despite of the state of the underlying file object. This\n is useful if you want the ``.data`` property to continue working\n after having ``.read()`` the file object. (Overridden if ``amt`` is\n set.)\n """\n self._init_decoder()\n if decode_content is None:\n decode_content = self.decode_content\n\n if self._fp is None:\n return\n\n flush_decoder = False\n fp_closed = getattr(self._fp, "closed", False)\n\n with self._error_catcher():\n data = self._fp_read(amt) if not fp_closed else b""\n if amt is None:\n flush_decoder = True\n else:\n cache_content = False\n if (\n amt != 0 and not data\n ): # Platform-specific: Buggy versions of Python.\n # Close the connection when no data is returned\n #\n # This is redundant to what httplib/http.client _should_\n # already do. However, versions of python released before\n # December 15, 2012 (http://bugs.python.org/issue16298) do\n # not properly close the connection in all cases. There is\n # no harm in redundantly calling close.\n self._fp.close()\n flush_decoder = True\n if self.enforce_content_length and self.length_remaining not in (\n 0,\n None,\n ):\n # This is an edge case that httplib failed to cover due\n # to concerns of backward compatibility. We're\n # addressing it here to make sure IncompleteRead is\n # raised during streaming, so all calls with incorrect\n # Content-Length are caught.\n raise IncompleteRead(self._fp_bytes_read, self.length_remaining)\n\n if data:\n self._fp_bytes_read += len(data)\n if self.length_remaining is not None:\n self.length_remaining -= len(data)\n\n data = self._decode(data, decode_content, flush_decoder)\n\n if cache_content:\n self._body = data\n\n return data\n\n def stream(self, amt=2 ** 16, decode_content=None):\n """\n A generator wrapper for the read() method. A call will block until\n ``amt`` bytes have been read from the connection or until the\n connection is closed.\n\n :param amt:\n How much of the content to read. The generator will return up to\n much data per iteration, but may return less. This is particularly\n likely when using compressed data. However, the empty string will\n never be returned.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n """\n if self.chunked and self.supports_chunked_reads():\n for line in self.read_chunked(amt, decode_content=decode_content):\n yield line\n else:\n while not is_fp_closed(self._fp):\n data = self.read(amt=amt, decode_content=decode_content)\n\n if data:\n yield data\n\n @classmethod\n def from_httplib(ResponseCls, r, **response_kw):\n """\n Given an :class:`http.client.HTTPResponse` instance ``r``, return a\n corresponding :class:`urllib3.response.HTTPResponse` object.\n\n Remaining parameters are passed to the HTTPResponse constructor, along\n with ``original_response=r``.\n """\n headers = r.msg\n\n if not isinstance(headers, HTTPHeaderDict):\n if six.PY2:\n # Python 2.7\n headers = HTTPHeaderDict.from_httplib(headers)\n else:\n headers = HTTPHeaderDict(headers.items())\n\n # HTTPResponse objects in Python 3 don't have a .strict attribute\n strict = getattr(r, "strict", 0)\n resp = ResponseCls(\n body=r,\n headers=headers,\n status=r.status,\n version=r.version,\n reason=r.reason,\n strict=strict,\n original_response=r,\n **response_kw\n )\n return resp\n\n # Backwards-compatibility methods for http.client.HTTPResponse\n def getheaders(self):\n warnings.warn(\n "HTTPResponse.getheaders() is deprecated and will be removed "\n "in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers\n\n def getheader(self, name, default=None):\n warnings.warn(\n "HTTPResponse.getheader() is deprecated and will be removed "\n "in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).",\n category=DeprecationWarning,\n stacklevel=2,\n )\n return self.headers.get(name, default)\n\n # Backwards compatibility for http.cookiejar\n def info(self):\n return self.headers\n\n # Overrides from io.IOBase\n def close(self):\n if not self.closed:\n self._fp.close()\n\n if self._connection:\n self._connection.close()\n\n if not self.auto_close:\n io.IOBase.close(self)\n\n @property\n def closed(self):\n if not self.auto_close:\n return io.IOBase.closed.__get__(self)\n elif self._fp is None:\n return True\n elif hasattr(self._fp, "isclosed"):\n return self._fp.isclosed()\n elif hasattr(self._fp, "closed"):\n return self._fp.closed\n else:\n return True\n\n def fileno(self):\n if self._fp is None:\n raise IOError("HTTPResponse has no file to get a fileno from")\n elif hasattr(self._fp, "fileno"):\n return self._fp.fileno()\n else:\n raise IOError(\n "The file-like object this HTTPResponse is wrapped "\n "around has no file descriptor"\n )\n\n def flush(self):\n if (\n self._fp is not None\n and hasattr(self._fp, "flush")\n and not getattr(self._fp, "closed", False)\n ):\n return self._fp.flush()\n\n def readable(self):\n # This method is required for `io` module compatibility.\n return True\n\n def readinto(self, b):\n # This method is required for `io` module compatibility.\n temp = self.read(len(b))\n if len(temp) == 0:\n return 0\n else:\n b[: len(temp)] = temp\n return len(temp)\n\n def supports_chunked_reads(self):\n """\n Checks if the underlying file-like object looks like a\n :class:`http.client.HTTPResponse` object. We do this by testing for\n the fp attribute. If it is present we assume it returns raw chunks as\n processed by read_chunked().\n """\n return hasattr(self._fp, "fp")\n\n def _update_chunk_length(self):\n # First, we'll figure out length of a chunk and then\n # we'll try to read it from socket.\n if self.chunk_left is not None:\n return\n line = self._fp.fp.readline()\n line = line.split(b";", 1)[0]\n try:\n self.chunk_left = int(line, 16)\n except ValueError:\n # Invalid chunked protocol response, abort.\n self.close()\n raise InvalidChunkLength(self, line)\n\n def _handle_chunk(self, amt):\n returned_chunk = None\n if amt is None:\n chunk = self._fp._safe_read(self.chunk_left)\n returned_chunk = chunk\n self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.\n self.chunk_left = None\n elif amt < self.chunk_left:\n value = self._fp._safe_read(amt)\n self.chunk_left = self.chunk_left - amt\n returned_chunk = value\n elif amt == self.chunk_left:\n value = self._fp._safe_read(amt)\n self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.\n self.chunk_left = None\n returned_chunk = value\n else: # amt > self.chunk_left\n returned_chunk = self._fp._safe_read(self.chunk_left)\n self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.\n self.chunk_left = None\n return returned_chunk\n\n def read_chunked(self, amt=None, decode_content=None):\n """\n Similar to :meth:`HTTPResponse.read`, but with an additional\n parameter: ``decode_content``.\n\n :param amt:\n How much of the content to read. If specified, caching is skipped\n because it doesn't make sense to cache partial content as the full\n response.\n\n :param decode_content:\n If True, will attempt to decode the body based on the\n 'content-encoding' header.\n """\n self._init_decoder()\n # FIXME: Rewrite this method and make it a class with a better structured logic.\n if not self.chunked:\n raise ResponseNotChunked(\n "Response is not chunked. "\n "Header 'transfer-encoding: chunked' is missing."\n )\n if not self.supports_chunked_reads():\n raise BodyNotHttplibCompatible(\n "Body should be http.client.HTTPResponse like. "\n "It should have have an fp attribute which returns raw chunks."\n )\n\n with self._error_catcher():\n # Don't bother reading the body of a HEAD request.\n if self._original_response and is_response_to_head(self._original_response):\n self._original_response.close()\n return\n\n # If a response is already read and closed\n # then return immediately.\n if self._fp.fp is None:\n return\n\n while True:\n self._update_chunk_length()\n if self.chunk_left == 0:\n break\n chunk = self._handle_chunk(amt)\n decoded = self._decode(\n chunk, decode_content=decode_content, flush_decoder=False\n )\n if decoded:\n yield decoded\n\n if decode_content:\n # On CPython and PyPy, we should never need to flush the\n # decoder. However, on Jython we *might* need to, so\n # lets defensively do it anyway.\n decoded = self._flush_decoder()\n if decoded: # Platform-specific: Jython.\n yield decoded\n\n # Chunk content ends with \r\n: discard it.\n while True:\n line = self._fp.fp.readline()\n if not line:\n # Some sites may not end with '\r\n'.\n break\n if line == b"\r\n":\n break\n\n # We read everything; close the "file".\n if self._original_response:\n self._original_response.close()\n\n def geturl(self):\n """\n Returns the URL that was the source of this response.\n If the request that generated this response redirected, this method\n will return the final redirect location.\n """\n if self.retries is not None and len(self.retries.history):\n return self.retries.history[-1].redirect_location\n else:\n return self._request_url\n\n def __iter__(self):\n buffer = []\n for chunk in self.stream(decode_content=True):\n if b"\n" in chunk:\n chunk = chunk.split(b"\n")\n yield b"".join(buffer) + chunk[0] + b"\n"\n for x in chunk[1:-1]:\n yield x + b"\n"\n if chunk[-1]:\n buffer = [chunk[-1]]\n else:\n buffer = []\n else:\n buffer.append(chunk)\n if buffer:\n yield b"".join(buffer)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\response.py | response.py | Python | 30,641 | 0.95 | 0.21843 | 0.110963 | awesome-app | 364 | 2024-04-30T21:40:08.221961 | MIT | false | d15dab20e01038cb65497c6699b7aa5d |
from __future__ import absolute_import\n\ntry:\n from collections.abc import Mapping, MutableMapping\nexcept ImportError:\n from collections import Mapping, MutableMapping\ntry:\n from threading import RLock\nexcept ImportError: # Platform-specific: No threads available\n\n class RLock:\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_value, traceback):\n pass\n\n\nfrom collections import OrderedDict\n\nfrom .exceptions import InvalidHeader\nfrom .packages import six\nfrom .packages.six import iterkeys, itervalues\n\n__all__ = ["RecentlyUsedContainer", "HTTPHeaderDict"]\n\n\n_Null = object()\n\n\nclass RecentlyUsedContainer(MutableMapping):\n """\n Provides a thread-safe dict-like container which maintains up to\n ``maxsize`` keys while throwing away the least-recently-used keys beyond\n ``maxsize``.\n\n :param maxsize:\n Maximum number of recent elements to retain.\n\n :param dispose_func:\n Every time an item is evicted from the container,\n ``dispose_func(value)`` is called. Callback which will get called\n """\n\n ContainerCls = OrderedDict\n\n def __init__(self, maxsize=10, dispose_func=None):\n self._maxsize = maxsize\n self.dispose_func = dispose_func\n\n self._container = self.ContainerCls()\n self.lock = RLock()\n\n def __getitem__(self, key):\n # Re-insert the item, moving it to the end of the eviction line.\n with self.lock:\n item = self._container.pop(key)\n self._container[key] = item\n return item\n\n def __setitem__(self, key, value):\n evicted_value = _Null\n with self.lock:\n # Possibly evict the existing value of 'key'\n evicted_value = self._container.get(key, _Null)\n self._container[key] = value\n\n # If we didn't evict an existing value, we might have to evict the\n # least recently used item from the beginning of the container.\n if len(self._container) > self._maxsize:\n _key, evicted_value = self._container.popitem(last=False)\n\n if self.dispose_func and evicted_value is not _Null:\n self.dispose_func(evicted_value)\n\n def __delitem__(self, key):\n with self.lock:\n value = self._container.pop(key)\n\n if self.dispose_func:\n self.dispose_func(value)\n\n def __len__(self):\n with self.lock:\n return len(self._container)\n\n def __iter__(self):\n raise NotImplementedError(\n "Iteration over this class is unlikely to be threadsafe."\n )\n\n def clear(self):\n with self.lock:\n # Copy pointers to all values, then wipe the mapping\n values = list(itervalues(self._container))\n self._container.clear()\n\n if self.dispose_func:\n for value in values:\n self.dispose_func(value)\n\n def keys(self):\n with self.lock:\n return list(iterkeys(self._container))\n\n\nclass HTTPHeaderDict(MutableMapping):\n """\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-insensitively.\n\n :param kwargs:\n Additional field-value pairs to pass in to ``dict.update``.\n\n A ``dict`` like container for storing HTTP Headers.\n\n Field names are stored and compared case-insensitively in compliance with\n RFC 7230. Iteration provides the first case-sensitive key seen for each\n case-insensitive pair.\n\n Using ``__setitem__`` syntax overwrites fields that compare equal\n case-insensitively in order to maintain ``dict``'s api. For fields that\n compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n in a loop.\n\n If multiple fields that are equal case-insensitively are passed to the\n constructor or ``.update``, the behavior is undefined and some will be\n lost.\n\n >>> headers = HTTPHeaderDict()\n >>> headers.add('Set-Cookie', 'foo=bar')\n >>> headers.add('set-cookie', 'baz=quxx')\n >>> headers['content-length'] = '7'\n >>> headers['SET-cookie']\n 'foo=bar, baz=quxx'\n >>> headers['Content-Length']\n '7'\n """\n\n def __init__(self, headers=None, **kwargs):\n super(HTTPHeaderDict, self).__init__()\n self._container = OrderedDict()\n if headers is not None:\n if isinstance(headers, HTTPHeaderDict):\n self._copy_from(headers)\n else:\n self.extend(headers)\n if kwargs:\n self.extend(kwargs)\n\n def __setitem__(self, key, val):\n self._container[key.lower()] = [key, val]\n return self._container[key.lower()]\n\n def __getitem__(self, key):\n val = self._container[key.lower()]\n return ", ".join(val[1:])\n\n def __delitem__(self, key):\n del self._container[key.lower()]\n\n def __contains__(self, key):\n return key.lower() in self._container\n\n def __eq__(self, other):\n if not isinstance(other, Mapping) and not hasattr(other, "keys"):\n return False\n if not isinstance(other, type(self)):\n other = type(self)(other)\n return dict((k.lower(), v) for k, v in self.itermerged()) == dict(\n (k.lower(), v) for k, v in other.itermerged()\n )\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n if six.PY2: # Python 2\n iterkeys = MutableMapping.iterkeys\n itervalues = MutableMapping.itervalues\n\n __marker = object()\n\n def __len__(self):\n return len(self._container)\n\n def __iter__(self):\n # Only provide the originally cased names\n for vals in self._container.values():\n yield vals[0]\n\n def pop(self, key, default=__marker):\n """D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n If key is not found, d is returned if given, otherwise KeyError is raised.\n """\n # Using the MutableMapping function directly fails due to the private marker.\n # Using ordinary dict.pop would expose the internal structures.\n # So let's reinvent the wheel.\n try:\n value = self[key]\n except KeyError:\n if default is self.__marker:\n raise\n return default\n else:\n del self[key]\n return value\n\n def discard(self, key):\n try:\n del self[key]\n except KeyError:\n pass\n\n def add(self, key, val):\n """Adds a (name, value) pair, doesn't overwrite the value if it already\n exists.\n\n >>> headers = HTTPHeaderDict(foo='bar')\n >>> headers.add('Foo', 'baz')\n >>> headers['foo']\n 'bar, baz'\n """\n key_lower = key.lower()\n new_vals = [key, val]\n # Keep the common case aka no item present as fast as possible\n vals = self._container.setdefault(key_lower, new_vals)\n if new_vals is not vals:\n vals.append(val)\n\n def extend(self, *args, **kwargs):\n """Generic import function for any type of header-like object.\n Adapted version of MutableMapping.update in order to insert items\n with self.add instead of self.__setitem__\n """\n if len(args) > 1:\n raise TypeError(\n "extend() takes at most 1 positional "\n "arguments ({0} given)".format(len(args))\n )\n other = args[0] if len(args) >= 1 else ()\n\n if isinstance(other, HTTPHeaderDict):\n for key, val in other.iteritems():\n self.add(key, val)\n elif isinstance(other, Mapping):\n for key in other:\n self.add(key, other[key])\n elif hasattr(other, "keys"):\n for key in other.keys():\n self.add(key, other[key])\n else:\n for key, value in other:\n self.add(key, value)\n\n for key, value in kwargs.items():\n self.add(key, value)\n\n def getlist(self, key, default=__marker):\n """Returns a list of all the values for the named field. Returns an\n empty list if the key doesn't exist."""\n try:\n vals = self._container[key.lower()]\n except KeyError:\n if default is self.__marker:\n return []\n return default\n else:\n return vals[1:]\n\n def _prepare_for_method_change(self):\n """\n Remove content-specific header fields before changing the request\n method to GET or HEAD according to RFC 9110, Section 15.4.\n """\n content_specific_headers = [\n "Content-Encoding",\n "Content-Language",\n "Content-Location",\n "Content-Type",\n "Content-Length",\n "Digest",\n "Last-Modified",\n ]\n for header in content_specific_headers:\n self.discard(header)\n return self\n\n # Backwards compatibility for httplib\n getheaders = getlist\n getallmatchingheaders = getlist\n iget = getlist\n\n # Backwards compatibility for http.cookiejar\n get_all = getlist\n\n def __repr__(self):\n return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))\n\n def _copy_from(self, other):\n for key in other:\n val = other.getlist(key)\n if isinstance(val, list):\n # Don't need to convert tuples\n val = list(val)\n self._container[key.lower()] = [key] + val\n\n def copy(self):\n clone = type(self)()\n clone._copy_from(self)\n return clone\n\n def iteritems(self):\n """Iterate over all header lines, including duplicate ones."""\n for key in self:\n vals = self._container[key.lower()]\n for val in vals[1:]:\n yield vals[0], val\n\n def itermerged(self):\n """Iterate over all headers, merging duplicate ones together."""\n for key in self:\n val = self._container[key.lower()]\n yield val[0], ", ".join(val[1:])\n\n def items(self):\n return list(self.iteritems())\n\n @classmethod\n def from_httplib(cls, message): # Python 2\n """Read headers from a Python 2 httplib message object."""\n # python2.7 does not expose a proper API for exporting multiheaders\n # efficiently. This function re-reads raw lines from the message\n # object and extracts the multiheaders properly.\n obs_fold_continued_leaders = (" ", "\t")\n headers = []\n\n for line in message.headers:\n if line.startswith(obs_fold_continued_leaders):\n if not headers:\n # We received a header line that starts with OWS as described\n # in RFC-7230 S3.2.4. This indicates a multiline header, but\n # there exists no previous header to which we can attach it.\n raise InvalidHeader(\n "Header continuation with no previous header: %s" % line\n )\n else:\n key, value = headers[-1]\n headers[-1] = (key, value + " " + line.strip())\n continue\n\n key, value = line.split(":", 1)\n headers.append((key, value.strip()))\n\n return cls(headers)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\_collections.py | _collections.py | Python | 11,372 | 0.95 | 0.250704 | 0.065972 | awesome-app | 861 | 2024-02-07T05:11:47.261676 | Apache-2.0 | false | 22c3eb7983299333432f17416c79c1eb |
# This file is protected via CODEOWNERS\n__version__ = "1.26.20"\n | .venv\Lib\site-packages\pip\_vendor\urllib3\_version.py | _version.py | Python | 64 | 0.6 | 0 | 0.5 | awesome-app | 227 | 2023-11-21T18:41:38.769609 | GPL-3.0 | false | a0bea5dbc98330dd1ddf8e05001eee45 |
"""\nPython HTTP library with thread-safe connection pooling, file post support, user friendly, and more\n"""\nfrom __future__ import absolute_import\n\n# Set default logging handler to avoid "No handler found" warnings.\nimport logging\nimport warnings\nfrom logging import NullHandler\n\nfrom . import exceptions\nfrom ._version import __version__\nfrom .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url\nfrom .filepost import encode_multipart_formdata\nfrom .poolmanager import PoolManager, ProxyManager, proxy_from_url\nfrom .response import HTTPResponse\nfrom .util.request import make_headers\nfrom .util.retry import Retry\nfrom .util.timeout import Timeout\nfrom .util.url import get_host\n\n# === NOTE TO REPACKAGERS AND VENDORS ===\n# Please delete this block, this logic is only\n# for urllib3 being distributed via PyPI.\n# See: https://github.com/urllib3/urllib3/issues/2680\ntry:\n import urllib3_secure_extra # type: ignore # noqa: F401\nexcept ImportError:\n pass\nelse:\n warnings.warn(\n "'urllib3[secure]' extra is deprecated and will be removed "\n "in a future release of urllib3 2.x. Read more in this issue: "\n "https://github.com/urllib3/urllib3/issues/2680",\n category=DeprecationWarning,\n stacklevel=2,\n )\n\n__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"\n__license__ = "MIT"\n__version__ = __version__\n\n__all__ = (\n "HTTPConnectionPool",\n "HTTPSConnectionPool",\n "PoolManager",\n "ProxyManager",\n "HTTPResponse",\n "Retry",\n "Timeout",\n "add_stderr_logger",\n "connection_from_url",\n "disable_warnings",\n "encode_multipart_formdata",\n "get_host",\n "make_headers",\n "proxy_from_url",\n)\n\nlogging.getLogger(__name__).addHandler(NullHandler())\n\n\ndef add_stderr_logger(level=logging.DEBUG):\n """\n Helper for quickly adding a StreamHandler to the logger. Useful for\n debugging.\n\n Returns the handler after adding it.\n """\n # This method needs to be in this __init__.py to get the __name__ correct\n # even if urllib3 is vendored within another package.\n logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))\n logger.addHandler(handler)\n logger.setLevel(level)\n logger.debug("Added a stderr logging handler to logger: %s", __name__)\n return handler\n\n\n# ... Clean up.\ndel NullHandler\n\n\n# All warning filters *must* be appended unless you're really certain that they\n# shouldn't be: otherwise, it's very hard for users to use most Python\n# mechanisms to silence them.\n# SecurityWarning's always go off by default.\nwarnings.simplefilter("always", exceptions.SecurityWarning, append=True)\n# SubjectAltNameWarning's should go off once per host\nwarnings.simplefilter("default", exceptions.SubjectAltNameWarning, append=True)\n# InsecurePlatformWarning's don't vary between requests, so we keep it default.\nwarnings.simplefilter("default", exceptions.InsecurePlatformWarning, append=True)\n# SNIMissingWarnings should go off only once.\nwarnings.simplefilter("default", exceptions.SNIMissingWarning, append=True)\n\n\ndef disable_warnings(category=exceptions.HTTPWarning):\n """\n Helper for quickly disabling all urllib3 warnings.\n """\n warnings.simplefilter("ignore", category)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__init__.py | __init__.py | Python | 3,333 | 0.95 | 0.088235 | 0.172414 | node-utils | 525 | 2024-09-10T07:13:21.318300 | BSD-3-Clause | false | aa0aaf78010eca6e197e854ce5250968 |
"""\nThis module provides a pool manager that uses Google App Engine's\n`URLFetch Service <https://cloud.google.com/appengine/docs/python/urlfetch>`_.\n\nExample usage::\n\n from pip._vendor.urllib3 import PoolManager\n from pip._vendor.urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox\n\n if is_appengine_sandbox():\n # AppEngineManager uses AppEngine's URLFetch API behind the scenes\n http = AppEngineManager()\n else:\n # PoolManager uses a socket-level API behind the scenes\n http = PoolManager()\n\n r = http.request('GET', 'https://google.com/')\n\nThere are `limitations <https://cloud.google.com/appengine/docs/python/\\nurlfetch/#Python_Quotas_and_limits>`_ to the URLFetch service and it may not be\nthe best choice for your application. There are three options for using\nurllib3 on Google App Engine:\n\n1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is\n cost-effective in many circumstances as long as your usage is within the\n limitations.\n2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets.\n Sockets also have `limitations and restrictions\n <https://cloud.google.com/appengine/docs/python/sockets/\\n #limitations-and-restrictions>`_ and have a lower free quota than URLFetch.\n To use sockets, be sure to specify the following in your ``app.yaml``::\n\n env_variables:\n GAE_USE_SOCKETS_HTTPLIB : 'true'\n\n3. If you are using `App Engine Flexible\n<https://cloud.google.com/appengine/docs/flexible/>`_, you can use the standard\n:class:`PoolManager` without any configuration or special environment variables.\n"""\n\nfrom __future__ import absolute_import\n\nimport io\nimport logging\nimport warnings\n\nfrom ..exceptions import (\n HTTPError,\n HTTPWarning,\n MaxRetryError,\n ProtocolError,\n SSLError,\n TimeoutError,\n)\nfrom ..packages.six.moves.urllib.parse import urljoin\nfrom ..request import RequestMethods\nfrom ..response import HTTPResponse\nfrom ..util.retry import Retry\nfrom ..util.timeout import Timeout\nfrom . import _appengine_environ\n\ntry:\n from google.appengine.api import urlfetch\nexcept ImportError:\n urlfetch = None\n\n\nlog = logging.getLogger(__name__)\n\n\nclass AppEnginePlatformWarning(HTTPWarning):\n pass\n\n\nclass AppEnginePlatformError(HTTPError):\n pass\n\n\nclass AppEngineManager(RequestMethods):\n """\n Connection manager for Google App Engine sandbox applications.\n\n This manager uses the URLFetch service directly instead of using the\n emulated httplib, and is subject to URLFetch limitations as described in\n the App Engine documentation `here\n <https://cloud.google.com/appengine/docs/python/urlfetch>`_.\n\n Notably it will raise an :class:`AppEnginePlatformError` if:\n * URLFetch is not available.\n * If you attempt to use this on App Engine Flexible, as full socket\n support is available.\n * If a request size is more than 10 megabytes.\n * If a response size is more than 32 megabytes.\n * If you use an unsupported request method such as OPTIONS.\n\n Beyond those cases, it will raise normal urllib3 errors.\n """\n\n def __init__(\n self,\n headers=None,\n retries=None,\n validate_certificate=True,\n urlfetch_retries=True,\n ):\n if not urlfetch:\n raise AppEnginePlatformError(\n "URLFetch is not available in this environment."\n )\n\n warnings.warn(\n "urllib3 is using URLFetch on Google App Engine sandbox instead "\n "of sockets. To use sockets directly instead of URLFetch see "\n "https://urllib3.readthedocs.io/en/1.26.x/reference/urllib3.contrib.html.",\n AppEnginePlatformWarning,\n )\n\n RequestMethods.__init__(self, headers)\n self.validate_certificate = validate_certificate\n self.urlfetch_retries = urlfetch_retries\n\n self.retries = retries or Retry.DEFAULT\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n # Return False to re-raise any potential exceptions\n return False\n\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n retries=None,\n redirect=True,\n timeout=Timeout.DEFAULT_TIMEOUT,\n **response_kw\n ):\n\n retries = self._get_retries(retries, redirect)\n\n try:\n follow_redirects = redirect and retries.redirect != 0 and retries.total\n response = urlfetch.fetch(\n url,\n payload=body,\n method=method,\n headers=headers or {},\n allow_truncated=False,\n follow_redirects=self.urlfetch_retries and follow_redirects,\n deadline=self._get_absolute_timeout(timeout),\n validate_certificate=self.validate_certificate,\n )\n except urlfetch.DeadlineExceededError as e:\n raise TimeoutError(self, e)\n\n except urlfetch.InvalidURLError as e:\n if "too large" in str(e):\n raise AppEnginePlatformError(\n "URLFetch request too large, URLFetch only "\n "supports requests up to 10mb in size.",\n e,\n )\n raise ProtocolError(e)\n\n except urlfetch.DownloadError as e:\n if "Too many redirects" in str(e):\n raise MaxRetryError(self, url, reason=e)\n raise ProtocolError(e)\n\n except urlfetch.ResponseTooLargeError as e:\n raise AppEnginePlatformError(\n "URLFetch response too large, URLFetch only supports"\n "responses up to 32mb in size.",\n e,\n )\n\n except urlfetch.SSLCertificateError as e:\n raise SSLError(e)\n\n except urlfetch.InvalidMethodError as e:\n raise AppEnginePlatformError(\n "URLFetch does not support method: %s" % method, e\n )\n\n http_response = self._urlfetch_response_to_http_response(\n response, retries=retries, **response_kw\n )\n\n # Handle redirect?\n redirect_location = redirect and http_response.get_redirect_location()\n if redirect_location:\n # Check for redirect response\n if self.urlfetch_retries and retries.raise_on_redirect:\n raise MaxRetryError(self, url, "too many redirects")\n else:\n if http_response.status == 303:\n method = "GET"\n\n try:\n retries = retries.increment(\n method, url, response=http_response, _pool=self\n )\n except MaxRetryError:\n if retries.raise_on_redirect:\n raise MaxRetryError(self, url, "too many redirects")\n return http_response\n\n retries.sleep_for_retry(http_response)\n log.debug("Redirecting %s -> %s", url, redirect_location)\n redirect_url = urljoin(url, redirect_location)\n return self.urlopen(\n method,\n redirect_url,\n body,\n headers,\n retries=retries,\n redirect=redirect,\n timeout=timeout,\n **response_kw\n )\n\n # Check if we should retry the HTTP response.\n has_retry_after = bool(http_response.headers.get("Retry-After"))\n if retries.is_retry(method, http_response.status, has_retry_after):\n retries = retries.increment(method, url, response=http_response, _pool=self)\n log.debug("Retry: %s", url)\n retries.sleep(http_response)\n return self.urlopen(\n method,\n url,\n body=body,\n headers=headers,\n retries=retries,\n redirect=redirect,\n timeout=timeout,\n **response_kw\n )\n\n return http_response\n\n def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):\n\n if is_prod_appengine():\n # Production GAE handles deflate encoding automatically, but does\n # not remove the encoding header.\n content_encoding = urlfetch_resp.headers.get("content-encoding")\n\n if content_encoding == "deflate":\n del urlfetch_resp.headers["content-encoding"]\n\n transfer_encoding = urlfetch_resp.headers.get("transfer-encoding")\n # We have a full response's content,\n # so let's make sure we don't report ourselves as chunked data.\n if transfer_encoding == "chunked":\n encodings = transfer_encoding.split(",")\n encodings.remove("chunked")\n urlfetch_resp.headers["transfer-encoding"] = ",".join(encodings)\n\n original_response = HTTPResponse(\n # In order for decoding to work, we must present the content as\n # a file-like object.\n body=io.BytesIO(urlfetch_resp.content),\n msg=urlfetch_resp.header_msg,\n headers=urlfetch_resp.headers,\n status=urlfetch_resp.status_code,\n **response_kw\n )\n\n return HTTPResponse(\n body=io.BytesIO(urlfetch_resp.content),\n headers=urlfetch_resp.headers,\n status=urlfetch_resp.status_code,\n original_response=original_response,\n **response_kw\n )\n\n def _get_absolute_timeout(self, timeout):\n if timeout is Timeout.DEFAULT_TIMEOUT:\n return None # Defer to URLFetch's default.\n if isinstance(timeout, Timeout):\n if timeout._read is not None or timeout._connect is not None:\n warnings.warn(\n "URLFetch does not support granular timeout settings, "\n "reverting to total or default URLFetch timeout.",\n AppEnginePlatformWarning,\n )\n return timeout.total\n return timeout\n\n def _get_retries(self, retries, redirect):\n if not isinstance(retries, Retry):\n retries = Retry.from_int(retries, redirect=redirect, default=self.retries)\n\n if retries.connect or retries.read or retries.redirect:\n warnings.warn(\n "URLFetch only supports total retries and does not "\n "recognize connect, read, or redirect retry parameters.",\n AppEnginePlatformWarning,\n )\n\n return retries\n\n\n# Alias methods from _appengine_environ to maintain public API interface.\n\nis_appengine = _appengine_environ.is_appengine\nis_appengine_sandbox = _appengine_environ.is_appengine_sandbox\nis_local_appengine = _appengine_environ.is_local_appengine\nis_prod_appengine = _appengine_environ.is_prod_appengine\nis_prod_appengine_mvms = _appengine_environ.is_prod_appengine_mvms\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\appengine.py | appengine.py | Python | 11,036 | 0.95 | 0.130573 | 0.093023 | react-lib | 317 | 2024-03-29T09:36:40.338574 | BSD-3-Clause | false | 0039628936ccb81ccf64ca087b7506dd |
"""\nNTLM authenticating pool, contributed by erikcederstran\n\nIssue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10\n"""\nfrom __future__ import absolute_import\n\nimport warnings\nfrom logging import getLogger\n\nfrom ntlm import ntlm\n\nfrom .. import HTTPSConnectionPool\nfrom ..packages.six.moves.http_client import HTTPSConnection\n\nwarnings.warn(\n "The 'urllib3.contrib.ntlmpool' module is deprecated and will be removed "\n "in urllib3 v2.0 release, urllib3 is not able to support it properly due "\n "to reasons listed in issue: https://github.com/urllib3/urllib3/issues/2282. "\n "If you are a user of this module please comment in the mentioned issue.",\n DeprecationWarning,\n)\n\nlog = getLogger(__name__)\n\n\nclass NTLMConnectionPool(HTTPSConnectionPool):\n """\n Implements an NTLM authentication version of an urllib3 connection pool\n """\n\n scheme = "https"\n\n def __init__(self, user, pw, authurl, *args, **kwargs):\n """\n authurl is a random URL on the server that is protected by NTLM.\n user is the Windows user, probably in the DOMAIN\\username format.\n pw is the password for the user.\n """\n super(NTLMConnectionPool, self).__init__(*args, **kwargs)\n self.authurl = authurl\n self.rawuser = user\n user_parts = user.split("\\", 1)\n self.domain = user_parts[0].upper()\n self.user = user_parts[1]\n self.pw = pw\n\n def _new_conn(self):\n # Performs the NTLM handshake that secures the connection. The socket\n # must be kept open while requests are performed.\n self.num_connections += 1\n log.debug(\n "Starting NTLM HTTPS connection no. %d: https://%s%s",\n self.num_connections,\n self.host,\n self.authurl,\n )\n\n headers = {"Connection": "Keep-Alive"}\n req_header = "Authorization"\n resp_header = "www-authenticate"\n\n conn = HTTPSConnection(host=self.host, port=self.port)\n\n # Send negotiation message\n headers[req_header] = "NTLM %s" % ntlm.create_NTLM_NEGOTIATE_MESSAGE(\n self.rawuser\n )\n log.debug("Request headers: %s", headers)\n conn.request("GET", self.authurl, None, headers)\n res = conn.getresponse()\n reshdr = dict(res.headers)\n log.debug("Response status: %s %s", res.status, res.reason)\n log.debug("Response headers: %s", reshdr)\n log.debug("Response data: %s [...]", res.read(100))\n\n # Remove the reference to the socket, so that it can not be closed by\n # the response object (we want to keep the socket open)\n res.fp = None\n\n # Server should respond with a challenge message\n auth_header_values = reshdr[resp_header].split(", ")\n auth_header_value = None\n for s in auth_header_values:\n if s[:5] == "NTLM ":\n auth_header_value = s[5:]\n if auth_header_value is None:\n raise Exception(\n "Unexpected %s response header: %s" % (resp_header, reshdr[resp_header])\n )\n\n # Send authentication message\n ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(\n auth_header_value\n )\n auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(\n ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags\n )\n headers[req_header] = "NTLM %s" % auth_msg\n log.debug("Request headers: %s", headers)\n conn.request("GET", self.authurl, None, headers)\n res = conn.getresponse()\n log.debug("Response status: %s %s", res.status, res.reason)\n log.debug("Response headers: %s", dict(res.headers))\n log.debug("Response data: %s [...]", res.read()[:100])\n if res.status != 200:\n if res.status == 401:\n raise Exception("Server rejected request: wrong username or password")\n raise Exception("Wrong server response: %s %s" % (res.status, res.reason))\n\n res.fp = None\n log.debug("Connection established")\n return conn\n\n def urlopen(\n self,\n method,\n url,\n body=None,\n headers=None,\n retries=3,\n redirect=True,\n assert_same_host=True,\n ):\n if headers is None:\n headers = {}\n headers["Connection"] = "Keep-Alive"\n return super(NTLMConnectionPool, self).urlopen(\n method, url, body, headers, retries, redirect, assert_same_host\n )\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\ntlmpool.py | ntlmpool.py | Python | 4,528 | 0.95 | 0.092308 | 0.063063 | node-utils | 949 | 2024-05-14T14:50:27.479361 | GPL-3.0 | false | 0d2564338ccabd0e3126c771ed288bb0 |
"""\nTLS with SNI_-support for Python 2. Follow these instructions if you would\nlike to verify TLS certificates in Python 2. Note, the default libraries do\n*not* do certificate checking; you need to do additional work to validate\ncertificates yourself.\n\nThis needs the following packages installed:\n\n* `pyOpenSSL`_ (tested with 16.0.0)\n* `cryptography`_ (minimum 1.3.4, from pyopenssl)\n* `idna`_ (minimum 2.0, from cryptography)\n\nHowever, pyopenssl depends on cryptography, which depends on idna, so while we\nuse all three directly here we end up having relatively few packages required.\n\nYou can install them with the following command:\n\n.. code-block:: bash\n\n $ python -m pip install pyopenssl cryptography idna\n\nTo activate certificate checking, call\n:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code\nbefore you begin making HTTP requests. This can be done in a ``sitecustomize``\nmodule, or at any other time before your application begins using ``urllib3``,\nlike this:\n\n.. code-block:: python\n\n try:\n import pip._vendor.urllib3.contrib.pyopenssl as pyopenssl\n pyopenssl.inject_into_urllib3()\n except ImportError:\n pass\n\nNow you can use :mod:`urllib3` as you normally would, and it will support SNI\nwhen the required modules are installed.\n\nActivating this module also has the positive side effect of disabling SSL/TLS\ncompression in Python 2 (see `CRIME attack`_).\n\n.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication\n.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)\n.. _pyopenssl: https://www.pyopenssl.org\n.. _cryptography: https://cryptography.io\n.. _idna: https://github.com/kjd/idna\n"""\nfrom __future__ import absolute_import\n\nimport OpenSSL.crypto\nimport OpenSSL.SSL\nfrom cryptography import x509\nfrom cryptography.hazmat.backends.openssl import backend as openssl_backend\n\ntry:\n from cryptography.x509 import UnsupportedExtension\nexcept ImportError:\n # UnsupportedExtension is gone in cryptography >= 2.1.0\n class UnsupportedExtension(Exception):\n pass\n\n\nfrom io import BytesIO\nfrom socket import error as SocketError\nfrom socket import timeout\n\ntry: # Platform-specific: Python 2\n from socket import _fileobject\nexcept ImportError: # Platform-specific: Python 3\n _fileobject = None\n from ..packages.backports.makefile import backport_makefile\n\nimport logging\nimport ssl\nimport sys\nimport warnings\n\nfrom .. import util\nfrom ..packages import six\nfrom ..util.ssl_ import PROTOCOL_TLS_CLIENT\n\nwarnings.warn(\n "'urllib3.contrib.pyopenssl' module is deprecated and will be removed "\n "in a future release of urllib3 2.x. Read more in this issue: "\n "https://github.com/urllib3/urllib3/issues/2680",\n category=DeprecationWarning,\n stacklevel=2,\n)\n\n__all__ = ["inject_into_urllib3", "extract_from_urllib3"]\n\n# SNI always works.\nHAS_SNI = True\n\n# Map from urllib3 to PyOpenSSL compatible parameter-values.\n_openssl_versions = {\n util.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD,\n PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD,\n ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,\n}\n\nif hasattr(ssl, "PROTOCOL_SSLv3") and hasattr(OpenSSL.SSL, "SSLv3_METHOD"):\n _openssl_versions[ssl.PROTOCOL_SSLv3] = OpenSSL.SSL.SSLv3_METHOD\n\nif hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"):\n _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD\n\nif hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"):\n _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD\n\n\n_stdlib_to_openssl_verify = {\n ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,\n ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,\n ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER\n + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,\n}\n_openssl_to_stdlib_verify = dict((v, k) for k, v in _stdlib_to_openssl_verify.items())\n\n# OpenSSL will only write 16K at a time\nSSL_WRITE_BLOCKSIZE = 16384\n\norig_util_HAS_SNI = util.HAS_SNI\norig_util_SSLContext = util.ssl_.SSLContext\n\n\nlog = logging.getLogger(__name__)\n\n\ndef inject_into_urllib3():\n "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support."\n\n _validate_dependencies_met()\n\n util.SSLContext = PyOpenSSLContext\n util.ssl_.SSLContext = PyOpenSSLContext\n util.HAS_SNI = HAS_SNI\n util.ssl_.HAS_SNI = HAS_SNI\n util.IS_PYOPENSSL = True\n util.ssl_.IS_PYOPENSSL = True\n\n\ndef extract_from_urllib3():\n "Undo monkey-patching by :func:`inject_into_urllib3`."\n\n util.SSLContext = orig_util_SSLContext\n util.ssl_.SSLContext = orig_util_SSLContext\n util.HAS_SNI = orig_util_HAS_SNI\n util.ssl_.HAS_SNI = orig_util_HAS_SNI\n util.IS_PYOPENSSL = False\n util.ssl_.IS_PYOPENSSL = False\n\n\ndef _validate_dependencies_met():\n """\n Verifies that PyOpenSSL's package-level dependencies have been met.\n Throws `ImportError` if they are not met.\n """\n # Method added in `cryptography==1.1`; not available in older versions\n from cryptography.x509.extensions import Extensions\n\n if getattr(Extensions, "get_extension_for_class", None) is None:\n raise ImportError(\n "'cryptography' module missing required functionality. "\n "Try upgrading to v1.3.4 or newer."\n )\n\n # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509\n # attribute is only present on those versions.\n from OpenSSL.crypto import X509\n\n x509 = X509()\n if getattr(x509, "_x509", None) is None:\n raise ImportError(\n "'pyOpenSSL' module missing required functionality. "\n "Try upgrading to v0.14 or newer."\n )\n\n\ndef _dnsname_to_stdlib(name):\n """\n Converts a dNSName SubjectAlternativeName field to the form used by the\n standard library on the given Python version.\n\n Cryptography produces a dNSName as a unicode string that was idna-decoded\n from ASCII bytes. We need to idna-encode that string to get it back, and\n then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib\n uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).\n\n If the name cannot be idna-encoded then we return None signalling that\n the name given should be skipped.\n """\n\n def idna_encode(name):\n """\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoids that problem.\n """\n from pip._vendor import idna\n\n try:\n for prefix in [u"*.", u"."]:\n if name.startswith(prefix):\n name = name[len(prefix) :]\n return prefix.encode("ascii") + idna.encode(name)\n return idna.encode(name)\n except idna.core.IDNAError:\n return None\n\n # Don't send IPv6 addresses through the IDNA encoder.\n if ":" in name:\n return name\n\n name = idna_encode(name)\n if name is None:\n return None\n elif sys.version_info >= (3, 0):\n name = name.decode("utf-8")\n return name\n\n\ndef get_subj_alt_name(peer_cert):\n """\n Given an PyOpenSSL certificate, provides all the subject alternative names.\n """\n # Pass the cert to cryptography, which has much better APIs for this.\n if hasattr(peer_cert, "to_cryptography"):\n cert = peer_cert.to_cryptography()\n else:\n der = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, peer_cert)\n cert = x509.load_der_x509_certificate(der, openssl_backend)\n\n # We want to find the SAN extension. Ask Cryptography to locate it (it's\n # faster than looping in Python)\n try:\n ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value\n except x509.ExtensionNotFound:\n # No such extension, return the empty list.\n return []\n except (\n x509.DuplicateExtension,\n UnsupportedExtension,\n x509.UnsupportedGeneralNameType,\n UnicodeError,\n ) as e:\n # A problem has been found with the quality of the certificate. Assume\n # no SAN field is present.\n log.warning(\n "A problem was encountered with the certificate that prevented "\n "urllib3 from finding the SubjectAlternativeName field. This can "\n "affect certificate validation. The error was %s",\n e,\n )\n return []\n\n # We want to return dNSName and iPAddress fields. We need to cast the IPs\n # back to strings because the match_hostname function wants them as\n # strings.\n # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8\n # decoded. This is pretty frustrating, but that's what the standard library\n # does with certificates, and so we need to attempt to do the same.\n # We also want to skip over names which cannot be idna encoded.\n names = [\n ("DNS", name)\n for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))\n if name is not None\n ]\n names.extend(\n ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress)\n )\n\n return names\n\n\nclass WrappedSocket(object):\n """API-compatibility wrapper for Python OpenSSL's Connection-class.\n\n Note: _makefile_refs, _drop() and _reuse() are needed for the garbage\n collector of pypy.\n """\n\n def __init__(self, connection, socket, suppress_ragged_eofs=True):\n self.connection = connection\n self.socket = socket\n self.suppress_ragged_eofs = suppress_ragged_eofs\n self._makefile_refs = 0\n self._closed = False\n\n def fileno(self):\n return self.socket.fileno()\n\n # Copy-pasted from Python 3.5 source code\n def _decref_socketios(self):\n if self._makefile_refs > 0:\n self._makefile_refs -= 1\n if self._closed:\n self.close()\n\n def recv(self, *args, **kwargs):\n try:\n data = self.connection.recv(*args, **kwargs)\n except OpenSSL.SSL.SysCallError as e:\n if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):\n return b""\n else:\n raise SocketError(str(e))\n except OpenSSL.SSL.ZeroReturnError:\n if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:\n return b""\n else:\n raise\n except OpenSSL.SSL.WantReadError:\n if not util.wait_for_read(self.socket, self.socket.gettimeout()):\n raise timeout("The read operation timed out")\n else:\n return self.recv(*args, **kwargs)\n\n # TLS 1.3 post-handshake authentication\n except OpenSSL.SSL.Error as e:\n raise ssl.SSLError("read error: %r" % e)\n else:\n return data\n\n def recv_into(self, *args, **kwargs):\n try:\n return self.connection.recv_into(*args, **kwargs)\n except OpenSSL.SSL.SysCallError as e:\n if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"):\n return 0\n else:\n raise SocketError(str(e))\n except OpenSSL.SSL.ZeroReturnError:\n if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:\n return 0\n else:\n raise\n except OpenSSL.SSL.WantReadError:\n if not util.wait_for_read(self.socket, self.socket.gettimeout()):\n raise timeout("The read operation timed out")\n else:\n return self.recv_into(*args, **kwargs)\n\n # TLS 1.3 post-handshake authentication\n except OpenSSL.SSL.Error as e:\n raise ssl.SSLError("read error: %r" % e)\n\n def settimeout(self, timeout):\n return self.socket.settimeout(timeout)\n\n def _send_until_done(self, data):\n while True:\n try:\n return self.connection.send(data)\n except OpenSSL.SSL.WantWriteError:\n if not util.wait_for_write(self.socket, self.socket.gettimeout()):\n raise timeout()\n continue\n except OpenSSL.SSL.SysCallError as e:\n raise SocketError(str(e))\n\n def sendall(self, data):\n total_sent = 0\n while total_sent < len(data):\n sent = self._send_until_done(\n data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]\n )\n total_sent += sent\n\n def shutdown(self):\n # FIXME rethrow compatible exceptions should we ever use this\n self.connection.shutdown()\n\n def close(self):\n if self._makefile_refs < 1:\n try:\n self._closed = True\n return self.connection.close()\n except OpenSSL.SSL.Error:\n return\n else:\n self._makefile_refs -= 1\n\n def getpeercert(self, binary_form=False):\n x509 = self.connection.get_peer_certificate()\n\n if not x509:\n return x509\n\n if binary_form:\n return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)\n\n return {\n "subject": ((("commonName", x509.get_subject().CN),),),\n "subjectAltName": get_subj_alt_name(x509),\n }\n\n def version(self):\n return self.connection.get_protocol_version_name()\n\n def _reuse(self):\n self._makefile_refs += 1\n\n def _drop(self):\n if self._makefile_refs < 1:\n self.close()\n else:\n self._makefile_refs -= 1\n\n\nif _fileobject: # Platform-specific: Python 2\n\n def makefile(self, mode, bufsize=-1):\n self._makefile_refs += 1\n return _fileobject(self, mode, bufsize, close=True)\n\nelse: # Platform-specific: Python 3\n makefile = backport_makefile\n\nWrappedSocket.makefile = makefile\n\n\nclass PyOpenSSLContext(object):\n """\n I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible\n for translating the interface of the standard library ``SSLContext`` object\n to calls into PyOpenSSL.\n """\n\n def __init__(self, protocol):\n self.protocol = _openssl_versions[protocol]\n self._ctx = OpenSSL.SSL.Context(self.protocol)\n self._options = 0\n self.check_hostname = False\n\n @property\n def options(self):\n return self._options\n\n @options.setter\n def options(self, value):\n self._options = value\n self._ctx.set_options(value)\n\n @property\n def verify_mode(self):\n return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]\n\n @verify_mode.setter\n def verify_mode(self, value):\n self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback)\n\n def set_default_verify_paths(self):\n self._ctx.set_default_verify_paths()\n\n def set_ciphers(self, ciphers):\n if isinstance(ciphers, six.text_type):\n ciphers = ciphers.encode("utf-8")\n self._ctx.set_cipher_list(ciphers)\n\n def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n if cafile is not None:\n cafile = cafile.encode("utf-8")\n if capath is not None:\n capath = capath.encode("utf-8")\n try:\n self._ctx.load_verify_locations(cafile, capath)\n if cadata is not None:\n self._ctx.load_verify_locations(BytesIO(cadata))\n except OpenSSL.SSL.Error as e:\n raise ssl.SSLError("unable to load trusted certificates: %r" % e)\n\n def load_cert_chain(self, certfile, keyfile=None, password=None):\n self._ctx.use_certificate_chain_file(certfile)\n if password is not None:\n if not isinstance(password, six.binary_type):\n password = password.encode("utf-8")\n self._ctx.set_passwd_cb(lambda *_: password)\n self._ctx.use_privatekey_file(keyfile or certfile)\n\n def set_alpn_protocols(self, protocols):\n protocols = [six.ensure_binary(p) for p in protocols]\n return self._ctx.set_alpn_protos(protocols)\n\n def wrap_socket(\n self,\n sock,\n server_side=False,\n do_handshake_on_connect=True,\n suppress_ragged_eofs=True,\n server_hostname=None,\n ):\n cnx = OpenSSL.SSL.Connection(self._ctx, sock)\n\n if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3\n server_hostname = server_hostname.encode("utf-8")\n\n if server_hostname is not None:\n cnx.set_tlsext_host_name(server_hostname)\n\n cnx.set_connect_state()\n\n while True:\n try:\n cnx.do_handshake()\n except OpenSSL.SSL.WantReadError:\n if not util.wait_for_read(sock, sock.gettimeout()):\n raise timeout("select timed out")\n continue\n except OpenSSL.SSL.Error as e:\n raise ssl.SSLError("bad handshake: %r" % e)\n break\n\n return WrappedSocket(cnx, sock)\n\n\ndef _verify_callback(cnx, x509, err_no, err_depth, return_code):\n return err_no == 0\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\pyopenssl.py | pyopenssl.py | Python | 17,081 | 0.95 | 0.196911 | 0.070048 | node-utils | 414 | 2025-05-18T04:27:01.326463 | Apache-2.0 | false | 395256c643fc9a1cc6277acda6fdca81 |
"""\nSecureTranport support for urllib3 via ctypes.\n\nThis makes platform-native TLS available to urllib3 users on macOS without the\nuse of a compiler. This is an important feature because the Python Package\nIndex is moving to become a TLSv1.2-or-higher server, and the default OpenSSL\nthat ships with macOS is not capable of doing TLSv1.2. The only way to resolve\nthis is to give macOS users an alternative solution to the problem, and that\nsolution is to use SecureTransport.\n\nWe use ctypes here because this solution must not require a compiler. That's\nbecause pip is not allowed to require a compiler either.\n\nThis is not intended to be a seriously long-term solution to this problem.\nThe hope is that PEP 543 will eventually solve this issue for us, at which\npoint we can retire this contrib module. But in the short term, we need to\nsolve the impending tire fire that is Python on Mac without this kind of\ncontrib module. So...here we are.\n\nTo use this module, simply import and inject it::\n\n import pip._vendor.urllib3.contrib.securetransport as securetransport\n securetransport.inject_into_urllib3()\n\nHappy TLSing!\n\nThis code is a bastardised version of the code found in Will Bond's oscrypto\nlibrary. An enormous debt is owed to him for blazing this trail for us. For\nthat reason, this code should be considered to be covered both by urllib3's\nlicense and by oscrypto's:\n\n.. code-block::\n\n Copyright (c) 2015-2016 Will Bond <will@wbond.net>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the "Software"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n"""\nfrom __future__ import absolute_import\n\nimport contextlib\nimport ctypes\nimport errno\nimport os.path\nimport shutil\nimport socket\nimport ssl\nimport struct\nimport threading\nimport weakref\n\nfrom .. import util\nfrom ..packages import six\nfrom ..util.ssl_ import PROTOCOL_TLS_CLIENT\nfrom ._securetransport.bindings import CoreFoundation, Security, SecurityConst\nfrom ._securetransport.low_level import (\n _assert_no_error,\n _build_tls_unknown_ca_alert,\n _cert_array_from_pem,\n _create_cfstring_array,\n _load_client_cert_chain,\n _temporary_keychain,\n)\n\ntry: # Platform-specific: Python 2\n from socket import _fileobject\nexcept ImportError: # Platform-specific: Python 3\n _fileobject = None\n from ..packages.backports.makefile import backport_makefile\n\n__all__ = ["inject_into_urllib3", "extract_from_urllib3"]\n\n# SNI always works\nHAS_SNI = True\n\norig_util_HAS_SNI = util.HAS_SNI\norig_util_SSLContext = util.ssl_.SSLContext\n\n# This dictionary is used by the read callback to obtain a handle to the\n# calling wrapped socket. This is a pretty silly approach, but for now it'll\n# do. I feel like I should be able to smuggle a handle to the wrapped socket\n# directly in the SSLConnectionRef, but for now this approach will work I\n# guess.\n#\n# We need to lock around this structure for inserts, but we don't do it for\n# reads/writes in the callbacks. The reasoning here goes as follows:\n#\n# 1. It is not possible to call into the callbacks before the dictionary is\n# populated, so once in the callback the id must be in the dictionary.\n# 2. The callbacks don't mutate the dictionary, they only read from it, and\n# so cannot conflict with any of the insertions.\n#\n# This is good: if we had to lock in the callbacks we'd drastically slow down\n# the performance of this code.\n_connection_refs = weakref.WeakValueDictionary()\n_connection_ref_lock = threading.Lock()\n\n# Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over\n# for no better reason than we need *a* limit, and this one is right there.\nSSL_WRITE_BLOCKSIZE = 16384\n\n# This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to\n# individual cipher suites. We need to do this because this is how\n# SecureTransport wants them.\nCIPHER_SUITES = [\n SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n SecurityConst.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n SecurityConst.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,\n SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,\n SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,\n SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,\n SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,\n SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,\n SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,\n SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,\n SecurityConst.TLS_AES_256_GCM_SHA384,\n SecurityConst.TLS_AES_128_GCM_SHA256,\n SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,\n SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,\n SecurityConst.TLS_AES_128_CCM_8_SHA256,\n SecurityConst.TLS_AES_128_CCM_SHA256,\n SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,\n SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,\n SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,\n SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,\n]\n\n# Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of\n# TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.\n# TLSv1 to 1.2 are supported on macOS 10.8+\n_protocol_to_min_max = {\n util.PROTOCOL_TLS: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),\n PROTOCOL_TLS_CLIENT: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),\n}\n\nif hasattr(ssl, "PROTOCOL_SSLv2"):\n _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (\n SecurityConst.kSSLProtocol2,\n SecurityConst.kSSLProtocol2,\n )\nif hasattr(ssl, "PROTOCOL_SSLv3"):\n _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (\n SecurityConst.kSSLProtocol3,\n SecurityConst.kSSLProtocol3,\n )\nif hasattr(ssl, "PROTOCOL_TLSv1"):\n _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (\n SecurityConst.kTLSProtocol1,\n SecurityConst.kTLSProtocol1,\n )\nif hasattr(ssl, "PROTOCOL_TLSv1_1"):\n _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (\n SecurityConst.kTLSProtocol11,\n SecurityConst.kTLSProtocol11,\n )\nif hasattr(ssl, "PROTOCOL_TLSv1_2"):\n _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (\n SecurityConst.kTLSProtocol12,\n SecurityConst.kTLSProtocol12,\n )\n\n\ndef inject_into_urllib3():\n """\n Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n """\n util.SSLContext = SecureTransportContext\n util.ssl_.SSLContext = SecureTransportContext\n util.HAS_SNI = HAS_SNI\n util.ssl_.HAS_SNI = HAS_SNI\n util.IS_SECURETRANSPORT = True\n util.ssl_.IS_SECURETRANSPORT = True\n\n\ndef extract_from_urllib3():\n """\n Undo monkey-patching by :func:`inject_into_urllib3`.\n """\n util.SSLContext = orig_util_SSLContext\n util.ssl_.SSLContext = orig_util_SSLContext\n util.HAS_SNI = orig_util_HAS_SNI\n util.ssl_.HAS_SNI = orig_util_HAS_SNI\n util.IS_SECURETRANSPORT = False\n util.ssl_.IS_SECURETRANSPORT = False\n\n\ndef _read_callback(connection_id, data_buffer, data_length_pointer):\n """\n SecureTransport read callback. This is called by ST to request that data\n be returned from the socket.\n """\n wrapped_socket = None\n try:\n wrapped_socket = _connection_refs.get(connection_id)\n if wrapped_socket is None:\n return SecurityConst.errSSLInternal\n base_socket = wrapped_socket.socket\n\n requested_length = data_length_pointer[0]\n\n timeout = wrapped_socket.gettimeout()\n error = None\n read_count = 0\n\n try:\n while read_count < requested_length:\n if timeout is None or timeout >= 0:\n if not util.wait_for_read(base_socket, timeout):\n raise socket.error(errno.EAGAIN, "timed out")\n\n remaining = requested_length - read_count\n buffer = (ctypes.c_char * remaining).from_address(\n data_buffer + read_count\n )\n chunk_size = base_socket.recv_into(buffer, remaining)\n read_count += chunk_size\n if not chunk_size:\n if not read_count:\n return SecurityConst.errSSLClosedGraceful\n break\n except (socket.error) as e:\n error = e.errno\n\n if error is not None and error != errno.EAGAIN:\n data_length_pointer[0] = read_count\n if error == errno.ECONNRESET or error == errno.EPIPE:\n return SecurityConst.errSSLClosedAbort\n raise\n\n data_length_pointer[0] = read_count\n\n if read_count != requested_length:\n return SecurityConst.errSSLWouldBlock\n\n return 0\n except Exception as e:\n if wrapped_socket is not None:\n wrapped_socket._exception = e\n return SecurityConst.errSSLInternal\n\n\ndef _write_callback(connection_id, data_buffer, data_length_pointer):\n """\n SecureTransport write callback. This is called by ST to request that data\n actually be sent on the network.\n """\n wrapped_socket = None\n try:\n wrapped_socket = _connection_refs.get(connection_id)\n if wrapped_socket is None:\n return SecurityConst.errSSLInternal\n base_socket = wrapped_socket.socket\n\n bytes_to_write = data_length_pointer[0]\n data = ctypes.string_at(data_buffer, bytes_to_write)\n\n timeout = wrapped_socket.gettimeout()\n error = None\n sent = 0\n\n try:\n while sent < bytes_to_write:\n if timeout is None or timeout >= 0:\n if not util.wait_for_write(base_socket, timeout):\n raise socket.error(errno.EAGAIN, "timed out")\n chunk_sent = base_socket.send(data)\n sent += chunk_sent\n\n # This has some needless copying here, but I'm not sure there's\n # much value in optimising this data path.\n data = data[chunk_sent:]\n except (socket.error) as e:\n error = e.errno\n\n if error is not None and error != errno.EAGAIN:\n data_length_pointer[0] = sent\n if error == errno.ECONNRESET or error == errno.EPIPE:\n return SecurityConst.errSSLClosedAbort\n raise\n\n data_length_pointer[0] = sent\n\n if sent != bytes_to_write:\n return SecurityConst.errSSLWouldBlock\n\n return 0\n except Exception as e:\n if wrapped_socket is not None:\n wrapped_socket._exception = e\n return SecurityConst.errSSLInternal\n\n\n# We need to keep these two objects references alive: if they get GC'd while\n# in use then SecureTransport could attempt to call a function that is in freed\n# memory. That would be...uh...bad. Yeah, that's the word. Bad.\n_read_callback_pointer = Security.SSLReadFunc(_read_callback)\n_write_callback_pointer = Security.SSLWriteFunc(_write_callback)\n\n\nclass WrappedSocket(object):\n """\n API-compatibility wrapper for Python's OpenSSL wrapped socket object.\n\n Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage\n collector of PyPy.\n """\n\n def __init__(self, socket):\n self.socket = socket\n self.context = None\n self._makefile_refs = 0\n self._closed = False\n self._exception = None\n self._keychain = None\n self._keychain_dir = None\n self._client_cert_chain = None\n\n # We save off the previously-configured timeout and then set it to\n # zero. This is done because we use select and friends to handle the\n # timeouts, but if we leave the timeout set on the lower socket then\n # Python will "kindly" call select on that socket again for us. Avoid\n # that by forcing the timeout to zero.\n self._timeout = self.socket.gettimeout()\n self.socket.settimeout(0)\n\n @contextlib.contextmanager\n def _raise_on_error(self):\n """\n A context manager that can be used to wrap calls that do I/O from\n SecureTransport. If any of the I/O callbacks hit an exception, this\n context manager will correctly propagate the exception after the fact.\n This avoids silently swallowing those exceptions.\n\n It also correctly forces the socket closed.\n """\n self._exception = None\n\n # We explicitly don't catch around this yield because in the unlikely\n # event that an exception was hit in the block we don't want to swallow\n # it.\n yield\n if self._exception is not None:\n exception, self._exception = self._exception, None\n self.close()\n raise exception\n\n def _set_ciphers(self):\n """\n Sets up the allowed ciphers. By default this matches the set in\n util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done\n custom and doesn't allow changing at this time, mostly because parsing\n OpenSSL cipher strings is going to be a freaking nightmare.\n """\n ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)\n result = Security.SSLSetEnabledCiphers(\n self.context, ciphers, len(CIPHER_SUITES)\n )\n _assert_no_error(result)\n\n def _set_alpn_protocols(self, protocols):\n """\n Sets up the ALPN protocols on the context.\n """\n if not protocols:\n return\n protocols_arr = _create_cfstring_array(protocols)\n try:\n result = Security.SSLSetALPNProtocols(self.context, protocols_arr)\n _assert_no_error(result)\n finally:\n CoreFoundation.CFRelease(protocols_arr)\n\n def _custom_validate(self, verify, trust_bundle):\n """\n Called when we have set custom validation. We do this in two cases:\n first, when cert validation is entirely disabled; and second, when\n using a custom trust DB.\n Raises an SSLError if the connection is not trusted.\n """\n # If we disabled cert validation, just say: cool.\n if not verify:\n return\n\n successes = (\n SecurityConst.kSecTrustResultUnspecified,\n SecurityConst.kSecTrustResultProceed,\n )\n try:\n trust_result = self._evaluate_trust(trust_bundle)\n if trust_result in successes:\n return\n reason = "error code: %d" % (trust_result,)\n except Exception as e:\n # Do not trust on error\n reason = "exception: %r" % (e,)\n\n # SecureTransport does not send an alert nor shuts down the connection.\n rec = _build_tls_unknown_ca_alert(self.version())\n self.socket.sendall(rec)\n # close the connection immediately\n # l_onoff = 1, activate linger\n # l_linger = 0, linger for 0 seoncds\n opts = struct.pack("ii", 1, 0)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, opts)\n self.close()\n raise ssl.SSLError("certificate verify failed, %s" % reason)\n\n def _evaluate_trust(self, trust_bundle):\n # We want data in memory, so load it up.\n if os.path.isfile(trust_bundle):\n with open(trust_bundle, "rb") as f:\n trust_bundle = f.read()\n\n cert_array = None\n trust = Security.SecTrustRef()\n\n try:\n # Get a CFArray that contains the certs we want.\n cert_array = _cert_array_from_pem(trust_bundle)\n\n # Ok, now the hard part. We want to get the SecTrustRef that ST has\n # created for this connection, shove our CAs into it, tell ST to\n # ignore everything else it knows, and then ask if it can build a\n # chain. This is a buuuunch of code.\n result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))\n _assert_no_error(result)\n if not trust:\n raise ssl.SSLError("Failed to copy trust reference")\n\n result = Security.SecTrustSetAnchorCertificates(trust, cert_array)\n _assert_no_error(result)\n\n result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)\n _assert_no_error(result)\n\n trust_result = Security.SecTrustResultType()\n result = Security.SecTrustEvaluate(trust, ctypes.byref(trust_result))\n _assert_no_error(result)\n finally:\n if trust:\n CoreFoundation.CFRelease(trust)\n\n if cert_array is not None:\n CoreFoundation.CFRelease(cert_array)\n\n return trust_result.value\n\n def handshake(\n self,\n server_hostname,\n verify,\n trust_bundle,\n min_version,\n max_version,\n client_cert,\n client_key,\n client_key_passphrase,\n alpn_protocols,\n ):\n """\n Actually performs the TLS handshake. This is run automatically by\n wrapped socket, and shouldn't be needed in user code.\n """\n # First, we do the initial bits of connection setup. We need to create\n # a context, set its I/O funcs, and set the connection reference.\n self.context = Security.SSLCreateContext(\n None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType\n )\n result = Security.SSLSetIOFuncs(\n self.context, _read_callback_pointer, _write_callback_pointer\n )\n _assert_no_error(result)\n\n # Here we need to compute the handle to use. We do this by taking the\n # id of self modulo 2**31 - 1. If this is already in the dictionary, we\n # just keep incrementing by one until we find a free space.\n with _connection_ref_lock:\n handle = id(self) % 2147483647\n while handle in _connection_refs:\n handle = (handle + 1) % 2147483647\n _connection_refs[handle] = self\n\n result = Security.SSLSetConnection(self.context, handle)\n _assert_no_error(result)\n\n # If we have a server hostname, we should set that too.\n if server_hostname:\n if not isinstance(server_hostname, bytes):\n server_hostname = server_hostname.encode("utf-8")\n\n result = Security.SSLSetPeerDomainName(\n self.context, server_hostname, len(server_hostname)\n )\n _assert_no_error(result)\n\n # Setup the ciphers.\n self._set_ciphers()\n\n # Setup the ALPN protocols.\n self._set_alpn_protocols(alpn_protocols)\n\n # Set the minimum and maximum TLS versions.\n result = Security.SSLSetProtocolVersionMin(self.context, min_version)\n _assert_no_error(result)\n\n result = Security.SSLSetProtocolVersionMax(self.context, max_version)\n _assert_no_error(result)\n\n # If there's a trust DB, we need to use it. We do that by telling\n # SecureTransport to break on server auth. We also do that if we don't\n # want to validate the certs at all: we just won't actually do any\n # authing in that case.\n if not verify or trust_bundle is not None:\n result = Security.SSLSetSessionOption(\n self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True\n )\n _assert_no_error(result)\n\n # If there's a client cert, we need to use it.\n if client_cert:\n self._keychain, self._keychain_dir = _temporary_keychain()\n self._client_cert_chain = _load_client_cert_chain(\n self._keychain, client_cert, client_key\n )\n result = Security.SSLSetCertificate(self.context, self._client_cert_chain)\n _assert_no_error(result)\n\n while True:\n with self._raise_on_error():\n result = Security.SSLHandshake(self.context)\n\n if result == SecurityConst.errSSLWouldBlock:\n raise socket.timeout("handshake timed out")\n elif result == SecurityConst.errSSLServerAuthCompleted:\n self._custom_validate(verify, trust_bundle)\n continue\n else:\n _assert_no_error(result)\n break\n\n def fileno(self):\n return self.socket.fileno()\n\n # Copy-pasted from Python 3.5 source code\n def _decref_socketios(self):\n if self._makefile_refs > 0:\n self._makefile_refs -= 1\n if self._closed:\n self.close()\n\n def recv(self, bufsiz):\n buffer = ctypes.create_string_buffer(bufsiz)\n bytes_read = self.recv_into(buffer, bufsiz)\n data = buffer[:bytes_read]\n return data\n\n def recv_into(self, buffer, nbytes=None):\n # Read short on EOF.\n if self._closed:\n return 0\n\n if nbytes is None:\n nbytes = len(buffer)\n\n buffer = (ctypes.c_char * nbytes).from_buffer(buffer)\n processed_bytes = ctypes.c_size_t(0)\n\n with self._raise_on_error():\n result = Security.SSLRead(\n self.context, buffer, nbytes, ctypes.byref(processed_bytes)\n )\n\n # There are some result codes that we want to treat as "not always\n # errors". Specifically, those are errSSLWouldBlock,\n # errSSLClosedGraceful, and errSSLClosedNoNotify.\n if result == SecurityConst.errSSLWouldBlock:\n # If we didn't process any bytes, then this was just a time out.\n # However, we can get errSSLWouldBlock in situations when we *did*\n # read some data, and in those cases we should just read "short"\n # and return.\n if processed_bytes.value == 0:\n # Timed out, no data read.\n raise socket.timeout("recv timed out")\n elif result in (\n SecurityConst.errSSLClosedGraceful,\n SecurityConst.errSSLClosedNoNotify,\n ):\n # The remote peer has closed this connection. We should do so as\n # well. Note that we don't actually return here because in\n # principle this could actually be fired along with return data.\n # It's unlikely though.\n self.close()\n else:\n _assert_no_error(result)\n\n # Ok, we read and probably succeeded. We should return whatever data\n # was actually read.\n return processed_bytes.value\n\n def settimeout(self, timeout):\n self._timeout = timeout\n\n def gettimeout(self):\n return self._timeout\n\n def send(self, data):\n processed_bytes = ctypes.c_size_t(0)\n\n with self._raise_on_error():\n result = Security.SSLWrite(\n self.context, data, len(data), ctypes.byref(processed_bytes)\n )\n\n if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:\n # Timed out\n raise socket.timeout("send timed out")\n else:\n _assert_no_error(result)\n\n # We sent, and probably succeeded. Tell them how much we sent.\n return processed_bytes.value\n\n def sendall(self, data):\n total_sent = 0\n while total_sent < len(data):\n sent = self.send(data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE])\n total_sent += sent\n\n def shutdown(self):\n with self._raise_on_error():\n Security.SSLClose(self.context)\n\n def close(self):\n # TODO: should I do clean shutdown here? Do I have to?\n if self._makefile_refs < 1:\n self._closed = True\n if self.context:\n CoreFoundation.CFRelease(self.context)\n self.context = None\n if self._client_cert_chain:\n CoreFoundation.CFRelease(self._client_cert_chain)\n self._client_cert_chain = None\n if self._keychain:\n Security.SecKeychainDelete(self._keychain)\n CoreFoundation.CFRelease(self._keychain)\n shutil.rmtree(self._keychain_dir)\n self._keychain = self._keychain_dir = None\n return self.socket.close()\n else:\n self._makefile_refs -= 1\n\n def getpeercert(self, binary_form=False):\n # Urgh, annoying.\n #\n # Here's how we do this:\n #\n # 1. Call SSLCopyPeerTrust to get hold of the trust object for this\n # connection.\n # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.\n # 3. To get the CN, call SecCertificateCopyCommonName and process that\n # string so that it's of the appropriate type.\n # 4. To get the SAN, we need to do something a bit more complex:\n # a. Call SecCertificateCopyValues to get the data, requesting\n # kSecOIDSubjectAltName.\n # b. Mess about with this dictionary to try to get the SANs out.\n #\n # This is gross. Really gross. It's going to be a few hundred LoC extra\n # just to repeat something that SecureTransport can *already do*. So my\n # operating assumption at this time is that what we want to do is\n # instead to just flag to urllib3 that it shouldn't do its own hostname\n # validation when using SecureTransport.\n if not binary_form:\n raise ValueError("SecureTransport only supports dumping binary certs")\n trust = Security.SecTrustRef()\n certdata = None\n der_bytes = None\n\n try:\n # Grab the trust store.\n result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))\n _assert_no_error(result)\n if not trust:\n # Probably we haven't done the handshake yet. No biggie.\n return None\n\n cert_count = Security.SecTrustGetCertificateCount(trust)\n if not cert_count:\n # Also a case that might happen if we haven't handshaked.\n # Handshook? Handshaken?\n return None\n\n leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)\n assert leaf\n\n # Ok, now we want the DER bytes.\n certdata = Security.SecCertificateCopyData(leaf)\n assert certdata\n\n data_length = CoreFoundation.CFDataGetLength(certdata)\n data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)\n der_bytes = ctypes.string_at(data_buffer, data_length)\n finally:\n if certdata:\n CoreFoundation.CFRelease(certdata)\n if trust:\n CoreFoundation.CFRelease(trust)\n\n return der_bytes\n\n def version(self):\n protocol = Security.SSLProtocol()\n result = Security.SSLGetNegotiatedProtocolVersion(\n self.context, ctypes.byref(protocol)\n )\n _assert_no_error(result)\n if protocol.value == SecurityConst.kTLSProtocol13:\n raise ssl.SSLError("SecureTransport does not support TLS 1.3")\n elif protocol.value == SecurityConst.kTLSProtocol12:\n return "TLSv1.2"\n elif protocol.value == SecurityConst.kTLSProtocol11:\n return "TLSv1.1"\n elif protocol.value == SecurityConst.kTLSProtocol1:\n return "TLSv1"\n elif protocol.value == SecurityConst.kSSLProtocol3:\n return "SSLv3"\n elif protocol.value == SecurityConst.kSSLProtocol2:\n return "SSLv2"\n else:\n raise ssl.SSLError("Unknown TLS version: %r" % protocol)\n\n def _reuse(self):\n self._makefile_refs += 1\n\n def _drop(self):\n if self._makefile_refs < 1:\n self.close()\n else:\n self._makefile_refs -= 1\n\n\nif _fileobject: # Platform-specific: Python 2\n\n def makefile(self, mode, bufsize=-1):\n self._makefile_refs += 1\n return _fileobject(self, mode, bufsize, close=True)\n\nelse: # Platform-specific: Python 3\n\n def makefile(self, mode="r", buffering=None, *args, **kwargs):\n # We disable buffering with SecureTransport because it conflicts with\n # the buffering that ST does internally (see issue #1153 for more).\n buffering = 0\n return backport_makefile(self, mode, buffering, *args, **kwargs)\n\n\nWrappedSocket.makefile = makefile\n\n\nclass SecureTransportContext(object):\n """\n I am a wrapper class for the SecureTransport library, to translate the\n interface of the standard library ``SSLContext`` object to calls into\n SecureTransport.\n """\n\n def __init__(self, protocol):\n self._min_version, self._max_version = _protocol_to_min_max[protocol]\n self._options = 0\n self._verify = False\n self._trust_bundle = None\n self._client_cert = None\n self._client_key = None\n self._client_key_passphrase = None\n self._alpn_protocols = None\n\n @property\n def check_hostname(self):\n """\n SecureTransport cannot have its hostname checking disabled. For more,\n see the comment on getpeercert() in this file.\n """\n return True\n\n @check_hostname.setter\n def check_hostname(self, value):\n """\n SecureTransport cannot have its hostname checking disabled. For more,\n see the comment on getpeercert() in this file.\n """\n pass\n\n @property\n def options(self):\n # TODO: Well, crap.\n #\n # So this is the bit of the code that is the most likely to cause us\n # trouble. Essentially we need to enumerate all of the SSL options that\n # users might want to use and try to see if we can sensibly translate\n # them, or whether we should just ignore them.\n return self._options\n\n @options.setter\n def options(self, value):\n # TODO: Update in line with above.\n self._options = value\n\n @property\n def verify_mode(self):\n return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE\n\n @verify_mode.setter\n def verify_mode(self, value):\n self._verify = True if value == ssl.CERT_REQUIRED else False\n\n def set_default_verify_paths(self):\n # So, this has to do something a bit weird. Specifically, what it does\n # is nothing.\n #\n # This means that, if we had previously had load_verify_locations\n # called, this does not undo that. We need to do that because it turns\n # out that the rest of the urllib3 code will attempt to load the\n # default verify paths if it hasn't been told about any paths, even if\n # the context itself was sometime earlier. We resolve that by just\n # ignoring it.\n pass\n\n def load_default_certs(self):\n return self.set_default_verify_paths()\n\n def set_ciphers(self, ciphers):\n # For now, we just require the default cipher string.\n if ciphers != util.ssl_.DEFAULT_CIPHERS:\n raise ValueError("SecureTransport doesn't support custom cipher strings")\n\n def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n # OK, we only really support cadata and cafile.\n if capath is not None:\n raise ValueError("SecureTransport does not support cert directories")\n\n # Raise if cafile does not exist.\n if cafile is not None:\n with open(cafile):\n pass\n\n self._trust_bundle = cafile or cadata\n\n def load_cert_chain(self, certfile, keyfile=None, password=None):\n self._client_cert = certfile\n self._client_key = keyfile\n self._client_cert_passphrase = password\n\n def set_alpn_protocols(self, protocols):\n """\n Sets the ALPN protocols that will later be set on the context.\n\n Raises a NotImplementedError if ALPN is not supported.\n """\n if not hasattr(Security, "SSLSetALPNProtocols"):\n raise NotImplementedError(\n "SecureTransport supports ALPN only in macOS 10.12+"\n )\n self._alpn_protocols = [six.ensure_binary(p) for p in protocols]\n\n def wrap_socket(\n self,\n sock,\n server_side=False,\n do_handshake_on_connect=True,\n suppress_ragged_eofs=True,\n server_hostname=None,\n ):\n # So, what do we do here? Firstly, we assert some properties. This is a\n # stripped down shim, so there is some functionality we don't support.\n # See PEP 543 for the real deal.\n assert not server_side\n assert do_handshake_on_connect\n assert suppress_ragged_eofs\n\n # Ok, we're good to go. Now we want to create the wrapped socket object\n # and store it in the appropriate place.\n wrapped_socket = WrappedSocket(sock)\n\n # Now we can handshake\n wrapped_socket.handshake(\n server_hostname,\n self._verify,\n self._trust_bundle,\n self._min_version,\n self._max_version,\n self._client_cert,\n self._client_key,\n self._client_key_passphrase,\n self._alpn_protocols,\n )\n return wrapped_socket\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\securetransport.py | securetransport.py | Python | 34,446 | 0.95 | 0.169565 | 0.171795 | react-lib | 792 | 2023-12-12T00:05:51.452048 | Apache-2.0 | false | 28c7513449b1d57d1d5cfbaa015b5ae3 |
# -*- coding: utf-8 -*-\n"""\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and\nSOCKS5. To enable its functionality, either install PySocks or install this\nmodule with the ``socks`` extra.\n\nThe SOCKS implementation supports the full range of urllib3 features. It also\nsupports the following SOCKS features:\n\n- SOCKS4A (``proxy_url='socks4a://...``)\n- SOCKS4 (``proxy_url='socks4://...``)\n- SOCKS5 with remote DNS (``proxy_url='socks5h://...``)\n- SOCKS5 with local DNS (``proxy_url='socks5://...``)\n- Usernames and passwords for the SOCKS proxy\n\n.. note::\n It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in\n your ``proxy_url`` to ensure that DNS resolution is done from the remote\n server instead of client-side when connecting to a domain name.\n\nSOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5\nsupports IPv4, IPv6, and domain names.\n\nWhen connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url``\nwill be sent as the ``userid`` section of the SOCKS request:\n\n.. code-block:: python\n\n proxy_url="socks4a://<userid>@proxy-host"\n\nWhen connecting to a SOCKS5 proxy the ``username`` and ``password`` portion\nof the ``proxy_url`` will be sent as the username/password to authenticate\nwith the proxy:\n\n.. code-block:: python\n\n proxy_url="socks5h://<username>:<password>@proxy-host"\n\n"""\nfrom __future__ import absolute_import\n\ntry:\n import socks\nexcept ImportError:\n import warnings\n\n from ..exceptions import DependencyWarning\n\n warnings.warn(\n (\n "SOCKS support in urllib3 requires the installation of optional "\n "dependencies: specifically, PySocks. For more information, see "\n "https://urllib3.readthedocs.io/en/1.26.x/contrib.html#socks-proxies"\n ),\n DependencyWarning,\n )\n raise\n\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom ..connection import HTTPConnection, HTTPSConnection\nfrom ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool\nfrom ..exceptions import ConnectTimeoutError, NewConnectionError\nfrom ..poolmanager import PoolManager\nfrom ..util.url import parse_url\n\ntry:\n import ssl\nexcept ImportError:\n ssl = None\n\n\nclass SOCKSConnection(HTTPConnection):\n """\n A plain-text HTTP connection that connects via a SOCKS proxy.\n """\n\n def __init__(self, *args, **kwargs):\n self._socks_options = kwargs.pop("_socks_options")\n super(SOCKSConnection, self).__init__(*args, **kwargs)\n\n def _new_conn(self):\n """\n Establish a new connection via the SOCKS proxy.\n """\n extra_kw = {}\n if self.source_address:\n extra_kw["source_address"] = self.source_address\n\n if self.socket_options:\n extra_kw["socket_options"] = self.socket_options\n\n try:\n conn = socks.create_connection(\n (self.host, self.port),\n proxy_type=self._socks_options["socks_version"],\n proxy_addr=self._socks_options["proxy_host"],\n proxy_port=self._socks_options["proxy_port"],\n proxy_username=self._socks_options["username"],\n proxy_password=self._socks_options["password"],\n proxy_rdns=self._socks_options["rdns"],\n timeout=self.timeout,\n **extra_kw\n )\n\n except SocketTimeout:\n raise ConnectTimeoutError(\n self,\n "Connection to %s timed out. (connect timeout=%s)"\n % (self.host, self.timeout),\n )\n\n except socks.ProxyError as e:\n # This is fragile as hell, but it seems to be the only way to raise\n # useful errors here.\n if e.socket_err:\n error = e.socket_err\n if isinstance(error, SocketTimeout):\n raise ConnectTimeoutError(\n self,\n "Connection to %s timed out. (connect timeout=%s)"\n % (self.host, self.timeout),\n )\n else:\n raise NewConnectionError(\n self, "Failed to establish a new connection: %s" % error\n )\n else:\n raise NewConnectionError(\n self, "Failed to establish a new connection: %s" % e\n )\n\n except SocketError as e: # Defensive: PySocks should catch all these.\n raise NewConnectionError(\n self, "Failed to establish a new connection: %s" % e\n )\n\n return conn\n\n\n# We don't need to duplicate the Verified/Unverified distinction from\n# urllib3/connection.py here because the HTTPSConnection will already have been\n# correctly set to either the Verified or Unverified form by that module. This\n# means the SOCKSHTTPSConnection will automatically be the correct type.\nclass SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):\n pass\n\n\nclass SOCKSHTTPConnectionPool(HTTPConnectionPool):\n ConnectionCls = SOCKSConnection\n\n\nclass SOCKSHTTPSConnectionPool(HTTPSConnectionPool):\n ConnectionCls = SOCKSHTTPSConnection\n\n\nclass SOCKSProxyManager(PoolManager):\n """\n A version of the urllib3 ProxyManager that routes connections via the\n defined SOCKS proxy.\n """\n\n pool_classes_by_scheme = {\n "http": SOCKSHTTPConnectionPool,\n "https": SOCKSHTTPSConnectionPool,\n }\n\n def __init__(\n self,\n proxy_url,\n username=None,\n password=None,\n num_pools=10,\n headers=None,\n **connection_pool_kw\n ):\n parsed = parse_url(proxy_url)\n\n if username is None and password is None and parsed.auth is not None:\n split = parsed.auth.split(":")\n if len(split) == 2:\n username, password = split\n if parsed.scheme == "socks5":\n socks_version = socks.PROXY_TYPE_SOCKS5\n rdns = False\n elif parsed.scheme == "socks5h":\n socks_version = socks.PROXY_TYPE_SOCKS5\n rdns = True\n elif parsed.scheme == "socks4":\n socks_version = socks.PROXY_TYPE_SOCKS4\n rdns = False\n elif parsed.scheme == "socks4a":\n socks_version = socks.PROXY_TYPE_SOCKS4\n rdns = True\n else:\n raise ValueError("Unable to determine SOCKS version from %s" % proxy_url)\n\n self.proxy_url = proxy_url\n\n socks_options = {\n "socks_version": socks_version,\n "proxy_host": parsed.host,\n "proxy_port": parsed.port,\n "username": username,\n "password": password,\n "rdns": rdns,\n }\n connection_pool_kw["_socks_options"] = socks_options\n\n super(SOCKSProxyManager, self).__init__(\n num_pools, headers, **connection_pool_kw\n )\n\n self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\socks.py | socks.py | Python | 7,097 | 0.95 | 0.097222 | 0.051724 | awesome-app | 790 | 2023-08-02T01:52:45.743365 | GPL-3.0 | false | 1cc7d6aeba0181cc04ca63f73e21abf4 |
"""\nThis module provides means to detect the App Engine environment.\n"""\n\nimport os\n\n\ndef is_appengine():\n return is_local_appengine() or is_prod_appengine()\n\n\ndef is_appengine_sandbox():\n """Reports if the app is running in the first generation sandbox.\n\n The second generation runtimes are technically still in a sandbox, but it\n is much less restrictive, so generally you shouldn't need to check for it.\n see https://cloud.google.com/appengine/docs/standard/runtimes\n """\n return is_appengine() and os.environ["APPENGINE_RUNTIME"] == "python27"\n\n\ndef is_local_appengine():\n return "APPENGINE_RUNTIME" in os.environ and os.environ.get(\n "SERVER_SOFTWARE", ""\n ).startswith("Development/")\n\n\ndef is_prod_appengine():\n return "APPENGINE_RUNTIME" in os.environ and os.environ.get(\n "SERVER_SOFTWARE", ""\n ).startswith("Google App Engine/")\n\n\ndef is_prod_appengine_mvms():\n """Deprecated."""\n return False\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\_appengine_environ.py | _appengine_environ.py | Python | 957 | 0.95 | 0.194444 | 0 | awesome-app | 660 | 2025-04-21T00:19:06.099879 | Apache-2.0 | false | acc1a179e0ec7e6c78ddf8ca298ab6c2 |
"""\nThis module uses ctypes to bind a whole bunch of functions and constants from\nSecureTransport. The goal here is to provide the low-level API to\nSecureTransport. These are essentially the C-level functions and constants, and\nthey're pretty gross to work with.\n\nThis code is a bastardised version of the code found in Will Bond's oscrypto\nlibrary. An enormous debt is owed to him for blazing this trail for us. For\nthat reason, this code should be considered to be covered both by urllib3's\nlicense and by oscrypto's:\n\n Copyright (c) 2015-2016 Will Bond <will@wbond.net>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the "Software"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n"""\nfrom __future__ import absolute_import\n\nimport platform\nfrom ctypes import (\n CDLL,\n CFUNCTYPE,\n POINTER,\n c_bool,\n c_byte,\n c_char_p,\n c_int32,\n c_long,\n c_size_t,\n c_uint32,\n c_ulong,\n c_void_p,\n)\nfrom ctypes.util import find_library\n\nfrom ...packages.six import raise_from\n\nif platform.system() != "Darwin":\n raise ImportError("Only macOS is supported")\n\nversion = platform.mac_ver()[0]\nversion_info = tuple(map(int, version.split(".")))\nif version_info < (10, 8):\n raise OSError(\n "Only OS X 10.8 and newer are supported, not %s.%s"\n % (version_info[0], version_info[1])\n )\n\n\ndef load_cdll(name, macos10_16_path):\n """Loads a CDLL by name, falling back to known path on 10.16+"""\n try:\n # Big Sur is technically 11 but we use 10.16 due to the Big Sur\n # beta being labeled as 10.16.\n if version_info >= (10, 16):\n path = macos10_16_path\n else:\n path = find_library(name)\n if not path:\n raise OSError # Caught and reraised as 'ImportError'\n return CDLL(path, use_errno=True)\n except OSError:\n raise_from(ImportError("The library %s failed to load" % name), None)\n\n\nSecurity = load_cdll(\n "Security", "/System/Library/Frameworks/Security.framework/Security"\n)\nCoreFoundation = load_cdll(\n "CoreFoundation",\n "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",\n)\n\n\nBoolean = c_bool\nCFIndex = c_long\nCFStringEncoding = c_uint32\nCFData = c_void_p\nCFString = c_void_p\nCFArray = c_void_p\nCFMutableArray = c_void_p\nCFDictionary = c_void_p\nCFError = c_void_p\nCFType = c_void_p\nCFTypeID = c_ulong\n\nCFTypeRef = POINTER(CFType)\nCFAllocatorRef = c_void_p\n\nOSStatus = c_int32\n\nCFDataRef = POINTER(CFData)\nCFStringRef = POINTER(CFString)\nCFArrayRef = POINTER(CFArray)\nCFMutableArrayRef = POINTER(CFMutableArray)\nCFDictionaryRef = POINTER(CFDictionary)\nCFArrayCallBacks = c_void_p\nCFDictionaryKeyCallBacks = c_void_p\nCFDictionaryValueCallBacks = c_void_p\n\nSecCertificateRef = POINTER(c_void_p)\nSecExternalFormat = c_uint32\nSecExternalItemType = c_uint32\nSecIdentityRef = POINTER(c_void_p)\nSecItemImportExportFlags = c_uint32\nSecItemImportExportKeyParameters = c_void_p\nSecKeychainRef = POINTER(c_void_p)\nSSLProtocol = c_uint32\nSSLCipherSuite = c_uint32\nSSLContextRef = POINTER(c_void_p)\nSecTrustRef = POINTER(c_void_p)\nSSLConnectionRef = c_uint32\nSecTrustResultType = c_uint32\nSecTrustOptionFlags = c_uint32\nSSLProtocolSide = c_uint32\nSSLConnectionType = c_uint32\nSSLSessionOption = c_uint32\n\n\ntry:\n Security.SecItemImport.argtypes = [\n CFDataRef,\n CFStringRef,\n POINTER(SecExternalFormat),\n POINTER(SecExternalItemType),\n SecItemImportExportFlags,\n POINTER(SecItemImportExportKeyParameters),\n SecKeychainRef,\n POINTER(CFArrayRef),\n ]\n Security.SecItemImport.restype = OSStatus\n\n Security.SecCertificateGetTypeID.argtypes = []\n Security.SecCertificateGetTypeID.restype = CFTypeID\n\n Security.SecIdentityGetTypeID.argtypes = []\n Security.SecIdentityGetTypeID.restype = CFTypeID\n\n Security.SecKeyGetTypeID.argtypes = []\n Security.SecKeyGetTypeID.restype = CFTypeID\n\n Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]\n Security.SecCertificateCreateWithData.restype = SecCertificateRef\n\n Security.SecCertificateCopyData.argtypes = [SecCertificateRef]\n Security.SecCertificateCopyData.restype = CFDataRef\n\n Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n Security.SecCopyErrorMessageString.restype = CFStringRef\n\n Security.SecIdentityCreateWithCertificate.argtypes = [\n CFTypeRef,\n SecCertificateRef,\n POINTER(SecIdentityRef),\n ]\n Security.SecIdentityCreateWithCertificate.restype = OSStatus\n\n Security.SecKeychainCreate.argtypes = [\n c_char_p,\n c_uint32,\n c_void_p,\n Boolean,\n c_void_p,\n POINTER(SecKeychainRef),\n ]\n Security.SecKeychainCreate.restype = OSStatus\n\n Security.SecKeychainDelete.argtypes = [SecKeychainRef]\n Security.SecKeychainDelete.restype = OSStatus\n\n Security.SecPKCS12Import.argtypes = [\n CFDataRef,\n CFDictionaryRef,\n POINTER(CFArrayRef),\n ]\n Security.SecPKCS12Import.restype = OSStatus\n\n SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t))\n SSLWriteFunc = CFUNCTYPE(\n OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t)\n )\n\n Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc]\n Security.SSLSetIOFuncs.restype = OSStatus\n\n Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t]\n Security.SSLSetPeerID.restype = OSStatus\n\n Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef]\n Security.SSLSetCertificate.restype = OSStatus\n\n Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean]\n Security.SSLSetCertificateAuthorities.restype = OSStatus\n\n Security.SSLSetConnection.argtypes = [SSLContextRef, SSLConnectionRef]\n Security.SSLSetConnection.restype = OSStatus\n\n Security.SSLSetPeerDomainName.argtypes = [SSLContextRef, c_char_p, c_size_t]\n Security.SSLSetPeerDomainName.restype = OSStatus\n\n Security.SSLHandshake.argtypes = [SSLContextRef]\n Security.SSLHandshake.restype = OSStatus\n\n Security.SSLRead.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]\n Security.SSLRead.restype = OSStatus\n\n Security.SSLWrite.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]\n Security.SSLWrite.restype = OSStatus\n\n Security.SSLClose.argtypes = [SSLContextRef]\n Security.SSLClose.restype = OSStatus\n\n Security.SSLGetNumberSupportedCiphers.argtypes = [SSLContextRef, POINTER(c_size_t)]\n Security.SSLGetNumberSupportedCiphers.restype = OSStatus\n\n Security.SSLGetSupportedCiphers.argtypes = [\n SSLContextRef,\n POINTER(SSLCipherSuite),\n POINTER(c_size_t),\n ]\n Security.SSLGetSupportedCiphers.restype = OSStatus\n\n Security.SSLSetEnabledCiphers.argtypes = [\n SSLContextRef,\n POINTER(SSLCipherSuite),\n c_size_t,\n ]\n Security.SSLSetEnabledCiphers.restype = OSStatus\n\n Security.SSLGetNumberEnabledCiphers.argtype = [SSLContextRef, POINTER(c_size_t)]\n Security.SSLGetNumberEnabledCiphers.restype = OSStatus\n\n Security.SSLGetEnabledCiphers.argtypes = [\n SSLContextRef,\n POINTER(SSLCipherSuite),\n POINTER(c_size_t),\n ]\n Security.SSLGetEnabledCiphers.restype = OSStatus\n\n Security.SSLGetNegotiatedCipher.argtypes = [SSLContextRef, POINTER(SSLCipherSuite)]\n Security.SSLGetNegotiatedCipher.restype = OSStatus\n\n Security.SSLGetNegotiatedProtocolVersion.argtypes = [\n SSLContextRef,\n POINTER(SSLProtocol),\n ]\n Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus\n\n Security.SSLCopyPeerTrust.argtypes = [SSLContextRef, POINTER(SecTrustRef)]\n Security.SSLCopyPeerTrust.restype = OSStatus\n\n Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]\n Security.SecTrustSetAnchorCertificates.restype = OSStatus\n\n Security.SecTrustSetAnchorCertificatesOnly.argstypes = [SecTrustRef, Boolean]\n Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus\n\n Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)]\n Security.SecTrustEvaluate.restype = OSStatus\n\n Security.SecTrustGetCertificateCount.argtypes = [SecTrustRef]\n Security.SecTrustGetCertificateCount.restype = CFIndex\n\n Security.SecTrustGetCertificateAtIndex.argtypes = [SecTrustRef, CFIndex]\n Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef\n\n Security.SSLCreateContext.argtypes = [\n CFAllocatorRef,\n SSLProtocolSide,\n SSLConnectionType,\n ]\n Security.SSLCreateContext.restype = SSLContextRef\n\n Security.SSLSetSessionOption.argtypes = [SSLContextRef, SSLSessionOption, Boolean]\n Security.SSLSetSessionOption.restype = OSStatus\n\n Security.SSLSetProtocolVersionMin.argtypes = [SSLContextRef, SSLProtocol]\n Security.SSLSetProtocolVersionMin.restype = OSStatus\n\n Security.SSLSetProtocolVersionMax.argtypes = [SSLContextRef, SSLProtocol]\n Security.SSLSetProtocolVersionMax.restype = OSStatus\n\n try:\n Security.SSLSetALPNProtocols.argtypes = [SSLContextRef, CFArrayRef]\n Security.SSLSetALPNProtocols.restype = OSStatus\n except AttributeError:\n # Supported only in 10.12+\n pass\n\n Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n Security.SecCopyErrorMessageString.restype = CFStringRef\n\n Security.SSLReadFunc = SSLReadFunc\n Security.SSLWriteFunc = SSLWriteFunc\n Security.SSLContextRef = SSLContextRef\n Security.SSLProtocol = SSLProtocol\n Security.SSLCipherSuite = SSLCipherSuite\n Security.SecIdentityRef = SecIdentityRef\n Security.SecKeychainRef = SecKeychainRef\n Security.SecTrustRef = SecTrustRef\n Security.SecTrustResultType = SecTrustResultType\n Security.SecExternalFormat = SecExternalFormat\n Security.OSStatus = OSStatus\n\n Security.kSecImportExportPassphrase = CFStringRef.in_dll(\n Security, "kSecImportExportPassphrase"\n )\n Security.kSecImportItemIdentity = CFStringRef.in_dll(\n Security, "kSecImportItemIdentity"\n )\n\n # CoreFoundation time!\n CoreFoundation.CFRetain.argtypes = [CFTypeRef]\n CoreFoundation.CFRetain.restype = CFTypeRef\n\n CoreFoundation.CFRelease.argtypes = [CFTypeRef]\n CoreFoundation.CFRelease.restype = None\n\n CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]\n CoreFoundation.CFGetTypeID.restype = CFTypeID\n\n CoreFoundation.CFStringCreateWithCString.argtypes = [\n CFAllocatorRef,\n c_char_p,\n CFStringEncoding,\n ]\n CoreFoundation.CFStringCreateWithCString.restype = CFStringRef\n\n CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]\n CoreFoundation.CFStringGetCStringPtr.restype = c_char_p\n\n CoreFoundation.CFStringGetCString.argtypes = [\n CFStringRef,\n c_char_p,\n CFIndex,\n CFStringEncoding,\n ]\n CoreFoundation.CFStringGetCString.restype = c_bool\n\n CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]\n CoreFoundation.CFDataCreate.restype = CFDataRef\n\n CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]\n CoreFoundation.CFDataGetLength.restype = CFIndex\n\n CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]\n CoreFoundation.CFDataGetBytePtr.restype = c_void_p\n\n CoreFoundation.CFDictionaryCreate.argtypes = [\n CFAllocatorRef,\n POINTER(CFTypeRef),\n POINTER(CFTypeRef),\n CFIndex,\n CFDictionaryKeyCallBacks,\n CFDictionaryValueCallBacks,\n ]\n CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef\n\n CoreFoundation.CFDictionaryGetValue.argtypes = [CFDictionaryRef, CFTypeRef]\n CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef\n\n CoreFoundation.CFArrayCreate.argtypes = [\n CFAllocatorRef,\n POINTER(CFTypeRef),\n CFIndex,\n CFArrayCallBacks,\n ]\n CoreFoundation.CFArrayCreate.restype = CFArrayRef\n\n CoreFoundation.CFArrayCreateMutable.argtypes = [\n CFAllocatorRef,\n CFIndex,\n CFArrayCallBacks,\n ]\n CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef\n\n CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]\n CoreFoundation.CFArrayAppendValue.restype = None\n\n CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]\n CoreFoundation.CFArrayGetCount.restype = CFIndex\n\n CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]\n CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p\n\n CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll(\n CoreFoundation, "kCFAllocatorDefault"\n )\n CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(\n CoreFoundation, "kCFTypeArrayCallBacks"\n )\n CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll(\n CoreFoundation, "kCFTypeDictionaryKeyCallBacks"\n )\n CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll(\n CoreFoundation, "kCFTypeDictionaryValueCallBacks"\n )\n\n CoreFoundation.CFTypeRef = CFTypeRef\n CoreFoundation.CFArrayRef = CFArrayRef\n CoreFoundation.CFStringRef = CFStringRef\n CoreFoundation.CFDictionaryRef = CFDictionaryRef\n\nexcept (AttributeError):\n raise ImportError("Error initializing ctypes")\n\n\nclass CFConst(object):\n """\n A class object that acts as essentially a namespace for CoreFoundation\n constants.\n """\n\n kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)\n\n\nclass SecurityConst(object):\n """\n A class object that acts as essentially a namespace for Security constants.\n """\n\n kSSLSessionOptionBreakOnServerAuth = 0\n\n kSSLProtocol2 = 1\n kSSLProtocol3 = 2\n kTLSProtocol1 = 4\n kTLSProtocol11 = 7\n kTLSProtocol12 = 8\n # SecureTransport does not support TLS 1.3 even if there's a constant for it\n kTLSProtocol13 = 10\n kTLSProtocolMaxSupported = 999\n\n kSSLClientSide = 1\n kSSLStreamType = 0\n\n kSecFormatPEMSequence = 10\n\n kSecTrustResultInvalid = 0\n kSecTrustResultProceed = 1\n # This gap is present on purpose: this was kSecTrustResultConfirm, which\n # is deprecated.\n kSecTrustResultDeny = 3\n kSecTrustResultUnspecified = 4\n kSecTrustResultRecoverableTrustFailure = 5\n kSecTrustResultFatalTrustFailure = 6\n kSecTrustResultOtherError = 7\n\n errSSLProtocol = -9800\n errSSLWouldBlock = -9803\n errSSLClosedGraceful = -9805\n errSSLClosedNoNotify = -9816\n errSSLClosedAbort = -9806\n\n errSSLXCertChainInvalid = -9807\n errSSLCrypto = -9809\n errSSLInternal = -9810\n errSSLCertExpired = -9814\n errSSLCertNotYetValid = -9815\n errSSLUnknownRootCert = -9812\n errSSLNoRootCert = -9813\n errSSLHostNameMismatch = -9843\n errSSLPeerHandshakeFail = -9824\n errSSLPeerUserCancelled = -9839\n errSSLWeakPeerEphemeralDHKey = -9850\n errSSLServerAuthCompleted = -9841\n errSSLRecordOverflow = -9847\n\n errSecVerifyFailed = -67808\n errSecNoTrustSettings = -25263\n errSecItemNotFound = -25300\n errSecInvalidTrustSettings = -25262\n\n # Cipher suites. We only pick the ones our default cipher string allows.\n # Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values\n TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C\n TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030\n TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B\n TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F\n TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9\n TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8\n TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F\n TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E\n TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024\n TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028\n TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A\n TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014\n TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B\n TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039\n TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023\n TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027\n TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009\n TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013\n TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067\n TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033\n TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D\n TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C\n TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D\n TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C\n TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035\n TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F\n TLS_AES_128_GCM_SHA256 = 0x1301\n TLS_AES_256_GCM_SHA384 = 0x1302\n TLS_AES_128_CCM_8_SHA256 = 0x1305\n TLS_AES_128_CCM_SHA256 = 0x1304\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\_securetransport\bindings.py | bindings.py | Python | 17,632 | 0.95 | 0.034682 | 0.021277 | vue-tools | 424 | 2024-05-18T02:43:52.516099 | Apache-2.0 | false | 6661de51e1663a18b4b84cd03f030d82 |
"""\nLow-level helpers for the SecureTransport bindings.\n\nThese are Python functions that are not directly related to the high-level APIs\nbut are necessary to get them to work. They include a whole bunch of low-level\nCoreFoundation messing about and memory management. The concerns in this module\nare almost entirely about trying to avoid memory leaks and providing\nappropriate and useful assistance to the higher-level code.\n"""\nimport base64\nimport ctypes\nimport itertools\nimport os\nimport re\nimport ssl\nimport struct\nimport tempfile\n\nfrom .bindings import CFConst, CoreFoundation, Security\n\n# This regular expression is used to grab PEM data out of a PEM bundle.\n_PEM_CERTS_RE = re.compile(\n b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL\n)\n\n\ndef _cf_data_from_bytes(bytestring):\n """\n Given a bytestring, create a CFData object from it. This CFData object must\n be CFReleased by the caller.\n """\n return CoreFoundation.CFDataCreate(\n CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)\n )\n\n\ndef _cf_dictionary_from_tuples(tuples):\n """\n Given a list of Python tuples, create an associated CFDictionary.\n """\n dictionary_size = len(tuples)\n\n # We need to get the dictionary keys and values out in the same order.\n keys = (t[0] for t in tuples)\n values = (t[1] for t in tuples)\n cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)\n cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)\n\n return CoreFoundation.CFDictionaryCreate(\n CoreFoundation.kCFAllocatorDefault,\n cf_keys,\n cf_values,\n dictionary_size,\n CoreFoundation.kCFTypeDictionaryKeyCallBacks,\n CoreFoundation.kCFTypeDictionaryValueCallBacks,\n )\n\n\ndef _cfstr(py_bstr):\n """\n Given a Python binary data, create a CFString.\n The string must be CFReleased by the caller.\n """\n c_str = ctypes.c_char_p(py_bstr)\n cf_str = CoreFoundation.CFStringCreateWithCString(\n CoreFoundation.kCFAllocatorDefault,\n c_str,\n CFConst.kCFStringEncodingUTF8,\n )\n return cf_str\n\n\ndef _create_cfstring_array(lst):\n """\n Given a list of Python binary data, create an associated CFMutableArray.\n The array must be CFReleased by the caller.\n\n Raises an ssl.SSLError on failure.\n """\n cf_arr = None\n try:\n cf_arr = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n if not cf_arr:\n raise MemoryError("Unable to allocate memory!")\n for item in lst:\n cf_str = _cfstr(item)\n if not cf_str:\n raise MemoryError("Unable to allocate memory!")\n try:\n CoreFoundation.CFArrayAppendValue(cf_arr, cf_str)\n finally:\n CoreFoundation.CFRelease(cf_str)\n except BaseException as e:\n if cf_arr:\n CoreFoundation.CFRelease(cf_arr)\n raise ssl.SSLError("Unable to allocate array: %s" % (e,))\n return cf_arr\n\n\ndef _cf_string_to_unicode(value):\n """\n Creates a Unicode string from a CFString object. Used entirely for error\n reporting.\n\n Yes, it annoys me quite a lot that this function is this complex.\n """\n value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))\n\n string = CoreFoundation.CFStringGetCStringPtr(\n value_as_void_p, CFConst.kCFStringEncodingUTF8\n )\n if string is None:\n buffer = ctypes.create_string_buffer(1024)\n result = CoreFoundation.CFStringGetCString(\n value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8\n )\n if not result:\n raise OSError("Error copying C string from CFStringRef")\n string = buffer.value\n if string is not None:\n string = string.decode("utf-8")\n return string\n\n\ndef _assert_no_error(error, exception_class=None):\n """\n Checks the return code and throws an exception if there is an error to\n report\n """\n if error == 0:\n return\n\n cf_error_string = Security.SecCopyErrorMessageString(error, None)\n output = _cf_string_to_unicode(cf_error_string)\n CoreFoundation.CFRelease(cf_error_string)\n\n if output is None or output == u"":\n output = u"OSStatus %s" % error\n\n if exception_class is None:\n exception_class = ssl.SSLError\n\n raise exception_class(output)\n\n\ndef _cert_array_from_pem(pem_bundle):\n """\n Given a bundle of certs in PEM format, turns them into a CFArray of certs\n that can be used to validate a cert chain.\n """\n # Normalize the PEM bundle's line endings.\n pem_bundle = pem_bundle.replace(b"\r\n", b"\n")\n\n der_certs = [\n base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle)\n ]\n if not der_certs:\n raise ssl.SSLError("No root certificates specified")\n\n cert_array = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n if not cert_array:\n raise ssl.SSLError("Unable to allocate memory!")\n\n try:\n for der_bytes in der_certs:\n certdata = _cf_data_from_bytes(der_bytes)\n if not certdata:\n raise ssl.SSLError("Unable to allocate memory!")\n cert = Security.SecCertificateCreateWithData(\n CoreFoundation.kCFAllocatorDefault, certdata\n )\n CoreFoundation.CFRelease(certdata)\n if not cert:\n raise ssl.SSLError("Unable to build cert object!")\n\n CoreFoundation.CFArrayAppendValue(cert_array, cert)\n CoreFoundation.CFRelease(cert)\n except Exception:\n # We need to free the array before the exception bubbles further.\n # We only want to do that if an error occurs: otherwise, the caller\n # should free.\n CoreFoundation.CFRelease(cert_array)\n raise\n\n return cert_array\n\n\ndef _is_cert(item):\n """\n Returns True if a given CFTypeRef is a certificate.\n """\n expected = Security.SecCertificateGetTypeID()\n return CoreFoundation.CFGetTypeID(item) == expected\n\n\ndef _is_identity(item):\n """\n Returns True if a given CFTypeRef is an identity.\n """\n expected = Security.SecIdentityGetTypeID()\n return CoreFoundation.CFGetTypeID(item) == expected\n\n\ndef _temporary_keychain():\n """\n This function creates a temporary Mac keychain that we can use to work with\n credentials. This keychain uses a one-time password and a temporary file to\n store the data. We expect to have one keychain per socket. The returned\n SecKeychainRef must be freed by the caller, including calling\n SecKeychainDelete.\n\n Returns a tuple of the SecKeychainRef and the path to the temporary\n directory that contains it.\n """\n # Unfortunately, SecKeychainCreate requires a path to a keychain. This\n # means we cannot use mkstemp to use a generic temporary file. Instead,\n # we're going to create a temporary directory and a filename to use there.\n # This filename will be 8 random bytes expanded into base64. We also need\n # some random bytes to password-protect the keychain we're creating, so we\n # ask for 40 random bytes.\n random_bytes = os.urandom(40)\n filename = base64.b16encode(random_bytes[:8]).decode("utf-8")\n password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8\n tempdirectory = tempfile.mkdtemp()\n\n keychain_path = os.path.join(tempdirectory, filename).encode("utf-8")\n\n # We now want to create the keychain itself.\n keychain = Security.SecKeychainRef()\n status = Security.SecKeychainCreate(\n keychain_path, len(password), password, False, None, ctypes.byref(keychain)\n )\n _assert_no_error(status)\n\n # Having created the keychain, we want to pass it off to the caller.\n return keychain, tempdirectory\n\n\ndef _load_items_from_file(keychain, path):\n """\n Given a single file, loads all the trust objects from it into arrays and\n the keychain.\n Returns a tuple of lists: the first list is a list of identities, the\n second a list of certs.\n """\n certificates = []\n identities = []\n result_array = None\n\n with open(path, "rb") as f:\n raw_filedata = f.read()\n\n try:\n filedata = CoreFoundation.CFDataCreate(\n CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata)\n )\n result_array = CoreFoundation.CFArrayRef()\n result = Security.SecItemImport(\n filedata, # cert data\n None, # Filename, leaving it out for now\n None, # What the type of the file is, we don't care\n None, # what's in the file, we don't care\n 0, # import flags\n None, # key params, can include passphrase in the future\n keychain, # The keychain to insert into\n ctypes.byref(result_array), # Results\n )\n _assert_no_error(result)\n\n # A CFArray is not very useful to us as an intermediary\n # representation, so we are going to extract the objects we want\n # and then free the array. We don't need to keep hold of keys: the\n # keychain already has them!\n result_count = CoreFoundation.CFArrayGetCount(result_array)\n for index in range(result_count):\n item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index)\n item = ctypes.cast(item, CoreFoundation.CFTypeRef)\n\n if _is_cert(item):\n CoreFoundation.CFRetain(item)\n certificates.append(item)\n elif _is_identity(item):\n CoreFoundation.CFRetain(item)\n identities.append(item)\n finally:\n if result_array:\n CoreFoundation.CFRelease(result_array)\n\n CoreFoundation.CFRelease(filedata)\n\n return (identities, certificates)\n\n\ndef _load_client_cert_chain(keychain, *paths):\n """\n Load certificates and maybe keys from a number of files. Has the end goal\n of returning a CFArray containing one SecIdentityRef, and then zero or more\n SecCertificateRef objects, suitable for use as a client certificate trust\n chain.\n """\n # Ok, the strategy.\n #\n # This relies on knowing that macOS will not give you a SecIdentityRef\n # unless you have imported a key into a keychain. This is a somewhat\n # artificial limitation of macOS (for example, it doesn't necessarily\n # affect iOS), but there is nothing inside Security.framework that lets you\n # get a SecIdentityRef without having a key in a keychain.\n #\n # So the policy here is we take all the files and iterate them in order.\n # Each one will use SecItemImport to have one or more objects loaded from\n # it. We will also point at a keychain that macOS can use to work with the\n # private key.\n #\n # Once we have all the objects, we'll check what we actually have. If we\n # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,\n # we'll take the first certificate (which we assume to be our leaf) and\n # ask the keychain to give us a SecIdentityRef with that cert's associated\n # key.\n #\n # We'll then return a CFArray containing the trust chain: one\n # SecIdentityRef and then zero-or-more SecCertificateRef objects. The\n # responsibility for freeing this CFArray will be with the caller. This\n # CFArray must remain alive for the entire connection, so in practice it\n # will be stored with a single SSLSocket, along with the reference to the\n # keychain.\n certificates = []\n identities = []\n\n # Filter out bad paths.\n paths = (path for path in paths if path)\n\n try:\n for file_path in paths:\n new_identities, new_certs = _load_items_from_file(keychain, file_path)\n identities.extend(new_identities)\n certificates.extend(new_certs)\n\n # Ok, we have everything. The question is: do we have an identity? If\n # not, we want to grab one from the first cert we have.\n if not identities:\n new_identity = Security.SecIdentityRef()\n status = Security.SecIdentityCreateWithCertificate(\n keychain, certificates[0], ctypes.byref(new_identity)\n )\n _assert_no_error(status)\n identities.append(new_identity)\n\n # We now want to release the original certificate, as we no longer\n # need it.\n CoreFoundation.CFRelease(certificates.pop(0))\n\n # We now need to build a new CFArray that holds the trust chain.\n trust_chain = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n for item in itertools.chain(identities, certificates):\n # ArrayAppendValue does a CFRetain on the item. That's fine,\n # because the finally block will release our other refs to them.\n CoreFoundation.CFArrayAppendValue(trust_chain, item)\n\n return trust_chain\n finally:\n for obj in itertools.chain(identities, certificates):\n CoreFoundation.CFRelease(obj)\n\n\nTLS_PROTOCOL_VERSIONS = {\n "SSLv2": (0, 2),\n "SSLv3": (3, 0),\n "TLSv1": (3, 1),\n "TLSv1.1": (3, 2),\n "TLSv1.2": (3, 3),\n}\n\n\ndef _build_tls_unknown_ca_alert(version):\n """\n Builds a TLS alert record for an unknown CA.\n """\n ver_maj, ver_min = TLS_PROTOCOL_VERSIONS[version]\n severity_fatal = 0x02\n description_unknown_ca = 0x30\n msg = struct.pack(">BB", severity_fatal, description_unknown_ca)\n msg_len = len(msg)\n record_type_alert = 0x15\n record = struct.pack(">BBBH", record_type_alert, ver_maj, ver_min, msg_len) + msg\n return record\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\_securetransport\low_level.py | low_level.py | Python | 13,922 | 0.95 | 0.151134 | 0.151786 | react-lib | 601 | 2025-06-15T21:16:15.667557 | BSD-3-Clause | false | c4cf8188919da124cdcf69982407b298 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\_securetransport\__pycache__\bindings.cpython-313.pyc | bindings.cpython-313.pyc | Other | 17,505 | 0.95 | 0.045113 | 0 | react-lib | 264 | 2025-04-24T09:17:51.608609 | BSD-3-Clause | false | 84ca923ad1a0f49525717984634e682a |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\_securetransport\__pycache__\low_level.cpython-313.pyc | low_level.cpython-313.pyc | Other | 14,822 | 0.95 | 0.054217 | 0.018868 | vue-tools | 927 | 2023-09-17T01:14:10.182680 | MIT | false | b9ecd8b36062d638e10e1493c27146fb |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\_securetransport\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 219 | 0.7 | 0 | 0 | python-kit | 61 | 2024-06-11T08:41:16.361461 | Apache-2.0 | false | 2ae5e827af1c69d98ef5a3248d403c74 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\appengine.cpython-313.pyc | appengine.cpython-313.pyc | Other | 11,772 | 0.95 | 0.068182 | 0.060345 | vue-tools | 259 | 2024-06-19T09:26:07.477172 | BSD-3-Clause | false | e498584c131c77d5fff1a2b2349cb529 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\ntlmpool.cpython-313.pyc | ntlmpool.cpython-313.pyc | Other | 5,740 | 0.95 | 0.015625 | 0 | vue-tools | 601 | 2025-01-21T12:27:20.570889 | Apache-2.0 | false | efbcbe146ed467657d816449114aa6e3 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\pyopenssl.cpython-313.pyc | pyopenssl.cpython-313.pyc | Other | 24,789 | 0.95 | 0.056872 | 0.041667 | react-lib | 655 | 2024-10-30T08:26:07.794557 | Apache-2.0 | false | f103b61d915f7ad8794ff07e9831c820 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\securetransport.cpython-313.pyc | securetransport.cpython-313.pyc | Other | 35,984 | 0.95 | 0.028653 | 0.021407 | vue-tools | 288 | 2024-01-11T02:09:45.976031 | GPL-3.0 | false | c33d3ea1d6b4f857d4714a9e62555300 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\socks.cpython-313.pyc | socks.cpython-313.pyc | Other | 7,734 | 0.95 | 0.01626 | 0 | react-lib | 752 | 2024-06-26T20:17:17.663893 | BSD-3-Clause | false | 1914b8eca7af8381f1e351ca6080bd5c |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\_appengine_environ.cpython-313.pyc | _appengine_environ.cpython-313.pyc | Other | 1,880 | 0.8 | 0.142857 | 0 | react-lib | 238 | 2025-04-12T01:35:00.081723 | GPL-3.0 | false | ac47a0e936194f70237571750de6bd9d |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\contrib\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 202 | 0.7 | 0 | 0 | vue-tools | 756 | 2024-07-15T15:51:07.885570 | GPL-3.0 | false | 4ea474398cadc98d97d43e62d520ad85 |
# Copyright (c) 2010-2020 Benjamin Peterson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the "Software"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n"""Utilities for writing code that runs on Python 2 and 3"""\n\nfrom __future__ import absolute_import\n\nimport functools\nimport itertools\nimport operator\nimport sys\nimport types\n\n__author__ = "Benjamin Peterson <benjamin@python.org>"\n__version__ = "1.16.0"\n\n\n# Useful for very coarse version differentiation.\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n\nif PY3:\n string_types = (str,)\n integer_types = (int,)\n class_types = (type,)\n text_type = str\n binary_type = bytes\n\n MAXSIZE = sys.maxsize\nelse:\n string_types = (basestring,)\n integer_types = (int, long)\n class_types = (type, types.ClassType)\n text_type = unicode\n binary_type = str\n\n if sys.platform.startswith("java"):\n # Jython always uses 32 bits.\n MAXSIZE = int((1 << 31) - 1)\n else:\n # It's possible to have sizeof(long) != sizeof(Py_ssize_t).\n class X(object):\n def __len__(self):\n return 1 << 31\n\n try:\n len(X())\n except OverflowError:\n # 32-bit\n MAXSIZE = int((1 << 31) - 1)\n else:\n # 64-bit\n MAXSIZE = int((1 << 63) - 1)\n del X\n\nif PY34:\n from importlib.util import spec_from_loader\nelse:\n spec_from_loader = None\n\n\ndef _add_doc(func, doc):\n """Add documentation to a function."""\n func.__doc__ = doc\n\n\ndef _import_module(name):\n """Import module, returning the module after the last dot."""\n __import__(name)\n return sys.modules[name]\n\n\nclass _LazyDescr(object):\n def __init__(self, name):\n self.name = name\n\n def __get__(self, obj, tp):\n result = self._resolve()\n setattr(obj, self.name, result) # Invokes __set__.\n try:\n # This is a bit ugly, but it avoids running this again by\n # removing this descriptor.\n delattr(obj.__class__, self.name)\n except AttributeError:\n pass\n return result\n\n\nclass MovedModule(_LazyDescr):\n def __init__(self, name, old, new=None):\n super(MovedModule, self).__init__(name)\n if PY3:\n if new is None:\n new = name\n self.mod = new\n else:\n self.mod = old\n\n def _resolve(self):\n return _import_module(self.mod)\n\n def __getattr__(self, attr):\n _module = self._resolve()\n value = getattr(_module, attr)\n setattr(self, attr, value)\n return value\n\n\nclass _LazyModule(types.ModuleType):\n def __init__(self, name):\n super(_LazyModule, self).__init__(name)\n self.__doc__ = self.__class__.__doc__\n\n def __dir__(self):\n attrs = ["__doc__", "__name__"]\n attrs += [attr.name for attr in self._moved_attributes]\n return attrs\n\n # Subclasses should override this\n _moved_attributes = []\n\n\nclass MovedAttribute(_LazyDescr):\n def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n super(MovedAttribute, self).__init__(name)\n if PY3:\n if new_mod is None:\n new_mod = name\n self.mod = new_mod\n if new_attr is None:\n if old_attr is None:\n new_attr = name\n else:\n new_attr = old_attr\n self.attr = new_attr\n else:\n self.mod = old_mod\n if old_attr is None:\n old_attr = name\n self.attr = old_attr\n\n def _resolve(self):\n module = _import_module(self.mod)\n return getattr(module, self.attr)\n\n\nclass _SixMetaPathImporter(object):\n\n """\n A meta path importer to import six.moves and its submodules.\n\n This class implements a PEP302 finder and loader. It should be compatible\n with Python 2.5 and all existing versions of Python3\n """\n\n def __init__(self, six_module_name):\n self.name = six_module_name\n self.known_modules = {}\n\n def _add_module(self, mod, *fullnames):\n for fullname in fullnames:\n self.known_modules[self.name + "." + fullname] = mod\n\n def _get_module(self, fullname):\n return self.known_modules[self.name + "." + fullname]\n\n def find_module(self, fullname, path=None):\n if fullname in self.known_modules:\n return self\n return None\n\n def find_spec(self, fullname, path, target=None):\n if fullname in self.known_modules:\n return spec_from_loader(fullname, self)\n return None\n\n def __get_module(self, fullname):\n try:\n return self.known_modules[fullname]\n except KeyError:\n raise ImportError("This loader does not know module " + fullname)\n\n def load_module(self, fullname):\n try:\n # in case of a reload\n return sys.modules[fullname]\n except KeyError:\n pass\n mod = self.__get_module(fullname)\n if isinstance(mod, MovedModule):\n mod = mod._resolve()\n else:\n mod.__loader__ = self\n sys.modules[fullname] = mod\n return mod\n\n def is_package(self, fullname):\n """\n Return true, if the named module is a package.\n\n We need this method to get correct spec objects with\n Python 3.4 (see PEP451)\n """\n return hasattr(self.__get_module(fullname), "__path__")\n\n def get_code(self, fullname):\n """Return None\n\n Required, if is_package is implemented"""\n self.__get_module(fullname) # eventually raises ImportError\n return None\n\n get_source = get_code # same as get_code\n\n def create_module(self, spec):\n return self.load_module(spec.name)\n\n def exec_module(self, module):\n pass\n\n\n_importer = _SixMetaPathImporter(__name__)\n\n\nclass _MovedItems(_LazyModule):\n\n """Lazy loading of moved objects"""\n\n __path__ = [] # mark as package\n\n\n_moved_attributes = [\n MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),\n MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),\n MovedAttribute(\n "filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"\n ),\n MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),\n MovedAttribute("intern", "__builtin__", "sys"),\n MovedAttribute("map", "itertools", "builtins", "imap", "map"),\n MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),\n MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),\n MovedAttribute("getoutput", "commands", "subprocess"),\n MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),\n MovedAttribute(\n "reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"\n ),\n MovedAttribute("reduce", "__builtin__", "functools"),\n MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),\n MovedAttribute("StringIO", "StringIO", "io"),\n MovedAttribute("UserDict", "UserDict", "collections"),\n MovedAttribute("UserList", "UserList", "collections"),\n MovedAttribute("UserString", "UserString", "collections"),\n MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),\n MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),\n MovedAttribute(\n "zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"\n ),\n MovedModule("builtins", "__builtin__"),\n MovedModule("configparser", "ConfigParser"),\n MovedModule(\n "collections_abc",\n "collections",\n "collections.abc" if sys.version_info >= (3, 3) else "collections",\n ),\n MovedModule("copyreg", "copy_reg"),\n MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),\n MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),\n MovedModule(\n "_dummy_thread",\n "dummy_thread",\n "_dummy_thread" if sys.version_info < (3, 9) else "_thread",\n ),\n MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),\n MovedModule("http_cookies", "Cookie", "http.cookies"),\n MovedModule("html_entities", "htmlentitydefs", "html.entities"),\n MovedModule("html_parser", "HTMLParser", "html.parser"),\n MovedModule("http_client", "httplib", "http.client"),\n MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),\n MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),\n MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),\n MovedModule(\n "email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"\n ),\n MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),\n MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),\n MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),\n MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),\n MovedModule("cPickle", "cPickle", "pickle"),\n MovedModule("queue", "Queue"),\n MovedModule("reprlib", "repr"),\n MovedModule("socketserver", "SocketServer"),\n MovedModule("_thread", "thread", "_thread"),\n MovedModule("tkinter", "Tkinter"),\n MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),\n MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),\n MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),\n MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),\n MovedModule("tkinter_tix", "Tix", "tkinter.tix"),\n MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),\n MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),\n MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),\n MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"),\n MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"),\n MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),\n MovedModule("tkinter_font", "tkFont", "tkinter.font"),\n MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),\n MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"),\n MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),\n MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),\n MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),\n MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),\n MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),\n MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),\n]\n# Add windows specific modules.\nif sys.platform == "win32":\n _moved_attributes += [\n MovedModule("winreg", "_winreg"),\n ]\n\nfor attr in _moved_attributes:\n setattr(_MovedItems, attr.name, attr)\n if isinstance(attr, MovedModule):\n _importer._add_module(attr, "moves." + attr.name)\ndel attr\n\n_MovedItems._moved_attributes = _moved_attributes\n\nmoves = _MovedItems(__name__ + ".moves")\n_importer._add_module(moves, "moves")\n\n\nclass Module_six_moves_urllib_parse(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_parse"""\n\n\n_urllib_parse_moved_attributes = [\n MovedAttribute("ParseResult", "urlparse", "urllib.parse"),\n MovedAttribute("SplitResult", "urlparse", "urllib.parse"),\n MovedAttribute("parse_qs", "urlparse", "urllib.parse"),\n MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),\n MovedAttribute("urldefrag", "urlparse", "urllib.parse"),\n MovedAttribute("urljoin", "urlparse", "urllib.parse"),\n MovedAttribute("urlparse", "urlparse", "urllib.parse"),\n MovedAttribute("urlsplit", "urlparse", "urllib.parse"),\n MovedAttribute("urlunparse", "urlparse", "urllib.parse"),\n MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),\n MovedAttribute("quote", "urllib", "urllib.parse"),\n MovedAttribute("quote_plus", "urllib", "urllib.parse"),\n MovedAttribute("unquote", "urllib", "urllib.parse"),\n MovedAttribute("unquote_plus", "urllib", "urllib.parse"),\n MovedAttribute(\n "unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"\n ),\n MovedAttribute("urlencode", "urllib", "urllib.parse"),\n MovedAttribute("splitquery", "urllib", "urllib.parse"),\n MovedAttribute("splittag", "urllib", "urllib.parse"),\n MovedAttribute("splituser", "urllib", "urllib.parse"),\n MovedAttribute("splitvalue", "urllib", "urllib.parse"),\n MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),\n MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),\n MovedAttribute("uses_params", "urlparse", "urllib.parse"),\n MovedAttribute("uses_query", "urlparse", "urllib.parse"),\n MovedAttribute("uses_relative", "urlparse", "urllib.parse"),\n]\nfor attr in _urllib_parse_moved_attributes:\n setattr(Module_six_moves_urllib_parse, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes\n\n_importer._add_module(\n Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),\n "moves.urllib_parse",\n "moves.urllib.parse",\n)\n\n\nclass Module_six_moves_urllib_error(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_error"""\n\n\n_urllib_error_moved_attributes = [\n MovedAttribute("URLError", "urllib2", "urllib.error"),\n MovedAttribute("HTTPError", "urllib2", "urllib.error"),\n MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),\n]\nfor attr in _urllib_error_moved_attributes:\n setattr(Module_six_moves_urllib_error, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes\n\n_importer._add_module(\n Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),\n "moves.urllib_error",\n "moves.urllib.error",\n)\n\n\nclass Module_six_moves_urllib_request(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_request"""\n\n\n_urllib_request_moved_attributes = [\n MovedAttribute("urlopen", "urllib2", "urllib.request"),\n MovedAttribute("install_opener", "urllib2", "urllib.request"),\n MovedAttribute("build_opener", "urllib2", "urllib.request"),\n MovedAttribute("pathname2url", "urllib", "urllib.request"),\n MovedAttribute("url2pathname", "urllib", "urllib.request"),\n MovedAttribute("getproxies", "urllib", "urllib.request"),\n MovedAttribute("Request", "urllib2", "urllib.request"),\n MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),\n MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),\n MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),\n MovedAttribute("BaseHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),\n MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),\n MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),\n MovedAttribute("FileHandler", "urllib2", "urllib.request"),\n MovedAttribute("FTPHandler", "urllib2", "urllib.request"),\n MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),\n MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),\n MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),\n MovedAttribute("urlretrieve", "urllib", "urllib.request"),\n MovedAttribute("urlcleanup", "urllib", "urllib.request"),\n MovedAttribute("URLopener", "urllib", "urllib.request"),\n MovedAttribute("FancyURLopener", "urllib", "urllib.request"),\n MovedAttribute("proxy_bypass", "urllib", "urllib.request"),\n MovedAttribute("parse_http_list", "urllib2", "urllib.request"),\n MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),\n]\nfor attr in _urllib_request_moved_attributes:\n setattr(Module_six_moves_urllib_request, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes\n\n_importer._add_module(\n Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),\n "moves.urllib_request",\n "moves.urllib.request",\n)\n\n\nclass Module_six_moves_urllib_response(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_response"""\n\n\n_urllib_response_moved_attributes = [\n MovedAttribute("addbase", "urllib", "urllib.response"),\n MovedAttribute("addclosehook", "urllib", "urllib.response"),\n MovedAttribute("addinfo", "urllib", "urllib.response"),\n MovedAttribute("addinfourl", "urllib", "urllib.response"),\n]\nfor attr in _urllib_response_moved_attributes:\n setattr(Module_six_moves_urllib_response, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes\n\n_importer._add_module(\n Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),\n "moves.urllib_response",\n "moves.urllib.response",\n)\n\n\nclass Module_six_moves_urllib_robotparser(_LazyModule):\n\n """Lazy loading of moved objects in six.moves.urllib_robotparser"""\n\n\n_urllib_robotparser_moved_attributes = [\n MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),\n]\nfor attr in _urllib_robotparser_moved_attributes:\n setattr(Module_six_moves_urllib_robotparser, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_robotparser._moved_attributes = (\n _urllib_robotparser_moved_attributes\n)\n\n_importer._add_module(\n Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),\n "moves.urllib_robotparser",\n "moves.urllib.robotparser",\n)\n\n\nclass Module_six_moves_urllib(types.ModuleType):\n\n """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""\n\n __path__ = [] # mark as package\n parse = _importer._get_module("moves.urllib_parse")\n error = _importer._get_module("moves.urllib_error")\n request = _importer._get_module("moves.urllib_request")\n response = _importer._get_module("moves.urllib_response")\n robotparser = _importer._get_module("moves.urllib_robotparser")\n\n def __dir__(self):\n return ["parse", "error", "request", "response", "robotparser"]\n\n\n_importer._add_module(\n Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib"\n)\n\n\ndef add_move(move):\n """Add an item to six.moves."""\n setattr(_MovedItems, move.name, move)\n\n\ndef remove_move(name):\n """Remove item from six.moves."""\n try:\n delattr(_MovedItems, name)\n except AttributeError:\n try:\n del moves.__dict__[name]\n except KeyError:\n raise AttributeError("no such move, %r" % (name,))\n\n\nif PY3:\n _meth_func = "__func__"\n _meth_self = "__self__"\n\n _func_closure = "__closure__"\n _func_code = "__code__"\n _func_defaults = "__defaults__"\n _func_globals = "__globals__"\nelse:\n _meth_func = "im_func"\n _meth_self = "im_self"\n\n _func_closure = "func_closure"\n _func_code = "func_code"\n _func_defaults = "func_defaults"\n _func_globals = "func_globals"\n\n\ntry:\n advance_iterator = next\nexcept NameError:\n\n def advance_iterator(it):\n return it.next()\n\n\nnext = advance_iterator\n\n\ntry:\n callable = callable\nexcept NameError:\n\n def callable(obj):\n return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)\n\n\nif PY3:\n\n def get_unbound_function(unbound):\n return unbound\n\n create_bound_method = types.MethodType\n\n def create_unbound_method(func, cls):\n return func\n\n Iterator = object\nelse:\n\n def get_unbound_function(unbound):\n return unbound.im_func\n\n def create_bound_method(func, obj):\n return types.MethodType(func, obj, obj.__class__)\n\n def create_unbound_method(func, cls):\n return types.MethodType(func, None, cls)\n\n class Iterator(object):\n def next(self):\n return type(self).__next__(self)\n\n callable = callable\n_add_doc(\n get_unbound_function, """Get the function out of a possibly unbound function"""\n)\n\n\nget_method_function = operator.attrgetter(_meth_func)\nget_method_self = operator.attrgetter(_meth_self)\nget_function_closure = operator.attrgetter(_func_closure)\nget_function_code = operator.attrgetter(_func_code)\nget_function_defaults = operator.attrgetter(_func_defaults)\nget_function_globals = operator.attrgetter(_func_globals)\n\n\nif PY3:\n\n def iterkeys(d, **kw):\n return iter(d.keys(**kw))\n\n def itervalues(d, **kw):\n return iter(d.values(**kw))\n\n def iteritems(d, **kw):\n return iter(d.items(**kw))\n\n def iterlists(d, **kw):\n return iter(d.lists(**kw))\n\n viewkeys = operator.methodcaller("keys")\n\n viewvalues = operator.methodcaller("values")\n\n viewitems = operator.methodcaller("items")\nelse:\n\n def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n\n def itervalues(d, **kw):\n return d.itervalues(**kw)\n\n def iteritems(d, **kw):\n return d.iteritems(**kw)\n\n def iterlists(d, **kw):\n return d.iterlists(**kw)\n\n viewkeys = operator.methodcaller("viewkeys")\n\n viewvalues = operator.methodcaller("viewvalues")\n\n viewitems = operator.methodcaller("viewitems")\n\n_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")\n_add_doc(itervalues, "Return an iterator over the values of a dictionary.")\n_add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.")\n_add_doc(\n iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary."\n)\n\n\nif PY3:\n\n def b(s):\n return s.encode("latin-1")\n\n def u(s):\n return s\n\n unichr = chr\n import struct\n\n int2byte = struct.Struct(">B").pack\n del struct\n byte2int = operator.itemgetter(0)\n indexbytes = operator.getitem\n iterbytes = iter\n import io\n\n StringIO = io.StringIO\n BytesIO = io.BytesIO\n del io\n _assertCountEqual = "assertCountEqual"\n if sys.version_info[1] <= 1:\n _assertRaisesRegex = "assertRaisesRegexp"\n _assertRegex = "assertRegexpMatches"\n _assertNotRegex = "assertNotRegexpMatches"\n else:\n _assertRaisesRegex = "assertRaisesRegex"\n _assertRegex = "assertRegex"\n _assertNotRegex = "assertNotRegex"\nelse:\n\n def b(s):\n return s\n\n # Workaround for standalone backslash\n\n def u(s):\n return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape")\n\n unichr = unichr\n int2byte = chr\n\n def byte2int(bs):\n return ord(bs[0])\n\n def indexbytes(buf, i):\n return ord(buf[i])\n\n iterbytes = functools.partial(itertools.imap, ord)\n import StringIO\n\n StringIO = BytesIO = StringIO.StringIO\n _assertCountEqual = "assertItemsEqual"\n _assertRaisesRegex = "assertRaisesRegexp"\n _assertRegex = "assertRegexpMatches"\n _assertNotRegex = "assertNotRegexpMatches"\n_add_doc(b, """Byte literal""")\n_add_doc(u, """Text literal""")\n\n\ndef assertCountEqual(self, *args, **kwargs):\n return getattr(self, _assertCountEqual)(*args, **kwargs)\n\n\ndef assertRaisesRegex(self, *args, **kwargs):\n return getattr(self, _assertRaisesRegex)(*args, **kwargs)\n\n\ndef assertRegex(self, *args, **kwargs):\n return getattr(self, _assertRegex)(*args, **kwargs)\n\n\ndef assertNotRegex(self, *args, **kwargs):\n return getattr(self, _assertNotRegex)(*args, **kwargs)\n\n\nif PY3:\n exec_ = getattr(moves.builtins, "exec")\n\n def reraise(tp, value, tb=None):\n try:\n if value is None:\n value = tp()\n if value.__traceback__ is not tb:\n raise value.with_traceback(tb)\n raise value\n finally:\n value = None\n tb = None\n\nelse:\n\n def exec_(_code_, _globs_=None, _locs_=None):\n """Execute code in a namespace."""\n if _globs_ is None:\n frame = sys._getframe(1)\n _globs_ = frame.f_globals\n if _locs_ is None:\n _locs_ = frame.f_locals\n del frame\n elif _locs_ is None:\n _locs_ = _globs_\n exec ("""exec _code_ in _globs_, _locs_""")\n\n exec_(\n """def reraise(tp, value, tb=None):\n try:\n raise tp, value, tb\n finally:\n tb = None\n"""\n )\n\n\nif sys.version_info[:2] > (3,):\n exec_(\n """def raise_from(value, from_value):\n try:\n raise value from from_value\n finally:\n value = None\n"""\n )\nelse:\n\n def raise_from(value, from_value):\n raise value\n\n\nprint_ = getattr(moves.builtins, "print", None)\nif print_ is None:\n\n def print_(*args, **kwargs):\n """The new-style print function for Python 2.4 and 2.5."""\n fp = kwargs.pop("file", sys.stdout)\n if fp is None:\n return\n\n def write(data):\n if not isinstance(data, basestring):\n data = str(data)\n # If the file has an encoding, encode unicode with it.\n if (\n isinstance(fp, file)\n and isinstance(data, unicode)\n and fp.encoding is not None\n ):\n errors = getattr(fp, "errors", None)\n if errors is None:\n errors = "strict"\n data = data.encode(fp.encoding, errors)\n fp.write(data)\n\n want_unicode = False\n sep = kwargs.pop("sep", None)\n if sep is not None:\n if isinstance(sep, unicode):\n want_unicode = True\n elif not isinstance(sep, str):\n raise TypeError("sep must be None or a string")\n end = kwargs.pop("end", None)\n if end is not None:\n if isinstance(end, unicode):\n want_unicode = True\n elif not isinstance(end, str):\n raise TypeError("end must be None or a string")\n if kwargs:\n raise TypeError("invalid keyword arguments to print()")\n if not want_unicode:\n for arg in args:\n if isinstance(arg, unicode):\n want_unicode = True\n break\n if want_unicode:\n newline = unicode("\n")\n space = unicode(" ")\n else:\n newline = "\n"\n space = " "\n if sep is None:\n sep = space\n if end is None:\n end = newline\n for i, arg in enumerate(args):\n if i:\n write(sep)\n write(arg)\n write(end)\n\n\nif sys.version_info[:2] < (3, 3):\n _print = print_\n\n def print_(*args, **kwargs):\n fp = kwargs.get("file", sys.stdout)\n flush = kwargs.pop("flush", False)\n _print(*args, **kwargs)\n if flush and fp is not None:\n fp.flush()\n\n\n_add_doc(reraise, """Reraise an exception.""")\n\nif sys.version_info[0:2] < (3, 4):\n # This does exactly the same what the :func:`py3:functools.update_wrapper`\n # function does on Python versions after 3.2. It sets the ``__wrapped__``\n # attribute on ``wrapper`` object and it doesn't raise an error if any of\n # the attributes mentioned in ``assigned`` and ``updated`` are missing on\n # ``wrapped`` object.\n def _update_wrapper(\n wrapper,\n wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES,\n ):\n for attr in assigned:\n try:\n value = getattr(wrapped, attr)\n except AttributeError:\n continue\n else:\n setattr(wrapper, attr, value)\n for attr in updated:\n getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n wrapper.__wrapped__ = wrapped\n return wrapper\n\n _update_wrapper.__doc__ = functools.update_wrapper.__doc__\n\n def wraps(\n wrapped,\n assigned=functools.WRAPPER_ASSIGNMENTS,\n updated=functools.WRAPPER_UPDATES,\n ):\n return functools.partial(\n _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated\n )\n\n wraps.__doc__ = functools.wraps.__doc__\n\nelse:\n wraps = functools.wraps\n\n\ndef with_metaclass(meta, *bases):\n """Create a base class with a metaclass."""\n # This requires a bit of explanation: the basic idea is to make a dummy\n # metaclass for one level of class instantiation that replaces itself with\n # the actual metaclass.\n class metaclass(type):\n def __new__(cls, name, this_bases, d):\n if sys.version_info[:2] >= (3, 7):\n # This version introduced PEP 560 that requires a bit\n # of extra care (we mimic what is done by __build_class__).\n resolved_bases = types.resolve_bases(bases)\n if resolved_bases is not bases:\n d["__orig_bases__"] = bases\n else:\n resolved_bases = bases\n return meta(name, resolved_bases, d)\n\n @classmethod\n def __prepare__(cls, name, this_bases):\n return meta.__prepare__(name, bases)\n\n return type.__new__(metaclass, "temporary_class", (), {})\n\n\ndef add_metaclass(metaclass):\n """Class decorator for creating a class with a metaclass."""\n\n def wrapper(cls):\n orig_vars = cls.__dict__.copy()\n slots = orig_vars.get("__slots__")\n if slots is not None:\n if isinstance(slots, str):\n slots = [slots]\n for slots_var in slots:\n orig_vars.pop(slots_var)\n orig_vars.pop("__dict__", None)\n orig_vars.pop("__weakref__", None)\n if hasattr(cls, "__qualname__"):\n orig_vars["__qualname__"] = cls.__qualname__\n return metaclass(cls.__name__, cls.__bases__, orig_vars)\n\n return wrapper\n\n\ndef ensure_binary(s, encoding="utf-8", errors="strict"):\n """Coerce **s** to six.binary_type.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> encoded to `bytes`\n - `bytes` -> `bytes`\n """\n if isinstance(s, binary_type):\n return s\n if isinstance(s, text_type):\n return s.encode(encoding, errors)\n raise TypeError("not expecting type '%s'" % type(s))\n\n\ndef ensure_str(s, encoding="utf-8", errors="strict"):\n """Coerce *s* to `str`.\n\n For Python 2:\n - `unicode` -> encoded to `str`\n - `str` -> `str`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n """\n # Optimization: Fast return for the common case.\n if type(s) is str:\n return s\n if PY2 and isinstance(s, text_type):\n return s.encode(encoding, errors)\n elif PY3 and isinstance(s, binary_type):\n return s.decode(encoding, errors)\n elif not isinstance(s, (text_type, binary_type)):\n raise TypeError("not expecting type '%s'" % type(s))\n return s\n\n\ndef ensure_text(s, encoding="utf-8", errors="strict"):\n """Coerce *s* to six.text_type.\n\n For Python 2:\n - `unicode` -> `unicode`\n - `str` -> `unicode`\n\n For Python 3:\n - `str` -> `str`\n - `bytes` -> decoded to `str`\n """\n if isinstance(s, binary_type):\n return s.decode(encoding, errors)\n elif isinstance(s, text_type):\n return s\n else:\n raise TypeError("not expecting type '%s'" % type(s))\n\n\ndef python_2_unicode_compatible(klass):\n """\n A class decorator that defines __unicode__ and __str__ methods under Python 2.\n Under Python 3 it does nothing.\n\n To support Python 2 and 3 with a single code base, define a __str__ method\n returning text and apply this decorator to the class.\n """\n if PY2:\n if "__str__" not in klass.__dict__:\n raise ValueError(\n "@python_2_unicode_compatible cannot be applied "\n "to %s because it doesn't define __str__()." % klass.__name__\n )\n klass.__unicode__ = klass.__str__\n klass.__str__ = lambda self: self.__unicode__().encode("utf-8")\n return klass\n\n\n# Complete the moves implementation.\n# This code is at the end of this module to speed up module loading.\n# Turn this module into a package.\n__path__ = [] # required for PEP 302 and PEP 451\n__package__ = __name__ # see PEP 366 @ReservedAssignment\nif globals().get("__spec__") is not None:\n __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable\n# Remove other six meta path importers, since they cause problems. This can\n# happen if six is removed from sys.modules and then reloaded. (Setuptools does\n# this for some reason.)\nif sys.meta_path:\n for i, importer in enumerate(sys.meta_path):\n # Here's some real nastiness: Another "instance" of the six module might\n # be floating around. Therefore, we can't use isinstance() to check for\n # the six meta path importer, since the other six instance will have\n # inserted an importer with different class.\n if (\n type(importer).__name__ == "_SixMetaPathImporter"\n and importer.name == __name__\n ):\n del sys.meta_path[i]\n break\n del i, importer\n# Finally, add the importer to the meta path import hook.\nsys.meta_path.append(_importer)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\six.py | six.py | Python | 34,665 | 0.95 | 0.187732 | 0.061772 | vue-tools | 280 | 2024-05-16T00:43:38.392217 | BSD-3-Clause | false | 6a3d2d8f7aa243d3576e2cec5fcf0ae2 |
# -*- coding: utf-8 -*-\n"""\nbackports.makefile\n~~~~~~~~~~~~~~~~~~\n\nBackports the Python 3 ``socket.makefile`` method for use with anything that\nwants to create a "fake" socket object.\n"""\nimport io\nfrom socket import SocketIO\n\n\ndef backport_makefile(\n self, mode="r", buffering=None, encoding=None, errors=None, newline=None\n):\n """\n Backport of ``socket.makefile`` from Python 3.5.\n """\n if not set(mode) <= {"r", "w", "b"}:\n raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))\n writing = "w" in mode\n reading = "r" in mode or not writing\n assert reading or writing\n binary = "b" in mode\n rawmode = ""\n if reading:\n rawmode += "r"\n if writing:\n rawmode += "w"\n raw = SocketIO(self, rawmode)\n self._makefile_refs += 1\n if buffering is None:\n buffering = -1\n if buffering < 0:\n buffering = io.DEFAULT_BUFFER_SIZE\n if buffering == 0:\n if not binary:\n raise ValueError("unbuffered streams must be binary")\n return raw\n if reading and writing:\n buffer = io.BufferedRWPair(raw, raw, buffering)\n elif reading:\n buffer = io.BufferedReader(raw, buffering)\n else:\n assert writing\n buffer = io.BufferedWriter(raw, buffering)\n if binary:\n return buffer\n text = io.TextIOWrapper(buffer, encoding, errors, newline)\n text.mode = mode\n return text\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\backports\makefile.py | makefile.py | Python | 1,417 | 0.95 | 0.215686 | 0.020833 | python-kit | 783 | 2025-01-31T08:28:44.805164 | Apache-2.0 | false | d26b39c4287d4132d46935c8e0b2e169 |
# -*- coding: utf-8 -*-\n"""\nbackports.weakref_finalize\n~~~~~~~~~~~~~~~~~~\n\nBackports the Python 3 ``weakref.finalize`` method.\n"""\nfrom __future__ import absolute_import\n\nimport itertools\nimport sys\nfrom weakref import ref\n\n__all__ = ["weakref_finalize"]\n\n\nclass weakref_finalize(object):\n """Class for finalization of weakrefable objects\n finalize(obj, func, *args, **kwargs) returns a callable finalizer\n object which will be called when obj is garbage collected. The\n first time the finalizer is called it evaluates func(*arg, **kwargs)\n and returns the result. After this the finalizer is dead, and\n calling it just returns None.\n When the program exits any remaining finalizers for which the\n atexit attribute is true will be run in reverse order of creation.\n By default atexit is true.\n """\n\n # Finalizer objects don't have any state of their own. They are\n # just used as keys to lookup _Info objects in the registry. This\n # ensures that they cannot be part of a ref-cycle.\n\n __slots__ = ()\n _registry = {}\n _shutdown = False\n _index_iter = itertools.count()\n _dirty = False\n _registered_with_atexit = False\n\n class _Info(object):\n __slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index")\n\n def __init__(self, obj, func, *args, **kwargs):\n if not self._registered_with_atexit:\n # We may register the exit function more than once because\n # of a thread race, but that is harmless\n import atexit\n\n atexit.register(self._exitfunc)\n weakref_finalize._registered_with_atexit = True\n info = self._Info()\n info.weakref = ref(obj, self)\n info.func = func\n info.args = args\n info.kwargs = kwargs or None\n info.atexit = True\n info.index = next(self._index_iter)\n self._registry[self] = info\n weakref_finalize._dirty = True\n\n def __call__(self, _=None):\n """If alive then mark as dead and return func(*args, **kwargs);\n otherwise return None"""\n info = self._registry.pop(self, None)\n if info and not self._shutdown:\n return info.func(*info.args, **(info.kwargs or {}))\n\n def detach(self):\n """If alive then mark as dead and return (obj, func, args, kwargs);\n otherwise return None"""\n info = self._registry.get(self)\n obj = info and info.weakref()\n if obj is not None and self._registry.pop(self, None):\n return (obj, info.func, info.args, info.kwargs or {})\n\n def peek(self):\n """If alive then return (obj, func, args, kwargs);\n otherwise return None"""\n info = self._registry.get(self)\n obj = info and info.weakref()\n if obj is not None:\n return (obj, info.func, info.args, info.kwargs or {})\n\n @property\n def alive(self):\n """Whether finalizer is alive"""\n return self in self._registry\n\n @property\n def atexit(self):\n """Whether finalizer should be called at exit"""\n info = self._registry.get(self)\n return bool(info) and info.atexit\n\n @atexit.setter\n def atexit(self, value):\n info = self._registry.get(self)\n if info:\n info.atexit = bool(value)\n\n def __repr__(self):\n info = self._registry.get(self)\n obj = info and info.weakref()\n if obj is None:\n return "<%s object at %#x; dead>" % (type(self).__name__, id(self))\n else:\n return "<%s object at %#x; for %r at %#x>" % (\n type(self).__name__,\n id(self),\n type(obj).__name__,\n id(obj),\n )\n\n @classmethod\n def _select_for_exit(cls):\n # Return live finalizers marked for exit, oldest first\n L = [(f, i) for (f, i) in cls._registry.items() if i.atexit]\n L.sort(key=lambda item: item[1].index)\n return [f for (f, i) in L]\n\n @classmethod\n def _exitfunc(cls):\n # At shutdown invoke finalizers for which atexit is true.\n # This is called once all other non-daemonic threads have been\n # joined.\n reenable_gc = False\n try:\n if cls._registry:\n import gc\n\n if gc.isenabled():\n reenable_gc = True\n gc.disable()\n pending = None\n while True:\n if pending is None or weakref_finalize._dirty:\n pending = cls._select_for_exit()\n weakref_finalize._dirty = False\n if not pending:\n break\n f = pending.pop()\n try:\n # gc is disabled, so (assuming no daemonic\n # threads) the following is the only line in\n # this function which might trigger creation\n # of a new finalizer\n f()\n except Exception:\n sys.excepthook(*sys.exc_info())\n assert f not in cls._registry\n finally:\n # prevent any more finalizers from executing during shutdown\n weakref_finalize._shutdown = True\n if reenable_gc:\n gc.enable()\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\backports\weakref_finalize.py | weakref_finalize.py | Python | 5,343 | 0.95 | 0.232258 | 0.111111 | node-utils | 835 | 2024-04-08T06:52:58.629338 | GPL-3.0 | false | f982b7d070fd238bd5c4069fbe0c795b |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\backports\__pycache__\makefile.cpython-313.pyc | makefile.cpython-313.pyc | Other | 1,937 | 0.8 | 0.030303 | 0 | python-kit | 259 | 2023-12-19T15:14:16.430918 | BSD-3-Clause | false | c67225cfc6ab55211f8e7fc83bb440f2 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\backports\__pycache__\weakref_finalize.cpython-313.pyc | weakref_finalize.cpython-313.pyc | Other | 7,532 | 0.95 | 0.04918 | 0.017241 | vue-tools | 176 | 2025-04-16T13:17:29.171732 | MIT | false | eac720e9005dac9f401632da2ed161a3 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\backports\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 213 | 0.7 | 0 | 0 | node-utils | 196 | 2025-01-30T17:11:47.260547 | Apache-2.0 | false | 550cccc843c86a131c5959582c0fc450 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\__pycache__\six.cpython-313.pyc | six.cpython-313.pyc | Other | 42,023 | 0.95 | 0.048077 | 0 | python-kit | 576 | 2025-01-29T04:32:01.940614 | Apache-2.0 | false | 4cad689462dfa7f2abac49c6debd9489 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\packages\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 203 | 0.7 | 0 | 0 | vue-tools | 456 | 2024-08-24T23:24:06.061005 | Apache-2.0 | false | 07880856920b2a99e953b0016394656a |
from __future__ import absolute_import\n\nimport socket\n\nfrom ..contrib import _appengine_environ\nfrom ..exceptions import LocationParseError\nfrom ..packages import six\nfrom .wait import NoWayToWaitForSocketError, wait_for_read\n\n\ndef is_connection_dropped(conn): # Platform-specific\n """\n Returns True if the connection is dropped and should be closed.\n\n :param conn:\n :class:`http.client.HTTPConnection` object.\n\n Note: For platforms like AppEngine, this will always return ``False`` to\n let the platform handle connection recycling transparently for us.\n """\n sock = getattr(conn, "sock", False)\n if sock is False: # Platform-specific: AppEngine\n return False\n if sock is None: # Connection already closed (such as by httplib).\n return True\n try:\n # Returns True if readable, which here means it's been dropped\n return wait_for_read(sock, timeout=0.0)\n except NoWayToWaitForSocketError: # Platform-specific: AppEngine\n return False\n\n\n# This function is copied from socket.py in the Python 2.7 standard\n# library test suite. Added to its signature is only `socket_options`.\n# One additional modification is that we avoid binding to IPv6 servers\n# discovered in DNS if the system doesn't have IPv6 functionality.\ndef create_connection(\n address,\n timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n source_address=None,\n socket_options=None,\n):\n """Connect to *address* and return the socket object.\n\n Convenience function. Connect to *address* (a 2-tuple ``(host,\n port)``) and return the socket object. Passing the optional\n *timeout* parameter will set the timeout on the socket instance\n before attempting to connect. If no *timeout* is supplied, the\n global default timeout setting returned by :func:`socket.getdefaulttimeout`\n is used. If *source_address* is set it must be a tuple of (host, port)\n for the socket to bind as a source address before making the connection.\n An host of '' or port 0 tells the OS to use the default.\n """\n\n host, port = address\n if host.startswith("["):\n host = host.strip("[]")\n err = None\n\n # Using the value from allowed_gai_family() in the context of getaddrinfo lets\n # us select whether to work with IPv4 DNS records, IPv6 records, or both.\n # The original create_connection function always returns all records.\n family = allowed_gai_family()\n\n try:\n host.encode("idna")\n except UnicodeError:\n return six.raise_from(\n LocationParseError(u"'%s', label empty or too long" % host), None\n )\n\n for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):\n af, socktype, proto, canonname, sa = res\n sock = None\n try:\n sock = socket.socket(af, socktype, proto)\n\n # If provided, set socket level options before connecting.\n _set_socket_options(sock, socket_options)\n\n if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:\n sock.settimeout(timeout)\n if source_address:\n sock.bind(source_address)\n sock.connect(sa)\n return sock\n\n except socket.error as e:\n err = e\n if sock is not None:\n sock.close()\n sock = None\n\n if err is not None:\n raise err\n\n raise socket.error("getaddrinfo returns an empty list")\n\n\ndef _set_socket_options(sock, options):\n if options is None:\n return\n\n for opt in options:\n sock.setsockopt(*opt)\n\n\ndef allowed_gai_family():\n """This function is designed to work in the context of\n getaddrinfo, where family=socket.AF_UNSPEC is the default and\n will perform a DNS search for both IPv6 and IPv4 records."""\n\n family = socket.AF_INET\n if HAS_IPV6:\n family = socket.AF_UNSPEC\n return family\n\n\ndef _has_ipv6(host):\n """Returns True if the system can bind an IPv6 address."""\n sock = None\n has_ipv6 = False\n\n # App Engine doesn't support IPV6 sockets and actually has a quota on the\n # number of sockets that can be used, so just early out here instead of\n # creating a socket needlessly.\n # See https://github.com/urllib3/urllib3/issues/1446\n if _appengine_environ.is_appengine_sandbox():\n return False\n\n if socket.has_ipv6:\n # has_ipv6 returns true if cPython was compiled with IPv6 support.\n # It does not tell us if the system has IPv6 support enabled. To\n # determine that we must bind to an IPv6 address.\n # https://github.com/urllib3/urllib3/pull/611\n # https://bugs.python.org/issue658327\n try:\n sock = socket.socket(socket.AF_INET6)\n sock.bind((host, 0))\n has_ipv6 = True\n except Exception:\n pass\n\n if sock:\n sock.close()\n return has_ipv6\n\n\nHAS_IPV6 = _has_ipv6("::1")\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\connection.py | connection.py | Python | 4,901 | 0.95 | 0.248322 | 0.161017 | python-kit | 944 | 2024-06-15T01:25:43.013541 | BSD-3-Clause | false | 3530b0109675511c483045517d150970 |
from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version\n\n\ndef connection_requires_http_tunnel(\n proxy_url=None, proxy_config=None, destination_scheme=None\n):\n """\n Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n :param URL proxy_url:\n URL of the proxy.\n :param ProxyConfig proxy_config:\n Proxy configuration from poolmanager.py\n :param str destination_scheme:\n The scheme of the destination. (i.e https, http, etc)\n """\n # If we're not using a proxy, no way to use a tunnel.\n if proxy_url is None:\n return False\n\n # HTTP destinations never require tunneling, we always forward.\n if destination_scheme == "http":\n return False\n\n # Support for forwarding with HTTPS proxies and HTTPS destinations.\n if (\n proxy_url.scheme == "https"\n and proxy_config\n and proxy_config.use_forwarding_for_https\n ):\n return False\n\n # Otherwise always use a tunnel.\n return True\n\n\ndef create_proxy_ssl_context(\n ssl_version, cert_reqs, ca_certs=None, ca_cert_dir=None, ca_cert_data=None\n):\n """\n Generates a default proxy ssl context if one hasn't been provided by the\n user.\n """\n ssl_context = create_urllib3_context(\n ssl_version=resolve_ssl_version(ssl_version),\n cert_reqs=resolve_cert_reqs(cert_reqs),\n )\n\n if (\n not ca_certs\n and not ca_cert_dir\n and not ca_cert_data\n and hasattr(ssl_context, "load_default_certs")\n ):\n ssl_context.load_default_certs()\n\n return ssl_context\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\proxy.py | proxy.py | Python | 1,605 | 0.95 | 0.157895 | 0.085106 | react-lib | 192 | 2023-10-11T15:08:18.111338 | Apache-2.0 | false | 6823df66ec0cb4e27629cfa1cde0ebdc |
import collections\n\nfrom ..packages import six\nfrom ..packages.six.moves import queue\n\nif six.PY2:\n # Queue is imported for side effects on MS Windows. See issue #229.\n import Queue as _unused_module_Queue # noqa: F401\n\n\nclass LifoQueue(queue.Queue):\n def _init(self, _):\n self.queue = collections.deque()\n\n def _qsize(self, len=len):\n return len(self.queue)\n\n def _put(self, item):\n self.queue.append(item)\n\n def _get(self):\n return self.queue.pop()\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\queue.py | queue.py | Python | 498 | 0.95 | 0.318182 | 0.066667 | node-utils | 958 | 2023-12-02T05:06:36.122209 | BSD-3-Clause | false | 716426931afad092ec0a85983ba6d094 |
from __future__ import absolute_import\n\nfrom base64 import b64encode\n\nfrom ..exceptions import UnrewindableBodyError\nfrom ..packages.six import b, integer_types\n\n# Pass as a value within ``headers`` to skip\n# emitting some HTTP headers that are added automatically.\n# The only headers that are supported are ``Accept-Encoding``,\n# ``Host``, and ``User-Agent``.\nSKIP_HEADER = "@@@SKIP_HEADER@@@"\nSKIPPABLE_HEADERS = frozenset(["accept-encoding", "host", "user-agent"])\n\nACCEPT_ENCODING = "gzip,deflate"\n\n_FAILEDTELL = object()\n\n\ndef make_headers(\n keep_alive=None,\n accept_encoding=None,\n user_agent=None,\n basic_auth=None,\n proxy_basic_auth=None,\n disable_cache=None,\n):\n """\n Shortcuts for generating request headers.\n\n :param keep_alive:\n If ``True``, adds 'connection: keep-alive' header.\n\n :param accept_encoding:\n Can be a boolean, list, or string.\n ``True`` translates to 'gzip,deflate'.\n List will get joined by comma.\n String will be used as provided.\n\n :param user_agent:\n String representing the user-agent you want, such as\n "python-urllib3/0.6"\n\n :param basic_auth:\n Colon-separated username:password string for 'authorization: basic ...'\n auth header.\n\n :param proxy_basic_auth:\n Colon-separated username:password string for 'proxy-authorization: basic ...'\n auth header.\n\n :param disable_cache:\n If ``True``, adds 'cache-control: no-cache' header.\n\n Example::\n\n >>> make_headers(keep_alive=True, user_agent="Batman/1.0")\n {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}\n >>> make_headers(accept_encoding=True)\n {'accept-encoding': 'gzip,deflate'}\n """\n headers = {}\n if accept_encoding:\n if isinstance(accept_encoding, str):\n pass\n elif isinstance(accept_encoding, list):\n accept_encoding = ",".join(accept_encoding)\n else:\n accept_encoding = ACCEPT_ENCODING\n headers["accept-encoding"] = accept_encoding\n\n if user_agent:\n headers["user-agent"] = user_agent\n\n if keep_alive:\n headers["connection"] = "keep-alive"\n\n if basic_auth:\n headers["authorization"] = "Basic " + b64encode(b(basic_auth)).decode("utf-8")\n\n if proxy_basic_auth:\n headers["proxy-authorization"] = "Basic " + b64encode(\n b(proxy_basic_auth)\n ).decode("utf-8")\n\n if disable_cache:\n headers["cache-control"] = "no-cache"\n\n return headers\n\n\ndef set_file_position(body, pos):\n """\n If a position is provided, move file to that point.\n Otherwise, we'll attempt to record a position for future use.\n """\n if pos is not None:\n rewind_body(body, pos)\n elif getattr(body, "tell", None) is not None:\n try:\n pos = body.tell()\n except (IOError, OSError):\n # This differentiates from None, allowing us to catch\n # a failed `tell()` later when trying to rewind the body.\n pos = _FAILEDTELL\n\n return pos\n\n\ndef rewind_body(body, body_pos):\n """\n Attempt to rewind body to a certain position.\n Primarily used for request redirects and retries.\n\n :param body:\n File-like object that supports seek.\n\n :param int pos:\n Position to seek to in file.\n """\n body_seek = getattr(body, "seek", None)\n if body_seek is not None and isinstance(body_pos, integer_types):\n try:\n body_seek(body_pos)\n except (IOError, OSError):\n raise UnrewindableBodyError(\n "An error occurred when rewinding request body for redirect/retry."\n )\n elif body_pos is _FAILEDTELL:\n raise UnrewindableBodyError(\n "Unable to record file position for rewinding "\n "request body during a redirect/retry."\n )\n else:\n raise ValueError(\n "body_pos must be of type integer, instead it was %s." % type(body_pos)\n )\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\request.py | request.py | Python | 3,997 | 0.95 | 0.160584 | 0.055046 | awesome-app | 643 | 2024-01-10T12:38:37.294455 | Apache-2.0 | false | aa68da750c53499c3d188288615c1276 |
from __future__ import absolute_import\n\nfrom email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect\n\nfrom ..exceptions import HeaderParsingError\nfrom ..packages.six.moves import http_client as httplib\n\n\ndef is_fp_closed(obj):\n """\n Checks whether a given file-like object is closed.\n\n :param obj:\n The file-like object to check.\n """\n\n try:\n # Check `isclosed()` first, in case Python3 doesn't set `closed`.\n # GH Issue #928\n return obj.isclosed()\n except AttributeError:\n pass\n\n try:\n # Check via the official file-like-object way.\n return obj.closed\n except AttributeError:\n pass\n\n try:\n # Check if the object is a container for another file-like object that\n # gets released on exhaustion (e.g. HTTPResponse).\n return obj.fp is None\n except AttributeError:\n pass\n\n raise ValueError("Unable to determine whether fp is closed.")\n\n\ndef assert_header_parsing(headers):\n """\n Asserts whether all headers have been successfully parsed.\n Extracts encountered errors from the result of parsing headers.\n\n Only works on Python 3.\n\n :param http.client.HTTPMessage headers: Headers to verify.\n\n :raises urllib3.exceptions.HeaderParsingError:\n If parsing errors are found.\n """\n\n # This will fail silently if we pass in the wrong kind of parameter.\n # To make debugging easier add an explicit check.\n if not isinstance(headers, httplib.HTTPMessage):\n raise TypeError("expected httplib.Message, got {0}.".format(type(headers)))\n\n defects = getattr(headers, "defects", None)\n get_payload = getattr(headers, "get_payload", None)\n\n unparsed_data = None\n if get_payload:\n # get_payload is actually email.message.Message.get_payload;\n # we're only interested in the result if it's not a multipart message\n if not headers.is_multipart():\n payload = get_payload()\n\n if isinstance(payload, (bytes, str)):\n unparsed_data = payload\n if defects:\n # httplib is assuming a response body is available\n # when parsing headers even when httplib only sends\n # header data to parse_headers() This results in\n # defects on multipart responses in particular.\n # See: https://github.com/urllib3/urllib3/issues/800\n\n # So we ignore the following defects:\n # - StartBoundaryNotFoundDefect:\n # The claimed start boundary was never found.\n # - MultipartInvariantViolationDefect:\n # A message claimed to be a multipart but no subparts were found.\n defects = [\n defect\n for defect in defects\n if not isinstance(\n defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)\n )\n ]\n\n if defects or unparsed_data:\n raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)\n\n\ndef is_response_to_head(response):\n """\n Checks whether the request of a response has been a HEAD-request.\n Handles the quirks of AppEngine.\n\n :param http.client.HTTPResponse response:\n Response to check if the originating request\n used 'HEAD' as a method.\n """\n # FIXME: Can we do this somehow without accessing private httplib _method?\n method = response._method\n if isinstance(method, int): # Platform-specific: Appengine\n return method == 3\n return method.upper() == "HEAD"\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\response.py | response.py | Python | 3,510 | 0.95 | 0.186916 | 0.238095 | node-utils | 614 | 2024-03-07T17:54:55.991985 | MIT | false | 6eb83504356cf0a5778199247f39e6ca |
from __future__ import absolute_import\n\nimport email\nimport logging\nimport re\nimport time\nimport warnings\nfrom collections import namedtuple\nfrom itertools import takewhile\n\nfrom ..exceptions import (\n ConnectTimeoutError,\n InvalidHeader,\n MaxRetryError,\n ProtocolError,\n ProxyError,\n ReadTimeoutError,\n ResponseError,\n)\nfrom ..packages import six\n\nlog = logging.getLogger(__name__)\n\n\n# Data structure for representing the metadata of requests that result in a retry.\nRequestHistory = namedtuple(\n "RequestHistory", ["method", "url", "error", "status", "redirect_location"]\n)\n\n\n# TODO: In v2 we can remove this sentinel and metaclass with deprecated options.\n_Default = object()\n\n\nclass _RetryMeta(type):\n @property\n def DEFAULT_METHOD_WHITELIST(cls):\n warnings.warn(\n "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "\n "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",\n DeprecationWarning,\n )\n return cls.DEFAULT_ALLOWED_METHODS\n\n @DEFAULT_METHOD_WHITELIST.setter\n def DEFAULT_METHOD_WHITELIST(cls, value):\n warnings.warn(\n "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "\n "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",\n DeprecationWarning,\n )\n cls.DEFAULT_ALLOWED_METHODS = value\n\n @property\n def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):\n warnings.warn(\n "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "\n "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",\n DeprecationWarning,\n )\n return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n @DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter\n def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):\n warnings.warn(\n "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "\n "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",\n DeprecationWarning,\n )\n cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value\n\n @property\n def BACKOFF_MAX(cls):\n warnings.warn(\n "Using 'Retry.BACKOFF_MAX' is deprecated and "\n "will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",\n DeprecationWarning,\n )\n return cls.DEFAULT_BACKOFF_MAX\n\n @BACKOFF_MAX.setter\n def BACKOFF_MAX(cls, value):\n warnings.warn(\n "Using 'Retry.BACKOFF_MAX' is deprecated and "\n "will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",\n DeprecationWarning,\n )\n cls.DEFAULT_BACKOFF_MAX = value\n\n\n@six.add_metaclass(_RetryMeta)\nclass Retry(object):\n """Retry configuration.\n\n Each retry attempt will create a new Retry object with updated values, so\n they can be safely reused.\n\n Retries can be defined as a default for a pool::\n\n retries = Retry(connect=5, read=2, redirect=5)\n http = PoolManager(retries=retries)\n response = http.request('GET', 'http://example.com/')\n\n Or per-request (which overrides the default for the pool)::\n\n response = http.request('GET', 'http://example.com/', retries=Retry(10))\n\n Retries can be disabled by passing ``False``::\n\n response = http.request('GET', 'http://example.com/', retries=False)\n\n Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n retries are disabled, in which case the causing exception will be raised.\n\n :param int total:\n Total number of retries to allow. Takes precedence over other counts.\n\n Set to ``None`` to remove this constraint and fall back on other\n counts.\n\n Set to ``0`` to fail on the first retry.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int connect:\n How many connection-related errors to retry on.\n\n These are errors raised before the request is sent to the remote server,\n which we assume has not triggered the server to process the request.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int read:\n How many times to retry on read errors.\n\n These errors are raised after the request was sent to the server, so the\n request may have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int redirect:\n How many redirects to perform. Limit this to avoid infinite redirect\n loops.\n\n A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n 308.\n\n Set to ``0`` to fail on the first retry of this type.\n\n Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n :param int status:\n How many times to retry on bad status codes.\n\n These are retries made on responses, where status code matches\n ``status_forcelist``.\n\n Set to ``0`` to fail on the first retry of this type.\n\n :param int other:\n How many times to retry on other errors.\n\n Other errors are errors that are not connect, read, redirect or status errors.\n These errors might be raised after the request was sent to the server, so the\n request might have side-effects.\n\n Set to ``0`` to fail on the first retry of this type.\n\n If ``total`` is not set, it's a good idea to set this to 0 to account\n for unexpected edge cases and avoid infinite retry loops.\n\n :param iterable allowed_methods:\n Set of uppercased HTTP method verbs that we should retry on.\n\n By default, we only retry on methods which are considered to be\n idempotent (multiple requests with the same parameters end with the\n same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n Set to a ``False`` value to retry on any verb.\n\n .. warning::\n\n Previously this parameter was named ``method_whitelist``, that\n usage is deprecated in v1.26.0 and will be removed in v2.0.\n\n :param iterable status_forcelist:\n A set of integer HTTP status codes that we should force a retry on.\n A retry is initiated if the request method is in ``allowed_methods``\n and the response status code is in ``status_forcelist``.\n\n By default, this is disabled with ``None``.\n\n :param float backoff_factor:\n A backoff factor to apply between attempts after the second try\n (most errors are resolved immediately by a second try without a\n delay). urllib3 will sleep for::\n\n {backoff factor} * (2 ** ({number of total retries} - 1))\n\n seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep\n for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer\n than :attr:`Retry.DEFAULT_BACKOFF_MAX`.\n\n By default, backoff is disabled (set to 0).\n\n :param bool raise_on_redirect: Whether, if the number of redirects is\n exhausted, to raise a MaxRetryError, or to return a response with a\n response code in the 3xx range.\n\n :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n whether we should raise an exception, or return a response,\n if status falls in ``status_forcelist`` range and retries have\n been exhausted.\n\n :param tuple history: The history of the request encountered during\n each call to :meth:`~Retry.increment`. The list is in the order\n the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n :param bool respect_retry_after_header:\n Whether to respect Retry-After header on status codes defined as\n :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n :param iterable remove_headers_on_redirect:\n Sequence of headers to remove from the request when a response\n indicating a redirect is returned before firing off the redirected\n request.\n """\n\n #: Default methods to be used for ``allowed_methods``\n DEFAULT_ALLOWED_METHODS = frozenset(\n ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]\n )\n\n #: Default status codes to be used for ``status_forcelist``\n RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n #: Default headers to be used for ``remove_headers_on_redirect``\n DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(\n ["Cookie", "Authorization", "Proxy-Authorization"]\n )\n\n #: Maximum backoff time.\n DEFAULT_BACKOFF_MAX = 120\n\n def __init__(\n self,\n total=10,\n connect=None,\n read=None,\n redirect=None,\n status=None,\n other=None,\n allowed_methods=_Default,\n status_forcelist=None,\n backoff_factor=0,\n raise_on_redirect=True,\n raise_on_status=True,\n history=None,\n respect_retry_after_header=True,\n remove_headers_on_redirect=_Default,\n # TODO: Deprecated, remove in v2.0\n method_whitelist=_Default,\n ):\n\n if method_whitelist is not _Default:\n if allowed_methods is not _Default:\n raise ValueError(\n "Using both 'allowed_methods' and "\n "'method_whitelist' together is not allowed. "\n "Instead only use 'allowed_methods'"\n )\n warnings.warn(\n "Using 'method_whitelist' with Retry is deprecated and "\n "will be removed in v2.0. Use 'allowed_methods' instead",\n DeprecationWarning,\n stacklevel=2,\n )\n allowed_methods = method_whitelist\n if allowed_methods is _Default:\n allowed_methods = self.DEFAULT_ALLOWED_METHODS\n if remove_headers_on_redirect is _Default:\n remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n self.total = total\n self.connect = connect\n self.read = read\n self.status = status\n self.other = other\n\n if redirect is False or total is False:\n redirect = 0\n raise_on_redirect = False\n\n self.redirect = redirect\n self.status_forcelist = status_forcelist or set()\n self.allowed_methods = allowed_methods\n self.backoff_factor = backoff_factor\n self.raise_on_redirect = raise_on_redirect\n self.raise_on_status = raise_on_status\n self.history = history or tuple()\n self.respect_retry_after_header = respect_retry_after_header\n self.remove_headers_on_redirect = frozenset(\n [h.lower() for h in remove_headers_on_redirect]\n )\n\n def new(self, **kw):\n params = dict(\n total=self.total,\n connect=self.connect,\n read=self.read,\n redirect=self.redirect,\n status=self.status,\n other=self.other,\n status_forcelist=self.status_forcelist,\n backoff_factor=self.backoff_factor,\n raise_on_redirect=self.raise_on_redirect,\n raise_on_status=self.raise_on_status,\n history=self.history,\n remove_headers_on_redirect=self.remove_headers_on_redirect,\n respect_retry_after_header=self.respect_retry_after_header,\n )\n\n # TODO: If already given in **kw we use what's given to us\n # If not given we need to figure out what to pass. We decide\n # based on whether our class has the 'method_whitelist' property\n # and if so we pass the deprecated 'method_whitelist' otherwise\n # we use 'allowed_methods'. Remove in v2.0\n if "method_whitelist" not in kw and "allowed_methods" not in kw:\n if "method_whitelist" in self.__dict__:\n warnings.warn(\n "Using 'method_whitelist' with Retry is deprecated and "\n "will be removed in v2.0. Use 'allowed_methods' instead",\n DeprecationWarning,\n )\n params["method_whitelist"] = self.allowed_methods\n else:\n params["allowed_methods"] = self.allowed_methods\n\n params.update(kw)\n return type(self)(**params)\n\n @classmethod\n def from_int(cls, retries, redirect=True, default=None):\n """Backwards-compatibility for the old retries format."""\n if retries is None:\n retries = default if default is not None else cls.DEFAULT\n\n if isinstance(retries, Retry):\n return retries\n\n redirect = bool(redirect) and None\n new_retries = cls(retries, redirect=redirect)\n log.debug("Converted retries value: %r -> %r", retries, new_retries)\n return new_retries\n\n def get_backoff_time(self):\n """Formula for computing the current backoff\n\n :rtype: float\n """\n # We want to consider only the last consecutive errors sequence (Ignore redirects).\n consecutive_errors_len = len(\n list(\n takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n )\n )\n if consecutive_errors_len <= 1:\n return 0\n\n backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n return min(self.DEFAULT_BACKOFF_MAX, backoff_value)\n\n def parse_retry_after(self, retry_after):\n # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n if re.match(r"^\s*[0-9]+\s*$", retry_after):\n seconds = int(retry_after)\n else:\n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)\n if retry_date_tuple[9] is None: # Python 2\n # Assume UTC if no timezone was specified\n # On Python2.7, parsedate_tz returns None for a timezone offset\n # instead of 0 if no timezone is given, where mktime_tz treats\n # a None timezone offset as local time.\n retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]\n\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n if seconds < 0:\n seconds = 0\n\n return seconds\n\n def get_retry_after(self, response):\n """Get the value of Retry-After in seconds."""\n\n retry_after = response.headers.get("Retry-After")\n\n if retry_after is None:\n return None\n\n return self.parse_retry_after(retry_after)\n\n def sleep_for_retry(self, response=None):\n retry_after = self.get_retry_after(response)\n if retry_after:\n time.sleep(retry_after)\n return True\n\n return False\n\n def _sleep_backoff(self):\n backoff = self.get_backoff_time()\n if backoff <= 0:\n return\n time.sleep(backoff)\n\n def sleep(self, response=None):\n """Sleep between retry attempts.\n\n This method will respect a server's ``Retry-After`` response header\n and sleep the duration of the time requested. If that is not present, it\n will use an exponential backoff. By default, the backoff factor is 0 and\n this method will return immediately.\n """\n\n if self.respect_retry_after_header and response:\n slept = self.sleep_for_retry(response)\n if slept:\n return\n\n self._sleep_backoff()\n\n def _is_connection_error(self, err):\n """Errors when we're fairly sure that the server did not receive the\n request, so it should be safe to retry.\n """\n if isinstance(err, ProxyError):\n err = err.original_error\n return isinstance(err, ConnectTimeoutError)\n\n def _is_read_error(self, err):\n """Errors that occur after the request has been started, so we should\n assume that the server began processing it.\n """\n return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n def _is_method_retryable(self, method):\n """Checks if a given HTTP method should be retried upon, depending if\n it is included in the allowed_methods\n """\n # TODO: For now favor if the Retry implementation sets its own method_whitelist\n # property outside of our constructor to avoid breaking custom implementations.\n if "method_whitelist" in self.__dict__:\n warnings.warn(\n "Using 'method_whitelist' with Retry is deprecated and "\n "will be removed in v2.0. Use 'allowed_methods' instead",\n DeprecationWarning,\n )\n allowed_methods = self.method_whitelist\n else:\n allowed_methods = self.allowed_methods\n\n if allowed_methods and method.upper() not in allowed_methods:\n return False\n return True\n\n def is_retry(self, method, status_code, has_retry_after=False):\n """Is this method/status code retryable? (Based on allowlists and control\n variables such as the number of total retries to allow, whether to\n respect the Retry-After header, whether this header is present, and\n whether the returned status code is on the list of status codes to\n be retried upon on the presence of the aforementioned header)\n """\n if not self._is_method_retryable(method):\n return False\n\n if self.status_forcelist and status_code in self.status_forcelist:\n return True\n\n return (\n self.total\n and self.respect_retry_after_header\n and has_retry_after\n and (status_code in self.RETRY_AFTER_STATUS_CODES)\n )\n\n def is_exhausted(self):\n """Are we out of retries?"""\n retry_counts = (\n self.total,\n self.connect,\n self.read,\n self.redirect,\n self.status,\n self.other,\n )\n retry_counts = list(filter(None, retry_counts))\n if not retry_counts:\n return False\n\n return min(retry_counts) < 0\n\n def increment(\n self,\n method=None,\n url=None,\n response=None,\n error=None,\n _pool=None,\n _stacktrace=None,\n ):\n """Return a new Retry object with incremented retry counters.\n\n :param response: A response object, or None, if the server did not\n return a response.\n :type response: :class:`~urllib3.response.HTTPResponse`\n :param Exception error: An error encountered during the request, or\n None if the response was received successfully.\n\n :return: A new ``Retry`` object.\n """\n if self.total is False and error:\n # Disabled, indicate to re-raise the error.\n raise six.reraise(type(error), error, _stacktrace)\n\n total = self.total\n if total is not None:\n total -= 1\n\n connect = self.connect\n read = self.read\n redirect = self.redirect\n status_count = self.status\n other = self.other\n cause = "unknown"\n status = None\n redirect_location = None\n\n if error and self._is_connection_error(error):\n # Connect retry?\n if connect is False:\n raise six.reraise(type(error), error, _stacktrace)\n elif connect is not None:\n connect -= 1\n\n elif error and self._is_read_error(error):\n # Read retry?\n if read is False or not self._is_method_retryable(method):\n raise six.reraise(type(error), error, _stacktrace)\n elif read is not None:\n read -= 1\n\n elif error:\n # Other retry?\n if other is not None:\n other -= 1\n\n elif response and response.get_redirect_location():\n # Redirect retry?\n if redirect is not None:\n redirect -= 1\n cause = "too many redirects"\n redirect_location = response.get_redirect_location()\n status = response.status\n\n else:\n # Incrementing because of a server error like a 500 in\n # status_forcelist and the given method is in the allowed_methods\n cause = ResponseError.GENERIC_ERROR\n if response and response.status:\n if status_count is not None:\n status_count -= 1\n cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n status = response.status\n\n history = self.history + (\n RequestHistory(method, url, error, status, redirect_location),\n )\n\n new_retry = self.new(\n total=total,\n connect=connect,\n read=read,\n redirect=redirect,\n status=status_count,\n other=other,\n history=history,\n )\n\n if new_retry.is_exhausted():\n raise MaxRetryError(_pool, url, error or ResponseError(cause))\n\n log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)\n\n return new_retry\n\n def __repr__(self):\n return (\n "{cls.__name__}(total={self.total}, connect={self.connect}, "\n "read={self.read}, redirect={self.redirect}, status={self.status})"\n ).format(cls=type(self), self=self)\n\n def __getattr__(self, item):\n if item == "method_whitelist":\n # TODO: Remove this deprecated alias in v2.0\n warnings.warn(\n "Using 'method_whitelist' with Retry is deprecated and "\n "will be removed in v2.0. Use 'allowed_methods' instead",\n DeprecationWarning,\n )\n return self.allowed_methods\n try:\n return getattr(super(Retry, self), item)\n except AttributeError:\n return getattr(Retry, item)\n\n\n# For backwards compatibility (equivalent to pre-v1.9):\nRetry.DEFAULT = Retry(3)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\retry.py | retry.py | Python | 22,050 | 0.95 | 0.152733 | 0.058 | react-lib | 478 | 2025-02-01T03:27:16.367663 | Apache-2.0 | false | 8a29318dd395289a179269e6c3481998 |
import io\nimport socket\nimport ssl\n\nfrom ..exceptions import ProxySchemeUnsupported\nfrom ..packages import six\n\nSSL_BLOCKSIZE = 16384\n\n\nclass SSLTransport:\n """\n The SSLTransport wraps an existing socket and establishes an SSL connection.\n\n Contrary to Python's implementation of SSLSocket, it allows you to chain\n multiple TLS connections together. It's particularly useful if you need to\n implement TLS within TLS.\n\n The class supports most of the socket API operations.\n """\n\n @staticmethod\n def _validate_ssl_context_for_tls_in_tls(ssl_context):\n """\n Raises a ProxySchemeUnsupported if the provided ssl_context can't be used\n for TLS in TLS.\n\n The only requirement is that the ssl_context provides the 'wrap_bio'\n methods.\n """\n\n if not hasattr(ssl_context, "wrap_bio"):\n if six.PY2:\n raise ProxySchemeUnsupported(\n "TLS in TLS requires SSLContext.wrap_bio() which isn't "\n "supported on Python 2"\n )\n else:\n raise ProxySchemeUnsupported(\n "TLS in TLS requires SSLContext.wrap_bio() which isn't "\n "available on non-native SSLContext"\n )\n\n def __init__(\n self, socket, ssl_context, server_hostname=None, suppress_ragged_eofs=True\n ):\n """\n Create an SSLTransport around socket using the provided ssl_context.\n """\n self.incoming = ssl.MemoryBIO()\n self.outgoing = ssl.MemoryBIO()\n\n self.suppress_ragged_eofs = suppress_ragged_eofs\n self.socket = socket\n\n self.sslobj = ssl_context.wrap_bio(\n self.incoming, self.outgoing, server_hostname=server_hostname\n )\n\n # Perform initial handshake.\n self._ssl_io_loop(self.sslobj.do_handshake)\n\n def __enter__(self):\n return self\n\n def __exit__(self, *_):\n self.close()\n\n def fileno(self):\n return self.socket.fileno()\n\n def read(self, len=1024, buffer=None):\n return self._wrap_ssl_read(len, buffer)\n\n def recv(self, len=1024, flags=0):\n if flags != 0:\n raise ValueError("non-zero flags not allowed in calls to recv")\n return self._wrap_ssl_read(len)\n\n def recv_into(self, buffer, nbytes=None, flags=0):\n if flags != 0:\n raise ValueError("non-zero flags not allowed in calls to recv_into")\n if buffer and (nbytes is None):\n nbytes = len(buffer)\n elif nbytes is None:\n nbytes = 1024\n return self.read(nbytes, buffer)\n\n def sendall(self, data, flags=0):\n if flags != 0:\n raise ValueError("non-zero flags not allowed in calls to sendall")\n count = 0\n with memoryview(data) as view, view.cast("B") as byte_view:\n amount = len(byte_view)\n while count < amount:\n v = self.send(byte_view[count:])\n count += v\n\n def send(self, data, flags=0):\n if flags != 0:\n raise ValueError("non-zero flags not allowed in calls to send")\n response = self._ssl_io_loop(self.sslobj.write, data)\n return response\n\n def makefile(\n self, mode="r", buffering=None, encoding=None, errors=None, newline=None\n ):\n """\n Python's httpclient uses makefile and buffered io when reading HTTP\n messages and we need to support it.\n\n This is unfortunately a copy and paste of socket.py makefile with small\n changes to point to the socket directly.\n """\n if not set(mode) <= {"r", "w", "b"}:\n raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))\n\n writing = "w" in mode\n reading = "r" in mode or not writing\n assert reading or writing\n binary = "b" in mode\n rawmode = ""\n if reading:\n rawmode += "r"\n if writing:\n rawmode += "w"\n raw = socket.SocketIO(self, rawmode)\n self.socket._io_refs += 1\n if buffering is None:\n buffering = -1\n if buffering < 0:\n buffering = io.DEFAULT_BUFFER_SIZE\n if buffering == 0:\n if not binary:\n raise ValueError("unbuffered streams must be binary")\n return raw\n if reading and writing:\n buffer = io.BufferedRWPair(raw, raw, buffering)\n elif reading:\n buffer = io.BufferedReader(raw, buffering)\n else:\n assert writing\n buffer = io.BufferedWriter(raw, buffering)\n if binary:\n return buffer\n text = io.TextIOWrapper(buffer, encoding, errors, newline)\n text.mode = mode\n return text\n\n def unwrap(self):\n self._ssl_io_loop(self.sslobj.unwrap)\n\n def close(self):\n self.socket.close()\n\n def getpeercert(self, binary_form=False):\n return self.sslobj.getpeercert(binary_form)\n\n def version(self):\n return self.sslobj.version()\n\n def cipher(self):\n return self.sslobj.cipher()\n\n def selected_alpn_protocol(self):\n return self.sslobj.selected_alpn_protocol()\n\n def selected_npn_protocol(self):\n return self.sslobj.selected_npn_protocol()\n\n def shared_ciphers(self):\n return self.sslobj.shared_ciphers()\n\n def compression(self):\n return self.sslobj.compression()\n\n def settimeout(self, value):\n self.socket.settimeout(value)\n\n def gettimeout(self):\n return self.socket.gettimeout()\n\n def _decref_socketios(self):\n self.socket._decref_socketios()\n\n def _wrap_ssl_read(self, len, buffer=None):\n try:\n return self._ssl_io_loop(self.sslobj.read, len, buffer)\n except ssl.SSLError as e:\n if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs:\n return 0 # eof, return 0.\n else:\n raise\n\n def _ssl_io_loop(self, func, *args):\n """Performs an I/O loop between incoming/outgoing and the socket."""\n should_loop = True\n ret = None\n\n while should_loop:\n errno = None\n try:\n ret = func(*args)\n except ssl.SSLError as e:\n if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):\n # WANT_READ, and WANT_WRITE are expected, others are not.\n raise e\n errno = e.errno\n\n buf = self.outgoing.read()\n self.socket.sendall(buf)\n\n if errno is None:\n should_loop = False\n elif errno == ssl.SSL_ERROR_WANT_READ:\n buf = self.socket.recv(SSL_BLOCKSIZE)\n if buf:\n self.incoming.write(buf)\n else:\n self.incoming.write_eof()\n return ret\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\ssltransport.py | ssltransport.py | Python | 6,895 | 0.95 | 0.244344 | 0.011111 | awesome-app | 609 | 2023-09-16T07:01:58.366910 | MIT | false | 33c5c43f65397d31eebbac57dc2cef3a |
from __future__ import absolute_import\n\nimport hashlib\nimport hmac\nimport os\nimport sys\nimport warnings\nfrom binascii import hexlify, unhexlify\n\nfrom ..exceptions import (\n InsecurePlatformWarning,\n ProxySchemeUnsupported,\n SNIMissingWarning,\n SSLError,\n)\nfrom ..packages import six\nfrom .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE\n\nSSLContext = None\nSSLTransport = None\nHAS_SNI = False\nIS_PYOPENSSL = False\nIS_SECURETRANSPORT = False\nALPN_PROTOCOLS = ["http/1.1"]\n\n# Maps the length of a digest to a possible hash function producing this digest\nHASHFUNC_MAP = {\n length: getattr(hashlib, algorithm, None)\n for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256"))\n}\n\n\ndef _const_compare_digest_backport(a, b):\n """\n Compare two digests of equal length in constant time.\n\n The digests must be of type str/bytes.\n Returns True if the digests match, and False otherwise.\n """\n result = abs(len(a) - len(b))\n for left, right in zip(bytearray(a), bytearray(b)):\n result |= left ^ right\n return result == 0\n\n\n_const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport)\n\ntry: # Test for SSL features\n import ssl\n from ssl import CERT_REQUIRED, wrap_socket\nexcept ImportError:\n pass\n\ntry:\n from ssl import HAS_SNI # Has SNI?\nexcept ImportError:\n pass\n\ntry:\n from .ssltransport import SSLTransport\nexcept ImportError:\n pass\n\n\ntry: # Platform-specific: Python 3.6\n from ssl import PROTOCOL_TLS\n\n PROTOCOL_SSLv23 = PROTOCOL_TLS\nexcept ImportError:\n try:\n from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS\n\n PROTOCOL_SSLv23 = PROTOCOL_TLS\n except ImportError:\n PROTOCOL_SSLv23 = PROTOCOL_TLS = 2\n\ntry:\n from ssl import PROTOCOL_TLS_CLIENT\nexcept ImportError:\n PROTOCOL_TLS_CLIENT = PROTOCOL_TLS\n\n\ntry:\n from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3\nexcept ImportError:\n OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000\n OP_NO_COMPRESSION = 0x20000\n\n\ntry: # OP_NO_TICKET was added in Python 3.6\n from ssl import OP_NO_TICKET\nexcept ImportError:\n OP_NO_TICKET = 0x4000\n\n\n# A secure default.\n# Sources for more information on TLS ciphers:\n#\n# - https://wiki.mozilla.org/Security/Server_Side_TLS\n# - https://www.ssllabs.com/projects/best-practices/index.html\n# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/\n#\n# The general intent is:\n# - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),\n# - prefer ECDHE over DHE for better performance,\n# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and\n# security,\n# - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,\n# - disable NULL authentication, MD5 MACs, DSS, and other\n# insecure ciphers for security reasons.\n# - NOTE: TLS 1.3 cipher suites are managed through a different interface\n# not exposed by CPython (yet!) and are enabled by default if they're available.\nDEFAULT_CIPHERS = ":".join(\n [\n "ECDHE+AESGCM",\n "ECDHE+CHACHA20",\n "DHE+AESGCM",\n "DHE+CHACHA20",\n "ECDH+AESGCM",\n "DH+AESGCM",\n "ECDH+AES",\n "DH+AES",\n "RSA+AESGCM",\n "RSA+AES",\n "!aNULL",\n "!eNULL",\n "!MD5",\n "!DSS",\n ]\n)\n\ntry:\n from ssl import SSLContext # Modern SSL?\nexcept ImportError:\n\n class SSLContext(object): # Platform-specific: Python 2\n def __init__(self, protocol_version):\n self.protocol = protocol_version\n # Use default values from a real SSLContext\n self.check_hostname = False\n self.verify_mode = ssl.CERT_NONE\n self.ca_certs = None\n self.options = 0\n self.certfile = None\n self.keyfile = None\n self.ciphers = None\n\n def load_cert_chain(self, certfile, keyfile):\n self.certfile = certfile\n self.keyfile = keyfile\n\n def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n self.ca_certs = cafile\n\n if capath is not None:\n raise SSLError("CA directories not supported in older Pythons")\n\n if cadata is not None:\n raise SSLError("CA data not supported in older Pythons")\n\n def set_ciphers(self, cipher_suite):\n self.ciphers = cipher_suite\n\n def wrap_socket(self, socket, server_hostname=None, server_side=False):\n warnings.warn(\n "A true SSLContext object is not available. This prevents "\n "urllib3 from configuring SSL appropriately and may cause "\n "certain SSL connections to fail. You can upgrade to a newer "\n "version of Python to solve this. For more information, see "\n "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"\n "#ssl-warnings",\n InsecurePlatformWarning,\n )\n kwargs = {\n "keyfile": self.keyfile,\n "certfile": self.certfile,\n "ca_certs": self.ca_certs,\n "cert_reqs": self.verify_mode,\n "ssl_version": self.protocol,\n "server_side": server_side,\n }\n return wrap_socket(socket, ciphers=self.ciphers, **kwargs)\n\n\ndef assert_fingerprint(cert, fingerprint):\n """\n Checks if given fingerprint matches the supplied certificate.\n\n :param cert:\n Certificate as bytes object.\n :param fingerprint:\n Fingerprint as string of hexdigits, can be interspersed by colons.\n """\n\n fingerprint = fingerprint.replace(":", "").lower()\n digest_length = len(fingerprint)\n if digest_length not in HASHFUNC_MAP:\n raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint))\n hashfunc = HASHFUNC_MAP.get(digest_length)\n if hashfunc is None:\n raise SSLError(\n "Hash function implementation unavailable for fingerprint length: {0}".format(\n digest_length\n )\n )\n\n # We need encode() here for py32; works on py2 and p33.\n fingerprint_bytes = unhexlify(fingerprint.encode())\n\n cert_digest = hashfunc(cert).digest()\n\n if not _const_compare_digest(cert_digest, fingerprint_bytes):\n raise SSLError(\n 'Fingerprints did not match. Expected "{0}", got "{1}".'.format(\n fingerprint, hexlify(cert_digest)\n )\n )\n\n\ndef resolve_cert_reqs(candidate):\n """\n Resolves the argument to a numeric constant, which can be passed to\n the wrap_socket function/method from the ssl module.\n Defaults to :data:`ssl.CERT_REQUIRED`.\n If given a string it is assumed to be the name of the constant in the\n :mod:`ssl` module or its abbreviation.\n (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n If it's neither `None` nor a string we assume it is already the numeric\n constant which can directly be passed to wrap_socket.\n """\n if candidate is None:\n return CERT_REQUIRED\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, "CERT_" + candidate)\n return res\n\n return candidate\n\n\ndef resolve_ssl_version(candidate):\n """\n like resolve_cert_reqs\n """\n if candidate is None:\n return PROTOCOL_TLS\n\n if isinstance(candidate, str):\n res = getattr(ssl, candidate, None)\n if res is None:\n res = getattr(ssl, "PROTOCOL_" + candidate)\n return res\n\n return candidate\n\n\ndef create_urllib3_context(\n ssl_version=None, cert_reqs=None, options=None, ciphers=None\n):\n """All arguments have the same meaning as ``ssl_wrap_socket``.\n\n By default, this function does a lot of the same work that\n ``ssl.create_default_context`` does on Python 3.4+. It:\n\n - Disables SSLv2, SSLv3, and compression\n - Sets a restricted set of server ciphers\n\n If you wish to enable SSLv3, you can do::\n\n from pip._vendor.urllib3.util import ssl_\n context = ssl_.create_urllib3_context()\n context.options &= ~ssl_.OP_NO_SSLv3\n\n You can do the same to enable compression (substituting ``COMPRESSION``\n for ``SSLv3`` in the last line above).\n\n :param ssl_version:\n The desired protocol version to use. This will default to\n PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n the server and your installation of OpenSSL support.\n :param cert_reqs:\n Whether to require the certificate verification. This defaults to\n ``ssl.CERT_REQUIRED``.\n :param options:\n Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.\n :param ciphers:\n Which cipher suites to allow the server to select.\n :returns:\n Constructed SSLContext object with specified options\n :rtype: SSLContext\n """\n # PROTOCOL_TLS is deprecated in Python 3.10\n if not ssl_version or ssl_version == PROTOCOL_TLS:\n ssl_version = PROTOCOL_TLS_CLIENT\n\n context = SSLContext(ssl_version)\n\n context.set_ciphers(ciphers or DEFAULT_CIPHERS)\n\n # Setting the default here, as we may have no ssl module on import\n cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n if options is None:\n options = 0\n # SSLv2 is easily broken and is considered harmful and dangerous\n options |= OP_NO_SSLv2\n # SSLv3 has several problems and is now dangerous\n options |= OP_NO_SSLv3\n # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n # (issue #309)\n options |= OP_NO_COMPRESSION\n # TLSv1.2 only. Unless set explicitly, do not request tickets.\n # This may save some bandwidth on wire, and although the ticket is encrypted,\n # there is a risk associated with it being on wire,\n # if the server is not rotating its ticketing keys properly.\n options |= OP_NO_TICKET\n\n context.options |= options\n\n # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is\n # necessary for conditional client cert authentication with TLS 1.3.\n # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older\n # versions of Python. We only enable on Python 3.7.4+ or if certificate\n # verification is enabled to work around Python issue #37428\n # See: https://bugs.python.org/issue37428\n if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(\n context, "post_handshake_auth", None\n ) is not None:\n context.post_handshake_auth = True\n\n def disable_check_hostname():\n if (\n getattr(context, "check_hostname", None) is not None\n ): # Platform-specific: Python 3.2\n # We do our own verification, including fingerprints and alternative\n # hostnames. So disable it here\n context.check_hostname = False\n\n # The order of the below lines setting verify_mode and check_hostname\n # matter due to safe-guards SSLContext has to prevent an SSLContext with\n # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more\n # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used\n # or not so we don't know the initial state of the freshly created SSLContext.\n if cert_reqs == ssl.CERT_REQUIRED:\n context.verify_mode = cert_reqs\n disable_check_hostname()\n else:\n disable_check_hostname()\n context.verify_mode = cert_reqs\n\n # Enable logging of TLS session keys via defacto standard environment variable\n # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.\n if hasattr(context, "keylog_filename"):\n sslkeylogfile = os.environ.get("SSLKEYLOGFILE")\n if sslkeylogfile:\n context.keylog_filename = sslkeylogfile\n\n return context\n\n\ndef ssl_wrap_socket(\n sock,\n keyfile=None,\n certfile=None,\n cert_reqs=None,\n ca_certs=None,\n server_hostname=None,\n ssl_version=None,\n ciphers=None,\n ssl_context=None,\n ca_cert_dir=None,\n key_password=None,\n ca_cert_data=None,\n tls_in_tls=False,\n):\n """\n All arguments except for server_hostname, ssl_context, and ca_cert_dir have\n the same meaning as they do when using :func:`ssl.wrap_socket`.\n\n :param server_hostname:\n When SNI is supported, the expected hostname of the certificate\n :param ssl_context:\n A pre-made :class:`SSLContext` object. If none is provided, one will\n be created using :func:`create_urllib3_context`.\n :param ciphers:\n A string of ciphers we wish the client to support.\n :param ca_cert_dir:\n A directory containing CA certificates in multiple separate files, as\n supported by OpenSSL's -CApath flag or the capath argument to\n SSLContext.load_verify_locations().\n :param key_password:\n Optional password if the keyfile is encrypted.\n :param ca_cert_data:\n Optional string containing CA certificates in PEM format suitable for\n passing as the cadata parameter to SSLContext.load_verify_locations()\n :param tls_in_tls:\n Use SSLTransport to wrap the existing socket.\n """\n context = ssl_context\n if context is None:\n # Note: This branch of code and all the variables in it are no longer\n # used by urllib3 itself. We should consider deprecating and removing\n # this code.\n context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)\n\n if ca_certs or ca_cert_dir or ca_cert_data:\n try:\n context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)\n except (IOError, OSError) as e:\n raise SSLError(e)\n\n elif ssl_context is None and hasattr(context, "load_default_certs"):\n # try to load OS default certs; works well on Windows (require Python3.4+)\n context.load_default_certs()\n\n # Attempt to detect if we get the goofy behavior of the\n # keyfile being encrypted and OpenSSL asking for the\n # passphrase via the terminal and instead error out.\n if keyfile and key_password is None and _is_key_file_encrypted(keyfile):\n raise SSLError("Client private key is encrypted, password is required")\n\n if certfile:\n if key_password is None:\n context.load_cert_chain(certfile, keyfile)\n else:\n context.load_cert_chain(certfile, keyfile, key_password)\n\n try:\n if hasattr(context, "set_alpn_protocols"):\n context.set_alpn_protocols(ALPN_PROTOCOLS)\n except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols\n pass\n\n # If we detect server_hostname is an IP address then the SNI\n # extension should not be used according to RFC3546 Section 3.1\n use_sni_hostname = server_hostname and not is_ipaddress(server_hostname)\n # SecureTransport uses server_hostname in certificate verification.\n send_sni = (use_sni_hostname and HAS_SNI) or (\n IS_SECURETRANSPORT and server_hostname\n )\n # Do not warn the user if server_hostname is an invalid SNI hostname.\n if not HAS_SNI and use_sni_hostname:\n warnings.warn(\n "An HTTPS request has been made, but the SNI (Server Name "\n "Indication) extension to TLS is not available on this platform. "\n "This may cause the server to present an incorrect TLS "\n "certificate, which can cause validation failures. You can upgrade to "\n "a newer version of Python to solve this. For more information, see "\n "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"\n "#ssl-warnings",\n SNIMissingWarning,\n )\n\n if send_sni:\n ssl_sock = _ssl_wrap_socket_impl(\n sock, context, tls_in_tls, server_hostname=server_hostname\n )\n else:\n ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)\n return ssl_sock\n\n\ndef is_ipaddress(hostname):\n """Detects whether the hostname given is an IPv4 or IPv6 address.\n Also detects IPv6 addresses with Zone IDs.\n\n :param str hostname: Hostname to examine.\n :return: True if the hostname is an IP address, False otherwise.\n """\n if not six.PY2 and isinstance(hostname, bytes):\n # IDN A-label bytes are ASCII compatible.\n hostname = hostname.decode("ascii")\n return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))\n\n\ndef _is_key_file_encrypted(key_file):\n """Detects if a key file is encrypted or not."""\n with open(key_file, "r") as f:\n for line in f:\n # Look for Proc-Type: 4,ENCRYPTED\n if "ENCRYPTED" in line:\n return True\n\n return False\n\n\ndef _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None):\n if tls_in_tls:\n if not SSLTransport:\n # Import error, ssl is not available.\n raise ProxySchemeUnsupported(\n "TLS in TLS requires support for the 'ssl' module"\n )\n\n SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)\n return SSLTransport(sock, ssl_context, server_hostname)\n\n if server_hostname:\n return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n else:\n return ssl_context.wrap_socket(sock)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\ssl_.py | ssl_.py | Python | 17,460 | 0.95 | 0.190476 | 0.140476 | node-utils | 854 | 2025-04-08T10:03:29.739845 | Apache-2.0 | false | 81df3f9f4ba3573a6a6919770f8ab6ed |
"""The match_hostname() function from Python 3.3.3, essential when using SSL."""\n\n# Note: This file is under the PSF license as the code comes from the python\n# stdlib. http://docs.python.org/3/license.html\n\nimport re\nimport sys\n\n# ipaddress has been backported to 2.6+ in pypi. If it is installed on the\n# system, use it to handle IPAddress ServerAltnames (this was added in\n# python-3.5) otherwise only do DNS matching. This allows\n# util.ssl_match_hostname to continue to be used in Python 2.7.\ntry:\n import ipaddress\nexcept ImportError:\n ipaddress = None\n\n__version__ = "3.5.0.1"\n\n\nclass CertificateError(ValueError):\n pass\n\n\ndef _dnsname_match(dn, hostname, max_wildcards=1):\n """Matching according to RFC 6125, section 6.4.3\n\n http://tools.ietf.org/html/rfc6125#section-6.4.3\n """\n pats = []\n if not dn:\n return False\n\n # Ported from python3-syntax:\n # leftmost, *remainder = dn.split(r'.')\n parts = dn.split(r".")\n leftmost = parts[0]\n remainder = parts[1:]\n\n wildcards = leftmost.count("*")\n if wildcards > max_wildcards:\n # Issue #17980: avoid denials of service by refusing more\n # than one wildcard per fragment. A survey of established\n # policy among SSL implementations showed it to be a\n # reasonable choice.\n raise CertificateError(\n "too many wildcards in certificate DNS name: " + repr(dn)\n )\n\n # speed up common case w/o wildcards\n if not wildcards:\n return dn.lower() == hostname.lower()\n\n # RFC 6125, section 6.4.3, subitem 1.\n # The client SHOULD NOT attempt to match a presented identifier in which\n # the wildcard character comprises a label other than the left-most label.\n if leftmost == "*":\n # When '*' is a fragment by itself, it matches a non-empty dotless\n # fragment.\n pats.append("[^.]+")\n elif leftmost.startswith("xn--") or hostname.startswith("xn--"):\n # RFC 6125, section 6.4.3, subitem 3.\n # The client SHOULD NOT attempt to match a presented identifier\n # where the wildcard character is embedded within an A-label or\n # U-label of an internationalized domain name.\n pats.append(re.escape(leftmost))\n else:\n # Otherwise, '*' matches any dotless string, e.g. www*\n pats.append(re.escape(leftmost).replace(r"\*", "[^.]*"))\n\n # add the remaining fragments, ignore any wildcards\n for frag in remainder:\n pats.append(re.escape(frag))\n\n pat = re.compile(r"\A" + r"\.".join(pats) + r"\Z", re.IGNORECASE)\n return pat.match(hostname)\n\n\ndef _to_unicode(obj):\n if isinstance(obj, str) and sys.version_info < (3,):\n # ignored flake8 # F821 to support python 2.7 function\n obj = unicode(obj, encoding="ascii", errors="strict") # noqa: F821\n return obj\n\n\ndef _ipaddress_match(ipname, host_ip):\n """Exact matching of IP addresses.\n\n RFC 6125 explicitly doesn't define an algorithm for this\n (section 1.7.2 - "Out of Scope").\n """\n # OpenSSL may add a trailing newline to a subjectAltName's IP address\n # Divergence from upstream: ipaddress can't handle byte str\n ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())\n return ip == host_ip\n\n\ndef match_hostname(cert, hostname):\n """Verify that *cert* (in decoded format as returned by\n SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125\n rules are followed, but IP addresses are not accepted for *hostname*.\n\n CertificateError is raised on failure. On success, the function\n returns nothing.\n """\n if not cert:\n raise ValueError(\n "empty or no certificate, match_hostname needs a "\n "SSL socket or SSL context with either "\n "CERT_OPTIONAL or CERT_REQUIRED"\n )\n try:\n # Divergence from upstream: ipaddress can't handle byte str\n host_ip = ipaddress.ip_address(_to_unicode(hostname))\n except (UnicodeError, ValueError):\n # ValueError: Not an IP address (common case)\n # UnicodeError: Divergence from upstream: Have to deal with ipaddress not taking\n # byte strings. addresses should be all ascii, so we consider it not\n # an ipaddress in this case\n host_ip = None\n except AttributeError:\n # Divergence from upstream: Make ipaddress library optional\n if ipaddress is None:\n host_ip = None\n else: # Defensive\n raise\n dnsnames = []\n san = cert.get("subjectAltName", ())\n for key, value in san:\n if key == "DNS":\n if host_ip is None and _dnsname_match(value, hostname):\n return\n dnsnames.append(value)\n elif key == "IP Address":\n if host_ip is not None and _ipaddress_match(value, host_ip):\n return\n dnsnames.append(value)\n if not dnsnames:\n # The subject is only checked when there is no dNSName entry\n # in subjectAltName\n for sub in cert.get("subject", ()):\n for key, value in sub:\n # XXX according to RFC 2818, the most specific Common Name\n # must be used.\n if key == "commonName":\n if _dnsname_match(value, hostname):\n return\n dnsnames.append(value)\n if len(dnsnames) > 1:\n raise CertificateError(\n "hostname %r "\n "doesn't match either of %s" % (hostname, ", ".join(map(repr, dnsnames)))\n )\n elif len(dnsnames) == 1:\n raise CertificateError("hostname %r doesn't match %r" % (hostname, dnsnames[0]))\n else:\n raise CertificateError(\n "no appropriate commonName or subjectAltName fields were found"\n )\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\ssl_match_hostname.py | ssl_match_hostname.py | Python | 5,758 | 0.95 | 0.188679 | 0.272059 | python-kit | 997 | 2024-02-26T11:33:31.998090 | GPL-3.0 | false | b0db7b081c5b51774a44654d586e0f40 |
from __future__ import absolute_import\n\nimport time\n\n# The default socket timeout, used by httplib to indicate that no timeout was; specified by the user\nfrom socket import _GLOBAL_DEFAULT_TIMEOUT, getdefaulttimeout\n\nfrom ..exceptions import TimeoutStateError\n\n# A sentinel value to indicate that no timeout was specified by the user in\n# urllib3\n_Default = object()\n\n\n# Use time.monotonic if available.\ncurrent_time = getattr(time, "monotonic", time.time)\n\n\nclass Timeout(object):\n """Timeout configuration.\n\n Timeouts can be defined as a default for a pool:\n\n .. code-block:: python\n\n timeout = Timeout(connect=2.0, read=7.0)\n http = PoolManager(timeout=timeout)\n response = http.request('GET', 'http://example.com/')\n\n Or per-request (which overrides the default for the pool):\n\n .. code-block:: python\n\n response = http.request('GET', 'http://example.com/', timeout=Timeout(10))\n\n Timeouts can be disabled by setting all the parameters to ``None``:\n\n .. code-block:: python\n\n no_timeout = Timeout(connect=None, read=None)\n response = http.request('GET', 'http://example.com/, timeout=no_timeout)\n\n\n :param total:\n This combines the connect and read timeouts into one; the read timeout\n will be set to the time leftover from the connect attempt. In the\n event that both a connect timeout and a total are specified, or a read\n timeout and a total are specified, the shorter timeout will be applied.\n\n Defaults to None.\n\n :type total: int, float, or None\n\n :param connect:\n The maximum amount of time (in seconds) to wait for a connection\n attempt to a server to succeed. Omitting the parameter will default the\n connect timeout to the system default, probably `the global default\n timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout for connection attempts.\n\n :type connect: int, float, or None\n\n :param read:\n The maximum amount of time (in seconds) to wait between consecutive\n read operations for a response from the server. Omitting the parameter\n will default the read timeout to the system default, probably `the\n global default timeout in socket.py\n <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n None will set an infinite timeout.\n\n :type read: int, float, or None\n\n .. note::\n\n Many factors can affect the total amount of time for urllib3 to return\n an HTTP response.\n\n For example, Python's DNS resolver does not obey the timeout specified\n on the socket. Other factors that can affect total request time include\n high CPU load, high swap, the program running at a low priority level,\n or other behaviors.\n\n In addition, the read and total timeouts only measure the time between\n read operations on the socket connecting the client and the server,\n not the total amount of time for the request to return a complete\n response. For most requests, the timeout is raised because the server\n has not sent the first byte in the specified time. This is not always\n the case; if a server streams one byte every fifteen seconds, a timeout\n of 20 seconds will not trigger, even though the request will take\n several minutes to complete.\n\n If your goal is to cut off any request after a set amount of wall clock\n time, consider having a second "watcher" thread to cut off a slow\n request.\n """\n\n #: A sentinel object representing the default timeout value\n DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT\n\n def __init__(self, total=None, connect=_Default, read=_Default):\n self._connect = self._validate_timeout(connect, "connect")\n self._read = self._validate_timeout(read, "read")\n self.total = self._validate_timeout(total, "total")\n self._start_connect = None\n\n def __repr__(self):\n return "%s(connect=%r, read=%r, total=%r)" % (\n type(self).__name__,\n self._connect,\n self._read,\n self.total,\n )\n\n # __str__ provided for backwards compatibility\n __str__ = __repr__\n\n @classmethod\n def resolve_default_timeout(cls, timeout):\n return getdefaulttimeout() if timeout is cls.DEFAULT_TIMEOUT else timeout\n\n @classmethod\n def _validate_timeout(cls, value, name):\n """Check that a timeout attribute is valid.\n\n :param value: The timeout value to validate\n :param name: The name of the timeout attribute to validate. This is\n used to specify in error messages.\n :return: The validated and casted version of the given value.\n :raises ValueError: If it is a numeric value less than or equal to\n zero, or the type is not an integer, float, or None.\n """\n if value is _Default:\n return cls.DEFAULT_TIMEOUT\n\n if value is None or value is cls.DEFAULT_TIMEOUT:\n return value\n\n if isinstance(value, bool):\n raise ValueError(\n "Timeout cannot be a boolean value. It must "\n "be an int, float or None."\n )\n try:\n float(value)\n except (TypeError, ValueError):\n raise ValueError(\n "Timeout value %s was %s, but it must be an "\n "int, float or None." % (name, value)\n )\n\n try:\n if value <= 0:\n raise ValueError(\n "Attempted to set %s timeout to %s, but the "\n "timeout cannot be set to a value less "\n "than or equal to 0." % (name, value)\n )\n except TypeError:\n # Python 3\n raise ValueError(\n "Timeout value %s was %s, but it must be an "\n "int, float or None." % (name, value)\n )\n\n return value\n\n @classmethod\n def from_float(cls, timeout):\n """Create a new Timeout from a legacy timeout value.\n\n The timeout value used by httplib.py sets the same timeout on the\n connect(), and recv() socket requests. This creates a :class:`Timeout`\n object that sets the individual timeouts to the ``timeout`` value\n passed to this function.\n\n :param timeout: The legacy timeout value.\n :type timeout: integer, float, sentinel default object, or None\n :return: Timeout object\n :rtype: :class:`Timeout`\n """\n return Timeout(read=timeout, connect=timeout)\n\n def clone(self):\n """Create a copy of the timeout object\n\n Timeout properties are stored per-pool but each request needs a fresh\n Timeout object to ensure each one has its own start/stop configured.\n\n :return: a copy of the timeout object\n :rtype: :class:`Timeout`\n """\n # We can't use copy.deepcopy because that will also create a new object\n # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n # detect the user default.\n return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n def start_connect(self):\n """Start the timeout clock, used during a connect() attempt\n\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to start a timer that has been started already.\n """\n if self._start_connect is not None:\n raise TimeoutStateError("Timeout timer has already been started.")\n self._start_connect = current_time()\n return self._start_connect\n\n def get_connect_duration(self):\n """Gets the time elapsed since the call to :meth:`start_connect`.\n\n :return: Elapsed time in seconds.\n :rtype: float\n :raises urllib3.exceptions.TimeoutStateError: if you attempt\n to get duration for a timer that hasn't been started.\n """\n if self._start_connect is None:\n raise TimeoutStateError(\n "Can't get connect duration for timer that has not started."\n )\n return current_time() - self._start_connect\n\n @property\n def connect_timeout(self):\n """Get the value to use when setting a connection timeout.\n\n This will be a positive float or integer, the value None\n (never timeout), or the default system timeout.\n\n :return: Connect timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n """\n if self.total is None:\n return self._connect\n\n if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:\n return self.total\n\n return min(self._connect, self.total)\n\n @property\n def read_timeout(self):\n """Get the value for the read timeout.\n\n This assumes some time has elapsed in the connection timeout and\n computes the read timeout appropriately.\n\n If self.total is set, the read timeout is dependent on the amount of\n time taken by the connect timeout. If the connection time has not been\n established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n raised.\n\n :return: Value to use for the read timeout.\n :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n has not yet been called on this object.\n """\n if (\n self.total is not None\n and self.total is not self.DEFAULT_TIMEOUT\n and self._read is not None\n and self._read is not self.DEFAULT_TIMEOUT\n ):\n # In case the connect timeout has not yet been established.\n if self._start_connect is None:\n return self._read\n return max(0, min(self.total - self.get_connect_duration(), self._read))\n elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:\n return max(0, self.total - self.get_connect_duration())\n else:\n return self._read\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\timeout.py | timeout.py | Python | 10,168 | 0.95 | 0.166052 | 0.052133 | awesome-app | 170 | 2024-09-22T16:41:28.554858 | Apache-2.0 | false | 888565383a82fcedaf9d2473b8911660 |
from __future__ import absolute_import\n\nimport re\nfrom collections import namedtuple\n\nfrom ..exceptions import LocationParseError\nfrom ..packages import six\n\nurl_attrs = ["scheme", "auth", "host", "port", "path", "query", "fragment"]\n\n# We only want to normalize urls with an HTTP(S) scheme.\n# urllib3 infers URLs without a scheme (None) to be http.\nNORMALIZABLE_SCHEMES = ("http", "https", None)\n\n# Almost all of these patterns were derived from the\n# 'rfc3986' module: https://github.com/python-hyper/rfc3986\nPERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}")\nSCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)")\nURI_RE = re.compile(\n r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?"\n r"(?://([^\\/?#]*))?"\n r"([^?#]*)"\n r"(?:\?([^#]*))?"\n r"(?:#(.*))?$",\n re.UNICODE | re.DOTALL,\n)\n\nIPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}"\nHEX_PAT = "[0-9A-Fa-f]{1,4}"\nLS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=HEX_PAT, ipv4=IPV4_PAT)\n_subs = {"hex": HEX_PAT, "ls32": LS32_PAT}\n_variations = [\n # 6( h16 ":" ) ls32\n "(?:%(hex)s:){6}%(ls32)s",\n # "::" 5( h16 ":" ) ls32\n "::(?:%(hex)s:){5}%(ls32)s",\n # [ h16 ] "::" 4( h16 ":" ) ls32\n "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s",\n # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32\n "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s",\n # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32\n "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s",\n # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32\n "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s",\n # [ *4( h16 ":" ) h16 ] "::" ls32\n "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s",\n # [ *5( h16 ":" ) h16 ] "::" h16\n "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s",\n # [ *6( h16 ":" ) h16 ] "::"\n "(?:(?:%(hex)s:){0,6}%(hex)s)?::",\n]\n\nUNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~"\nIPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")"\nZONE_ID_PAT = "(?:%25|%)(?:[" + UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+"\nIPV6_ADDRZ_PAT = r"\[" + IPV6_PAT + r"(?:" + ZONE_ID_PAT + r")?\]"\nREG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*"\nTARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$")\n\nIPV4_RE = re.compile("^" + IPV4_PAT + "$")\nIPV6_RE = re.compile("^" + IPV6_PAT + "$")\nIPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT + "$")\nBRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$")\nZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$")\n\n_HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % (\n REG_NAME_PAT,\n IPV4_PAT,\n IPV6_ADDRZ_PAT,\n)\n_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)\n\nUNRESERVED_CHARS = set(\n "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~"\n)\nSUB_DELIM_CHARS = set("!$&'()*+,;=")\nUSERINFO_CHARS = UNRESERVED_CHARS | SUB_DELIM_CHARS | {":"}\nPATH_CHARS = USERINFO_CHARS | {"@", "/"}\nQUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {"?"}\n\n\nclass Url(namedtuple("Url", url_attrs)):\n """\n Data structure for representing an HTTP URL. Used as a return value for\n :func:`parse_url`. Both the scheme and host are normalized as they are\n both case-insensitive according to RFC 3986.\n """\n\n __slots__ = ()\n\n def __new__(\n cls,\n scheme=None,\n auth=None,\n host=None,\n port=None,\n path=None,\n query=None,\n fragment=None,\n ):\n if path and not path.startswith("/"):\n path = "/" + path\n if scheme is not None:\n scheme = scheme.lower()\n return super(Url, cls).__new__(\n cls, scheme, auth, host, port, path, query, fragment\n )\n\n @property\n def hostname(self):\n """For backwards-compatibility with urlparse. We're nice like that."""\n return self.host\n\n @property\n def request_uri(self):\n """Absolute path including the query string."""\n uri = self.path or "/"\n\n if self.query is not None:\n uri += "?" + self.query\n\n return uri\n\n @property\n def netloc(self):\n """Network location including host and port"""\n if self.port:\n return "%s:%d" % (self.host, self.port)\n return self.host\n\n @property\n def url(self):\n """\n Convert self into a url\n\n This function should more or less round-trip with :func:`.parse_url`. The\n returned url may not be exactly the same as the url inputted to\n :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n with a blank port will have : removed).\n\n Example: ::\n\n >>> U = parse_url('http://google.com/mail/')\n >>> U.url\n 'http://google.com/mail/'\n >>> Url('http', 'username:password', 'host.com', 80,\n ... '/path', 'query', 'fragment').url\n 'http://username:password@host.com:80/path?query#fragment'\n """\n scheme, auth, host, port, path, query, fragment = self\n url = u""\n\n # We use "is not None" we want things to happen with empty strings (or 0 port)\n if scheme is not None:\n url += scheme + u"://"\n if auth is not None:\n url += auth + u"@"\n if host is not None:\n url += host\n if port is not None:\n url += u":" + str(port)\n if path is not None:\n url += path\n if query is not None:\n url += u"?" + query\n if fragment is not None:\n url += u"#" + fragment\n\n return url\n\n def __str__(self):\n return self.url\n\n\ndef split_first(s, delims):\n """\n .. deprecated:: 1.25\n\n Given a string and an iterable of delimiters, split on the first found\n delimiter. Return two split parts and the matched delimiter.\n\n If not found, then the first part is the full input string.\n\n Example::\n\n >>> split_first('foo/bar?baz', '?/=')\n ('foo', 'bar?baz', '/')\n >>> split_first('foo/bar?baz', '123')\n ('foo/bar?baz', '', None)\n\n Scales linearly with number of delims. Not ideal for large number of delims.\n """\n min_idx = None\n min_delim = None\n for d in delims:\n idx = s.find(d)\n if idx < 0:\n continue\n\n if min_idx is None or idx < min_idx:\n min_idx = idx\n min_delim = d\n\n if min_idx is None or min_idx < 0:\n return s, "", None\n\n return s[:min_idx], s[min_idx + 1 :], min_delim\n\n\ndef _encode_invalid_chars(component, allowed_chars, encoding="utf-8"):\n """Percent-encodes a URI component without reapplying\n onto an already percent-encoded component.\n """\n if component is None:\n return component\n\n component = six.ensure_text(component)\n\n # Normalize existing percent-encoded bytes.\n # Try to see if the component we're encoding is already percent-encoded\n # so we can skip all '%' characters but still encode all others.\n component, percent_encodings = PERCENT_RE.subn(\n lambda match: match.group(0).upper(), component\n )\n\n uri_bytes = component.encode("utf-8", "surrogatepass")\n is_percent_encoded = percent_encodings == uri_bytes.count(b"%")\n encoded_component = bytearray()\n\n for i in range(0, len(uri_bytes)):\n # Will return a single character bytestring on both Python 2 & 3\n byte = uri_bytes[i : i + 1]\n byte_ord = ord(byte)\n if (is_percent_encoded and byte == b"%") or (\n byte_ord < 128 and byte.decode() in allowed_chars\n ):\n encoded_component += byte\n continue\n encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))\n\n return encoded_component.decode(encoding)\n\n\ndef _remove_path_dot_segments(path):\n # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code\n segments = path.split("/") # Turn the path into a list of segments\n output = [] # Initialize the variable to use to store output\n\n for segment in segments:\n # '.' is the current directory, so ignore it, it is superfluous\n if segment == ".":\n continue\n # Anything other than '..', should be appended to the output\n elif segment != "..":\n output.append(segment)\n # In this case segment == '..', if we can, we should pop the last\n # element\n elif output:\n output.pop()\n\n # If the path starts with '/' and the output is empty or the first string\n # is non-empty\n if path.startswith("/") and (not output or output[0]):\n output.insert(0, "")\n\n # If the path starts with '/.' or '/..' ensure we add one more empty\n # string to add a trailing '/'\n if path.endswith(("/.", "/..")):\n output.append("")\n\n return "/".join(output)\n\n\ndef _normalize_host(host, scheme):\n if host:\n if isinstance(host, six.binary_type):\n host = six.ensure_str(host)\n\n if scheme in NORMALIZABLE_SCHEMES:\n is_ipv6 = IPV6_ADDRZ_RE.match(host)\n if is_ipv6:\n # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as\n # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID\n # separator as necessary to return a valid RFC 4007 scoped IP.\n match = ZONE_ID_RE.search(host)\n if match:\n start, end = match.span(1)\n zone_id = host[start:end]\n\n if zone_id.startswith("%25") and zone_id != "%25":\n zone_id = zone_id[3:]\n else:\n zone_id = zone_id[1:]\n zone_id = "%" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS)\n return host[:start].lower() + zone_id + host[end:]\n else:\n return host.lower()\n elif not IPV4_RE.match(host):\n return six.ensure_str(\n b".".join([_idna_encode(label) for label in host.split(".")])\n )\n return host\n\n\ndef _idna_encode(name):\n if name and any(ord(x) >= 128 for x in name):\n try:\n from pip._vendor import idna\n except ImportError:\n six.raise_from(\n LocationParseError("Unable to parse URL without the 'idna' module"),\n None,\n )\n try:\n return idna.encode(name.lower(), strict=True, std3_rules=True)\n except idna.IDNAError:\n six.raise_from(\n LocationParseError(u"Name '%s' is not a valid IDNA label" % name), None\n )\n return name.lower().encode("ascii")\n\n\ndef _encode_target(target):\n """Percent-encodes a request target so that there are no invalid characters"""\n path, query = TARGET_RE.match(target).groups()\n target = _encode_invalid_chars(path, PATH_CHARS)\n query = _encode_invalid_chars(query, QUERY_CHARS)\n if query is not None:\n target += "?" + query\n return target\n\n\ndef parse_url(url):\n """\n Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n performed to parse incomplete urls. Fields not provided will be None.\n This parser is RFC 3986 and RFC 6874 compliant.\n\n The parser logic and helper functions are based heavily on\n work done in the ``rfc3986`` module.\n\n :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n Partly backwards-compatible with :mod:`urlparse`.\n\n Example::\n\n >>> parse_url('http://google.com/mail/')\n Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n >>> parse_url('google.com:80')\n Url(scheme=None, host='google.com', port=80, path=None, ...)\n >>> parse_url('/foo?bar')\n Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n """\n if not url:\n # Empty\n return Url()\n\n source_url = url\n if not SCHEME_RE.search(url):\n url = "//" + url\n\n try:\n scheme, authority, path, query, fragment = URI_RE.match(url).groups()\n normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES\n\n if scheme:\n scheme = scheme.lower()\n\n if authority:\n auth, _, host_port = authority.rpartition("@")\n auth = auth or None\n host, port = _HOST_PORT_RE.match(host_port).groups()\n if auth and normalize_uri:\n auth = _encode_invalid_chars(auth, USERINFO_CHARS)\n if port == "":\n port = None\n else:\n auth, host, port = None, None, None\n\n if port is not None:\n port = int(port)\n if not (0 <= port <= 65535):\n raise LocationParseError(url)\n\n host = _normalize_host(host, scheme)\n\n if normalize_uri and path:\n path = _remove_path_dot_segments(path)\n path = _encode_invalid_chars(path, PATH_CHARS)\n if normalize_uri and query:\n query = _encode_invalid_chars(query, QUERY_CHARS)\n if normalize_uri and fragment:\n fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)\n\n except (ValueError, AttributeError):\n return six.raise_from(LocationParseError(source_url), None)\n\n # For the sake of backwards compatibility we put empty\n # string values for path if there are any defined values\n # beyond the path in the URL.\n # TODO: Remove this when we break backwards compatibility.\n if not path:\n if query is not None or fragment is not None:\n path = ""\n else:\n path = None\n\n # Ensure that each part of the URL is a `str` for\n # backwards compatibility.\n if isinstance(url, six.text_type):\n ensure_func = six.ensure_text\n else:\n ensure_func = six.ensure_str\n\n def ensure_type(x):\n return x if x is None else ensure_func(x)\n\n return Url(\n scheme=ensure_type(scheme),\n auth=ensure_type(auth),\n host=ensure_type(host),\n port=port,\n path=ensure_type(path),\n query=ensure_type(query),\n fragment=ensure_type(fragment),\n )\n\n\ndef get_host(url):\n """\n Deprecated. Use :func:`parse_url` instead.\n """\n p = parse_url(url)\n return p.scheme or "http", p.hostname, p.port\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\url.py | url.py | Python | 14,296 | 0.95 | 0.181609 | 0.103641 | vue-tools | 236 | 2024-03-28T20:35:50.802215 | BSD-3-Clause | false | 3b0f140e69e68b5aa6006e4c7621e365 |
import errno\nimport select\nimport sys\nfrom functools import partial\n\ntry:\n from time import monotonic\nexcept ImportError:\n from time import time as monotonic\n\n__all__ = ["NoWayToWaitForSocketError", "wait_for_read", "wait_for_write"]\n\n\nclass NoWayToWaitForSocketError(Exception):\n pass\n\n\n# How should we wait on sockets?\n#\n# There are two types of APIs you can use for waiting on sockets: the fancy\n# modern stateful APIs like epoll/kqueue, and the older stateless APIs like\n# select/poll. The stateful APIs are more efficient when you have a lots of\n# sockets to keep track of, because you can set them up once and then use them\n# lots of times. But we only ever want to wait on a single socket at a time\n# and don't want to keep track of state, so the stateless APIs are actually\n# more efficient. So we want to use select() or poll().\n#\n# Now, how do we choose between select() and poll()? On traditional Unixes,\n# select() has a strange calling convention that makes it slow, or fail\n# altogether, for high-numbered file descriptors. The point of poll() is to fix\n# that, so on Unixes, we prefer poll().\n#\n# On Windows, there is no poll() (or at least Python doesn't provide a wrapper\n# for it), but that's OK, because on Windows, select() doesn't have this\n# strange calling convention; plain select() works fine.\n#\n# So: on Windows we use select(), and everywhere else we use poll(). We also\n# fall back to select() in case poll() is somehow broken or missing.\n\nif sys.version_info >= (3, 5):\n # Modern Python, that retries syscalls by default\n def _retry_on_intr(fn, timeout):\n return fn(timeout)\n\nelse:\n # Old and broken Pythons.\n def _retry_on_intr(fn, timeout):\n if timeout is None:\n deadline = float("inf")\n else:\n deadline = monotonic() + timeout\n\n while True:\n try:\n return fn(timeout)\n # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7\n except (OSError, select.error) as e:\n # 'e.args[0]' incantation works for both OSError and select.error\n if e.args[0] != errno.EINTR:\n raise\n else:\n timeout = deadline - monotonic()\n if timeout < 0:\n timeout = 0\n if timeout == float("inf"):\n timeout = None\n continue\n\n\ndef select_wait_for_socket(sock, read=False, write=False, timeout=None):\n if not read and not write:\n raise RuntimeError("must specify at least one of read=True, write=True")\n rcheck = []\n wcheck = []\n if read:\n rcheck.append(sock)\n if write:\n wcheck.append(sock)\n # When doing a non-blocking connect, most systems signal success by\n # marking the socket writable. Windows, though, signals success by marked\n # it as "exceptional". We paper over the difference by checking the write\n # sockets for both conditions. (The stdlib selectors module does the same\n # thing.)\n fn = partial(select.select, rcheck, wcheck, wcheck)\n rready, wready, xready = _retry_on_intr(fn, timeout)\n return bool(rready or wready or xready)\n\n\ndef poll_wait_for_socket(sock, read=False, write=False, timeout=None):\n if not read and not write:\n raise RuntimeError("must specify at least one of read=True, write=True")\n mask = 0\n if read:\n mask |= select.POLLIN\n if write:\n mask |= select.POLLOUT\n poll_obj = select.poll()\n poll_obj.register(sock, mask)\n\n # For some reason, poll() takes timeout in milliseconds\n def do_poll(t):\n if t is not None:\n t *= 1000\n return poll_obj.poll(t)\n\n return bool(_retry_on_intr(do_poll, timeout))\n\n\ndef null_wait_for_socket(*args, **kwargs):\n raise NoWayToWaitForSocketError("no select-equivalent available")\n\n\ndef _have_working_poll():\n # Apparently some systems have a select.poll that fails as soon as you try\n # to use it, either due to strange configuration or broken monkeypatching\n # from libraries like eventlet/greenlet.\n try:\n poll_obj = select.poll()\n _retry_on_intr(poll_obj.poll, 0)\n except (AttributeError, OSError):\n return False\n else:\n return True\n\n\ndef wait_for_socket(*args, **kwargs):\n # We delay choosing which implementation to use until the first time we're\n # called. We could do it at import time, but then we might make the wrong\n # decision if someone goes wild with monkeypatching select.poll after\n # we're imported.\n global wait_for_socket\n if _have_working_poll():\n wait_for_socket = poll_wait_for_socket\n elif hasattr(select, "select"):\n wait_for_socket = select_wait_for_socket\n else: # Platform-specific: Appengine.\n wait_for_socket = null_wait_for_socket\n return wait_for_socket(*args, **kwargs)\n\n\ndef wait_for_read(sock, timeout=None):\n """Waits for reading to be available on a given socket.\n Returns True if the socket is readable, or False if the timeout expired.\n """\n return wait_for_socket(sock, read=True, timeout=timeout)\n\n\ndef wait_for_write(sock, timeout=None):\n """Waits for writing to be available on a given socket.\n Returns True if the socket is readable, or False if the timeout expired.\n """\n return wait_for_socket(sock, write=True, timeout=timeout)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\wait.py | wait.py | Python | 5,403 | 0.95 | 0.282895 | 0.299213 | node-utils | 520 | 2025-03-08T16:06:25.532115 | BSD-3-Clause | false | cf3f909036467c64f0829344e4c49904 |
from __future__ import absolute_import\n\n# For backwards compatibility, provide imports that used to be here.\nfrom .connection import is_connection_dropped\nfrom .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers\nfrom .response import is_fp_closed\nfrom .retry import Retry\nfrom .ssl_ import (\n ALPN_PROTOCOLS,\n HAS_SNI,\n IS_PYOPENSSL,\n IS_SECURETRANSPORT,\n PROTOCOL_TLS,\n SSLContext,\n assert_fingerprint,\n resolve_cert_reqs,\n resolve_ssl_version,\n ssl_wrap_socket,\n)\nfrom .timeout import Timeout, current_time\nfrom .url import Url, get_host, parse_url, split_first\nfrom .wait import wait_for_read, wait_for_write\n\n__all__ = (\n "HAS_SNI",\n "IS_PYOPENSSL",\n "IS_SECURETRANSPORT",\n "SSLContext",\n "PROTOCOL_TLS",\n "ALPN_PROTOCOLS",\n "Retry",\n "Timeout",\n "Url",\n "assert_fingerprint",\n "current_time",\n "is_connection_dropped",\n "is_fp_closed",\n "get_host",\n "parse_url",\n "make_headers",\n "resolve_cert_reqs",\n "resolve_ssl_version",\n "split_first",\n "ssl_wrap_socket",\n "wait_for_read",\n "wait_for_write",\n "SKIP_HEADER",\n "SKIPPABLE_HEADERS",\n)\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__init__.py | __init__.py | Python | 1,155 | 0.95 | 0 | 0.021277 | python-kit | 391 | 2023-10-06T18:14:01.947551 | MIT | false | f951fb1888473ee32752499ce9b841a5 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\connection.cpython-313.pyc | connection.cpython-313.pyc | Other | 4,781 | 0.95 | 0.133333 | 0.037037 | vue-tools | 933 | 2024-07-21T03:00:09.895293 | MIT | false | 86ca7579bc7a9795cd0290f141907f92 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\proxy.cpython-313.pyc | proxy.cpython-313.pyc | Other | 1,579 | 0.95 | 0.133333 | 0 | vue-tools | 437 | 2025-03-24T20:51:49.943817 | BSD-3-Clause | false | 83173baaf29194b226f0cdf7c21f9ebd |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\queue.cpython-313.pyc | queue.cpython-313.pyc | Other | 1,428 | 0.7 | 0 | 0 | awesome-app | 96 | 2023-11-20T03:35:57.283550 | MIT | false | 77d1cc46718e0d77387f655b7da06df3 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\request.cpython-313.pyc | request.cpython-313.pyc | Other | 4,148 | 0.95 | 0.075269 | 0 | react-lib | 683 | 2025-04-04T11:01:55.410979 | GPL-3.0 | false | fe436cfa72aa22cd654cb0c378ca780a |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\response.cpython-313.pyc | response.cpython-313.pyc | Other | 3,047 | 0.95 | 0.017544 | 0 | python-kit | 502 | 2024-05-14T07:18:19.503197 | BSD-3-Clause | false | c1ec59e0e1f34a609eff8c8d019602f7 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\retry.cpython-313.pyc | retry.cpython-313.pyc | Other | 21,554 | 0.95 | 0.064615 | 0 | node-utils | 884 | 2024-03-12T02:28:26.682374 | MIT | false | bd7a2a7ce7c861b3ad732f4ec35f0f1c |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\ssltransport.cpython-313.pyc | ssltransport.cpython-313.pyc | Other | 10,937 | 0.95 | 0.043011 | 0.012048 | react-lib | 746 | 2025-01-27T13:32:41.885304 | GPL-3.0 | false | 9d690ee83e51efa815792efa44fc4707 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\ssl_.cpython-313.pyc | ssl_.cpython-313.pyc | Other | 15,503 | 0.95 | 0.068293 | 0 | node-utils | 626 | 2024-11-19T22:24:05.152053 | MIT | false | 11e5526591aefa6f8d41754e8e5f3a30 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\ssl_match_hostname.cpython-313.pyc | ssl_match_hostname.cpython-313.pyc | Other | 5,222 | 0.95 | 0.047619 | 0.012987 | awesome-app | 166 | 2023-10-01T12:18:54.991353 | BSD-3-Clause | false | bee90556b0610db8d6263fbbfdb112ce |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\timeout.cpython-313.pyc | timeout.cpython-313.pyc | Other | 10,682 | 0.95 | 0.095238 | 0.006711 | awesome-app | 865 | 2024-08-18T14:10:02.966861 | GPL-3.0 | false | 4d350540b84526a013fabb90b4d1d4a4 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\url.cpython-313.pyc | url.cpython-313.pyc | Other | 15,939 | 0.95 | 0.029268 | 0.021858 | react-lib | 848 | 2023-11-17T07:49:14.555924 | GPL-3.0 | false | 3afaa0fc553c1570d142097e3dbe4aaf |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\wait.cpython-313.pyc | wait.cpython-313.pyc | Other | 4,581 | 0.8 | 0.139535 | 0.027778 | react-lib | 843 | 2024-06-08T19:30:29.419128 | BSD-3-Clause | false | 5cb78aae9ac7e6760d550911a0e38caf |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\util\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 1,150 | 0.95 | 0 | 0 | react-lib | 841 | 2025-05-19T06:38:50.894628 | GPL-3.0 | false | fb69da4e3a9674a192ef20b3b3eff6c6 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\connection.cpython-313.pyc | connection.cpython-313.pyc | Other | 20,731 | 0.95 | 0.05102 | 0 | awesome-app | 210 | 2025-03-14T21:37:42.032269 | BSD-3-Clause | false | 7a6c8a0f8da4b38eae1ee848fdcbe7a0 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\connectionpool.cpython-313.pyc | connectionpool.cpython-313.pyc | Other | 36,063 | 0.95 | 0.12474 | 0 | awesome-app | 169 | 2025-05-18T01:54:54.714462 | BSD-3-Clause | false | f4e9aec3aaad65cbc7f993d0943d96fa |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\exceptions.cpython-313.pyc | exceptions.cpython-313.pyc | Other | 14,183 | 0.95 | 0.117647 | 0 | node-utils | 558 | 2024-03-31T08:06:26.108845 | BSD-3-Clause | false | c8f69fcd0bfb9814815d41706228d5e7 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\fields.cpython-313.pyc | fields.cpython-313.pyc | Other | 10,190 | 0.95 | 0.086093 | 0 | awesome-app | 949 | 2024-05-20T12:51:15.562053 | BSD-3-Clause | false | 0e0247d1bd5203bd57fc2e2c10c83c6a |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\filepost.cpython-313.pyc | filepost.cpython-313.pyc | Other | 3,999 | 0.95 | 0.111111 | 0 | node-utils | 866 | 2024-01-01T04:44:39.460055 | Apache-2.0 | false | 30c1f38dd773f11a23e5144e72b9a3e9 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\poolmanager.cpython-313.pyc | poolmanager.cpython-313.pyc | Other | 19,989 | 0.95 | 0.103586 | 0.004484 | vue-tools | 770 | 2024-12-31T11:29:44.871621 | BSD-3-Clause | false | 580427cf63671b3a2db1a8d66ad23dec |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\request.cpython-313.pyc | request.cpython-313.pyc | Other | 6,971 | 0.95 | 0.118182 | 0 | awesome-app | 732 | 2023-12-24T03:36:36.321357 | BSD-3-Clause | false | a155281cd6f2cf01285ec4ece5b69498 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\response.cpython-313.pyc | response.cpython-313.pyc | Other | 34,279 | 0.95 | 0.075075 | 0.019802 | awesome-app | 581 | 2023-08-05T18:56:12.885773 | MIT | false | b7858c7c4acbe289d1f90181630ea3ee |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\_collections.cpython-313.pyc | _collections.cpython-313.pyc | Other | 16,436 | 0.95 | 0.053476 | 0.011429 | awesome-app | 405 | 2025-05-12T03:32:20.461413 | BSD-3-Clause | false | f8fbf5a183adbbca605b0d6fd34f2618 |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\_version.cpython-313.pyc | _version.cpython-313.pyc | Other | 222 | 0.7 | 0 | 0 | awesome-app | 365 | 2024-09-15T07:28:44.522545 | Apache-2.0 | false | a3d6f0b210a02e875c6fc65d97c2d5bd |
\n\n | .venv\Lib\site-packages\pip\_vendor\urllib3\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 3,357 | 0.95 | 0.075 | 0 | python-kit | 524 | 2024-07-16T22:57:03.237707 | MIT | false | c200ae3abf6d55b4793cf9fc3d6e4322 |
\n\n | .venv\Lib\site-packages\pip\_vendor\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 4,598 | 0.95 | 0.007874 | 0.008065 | python-kit | 281 | 2024-04-15T23:43:27.827430 | GPL-3.0 | false | 77679ac802d2deb328cc31a81acb2684 |
\n\n | .venv\Lib\site-packages\pip\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 685 | 0.8 | 0.142857 | 0 | react-lib | 620 | 2024-04-16T09:19:26.426950 | Apache-2.0 | false | 30f38da13af5e7f306d1ac551d1bfeb5 |
\n\n | .venv\Lib\site-packages\pip\__pycache__\__main__.cpython-313.pyc | __main__.cpython-313.pyc | Other | 847 | 0.8 | 0 | 0 | node-utils | 714 | 2025-04-06T01:18:43.520610 | Apache-2.0 | false | 0ec67eefe9d7f9b17a4bd1b2c89047f7 |
\n\n | .venv\Lib\site-packages\pip\__pycache__\__pip-runner__.cpython-313.pyc | __pip-runner__.cpython-313.pyc | Other | 2,284 | 0.95 | 0 | 0 | python-kit | 516 | 2024-01-16T21:23:00.107149 | GPL-3.0 | false | 95cb14cf36353857913710f69b2d411f |
[console_scripts]\npip = pip._internal.cli.main:main\npip3 = pip._internal.cli.main:main\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\entry_points.txt | entry_points.txt | Other | 87 | 0.5 | 0 | 0 | vue-tools | 280 | 2024-01-30T14:23:59.732896 | GPL-3.0 | false | b466ddb597da043c0740b1c7538bdde8 |
pip\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\INSTALLER | INSTALLER | Other | 4 | 0.5 | 0 | 0 | vue-tools | 311 | 2024-02-10T09:20:03.896324 | BSD-3-Clause | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
Metadata-Version: 2.4\nName: pip\nVersion: 25.1.1\nSummary: The PyPA recommended tool for installing Python packages.\nAuthor-email: The pip developers <distutils-sig@python.org>\nLicense: MIT\nProject-URL: Homepage, https://pip.pypa.io/\nProject-URL: Documentation, https://pip.pypa.io\nProject-URL: Source, https://github.com/pypa/pip\nProject-URL: Changelog, https://pip.pypa.io/en/stable/news/\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Topic :: Software Development :: Build Tools\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nClassifier: Programming Language :: Python :: Implementation :: CPython\nClassifier: Programming Language :: Python :: Implementation :: PyPy\nRequires-Python: >=3.9\nDescription-Content-Type: text/x-rst\nLicense-File: LICENSE.txt\nLicense-File: AUTHORS.txt\nDynamic: license-file\n\npip - The Python Package Installer\n==================================\n\n.. |pypi-version| image:: https://img.shields.io/pypi/v/pip.svg\n :target: https://pypi.org/project/pip/\n :alt: PyPI\n\n.. |python-versions| image:: https://img.shields.io/pypi/pyversions/pip\n :target: https://pypi.org/project/pip\n :alt: PyPI - Python Version\n\n.. |docs-badge| image:: https://readthedocs.org/projects/pip/badge/?version=latest\n :target: https://pip.pypa.io/en/latest\n :alt: Documentation\n\n|pypi-version| |python-versions| |docs-badge|\n\npip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.\n\nPlease take a look at our documentation for how to install and use pip:\n\n* `Installation`_\n* `Usage`_\n\nWe release updates regularly, with a new version every 3 months. Find more details in our documentation:\n\n* `Release notes`_\n* `Release process`_\n\nIf you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:\n\n* `Issue tracking`_\n* `Discourse channel`_\n* `User IRC`_\n\nIf you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:\n\n* `GitHub page`_\n* `Development documentation`_\n* `Development IRC`_\n\nCode of Conduct\n---------------\n\nEveryone interacting in the pip project's codebases, issue trackers, chat\nrooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.\n\n.. _package installer: https://packaging.python.org/guides/tool-recommendations/\n.. _Python Package Index: https://pypi.org\n.. _Installation: https://pip.pypa.io/en/stable/installation/\n.. _Usage: https://pip.pypa.io/en/stable/\n.. _Release notes: https://pip.pypa.io/en/stable/news.html\n.. _Release process: https://pip.pypa.io/en/latest/development/release-process/\n.. _GitHub page: https://github.com/pypa/pip\n.. _Development documentation: https://pip.pypa.io/en/latest/development\n.. _Issue tracking: https://github.com/pypa/pip/issues\n.. _Discourse channel: https://discuss.python.org/c/packaging\n.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa\n.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev\n.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\METADATA | METADATA | Other | 3,649 | 0.8 | 0.033333 | 0.136986 | react-lib | 571 | 2025-06-14T05:49:46.483384 | Apache-2.0 | false | 5a316017b567748d68967d7f6fa8a29a |
../../Scripts/pip.exe,sha256=P3h-mdtzo3lnWfZ-jQaMtoXapbXlJYWim2oHmnl4LsM,108423\n../../Scripts/pip3.13.exe,sha256=P3h-mdtzo3lnWfZ-jQaMtoXapbXlJYWim2oHmnl4LsM,108423\n../../Scripts/pip3.exe,sha256=P3h-mdtzo3lnWfZ-jQaMtoXapbXlJYWim2oHmnl4LsM,108423\npip-25.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\npip-25.1.1.dist-info/METADATA,sha256=QFxj1tLpk8hGWrgQLRhJYUpwo_1FqBr43OT0srIZcmU,3649\npip-25.1.1.dist-info/RECORD,,\npip-25.1.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip-25.1.1.dist-info/WHEEL,sha256=pxyMxgL8-pra_rKaQ4drOZAegBVuX-G_4nRHjjgWbmo,91\npip-25.1.1.dist-info/entry_points.txt,sha256=eeIjuzfnfR2PrhbjnbzFU6MnSS70kZLxwaHHq6M-bD0,87\npip-25.1.1.dist-info/licenses/AUTHORS.txt,sha256=YzDFTYpeYnwpmODDFTgyKZNKWcfdO10L5Ex_U6kJLRc,11223\npip-25.1.1.dist-info/licenses/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093\npip-25.1.1.dist-info/top_level.txt,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\npip/__init__.py,sha256=zQQ7Na8YWi0IN86IUKEzDAJtyVpXdJXYDkQ536caUiQ,357\npip/__main__.py,sha256=WzbhHXTbSE6gBY19mNN9m4s5o_365LOvTYSgqgbdBhE,854\npip/__pip-runner__.py,sha256=JOoEZTwrtv7jRaXBkgSQKAE04yNyfFmGHxqpHiGHvL0,1450\npip/__pycache__/__init__.cpython-313.pyc,,\npip/__pycache__/__main__.cpython-313.pyc,,\npip/__pycache__/__pip-runner__.cpython-313.pyc,,\npip/_internal/__init__.py,sha256=MfcoOluDZ8QMCFYal04IqOJ9q6m2V7a0aOsnI-WOxUo,513\npip/_internal/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/__pycache__/build_env.cpython-313.pyc,,\npip/_internal/__pycache__/cache.cpython-313.pyc,,\npip/_internal/__pycache__/configuration.cpython-313.pyc,,\npip/_internal/__pycache__/exceptions.cpython-313.pyc,,\npip/_internal/__pycache__/main.cpython-313.pyc,,\npip/_internal/__pycache__/pyproject.cpython-313.pyc,,\npip/_internal/__pycache__/self_outdated_check.cpython-313.pyc,,\npip/_internal/__pycache__/wheel_builder.cpython-313.pyc,,\npip/_internal/build_env.py,sha256=60_espLI9X3C2db3Ww2gIcyjNk2cAPNcc5gsVO4DOqg,10924\npip/_internal/cache.py,sha256=SjhJK1C6NbonrU4AyYXKTOH0CGOk5cJrYt60mRANnPM,10368\npip/_internal/cli/__init__.py,sha256=Iqg_tKA771XuMO1P4t_sDHnSKPzkUb9D0DqunAmw_ko,131\npip/_internal/cli/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/cli/__pycache__/autocompletion.cpython-313.pyc,,\npip/_internal/cli/__pycache__/base_command.cpython-313.pyc,,\npip/_internal/cli/__pycache__/cmdoptions.cpython-313.pyc,,\npip/_internal/cli/__pycache__/command_context.cpython-313.pyc,,\npip/_internal/cli/__pycache__/index_command.cpython-313.pyc,,\npip/_internal/cli/__pycache__/main.cpython-313.pyc,,\npip/_internal/cli/__pycache__/main_parser.cpython-313.pyc,,\npip/_internal/cli/__pycache__/parser.cpython-313.pyc,,\npip/_internal/cli/__pycache__/progress_bars.cpython-313.pyc,,\npip/_internal/cli/__pycache__/req_command.cpython-313.pyc,,\npip/_internal/cli/__pycache__/spinners.cpython-313.pyc,,\npip/_internal/cli/__pycache__/status_codes.cpython-313.pyc,,\npip/_internal/cli/autocompletion.py,sha256=fs0Wy16Ga5tX1IZKvww5BDi7i5zyzfCPvu7cgXlgXys,6864\npip/_internal/cli/base_command.py,sha256=0A8YuJVJh2YyXU8pdW0eidLg1eklCW5cU01mpI-FAxA,8351\npip/_internal/cli/cmdoptions.py,sha256=-_V4gjMa0c3U8-vXKAyb5xVViJNzFAxBI3Zx_6Ds5-g,31909\npip/_internal/cli/command_context.py,sha256=RHgIPwtObh5KhMrd3YZTkl8zbVG-6Okml7YbFX4Ehg0,774\npip/_internal/cli/index_command.py,sha256=kplkusUgCZy75jNCo-etaDmSG8UvqcR2W50ALDdm6dk,5720\npip/_internal/cli/main.py,sha256=1bXC7uL3tdb_EZlGVKs6_TgzC9tlKU7zhAZsbZA-IzY,2816\npip/_internal/cli/main_parser.py,sha256=chZqNmCuO_JYt8ynBCumh4crURaRoXBZ0RxoSYQIwCw,4337\npip/_internal/cli/parser.py,sha256=VCMtduzECUV87KaHNu-xJ-wLNL82yT3x16V4XBxOAqI,10825\npip/_internal/cli/progress_bars.py,sha256=r9BD4T2-egcInB1Uh9Jjw3EP9F3INy5kZhGwSePm9jo,4435\npip/_internal/cli/req_command.py,sha256=1yfssBvnUKNer8D7iT3OHqdJJNdCqRhwDqUFWgieppk,12934\npip/_internal/cli/spinners.py,sha256=hIJ83GerdFgFCdobIA23Jggetegl_uC4Sp586nzFbPE,5118\npip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116\npip/_internal/commands/__init__.py,sha256=3405KyFv4l0ruxeF69oosFanxNQcC_fHBGv7Rpt0PXg,4009\npip/_internal/commands/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/commands/__pycache__/cache.cpython-313.pyc,,\npip/_internal/commands/__pycache__/check.cpython-313.pyc,,\npip/_internal/commands/__pycache__/completion.cpython-313.pyc,,\npip/_internal/commands/__pycache__/configuration.cpython-313.pyc,,\npip/_internal/commands/__pycache__/debug.cpython-313.pyc,,\npip/_internal/commands/__pycache__/download.cpython-313.pyc,,\npip/_internal/commands/__pycache__/freeze.cpython-313.pyc,,\npip/_internal/commands/__pycache__/hash.cpython-313.pyc,,\npip/_internal/commands/__pycache__/help.cpython-313.pyc,,\npip/_internal/commands/__pycache__/index.cpython-313.pyc,,\npip/_internal/commands/__pycache__/inspect.cpython-313.pyc,,\npip/_internal/commands/__pycache__/install.cpython-313.pyc,,\npip/_internal/commands/__pycache__/list.cpython-313.pyc,,\npip/_internal/commands/__pycache__/lock.cpython-313.pyc,,\npip/_internal/commands/__pycache__/search.cpython-313.pyc,,\npip/_internal/commands/__pycache__/show.cpython-313.pyc,,\npip/_internal/commands/__pycache__/uninstall.cpython-313.pyc,,\npip/_internal/commands/__pycache__/wheel.cpython-313.pyc,,\npip/_internal/commands/cache.py,sha256=IOezTicHjGE5sWdBx2nwPVgbjuJHM3s-BZEkpZLemuY,8107\npip/_internal/commands/check.py,sha256=Hr_4eiMd9cgVDgEvjtIdw915NmL7ROIWW8enkr8slPQ,2268\npip/_internal/commands/completion.py,sha256=W9QFQTPLjy2tPACJ_y3g9EgB1pbsh7pvCUX8ocuIdPg,4554\npip/_internal/commands/configuration.py,sha256=n98enwp6y0b5G6fiRQjaZo43FlJKYve_daMhN-4BRNc,9766\npip/_internal/commands/debug.py,sha256=DNDRgE9YsKrbYzU0s3VKi8rHtKF4X13CJ_br_8PUXO0,6797\npip/_internal/commands/download.py,sha256=0qB0nys6ZEPsog451lDsjL5Bx7Z97t-B80oFZKhpzKM,5273\npip/_internal/commands/freeze.py,sha256=YW-aMmAzzOaBWWobo9g4DPKuWp0dTC32lWMqXzKFLzE,3144\npip/_internal/commands/hash.py,sha256=EVVOuvGtoPEdFi8SNnmdqlCQrhCxV-kJsdwtdcCnXGQ,1703\npip/_internal/commands/help.py,sha256=gcc6QDkcgHMOuAn5UxaZwAStsRBrnGSn_yxjS57JIoM,1132\npip/_internal/commands/index.py,sha256=8UucFVwx6FmM8cNbaPY8iI5kZdV3f6jhqDa-S8aGgpg,5068\npip/_internal/commands/inspect.py,sha256=PGrY9TRTRCM3y5Ml8Bdk8DEOXquWRfscr4DRo1LOTPc,3189\npip/_internal/commands/install.py,sha256=SRsiLpead7A8bLdxMqxTAJM3sUFHtgN9zgBT98UQz5E,29757\npip/_internal/commands/list.py,sha256=Rwtf8B0d0-WrkM7Qsv41-dWg8I_r9BLuZV30wSWnzgU,13274\npip/_internal/commands/lock.py,sha256=bUYrryKa769UXM61imojoeVVgc_1ZHK-9a0hIJmmlCg,5941\npip/_internal/commands/search.py,sha256=IrfvxcRCSoZY9A5XAlCF1wtl_y2HPcXslQdHcjzwMNk,5784\npip/_internal/commands/show.py,sha256=Yh5rGYhR2Io5TkL0fFCMWE1VqqM4xhPHjhbdS3QgEac,8028\npip/_internal/commands/uninstall.py,sha256=7pOR7enK76gimyxQbzxcG1OsyLXL3DvX939xmM8Fvtg,3892\npip/_internal/commands/wheel.py,sha256=NEfaVF4f41VBNSn93RL8gkfCEDmdGhbP9xu_dE6cdUk,6346\npip/_internal/configuration.py,sha256=-KOok6jh3hFzXMPQFPJ1_EFjBpAsge-RSreQuLHLmzo,14005\npip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858\npip/_internal/distributions/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/distributions/__pycache__/base.cpython-313.pyc,,\npip/_internal/distributions/__pycache__/installed.cpython-313.pyc,,\npip/_internal/distributions/__pycache__/sdist.cpython-313.pyc,,\npip/_internal/distributions/__pycache__/wheel.cpython-313.pyc,,\npip/_internal/distributions/base.py,sha256=QeB9qvKXDIjLdPBDE5fMgpfGqMMCr-govnuoQnGuiF8,1783\npip/_internal/distributions/installed.py,sha256=QinHFbWAQ8oE0pbD8MFZWkwlnfU1QYTccA1vnhrlYOU,842\npip/_internal/distributions/sdist.py,sha256=PlcP4a6-R6c98XnOM-b6Lkb3rsvh9iG4ok8shaanrzs,6751\npip/_internal/distributions/wheel.py,sha256=THBYfnv7VVt8mYhMYUtH13S1E7FDwtDyDfmUcl8ai0E,1317\npip/_internal/exceptions.py,sha256=wpE11H0e4L9G6AH70sRG149z82X7wX530HK-9eA_DIQ,28464\npip/_internal/index/__init__.py,sha256=tzwMH_fhQeubwMqHdSivasg1cRgTSbNg2CiMVnzMmyU,29\npip/_internal/index/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/index/__pycache__/collector.cpython-313.pyc,,\npip/_internal/index/__pycache__/package_finder.cpython-313.pyc,,\npip/_internal/index/__pycache__/sources.cpython-313.pyc,,\npip/_internal/index/collector.py,sha256=RdPO0JLAlmyBWPAWYHPyRoGjz3GNAeTngCNkbGey_mE,16265\npip/_internal/index/package_finder.py,sha256=RohRzzLExoXl7QDdTiqyxIaQEcHUn6UNOr9KzC1vjL0,38446\npip/_internal/index/sources.py,sha256=lPBLK5Xiy8Q6IQMio26Wl7ocfZOKkgGklIBNyUJ23fI,8632\npip/_internal/locations/__init__.py,sha256=vvTMNxghT0aEXrSdqpNtuRDGx08bzJxfDAUUfQ0Vb0A,14309\npip/_internal/locations/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/locations/__pycache__/_distutils.cpython-313.pyc,,\npip/_internal/locations/__pycache__/_sysconfig.cpython-313.pyc,,\npip/_internal/locations/__pycache__/base.cpython-313.pyc,,\npip/_internal/locations/_distutils.py,sha256=x6nyVLj7X11Y4khIdf-mFlxMl2FWadtVEgeb8upc_WI,6013\npip/_internal/locations/_sysconfig.py,sha256=IGzds60qsFneRogC-oeBaY7bEh3lPt_v47kMJChQXsU,7724\npip/_internal/locations/base.py,sha256=RQiPi1d4FVM2Bxk04dQhXZ2PqkeljEL2fZZ9SYqIQ78,2556\npip/_internal/main.py,sha256=r-UnUe8HLo5XFJz8inTcOOTiu_sxNhgHb6VwlGUllOI,340\npip/_internal/metadata/__init__.py,sha256=nGWuZvjQlIHudlMz_-bsUs2LDA2ZKNPGevZoEGcd64Y,5723\npip/_internal/metadata/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/metadata/__pycache__/_json.cpython-313.pyc,,\npip/_internal/metadata/__pycache__/base.cpython-313.pyc,,\npip/_internal/metadata/__pycache__/pkg_resources.cpython-313.pyc,,\npip/_internal/metadata/_json.py,sha256=ezrIYazHCINM2QUk1eA9wEAMj3aeGWeDVgGalgUzKpc,2707\npip/_internal/metadata/base.py,sha256=jCbzdIc8MgWnPR4rfrvSQhSVzSoOyKOXhj3xe8BoG8c,25467\npip/_internal/metadata/importlib/__init__.py,sha256=jUUidoxnHcfITHHaAWG1G2i5fdBYklv_uJcjo2x7VYE,135\npip/_internal/metadata/importlib/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/metadata/importlib/__pycache__/_compat.cpython-313.pyc,,\npip/_internal/metadata/importlib/__pycache__/_dists.cpython-313.pyc,,\npip/_internal/metadata/importlib/__pycache__/_envs.cpython-313.pyc,,\npip/_internal/metadata/importlib/_compat.py,sha256=c6av8sP8BBjAZuFSJow1iWfygUXNM3xRTCn5nqw6B9M,2796\npip/_internal/metadata/importlib/_dists.py,sha256=ftmYiyfUGUIjnVwt6W-Ijsimy5c28KgmXly5Q5IQ2P4,8279\npip/_internal/metadata/importlib/_envs.py,sha256=X63CkdAPJCYPhefYSLiQzPf9ijMXm5nL_A_Z68yp2-w,5297\npip/_internal/metadata/pkg_resources.py,sha256=U07ETAINSGeSRBfWUG93E4tZZbaW_f7PGzEqZN0hulc,10542\npip/_internal/models/__init__.py,sha256=AjmCEBxX_MH9f_jVjIGNCFJKYCYeSEe18yyvNx4uRKQ,62\npip/_internal/models/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/models/__pycache__/candidate.cpython-313.pyc,,\npip/_internal/models/__pycache__/direct_url.cpython-313.pyc,,\npip/_internal/models/__pycache__/format_control.cpython-313.pyc,,\npip/_internal/models/__pycache__/index.cpython-313.pyc,,\npip/_internal/models/__pycache__/installation_report.cpython-313.pyc,,\npip/_internal/models/__pycache__/link.cpython-313.pyc,,\npip/_internal/models/__pycache__/pylock.cpython-313.pyc,,\npip/_internal/models/__pycache__/scheme.cpython-313.pyc,,\npip/_internal/models/__pycache__/search_scope.cpython-313.pyc,,\npip/_internal/models/__pycache__/selection_prefs.cpython-313.pyc,,\npip/_internal/models/__pycache__/target_python.cpython-313.pyc,,\npip/_internal/models/__pycache__/wheel.cpython-313.pyc,,\npip/_internal/models/candidate.py,sha256=zzgFRuw_kWPjKpGw7LC0ZUMD2CQ2EberUIYs8izjdCA,753\npip/_internal/models/direct_url.py,sha256=lJ1fIVTgk5UG5SzTNR0FpgSGAQjChlH-3otgiEJAhIs,6576\npip/_internal/models/format_control.py,sha256=wtsQqSK9HaUiNxQEuB-C62eVimw6G4_VQFxV9-_KDBE,2486\npip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030\npip/_internal/models/installation_report.py,sha256=zRVZoaz-2vsrezj_H3hLOhMZCK9c7TbzWgC-jOalD00,2818\npip/_internal/models/link.py,sha256=wIAgxhiu05ycLhbtAibknXX5L6X9ju_PPLVnMcvh9B4,21511\npip/_internal/models/pylock.py,sha256=n3-I26bf2v-Kn6qcx4ATB_Zel2SLhaUxZBmsMeGgYAo,6196\npip/_internal/models/scheme.py,sha256=PakmHJM3e8OOWSZFtfz1Az7f1meONJnkGuQxFlt3wBE,575\npip/_internal/models/search_scope.py,sha256=67NEnsYY84784S-MM7ekQuo9KXLH-7MzFntXjapvAo0,4531\npip/_internal/models/selection_prefs.py,sha256=qaFfDs3ciqoXPg6xx45N1jPLqccLJw4N0s4P0PyHTQ8,2015\npip/_internal/models/target_python.py,sha256=2XaH2rZ5ZF-K5wcJbEMGEl7SqrTToDDNkrtQ2v_v_-Q,4271\npip/_internal/models/wheel.py,sha256=10NUTXIRjf2P8oe1Wzolv8oUv7-YurrOduVFUIaDhdM,5506\npip/_internal/network/__init__.py,sha256=FMy06P__y6jMjUc8z3ZcQdKF-pmZ2zM14_vBeHPGhUI,49\npip/_internal/network/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/network/__pycache__/auth.cpython-313.pyc,,\npip/_internal/network/__pycache__/cache.cpython-313.pyc,,\npip/_internal/network/__pycache__/download.cpython-313.pyc,,\npip/_internal/network/__pycache__/lazy_wheel.cpython-313.pyc,,\npip/_internal/network/__pycache__/session.cpython-313.pyc,,\npip/_internal/network/__pycache__/utils.cpython-313.pyc,,\npip/_internal/network/__pycache__/xmlrpc.cpython-313.pyc,,\npip/_internal/network/auth.py,sha256=D4gASjUrqoDFlSt6gQ767KAAjv6PUyJU0puDlhXNVRE,20809\npip/_internal/network/cache.py,sha256=JGYT-BUaSMdEBwII_K1UE6qyBItz7hzGkyLl_JRzkBY,4613\npip/_internal/network/download.py,sha256=6IdZyoERWIsXXFUFL_h_e_xi8Z0G0UlpkodPy8qKv2U,11078\npip/_internal/network/lazy_wheel.py,sha256=PBdoMoNQQIA84Fhgne38jWF52W4x_KtsHjxgv4dkRKA,7622\npip/_internal/network/session.py,sha256=msM4es16LmmNEYNkrYyg8fTc7gAHbKFltawfKP27LOI,18771\npip/_internal/network/utils.py,sha256=Inaxel-NxBu4PQWkjyErdnfewsFCcgHph7dzR1-FboY,4088\npip/_internal/network/xmlrpc.py,sha256=jW9oDSWamMld3iZOO9RbonVC8ZStkHyppCszoevkuJg,1837\npip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/operations/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/operations/__pycache__/check.cpython-313.pyc,,\npip/_internal/operations/__pycache__/freeze.cpython-313.pyc,,\npip/_internal/operations/__pycache__/prepare.cpython-313.pyc,,\npip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/operations/build/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/build_tracker.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/metadata.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/metadata_editable.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/metadata_legacy.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/wheel.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/wheel_editable.cpython-313.pyc,,\npip/_internal/operations/build/__pycache__/wheel_legacy.cpython-313.pyc,,\npip/_internal/operations/build/build_tracker.py,sha256=-ARW_TcjHCOX7D2NUOGntB4Fgc6b4aolsXkAK6BWL7w,4774\npip/_internal/operations/build/metadata.py,sha256=INHaeiRfOiLYCXApfDNRo9Cw2xI4VwTc0KItvfdfOjk,1421\npip/_internal/operations/build/metadata_editable.py,sha256=oWudMsnjy4loO_Jy7g4N9nxsnaEX_iDlVRgCy7pu1rs,1509\npip/_internal/operations/build/metadata_legacy.py,sha256=wv8cFA0wTqF62Jlm9QwloYZsofOyQ7sWBBmvCcVvn1k,2189\npip/_internal/operations/build/wheel.py,sha256=sT12FBLAxDC6wyrDorh8kvcZ1jG5qInCRWzzP-UkJiQ,1075\npip/_internal/operations/build/wheel_editable.py,sha256=yOtoH6zpAkoKYEUtr8FhzrYnkNHQaQBjWQ2HYae1MQg,1417\npip/_internal/operations/build/wheel_legacy.py,sha256=KXpyGYoCQYcudXNZvohLXgWHaCk4Gf3z0dbS9ol4uu0,3620\npip/_internal/operations/check.py,sha256=4cnD_2eglsDe5s2CoYkxDt4HcRitTywzLMfTZ-tGQ4U,5911\npip/_internal/operations/freeze.py,sha256=1_M79jAQKnCxWr-KCCmHuVXOVFGaUJHmoWLfFzgh7K4,9843\npip/_internal/operations/install/__init__.py,sha256=ak-UETcQPKlFZaWoYKWu5QVXbpFBvg0sXc3i0O4vSYY,50\npip/_internal/operations/install/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/operations/install/__pycache__/editable_legacy.cpython-313.pyc,,\npip/_internal/operations/install/__pycache__/wheel.cpython-313.pyc,,\npip/_internal/operations/install/editable_legacy.py,sha256=TI6wT8sLqDTprWZLYEOBOe7a6-1B9uwKb7kTBxLIaWY,1282\npip/_internal/operations/install/wheel.py,sha256=4NYSQ9ypl69iiduh5gUPCK3WNYqouTHZ0rMXoVgkiZw,27553\npip/_internal/operations/prepare.py,sha256=-i9dYwwJJjN7h6sZTabcz84tizgn7EAsY0sHnLAfs3Q,28363\npip/_internal/pyproject.py,sha256=GLJ6rWRS5_2noKdajohoLyDty57Z7QXhcUAYghmTnWc,7286\npip/_internal/req/__init__.py,sha256=dX2QGlfDwEqE5pLjOeM-f2qEgXFn6f2Vdi_zIHAYy1k,3096\npip/_internal/req/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/req/__pycache__/constructors.cpython-313.pyc,,\npip/_internal/req/__pycache__/req_dependency_group.cpython-313.pyc,,\npip/_internal/req/__pycache__/req_file.cpython-313.pyc,,\npip/_internal/req/__pycache__/req_install.cpython-313.pyc,,\npip/_internal/req/__pycache__/req_set.cpython-313.pyc,,\npip/_internal/req/__pycache__/req_uninstall.cpython-313.pyc,,\npip/_internal/req/constructors.py,sha256=v1qzCN1mIldwx-nCrPc8JO4lxkm3Fv8M5RWvt8LISjc,18430\npip/_internal/req/req_dependency_group.py,sha256=5PGuZidqwDeTHZkP4tnNrlPrasfvJBONd1B5S0146zs,2677\npip/_internal/req/req_file.py,sha256=eys82McgaICOGic2UZRHjD720piKJPwmeSYdXlWwl6w,20234\npip/_internal/req/req_install.py,sha256=gMoFak9zrhjHlHaOQxPFheHKtIobppFgq1WrKel_nTE,35788\npip/_internal/req/req_set.py,sha256=j3esG0s6SzoVReX9rWn4rpYNtyET_fwxbwJPRimvRxo,2858\npip/_internal/req/req_uninstall.py,sha256=PQ6SyocDycUYsLAsTpjkbdwO_qjdo-y8BvQfZ5Avdrw,24075\npip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/resolution/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/resolution/__pycache__/base.cpython-313.pyc,,\npip/_internal/resolution/base.py,sha256=qlmh325SBVfvG6Me9gc5Nsh5sdwHBwzHBq6aEXtKsLA,583\npip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/resolution/legacy/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/resolution/legacy/__pycache__/resolver.cpython-313.pyc,,\npip/_internal/resolution/legacy/resolver.py,sha256=3HZiJBRd1FTN6jQpI4qRO8-TbLYeIbUTS6PFvXnXs2w,24068\npip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/resolution/resolvelib/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/base.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/candidates.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/factory.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/found_candidates.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/provider.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/reporter.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/requirements.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/__pycache__/resolver.cpython-313.pyc,,\npip/_internal/resolution/resolvelib/base.py,sha256=DCf669FsqyQY5uqXeePDHQY1e4QO-pBzWH8O0s9-K94,5023\npip/_internal/resolution/resolvelib/candidates.py,sha256=U3Qp83jhM_RiJviyrlPCijbps6wYO6VsTDaTnCf_B3o,20241\npip/_internal/resolution/resolvelib/factory.py,sha256=FCvHc9M8UJ_7iU63QtPiHuq_BmfdnBiMJ8WaDBJNFxk,32668\npip/_internal/resolution/resolvelib/found_candidates.py,sha256=6lAF_pLQ2_Z0CBOHIFxGp6NfvT1uwIpCui6e-GgI5tk,6000\npip/_internal/resolution/resolvelib/provider.py,sha256=8ptYOOjfa336D4FZ751EQHR0LDq8jJhIGJXDou8Cv8Y,11190\npip/_internal/resolution/resolvelib/reporter.py,sha256=EwJAHOjWZ8eTHQWss7zJjmQEj6ooP6oWSwwVXFtgpqQ,3260\npip/_internal/resolution/resolvelib/requirements.py,sha256=7JG4Z72e5Yk4vU0S5ulGvbqTy4FMQGYhY5zQhX9zTtY,8065\npip/_internal/resolution/resolvelib/resolver.py,sha256=9zcR4c7UZV1j2ILTmb68Ck_5HdvQvf4cmTBE2bWHkKg,12785\npip/_internal/self_outdated_check.py,sha256=1PFtttvLAeyCVR3tPoBq2sOlPD0IJ-KSqU6bc1HUk9c,8318\npip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/utils/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/utils/__pycache__/_jaraco_text.cpython-313.pyc,,\npip/_internal/utils/__pycache__/_log.cpython-313.pyc,,\npip/_internal/utils/__pycache__/appdirs.cpython-313.pyc,,\npip/_internal/utils/__pycache__/compat.cpython-313.pyc,,\npip/_internal/utils/__pycache__/compatibility_tags.cpython-313.pyc,,\npip/_internal/utils/__pycache__/datetime.cpython-313.pyc,,\npip/_internal/utils/__pycache__/deprecation.cpython-313.pyc,,\npip/_internal/utils/__pycache__/direct_url_helpers.cpython-313.pyc,,\npip/_internal/utils/__pycache__/egg_link.cpython-313.pyc,,\npip/_internal/utils/__pycache__/entrypoints.cpython-313.pyc,,\npip/_internal/utils/__pycache__/filesystem.cpython-313.pyc,,\npip/_internal/utils/__pycache__/filetypes.cpython-313.pyc,,\npip/_internal/utils/__pycache__/glibc.cpython-313.pyc,,\npip/_internal/utils/__pycache__/hashes.cpython-313.pyc,,\npip/_internal/utils/__pycache__/logging.cpython-313.pyc,,\npip/_internal/utils/__pycache__/misc.cpython-313.pyc,,\npip/_internal/utils/__pycache__/packaging.cpython-313.pyc,,\npip/_internal/utils/__pycache__/retry.cpython-313.pyc,,\npip/_internal/utils/__pycache__/setuptools_build.cpython-313.pyc,,\npip/_internal/utils/__pycache__/subprocess.cpython-313.pyc,,\npip/_internal/utils/__pycache__/temp_dir.cpython-313.pyc,,\npip/_internal/utils/__pycache__/unpacking.cpython-313.pyc,,\npip/_internal/utils/__pycache__/urls.cpython-313.pyc,,\npip/_internal/utils/__pycache__/virtualenv.cpython-313.pyc,,\npip/_internal/utils/__pycache__/wheel.cpython-313.pyc,,\npip/_internal/utils/_jaraco_text.py,sha256=M15uUPIh5NpP1tdUGBxRau6q1ZAEtI8-XyLEETscFfE,3350\npip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015\npip/_internal/utils/appdirs.py,sha256=zrIISCn2QxlXYw-zJZZBTrFNTyy_0WNKiI-TOoN6wJo,1705\npip/_internal/utils/compat.py,sha256=ckkFveBiYQjRWjkNsajt_oWPS57tJvE8XxoC4OIYgCY,2399\npip/_internal/utils/compatibility_tags.py,sha256=q5W7IrNlqC5ke0AqWRG6aX5pimiqh--xuPCCNwCKPsU,6662\npip/_internal/utils/datetime.py,sha256=Gt29Ml4ToPSM88j54iu43WKtrU9A-moP4QmMiiqzedU,241\npip/_internal/utils/deprecation.py,sha256=k7Qg_UBAaaTdyq82YVARA6D7RmcGTXGv7fnfcgigj4Q,3707\npip/_internal/utils/direct_url_helpers.py,sha256=r2MRtkVDACv9AGqYODBUC9CjwgtsUU1s68hmgfCJMtA,3196\npip/_internal/utils/egg_link.py,sha256=0FePZoUYKv4RGQ2t6x7w5Z427wbA_Uo3WZnAkrgsuqo,2463\npip/_internal/utils/entrypoints.py,sha256=4CheZ81OBPPLb3Gn-X_WEPtllUibpwDVzlVQ4RFh7PM,3325\npip/_internal/utils/filesystem.py,sha256=ajvA-q4ocliW9kPp8Yquh-4vssXbu-UKbo5FV9V4X64,4950\npip/_internal/utils/filetypes.py,sha256=OCPzUxq3Aa6k_95MiI8DYgkOzutTs47fA-v-vYUJp9E,715\npip/_internal/utils/glibc.py,sha256=vUkWq_1pJuzcYNcGKLlQmABoUiisK8noYY1yc8Wq4w4,3734\npip/_internal/utils/hashes.py,sha256=XGGLL0AG8-RhWnyz87xF6MFZ--BKadHU35D47eApCKI,4972\npip/_internal/utils/logging.py,sha256=zMZK1NxfhM4QMGUyaU9q1grNuDhLSVbSkGCvZBKmaPw,12076\npip/_internal/utils/misc.py,sha256=DWnYxBUItjRp7hhxEg4ih6P6YpKrykM86dbi_EcU8SQ,23450\npip/_internal/utils/packaging.py,sha256=CjJOqLNENW-U88ojOllVL40f1ab2W2Bm3KHCavwNNfw,1603\npip/_internal/utils/retry.py,sha256=mhFbykXjhTnZfgzeuy-vl9c8nECnYn_CMtwNJX2tYzQ,1392\npip/_internal/utils/setuptools_build.py,sha256=J9EyRantVgu4V-xS_qfQy2mcPLVUM7A-227QdKGUZCA,4482\npip/_internal/utils/subprocess.py,sha256=EsvqSRiSMHF98T8Txmu6NLU3U--MpTTQjtNgKP0P--M,8988\npip/_internal/utils/temp_dir.py,sha256=5qOXe8M4JeY6vaFQM867d5zkp1bSwMZ-KT5jymmP0Zg,9310\npip/_internal/utils/unpacking.py,sha256=4yCqlRAI2zxl5tfxlnLoWLNcEn-k1c3vaet_oaJ42iI,11926\npip/_internal/utils/urls.py,sha256=qceSOZb5lbNDrHNsv7_S4L4Ytszja5NwPKUMnZHbYnM,1599\npip/_internal/utils/virtualenv.py,sha256=S6f7csYorRpiD6cvn3jISZYc3I8PJC43H5iMFpRAEDU,3456\npip/_internal/utils/wheel.py,sha256=MHObYn6d7VyZL10i-W1xoJZ2hT5-wB1WkII70AsYUE8,4493\npip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596\npip/_internal/vcs/__pycache__/__init__.cpython-313.pyc,,\npip/_internal/vcs/__pycache__/bazaar.cpython-313.pyc,,\npip/_internal/vcs/__pycache__/git.cpython-313.pyc,,\npip/_internal/vcs/__pycache__/mercurial.cpython-313.pyc,,\npip/_internal/vcs/__pycache__/subversion.cpython-313.pyc,,\npip/_internal/vcs/__pycache__/versioncontrol.cpython-313.pyc,,\npip/_internal/vcs/bazaar.py,sha256=EKStcQaKpNu0NK4p5Q10Oc4xb3DUxFw024XrJy40bFQ,3528\npip/_internal/vcs/git.py,sha256=3KLPrKsDL9xZchmz4H1Obo8fM2Fh8ChrhtDHWjbkj-I,18591\npip/_internal/vcs/mercurial.py,sha256=oULOhzJ2Uie-06d1omkL-_Gc6meGaUkyogvqG9ZCyPs,5249\npip/_internal/vcs/subversion.py,sha256=ddTugHBqHzV3ebKlU5QXHPN4gUqlyXbOx8q8NgXKvs8,11735\npip/_internal/vcs/versioncontrol.py,sha256=cvf_-hnTAjQLXJ3d17FMNhQfcO1AcKWUF10tfrYyP-c,22440\npip/_internal/wheel_builder.py,sha256=Z5Z2ANADbKdSHY9BHqw9zG5-1AxstO6YM6m9yLWe7Vw,11212\npip/_vendor/__init__.py,sha256=WzusPTGWIMeQQWSVJ0h2rafGkVTa9WKJ2HT-2-EoZrU,4907\npip/_vendor/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/__pycache__/typing_extensions.cpython-313.pyc,,\npip/_vendor/cachecontrol/__init__.py,sha256=x9ecUkiwNvAGfE3g0eaRx3VrJZnZWAluA2LRcvab3HQ,677\npip/_vendor/cachecontrol/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/_cmd.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/adapter.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/cache.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/controller.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/filewrapper.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/heuristics.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/serialize.cpython-313.pyc,,\npip/_vendor/cachecontrol/__pycache__/wrapper.cpython-313.pyc,,\npip/_vendor/cachecontrol/_cmd.py,sha256=iist2EpzJvDVIhMAxXq8iFnTBsiZAd6iplxfmNboNyk,1737\npip/_vendor/cachecontrol/adapter.py,sha256=8y6rTPXOzVHmDKCW5CR9sivLVuDv-cpdGcZYdRWNaPw,6599\npip/_vendor/cachecontrol/cache.py,sha256=OXwv7Fn2AwnKNiahJHnjtvaKLndvVLv_-zO-ltlV9qI,1953\npip/_vendor/cachecontrol/caches/__init__.py,sha256=dtrrroK5BnADR1GWjCZ19aZ0tFsMfvFBtLQQU1sp_ag,303\npip/_vendor/cachecontrol/caches/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/cachecontrol/caches/__pycache__/file_cache.cpython-313.pyc,,\npip/_vendor/cachecontrol/caches/__pycache__/redis_cache.cpython-313.pyc,,\npip/_vendor/cachecontrol/caches/file_cache.py,sha256=d8upFmy_zwaCmlbWEVBlLXFddt8Zw8c5SFpxeOZsdfw,4117\npip/_vendor/cachecontrol/caches/redis_cache.py,sha256=9rmqwtYu_ljVkW6_oLqbC7EaX_a8YT_yLuna-eS0dgo,1386\npip/_vendor/cachecontrol/controller.py,sha256=cx0Hl8xLZgUuXuy78Gih9AYjCtqurmYjVJxyA4yWt7w,19101\npip/_vendor/cachecontrol/filewrapper.py,sha256=2ktXNPE0KqnyzF24aOsKCA58HQq1xeC6l2g6_zwjghc,4291\npip/_vendor/cachecontrol/heuristics.py,sha256=gqMXU8w0gQuEQiSdu3Yg-0vd9kW7nrWKbLca75rheGE,4881\npip/_vendor/cachecontrol/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/cachecontrol/serialize.py,sha256=HQd2IllQ05HzPkVLMXTF2uX5mjEQjDBkxCqUJUODpZk,5163\npip/_vendor/cachecontrol/wrapper.py,sha256=hsGc7g8QGQTT-4f8tgz3AM5qwScg6FO0BSdLSRdEvpU,1417\npip/_vendor/certifi/__init__.py,sha256=neIaAf7BM36ygmQCmy-ZsSyjnvjWghFeu13wwEAnjj0,94\npip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255\npip/_vendor/certifi/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/certifi/__pycache__/__main__.cpython-313.pyc,,\npip/_vendor/certifi/__pycache__/core.cpython-313.pyc,,\npip/_vendor/certifi/cacert.pem,sha256=xVsh-Qf3-G1IrdCTVS-1ZRdJ_1-GBQjMu0I9bB-9gMc,297255\npip/_vendor/certifi/core.py,sha256=2SRT5rIcQChFDbe37BQa-kULxAgJ8qN6l1jfqTp4HIs,4486\npip/_vendor/certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/dependency_groups/__init__.py,sha256=C3OFu0NGwDzQ4LOmmSOFPsRSvkbBn-mdd4j_5YqJw-s,250\npip/_vendor/dependency_groups/__main__.py,sha256=UNTM7P5mfVtT7wDi9kOTXWgV3fu3e8bTrt1Qp1jvjKo,1709\npip/_vendor/dependency_groups/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/dependency_groups/__pycache__/__main__.cpython-313.pyc,,\npip/_vendor/dependency_groups/__pycache__/_implementation.cpython-313.pyc,,\npip/_vendor/dependency_groups/__pycache__/_lint_dependency_groups.cpython-313.pyc,,\npip/_vendor/dependency_groups/__pycache__/_pip_wrapper.cpython-313.pyc,,\npip/_vendor/dependency_groups/__pycache__/_toml_compat.cpython-313.pyc,,\npip/_vendor/dependency_groups/_implementation.py,sha256=Gqb2DlQELRakeHlKf6QtQSW0M-bcEomxHw4JsvID1ls,8041\npip/_vendor/dependency_groups/_lint_dependency_groups.py,sha256=yp-DDqKXtbkDTNa0ifa-FmOA8ra24lPZEXftW-R5AuI,1710\npip/_vendor/dependency_groups/_pip_wrapper.py,sha256=nuVW_w_ntVxpE26ELEvngMY0N04sFLsijXRyZZROFG8,1865\npip/_vendor/dependency_groups/_toml_compat.py,sha256=BHnXnFacm3DeolsA35GjI6qkDApvua-1F20kv3BfZWE,285\npip/_vendor/dependency_groups/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/distlib/__init__.py,sha256=dcwgYGYGQqAEawBXPDtIx80DO_3cOmFv8HTc8JMzknQ,625\npip/_vendor/distlib/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/compat.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/database.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/index.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/locators.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/manifest.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/markers.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/metadata.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/resources.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/scripts.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/util.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/version.cpython-313.pyc,,\npip/_vendor/distlib/__pycache__/wheel.cpython-313.pyc,,\npip/_vendor/distlib/compat.py,sha256=2jRSjRI4o-vlXeTK2BCGIUhkc6e9ZGhSsacRM5oseTw,41467\npip/_vendor/distlib/database.py,sha256=mHy_LxiXIsIVRb-T0-idBrVLw3Ffij5teHCpbjmJ9YU,51160\npip/_vendor/distlib/index.py,sha256=lTbw268rRhj8dw1sib3VZ_0EhSGgoJO3FKJzSFMOaeA,20797\npip/_vendor/distlib/locators.py,sha256=oBeAZpFuPQSY09MgNnLfQGGAXXvVO96BFpZyKMuK4tM,51026\npip/_vendor/distlib/manifest.py,sha256=3qfmAmVwxRqU1o23AlfXrQGZzh6g_GGzTAP_Hb9C5zQ,14168\npip/_vendor/distlib/markers.py,sha256=X6sDvkFGcYS8gUW8hfsWuKEKAqhQZAJ7iXOMLxRYjYk,5164\npip/_vendor/distlib/metadata.py,sha256=zil3sg2EUfLXVigljY2d_03IJt-JSs7nX-73fECMX2s,38724\npip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820\npip/_vendor/distlib/scripts.py,sha256=BJliaDAZaVB7WAkwokgC3HXwLD2iWiHaVI50H7C6eG8,18608\npip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792\npip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784\npip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032\npip/_vendor/distlib/util.py,sha256=vMPGvsS4j9hF6Y9k3Tyom1aaHLb0rFmZAEyzeAdel9w,66682\npip/_vendor/distlib/version.py,sha256=s5VIs8wBn0fxzGxWM_aA2ZZyx525HcZbMvcTlTyZ3Rg,23727\npip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648\npip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448\npip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888\npip/_vendor/distlib/wheel.py,sha256=DFIVguEQHCdxnSdAO0dfFsgMcvVZitg7bCOuLwZ7A_s,43979\npip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981\npip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64\npip/_vendor/distro/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/distro/__pycache__/__main__.cpython-313.pyc,,\npip/_vendor/distro/__pycache__/distro.cpython-313.pyc,,\npip/_vendor/distro/distro.py,sha256=XqbefacAhDT4zr_trnbA15eY8vdK4GTghgmvUGrEM_4,49430\npip/_vendor/distro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868\npip/_vendor/idna/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/codec.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/compat.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/core.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/idnadata.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/intranges.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/package_data.cpython-313.pyc,,\npip/_vendor/idna/__pycache__/uts46data.cpython-313.pyc,,\npip/_vendor/idna/codec.py,sha256=PEew3ItwzjW4hymbasnty2N2OXvNcgHB-JjrBuxHPYY,3422\npip/_vendor/idna/compat.py,sha256=RzLy6QQCdl9784aFhb2EX9EKGCJjg0P3PilGdeXXcx8,316\npip/_vendor/idna/core.py,sha256=YJYyAMnwiQEPjVC4-Fqu_p4CJ6yKKuDGmppBNQNQpFs,13239\npip/_vendor/idna/idnadata.py,sha256=W30GcIGvtOWYwAjZj4ZjuouUutC6ffgNuyjJy7fZ-lo,78306\npip/_vendor/idna/intranges.py,sha256=amUtkdhYcQG8Zr-CoMM_kVRacxkivC1WgxN1b63KKdU,1898\npip/_vendor/idna/package_data.py,sha256=q59S3OXsc5VI8j6vSD0sGBMyk6zZ4vWFREE88yCJYKs,21\npip/_vendor/idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/idna/uts46data.py,sha256=rt90K9J40gUSwppDPCrhjgi5AA6pWM65dEGRSf6rIhM,239289\npip/_vendor/msgpack/__init__.py,sha256=reRaiOtEzSjPnr7TpxjgIvbfln5pV66FhricAs2eC-g,1109\npip/_vendor/msgpack/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/msgpack/__pycache__/exceptions.cpython-313.pyc,,\npip/_vendor/msgpack/__pycache__/ext.cpython-313.pyc,,\npip/_vendor/msgpack/__pycache__/fallback.cpython-313.pyc,,\npip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081\npip/_vendor/msgpack/ext.py,sha256=kteJv03n9tYzd5oo3xYopVTo4vRaAxonBQQJhXohZZo,5726\npip/_vendor/msgpack/fallback.py,sha256=0g1Pzp0vtmBEmJ5w9F3s_-JMVURP8RS4G1cc5TRaAsI,32390\npip/_vendor/packaging/__init__.py,sha256=_0cDiPVf2S-bNfVmZguxxzmrIYWlyASxpqph4qsJWUc,494\npip/_vendor/packaging/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/_elffile.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/_manylinux.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/_musllinux.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/_parser.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/_structures.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/_tokenizer.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/markers.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/metadata.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/requirements.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/specifiers.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/tags.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/utils.cpython-313.pyc,,\npip/_vendor/packaging/__pycache__/version.cpython-313.pyc,,\npip/_vendor/packaging/_elffile.py,sha256=UkrbDtW7aeq3qqoAfU16ojyHZ1xsTvGke_WqMTKAKd0,3286\npip/_vendor/packaging/_manylinux.py,sha256=t4y_-dTOcfr36gLY-ztiOpxxJFGO2ikC11HgfysGxiM,9596\npip/_vendor/packaging/_musllinux.py,sha256=p9ZqNYiOItGee8KcZFeHF_YcdhVwGHdK6r-8lgixvGQ,2694\npip/_vendor/packaging/_parser.py,sha256=gYfnj0pRHflVc4RHZit13KNTyN9iiVcU2RUCGi22BwM,10221\npip/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431\npip/_vendor/packaging/_tokenizer.py,sha256=OYzt7qKxylOAJ-q0XyK1qAycyPRYLfMPdGQKRXkZWyI,5310\npip/_vendor/packaging/licenses/__init__.py,sha256=3bx-gryo4sRv5LsrwApouy65VIs3u6irSORJzALkrzU,5727\npip/_vendor/packaging/licenses/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/packaging/licenses/__pycache__/_spdx.cpython-313.pyc,,\npip/_vendor/packaging/licenses/_spdx.py,sha256=oAm1ztPFwlsmCKe7lAAsv_OIOfS1cWDu9bNBkeu-2ns,48398\npip/_vendor/packaging/markers.py,sha256=P0we27jm1xUzgGMJxBjtUFCIWeBxTsMeJTOJ6chZmAY,12049\npip/_vendor/packaging/metadata.py,sha256=8IZErqQQnNm53dZZuYq4FGU4_dpyinMeH1QFBIWIkfE,34739\npip/_vendor/packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/packaging/requirements.py,sha256=gYyRSAdbrIyKDY66ugIDUQjRMvxkH2ALioTmX3tnL6o,2947\npip/_vendor/packaging/specifiers.py,sha256=yc9D_MycJEmwUpZvcs1OZL9HfiNFmyw0RZaeHRNHkPw,40079\npip/_vendor/packaging/tags.py,sha256=41s97W9Zatrq2Ed7Rc3qeBDaHe8pKKvYq2mGjwahfXk,22745\npip/_vendor/packaging/utils.py,sha256=0F3Hh9OFuRgrhTgGZUl5K22Fv1YP2tZl1z_2gO6kJiA,5050\npip/_vendor/packaging/version.py,sha256=oiHqzTUv_p12hpjgsLDVcaF5hT7pDaSOViUNMD4GTW0,16688\npip/_vendor/pkg_resources/__init__.py,sha256=jrhDRbOubP74QuPXxd7U7Po42PH2l-LZ2XfcO7llpZ4,124463\npip/_vendor/pkg_resources/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/platformdirs/__init__.py,sha256=UfeSHWl8AeTtbOBOoHAxK4dODOWkZtfy-m_i7cWdJ8c,22344\npip/_vendor/platformdirs/__main__.py,sha256=jBJ8zb7Mpx5ebcqF83xrpO94MaeCpNGHVf9cvDN2JLg,1505\npip/_vendor/platformdirs/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/__main__.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/android.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/api.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/macos.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/unix.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/version.cpython-313.pyc,,\npip/_vendor/platformdirs/__pycache__/windows.cpython-313.pyc,,\npip/_vendor/platformdirs/android.py,sha256=r0DshVBf-RO1jXJGX8C4Til7F1XWt-bkdWMgmvEiaYg,9013\npip/_vendor/platformdirs/api.py,sha256=U9EzI3EYxcXWUCtIGRllqrcN99i2LSY1mq2-GtsUwEQ,9277\npip/_vendor/platformdirs/macos.py,sha256=UlbyFZ8Rzu3xndCqQEHrfsYTeHwYdFap1Ioz-yxveT4,6154\npip/_vendor/platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/platformdirs/unix.py,sha256=WZmkUA--L3JNRGmz32s35YfoD3ica6xKIPdCV_HhLcs,10458\npip/_vendor/platformdirs/version.py,sha256=0fnw4ljascx7O5PfIeZ2yj6w3pAkqwp099vDcivxuvY,511\npip/_vendor/platformdirs/windows.py,sha256=IFpiohUBwxPtCzlyKwNtxyW4Jk8haa6W8o59mfrDXVo,10125\npip/_vendor/pygments/__init__.py,sha256=qMm7-KYqNpMrmjymZaqfH-_9iJtjnexAKodkb9G5D5g,2983\npip/_vendor/pygments/__main__.py,sha256=WrndpSe6i1ckX_SQ1KaxD9CTKGzD0EuCOFxcbwFpoLU,353\npip/_vendor/pygments/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/__main__.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/console.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/filter.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/formatter.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/lexer.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/modeline.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/plugin.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/regexopt.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/scanner.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/sphinxext.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/style.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/token.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/unistring.cpython-313.pyc,,\npip/_vendor/pygments/__pycache__/util.cpython-313.pyc,,\npip/_vendor/pygments/console.py,sha256=AagDWqwea2yBWf10KC9ptBgMpMjxKp8yABAmh-NQOVk,1718\npip/_vendor/pygments/filter.py,sha256=YLtpTnZiu07nY3oK9nfR6E9Y1FBHhP5PX8gvkJWcfag,1910\npip/_vendor/pygments/filters/__init__.py,sha256=4U4jtA0X3iP83uQnB9-TI-HDSw8E8y8zMYHa0UjbbaI,40392\npip/_vendor/pygments/filters/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pygments/formatter.py,sha256=KZQMmyo_xkOIkQG8g66LYEkBh1bx7a0HyGCBcvhI9Ew,4390\npip/_vendor/pygments/formatters/__init__.py,sha256=KTwBmnXlaopJhQDOemVHYHskiDghuq-08YtP6xPNJPg,5385\npip/_vendor/pygments/formatters/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-313.pyc,,\npip/_vendor/pygments/formatters/_mapping.py,sha256=1Cw37FuQlNacnxRKmtlPX4nyLoX9_ttko5ZwscNUZZ4,4176\npip/_vendor/pygments/lexer.py,sha256=_kBrOJ_NT5Tl0IVM0rA9c8eysP6_yrlGzEQI0eVYB-A,35349\npip/_vendor/pygments/lexers/__init__.py,sha256=wbIME35GH7bI1B9rNPJFqWT-ij_RApZDYPUlZycaLzA,12115\npip/_vendor/pygments/lexers/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-313.pyc,,\npip/_vendor/pygments/lexers/__pycache__/python.cpython-313.pyc,,\npip/_vendor/pygments/lexers/_mapping.py,sha256=l4tCXM8e9aPC2BD6sjIr0deT-J-z5tHgCwL-p1fS0PE,77602\npip/_vendor/pygments/lexers/python.py,sha256=vxjn1cOHclIKJKxoyiBsQTY65GHbkZtZRuKQ2AVCKaw,53853\npip/_vendor/pygments/modeline.py,sha256=K5eSkR8GS1r5OkXXTHOcV0aM_6xpk9eWNEIAW-OOJ2g,1005\npip/_vendor/pygments/plugin.py,sha256=tPx0rJCTIZ9ioRgLNYG4pifCbAwTRUZddvLw-NfAk2w,1891\npip/_vendor/pygments/regexopt.py,sha256=wXaP9Gjp_hKAdnICqoDkRxAOQJSc4v3X6mcxx3z-TNs,3072\npip/_vendor/pygments/scanner.py,sha256=nNcETRR1tRuiTaHmHSTTECVYFPcLf6mDZu1e4u91A9E,3092\npip/_vendor/pygments/sphinxext.py,sha256=5x7Zh9YlU6ISJ31dMwduiaanb5dWZnKg3MyEQsseNnQ,7981\npip/_vendor/pygments/style.py,sha256=PlOZqlsnTVd58RGy50vkA2cXQ_lP5bF5EGMEBTno6DA,6420\npip/_vendor/pygments/styles/__init__.py,sha256=x9ebctfyvCAFpMTlMJ5YxwcNYBzjgq6zJaKkNm78r4M,2042\npip/_vendor/pygments/styles/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pygments/styles/__pycache__/_mapping.cpython-313.pyc,,\npip/_vendor/pygments/styles/_mapping.py,sha256=6lovFUE29tz6EsV3XYY4hgozJ7q1JL7cfO3UOlgnS8w,3312\npip/_vendor/pygments/token.py,sha256=WbdWGhYm_Vosb0DDxW9lHNPgITXfWTsQmHt6cy9RbcM,6226\npip/_vendor/pygments/unistring.py,sha256=al-_rBemRuGvinsrM6atNsHTmJ6DUbw24q2O2Ru1cBc,63208\npip/_vendor/pygments/util.py,sha256=oRtSpiAo5jM9ulntkvVbgXUdiAW57jnuYGB7t9fYuhc,10031\npip/_vendor/pyproject_hooks/__init__.py,sha256=cPB_a9LXz5xvsRbX1o2qyAdjLatZJdQ_Lc5McNX-X7Y,691\npip/_vendor/pyproject_hooks/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pyproject_hooks/__pycache__/_impl.cpython-313.pyc,,\npip/_vendor/pyproject_hooks/_impl.py,sha256=jY-raxnmyRyB57ruAitrJRUzEexuAhGTpgMygqx67Z4,14936\npip/_vendor/pyproject_hooks/_in_process/__init__.py,sha256=MJNPpfIxcO-FghxpBbxkG1rFiQf6HOUbV4U5mq0HFns,557\npip/_vendor/pyproject_hooks/_in_process/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/pyproject_hooks/_in_process/__pycache__/_in_process.cpython-313.pyc,,\npip/_vendor/pyproject_hooks/_in_process/_in_process.py,sha256=qcXMhmx__MIJq10gGHW3mA4Tl8dy8YzHMccwnNoKlw0,12216\npip/_vendor/pyproject_hooks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/requests/__init__.py,sha256=HlB_HzhrzGtfD_aaYUwUh1zWXLZ75_YCLyit75d0Vz8,5057\npip/_vendor/requests/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/__version__.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/_internal_utils.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/adapters.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/api.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/auth.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/certs.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/compat.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/cookies.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/exceptions.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/help.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/hooks.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/models.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/packages.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/sessions.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/status_codes.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/structures.cpython-313.pyc,,\npip/_vendor/requests/__pycache__/utils.cpython-313.pyc,,\npip/_vendor/requests/__version__.py,sha256=FVfglgZmNQnmYPXpOohDU58F5EUb_-VnSTaAesS187g,435\npip/_vendor/requests/_internal_utils.py,sha256=nMQymr4hs32TqVo5AbCrmcJEhvPUh7xXlluyqwslLiQ,1495\npip/_vendor/requests/adapters.py,sha256=J7VeVxKBvawbtlX2DERVo05J9BXTcWYLMHNd1Baa-bk,27607\npip/_vendor/requests/api.py,sha256=_Zb9Oa7tzVIizTKwFrPjDEY9ejtm_OnSRERnADxGsQs,6449\npip/_vendor/requests/auth.py,sha256=kF75tqnLctZ9Mf_hm9TZIj4cQWnN5uxRz8oWsx5wmR0,10186\npip/_vendor/requests/certs.py,sha256=kHDlkK_beuHXeMPc5jta2wgl8gdKeUWt5f2nTDVrvt8,441\npip/_vendor/requests/compat.py,sha256=Mo9f9xZpefod8Zm-n9_StJcVTmwSukXR2p3IQyyVXvU,1485\npip/_vendor/requests/cookies.py,sha256=bNi-iqEj4NPZ00-ob-rHvzkvObzN3lEpgw3g6paS3Xw,18590\npip/_vendor/requests/exceptions.py,sha256=D1wqzYWne1mS2rU43tP9CeN1G7QAy7eqL9o1god6Ejw,4272\npip/_vendor/requests/help.py,sha256=hRKaf9u0G7fdwrqMHtF3oG16RKktRf6KiwtSq2Fo1_0,3813\npip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733\npip/_vendor/requests/models.py,sha256=x4K4CmH-lC0l2Kb-iPfMN4dRXxHEcbOaEWBL_i09AwI,35483\npip/_vendor/requests/packages.py,sha256=_ZQDCJTJ8SP3kVWunSqBsRZNPzj2c1WFVqbdr08pz3U,1057\npip/_vendor/requests/sessions.py,sha256=ykTI8UWGSltOfH07HKollH7kTBGw4WhiBVaQGmckTw4,30495\npip/_vendor/requests/status_codes.py,sha256=iJUAeA25baTdw-6PfD0eF4qhpINDJRJI-yaMqxs4LEI,4322\npip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912\npip/_vendor/requests/utils.py,sha256=L79vnFbzJ3SFLKtJwpoWe41Tozi3RlZv94pY1TFIyow,33631\npip/_vendor/resolvelib/__init__.py,sha256=4LcBWHMH317EKEkpV5XLVnqiU1lrmCiygjsADuCgz4s,541\npip/_vendor/resolvelib/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/resolvelib/__pycache__/providers.cpython-313.pyc,,\npip/_vendor/resolvelib/__pycache__/reporters.cpython-313.pyc,,\npip/_vendor/resolvelib/__pycache__/structs.cpython-313.pyc,,\npip/_vendor/resolvelib/providers.py,sha256=pIWJbIdJJ9GFtNbtwTH0Ia43Vj6hYCEJj2DOLue15FM,8914\npip/_vendor/resolvelib/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/resolvelib/reporters.py,sha256=8BNa7G9cKW4Lie4BhDhd7Z57J_Vlb1CYPGSgVN2erMA,2038\npip/_vendor/resolvelib/resolvers/__init__.py,sha256=GMYuhrbSsYTIjOij0tuJKLvlk6UXmp3nXQetn2sOvpQ,640\npip/_vendor/resolvelib/resolvers/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/resolvelib/resolvers/__pycache__/abstract.cpython-313.pyc,,\npip/_vendor/resolvelib/resolvers/__pycache__/criterion.cpython-313.pyc,,\npip/_vendor/resolvelib/resolvers/__pycache__/exceptions.cpython-313.pyc,,\npip/_vendor/resolvelib/resolvers/__pycache__/resolution.cpython-313.pyc,,\npip/_vendor/resolvelib/resolvers/abstract.py,sha256=jZOBVigE4PUub9i3F-bTvBwaIXX8S9EU3CGASBvFqEU,1558\npip/_vendor/resolvelib/resolvers/criterion.py,sha256=lcmZGv5sKHOnFD_RzZwvlGSj19MeA-5rCMpdf2Sgw7Y,1768\npip/_vendor/resolvelib/resolvers/exceptions.py,sha256=ln_jaQtgLlRUSFY627yiHG2gD7AgaXzRKaElFVh7fDQ,1768\npip/_vendor/resolvelib/resolvers/resolution.py,sha256=yQegMuOmlzAElLLpgD-k6NbPDMCQf29rWhiFC26OdkM,20671\npip/_vendor/resolvelib/structs.py,sha256=pu-EJiR2IBITr2SQeNPRa0rXhjlStfmO_GEgAhr3004,6420\npip/_vendor/rich/__init__.py,sha256=dRxjIL-SbFVY0q3IjSMrfgBTHrm1LZDgLOygVBwiYZc,6090\npip/_vendor/rich/__main__.py,sha256=eO7Cq8JnrgG8zVoeImiAs92q3hXNMIfp0w5lMsO7Q2Y,8477\npip/_vendor/rich/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/__main__.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_cell_widths.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_emoji_codes.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_emoji_replace.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_export_format.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_extension.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_fileno.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_inspect.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_log_render.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_loop.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_null_file.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_palettes.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_pick.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_ratio.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_spinners.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_stack.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_timer.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_win32_console.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_windows.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_windows_renderer.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/_wrap.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/abc.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/align.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/ansi.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/bar.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/box.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/cells.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/color.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/color_triplet.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/columns.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/console.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/constrain.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/containers.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/control.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/default_styles.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/diagnose.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/emoji.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/errors.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/file_proxy.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/filesize.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/highlighter.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/json.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/jupyter.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/layout.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/live.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/live_render.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/logging.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/markup.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/measure.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/padding.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/pager.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/palette.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/panel.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/pretty.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/progress.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/progress_bar.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/prompt.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/protocol.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/region.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/repr.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/rule.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/scope.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/screen.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/segment.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/spinner.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/status.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/style.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/styled.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/syntax.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/table.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/terminal_theme.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/text.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/theme.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/themes.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/traceback.cpython-313.pyc,,\npip/_vendor/rich/__pycache__/tree.cpython-313.pyc,,\npip/_vendor/rich/_cell_widths.py,sha256=fbmeyetEdHjzE_Vx2l1uK7tnPOhMs2X1lJfO3vsKDpA,10209\npip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235\npip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064\npip/_vendor/rich/_export_format.py,sha256=RI08pSrm5tBSzPMvnbTqbD9WIalaOoN5d4M1RTmLq1Y,2128\npip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265\npip/_vendor/rich/_fileno.py,sha256=HWZxP5C2ajMbHryvAQZseflVfQoGzsKOHzKGsLD8ynQ,799\npip/_vendor/rich/_inspect.py,sha256=QM05lEFnFoTaFqpnbx-zBEI6k8oIKrD3cvjEOQNhKig,9655\npip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225\npip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236\npip/_vendor/rich/_null_file.py,sha256=ADGKp1yt-k70FMKV6tnqCqecB-rSJzp-WQsD7LPL-kg,1394\npip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063\npip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423\npip/_vendor/rich/_ratio.py,sha256=Zt58apszI6hAAcXPpgdWKpu3c31UBWebOeR4mbyptvU,5471\npip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919\npip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351\npip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417\npip/_vendor/rich/_win32_console.py,sha256=BSaDRIMwBLITn_m0mTRLPqME5q-quGdSMuYMpYeYJwc,22755\npip/_vendor/rich/_windows.py,sha256=aBwaD_S56SbgopIvayVmpk0Y28uwY2C5Bab1wl3Bp-I,1925\npip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783\npip/_vendor/rich/_wrap.py,sha256=FlSsom5EX0LVkA3KWy34yHnCfLtqX-ZIepXKh-70rpc,3404\npip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890\npip/_vendor/rich/align.py,sha256=Rh-3adnDaN1Ao07EjR2PhgE62PGLPgO8SMwJBku1urQ,10469\npip/_vendor/rich/ansi.py,sha256=Avs1LHbSdcyOvDOdpELZUoULcBiYewY76eNBp6uFBhs,6921\npip/_vendor/rich/bar.py,sha256=ldbVHOzKJOnflVNuv1xS7g6dLX2E3wMnXkdPbpzJTcs,3263\npip/_vendor/rich/box.py,sha256=nr5fYIUghB_iUCEq6y0Z3LlCT8gFPDrzN9u2kn7tJl4,10831\npip/_vendor/rich/cells.py,sha256=KrQkj5-LghCCpJLSNQIyAZjndc4bnEqOEmi5YuZ9UCY,5130\npip/_vendor/rich/color.py,sha256=3HSULVDj7qQkXUdFWv78JOiSZzfy5y1nkcYhna296V0,18211\npip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054\npip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131\npip/_vendor/rich/console.py,sha256=_RJizBQIn9qxr4Ln7Q_SC5N9ekPWPAxH0KGVxsgg69Y,100565\npip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288\npip/_vendor/rich/containers.py,sha256=c_56TxcedGYqDepHBMTuZdUIijitAQgnox-Qde0Z1qo,5502\npip/_vendor/rich/control.py,sha256=DSkHTUQLorfSERAKE_oTAEUFefZnZp4bQb4q8rHbKws,6630\npip/_vendor/rich/default_styles.py,sha256=khQFqqaoDs3bprMqWpHw8nO5UpG2DN6QtuTd6LzZwYc,8257\npip/_vendor/rich/diagnose.py,sha256=WNPjU2pEdrPICJ24KOaTD_hzP839qArpmF1JIM5x_EQ,998\npip/_vendor/rich/emoji.py,sha256=omTF9asaAnsM4yLY94eR_9dgRRSm1lHUszX20D1yYCQ,2501\npip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642\npip/_vendor/rich/file_proxy.py,sha256=Tl9THMDZ-Pk5Wm8sI1gGg_U5DhusmxD-FZ0fUbcU0W0,1683\npip/_vendor/rich/filesize.py,sha256=_iz9lIpRgvW7MNSeCZnLg-HwzbP4GETg543WqD8SFs0,2484\npip/_vendor/rich/highlighter.py,sha256=G_sn-8DKjM1sEjLG_oc4ovkWmiUpWvj8bXi0yed2LnY,9586\npip/_vendor/rich/json.py,sha256=vVEoKdawoJRjAFayPwXkMBPLy7RSTs-f44wSQDR2nJ0,5031\npip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252\npip/_vendor/rich/layout.py,sha256=ajkSFAtEVv9EFTcFs-w4uZfft7nEXhNzL7ZVdgrT5rI,14004\npip/_vendor/rich/live.py,sha256=DhzAPEnjTxQuq9_0Y2xh2MUwQcP_aGPkenLfKETslwM,14270\npip/_vendor/rich/live_render.py,sha256=zJtB471jGziBtEwxc54x12wEQtH4BuQr1SA8v9kU82w,3666\npip/_vendor/rich/logging.py,sha256=ZgpKMMBY_BuMAI_BYzo-UtXak6t5oH9VK8m9Q2Lm0f4,12458\npip/_vendor/rich/markup.py,sha256=3euGKP5s41NCQwaSjTnJxus5iZMHjxpIM0W6fCxra38,8451\npip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305\npip/_vendor/rich/padding.py,sha256=KVEI3tOwo9sgK1YNSuH__M1_jUWmLZwRVV_KmOtVzyM,4908\npip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828\npip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396\npip/_vendor/rich/panel.py,sha256=SUDaa3z4MU7vIjzvbi0SXuc6BslDzADwdY1AX4TbTdY,11225\npip/_vendor/rich/pretty.py,sha256=gy3S72u4FRg2ytoo7N1ZDWDIvB4unbzd5iUGdgm-8fc,36391\npip/_vendor/rich/progress.py,sha256=MtmCjTk5zYU_XtRHxRHTAEHG6hF9PeF7EMWbEPleIC0,60357\npip/_vendor/rich/progress_bar.py,sha256=mZTPpJUwcfcdgQCTTz3kyY-fc79ddLwtx6Ghhxfo064,8162\npip/_vendor/rich/prompt.py,sha256=l0RhQU-0UVTV9e08xW1BbIj0Jq2IXyChX4lC0lFNzt4,12447\npip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391\npip/_vendor/rich/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166\npip/_vendor/rich/repr.py,sha256=5MZJZmONgC6kud-QW-_m1okXwL2aR6u6y-pUcUCJz28,4431\npip/_vendor/rich/rule.py,sha256=0fNaS_aERa3UMRc3T5WMpN_sumtDxfaor2y3of1ftBk,4602\npip/_vendor/rich/scope.py,sha256=TMUU8qo17thyqQCPqjDLYpg_UU1k5qVd-WwiJvnJVas,2843\npip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591\npip/_vendor/rich/segment.py,sha256=otnKeKGEV-WRlQVosfJVeFDcDxAKHpvJ_hLzSu5lumM,24743\npip/_vendor/rich/spinner.py,sha256=PT5qgXPG3ZpqRj7n3EZQ6NW56mx3ldZqZCU7gEMyZk4,4364\npip/_vendor/rich/status.py,sha256=kkPph3YeAZBo-X-4wPp8gTqZyU466NLwZBA4PZTTewo,4424\npip/_vendor/rich/style.py,sha256=xpj4uMBZMtuNuNomfUiamigl3p1sDvTCZwrG1tcTVeg,27059\npip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258\npip/_vendor/rich/syntax.py,sha256=qqAnEUZ4K57Po81_5RBxnsuU4KRzSdvDPAhKw8ma_3E,35763\npip/_vendor/rich/table.py,sha256=ZmT7V7MMCOYKw7TGY9SZLyYDf6JdM-WVf07FdVuVhTI,40049\npip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370\npip/_vendor/rich/text.py,sha256=AO7JPCz6-gaN1thVLXMBntEmDPVYFgFNG1oM61_sanU,47552\npip/_vendor/rich/theme.py,sha256=oNyhXhGagtDlbDye3tVu3esWOWk0vNkuxFw-_unlaK0,3771\npip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102\npip/_vendor/rich/traceback.py,sha256=ZA8Q67DyP5a_stpIh6GPf9IiXj_s3dAhDIr6Zbfkahk,35170\npip/_vendor/rich/tree.py,sha256=yWnQ6rAvRGJ3qZGqBrxS2SW2TKBTNrP0SdY8QxOFPuw,9451\npip/_vendor/tomli/__init__.py,sha256=PhNw_eyLgdn7McJ6nrAN8yIm3dXC75vr1sVGVVwDSpA,314\npip/_vendor/tomli/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/tomli/__pycache__/_parser.cpython-313.pyc,,\npip/_vendor/tomli/__pycache__/_re.cpython-313.pyc,,\npip/_vendor/tomli/__pycache__/_types.cpython-313.pyc,,\npip/_vendor/tomli/_parser.py,sha256=9w8LG0jB7fwmZZWB0vVXbeejDHcl4ANIJxB2scEnDlA,25591\npip/_vendor/tomli/_re.py,sha256=sh4sBDRgO94KJZwNIrgdcyV_qQast50YvzOAUGpRDKA,3171\npip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254\npip/_vendor/tomli/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26\npip/_vendor/tomli_w/__init__.py,sha256=0F8yDtXx3Uunhm874KrAcP76srsM98y7WyHQwCulZbo,169\npip/_vendor/tomli_w/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/tomli_w/__pycache__/_writer.cpython-313.pyc,,\npip/_vendor/tomli_w/_writer.py,sha256=dsifFS2xYf1i76mmRyfz9y125xC7Z_HQ845ZKhJsYXs,6961\npip/_vendor/tomli_w/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26\npip/_vendor/truststore/__init__.py,sha256=2wRSVijjRzPLVXUzWqvdZLNsEOhDfopKLd2EKAYLwKU,1320\npip/_vendor/truststore/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/truststore/__pycache__/_api.cpython-313.pyc,,\npip/_vendor/truststore/__pycache__/_macos.cpython-313.pyc,,\npip/_vendor/truststore/__pycache__/_openssl.cpython-313.pyc,,\npip/_vendor/truststore/__pycache__/_ssl_constants.cpython-313.pyc,,\npip/_vendor/truststore/__pycache__/_windows.cpython-313.pyc,,\npip/_vendor/truststore/_api.py,sha256=40I0ojO2DnITiHvOnUYvJ1bfQMBKHOkci14noNxEnCs,11246\npip/_vendor/truststore/_macos.py,sha256=nZlLkOmszUE0g6ryRwBVGY5COzPyudcsiJtDWarM5LQ,20503\npip/_vendor/truststore/_openssl.py,sha256=LLUZ7ZGaio-i5dpKKjKCSeSufmn6T8pi9lDcFnvSyq0,2324\npip/_vendor/truststore/_ssl_constants.py,sha256=NUD4fVKdSD02ri7-db0tnO0VqLP9aHuzmStcW7tAl08,1130\npip/_vendor/truststore/_windows.py,sha256=rAHyKYD8M7t-bXfG8VgOVa3TpfhVhbt4rZQlO45YuP8,17993\npip/_vendor/truststore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/typing_extensions.py,sha256=ipKHUPtZCqL6c-HfvGl-9t0opsXcSL72y4GYjyJXs_g,172702\npip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333\npip/_vendor/urllib3/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/_collections.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/_version.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/connection.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/connectionpool.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/exceptions.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/fields.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/filepost.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/poolmanager.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/request.cpython-313.pyc,,\npip/_vendor/urllib3/__pycache__/response.cpython-313.pyc,,\npip/_vendor/urllib3/_collections.py,sha256=pyASJJhW7wdOpqJj9QJA8FyGRfr8E8uUUhqUvhF0728,11372\npip/_vendor/urllib3/_version.py,sha256=t9wGB6ooOTXXgiY66K1m6BZS1CJyXHAU8EoWDTe6Shk,64\npip/_vendor/urllib3/connection.py,sha256=ttIA909BrbTUzwkqEe_TzZVh4JOOj7g61Ysei2mrwGg,20314\npip/_vendor/urllib3/connectionpool.py,sha256=e2eiAwNbFNCKxj4bwDKNK-w7HIdSz3OmMxU_TIt-evQ,40408\npip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/contrib/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/__pycache__/appengine.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/__pycache__/securetransport.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/__pycache__/socks.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957\npip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/contrib/_securetransport/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/_securetransport/__pycache__/bindings.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/_securetransport/__pycache__/low_level.cpython-313.pyc,,\npip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632\npip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922\npip/_vendor/urllib3/contrib/appengine.py,sha256=VR68eAVE137lxTgjBDwCna5UiBZTOKa01Aj_-5BaCz4,11036\npip/_vendor/urllib3/contrib/ntlmpool.py,sha256=NlfkW7WMdW8ziqudopjHoW299og1BTWi0IeIibquFwk,4528\npip/_vendor/urllib3/contrib/pyopenssl.py,sha256=hDJh4MhyY_p-oKlFcYcQaVQRDv6GMmBGuW9yjxyeejM,17081\npip/_vendor/urllib3/contrib/securetransport.py,sha256=Fef1IIUUFHqpevzXiDPbIGkDKchY2FVKeVeLGR1Qq3g,34446\npip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097\npip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217\npip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579\npip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440\npip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/packages/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/urllib3/packages/__pycache__/six.cpython-313.pyc,,\npip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-313.pyc,,\npip/_vendor/urllib3/packages/backports/__pycache__/weakref_finalize.cpython-313.pyc,,\npip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417\npip/_vendor/urllib3/packages/backports/weakref_finalize.py,sha256=tRCal5OAhNSRyb0DhHp-38AtIlCsRP8BxF3NX-6rqIA,5343\npip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665\npip/_vendor/urllib3/poolmanager.py,sha256=aWyhXRtNO4JUnCSVVqKTKQd8EXTvUm1VN9pgs2bcONo,19990\npip/_vendor/urllib3/request.py,sha256=YTWFNr7QIwh7E1W9dde9LM77v2VWTJ5V78XuTTw7D1A,6691\npip/_vendor/urllib3/response.py,sha256=fmDJAFkG71uFTn-sVSTh2Iw0WmcXQYqkbRjihvwBjU8,30641\npip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155\npip/_vendor/urllib3/util/__pycache__/__init__.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/connection.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/proxy.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/queue.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/request.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/response.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/retry.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/ssl_.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/ssl_match_hostname.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/timeout.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/url.cpython-313.pyc,,\npip/_vendor/urllib3/util/__pycache__/wait.cpython-313.pyc,,\npip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901\npip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605\npip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498\npip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997\npip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510\npip/_vendor/urllib3/util/retry.py,sha256=6ENvOZ8PBDzh8kgixpql9lIrb2dxH-k7ZmBanJF2Ng4,22050\npip/_vendor/urllib3/util/ssl_.py,sha256=QDuuTxPSCj1rYtZ4xpD7Ux-r20TD50aHyqKyhQ7Bq4A,17460\npip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758\npip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895\npip/_vendor/urllib3/util/timeout.py,sha256=cwq4dMk87mJHSBktK1miYJ-85G-3T3RmT20v7SFCpno,10168\npip/_vendor/urllib3/util/url.py,sha256=lCAE7M5myA8EDdW0sJuyyZhVB9K_j38ljWhHAnFaWoE,14296\npip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403\npip/_vendor/vendor.txt,sha256=Fym1hhuw75IJOl33NPi5nIJJc66DioBSUWrVRIVtRUE,373\npip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\RECORD | RECORD | Other | 65,973 | 0.65 | 0 | 0 | node-utils | 72 | 2025-03-24T21:40:30.604694 | BSD-3-Clause | false | 5246153c5704541eb45571e1eee0c761 |
pip\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\top_level.txt | top_level.txt | Other | 4 | 0.5 | 0 | 0 | vue-tools | 354 | 2025-03-10T21:48:01.556430 | BSD-3-Clause | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
Wheel-Version: 1.0\nGenerator: setuptools (79.0.0)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\WHEEL | WHEEL | Other | 91 | 0.5 | 0 | 0 | python-kit | 72 | 2025-03-13T03:27:48.947538 | GPL-3.0 | false | 2c3a81c4e896aff63e960910b621a709 |
@Switch01\nA_Rog\nAakanksha Agrawal\nAbhinav Sagar\nABHYUDAY PRATAP SINGH\nabs51295\nAceGentile\nAdam Chainz\nAdam Tse\nAdam Turner\nAdam Wentz\nadmin\nAdolfo Ochagavía\nAdrien Morison\nAgus\nahayrapetyan\nAhilya\nAinsworthK\nAkash Srivastava\nAlan Yee\nAlbert Tugushev\nAlbert-Guan\nalbertg\nAlberto Sottile\nAleks Bunin\nAles Erjavec\nAlethea Flowers\nAlex Gaynor\nAlex Grönholm\nAlex Hedges\nAlex Loosley\nAlex Morega\nAlex Stachowiak\nAlexander Regueiro\nAlexander Shtyrov\nAlexandre Conrad\nAlexey Popravka\nAleš Erjavec\nAlli\nAmi Fischman\nAnanya Maiti\nAnatoly Techtonik\nAnders Kaseorg\nAndre Aguiar\nAndreas Lutro\nAndrei Geacar\nAndrew Gaul\nAndrew Shymanel\nAndrey Bienkowski\nAndrey Bulgakov\nAndrés Delfino\nAndy Freeland\nAndy Kluger\nAni Hayrapetyan\nAniruddha Basak\nAnish Tambe\nAnrs Hu\nAnthony Sottile\nAntoine Musso\nAnton Ovchinnikov\nAnton Patrushev\nAnton Zelenov\nAntonio Alvarado Hernandez\nAntony Lee\nAntti Kaihola\nAnubhav Patel\nAnudit Nagar\nAnuj Godase\nAQNOUCH Mohammed\nAraHaan\narena\narenasys\nArindam Choudhury\nArmin Ronacher\nArnon Yaari\nArtem\nArun Babu Neelicattu\nAshley Manton\nAshwin Ramaswami\natse\nAtsushi Odagiri\nAvinash Karhana\nAvner Cohen\nAwit (Ah-Wit) Ghirmai\nBaptiste Mispelon\nBarney Gale\nbarneygale\nBartek Ogryczak\nBastian Venthur\nBen Bodenmiller\nBen Darnell\nBen Hoyt\nBen Mares\nBen Rosser\nBence Nagy\nBenjamin Peterson\nBenjamin VanEvery\nBenoit Pierre\nBerker Peksag\nBernard\nBernard Tyers\nBernardo B. Marques\nBernhard M. Wiedemann\nBertil Hatt\nBhavam Vidyarthi\nBlazej Michalik\nBogdan Opanchuk\nBorisZZZ\nBrad Erickson\nBradley Ayers\nBradley Reynolds\nBranch Vincent\nBrandon L. Reiss\nBrandt Bucher\nBrannon Dorsey\nBrett Randall\nBrett Rosen\nBrian Cristante\nBrian Rosner\nbriantracy\nBrownTruck\nBruno Oliveira\nBruno Renié\nBruno S\nBstrdsmkr\nBuck Golemon\nburrows\nBussonnier Matthias\nbwoodsend\nc22\nCaleb Brown\nCaleb Martinez\nCalvin Smith\nCarl Meyer\nCarlos Liam\nCarol Willing\nCarter Thayer\nCass\nChandrasekhar Atina\nCharlie Marsh\ncharwick\nChih-Hsuan Yen\nChris Brinker\nChris Hunt\nChris Jerdonek\nChris Kuehl\nChris Markiewicz\nChris McDonough\nChris Pawley\nChris Pryer\nChris Wolfe\nChristian Clauss\nChristian Heimes\nChristian Oudard\nChristoph Reiter\nChristopher Hunt\nChristopher Snyder\nchrysle\ncjc7373\nClark Boylan\nClaudio Jolowicz\nClay McClure\nCody\nCody Soyland\nColin Watson\nCollin Anderson\nConnor Osborn\nCooper Lees\nCooper Ry Lees\nCory Benfield\nCory Wright\nCraig Kerstiens\nCristian Sorinel\nCristina\nCristina Muñoz\nctg123\nCurtis Doty\ncytolentino\nDaan De Meyer\nDale\nDamian\nDamian Quiroga\nDamian Shaw\nDan Black\nDan Savilonis\nDan Sully\nDane Hillard\ndaniel\nDaniel Collins\nDaniel Hahler\nDaniel Holth\nDaniel Jost\nDaniel Katz\nDaniel Shaulov\nDaniele Esposti\nDaniele Nicolodi\nDaniele Procida\nDaniil Konovalenko\nDanny Hermes\nDanny McClanahan\nDarren Kavanagh\nDav Clark\nDave Abrahams\nDave Jones\nDavid Aguilar\nDavid Black\nDavid Bordeynik\nDavid Caro\nDavid D Lowe\nDavid Evans\nDavid Hewitt\nDavid Linke\nDavid Poggi\nDavid Poznik\nDavid Pursehouse\nDavid Runge\nDavid Tucker\nDavid Wales\nDavidovich\nddelange\nDeepak Sharma\nDeepyaman Datta\nDenise Yu\ndependabot[bot]\nderwolfe\nDesetude\ndeveloper\nDevesh Kumar Singh\ndevsagul\nDiego Caraballo\nDiego Ramirez\nDiegoCaraballo\nDimitri Merejkowsky\nDimitri Papadopoulos\nDimitri Papadopoulos Orfanos\nDirk Stolle\nDmitry Gladkov\nDmitry Volodin\nDomen Kožar\nDominic Davis-Foster\nDonald Stufft\nDongweiming\ndoron zarhi\nDos Moonen\nDouglas Thor\nDrFeathers\nDustin Ingram\nDustin Rodrigues\nDwayne Bailey\nEd Morley\nEdgar Ramírez\nEdgar Ramírez Mondragón\nEe Durbin\nEfflam Lemaillet\nefflamlemaillet\nEitan Adler\nekristina\nelainechan\nEli Schwartz\nElisha Hollander\nEllen Marie Dash\nEmil Burzo\nEmil Styrke\nEmmanuel Arias\nEndoh Takanao\nenoch\nErdinc Mutlu\nEric Cousineau\nEric Gillingham\nEric Hanchrow\nEric Hopper\nErik M. Bray\nErik Rose\nErwin Janssen\nEugene Vereshchagin\neverdimension\nFederico\nFelipe Peter\nFelix Yan\nfiber-space\nFilip Kokosiński\nFilipe Laíns\nFinn Womack\nfinnagin\nFlavio Amurrio\nFlorian Briand\nFlorian Rathgeber\nFrancesco\nFrancesco Montesano\nFredrik Orderud\nFredrik Roubert\nFrost Ming\nGabriel Curio\nGabriel de Perthuis\nGarry Polley\ngavin\ngdanielson\nGeoffrey Sneddon\nGeorge Margaritis\nGeorge Song\nGeorgi Valkov\nGeorgy Pchelkin\nghost\nGiftlin Rajaiah\ngizmoguy1\ngkdoc\nGodefroid Chapelle\nGopinath M\nGOTO Hayato\ngousaiyang\ngpiks\nGreg Roodt\nGreg Ward\nGuilherme Espada\nGuillaume Seguin\ngutsytechster\nGuy Rozendorn\nGuy Tuval\ngzpan123\nHanjun Kim\nHari Charan\nHarsh Vardhan\nharupy\nHarutaka Kawamura\nhauntsaninja\nHenrich Hartzer\nHenry Schreiner\nHerbert Pfennig\nHolly Stotelmyer\nHonnix\nHsiaoming Yang\nHugo Lopes Tavares\nHugo van Kemenade\nHugues Bruant\nHynek Schlawack\nIan Bicking\nIan Cordasco\nIan Lee\nIan Stapleton Cordasco\nIan Wienand\nIgor Kuzmitshov\nIgor Sobreira\nIkko Ashimine\nIlan Schnell\nIllia Volochii\nIlya Baryshev\nInada Naoki\nIonel Cristian Mărieș\nIonel Maries Cristian\nItamar Turner-Trauring\niTrooz\nIvan Pozdeev\nJ. Nick Koston\nJacob Kim\nJacob Walls\nJaime Sanz\nJake Lishman\njakirkham\nJakub Kuczys\nJakub Stasiak\nJakub Vysoky\nJakub Wilk\nJames Cleveland\nJames Curtin\nJames Firth\nJames Gerity\nJames Polley\nJan Pokorný\nJannis Leidel\nJarek Potiuk\njarondl\nJason Curtis\nJason R. Coombs\nJasonMo\nJasonMo1\nJay Graves\nJean Abou Samra\nJean-Christophe Fillion-Robin\nJeff Barber\nJeff Dairiki\nJeff Widman\nJelmer Vernooij\njenix21\nJeremy Fleischman\nJeremy Stanley\nJeremy Zafran\nJesse Rittner\nJiashuo Li\nJim Fisher\nJim Garrison\nJinzhe Zeng\nJiun Bae\nJivan Amara\nJoa\nJoe Bylund\nJoe Michelini\nJohannes Altmanninger\nJohn Paton\nJohn Sirois\nJohn T. Wodder II\nJohn-Scott Atlakson\njohnthagen\nJon Banafato\nJon Dufresne\nJon Parise\nJonas Nockert\nJonathan Herbert\nJoonatan Partanen\nJoost Molenaar\nJorge Niedbalski\nJoseph Bylund\nJoseph Long\nJosh Bronson\nJosh Cannon\nJosh Hansen\nJosh Schneier\nJoshua\nJoshuaPerdue\nJuan Luis Cano Rodríguez\nJuanjo Bazán\nJudah Rand\nJulian Berman\nJulian Gethmann\nJulien Demoor\nJuly Tikhonov\nJussi Kukkonen\nJustin van Heek\njwg4\nJyrki Pulliainen\nKai Chen\nKai Mueller\nKamal Bin Mustafa\nKarolina Surma\nkasium\nkaustav haldar\nkeanemind\nKeith Maxwell\nKelsey Hightower\nKenneth Belitzky\nKenneth Reitz\nKevin Burke\nKevin Carter\nKevin Frommelt\nKevin R Patterson\nKexuan Sun\nKit Randel\nKlaas van Schelven\nKOLANICH\nkonstin\nkpinc\nKrishan Bhasin\nKrishna Oza\nKumar McMillan\nKuntal Majumder\nKurt McKee\nKyle Persohn\nlakshmanaram\nLaszlo Kiss-Kollar\nLaurent Bristiel\nLaurent LAPORTE\nLaurie O\nLaurie Opperman\nlayday\nLeon Sasson\nLev Givon\nLincoln de Sousa\nLipis\nlorddavidiii\nLoren Carvalho\nLucas Cimon\nLudovic Gasc\nLuis Medel\nLukas Geiger\nLukas Juhrich\nLuke Macken\nLuo Jiebin\nluojiebin\nluz.paz\nLászló Kiss Kollár\nM00nL1ght\nMalcolm Smith\nMarc Abramowitz\nMarc Tamlyn\nMarcus Smith\nMariatta\nMark Kohler\nMark McLoughlin\nMark Williams\nMarkus Hametner\nMartey Dodoo\nMartin Fischer\nMartin Häcker\nMartin Pavlasek\nMasaki\nMasklinn\nMatej Stuchlik\nMathew Jennings\nMathieu Bridon\nMathieu Kniewallner\nMatt Bacchi\nMatt Good\nMatt Maker\nMatt Robenolt\nMatt Wozniski\nmatthew\nMatthew Einhorn\nMatthew Feickert\nMatthew Gilliard\nMatthew Hughes\nMatthew Iversen\nMatthew Treinish\nMatthew Trumbell\nMatthew Willson\nMatthias Bussonnier\nmattip\nMaurits van Rees\nMax W Chase\nMaxim Kurnikov\nMaxime Rouyrre\nmayeut\nmbaluna\nMd Sujauddin Sekh\nmdebi\nmemoselyk\nmeowmeowcat\nMichael\nMichael Aquilina\nMichael E. Karpeles\nMichael Klich\nMichael Mintz\nMichael Williamson\nmichaelpacer\nMichał Górny\nMickaël Schoentgen\nMiguel Araujo Perez\nMihir Singh\nMike\nMike Hendricks\nMin RK\nMinRK\nMiro Hrončok\nMonica Baluna\nmontefra\nMonty Taylor\nmorotti\nmrKazzila\nMuha Ajjan\nNadav Wexler\nNahuel Ambrosini\nNate Coraor\nNate Prewitt\nNathan Houghton\nNathaniel J. Smith\nNehal J Wani\nNeil Botelho\nNguyễn Gia Phong\nNicholas Serra\nNick Coghlan\nNick Stenning\nNick Timkovich\nNicolas Bock\nNicole Harris\nNikhil Benesch\nNikhil Ladha\nNikita Chepanov\nNikolay Korolev\nNipunn Koorapati\nNitesh Sharma\nNiyas Sait\nNoah\nNoah Gorny\nNowell Strite\nNtaleGrey\nnucccc\nnvdv\nOBITORASU\nOfek Lev\nofrinevo\nOleg Burnaev\nOliver Freund\nOliver Jeeves\nOliver Mannion\nOliver Tonnhofer\nOlivier Girardot\nOlivier Grisel\nOllie Rutherfurd\nOMOTO Kenji\nOmry Yadan\nonlinejudge95\nOren Held\nOscar Benjamin\nOz N Tiram\nPachwenko\nPatrick Dubroy\nPatrick Jenkins\nPatrick Lawson\npatricktokeeffe\nPatrik Kopkan\nPaul Ganssle\nPaul Kehrer\nPaul Moore\nPaul Nasrat\nPaul Oswald\nPaul van der Linden\nPaulus Schoutsen\nPavel Safronov\nPavithra Eswaramoorthy\nPawel Jasinski\nPaweł Szramowski\nPekka Klärck\nPeter Gessler\nPeter Lisák\nPeter Shen\nPeter Waller\nPetr Viktorin\npetr-tik\nPhaneendra Chiruvella\nPhil Elson\nPhil Freo\nPhil Pennock\nPhil Whelan\nPhilip Jägenstedt\nPhilip Molloy\nPhilippe Ombredanne\nPi Delport\nPierre-Yves Rofes\nPieter Degroote\npip\nPrabakaran Kumaresshan\nPrabhjyotsing Surjit Singh Sodhi\nPrabhu Marappan\nPradyun Gedam\nPrashant Sharma\nPratik Mallya\npre-commit-ci[bot]\nPreet Thakkar\nPreston Holmes\nPrzemek Wrzos\nPulkit Goyal\nq0w\nQiangning Hong\nQiming Xu\nQuentin Lee\nQuentin Pradet\nR. David Murray\nRafael Caricio\nRalf Schmitt\nRan Benita\nRandy Döring\nRazzi Abuissa\nrdb\nReece Dunham\nRemi Rampin\nRene Dudfield\nRiccardo Magliocchetti\nRiccardo Schirone\nRichard Jones\nRichard Si\nRicky Ng-Adam\nRishi\nrmorotti\nRobberPhex\nRobert Collins\nRobert McGibbon\nRobert Pollak\nRobert T. McGibbon\nrobin elisha robinson\nRoey Berman\nRohan Jain\nRoman Bogorodskiy\nRoman Donchenko\nRomuald Brunet\nronaudinho\nRonny Pfannschmidt\nRory McCann\nRoss Brattain\nRoy Wellington Ⅳ\nRuairidh MacLeod\nRussell Keith-Magee\nRyan Shepherd\nRyan Wooden\nryneeverett\nS. Guliaev\nSachi King\nSalvatore Rinchiera\nsandeepkiran-js\nSander Van Balen\nSavio Jomton\nschlamar\nScott Kitterman\nSean\nseanj\nSebastian Jordan\nSebastian Schaetz\nSegev Finer\nSeongSoo Cho\nSergey Vasilyev\nSeth Michael Larson\nSeth Woodworth\nShahar Epstein\nShantanu\nshenxianpeng\nshireenrao\nShivansh-007\nShixian Sheng\nShlomi Fish\nShovan Maity\nSimeon Visser\nSimon Cross\nSimon Pichugin\nsinoroc\nsinscary\nsnook92\nsocketubs\nSorin Sbarnea\nSrinivas Nyayapati\nSrishti Hegde\nStavros Korokithakis\nStefan Scherfke\nStefano Rivera\nStephan Erb\nStephen Rosen\nstepshal\nSteve (Gadget) Barnes\nSteve Barnes\nSteve Dower\nSteve Kowalik\nSteven Myint\nSteven Silvester\nstonebig\nstudioj\nStéphane Bidoul\nStéphane Bidoul (ACSONE)\nStéphane Klein\nSumana Harihareswara\nSurbhi Sharma\nSviatoslav Sydorenko\nSviatoslav Sydorenko (Святослав Сидоренко)\nSwat009\nSylvain\nTakayuki SHIMIZUKAWA\nTaneli Hukkinen\ntbeswick\nThiago\nThijs Triemstra\nThomas Fenzl\nThomas Grainger\nThomas Guettler\nThomas Johansson\nThomas Kluyver\nThomas Smith\nThomas VINCENT\nTim D. Smith\nTim Gates\nTim Harder\nTim Heap\ntim smith\ntinruufu\nTobias Hermann\nTom Forbes\nTom Freudenheim\nTom V\nTomas Hrnciar\nTomas Orsava\nTomer Chachamu\nTommi Enenkel | AnB\nTomáš Hrnčiar\nTony Beswick\nTony Narlock\nTony Zhaocheng Tan\nTonyBeswick\ntoonarmycaptain\nToshio Kuratomi\ntoxinu\nTravis Swicegood\nTushar Sadhwani\nTzu-ping Chung\nValentin Haenel\nVictor Stinner\nvictorvpaulo\nVikram - Google\nViktor Szépe\nVille Skyttä\nVinay Sajip\nVincent Philippon\nVinicyus Macedo\nVipul Kumar\nVitaly Babiy\nVladimir Fokow\nVladimir Rutsky\nW. Trevor King\nWil Tan\nWilfred Hughes\nWilliam Edwards\nWilliam ML Leslie\nWilliam T Olson\nWilliam Woodruff\nWilson Mo\nwim glenn\nWinson Luk\nWolfgang Maier\nWu Zhenyu\nXAMES3\nXavier Fernandez\nXianpeng Shen\nxoviat\nxtreak\nYAMAMOTO Takashi\nYen Chi Hsuan\nYeray Diaz Diaz\nYoval P\nYu Jian\nYuan Jing Vincent Yan\nYusuke Hayashi\nZearin\nZhiping Deng\nziebam\nZvezdan Petkovic\nŁukasz Langa\nРоман Донченко\nСемён Марьясин\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\licenses\AUTHORS.txt | AUTHORS.txt | Other | 11,223 | 0.7 | 0 | 0 | python-kit | 411 | 2024-05-07T06:29:24.277635 | Apache-2.0 | false | b0638132ad6e433f77c08dad6c64556b |
Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n"Software"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n | .venv\Lib\site-packages\pip-25.1.1.dist-info\licenses\LICENSE.txt | LICENSE.txt | Other | 1,093 | 0.7 | 0 | 0 | vue-tools | 555 | 2024-11-27T22:17:06.179947 | BSD-3-Clause | false | 63ec52baf95163b597008bb46db68030 |
Pluggable Distributions of Python Software\n==========================================\n\nDistributions\n-------------\n\nA "Distribution" is a collection of files that represent a "Release" of a\n"Project" as of a particular point in time, denoted by a\n"Version"::\n\n >>> import sys, pkg_resources\n >>> from pkg_resources import Distribution\n >>> Distribution(project_name="Foo", version="1.2")\n Foo 1.2\n\nDistributions have a location, which can be a filename, URL, or really anything\nelse you care to use::\n\n >>> dist = Distribution(\n ... location="http://example.com/something",\n ... project_name="Bar", version="0.9"\n ... )\n\n >>> dist\n Bar 0.9 (http://example.com/something)\n\n\nDistributions have various introspectable attributes::\n\n >>> dist.location\n 'http://example.com/something'\n\n >>> dist.project_name\n 'Bar'\n\n >>> dist.version\n '0.9'\n\n >>> dist.py_version == '{}.{}'.format(*sys.version_info)\n True\n\n >>> print(dist.platform)\n None\n\nIncluding various computed attributes::\n\n >>> from pkg_resources import parse_version\n >>> dist.parsed_version == parse_version(dist.version)\n True\n\n >>> dist.key # case-insensitive form of the project name\n 'bar'\n\nDistributions are compared (and hashed) by version first::\n\n >>> Distribution(version='1.0') == Distribution(version='1.0')\n True\n >>> Distribution(version='1.0') == Distribution(version='1.1')\n False\n >>> Distribution(version='1.0') < Distribution(version='1.1')\n True\n\nbut also by project name (case-insensitive), platform, Python version,\nlocation, etc.::\n\n >>> Distribution(project_name="Foo",version="1.0") == \\n ... Distribution(project_name="Foo",version="1.0")\n True\n\n >>> Distribution(project_name="Foo",version="1.0") == \\n ... Distribution(project_name="foo",version="1.0")\n True\n\n >>> Distribution(project_name="Foo",version="1.0") == \\n ... Distribution(project_name="Foo",version="1.1")\n False\n\n >>> Distribution(project_name="Foo",py_version="2.3",version="1.0") == \\n ... Distribution(project_name="Foo",py_version="2.4",version="1.0")\n False\n\n >>> Distribution(location="spam",version="1.0") == \\n ... Distribution(location="spam",version="1.0")\n True\n\n >>> Distribution(location="spam",version="1.0") == \\n ... Distribution(location="baz",version="1.0")\n False\n\n\n\nHash and compare distribution by prio/plat\n\nGet version from metadata\nprovider capabilities\negg_name()\nas_requirement()\nfrom_location, from_filename (w/path normalization)\n\nReleases may have zero or more "Requirements", which indicate\nwhat releases of another project the release requires in order to\nfunction. A Requirement names the other project, expresses some criteria\nas to what releases of that project are acceptable, and lists any "Extras"\nthat the requiring release may need from that project. (An Extra is an\noptional feature of a Release, that can only be used if its additional\nRequirements are satisfied.)\n\n\n\nThe Working Set\n---------------\n\nA collection of active distributions is called a Working Set. Note that a\nWorking Set can contain any importable distribution, not just pluggable ones.\nFor example, the Python standard library is an importable distribution that\nwill usually be part of the Working Set, even though it is not pluggable.\nSimilarly, when you are doing development work on a project, the files you are\nediting are also a Distribution. (And, with a little attention to the\ndirectory names used, and including some additional metadata, such a\n"development distribution" can be made pluggable as well.)\n\n >>> from pkg_resources import WorkingSet\n\nA working set's entries are the sys.path entries that correspond to the active\ndistributions. By default, the working set's entries are the items on\n``sys.path``::\n\n >>> ws = WorkingSet()\n >>> ws.entries == sys.path\n True\n\nBut you can also create an empty working set explicitly, and add distributions\nto it::\n\n >>> ws = WorkingSet([])\n >>> ws.add(dist)\n >>> ws.entries\n ['http://example.com/something']\n >>> dist in ws\n True\n >>> Distribution('foo',version="") in ws\n False\n\nAnd you can iterate over its distributions::\n\n >>> list(ws)\n [Bar 0.9 (http://example.com/something)]\n\nAdding the same distribution more than once is a no-op::\n\n >>> ws.add(dist)\n >>> list(ws)\n [Bar 0.9 (http://example.com/something)]\n\nFor that matter, adding multiple distributions for the same project also does\nnothing, because a working set can only hold one active distribution per\nproject -- the first one added to it::\n\n >>> ws.add(\n ... Distribution(\n ... 'http://example.com/something', project_name="Bar",\n ... version="7.2"\n ... )\n ... )\n >>> list(ws)\n [Bar 0.9 (http://example.com/something)]\n\nYou can append a path entry to a working set using ``add_entry()``::\n\n >>> ws.entries\n ['http://example.com/something']\n >>> ws.add_entry(pkg_resources.__file__)\n >>> ws.entries\n ['http://example.com/something', '...pkg_resources...']\n\nMultiple additions result in multiple entries, even if the entry is already in\nthe working set (because ``sys.path`` can contain the same entry more than\nonce)::\n\n >>> ws.add_entry(pkg_resources.__file__)\n >>> ws.entries\n ['...example.com...', '...pkg_resources...', '...pkg_resources...']\n\nAnd you can specify the path entry a distribution was found under, using the\noptional second parameter to ``add()``::\n\n >>> ws = WorkingSet([])\n >>> ws.add(dist,"foo")\n >>> ws.entries\n ['foo']\n\nBut even if a distribution is found under multiple path entries, it still only\nshows up once when iterating the working set:\n\n >>> ws.add_entry(ws.entries[0])\n >>> list(ws)\n [Bar 0.9 (http://example.com/something)]\n\nYou can ask a WorkingSet to ``find()`` a distribution matching a requirement::\n\n >>> from pkg_resources import Requirement\n >>> print(ws.find(Requirement.parse("Foo==1.0"))) # no match, return None\n None\n\n >>> ws.find(Requirement.parse("Bar==0.9")) # match, return distribution\n Bar 0.9 (http://example.com/something)\n\nNote that asking for a conflicting version of a distribution already in a\nworking set triggers a ``pkg_resources.VersionConflict`` error:\n\n >>> try:\n ... ws.find(Requirement.parse("Bar==1.0"))\n ... except pkg_resources.VersionConflict as exc:\n ... print(str(exc))\n ... else:\n ... raise AssertionError("VersionConflict was not raised")\n (Bar 0.9 (http://example.com/something), Requirement.parse('Bar==1.0'))\n\nYou can subscribe a callback function to receive notifications whenever a new\ndistribution is added to a working set. The callback is immediately invoked\nonce for each existing distribution in the working set, and then is called\nagain for new distributions added thereafter::\n\n >>> def added(dist): print("Added %s" % dist)\n >>> ws.subscribe(added)\n Added Bar 0.9\n >>> foo12 = Distribution(project_name="Foo", version="1.2", location="f12")\n >>> ws.add(foo12)\n Added Foo 1.2\n\nNote, however, that only the first distribution added for a given project name\nwill trigger a callback, even during the initial ``subscribe()`` callback::\n\n >>> foo14 = Distribution(project_name="Foo", version="1.4", location="f14")\n >>> ws.add(foo14) # no callback, because Foo 1.2 is already active\n\n >>> ws = WorkingSet([])\n >>> ws.add(foo12)\n >>> ws.add(foo14)\n >>> ws.subscribe(added)\n Added Foo 1.2\n\nAnd adding a callback more than once has no effect, either::\n\n >>> ws.subscribe(added) # no callbacks\n\n # and no double-callbacks on subsequent additions, either\n >>> just_a_test = Distribution(project_name="JustATest", version="0.99")\n >>> ws.add(just_a_test)\n Added JustATest 0.99\n\n\nFinding Plugins\n---------------\n\n``WorkingSet`` objects can be used to figure out what plugins in an\n``Environment`` can be loaded without any resolution errors::\n\n >>> from pkg_resources import Environment\n\n >>> plugins = Environment([]) # normally, a list of plugin directories\n >>> plugins.add(foo12)\n >>> plugins.add(foo14)\n >>> plugins.add(just_a_test)\n\nIn the simplest case, we just get the newest version of each distribution in\nthe plugin environment::\n\n >>> ws = WorkingSet([])\n >>> ws.find_plugins(plugins)\n ([JustATest 0.99, Foo 1.4 (f14)], {})\n\nBut if there's a problem with a version conflict or missing requirements, the\nmethod falls back to older versions, and the error info dict will contain an\nexception instance for each unloadable plugin::\n\n >>> ws.add(foo12) # this will conflict with Foo 1.4\n >>> ws.find_plugins(plugins)\n ([JustATest 0.99, Foo 1.2 (f12)], {Foo 1.4 (f14): VersionConflict(...)})\n\nBut if you disallow fallbacks, the failed plugin will be skipped instead of\ntrying older versions::\n\n >>> ws.find_plugins(plugins, fallback=False)\n ([JustATest 0.99], {Foo 1.4 (f14): VersionConflict(...)})\n\n\n\nPlatform Compatibility Rules\n----------------------------\n\nOn the Mac, there are potential compatibility issues for modules compiled\non newer versions of macOS than what the user is running. Additionally,\nmacOS will soon have two platforms to contend with: Intel and PowerPC.\n\nBasic equality works as on other platforms::\n\n >>> from pkg_resources import compatible_platforms as cp\n >>> reqd = 'macosx-10.4-ppc'\n >>> cp(reqd, reqd)\n True\n >>> cp("win32", reqd)\n False\n\nDistributions made on other machine types are not compatible::\n\n >>> cp("macosx-10.4-i386", reqd)\n False\n\nDistributions made on earlier versions of the OS are compatible, as\nlong as they are from the same top-level version. The patchlevel version\nnumber does not matter::\n\n >>> cp("macosx-10.4-ppc", reqd)\n True\n >>> cp("macosx-10.3-ppc", reqd)\n True\n >>> cp("macosx-10.5-ppc", reqd)\n False\n >>> cp("macosx-9.5-ppc", reqd)\n False\n\nBackwards compatibility for packages made via earlier versions of\nsetuptools is provided as well::\n\n >>> cp("darwin-8.2.0-Power_Macintosh", reqd)\n True\n >>> cp("darwin-7.2.0-Power_Macintosh", reqd)\n True\n >>> cp("darwin-8.2.0-Power_Macintosh", "macosx-10.3-ppc")\n False\n\n\nEnvironment Markers\n-------------------\n\n >>> from pkg_resources import invalid_marker as im, evaluate_marker as em\n >>> import os\n\n >>> print(im("sys_platform"))\n Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in\n sys_platform\n ^\n\n >>> print(im("sys_platform=="))\n Expected a marker variable or quoted string\n sys_platform==\n ^\n\n >>> print(im("sys_platform=='win32'"))\n False\n\n >>> print(im("sys=='x'"))\n Expected a marker variable or quoted string\n sys=='x'\n ^\n\n >>> print(im("(extra)"))\n Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in\n (extra)\n ^\n\n >>> print(im("(extra"))\n Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in\n (extra\n ^\n\n >>> print(im("os.open('foo')=='y'"))\n Expected a marker variable or quoted string\n os.open('foo')=='y'\n ^\n\n >>> print(im("'x'=='y' and os.open('foo')=='y'")) # no short-circuit!\n Expected a marker variable or quoted string\n 'x'=='y' and os.open('foo')=='y'\n ^\n\n >>> print(im("'x'=='x' or os.open('foo')=='y'")) # no short-circuit!\n Expected a marker variable or quoted string\n 'x'=='x' or os.open('foo')=='y'\n ^\n\n >>> print(im("r'x'=='x'"))\n Expected a marker variable or quoted string\n r'x'=='x'\n ^\n\n >>> print(im("'''x'''=='x'"))\n Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in\n '''x'''=='x'\n ^\n\n >>> print(im('"""x"""=="x"'))\n Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in\n """x"""=="x"\n ^\n\n >>> print(im(r"x\n=='x'"))\n Expected a marker variable or quoted string\n x\n=='x'\n ^\n\n >>> print(im("os.open=='y'"))\n Expected a marker variable or quoted string\n os.open=='y'\n ^\n\n >>> em("sys_platform=='win32'") == (sys.platform=='win32')\n True\n\n >>> em("python_version >= '2.7'")\n True\n\n >>> em("python_version > '2.6'")\n True\n\n >>> im("implementation_name=='cpython'")\n False\n\n >>> im("platform_python_implementation=='CPython'")\n False\n\n >>> im("implementation_version=='3.5.1'")\n False\n | .venv\Lib\site-packages\pkg_resources\api_tests.txt | api_tests.txt | Other | 12,595 | 0.95 | 0.040094 | 0.003205 | node-utils | 29 | 2025-04-10T13:09:29.112421 | MIT | true | 77459c19444030a0926f523388fa4ef8 |
import shutil\nfrom pathlib import Path\n\nimport pytest\n\nimport pkg_resources\n\nTESTS_DATA_DIR = Path(__file__).parent / 'data'\n\n\nclass TestFindDistributions:\n @pytest.fixture\n def target_dir(self, tmpdir):\n target_dir = tmpdir.mkdir('target')\n # place a .egg named directory in the target that is not an egg:\n target_dir.mkdir('not.an.egg')\n return target_dir\n\n def test_non_egg_dir_named_egg(self, target_dir):\n dists = pkg_resources.find_distributions(str(target_dir))\n assert not list(dists)\n\n def test_standalone_egg_directory(self, target_dir):\n shutil.copytree(\n TESTS_DATA_DIR / 'my-test-package_unpacked-egg',\n target_dir,\n dirs_exist_ok=True,\n )\n dists = pkg_resources.find_distributions(str(target_dir))\n assert [dist.project_name for dist in dists] == ['my-test-package']\n dists = pkg_resources.find_distributions(str(target_dir), only=True)\n assert not list(dists)\n\n def test_zipped_egg(self, target_dir):\n shutil.copytree(\n TESTS_DATA_DIR / 'my-test-package_zipped-egg',\n target_dir,\n dirs_exist_ok=True,\n )\n dists = pkg_resources.find_distributions(str(target_dir))\n assert [dist.project_name for dist in dists] == ['my-test-package']\n dists = pkg_resources.find_distributions(str(target_dir), only=True)\n assert not list(dists)\n\n def test_zipped_sdist_one_level_removed(self, target_dir):\n shutil.copytree(\n TESTS_DATA_DIR / 'my-test-package-zip', target_dir, dirs_exist_ok=True\n )\n dists = pkg_resources.find_distributions(\n str(target_dir / "my-test-package.zip")\n )\n assert [dist.project_name for dist in dists] == ['my-test-package']\n dists = pkg_resources.find_distributions(\n str(target_dir / "my-test-package.zip"), only=True\n )\n assert not list(dists)\n | .venv\Lib\site-packages\pkg_resources\tests\test_find_distributions.py | test_find_distributions.py | Python | 1,972 | 0.95 | 0.160714 | 0.021277 | vue-tools | 49 | 2025-01-25T19:50:54.603678 | Apache-2.0 | true | bcb1a09e9681087b76b9926f9e64035d |
import platform\nfrom inspect import cleandoc\n\nimport jaraco.path\nimport pytest\n\npytestmark = pytest.mark.integration\n\n\n# For the sake of simplicity this test uses fixtures defined in\n# `setuptools.test.fixtures`,\n# and it also exercise conditions considered deprecated...\n# So if needed this test can be deleted.\n@pytest.mark.skipif(\n platform.system() != "Linux",\n reason="only demonstrated to fail on Linux in #4399",\n)\ndef test_interop_pkg_resources_iter_entry_points(tmp_path, venv):\n """\n Importing pkg_resources.iter_entry_points on console_scripts\n seems to cause trouble with zope-interface, when deprecates installation method\n is used. See #4399.\n """\n project = {\n "pkg": {\n "foo.py": cleandoc(\n """\n from pkg_resources import iter_entry_points\n\n def bar():\n print("Print me if you can")\n """\n ),\n "setup.py": cleandoc(\n """\n from setuptools import setup, find_packages\n\n setup(\n install_requires=["zope-interface==6.4.post2"],\n entry_points={\n "console_scripts": [\n "foo=foo:bar",\n ],\n },\n )\n """\n ),\n }\n }\n jaraco.path.build(project, prefix=tmp_path)\n cmd = ["pip", "install", "-e", ".", "--no-use-pep517"]\n venv.run(cmd, cwd=tmp_path / "pkg") # Needs this version of pkg_resources installed\n out = venv.run(["foo"])\n assert "Print me if you can" in out\n | .venv\Lib\site-packages\pkg_resources\tests\test_integration_zope_interface.py | test_integration_zope_interface.py | Python | 1,652 | 0.95 | 0.092593 | 0.083333 | awesome-app | 740 | 2024-08-24T07:26:17.793015 | GPL-3.0 | true | c837402849bc2eb66205766d3db1c883 |
from unittest import mock\n\nfrom pkg_resources import evaluate_marker\n\n\n@mock.patch('platform.python_version', return_value='2.7.10')\ndef test_ordering(python_version_mock):\n assert evaluate_marker("python_full_version > '2.7.3'") is True\n | .venv\Lib\site-packages\pkg_resources\tests\test_markers.py | test_markers.py | Python | 241 | 0.85 | 0.125 | 0 | react-lib | 367 | 2024-04-23T03:03:25.612140 | Apache-2.0 | true | 9dbfa3017f2ecff404c22a63eaa05930 |
from __future__ import annotations\n\nimport builtins\nimport datetime\nimport inspect\nimport os\nimport plistlib\nimport stat\nimport subprocess\nimport sys\nimport tempfile\nimport zipfile\nfrom unittest import mock\n\nimport pytest\n\nimport pkg_resources\nfrom pkg_resources import DistInfoDistribution, Distribution, EggInfoDistribution\n\nimport distutils.command.install_egg_info\nimport distutils.dist\n\n\nclass EggRemover(str):\n def __call__(self):\n if self in sys.path:\n sys.path.remove(self)\n if os.path.exists(self):\n os.remove(self)\n\n\nclass TestZipProvider:\n finalizers: list[EggRemover] = []\n\n ref_time = datetime.datetime(2013, 5, 12, 13, 25, 0)\n "A reference time for a file modification"\n\n @classmethod\n def setup_class(cls):\n "create a zip egg and add it to sys.path"\n egg = tempfile.NamedTemporaryFile(suffix='.egg', delete=False)\n zip_egg = zipfile.ZipFile(egg, 'w')\n zip_info = zipfile.ZipInfo()\n zip_info.filename = 'mod.py'\n zip_info.date_time = cls.ref_time.timetuple()\n zip_egg.writestr(zip_info, 'x = 3\n')\n zip_info = zipfile.ZipInfo()\n zip_info.filename = 'data.dat'\n zip_info.date_time = cls.ref_time.timetuple()\n zip_egg.writestr(zip_info, 'hello, world!')\n zip_info = zipfile.ZipInfo()\n zip_info.filename = 'subdir/mod2.py'\n zip_info.date_time = cls.ref_time.timetuple()\n zip_egg.writestr(zip_info, 'x = 6\n')\n zip_info = zipfile.ZipInfo()\n zip_info.filename = 'subdir/data2.dat'\n zip_info.date_time = cls.ref_time.timetuple()\n zip_egg.writestr(zip_info, 'goodbye, world!')\n zip_egg.close()\n egg.close()\n\n sys.path.append(egg.name)\n subdir = os.path.join(egg.name, 'subdir')\n sys.path.append(subdir)\n cls.finalizers.append(EggRemover(subdir))\n cls.finalizers.append(EggRemover(egg.name))\n\n @classmethod\n def teardown_class(cls):\n for finalizer in cls.finalizers:\n finalizer()\n\n def test_resource_listdir(self):\n import mod # pyright: ignore[reportMissingImports] # Temporary package for test\n\n zp = pkg_resources.ZipProvider(mod)\n\n expected_root = ['data.dat', 'mod.py', 'subdir']\n assert sorted(zp.resource_listdir('')) == expected_root\n\n expected_subdir = ['data2.dat', 'mod2.py']\n assert sorted(zp.resource_listdir('subdir')) == expected_subdir\n assert sorted(zp.resource_listdir('subdir/')) == expected_subdir\n\n assert zp.resource_listdir('nonexistent') == []\n assert zp.resource_listdir('nonexistent/') == []\n\n import mod2 # pyright: ignore[reportMissingImports] # Temporary package for test\n\n zp2 = pkg_resources.ZipProvider(mod2)\n\n assert sorted(zp2.resource_listdir('')) == expected_subdir\n\n assert zp2.resource_listdir('subdir') == []\n assert zp2.resource_listdir('subdir/') == []\n\n def test_resource_filename_rewrites_on_change(self):\n """\n If a previous call to get_resource_filename has saved the file, but\n the file has been subsequently mutated with different file of the\n same size and modification time, it should not be overwritten on a\n subsequent call to get_resource_filename.\n """\n import mod # pyright: ignore[reportMissingImports] # Temporary package for test\n\n manager = pkg_resources.ResourceManager()\n zp = pkg_resources.ZipProvider(mod)\n filename = zp.get_resource_filename(manager, 'data.dat')\n actual = datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)\n assert actual == self.ref_time\n f = open(filename, 'w', encoding="utf-8")\n f.write('hello, world?')\n f.close()\n ts = self.ref_time.timestamp()\n os.utime(filename, (ts, ts))\n filename = zp.get_resource_filename(manager, 'data.dat')\n with open(filename, encoding="utf-8") as f:\n assert f.read() == 'hello, world!'\n manager.cleanup_resources()\n\n\nclass TestResourceManager:\n def test_get_cache_path(self):\n mgr = pkg_resources.ResourceManager()\n path = mgr.get_cache_path('foo')\n type_ = str(type(path))\n message = "Unexpected type from get_cache_path: " + type_\n assert isinstance(path, str), message\n\n def test_get_cache_path_race(self, tmpdir):\n # Patch to os.path.isdir to create a race condition\n def patched_isdir(dirname, unpatched_isdir=pkg_resources.isdir):\n patched_isdir.dirnames.append(dirname)\n\n was_dir = unpatched_isdir(dirname)\n if not was_dir:\n os.makedirs(dirname)\n return was_dir\n\n patched_isdir.dirnames = []\n\n # Get a cache path with a "race condition"\n mgr = pkg_resources.ResourceManager()\n mgr.set_extraction_path(str(tmpdir))\n\n archive_name = os.sep.join(('foo', 'bar', 'baz'))\n with mock.patch.object(pkg_resources, 'isdir', new=patched_isdir):\n mgr.get_cache_path(archive_name)\n\n # Because this test relies on the implementation details of this\n # function, these assertions are a sentinel to ensure that the\n # test suite will not fail silently if the implementation changes.\n called_dirnames = patched_isdir.dirnames\n assert len(called_dirnames) == 2\n assert called_dirnames[0].split(os.sep)[-2:] == ['foo', 'bar']\n assert called_dirnames[1].split(os.sep)[-1:] == ['foo']\n\n """\n Tests to ensure that pkg_resources runs independently from setuptools.\n """\n\n def test_setuptools_not_imported(self):\n """\n In a separate Python environment, import pkg_resources and assert\n that action doesn't cause setuptools to be imported.\n """\n lines = (\n 'import pkg_resources',\n 'import sys',\n ('assert "setuptools" not in sys.modules, "setuptools was imported"'),\n )\n cmd = [sys.executable, '-c', '; '.join(lines)]\n subprocess.check_call(cmd)\n\n\ndef make_test_distribution(metadata_path, metadata):\n """\n Make a test Distribution object, and return it.\n\n :param metadata_path: the path to the metadata file that should be\n created. This should be inside a distribution directory that should\n also be created. For example, an argument value might end with\n "<project>.dist-info/METADATA".\n :param metadata: the desired contents of the metadata file, as bytes.\n """\n dist_dir = os.path.dirname(metadata_path)\n os.mkdir(dist_dir)\n with open(metadata_path, 'wb') as f:\n f.write(metadata)\n dists = list(pkg_resources.distributions_from_metadata(dist_dir))\n (dist,) = dists\n\n return dist\n\n\ndef test_get_metadata__bad_utf8(tmpdir):\n """\n Test a metadata file with bytes that can't be decoded as utf-8.\n """\n filename = 'METADATA'\n # Convert the tmpdir LocalPath object to a string before joining.\n metadata_path = os.path.join(str(tmpdir), 'foo.dist-info', filename)\n # Encode a non-ascii string with the wrong encoding (not utf-8).\n metadata = 'née'.encode('iso-8859-1')\n dist = make_test_distribution(metadata_path, metadata=metadata)\n\n with pytest.raises(UnicodeDecodeError) as excinfo:\n dist.get_metadata(filename)\n\n exc = excinfo.value\n actual = str(exc)\n expected = (\n # The error message starts with "'utf-8' codec ..." However, the\n # spelling of "utf-8" can vary (e.g. "utf8") so we don't include it\n "codec can't decode byte 0xe9 in position 1: "\n 'invalid continuation byte in METADATA file at path: '\n )\n assert expected in actual, f'actual: {actual}'\n assert actual.endswith(metadata_path), f'actual: {actual}'\n\n\ndef make_distribution_no_version(tmpdir, basename):\n """\n Create a distribution directory with no file containing the version.\n """\n dist_dir = tmpdir / basename\n dist_dir.ensure_dir()\n # Make the directory non-empty so distributions_from_metadata()\n # will detect it and yield it.\n dist_dir.join('temp.txt').ensure()\n\n dists = list(pkg_resources.distributions_from_metadata(dist_dir))\n assert len(dists) == 1\n (dist,) = dists\n\n return dist, dist_dir\n\n\n@pytest.mark.parametrize(\n ("suffix", "expected_filename", "expected_dist_type"),\n [\n ('egg-info', 'PKG-INFO', EggInfoDistribution),\n ('dist-info', 'METADATA', DistInfoDistribution),\n ],\n)\n@pytest.mark.xfail(\n sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final',\n reason="https://github.com/python/cpython/issues/103632",\n)\ndef test_distribution_version_missing(\n tmpdir, suffix, expected_filename, expected_dist_type\n):\n """\n Test Distribution.version when the "Version" header is missing.\n """\n basename = f'foo.{suffix}'\n dist, dist_dir = make_distribution_no_version(tmpdir, basename)\n\n expected_text = (\n f"Missing 'Version:' header and/or {expected_filename} file at path: "\n )\n metadata_path = os.path.join(dist_dir, expected_filename)\n\n # Now check the exception raised when the "version" attribute is accessed.\n with pytest.raises(ValueError) as excinfo:\n dist.version\n\n err = str(excinfo.value)\n # Include a string expression after the assert so the full strings\n # will be visible for inspection on failure.\n assert expected_text in err, str((expected_text, err))\n\n # Also check the args passed to the ValueError.\n msg, dist = excinfo.value.args\n assert expected_text in msg\n # Check that the message portion contains the path.\n assert metadata_path in msg, str((metadata_path, msg))\n assert type(dist) is expected_dist_type\n\n\n@pytest.mark.xfail(\n sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final',\n reason="https://github.com/python/cpython/issues/103632",\n)\ndef test_distribution_version_missing_undetected_path():\n """\n Test Distribution.version when the "Version" header is missing and\n the path can't be detected.\n """\n # Create a Distribution object with no metadata argument, which results\n # in an empty metadata provider.\n dist = Distribution('/foo')\n with pytest.raises(ValueError) as excinfo:\n dist.version\n\n msg, dist = excinfo.value.args\n expected = (\n "Missing 'Version:' header and/or PKG-INFO file at path: [could not detect]"\n )\n assert msg == expected\n\n\n@pytest.mark.parametrize('only', [False, True])\ndef test_dist_info_is_not_dir(tmp_path, only):\n """Test path containing a file with dist-info extension."""\n dist_info = tmp_path / 'foobar.dist-info'\n dist_info.touch()\n assert not pkg_resources.dist_factory(str(tmp_path), str(dist_info), only)\n\n\ndef test_macos_vers_fallback(monkeypatch, tmp_path):\n """Regression test for pkg_resources._macos_vers"""\n orig_open = builtins.open\n\n # Pretend we need to use the plist file\n monkeypatch.setattr('platform.mac_ver', mock.Mock(return_value=('', (), '')))\n\n # Create fake content for the fake plist file\n with open(tmp_path / 'fake.plist', 'wb') as fake_file:\n plistlib.dump({"ProductVersion": "11.4"}, fake_file)\n\n # Pretend the fake file exists\n monkeypatch.setattr('os.path.exists', mock.Mock(return_value=True))\n\n def fake_open(file, *args, **kwargs):\n return orig_open(tmp_path / 'fake.plist', *args, **kwargs)\n\n # Ensure that the _macos_vers works correctly\n with mock.patch('builtins.open', mock.Mock(side_effect=fake_open)) as m:\n pkg_resources._macos_vers.cache_clear()\n assert pkg_resources._macos_vers() == ["11", "4"]\n pkg_resources._macos_vers.cache_clear()\n\n m.assert_called()\n\n\nclass TestDeepVersionLookupDistutils:\n @pytest.fixture\n def env(self, tmpdir):\n """\n Create a package environment, similar to a virtualenv,\n in which packages are installed.\n """\n\n class Environment(str):\n pass\n\n env = Environment(tmpdir)\n tmpdir.chmod(stat.S_IRWXU)\n subs = 'home', 'lib', 'scripts', 'data', 'egg-base'\n env.paths = dict((dirname, str(tmpdir / dirname)) for dirname in subs)\n list(map(os.mkdir, env.paths.values()))\n return env\n\n def create_foo_pkg(self, env, version):\n """\n Create a foo package installed (distutils-style) to env.paths['lib']\n as version.\n """\n ld = "This package has unicode metadata! ❄"\n attrs = dict(name='foo', version=version, long_description=ld)\n dist = distutils.dist.Distribution(attrs)\n iei_cmd = distutils.command.install_egg_info.install_egg_info(dist)\n iei_cmd.initialize_options()\n iei_cmd.install_dir = env.paths['lib']\n iei_cmd.finalize_options()\n iei_cmd.run()\n\n def test_version_resolved_from_egg_info(self, env):\n version = '1.11.0.dev0+2329eae'\n self.create_foo_pkg(env, version)\n\n # this requirement parsing will raise a VersionConflict unless the\n # .egg-info file is parsed (see #419 on BitBucket)\n req = pkg_resources.Requirement.parse('foo>=1.9')\n dist = pkg_resources.WorkingSet([env.paths['lib']]).find(req)\n assert dist.version == version\n\n @pytest.mark.parametrize(\n ("unnormalized", "normalized"),\n [\n ('foo', 'foo'),\n ('foo/', 'foo'),\n ('foo/bar', 'foo/bar'),\n ('foo/bar/', 'foo/bar'),\n ],\n )\n def test_normalize_path_trailing_sep(self, unnormalized, normalized):\n """Ensure the trailing slash is cleaned for path comparison.\n\n See pypa/setuptools#1519.\n """\n result_from_unnormalized = pkg_resources.normalize_path(unnormalized)\n result_from_normalized = pkg_resources.normalize_path(normalized)\n assert result_from_unnormalized == result_from_normalized\n\n @pytest.mark.skipif(\n os.path.normcase('A') != os.path.normcase('a'),\n reason='Testing case-insensitive filesystems.',\n )\n @pytest.mark.parametrize(\n ("unnormalized", "normalized"),\n [\n ('MiXeD/CasE', 'mixed/case'),\n ],\n )\n def test_normalize_path_normcase(self, unnormalized, normalized):\n """Ensure mixed case is normalized on case-insensitive filesystems."""\n result_from_unnormalized = pkg_resources.normalize_path(unnormalized)\n result_from_normalized = pkg_resources.normalize_path(normalized)\n assert result_from_unnormalized == result_from_normalized\n\n @pytest.mark.skipif(\n os.path.sep != '\\',\n reason='Testing systems using backslashes as path separators.',\n )\n @pytest.mark.parametrize(\n ("unnormalized", "expected"),\n [\n ('forward/slash', 'forward\\slash'),\n ('forward/slash/', 'forward\\slash'),\n ('backward\\slash\\', 'backward\\slash'),\n ],\n )\n def test_normalize_path_backslash_sep(self, unnormalized, expected):\n """Ensure path seps are cleaned on backslash path sep systems."""\n result = pkg_resources.normalize_path(unnormalized)\n assert result.endswith(expected)\n\n\nclass TestWorkdirRequire:\n def fake_site_packages(self, tmp_path, monkeypatch, dist_files):\n site_packages = tmp_path / "site-packages"\n site_packages.mkdir()\n for file, content in self.FILES.items():\n path = site_packages / file\n path.parent.mkdir(exist_ok=True, parents=True)\n path.write_text(inspect.cleandoc(content), encoding="utf-8")\n\n monkeypatch.setattr(sys, "path", [site_packages])\n return os.fspath(site_packages)\n\n FILES = {\n "pkg1_mod-1.2.3.dist-info/METADATA": """\n Metadata-Version: 2.4\n Name: pkg1.mod\n Version: 1.2.3\n """,\n "pkg2.mod-0.42.dist-info/METADATA": """\n Metadata-Version: 2.1\n Name: pkg2.mod\n Version: 0.42\n """,\n "pkg3_mod.egg-info/PKG-INFO": """\n Name: pkg3.mod\n Version: 1.2.3.4\n """,\n "pkg4.mod.egg-info/PKG-INFO": """\n Name: pkg4.mod\n Version: 0.42.1\n """,\n }\n\n @pytest.mark.parametrize(\n ("version", "requirement"),\n [\n ("1.2.3", "pkg1.mod>=1"),\n ("0.42", "pkg2.mod>=0.4"),\n ("1.2.3.4", "pkg3.mod<=2"),\n ("0.42.1", "pkg4.mod>0.2,<1"),\n ],\n )\n def test_require_non_normalised_name(\n self, tmp_path, monkeypatch, version, requirement\n ):\n # https://github.com/pypa/setuptools/issues/4853\n site_packages = self.fake_site_packages(tmp_path, monkeypatch, self.FILES)\n ws = pkg_resources.WorkingSet([site_packages])\n\n for req in [requirement, requirement.replace(".", "-")]:\n [dist] = ws.require(req)\n assert dist.version == version\n assert os.path.samefile(\n os.path.commonpath([dist.location, site_packages]), site_packages\n )\n | .venv\Lib\site-packages\pkg_resources\tests\test_pkg_resources.py | test_pkg_resources.py | Python | 17,111 | 0.95 | 0.098969 | 0.061881 | awesome-app | 544 | 2024-08-09T13:23:32.380886 | Apache-2.0 | true | dff93f443dddff8589205686138e1c1c |
import itertools\nimport os\nimport platform\nimport string\nimport sys\n\nimport pytest\nfrom packaging.specifiers import SpecifierSet\n\nimport pkg_resources\nfrom pkg_resources import (\n Distribution,\n EntryPoint,\n Requirement,\n VersionConflict,\n WorkingSet,\n parse_requirements,\n parse_version,\n safe_name,\n safe_version,\n)\n\n\n# from Python 3.6 docs. Available from itertools on Python 3.10\ndef pairwise(iterable):\n "s -> (s0,s1), (s1,s2), (s2, s3), ..."\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\nclass Metadata(pkg_resources.EmptyProvider):\n """Mock object to return metadata as if from an on-disk distribution"""\n\n def __init__(self, *pairs) -> None:\n self.metadata = dict(pairs)\n\n def has_metadata(self, name) -> bool:\n return name in self.metadata\n\n def get_metadata(self, name):\n return self.metadata[name]\n\n def get_metadata_lines(self, name):\n return pkg_resources.yield_lines(self.get_metadata(name))\n\n\ndist_from_fn = pkg_resources.Distribution.from_filename\n\n\nclass TestDistro:\n def testCollection(self):\n # empty path should produce no distributions\n ad = pkg_resources.Environment([], platform=None, python=None)\n assert list(ad) == []\n assert ad['FooPkg'] == []\n ad.add(dist_from_fn("FooPkg-1.3_1.egg"))\n ad.add(dist_from_fn("FooPkg-1.4-py2.4-win32.egg"))\n ad.add(dist_from_fn("FooPkg-1.2-py2.4.egg"))\n\n # Name is in there now\n assert ad['FooPkg']\n # But only 1 package\n assert list(ad) == ['foopkg']\n\n # Distributions sort by version\n expected = ['1.4', '1.3-1', '1.2']\n assert [dist.version for dist in ad['FooPkg']] == expected\n\n # Removing a distribution leaves sequence alone\n ad.remove(ad['FooPkg'][1])\n assert [dist.version for dist in ad['FooPkg']] == ['1.4', '1.2']\n\n # And inserting adds them in order\n ad.add(dist_from_fn("FooPkg-1.9.egg"))\n assert [dist.version for dist in ad['FooPkg']] == ['1.9', '1.4', '1.2']\n\n ws = WorkingSet([])\n foo12 = dist_from_fn("FooPkg-1.2-py2.4.egg")\n foo14 = dist_from_fn("FooPkg-1.4-py2.4-win32.egg")\n (req,) = parse_requirements("FooPkg>=1.3")\n\n # Nominal case: no distros on path, should yield all applicable\n assert ad.best_match(req, ws).version == '1.9'\n # If a matching distro is already installed, should return only that\n ws.add(foo14)\n assert ad.best_match(req, ws).version == '1.4'\n\n # If the first matching distro is unsuitable, it's a version conflict\n ws = WorkingSet([])\n ws.add(foo12)\n ws.add(foo14)\n with pytest.raises(VersionConflict):\n ad.best_match(req, ws)\n\n # If more than one match on the path, the first one takes precedence\n ws = WorkingSet([])\n ws.add(foo14)\n ws.add(foo12)\n ws.add(foo14)\n assert ad.best_match(req, ws).version == '1.4'\n\n def checkFooPkg(self, d):\n assert d.project_name == "FooPkg"\n assert d.key == "foopkg"\n assert d.version == "1.3.post1"\n assert d.py_version == "2.4"\n assert d.platform == "win32"\n assert d.parsed_version == parse_version("1.3-1")\n\n def testDistroBasics(self):\n d = Distribution(\n "/some/path",\n project_name="FooPkg",\n version="1.3-1",\n py_version="2.4",\n platform="win32",\n )\n self.checkFooPkg(d)\n\n d = Distribution("/some/path")\n assert d.py_version == f'{sys.version_info.major}.{sys.version_info.minor}'\n assert d.platform is None\n\n def testDistroParse(self):\n d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg")\n self.checkFooPkg(d)\n d = dist_from_fn("FooPkg-1.3.post1-py2.4-win32.egg-info")\n self.checkFooPkg(d)\n\n def testDistroMetadata(self):\n d = Distribution(\n "/some/path",\n project_name="FooPkg",\n py_version="2.4",\n platform="win32",\n metadata=Metadata(('PKG-INFO', "Metadata-Version: 1.0\nVersion: 1.3-1\n")),\n )\n self.checkFooPkg(d)\n\n def distRequires(self, txt):\n return Distribution("/foo", metadata=Metadata(('depends.txt', txt)))\n\n def checkRequires(self, dist, txt, extras=()):\n assert list(dist.requires(extras)) == list(parse_requirements(txt))\n\n def testDistroDependsSimple(self):\n for v in "Twisted>=1.5", "Twisted>=1.5\nZConfig>=2.0":\n self.checkRequires(self.distRequires(v), v)\n\n needs_object_dir = pytest.mark.skipif(\n not hasattr(object, '__dir__'),\n reason='object.__dir__ necessary for self.__dir__ implementation',\n )\n\n def test_distribution_dir(self):\n d = pkg_resources.Distribution()\n dir(d)\n\n @needs_object_dir\n def test_distribution_dir_includes_provider_dir(self):\n d = pkg_resources.Distribution()\n before = d.__dir__()\n assert 'test_attr' not in before\n d._provider.test_attr = None\n after = d.__dir__()\n assert len(after) == len(before) + 1\n assert 'test_attr' in after\n\n @needs_object_dir\n def test_distribution_dir_ignores_provider_dir_leading_underscore(self):\n d = pkg_resources.Distribution()\n before = d.__dir__()\n assert '_test_attr' not in before\n d._provider._test_attr = None\n after = d.__dir__()\n assert len(after) == len(before)\n assert '_test_attr' not in after\n\n def testResolve(self):\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n # Resolving no requirements -> nothing to install\n assert list(ws.resolve([], ad)) == []\n # Request something not in the collection -> DistributionNotFound\n with pytest.raises(pkg_resources.DistributionNotFound):\n ws.resolve(parse_requirements("Foo"), ad)\n\n Foo = Distribution.from_filename(\n "/foo_dir/Foo-1.2.egg",\n metadata=Metadata(('depends.txt', "[bar]\nBaz>=2.0")),\n )\n ad.add(Foo)\n ad.add(Distribution.from_filename("Foo-0.9.egg"))\n\n # Request thing(s) that are available -> list to activate\n for i in range(3):\n targets = list(ws.resolve(parse_requirements("Foo"), ad))\n assert targets == [Foo]\n list(map(ws.add, targets))\n with pytest.raises(VersionConflict):\n ws.resolve(parse_requirements("Foo==0.9"), ad)\n ws = WorkingSet([]) # reset\n\n # Request an extra that causes an unresolved dependency for "Baz"\n with pytest.raises(pkg_resources.DistributionNotFound):\n ws.resolve(parse_requirements("Foo[bar]"), ad)\n Baz = Distribution.from_filename(\n "/foo_dir/Baz-2.1.egg", metadata=Metadata(('depends.txt', "Foo"))\n )\n ad.add(Baz)\n\n # Activation list now includes resolved dependency\n assert list(ws.resolve(parse_requirements("Foo[bar]"), ad)) == [Foo, Baz]\n # Requests for conflicting versions produce VersionConflict\n with pytest.raises(VersionConflict) as vc:\n ws.resolve(parse_requirements("Foo==1.2\nFoo!=1.2"), ad)\n\n msg = 'Foo 0.9 is installed but Foo==1.2 is required'\n assert vc.value.report() == msg\n\n def test_environment_marker_evaluation_negative(self):\n """Environment markers are evaluated at resolution time."""\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n res = ws.resolve(parse_requirements("Foo;python_version<'2'"), ad)\n assert list(res) == []\n\n def test_environment_marker_evaluation_positive(self):\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n Foo = Distribution.from_filename("/foo_dir/Foo-1.2.dist-info")\n ad.add(Foo)\n res = ws.resolve(parse_requirements("Foo;python_version>='2'"), ad)\n assert list(res) == [Foo]\n\n def test_environment_marker_evaluation_called(self):\n """\n If one package foo requires bar without any extras,\n markers should pass for bar without extras.\n """\n (parent_req,) = parse_requirements("foo")\n (req,) = parse_requirements("bar;python_version>='2'")\n req_extras = pkg_resources._ReqExtras({req: parent_req.extras})\n assert req_extras.markers_pass(req)\n\n (parent_req,) = parse_requirements("foo[]")\n (req,) = parse_requirements("bar;python_version>='2'")\n req_extras = pkg_resources._ReqExtras({req: parent_req.extras})\n assert req_extras.markers_pass(req)\n\n def test_marker_evaluation_with_extras(self):\n """Extras are also evaluated as markers at resolution time."""\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n Foo = Distribution.from_filename(\n "/foo_dir/Foo-1.2.dist-info",\n metadata=Metadata((\n "METADATA",\n "Provides-Extra: baz\nRequires-Dist: quux; extra=='baz'",\n )),\n )\n ad.add(Foo)\n assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo]\n quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")\n ad.add(quux)\n res = list(ws.resolve(parse_requirements("Foo[baz]"), ad))\n assert res == [Foo, quux]\n\n def test_marker_evaluation_with_extras_normlized(self):\n """Extras are also evaluated as markers at resolution time."""\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n Foo = Distribution.from_filename(\n "/foo_dir/Foo-1.2.dist-info",\n metadata=Metadata((\n "METADATA",\n "Provides-Extra: baz-lightyear\n"\n "Requires-Dist: quux; extra=='baz-lightyear'",\n )),\n )\n ad.add(Foo)\n assert list(ws.resolve(parse_requirements("Foo"), ad)) == [Foo]\n quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")\n ad.add(quux)\n res = list(ws.resolve(parse_requirements("Foo[baz-lightyear]"), ad))\n assert res == [Foo, quux]\n\n def test_marker_evaluation_with_multiple_extras(self):\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n Foo = Distribution.from_filename(\n "/foo_dir/Foo-1.2.dist-info",\n metadata=Metadata((\n "METADATA",\n "Provides-Extra: baz\n"\n "Requires-Dist: quux; extra=='baz'\n"\n "Provides-Extra: bar\n"\n "Requires-Dist: fred; extra=='bar'\n",\n )),\n )\n ad.add(Foo)\n quux = Distribution.from_filename("/foo_dir/quux-1.0.dist-info")\n ad.add(quux)\n fred = Distribution.from_filename("/foo_dir/fred-0.1.dist-info")\n ad.add(fred)\n res = list(ws.resolve(parse_requirements("Foo[baz,bar]"), ad))\n assert sorted(res) == [fred, quux, Foo]\n\n def test_marker_evaluation_with_extras_loop(self):\n ad = pkg_resources.Environment([])\n ws = WorkingSet([])\n a = Distribution.from_filename(\n "/foo_dir/a-0.2.dist-info",\n metadata=Metadata(("METADATA", "Requires-Dist: c[a]")),\n )\n b = Distribution.from_filename(\n "/foo_dir/b-0.3.dist-info",\n metadata=Metadata(("METADATA", "Requires-Dist: c[b]")),\n )\n c = Distribution.from_filename(\n "/foo_dir/c-1.0.dist-info",\n metadata=Metadata((\n "METADATA",\n "Provides-Extra: a\n"\n "Requires-Dist: b;extra=='a'\n"\n "Provides-Extra: b\n"\n "Requires-Dist: foo;extra=='b'",\n )),\n )\n foo = Distribution.from_filename("/foo_dir/foo-0.1.dist-info")\n for dist in (a, b, c, foo):\n ad.add(dist)\n res = list(ws.resolve(parse_requirements("a"), ad))\n assert res == [a, c, b, foo]\n\n @pytest.mark.xfail(\n sys.version_info[:2] == (3, 12) and sys.version_info.releaselevel != 'final',\n reason="https://github.com/python/cpython/issues/103632",\n )\n def testDistroDependsOptions(self):\n d = self.distRequires(\n """\n Twisted>=1.5\n [docgen]\n ZConfig>=2.0\n docutils>=0.3\n [fastcgi]\n fcgiapp>=0.1"""\n )\n self.checkRequires(d, "Twisted>=1.5")\n self.checkRequires(\n d, "Twisted>=1.5 ZConfig>=2.0 docutils>=0.3".split(), ["docgen"]\n )\n self.checkRequires(d, "Twisted>=1.5 fcgiapp>=0.1".split(), ["fastcgi"])\n self.checkRequires(\n d,\n "Twisted>=1.5 ZConfig>=2.0 docutils>=0.3 fcgiapp>=0.1".split(),\n ["docgen", "fastcgi"],\n )\n self.checkRequires(\n d,\n "Twisted>=1.5 fcgiapp>=0.1 ZConfig>=2.0 docutils>=0.3".split(),\n ["fastcgi", "docgen"],\n )\n with pytest.raises(pkg_resources.UnknownExtra):\n d.requires(["foo"])\n\n\nclass TestWorkingSet:\n def test_find_conflicting(self):\n ws = WorkingSet([])\n Foo = Distribution.from_filename("/foo_dir/Foo-1.2.egg")\n ws.add(Foo)\n\n # create a requirement that conflicts with Foo 1.2\n req = next(parse_requirements("Foo<1.2"))\n\n with pytest.raises(VersionConflict) as vc:\n ws.find(req)\n\n msg = 'Foo 1.2 is installed but Foo<1.2 is required'\n assert vc.value.report() == msg\n\n def test_resolve_conflicts_with_prior(self):\n """\n A ContextualVersionConflict should be raised when a requirement\n conflicts with a prior requirement for a different package.\n """\n # Create installation where Foo depends on Baz 1.0 and Bar depends on\n # Baz 2.0.\n ws = WorkingSet([])\n md = Metadata(('depends.txt', "Baz==1.0"))\n Foo = Distribution.from_filename("/foo_dir/Foo-1.0.egg", metadata=md)\n ws.add(Foo)\n md = Metadata(('depends.txt', "Baz==2.0"))\n Bar = Distribution.from_filename("/foo_dir/Bar-1.0.egg", metadata=md)\n ws.add(Bar)\n Baz = Distribution.from_filename("/foo_dir/Baz-1.0.egg")\n ws.add(Baz)\n Baz = Distribution.from_filename("/foo_dir/Baz-2.0.egg")\n ws.add(Baz)\n\n with pytest.raises(VersionConflict) as vc:\n ws.resolve(parse_requirements("Foo\nBar\n"))\n\n msg = "Baz 1.0 is installed but Baz==2.0 is required by "\n msg += repr(set(['Bar']))\n assert vc.value.report() == msg\n\n\nclass TestEntryPoints:\n def assertfields(self, ep):\n assert ep.name == "foo"\n assert ep.module_name == "pkg_resources.tests.test_resources"\n assert ep.attrs == ("TestEntryPoints",)\n assert ep.extras == ("x",)\n assert ep.load() is TestEntryPoints\n expect = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"\n assert str(ep) == expect\n\n def setup_method(self, method):\n self.dist = Distribution.from_filename(\n "FooPkg-1.2-py2.4.egg", metadata=Metadata(('requires.txt', '[x]'))\n )\n\n def testBasics(self):\n ep = EntryPoint(\n "foo",\n "pkg_resources.tests.test_resources",\n ["TestEntryPoints"],\n ["x"],\n self.dist,\n )\n self.assertfields(ep)\n\n def testParse(self):\n s = "foo = pkg_resources.tests.test_resources:TestEntryPoints [x]"\n ep = EntryPoint.parse(s, self.dist)\n self.assertfields(ep)\n\n ep = EntryPoint.parse("bar baz= spammity[PING]")\n assert ep.name == "bar baz"\n assert ep.module_name == "spammity"\n assert ep.attrs == ()\n assert ep.extras == ("ping",)\n\n ep = EntryPoint.parse(" fizzly = wocka:foo")\n assert ep.name == "fizzly"\n assert ep.module_name == "wocka"\n assert ep.attrs == ("foo",)\n assert ep.extras == ()\n\n # plus in the name\n spec = "html+mako = mako.ext.pygmentplugin:MakoHtmlLexer"\n ep = EntryPoint.parse(spec)\n assert ep.name == 'html+mako'\n\n reject_specs = "foo", "x=a:b:c", "q=x/na", "fez=pish:tush-z", "x=f[a]>2"\n\n @pytest.mark.parametrize("reject_spec", reject_specs)\n def test_reject_spec(self, reject_spec):\n with pytest.raises(ValueError):\n EntryPoint.parse(reject_spec)\n\n def test_printable_name(self):\n """\n Allow any printable character in the name.\n """\n # Create a name with all printable characters; strip the whitespace.\n name = string.printable.strip()\n spec = "{name} = module:attr".format(**locals())\n ep = EntryPoint.parse(spec)\n assert ep.name == name\n\n def checkSubMap(self, m):\n assert len(m) == len(self.submap_expect)\n for key, ep in self.submap_expect.items():\n assert m.get(key).name == ep.name\n assert m.get(key).module_name == ep.module_name\n assert sorted(m.get(key).attrs) == sorted(ep.attrs)\n assert sorted(m.get(key).extras) == sorted(ep.extras)\n\n submap_expect = dict(\n feature1=EntryPoint('feature1', 'somemodule', ['somefunction']),\n feature2=EntryPoint(\n 'feature2', 'another.module', ['SomeClass'], ['extra1', 'extra2']\n ),\n feature3=EntryPoint('feature3', 'this.module', extras=['something']),\n )\n submap_str = """\n # define features for blah blah\n feature1 = somemodule:somefunction\n feature2 = another.module:SomeClass [extra1,extra2]\n feature3 = this.module [something]\n """\n\n def testParseList(self):\n self.checkSubMap(EntryPoint.parse_group("xyz", self.submap_str))\n with pytest.raises(ValueError):\n EntryPoint.parse_group("x a", "foo=bar")\n with pytest.raises(ValueError):\n EntryPoint.parse_group("x", ["foo=baz", "foo=bar"])\n\n def testParseMap(self):\n m = EntryPoint.parse_map({'xyz': self.submap_str})\n self.checkSubMap(m['xyz'])\n assert list(m.keys()) == ['xyz']\n m = EntryPoint.parse_map("[xyz]\n" + self.submap_str)\n self.checkSubMap(m['xyz'])\n assert list(m.keys()) == ['xyz']\n with pytest.raises(ValueError):\n EntryPoint.parse_map(["[xyz]", "[xyz]"])\n with pytest.raises(ValueError):\n EntryPoint.parse_map(self.submap_str)\n\n def testDeprecationWarnings(self):\n ep = EntryPoint(\n "foo", "pkg_resources.tests.test_resources", ["TestEntryPoints"], ["x"]\n )\n with pytest.warns(pkg_resources.PkgResourcesDeprecationWarning):\n ep.load(require=False)\n\n\nclass TestRequirements:\n def testBasics(self):\n r = Requirement.parse("Twisted>=1.2")\n assert str(r) == "Twisted>=1.2"\n assert repr(r) == "Requirement.parse('Twisted>=1.2')"\n assert r == Requirement("Twisted>=1.2")\n assert r == Requirement("twisTed>=1.2")\n assert r != Requirement("Twisted>=2.0")\n assert r != Requirement("Zope>=1.2")\n assert r != Requirement("Zope>=3.0")\n assert r != Requirement("Twisted[extras]>=1.2")\n\n def testOrdering(self):\n r1 = Requirement("Twisted==1.2c1,>=1.2")\n r2 = Requirement("Twisted>=1.2,==1.2c1")\n assert r1 == r2\n assert str(r1) == str(r2)\n assert str(r2) == "Twisted==1.2c1,>=1.2"\n assert Requirement("Twisted") != Requirement(\n "Twisted @ https://localhost/twisted.zip"\n )\n\n def testBasicContains(self):\n r = Requirement("Twisted>=1.2")\n foo_dist = Distribution.from_filename("FooPkg-1.3_1.egg")\n twist11 = Distribution.from_filename("Twisted-1.1.egg")\n twist12 = Distribution.from_filename("Twisted-1.2.egg")\n assert parse_version('1.2') in r\n assert parse_version('1.1') not in r\n assert '1.2' in r\n assert '1.1' not in r\n assert foo_dist not in r\n assert twist11 not in r\n assert twist12 in r\n\n def testOptionsAndHashing(self):\n r1 = Requirement.parse("Twisted[foo,bar]>=1.2")\n r2 = Requirement.parse("Twisted[bar,FOO]>=1.2")\n assert r1 == r2\n assert set(r1.extras) == set(("foo", "bar"))\n assert set(r2.extras) == set(("foo", "bar"))\n assert hash(r1) == hash(r2)\n assert hash(r1) == hash((\n "twisted",\n None,\n SpecifierSet(">=1.2"),\n frozenset(["foo", "bar"]),\n None,\n ))\n assert hash(\n Requirement.parse("Twisted @ https://localhost/twisted.zip")\n ) == hash((\n "twisted",\n "https://localhost/twisted.zip",\n SpecifierSet(),\n frozenset(),\n None,\n ))\n\n def testVersionEquality(self):\n r1 = Requirement.parse("foo==0.3a2")\n r2 = Requirement.parse("foo!=0.3a4")\n d = Distribution.from_filename\n\n assert d("foo-0.3a4.egg") not in r1\n assert d("foo-0.3a1.egg") not in r1\n assert d("foo-0.3a4.egg") not in r2\n\n assert d("foo-0.3a2.egg") in r1\n assert d("foo-0.3a2.egg") in r2\n assert d("foo-0.3a3.egg") in r2\n assert d("foo-0.3a5.egg") in r2\n\n def testSetuptoolsProjectName(self):\n """\n The setuptools project should implement the setuptools package.\n """\n\n assert Requirement.parse('setuptools').project_name == 'setuptools'\n # setuptools 0.7 and higher means setuptools.\n assert Requirement.parse('setuptools == 0.7').project_name == 'setuptools'\n assert Requirement.parse('setuptools == 0.7a1').project_name == 'setuptools'\n assert Requirement.parse('setuptools >= 0.7').project_name == 'setuptools'\n\n\nclass TestParsing:\n def testEmptyParse(self):\n assert list(parse_requirements('')) == []\n\n def testYielding(self):\n for inp, out in [\n ([], []),\n ('x', ['x']),\n ([[]], []),\n (' x\n y', ['x', 'y']),\n (['x\n\n', 'y'], ['x', 'y']),\n ]:\n assert list(pkg_resources.yield_lines(inp)) == out\n\n def testSplitting(self):\n sample = """\n x\n [Y]\n z\n\n a\n [b ]\n # foo\n c\n [ d]\n [q]\n v\n """\n assert list(pkg_resources.split_sections(sample)) == [\n (None, ["x"]),\n ("Y", ["z", "a"]),\n ("b", ["c"]),\n ("d", []),\n ("q", ["v"]),\n ]\n with pytest.raises(ValueError):\n list(pkg_resources.split_sections("[foo"))\n\n def testSafeName(self):\n assert safe_name("adns-python") == "adns-python"\n assert safe_name("WSGI Utils") == "WSGI-Utils"\n assert safe_name("WSGI Utils") == "WSGI-Utils"\n assert safe_name("Money$$$Maker") == "Money-Maker"\n assert safe_name("peak.web") != "peak-web"\n\n def testSafeVersion(self):\n assert safe_version("1.2-1") == "1.2.post1"\n assert safe_version("1.2 alpha") == "1.2.alpha"\n assert safe_version("2.3.4 20050521") == "2.3.4.20050521"\n assert safe_version("Money$$$Maker") == "Money-Maker"\n assert safe_version("peak.web") == "peak.web"\n\n def testSimpleRequirements(self):\n assert list(parse_requirements('Twis-Ted>=1.2-1')) == [\n Requirement('Twis-Ted>=1.2-1')\n ]\n assert list(parse_requirements('Twisted >=1.2, \\ # more\n<2.0')) == [\n Requirement('Twisted>=1.2,<2.0')\n ]\n assert Requirement.parse("FooBar==1.99a3") == Requirement("FooBar==1.99a3")\n with pytest.raises(ValueError):\n Requirement.parse(">=2.3")\n with pytest.raises(ValueError):\n Requirement.parse("x\\")\n with pytest.raises(ValueError):\n Requirement.parse("x==2 q")\n with pytest.raises(ValueError):\n Requirement.parse("X==1\nY==2")\n with pytest.raises(ValueError):\n Requirement.parse("#")\n\n def test_requirements_with_markers(self):\n assert Requirement.parse("foobar;os_name=='a'") == Requirement.parse(\n "foobar;os_name=='a'"\n )\n assert Requirement.parse(\n "name==1.1;python_version=='2.7'"\n ) != Requirement.parse("name==1.1;python_version=='3.6'")\n assert Requirement.parse(\n "name==1.0;python_version=='2.7'"\n ) != Requirement.parse("name==1.2;python_version=='2.7'")\n assert Requirement.parse(\n "name[foo]==1.0;python_version=='3.6'"\n ) != Requirement.parse("name[foo,bar]==1.0;python_version=='3.6'")\n\n def test_local_version(self):\n parse_requirements('foo==1.0+org1')\n\n def test_spaces_between_multiple_versions(self):\n parse_requirements('foo>=1.0, <3')\n parse_requirements('foo >= 1.0, < 3')\n\n @pytest.mark.parametrize(\n ("lower", "upper"),\n [\n ('1.2-rc1', '1.2rc1'),\n ('0.4', '0.4.0'),\n ('0.4.0.0', '0.4.0'),\n ('0.4.0-0', '0.4-0'),\n ('0post1', '0.0post1'),\n ('0pre1', '0.0c1'),\n ('0.0.0preview1', '0c1'),\n ('0.0c1', '0-rc1'),\n ('1.2a1', '1.2.a.1'),\n ('1.2.a', '1.2a'),\n ],\n )\n def testVersionEquality(self, lower, upper):\n assert parse_version(lower) == parse_version(upper)\n\n torture = """\n 0.80.1-3 0.80.1-2 0.80.1-1 0.79.9999+0.80.0pre4-1\n 0.79.9999+0.80.0pre2-3 0.79.9999+0.80.0pre2-2\n 0.77.2-1 0.77.1-1 0.77.0-1\n """\n\n @pytest.mark.parametrize(\n ("lower", "upper"),\n [\n ('2.1', '2.1.1'),\n ('2a1', '2b0'),\n ('2a1', '2.1'),\n ('2.3a1', '2.3'),\n ('2.1-1', '2.1-2'),\n ('2.1-1', '2.1.1'),\n ('2.1', '2.1post4'),\n ('2.1a0-20040501', '2.1'),\n ('1.1', '02.1'),\n ('3.2', '3.2.post0'),\n ('3.2post1', '3.2post2'),\n ('0.4', '4.0'),\n ('0.0.4', '0.4.0'),\n ('0post1', '0.4post1'),\n ('2.1.0-rc1', '2.1.0'),\n ('2.1dev', '2.1a0'),\n ]\n + list(pairwise(reversed(torture.split()))),\n )\n def testVersionOrdering(self, lower, upper):\n assert parse_version(lower) < parse_version(upper)\n\n def testVersionHashable(self):\n """\n Ensure that our versions stay hashable even though we've subclassed\n them and added some shim code to them.\n """\n assert hash(parse_version("1.0")) == hash(parse_version("1.0"))\n\n\nclass TestNamespaces:\n ns_str = "__import__('pkg_resources').declare_namespace(__name__)\n"\n\n @pytest.fixture\n def symlinked_tmpdir(self, tmpdir):\n """\n Where available, return the tempdir as a symlink,\n which as revealed in #231 is more fragile than\n a natural tempdir.\n """\n if not hasattr(os, 'symlink'):\n yield str(tmpdir)\n return\n\n link_name = str(tmpdir) + '-linked'\n os.symlink(str(tmpdir), link_name)\n try:\n yield type(tmpdir)(link_name)\n finally:\n os.unlink(link_name)\n\n @pytest.fixture(autouse=True)\n def patched_path(self, tmpdir):\n """\n Patch sys.path to include the 'site-pkgs' dir. Also\n restore pkg_resources._namespace_packages to its\n former state.\n """\n saved_ns_pkgs = pkg_resources._namespace_packages.copy()\n saved_sys_path = sys.path[:]\n site_pkgs = tmpdir.mkdir('site-pkgs')\n sys.path.append(str(site_pkgs))\n try:\n yield\n finally:\n pkg_resources._namespace_packages = saved_ns_pkgs\n sys.path = saved_sys_path\n\n issue591 = pytest.mark.xfail(platform.system() == 'Windows', reason="#591")\n\n @issue591\n def test_two_levels_deep(self, symlinked_tmpdir):\n """\n Test nested namespace packages\n Create namespace packages in the following tree :\n site-packages-1/pkg1/pkg2\n site-packages-2/pkg1/pkg2\n Check both are in the _namespace_packages dict and that their __path__\n is correct\n """\n real_tmpdir = symlinked_tmpdir.realpath()\n tmpdir = symlinked_tmpdir\n sys.path.append(str(tmpdir / 'site-pkgs2'))\n site_dirs = tmpdir / 'site-pkgs', tmpdir / 'site-pkgs2'\n for site in site_dirs:\n pkg1 = site / 'pkg1'\n pkg2 = pkg1 / 'pkg2'\n pkg2.ensure_dir()\n (pkg1 / '__init__.py').write_text(self.ns_str, encoding='utf-8')\n (pkg2 / '__init__.py').write_text(self.ns_str, encoding='utf-8')\n with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"):\n import pkg1 # pyright: ignore[reportMissingImports] # Temporary package for test\n assert "pkg1" in pkg_resources._namespace_packages\n # attempt to import pkg2 from site-pkgs2\n with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"):\n import pkg1.pkg2 # pyright: ignore[reportMissingImports] # Temporary package for test\n # check the _namespace_packages dict\n assert "pkg1.pkg2" in pkg_resources._namespace_packages\n assert pkg_resources._namespace_packages["pkg1"] == ["pkg1.pkg2"]\n # check the __path__ attribute contains both paths\n expected = [\n str(real_tmpdir / "site-pkgs" / "pkg1" / "pkg2"),\n str(real_tmpdir / "site-pkgs2" / "pkg1" / "pkg2"),\n ]\n assert pkg1.pkg2.__path__ == expected\n\n @issue591\n def test_path_order(self, symlinked_tmpdir):\n """\n Test that if multiple versions of the same namespace package subpackage\n are on different sys.path entries, that only the one earliest on\n sys.path is imported, and that the namespace package's __path__ is in\n the correct order.\n\n Regression test for https://github.com/pypa/setuptools/issues/207\n """\n\n tmpdir = symlinked_tmpdir\n site_dirs = (\n tmpdir / "site-pkgs",\n tmpdir / "site-pkgs2",\n tmpdir / "site-pkgs3",\n )\n\n vers_str = "__version__ = %r"\n\n for number, site in enumerate(site_dirs, 1):\n if number > 1:\n sys.path.append(str(site))\n nspkg = site / 'nspkg'\n subpkg = nspkg / 'subpkg'\n subpkg.ensure_dir()\n (nspkg / '__init__.py').write_text(self.ns_str, encoding='utf-8')\n (subpkg / '__init__.py').write_text(vers_str % number, encoding='utf-8')\n\n with pytest.warns(DeprecationWarning, match="pkg_resources.declare_namespace"):\n import nspkg # pyright: ignore[reportMissingImports] # Temporary package for test\n import nspkg.subpkg # pyright: ignore[reportMissingImports] # Temporary package for test\n expected = [str(site.realpath() / 'nspkg') for site in site_dirs]\n assert nspkg.__path__ == expected\n assert nspkg.subpkg.__version__ == 1\n | .venv\Lib\site-packages\pkg_resources\tests\test_resources.py | test_resources.py | Python | 31,252 | 0.95 | 0.10817 | 0.036939 | awesome-app | 774 | 2024-12-16T23:20:37.423002 | GPL-3.0 | true | b73854e692c17d38dd34bcf028783080 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.