ZTWHHH commited on
Commit
78e63d7
·
verified ·
1 Parent(s): 81fb5e3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava/lib/python3.10/site-packages/pip/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llava/lib/python3.10/site-packages/pip/__pycache__/__main__.cpython-310.pyc +0 -0
  3. llava/lib/python3.10/site-packages/pip/__pycache__/__pip-runner__.cpython-310.pyc +0 -0
  4. llava/lib/python3.10/site-packages/pip/_vendor/certifi/__init__.py +4 -0
  5. llava/lib/python3.10/site-packages/pip/_vendor/certifi/__main__.py +12 -0
  6. llava/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-310.pyc +0 -0
  7. llava/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__main__.cpython-310.pyc +0 -0
  8. llava/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-310.pyc +0 -0
  9. llava/lib/python3.10/site-packages/pip/_vendor/certifi/cacert.pem +0 -0
  10. llava/lib/python3.10/site-packages/pip/_vendor/certifi/core.py +114 -0
  11. llava/lib/python3.10/site-packages/pip/_vendor/certifi/py.typed +0 -0
  12. llava/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py +0 -0
  13. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__init__.py +36 -0
  14. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/__init__.cpython-310.pyc +0 -0
  15. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_api.cpython-310.pyc +0 -0
  16. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_macos.cpython-310.pyc +0 -0
  17. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_openssl.cpython-310.pyc +0 -0
  18. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_ssl_constants.cpython-310.pyc +0 -0
  19. llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_windows.cpython-310.pyc +0 -0
  20. llava/lib/python3.10/site-packages/pip/_vendor/truststore/_api.py +316 -0
  21. llava/lib/python3.10/site-packages/pip/_vendor/truststore/_macos.py +571 -0
  22. llava/lib/python3.10/site-packages/pip/_vendor/truststore/_openssl.py +66 -0
  23. llava/lib/python3.10/site-packages/pip/_vendor/truststore/_ssl_constants.py +31 -0
  24. llava/lib/python3.10/site-packages/pip/_vendor/truststore/_windows.py +567 -0
  25. llava/lib/python3.10/site-packages/pip/_vendor/truststore/py.typed +0 -0
  26. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/__init__.cpython-310.pyc +0 -0
  27. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/_collections.cpython-310.pyc +0 -0
  28. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-310.pyc +0 -0
  29. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-310.pyc +0 -0
  30. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-310.pyc +0 -0
  31. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/exceptions.cpython-310.pyc +0 -0
  32. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/fields.cpython-310.pyc +0 -0
  33. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/filepost.cpython-310.pyc +0 -0
  34. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/poolmanager.cpython-310.pyc +0 -0
  35. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/request.cpython-310.pyc +0 -0
  36. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/response.cpython-310.pyc +0 -0
  37. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/__init__.py +0 -0
  38. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-310.pyc +0 -0
  39. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/__pycache__/six.cpython-310.pyc +0 -0
  40. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__init__.py +0 -0
  41. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-310.pyc +0 -0
  42. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-310.pyc +0 -0
  43. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__pycache__/weakref_finalize.cpython-310.pyc +0 -0
  44. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py +51 -0
  45. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/weakref_finalize.py +155 -0
  46. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/six.py +1076 -0
  47. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-310.pyc +0 -0
  48. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-310.pyc +0 -0
  49. llava/lib/python3.10/site-packages/pip/_vendor/urllib3/util/__pycache__/timeout.cpython-310.pyc +0 -0
  50. llava/lib/python3.10/site-packages/setuptools/__init__.py +286 -0
llava/lib/python3.10/site-packages/pip/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (610 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (444 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/__pycache__/__pip-runner__.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/certifi/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .core import contents, where
2
+
3
+ __all__ = ["contents", "where"]
4
+ __version__ = "2024.08.30"
llava/lib/python3.10/site-packages/pip/_vendor/certifi/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from pip._vendor.certifi import contents, where
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("-c", "--contents", action="store_true")
7
+ args = parser.parse_args()
8
+
9
+ if args.contents:
10
+ print(contents())
11
+ else:
12
+ print(where())
llava/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (283 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (433 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/certifi/__pycache__/core.cpython-310.pyc ADDED
Binary file (2.13 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/certifi/cacert.pem ADDED
The diff for this file is too large to render. See raw diff
 
llava/lib/python3.10/site-packages/pip/_vendor/certifi/core.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ certifi.py
3
+ ~~~~~~~~~~
4
+
5
+ This module returns the installation location of cacert.pem or its contents.
6
+ """
7
+ import sys
8
+ import atexit
9
+
10
+ def exit_cacert_ctx() -> None:
11
+ _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr]
12
+
13
+
14
+ if sys.version_info >= (3, 11):
15
+
16
+ from importlib.resources import as_file, files
17
+
18
+ _CACERT_CTX = None
19
+ _CACERT_PATH = None
20
+
21
+ def where() -> str:
22
+ # This is slightly terrible, but we want to delay extracting the file
23
+ # in cases where we're inside of a zipimport situation until someone
24
+ # actually calls where(), but we don't want to re-extract the file
25
+ # on every call of where(), so we'll do it once then store it in a
26
+ # global variable.
27
+ global _CACERT_CTX
28
+ global _CACERT_PATH
29
+ if _CACERT_PATH is None:
30
+ # This is slightly janky, the importlib.resources API wants you to
31
+ # manage the cleanup of this file, so it doesn't actually return a
32
+ # path, it returns a context manager that will give you the path
33
+ # when you enter it and will do any cleanup when you leave it. In
34
+ # the common case of not needing a temporary file, it will just
35
+ # return the file system location and the __exit__() is a no-op.
36
+ #
37
+ # We also have to hold onto the actual context manager, because
38
+ # it will do the cleanup whenever it gets garbage collected, so
39
+ # we will also store that at the global level as well.
40
+ _CACERT_CTX = as_file(files("pip._vendor.certifi").joinpath("cacert.pem"))
41
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
42
+ atexit.register(exit_cacert_ctx)
43
+
44
+ return _CACERT_PATH
45
+
46
+ def contents() -> str:
47
+ return files("pip._vendor.certifi").joinpath("cacert.pem").read_text(encoding="ascii")
48
+
49
+ elif sys.version_info >= (3, 7):
50
+
51
+ from importlib.resources import path as get_path, read_text
52
+
53
+ _CACERT_CTX = None
54
+ _CACERT_PATH = None
55
+
56
+ def where() -> str:
57
+ # This is slightly terrible, but we want to delay extracting the
58
+ # file in cases where we're inside of a zipimport situation until
59
+ # someone actually calls where(), but we don't want to re-extract
60
+ # the file on every call of where(), so we'll do it once then store
61
+ # it in a global variable.
62
+ global _CACERT_CTX
63
+ global _CACERT_PATH
64
+ if _CACERT_PATH is None:
65
+ # This is slightly janky, the importlib.resources API wants you
66
+ # to manage the cleanup of this file, so it doesn't actually
67
+ # return a path, it returns a context manager that will give
68
+ # you the path when you enter it and will do any cleanup when
69
+ # you leave it. In the common case of not needing a temporary
70
+ # file, it will just return the file system location and the
71
+ # __exit__() is a no-op.
72
+ #
73
+ # We also have to hold onto the actual context manager, because
74
+ # it will do the cleanup whenever it gets garbage collected, so
75
+ # we will also store that at the global level as well.
76
+ _CACERT_CTX = get_path("pip._vendor.certifi", "cacert.pem")
77
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
78
+ atexit.register(exit_cacert_ctx)
79
+
80
+ return _CACERT_PATH
81
+
82
+ def contents() -> str:
83
+ return read_text("pip._vendor.certifi", "cacert.pem", encoding="ascii")
84
+
85
+ else:
86
+ import os
87
+ import types
88
+ from typing import Union
89
+
90
+ Package = Union[types.ModuleType, str]
91
+ Resource = Union[str, "os.PathLike"]
92
+
93
+ # This fallback will work for Python versions prior to 3.7 that lack the
94
+ # importlib.resources module but relies on the existing `where` function
95
+ # so won't address issues with environments like PyOxidizer that don't set
96
+ # __file__ on modules.
97
+ def read_text(
98
+ package: Package,
99
+ resource: Resource,
100
+ encoding: str = 'utf-8',
101
+ errors: str = 'strict'
102
+ ) -> str:
103
+ with open(where(), encoding=encoding) as data:
104
+ return data.read()
105
+
106
+ # If we don't have importlib.resources, then we will just do the old logic
107
+ # of assuming we're on the filesystem and munge the path directly.
108
+ def where() -> str:
109
+ f = os.path.dirname(__file__)
110
+
111
+ return os.path.join(f, "cacert.pem")
112
+
113
+ def contents() -> str:
114
+ return read_text("pip._vendor.certifi", "cacert.pem", encoding="ascii")
llava/lib/python3.10/site-packages/pip/_vendor/certifi/py.typed ADDED
File without changes
llava/lib/python3.10/site-packages/pip/_vendor/pkg_resources/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verify certificates using native system trust stores"""
2
+
3
+ import sys as _sys
4
+
5
+ if _sys.version_info < (3, 10):
6
+ raise ImportError("truststore requires Python 3.10 or later")
7
+
8
+ # Detect Python runtimes which don't implement SSLObject.get_unverified_chain() API
9
+ # This API only became public in Python 3.13 but was available in CPython and PyPy since 3.10.
10
+ if _sys.version_info < (3, 13):
11
+ try:
12
+ import ssl as _ssl
13
+ except ImportError:
14
+ raise ImportError("truststore requires the 'ssl' module")
15
+ else:
16
+ _sslmem = _ssl.MemoryBIO()
17
+ _sslobj = _ssl.create_default_context().wrap_bio(
18
+ _sslmem,
19
+ _sslmem,
20
+ )
21
+ try:
22
+ while not hasattr(_sslobj, "get_unverified_chain"):
23
+ _sslobj = _sslobj._sslobj # type: ignore[attr-defined]
24
+ except AttributeError:
25
+ raise ImportError(
26
+ "truststore requires peer certificate chain APIs to be available"
27
+ ) from None
28
+
29
+ del _ssl, _sslobj, _sslmem # noqa: F821
30
+
31
+ from ._api import SSLContext, extract_from_ssl, inject_into_ssl # noqa: E402
32
+
33
+ del _api, _sys # type: ignore[name-defined] # noqa: F821
34
+
35
+ __all__ = ["SSLContext", "inject_into_ssl", "extract_from_ssl"]
36
+ __version__ = "0.10.0"
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (948 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_api.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_macos.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_openssl.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_ssl_constants.cpython-310.pyc ADDED
Binary file (775 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/__pycache__/_windows.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/truststore/_api.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import socket
4
+ import ssl
5
+ import sys
6
+ import typing
7
+
8
+ import _ssl # type: ignore[import-not-found]
9
+
10
+ from ._ssl_constants import (
11
+ _original_SSLContext,
12
+ _original_super_SSLContext,
13
+ _truststore_SSLContext_dunder_class,
14
+ _truststore_SSLContext_super_class,
15
+ )
16
+
17
+ if platform.system() == "Windows":
18
+ from ._windows import _configure_context, _verify_peercerts_impl
19
+ elif platform.system() == "Darwin":
20
+ from ._macos import _configure_context, _verify_peercerts_impl
21
+ else:
22
+ from ._openssl import _configure_context, _verify_peercerts_impl
23
+
24
+ if typing.TYPE_CHECKING:
25
+ from pip._vendor.typing_extensions import Buffer
26
+
27
+ # From typeshed/stdlib/ssl.pyi
28
+ _StrOrBytesPath: typing.TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes]
29
+ _PasswordType: typing.TypeAlias = str | bytes | typing.Callable[[], str | bytes]
30
+
31
+
32
+ def inject_into_ssl() -> None:
33
+ """Injects the :class:`truststore.SSLContext` into the ``ssl``
34
+ module by replacing :class:`ssl.SSLContext`.
35
+ """
36
+ setattr(ssl, "SSLContext", SSLContext)
37
+ # urllib3 holds on to its own reference of ssl.SSLContext
38
+ # so we need to replace that reference too.
39
+ try:
40
+ import pip._vendor.urllib3.util.ssl_ as urllib3_ssl
41
+
42
+ setattr(urllib3_ssl, "SSLContext", SSLContext)
43
+ except ImportError:
44
+ pass
45
+
46
+
47
+ def extract_from_ssl() -> None:
48
+ """Restores the :class:`ssl.SSLContext` class to its original state"""
49
+ setattr(ssl, "SSLContext", _original_SSLContext)
50
+ try:
51
+ import pip._vendor.urllib3.util.ssl_ as urllib3_ssl
52
+
53
+ urllib3_ssl.SSLContext = _original_SSLContext # type: ignore[assignment]
54
+ except ImportError:
55
+ pass
56
+
57
+
58
+ class SSLContext(_truststore_SSLContext_super_class): # type: ignore[misc]
59
+ """SSLContext API that uses system certificates on all platforms"""
60
+
61
+ @property # type: ignore[misc]
62
+ def __class__(self) -> type:
63
+ # Dirty hack to get around isinstance() checks
64
+ # for ssl.SSLContext instances in aiohttp/trustme
65
+ # when using non-CPython implementations.
66
+ return _truststore_SSLContext_dunder_class or SSLContext
67
+
68
+ def __init__(self, protocol: int = None) -> None: # type: ignore[assignment]
69
+ self._ctx = _original_SSLContext(protocol)
70
+
71
+ class TruststoreSSLObject(ssl.SSLObject):
72
+ # This object exists because wrap_bio() doesn't
73
+ # immediately do the handshake so we need to do
74
+ # certificate verifications after SSLObject.do_handshake()
75
+
76
+ def do_handshake(self) -> None:
77
+ ret = super().do_handshake()
78
+ _verify_peercerts(self, server_hostname=self.server_hostname)
79
+ return ret
80
+
81
+ self._ctx.sslobject_class = TruststoreSSLObject
82
+
83
+ def wrap_socket(
84
+ self,
85
+ sock: socket.socket,
86
+ server_side: bool = False,
87
+ do_handshake_on_connect: bool = True,
88
+ suppress_ragged_eofs: bool = True,
89
+ server_hostname: str | None = None,
90
+ session: ssl.SSLSession | None = None,
91
+ ) -> ssl.SSLSocket:
92
+ # Use a context manager here because the
93
+ # inner SSLContext holds on to our state
94
+ # but also does the actual handshake.
95
+ with _configure_context(self._ctx):
96
+ ssl_sock = self._ctx.wrap_socket(
97
+ sock,
98
+ server_side=server_side,
99
+ server_hostname=server_hostname,
100
+ do_handshake_on_connect=do_handshake_on_connect,
101
+ suppress_ragged_eofs=suppress_ragged_eofs,
102
+ session=session,
103
+ )
104
+ try:
105
+ _verify_peercerts(ssl_sock, server_hostname=server_hostname)
106
+ except Exception:
107
+ ssl_sock.close()
108
+ raise
109
+ return ssl_sock
110
+
111
+ def wrap_bio(
112
+ self,
113
+ incoming: ssl.MemoryBIO,
114
+ outgoing: ssl.MemoryBIO,
115
+ server_side: bool = False,
116
+ server_hostname: str | None = None,
117
+ session: ssl.SSLSession | None = None,
118
+ ) -> ssl.SSLObject:
119
+ with _configure_context(self._ctx):
120
+ ssl_obj = self._ctx.wrap_bio(
121
+ incoming,
122
+ outgoing,
123
+ server_hostname=server_hostname,
124
+ server_side=server_side,
125
+ session=session,
126
+ )
127
+ return ssl_obj
128
+
129
+ def load_verify_locations(
130
+ self,
131
+ cafile: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,
132
+ capath: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,
133
+ cadata: typing.Union[str, "Buffer", None] = None,
134
+ ) -> None:
135
+ return self._ctx.load_verify_locations(
136
+ cafile=cafile, capath=capath, cadata=cadata
137
+ )
138
+
139
+ def load_cert_chain(
140
+ self,
141
+ certfile: _StrOrBytesPath,
142
+ keyfile: _StrOrBytesPath | None = None,
143
+ password: _PasswordType | None = None,
144
+ ) -> None:
145
+ return self._ctx.load_cert_chain(
146
+ certfile=certfile, keyfile=keyfile, password=password
147
+ )
148
+
149
+ def load_default_certs(
150
+ self, purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH
151
+ ) -> None:
152
+ return self._ctx.load_default_certs(purpose)
153
+
154
+ def set_alpn_protocols(self, alpn_protocols: typing.Iterable[str]) -> None:
155
+ return self._ctx.set_alpn_protocols(alpn_protocols)
156
+
157
+ def set_npn_protocols(self, npn_protocols: typing.Iterable[str]) -> None:
158
+ return self._ctx.set_npn_protocols(npn_protocols)
159
+
160
+ def set_ciphers(self, __cipherlist: str) -> None:
161
+ return self._ctx.set_ciphers(__cipherlist)
162
+
163
+ def get_ciphers(self) -> typing.Any:
164
+ return self._ctx.get_ciphers()
165
+
166
+ def session_stats(self) -> dict[str, int]:
167
+ return self._ctx.session_stats()
168
+
169
+ def cert_store_stats(self) -> dict[str, int]:
170
+ raise NotImplementedError()
171
+
172
+ def set_default_verify_paths(self) -> None:
173
+ self._ctx.set_default_verify_paths()
174
+
175
+ @typing.overload
176
+ def get_ca_certs(
177
+ self, binary_form: typing.Literal[False] = ...
178
+ ) -> list[typing.Any]: ...
179
+
180
+ @typing.overload
181
+ def get_ca_certs(self, binary_form: typing.Literal[True] = ...) -> list[bytes]: ...
182
+
183
+ @typing.overload
184
+ def get_ca_certs(self, binary_form: bool = ...) -> typing.Any: ...
185
+
186
+ def get_ca_certs(self, binary_form: bool = False) -> list[typing.Any] | list[bytes]:
187
+ raise NotImplementedError()
188
+
189
+ @property
190
+ def check_hostname(self) -> bool:
191
+ return self._ctx.check_hostname
192
+
193
+ @check_hostname.setter
194
+ def check_hostname(self, value: bool) -> None:
195
+ self._ctx.check_hostname = value
196
+
197
+ @property
198
+ def hostname_checks_common_name(self) -> bool:
199
+ return self._ctx.hostname_checks_common_name
200
+
201
+ @hostname_checks_common_name.setter
202
+ def hostname_checks_common_name(self, value: bool) -> None:
203
+ self._ctx.hostname_checks_common_name = value
204
+
205
+ @property
206
+ def keylog_filename(self) -> str:
207
+ return self._ctx.keylog_filename
208
+
209
+ @keylog_filename.setter
210
+ def keylog_filename(self, value: str) -> None:
211
+ self._ctx.keylog_filename = value
212
+
213
+ @property
214
+ def maximum_version(self) -> ssl.TLSVersion:
215
+ return self._ctx.maximum_version
216
+
217
+ @maximum_version.setter
218
+ def maximum_version(self, value: ssl.TLSVersion) -> None:
219
+ _original_super_SSLContext.maximum_version.__set__( # type: ignore[attr-defined]
220
+ self._ctx, value
221
+ )
222
+
223
+ @property
224
+ def minimum_version(self) -> ssl.TLSVersion:
225
+ return self._ctx.minimum_version
226
+
227
+ @minimum_version.setter
228
+ def minimum_version(self, value: ssl.TLSVersion) -> None:
229
+ _original_super_SSLContext.minimum_version.__set__( # type: ignore[attr-defined]
230
+ self._ctx, value
231
+ )
232
+
233
+ @property
234
+ def options(self) -> ssl.Options:
235
+ return self._ctx.options
236
+
237
+ @options.setter
238
+ def options(self, value: ssl.Options) -> None:
239
+ _original_super_SSLContext.options.__set__( # type: ignore[attr-defined]
240
+ self._ctx, value
241
+ )
242
+
243
+ @property
244
+ def post_handshake_auth(self) -> bool:
245
+ return self._ctx.post_handshake_auth
246
+
247
+ @post_handshake_auth.setter
248
+ def post_handshake_auth(self, value: bool) -> None:
249
+ self._ctx.post_handshake_auth = value
250
+
251
+ @property
252
+ def protocol(self) -> ssl._SSLMethod:
253
+ return self._ctx.protocol
254
+
255
+ @property
256
+ def security_level(self) -> int:
257
+ return self._ctx.security_level
258
+
259
+ @property
260
+ def verify_flags(self) -> ssl.VerifyFlags:
261
+ return self._ctx.verify_flags
262
+
263
+ @verify_flags.setter
264
+ def verify_flags(self, value: ssl.VerifyFlags) -> None:
265
+ _original_super_SSLContext.verify_flags.__set__( # type: ignore[attr-defined]
266
+ self._ctx, value
267
+ )
268
+
269
+ @property
270
+ def verify_mode(self) -> ssl.VerifyMode:
271
+ return self._ctx.verify_mode
272
+
273
+ @verify_mode.setter
274
+ def verify_mode(self, value: ssl.VerifyMode) -> None:
275
+ _original_super_SSLContext.verify_mode.__set__( # type: ignore[attr-defined]
276
+ self._ctx, value
277
+ )
278
+
279
+
280
+ # Python 3.13+ makes get_unverified_chain() a public API that only returns DER
281
+ # encoded certificates. We detect whether we need to call public_bytes() for 3.10->3.12
282
+ # Pre-3.13 returned None instead of an empty list from get_unverified_chain()
283
+ if sys.version_info >= (3, 13):
284
+
285
+ def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:
286
+ unverified_chain = sslobj.get_unverified_chain() or () # type: ignore[attr-defined]
287
+ return [
288
+ cert if isinstance(cert, bytes) else cert.public_bytes(_ssl.ENCODING_DER)
289
+ for cert in unverified_chain
290
+ ]
291
+
292
+ else:
293
+
294
+ def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:
295
+ unverified_chain = sslobj.get_unverified_chain() or () # type: ignore[attr-defined]
296
+ return [cert.public_bytes(_ssl.ENCODING_DER) for cert in unverified_chain]
297
+
298
+
299
+ def _verify_peercerts(
300
+ sock_or_sslobj: ssl.SSLSocket | ssl.SSLObject, server_hostname: str | None
301
+ ) -> None:
302
+ """
303
+ Verifies the peer certificates from an SSLSocket or SSLObject
304
+ against the certificates in the OS trust store.
305
+ """
306
+ sslobj: ssl.SSLObject = sock_or_sslobj # type: ignore[assignment]
307
+ try:
308
+ while not hasattr(sslobj, "get_unverified_chain"):
309
+ sslobj = sslobj._sslobj # type: ignore[attr-defined]
310
+ except AttributeError:
311
+ pass
312
+
313
+ cert_bytes = _get_unverified_chain_bytes(sslobj)
314
+ _verify_peercerts_impl(
315
+ sock_or_sslobj.context, cert_bytes, server_hostname=server_hostname
316
+ )
llava/lib/python3.10/site-packages/pip/_vendor/truststore/_macos.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import ctypes
3
+ import platform
4
+ import ssl
5
+ import typing
6
+ from ctypes import (
7
+ CDLL,
8
+ POINTER,
9
+ c_bool,
10
+ c_char_p,
11
+ c_int32,
12
+ c_long,
13
+ c_uint32,
14
+ c_ulong,
15
+ c_void_p,
16
+ )
17
+ from ctypes.util import find_library
18
+
19
+ from ._ssl_constants import _set_ssl_context_verify_mode
20
+
21
+ _mac_version = platform.mac_ver()[0]
22
+ _mac_version_info = tuple(map(int, _mac_version.split(".")))
23
+ if _mac_version_info < (10, 8):
24
+ raise ImportError(
25
+ f"Only OS X 10.8 and newer are supported, not {_mac_version_info[0]}.{_mac_version_info[1]}"
26
+ )
27
+
28
+ _is_macos_version_10_14_or_later = _mac_version_info >= (10, 14)
29
+
30
+
31
+ def _load_cdll(name: str, macos10_16_path: str) -> CDLL:
32
+ """Loads a CDLL by name, falling back to known path on 10.16+"""
33
+ try:
34
+ # Big Sur is technically 11 but we use 10.16 due to the Big Sur
35
+ # beta being labeled as 10.16.
36
+ path: str | None
37
+ if _mac_version_info >= (10, 16):
38
+ path = macos10_16_path
39
+ else:
40
+ path = find_library(name)
41
+ if not path:
42
+ raise OSError # Caught and reraised as 'ImportError'
43
+ return CDLL(path, use_errno=True)
44
+ except OSError:
45
+ raise ImportError(f"The library {name} failed to load") from None
46
+
47
+
48
+ Security = _load_cdll(
49
+ "Security", "/System/Library/Frameworks/Security.framework/Security"
50
+ )
51
+ CoreFoundation = _load_cdll(
52
+ "CoreFoundation",
53
+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",
54
+ )
55
+
56
+ Boolean = c_bool
57
+ CFIndex = c_long
58
+ CFStringEncoding = c_uint32
59
+ CFData = c_void_p
60
+ CFString = c_void_p
61
+ CFArray = c_void_p
62
+ CFMutableArray = c_void_p
63
+ CFError = c_void_p
64
+ CFType = c_void_p
65
+ CFTypeID = c_ulong
66
+ CFTypeRef = POINTER(CFType)
67
+ CFAllocatorRef = c_void_p
68
+
69
+ OSStatus = c_int32
70
+
71
+ CFErrorRef = POINTER(CFError)
72
+ CFDataRef = POINTER(CFData)
73
+ CFStringRef = POINTER(CFString)
74
+ CFArrayRef = POINTER(CFArray)
75
+ CFMutableArrayRef = POINTER(CFMutableArray)
76
+ CFArrayCallBacks = c_void_p
77
+ CFOptionFlags = c_uint32
78
+
79
+ SecCertificateRef = POINTER(c_void_p)
80
+ SecPolicyRef = POINTER(c_void_p)
81
+ SecTrustRef = POINTER(c_void_p)
82
+ SecTrustResultType = c_uint32
83
+ SecTrustOptionFlags = c_uint32
84
+
85
+ try:
86
+ Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]
87
+ Security.SecCertificateCreateWithData.restype = SecCertificateRef
88
+
89
+ Security.SecCertificateCopyData.argtypes = [SecCertificateRef]
90
+ Security.SecCertificateCopyData.restype = CFDataRef
91
+
92
+ Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]
93
+ Security.SecCopyErrorMessageString.restype = CFStringRef
94
+
95
+ Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]
96
+ Security.SecTrustSetAnchorCertificates.restype = OSStatus
97
+
98
+ Security.SecTrustSetAnchorCertificatesOnly.argtypes = [SecTrustRef, Boolean]
99
+ Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus
100
+
101
+ Security.SecPolicyCreateRevocation.argtypes = [CFOptionFlags]
102
+ Security.SecPolicyCreateRevocation.restype = SecPolicyRef
103
+
104
+ Security.SecPolicyCreateSSL.argtypes = [Boolean, CFStringRef]
105
+ Security.SecPolicyCreateSSL.restype = SecPolicyRef
106
+
107
+ Security.SecTrustCreateWithCertificates.argtypes = [
108
+ CFTypeRef,
109
+ CFTypeRef,
110
+ POINTER(SecTrustRef),
111
+ ]
112
+ Security.SecTrustCreateWithCertificates.restype = OSStatus
113
+
114
+ Security.SecTrustGetTrustResult.argtypes = [
115
+ SecTrustRef,
116
+ POINTER(SecTrustResultType),
117
+ ]
118
+ Security.SecTrustGetTrustResult.restype = OSStatus
119
+
120
+ Security.SecTrustEvaluate.argtypes = [
121
+ SecTrustRef,
122
+ POINTER(SecTrustResultType),
123
+ ]
124
+ Security.SecTrustEvaluate.restype = OSStatus
125
+
126
+ Security.SecTrustRef = SecTrustRef # type: ignore[attr-defined]
127
+ Security.SecTrustResultType = SecTrustResultType # type: ignore[attr-defined]
128
+ Security.OSStatus = OSStatus # type: ignore[attr-defined]
129
+
130
+ kSecRevocationUseAnyAvailableMethod = 3
131
+ kSecRevocationRequirePositiveResponse = 8
132
+
133
+ CoreFoundation.CFRelease.argtypes = [CFTypeRef]
134
+ CoreFoundation.CFRelease.restype = None
135
+
136
+ CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]
137
+ CoreFoundation.CFGetTypeID.restype = CFTypeID
138
+
139
+ CoreFoundation.CFStringCreateWithCString.argtypes = [
140
+ CFAllocatorRef,
141
+ c_char_p,
142
+ CFStringEncoding,
143
+ ]
144
+ CoreFoundation.CFStringCreateWithCString.restype = CFStringRef
145
+
146
+ CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]
147
+ CoreFoundation.CFStringGetCStringPtr.restype = c_char_p
148
+
149
+ CoreFoundation.CFStringGetCString.argtypes = [
150
+ CFStringRef,
151
+ c_char_p,
152
+ CFIndex,
153
+ CFStringEncoding,
154
+ ]
155
+ CoreFoundation.CFStringGetCString.restype = c_bool
156
+
157
+ CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]
158
+ CoreFoundation.CFDataCreate.restype = CFDataRef
159
+
160
+ CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]
161
+ CoreFoundation.CFDataGetLength.restype = CFIndex
162
+
163
+ CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]
164
+ CoreFoundation.CFDataGetBytePtr.restype = c_void_p
165
+
166
+ CoreFoundation.CFArrayCreate.argtypes = [
167
+ CFAllocatorRef,
168
+ POINTER(CFTypeRef),
169
+ CFIndex,
170
+ CFArrayCallBacks,
171
+ ]
172
+ CoreFoundation.CFArrayCreate.restype = CFArrayRef
173
+
174
+ CoreFoundation.CFArrayCreateMutable.argtypes = [
175
+ CFAllocatorRef,
176
+ CFIndex,
177
+ CFArrayCallBacks,
178
+ ]
179
+ CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef
180
+
181
+ CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]
182
+ CoreFoundation.CFArrayAppendValue.restype = None
183
+
184
+ CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]
185
+ CoreFoundation.CFArrayGetCount.restype = CFIndex
186
+
187
+ CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]
188
+ CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p
189
+
190
+ CoreFoundation.CFErrorGetCode.argtypes = [CFErrorRef]
191
+ CoreFoundation.CFErrorGetCode.restype = CFIndex
192
+
193
+ CoreFoundation.CFErrorCopyDescription.argtypes = [CFErrorRef]
194
+ CoreFoundation.CFErrorCopyDescription.restype = CFStringRef
195
+
196
+ CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( # type: ignore[attr-defined]
197
+ CoreFoundation, "kCFAllocatorDefault"
198
+ )
199
+ CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( # type: ignore[attr-defined]
200
+ CoreFoundation, "kCFTypeArrayCallBacks"
201
+ )
202
+
203
+ CoreFoundation.CFTypeRef = CFTypeRef # type: ignore[attr-defined]
204
+ CoreFoundation.CFArrayRef = CFArrayRef # type: ignore[attr-defined]
205
+ CoreFoundation.CFStringRef = CFStringRef # type: ignore[attr-defined]
206
+ CoreFoundation.CFErrorRef = CFErrorRef # type: ignore[attr-defined]
207
+
208
+ except AttributeError as e:
209
+ raise ImportError(f"Error initializing ctypes: {e}") from None
210
+
211
+ # SecTrustEvaluateWithError is macOS 10.14+
212
+ if _is_macos_version_10_14_or_later:
213
+ try:
214
+ Security.SecTrustEvaluateWithError.argtypes = [
215
+ SecTrustRef,
216
+ POINTER(CFErrorRef),
217
+ ]
218
+ Security.SecTrustEvaluateWithError.restype = c_bool
219
+ except AttributeError as e:
220
+ raise ImportError(f"Error initializing ctypes: {e}") from None
221
+
222
+
223
+ def _handle_osstatus(result: OSStatus, _: typing.Any, args: typing.Any) -> typing.Any:
224
+ """
225
+ Raises an error if the OSStatus value is non-zero.
226
+ """
227
+ if int(result) == 0:
228
+ return args
229
+
230
+ # Returns a CFString which we need to transform
231
+ # into a UTF-8 Python string.
232
+ error_message_cfstring = None
233
+ try:
234
+ error_message_cfstring = Security.SecCopyErrorMessageString(result, None)
235
+
236
+ # First step is convert the CFString into a C string pointer.
237
+ # We try the fast no-copy way first.
238
+ error_message_cfstring_c_void_p = ctypes.cast(
239
+ error_message_cfstring, ctypes.POINTER(ctypes.c_void_p)
240
+ )
241
+ message = CoreFoundation.CFStringGetCStringPtr(
242
+ error_message_cfstring_c_void_p, CFConst.kCFStringEncodingUTF8
243
+ )
244
+
245
+ # Quoting the Apple dev docs:
246
+ #
247
+ # "A pointer to a C string or NULL if the internal
248
+ # storage of theString does not allow this to be
249
+ # returned efficiently."
250
+ #
251
+ # So we need to get our hands dirty.
252
+ if message is None:
253
+ buffer = ctypes.create_string_buffer(1024)
254
+ result = CoreFoundation.CFStringGetCString(
255
+ error_message_cfstring_c_void_p,
256
+ buffer,
257
+ 1024,
258
+ CFConst.kCFStringEncodingUTF8,
259
+ )
260
+ if not result:
261
+ raise OSError("Error copying C string from CFStringRef")
262
+ message = buffer.value
263
+
264
+ finally:
265
+ if error_message_cfstring is not None:
266
+ CoreFoundation.CFRelease(error_message_cfstring)
267
+
268
+ # If no message can be found for this status we come
269
+ # up with a generic one that forwards the status code.
270
+ if message is None or message == "":
271
+ message = f"SecureTransport operation returned a non-zero OSStatus: {result}"
272
+
273
+ raise ssl.SSLError(message)
274
+
275
+
276
+ Security.SecTrustCreateWithCertificates.errcheck = _handle_osstatus # type: ignore[assignment]
277
+ Security.SecTrustSetAnchorCertificates.errcheck = _handle_osstatus # type: ignore[assignment]
278
+ Security.SecTrustSetAnchorCertificatesOnly.errcheck = _handle_osstatus # type: ignore[assignment]
279
+ Security.SecTrustGetTrustResult.errcheck = _handle_osstatus # type: ignore[assignment]
280
+ Security.SecTrustEvaluate.errcheck = _handle_osstatus # type: ignore[assignment]
281
+
282
+
283
+ class CFConst:
284
+ """CoreFoundation constants"""
285
+
286
+ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)
287
+
288
+ errSecIncompleteCertRevocationCheck = -67635
289
+ errSecHostNameMismatch = -67602
290
+ errSecCertificateExpired = -67818
291
+ errSecNotTrusted = -67843
292
+
293
+
294
+ def _bytes_to_cf_data_ref(value: bytes) -> CFDataRef: # type: ignore[valid-type]
295
+ return CoreFoundation.CFDataCreate( # type: ignore[no-any-return]
296
+ CoreFoundation.kCFAllocatorDefault, value, len(value)
297
+ )
298
+
299
+
300
+ def _bytes_to_cf_string(value: bytes) -> CFString:
301
+ """
302
+ Given a Python binary data, create a CFString.
303
+ The string must be CFReleased by the caller.
304
+ """
305
+ c_str = ctypes.c_char_p(value)
306
+ cf_str = CoreFoundation.CFStringCreateWithCString(
307
+ CoreFoundation.kCFAllocatorDefault,
308
+ c_str,
309
+ CFConst.kCFStringEncodingUTF8,
310
+ )
311
+ return cf_str # type: ignore[no-any-return]
312
+
313
+
314
+ def _cf_string_ref_to_str(cf_string_ref: CFStringRef) -> str | None: # type: ignore[valid-type]
315
+ """
316
+ Creates a Unicode string from a CFString object. Used entirely for error
317
+ reporting.
318
+ Yes, it annoys me quite a lot that this function is this complex.
319
+ """
320
+
321
+ string = CoreFoundation.CFStringGetCStringPtr(
322
+ cf_string_ref, CFConst.kCFStringEncodingUTF8
323
+ )
324
+ if string is None:
325
+ buffer = ctypes.create_string_buffer(1024)
326
+ result = CoreFoundation.CFStringGetCString(
327
+ cf_string_ref, buffer, 1024, CFConst.kCFStringEncodingUTF8
328
+ )
329
+ if not result:
330
+ raise OSError("Error copying C string from CFStringRef")
331
+ string = buffer.value
332
+ if string is not None:
333
+ string = string.decode("utf-8")
334
+ return string # type: ignore[no-any-return]
335
+
336
+
337
+ def _der_certs_to_cf_cert_array(certs: list[bytes]) -> CFMutableArrayRef: # type: ignore[valid-type]
338
+ """Builds a CFArray of SecCertificateRefs from a list of DER-encoded certificates.
339
+ Responsibility of the caller to call CoreFoundation.CFRelease on the CFArray.
340
+ """
341
+ cf_array = CoreFoundation.CFArrayCreateMutable(
342
+ CoreFoundation.kCFAllocatorDefault,
343
+ 0,
344
+ ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
345
+ )
346
+ if not cf_array:
347
+ raise MemoryError("Unable to allocate memory!")
348
+
349
+ for cert_data in certs:
350
+ cf_data = None
351
+ sec_cert_ref = None
352
+ try:
353
+ cf_data = _bytes_to_cf_data_ref(cert_data)
354
+ sec_cert_ref = Security.SecCertificateCreateWithData(
355
+ CoreFoundation.kCFAllocatorDefault, cf_data
356
+ )
357
+ CoreFoundation.CFArrayAppendValue(cf_array, sec_cert_ref)
358
+ finally:
359
+ if cf_data:
360
+ CoreFoundation.CFRelease(cf_data)
361
+ if sec_cert_ref:
362
+ CoreFoundation.CFRelease(sec_cert_ref)
363
+
364
+ return cf_array # type: ignore[no-any-return]
365
+
366
+
367
+ @contextlib.contextmanager
368
+ def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:
369
+ check_hostname = ctx.check_hostname
370
+ verify_mode = ctx.verify_mode
371
+ ctx.check_hostname = False
372
+ _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)
373
+ try:
374
+ yield
375
+ finally:
376
+ ctx.check_hostname = check_hostname
377
+ _set_ssl_context_verify_mode(ctx, verify_mode)
378
+
379
+
380
+ def _verify_peercerts_impl(
381
+ ssl_context: ssl.SSLContext,
382
+ cert_chain: list[bytes],
383
+ server_hostname: str | None = None,
384
+ ) -> None:
385
+ certs = None
386
+ policies = None
387
+ trust = None
388
+ try:
389
+ # Only set a hostname on the policy if we're verifying the hostname
390
+ # on the leaf certificate.
391
+ if server_hostname is not None and ssl_context.check_hostname:
392
+ cf_str_hostname = None
393
+ try:
394
+ cf_str_hostname = _bytes_to_cf_string(server_hostname.encode("ascii"))
395
+ ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)
396
+ finally:
397
+ if cf_str_hostname:
398
+ CoreFoundation.CFRelease(cf_str_hostname)
399
+ else:
400
+ ssl_policy = Security.SecPolicyCreateSSL(True, None)
401
+
402
+ policies = ssl_policy
403
+ if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:
404
+ # Add explicit policy requiring positive revocation checks
405
+ policies = CoreFoundation.CFArrayCreateMutable(
406
+ CoreFoundation.kCFAllocatorDefault,
407
+ 0,
408
+ ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),
409
+ )
410
+ CoreFoundation.CFArrayAppendValue(policies, ssl_policy)
411
+ CoreFoundation.CFRelease(ssl_policy)
412
+ revocation_policy = Security.SecPolicyCreateRevocation(
413
+ kSecRevocationUseAnyAvailableMethod
414
+ | kSecRevocationRequirePositiveResponse
415
+ )
416
+ CoreFoundation.CFArrayAppendValue(policies, revocation_policy)
417
+ CoreFoundation.CFRelease(revocation_policy)
418
+ elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:
419
+ raise NotImplementedError("VERIFY_CRL_CHECK_LEAF not implemented for macOS")
420
+
421
+ certs = None
422
+ try:
423
+ certs = _der_certs_to_cf_cert_array(cert_chain)
424
+
425
+ # Now that we have certificates loaded and a SecPolicy
426
+ # we can finally create a SecTrust object!
427
+ trust = Security.SecTrustRef()
428
+ Security.SecTrustCreateWithCertificates(
429
+ certs, policies, ctypes.byref(trust)
430
+ )
431
+
432
+ finally:
433
+ # The certs are now being held by SecTrust so we can
434
+ # release our handles for the array.
435
+ if certs:
436
+ CoreFoundation.CFRelease(certs)
437
+
438
+ # If there are additional trust anchors to load we need to transform
439
+ # the list of DER-encoded certificates into a CFArray.
440
+ ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(
441
+ binary_form=True
442
+ )
443
+ if ctx_ca_certs_der:
444
+ ctx_ca_certs = None
445
+ try:
446
+ ctx_ca_certs = _der_certs_to_cf_cert_array(ctx_ca_certs_der)
447
+ Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)
448
+ finally:
449
+ if ctx_ca_certs:
450
+ CoreFoundation.CFRelease(ctx_ca_certs)
451
+
452
+ # We always want system certificates.
453
+ Security.SecTrustSetAnchorCertificatesOnly(trust, False)
454
+
455
+ # macOS 10.13 and earlier don't support SecTrustEvaluateWithError()
456
+ # so we use SecTrustEvaluate() which means we need to construct error
457
+ # messages ourselves.
458
+ if _is_macos_version_10_14_or_later:
459
+ _verify_peercerts_impl_macos_10_14(ssl_context, trust)
460
+ else:
461
+ _verify_peercerts_impl_macos_10_13(ssl_context, trust)
462
+ finally:
463
+ if policies:
464
+ CoreFoundation.CFRelease(policies)
465
+ if trust:
466
+ CoreFoundation.CFRelease(trust)
467
+
468
+
469
+ def _verify_peercerts_impl_macos_10_13(
470
+ ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any
471
+ ) -> None:
472
+ """Verify using 'SecTrustEvaluate' API for macOS 10.13 and earlier.
473
+ macOS 10.14 added the 'SecTrustEvaluateWithError' API.
474
+ """
475
+ sec_trust_result_type = Security.SecTrustResultType()
476
+ Security.SecTrustEvaluate(sec_trust_ref, ctypes.byref(sec_trust_result_type))
477
+
478
+ try:
479
+ sec_trust_result_type_as_int = int(sec_trust_result_type.value)
480
+ except (ValueError, TypeError):
481
+ sec_trust_result_type_as_int = -1
482
+
483
+ # Apple doesn't document these values in their own API docs.
484
+ # See: https://github.com/xybp888/iOS-SDKs/blob/master/iPhoneOS13.0.sdk/System/Library/Frameworks/Security.framework/Headers/SecTrust.h#L84
485
+ if (
486
+ ssl_context.verify_mode == ssl.CERT_REQUIRED
487
+ and sec_trust_result_type_as_int not in (1, 4)
488
+ ):
489
+ # Note that we're not able to ignore only hostname errors
490
+ # for macOS 10.13 and earlier, so check_hostname=False will
491
+ # still return an error.
492
+ sec_trust_result_type_to_message = {
493
+ 0: "Invalid trust result type",
494
+ # 1: "Trust evaluation succeeded",
495
+ 2: "User confirmation required",
496
+ 3: "User specified that certificate is not trusted",
497
+ # 4: "Trust result is unspecified",
498
+ 5: "Recoverable trust failure occurred",
499
+ 6: "Fatal trust failure occurred",
500
+ 7: "Other error occurred, certificate may be revoked",
501
+ }
502
+ error_message = sec_trust_result_type_to_message.get(
503
+ sec_trust_result_type_as_int,
504
+ f"Unknown trust result: {sec_trust_result_type_as_int}",
505
+ )
506
+
507
+ err = ssl.SSLCertVerificationError(error_message)
508
+ err.verify_message = error_message
509
+ err.verify_code = sec_trust_result_type_as_int
510
+ raise err
511
+
512
+
513
+ def _verify_peercerts_impl_macos_10_14(
514
+ ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any
515
+ ) -> None:
516
+ """Verify using 'SecTrustEvaluateWithError' API for macOS 10.14+."""
517
+ cf_error = CoreFoundation.CFErrorRef()
518
+ sec_trust_eval_result = Security.SecTrustEvaluateWithError(
519
+ sec_trust_ref, ctypes.byref(cf_error)
520
+ )
521
+ # sec_trust_eval_result is a bool (0 or 1)
522
+ # where 1 means that the certs are trusted.
523
+ if sec_trust_eval_result == 1:
524
+ is_trusted = True
525
+ elif sec_trust_eval_result == 0:
526
+ is_trusted = False
527
+ else:
528
+ raise ssl.SSLError(
529
+ f"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}"
530
+ )
531
+
532
+ cf_error_code = 0
533
+ if not is_trusted:
534
+ cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)
535
+
536
+ # If the error is a known failure that we're
537
+ # explicitly okay with from SSLContext configuration
538
+ # we can set is_trusted accordingly.
539
+ if ssl_context.verify_mode != ssl.CERT_REQUIRED and (
540
+ cf_error_code == CFConst.errSecNotTrusted
541
+ or cf_error_code == CFConst.errSecCertificateExpired
542
+ ):
543
+ is_trusted = True
544
+
545
+ # If we're still not trusted then we start to
546
+ # construct and raise the SSLCertVerificationError.
547
+ if not is_trusted:
548
+ cf_error_string_ref = None
549
+ try:
550
+ cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)
551
+
552
+ # Can this ever return 'None' if there's a CFError?
553
+ cf_error_message = (
554
+ _cf_string_ref_to_str(cf_error_string_ref)
555
+ or "Certificate verification failed"
556
+ )
557
+
558
+ # TODO: Not sure if we need the SecTrustResultType for anything?
559
+ # We only care whether or not it's a success or failure for now.
560
+ sec_trust_result_type = Security.SecTrustResultType()
561
+ Security.SecTrustGetTrustResult(
562
+ sec_trust_ref, ctypes.byref(sec_trust_result_type)
563
+ )
564
+
565
+ err = ssl.SSLCertVerificationError(cf_error_message)
566
+ err.verify_message = cf_error_message
567
+ err.verify_code = cf_error_code
568
+ raise err
569
+ finally:
570
+ if cf_error_string_ref:
571
+ CoreFoundation.CFRelease(cf_error_string_ref)
llava/lib/python3.10/site-packages/pip/_vendor/truststore/_openssl.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import os
3
+ import re
4
+ import ssl
5
+ import typing
6
+
7
+ # candidates based on https://github.com/tiran/certifi-system-store by Christian Heimes
8
+ _CA_FILE_CANDIDATES = [
9
+ # Alpine, Arch, Fedora 34+, OpenWRT, RHEL 9+, BSD
10
+ "/etc/ssl/cert.pem",
11
+ # Fedora <= 34, RHEL <= 9, CentOS <= 9
12
+ "/etc/pki/tls/cert.pem",
13
+ # Debian, Ubuntu (requires ca-certificates)
14
+ "/etc/ssl/certs/ca-certificates.crt",
15
+ # SUSE
16
+ "/etc/ssl/ca-bundle.pem",
17
+ ]
18
+
19
+ _HASHED_CERT_FILENAME_RE = re.compile(r"^[0-9a-fA-F]{8}\.[0-9]$")
20
+
21
+
22
+ @contextlib.contextmanager
23
+ def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:
24
+ # First, check whether the default locations from OpenSSL
25
+ # seem like they will give us a usable set of CA certs.
26
+ # ssl.get_default_verify_paths already takes care of:
27
+ # - getting cafile from either the SSL_CERT_FILE env var
28
+ # or the path configured when OpenSSL was compiled,
29
+ # and verifying that that path exists
30
+ # - getting capath from either the SSL_CERT_DIR env var
31
+ # or the path configured when OpenSSL was compiled,
32
+ # and verifying that that path exists
33
+ # In addition we'll check whether capath appears to contain certs.
34
+ defaults = ssl.get_default_verify_paths()
35
+ if defaults.cafile or (defaults.capath and _capath_contains_certs(defaults.capath)):
36
+ ctx.set_default_verify_paths()
37
+ else:
38
+ # cafile from OpenSSL doesn't exist
39
+ # and capath from OpenSSL doesn't contain certs.
40
+ # Let's search other common locations instead.
41
+ for cafile in _CA_FILE_CANDIDATES:
42
+ if os.path.isfile(cafile):
43
+ ctx.load_verify_locations(cafile=cafile)
44
+ break
45
+
46
+ yield
47
+
48
+
49
+ def _capath_contains_certs(capath: str) -> bool:
50
+ """Check whether capath exists and contains certs in the expected format."""
51
+ if not os.path.isdir(capath):
52
+ return False
53
+ for name in os.listdir(capath):
54
+ if _HASHED_CERT_FILENAME_RE.match(name):
55
+ return True
56
+ return False
57
+
58
+
59
+ def _verify_peercerts_impl(
60
+ ssl_context: ssl.SSLContext,
61
+ cert_chain: list[bytes],
62
+ server_hostname: str | None = None,
63
+ ) -> None:
64
+ # This is a no-op because we've enabled SSLContext's built-in
65
+ # verification via verify_mode=CERT_REQUIRED, and don't need to repeat it.
66
+ pass
llava/lib/python3.10/site-packages/pip/_vendor/truststore/_ssl_constants.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ssl
2
+ import sys
3
+ import typing
4
+
5
+ # Hold on to the original class so we can create it consistently
6
+ # even if we inject our own SSLContext into the ssl module.
7
+ _original_SSLContext = ssl.SSLContext
8
+ _original_super_SSLContext = super(_original_SSLContext, _original_SSLContext)
9
+
10
+ # CPython is known to be good, but non-CPython implementations
11
+ # may implement SSLContext differently so to be safe we don't
12
+ # subclass the SSLContext.
13
+
14
+ # This is returned by truststore.SSLContext.__class__()
15
+ _truststore_SSLContext_dunder_class: typing.Optional[type]
16
+
17
+ # This value is the superclass of truststore.SSLContext.
18
+ _truststore_SSLContext_super_class: type
19
+
20
+ if sys.implementation.name == "cpython":
21
+ _truststore_SSLContext_super_class = _original_SSLContext
22
+ _truststore_SSLContext_dunder_class = None
23
+ else:
24
+ _truststore_SSLContext_super_class = object
25
+ _truststore_SSLContext_dunder_class = _original_SSLContext
26
+
27
+
28
+ def _set_ssl_context_verify_mode(
29
+ ssl_context: ssl.SSLContext, verify_mode: ssl.VerifyMode
30
+ ) -> None:
31
+ _original_super_SSLContext.verify_mode.__set__(ssl_context, verify_mode) # type: ignore[attr-defined]
llava/lib/python3.10/site-packages/pip/_vendor/truststore/_windows.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import ssl
3
+ import typing
4
+ from ctypes import WinDLL # type: ignore
5
+ from ctypes import WinError # type: ignore
6
+ from ctypes import (
7
+ POINTER,
8
+ Structure,
9
+ c_char_p,
10
+ c_ulong,
11
+ c_void_p,
12
+ c_wchar_p,
13
+ cast,
14
+ create_unicode_buffer,
15
+ pointer,
16
+ sizeof,
17
+ )
18
+ from ctypes.wintypes import (
19
+ BOOL,
20
+ DWORD,
21
+ HANDLE,
22
+ LONG,
23
+ LPCSTR,
24
+ LPCVOID,
25
+ LPCWSTR,
26
+ LPFILETIME,
27
+ LPSTR,
28
+ LPWSTR,
29
+ )
30
+ from typing import TYPE_CHECKING, Any
31
+
32
+ from ._ssl_constants import _set_ssl_context_verify_mode
33
+
34
+ HCERTCHAINENGINE = HANDLE
35
+ HCERTSTORE = HANDLE
36
+ HCRYPTPROV_LEGACY = HANDLE
37
+
38
+
39
+ class CERT_CONTEXT(Structure):
40
+ _fields_ = (
41
+ ("dwCertEncodingType", DWORD),
42
+ ("pbCertEncoded", c_void_p),
43
+ ("cbCertEncoded", DWORD),
44
+ ("pCertInfo", c_void_p),
45
+ ("hCertStore", HCERTSTORE),
46
+ )
47
+
48
+
49
+ PCERT_CONTEXT = POINTER(CERT_CONTEXT)
50
+ PCCERT_CONTEXT = POINTER(PCERT_CONTEXT)
51
+
52
+
53
+ class CERT_ENHKEY_USAGE(Structure):
54
+ _fields_ = (
55
+ ("cUsageIdentifier", DWORD),
56
+ ("rgpszUsageIdentifier", POINTER(LPSTR)),
57
+ )
58
+
59
+
60
+ PCERT_ENHKEY_USAGE = POINTER(CERT_ENHKEY_USAGE)
61
+
62
+
63
+ class CERT_USAGE_MATCH(Structure):
64
+ _fields_ = (
65
+ ("dwType", DWORD),
66
+ ("Usage", CERT_ENHKEY_USAGE),
67
+ )
68
+
69
+
70
+ class CERT_CHAIN_PARA(Structure):
71
+ _fields_ = (
72
+ ("cbSize", DWORD),
73
+ ("RequestedUsage", CERT_USAGE_MATCH),
74
+ ("RequestedIssuancePolicy", CERT_USAGE_MATCH),
75
+ ("dwUrlRetrievalTimeout", DWORD),
76
+ ("fCheckRevocationFreshnessTime", BOOL),
77
+ ("dwRevocationFreshnessTime", DWORD),
78
+ ("pftCacheResync", LPFILETIME),
79
+ ("pStrongSignPara", c_void_p),
80
+ ("dwStrongSignFlags", DWORD),
81
+ )
82
+
83
+
84
+ if TYPE_CHECKING:
85
+ PCERT_CHAIN_PARA = pointer[CERT_CHAIN_PARA] # type: ignore[misc]
86
+ else:
87
+ PCERT_CHAIN_PARA = POINTER(CERT_CHAIN_PARA)
88
+
89
+
90
+ class CERT_TRUST_STATUS(Structure):
91
+ _fields_ = (
92
+ ("dwErrorStatus", DWORD),
93
+ ("dwInfoStatus", DWORD),
94
+ )
95
+
96
+
97
+ class CERT_CHAIN_ELEMENT(Structure):
98
+ _fields_ = (
99
+ ("cbSize", DWORD),
100
+ ("pCertContext", PCERT_CONTEXT),
101
+ ("TrustStatus", CERT_TRUST_STATUS),
102
+ ("pRevocationInfo", c_void_p),
103
+ ("pIssuanceUsage", PCERT_ENHKEY_USAGE),
104
+ ("pApplicationUsage", PCERT_ENHKEY_USAGE),
105
+ ("pwszExtendedErrorInfo", LPCWSTR),
106
+ )
107
+
108
+
109
+ PCERT_CHAIN_ELEMENT = POINTER(CERT_CHAIN_ELEMENT)
110
+
111
+
112
+ class CERT_SIMPLE_CHAIN(Structure):
113
+ _fields_ = (
114
+ ("cbSize", DWORD),
115
+ ("TrustStatus", CERT_TRUST_STATUS),
116
+ ("cElement", DWORD),
117
+ ("rgpElement", POINTER(PCERT_CHAIN_ELEMENT)),
118
+ ("pTrustListInfo", c_void_p),
119
+ ("fHasRevocationFreshnessTime", BOOL),
120
+ ("dwRevocationFreshnessTime", DWORD),
121
+ )
122
+
123
+
124
+ PCERT_SIMPLE_CHAIN = POINTER(CERT_SIMPLE_CHAIN)
125
+
126
+
127
+ class CERT_CHAIN_CONTEXT(Structure):
128
+ _fields_ = (
129
+ ("cbSize", DWORD),
130
+ ("TrustStatus", CERT_TRUST_STATUS),
131
+ ("cChain", DWORD),
132
+ ("rgpChain", POINTER(PCERT_SIMPLE_CHAIN)),
133
+ ("cLowerQualityChainContext", DWORD),
134
+ ("rgpLowerQualityChainContext", c_void_p),
135
+ ("fHasRevocationFreshnessTime", BOOL),
136
+ ("dwRevocationFreshnessTime", DWORD),
137
+ )
138
+
139
+
140
+ PCERT_CHAIN_CONTEXT = POINTER(CERT_CHAIN_CONTEXT)
141
+ PCCERT_CHAIN_CONTEXT = POINTER(PCERT_CHAIN_CONTEXT)
142
+
143
+
144
+ class SSL_EXTRA_CERT_CHAIN_POLICY_PARA(Structure):
145
+ _fields_ = (
146
+ ("cbSize", DWORD),
147
+ ("dwAuthType", DWORD),
148
+ ("fdwChecks", DWORD),
149
+ ("pwszServerName", LPCWSTR),
150
+ )
151
+
152
+
153
+ class CERT_CHAIN_POLICY_PARA(Structure):
154
+ _fields_ = (
155
+ ("cbSize", DWORD),
156
+ ("dwFlags", DWORD),
157
+ ("pvExtraPolicyPara", c_void_p),
158
+ )
159
+
160
+
161
+ PCERT_CHAIN_POLICY_PARA = POINTER(CERT_CHAIN_POLICY_PARA)
162
+
163
+
164
+ class CERT_CHAIN_POLICY_STATUS(Structure):
165
+ _fields_ = (
166
+ ("cbSize", DWORD),
167
+ ("dwError", DWORD),
168
+ ("lChainIndex", LONG),
169
+ ("lElementIndex", LONG),
170
+ ("pvExtraPolicyStatus", c_void_p),
171
+ )
172
+
173
+
174
+ PCERT_CHAIN_POLICY_STATUS = POINTER(CERT_CHAIN_POLICY_STATUS)
175
+
176
+
177
+ class CERT_CHAIN_ENGINE_CONFIG(Structure):
178
+ _fields_ = (
179
+ ("cbSize", DWORD),
180
+ ("hRestrictedRoot", HCERTSTORE),
181
+ ("hRestrictedTrust", HCERTSTORE),
182
+ ("hRestrictedOther", HCERTSTORE),
183
+ ("cAdditionalStore", DWORD),
184
+ ("rghAdditionalStore", c_void_p),
185
+ ("dwFlags", DWORD),
186
+ ("dwUrlRetrievalTimeout", DWORD),
187
+ ("MaximumCachedCertificates", DWORD),
188
+ ("CycleDetectionModulus", DWORD),
189
+ ("hExclusiveRoot", HCERTSTORE),
190
+ ("hExclusiveTrustedPeople", HCERTSTORE),
191
+ ("dwExclusiveFlags", DWORD),
192
+ )
193
+
194
+
195
+ PCERT_CHAIN_ENGINE_CONFIG = POINTER(CERT_CHAIN_ENGINE_CONFIG)
196
+ PHCERTCHAINENGINE = POINTER(HCERTCHAINENGINE)
197
+
198
+ X509_ASN_ENCODING = 0x00000001
199
+ PKCS_7_ASN_ENCODING = 0x00010000
200
+ CERT_STORE_PROV_MEMORY = b"Memory"
201
+ CERT_STORE_ADD_USE_EXISTING = 2
202
+ USAGE_MATCH_TYPE_OR = 1
203
+ OID_PKIX_KP_SERVER_AUTH = c_char_p(b"1.3.6.1.5.5.7.3.1")
204
+ CERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000
205
+ CERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000
206
+ CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS = 0x00000007
207
+ CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG = 0x00000008
208
+ CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 0x00000010
209
+ CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG = 0x00000040
210
+ CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG = 0x00000020
211
+ CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG = 0x00000080
212
+ CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS = 0x00000F00
213
+ CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG = 0x00008000
214
+ CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG = 0x00004000
215
+ SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000
216
+ AUTHTYPE_SERVER = 2
217
+ CERT_CHAIN_POLICY_SSL = 4
218
+ FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
219
+ FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
220
+
221
+ # Flags to set for SSLContext.verify_mode=CERT_NONE
222
+ CERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS = (
223
+ CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS
224
+ | CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG
225
+ | CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG
226
+ | CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG
227
+ | CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG
228
+ | CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG
229
+ | CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
230
+ | CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG
231
+ | CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG
232
+ )
233
+
234
+ wincrypt = WinDLL("crypt32.dll")
235
+ kernel32 = WinDLL("kernel32.dll")
236
+
237
+
238
+ def _handle_win_error(result: bool, _: Any, args: Any) -> Any:
239
+ if not result:
240
+ # Note, actually raises OSError after calling GetLastError and FormatMessage
241
+ raise WinError()
242
+ return args
243
+
244
+
245
+ CertCreateCertificateChainEngine = wincrypt.CertCreateCertificateChainEngine
246
+ CertCreateCertificateChainEngine.argtypes = (
247
+ PCERT_CHAIN_ENGINE_CONFIG,
248
+ PHCERTCHAINENGINE,
249
+ )
250
+ CertCreateCertificateChainEngine.errcheck = _handle_win_error
251
+
252
+ CertOpenStore = wincrypt.CertOpenStore
253
+ CertOpenStore.argtypes = (LPCSTR, DWORD, HCRYPTPROV_LEGACY, DWORD, c_void_p)
254
+ CertOpenStore.restype = HCERTSTORE
255
+ CertOpenStore.errcheck = _handle_win_error
256
+
257
+ CertAddEncodedCertificateToStore = wincrypt.CertAddEncodedCertificateToStore
258
+ CertAddEncodedCertificateToStore.argtypes = (
259
+ HCERTSTORE,
260
+ DWORD,
261
+ c_char_p,
262
+ DWORD,
263
+ DWORD,
264
+ PCCERT_CONTEXT,
265
+ )
266
+ CertAddEncodedCertificateToStore.restype = BOOL
267
+
268
+ CertCreateCertificateContext = wincrypt.CertCreateCertificateContext
269
+ CertCreateCertificateContext.argtypes = (DWORD, c_char_p, DWORD)
270
+ CertCreateCertificateContext.restype = PCERT_CONTEXT
271
+ CertCreateCertificateContext.errcheck = _handle_win_error
272
+
273
+ CertGetCertificateChain = wincrypt.CertGetCertificateChain
274
+ CertGetCertificateChain.argtypes = (
275
+ HCERTCHAINENGINE,
276
+ PCERT_CONTEXT,
277
+ LPFILETIME,
278
+ HCERTSTORE,
279
+ PCERT_CHAIN_PARA,
280
+ DWORD,
281
+ c_void_p,
282
+ PCCERT_CHAIN_CONTEXT,
283
+ )
284
+ CertGetCertificateChain.restype = BOOL
285
+ CertGetCertificateChain.errcheck = _handle_win_error
286
+
287
+ CertVerifyCertificateChainPolicy = wincrypt.CertVerifyCertificateChainPolicy
288
+ CertVerifyCertificateChainPolicy.argtypes = (
289
+ c_ulong,
290
+ PCERT_CHAIN_CONTEXT,
291
+ PCERT_CHAIN_POLICY_PARA,
292
+ PCERT_CHAIN_POLICY_STATUS,
293
+ )
294
+ CertVerifyCertificateChainPolicy.restype = BOOL
295
+
296
+ CertCloseStore = wincrypt.CertCloseStore
297
+ CertCloseStore.argtypes = (HCERTSTORE, DWORD)
298
+ CertCloseStore.restype = BOOL
299
+ CertCloseStore.errcheck = _handle_win_error
300
+
301
+ CertFreeCertificateChain = wincrypt.CertFreeCertificateChain
302
+ CertFreeCertificateChain.argtypes = (PCERT_CHAIN_CONTEXT,)
303
+
304
+ CertFreeCertificateContext = wincrypt.CertFreeCertificateContext
305
+ CertFreeCertificateContext.argtypes = (PCERT_CONTEXT,)
306
+
307
+ CertFreeCertificateChainEngine = wincrypt.CertFreeCertificateChainEngine
308
+ CertFreeCertificateChainEngine.argtypes = (HCERTCHAINENGINE,)
309
+
310
+ FormatMessageW = kernel32.FormatMessageW
311
+ FormatMessageW.argtypes = (
312
+ DWORD,
313
+ LPCVOID,
314
+ DWORD,
315
+ DWORD,
316
+ LPWSTR,
317
+ DWORD,
318
+ c_void_p,
319
+ )
320
+ FormatMessageW.restype = DWORD
321
+
322
+
323
+ def _verify_peercerts_impl(
324
+ ssl_context: ssl.SSLContext,
325
+ cert_chain: list[bytes],
326
+ server_hostname: str | None = None,
327
+ ) -> None:
328
+ """Verify the cert_chain from the server using Windows APIs."""
329
+
330
+ # If the peer didn't send any certificates then
331
+ # we can't do verification. Raise an error.
332
+ if not cert_chain:
333
+ raise ssl.SSLCertVerificationError("Peer sent no certificates to verify")
334
+
335
+ pCertContext = None
336
+ hIntermediateCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)
337
+ try:
338
+ # Add intermediate certs to an in-memory cert store
339
+ for cert_bytes in cert_chain[1:]:
340
+ CertAddEncodedCertificateToStore(
341
+ hIntermediateCertStore,
342
+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
343
+ cert_bytes,
344
+ len(cert_bytes),
345
+ CERT_STORE_ADD_USE_EXISTING,
346
+ None,
347
+ )
348
+
349
+ # Cert context for leaf cert
350
+ leaf_cert = cert_chain[0]
351
+ pCertContext = CertCreateCertificateContext(
352
+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, leaf_cert, len(leaf_cert)
353
+ )
354
+
355
+ # Chain params to match certs for serverAuth extended usage
356
+ cert_enhkey_usage = CERT_ENHKEY_USAGE()
357
+ cert_enhkey_usage.cUsageIdentifier = 1
358
+ cert_enhkey_usage.rgpszUsageIdentifier = (c_char_p * 1)(OID_PKIX_KP_SERVER_AUTH)
359
+ cert_usage_match = CERT_USAGE_MATCH()
360
+ cert_usage_match.Usage = cert_enhkey_usage
361
+ chain_params = CERT_CHAIN_PARA()
362
+ chain_params.RequestedUsage = cert_usage_match
363
+ chain_params.cbSize = sizeof(chain_params)
364
+ pChainPara = pointer(chain_params)
365
+
366
+ if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:
367
+ chain_flags = CERT_CHAIN_REVOCATION_CHECK_CHAIN
368
+ elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:
369
+ chain_flags = CERT_CHAIN_REVOCATION_CHECK_END_CERT
370
+ else:
371
+ chain_flags = 0
372
+
373
+ try:
374
+ # First attempt to verify using the default Windows system trust roots
375
+ # (default chain engine).
376
+ _get_and_verify_cert_chain(
377
+ ssl_context,
378
+ None,
379
+ hIntermediateCertStore,
380
+ pCertContext,
381
+ pChainPara,
382
+ server_hostname,
383
+ chain_flags=chain_flags,
384
+ )
385
+ except ssl.SSLCertVerificationError as e:
386
+ # If that fails but custom CA certs have been added
387
+ # to the SSLContext using load_verify_locations,
388
+ # try verifying using a custom chain engine
389
+ # that trusts the custom CA certs.
390
+ custom_ca_certs: list[bytes] | None = ssl_context.get_ca_certs(
391
+ binary_form=True
392
+ )
393
+ if custom_ca_certs:
394
+ try:
395
+ _verify_using_custom_ca_certs(
396
+ ssl_context,
397
+ custom_ca_certs,
398
+ hIntermediateCertStore,
399
+ pCertContext,
400
+ pChainPara,
401
+ server_hostname,
402
+ chain_flags=chain_flags,
403
+ )
404
+ # Raise the original error, not the new error.
405
+ except ssl.SSLCertVerificationError:
406
+ raise e from None
407
+ else:
408
+ raise
409
+ finally:
410
+ CertCloseStore(hIntermediateCertStore, 0)
411
+ if pCertContext:
412
+ CertFreeCertificateContext(pCertContext)
413
+
414
+
415
+ def _get_and_verify_cert_chain(
416
+ ssl_context: ssl.SSLContext,
417
+ hChainEngine: HCERTCHAINENGINE | None,
418
+ hIntermediateCertStore: HCERTSTORE,
419
+ pPeerCertContext: c_void_p,
420
+ pChainPara: PCERT_CHAIN_PARA, # type: ignore[valid-type]
421
+ server_hostname: str | None,
422
+ chain_flags: int,
423
+ ) -> None:
424
+ ppChainContext = None
425
+ try:
426
+ # Get cert chain
427
+ ppChainContext = pointer(PCERT_CHAIN_CONTEXT())
428
+ CertGetCertificateChain(
429
+ hChainEngine, # chain engine
430
+ pPeerCertContext, # leaf cert context
431
+ None, # current system time
432
+ hIntermediateCertStore, # additional in-memory cert store
433
+ pChainPara, # chain-building parameters
434
+ chain_flags,
435
+ None, # reserved
436
+ ppChainContext, # the resulting chain context
437
+ )
438
+ pChainContext = ppChainContext.contents
439
+
440
+ # Verify cert chain
441
+ ssl_extra_cert_chain_policy_para = SSL_EXTRA_CERT_CHAIN_POLICY_PARA()
442
+ ssl_extra_cert_chain_policy_para.cbSize = sizeof(
443
+ ssl_extra_cert_chain_policy_para
444
+ )
445
+ ssl_extra_cert_chain_policy_para.dwAuthType = AUTHTYPE_SERVER
446
+ ssl_extra_cert_chain_policy_para.fdwChecks = 0
447
+ if ssl_context.check_hostname is False:
448
+ ssl_extra_cert_chain_policy_para.fdwChecks = (
449
+ SECURITY_FLAG_IGNORE_CERT_CN_INVALID
450
+ )
451
+ if server_hostname:
452
+ ssl_extra_cert_chain_policy_para.pwszServerName = c_wchar_p(server_hostname)
453
+
454
+ chain_policy = CERT_CHAIN_POLICY_PARA()
455
+ chain_policy.pvExtraPolicyPara = cast(
456
+ pointer(ssl_extra_cert_chain_policy_para), c_void_p
457
+ )
458
+ if ssl_context.verify_mode == ssl.CERT_NONE:
459
+ chain_policy.dwFlags |= CERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS
460
+ chain_policy.cbSize = sizeof(chain_policy)
461
+
462
+ pPolicyPara = pointer(chain_policy)
463
+ policy_status = CERT_CHAIN_POLICY_STATUS()
464
+ policy_status.cbSize = sizeof(policy_status)
465
+ pPolicyStatus = pointer(policy_status)
466
+ CertVerifyCertificateChainPolicy(
467
+ CERT_CHAIN_POLICY_SSL,
468
+ pChainContext,
469
+ pPolicyPara,
470
+ pPolicyStatus,
471
+ )
472
+
473
+ # Check status
474
+ error_code = policy_status.dwError
475
+ if error_code:
476
+ # Try getting a human readable message for an error code.
477
+ error_message_buf = create_unicode_buffer(1024)
478
+ error_message_chars = FormatMessageW(
479
+ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
480
+ None,
481
+ error_code,
482
+ 0,
483
+ error_message_buf,
484
+ sizeof(error_message_buf),
485
+ None,
486
+ )
487
+
488
+ # See if we received a message for the error,
489
+ # otherwise we use a generic error with the
490
+ # error code and hope that it's search-able.
491
+ if error_message_chars <= 0:
492
+ error_message = f"Certificate chain policy error {error_code:#x} [{policy_status.lElementIndex}]"
493
+ else:
494
+ error_message = error_message_buf.value.strip()
495
+
496
+ err = ssl.SSLCertVerificationError(error_message)
497
+ err.verify_message = error_message
498
+ err.verify_code = error_code
499
+ raise err from None
500
+ finally:
501
+ if ppChainContext:
502
+ CertFreeCertificateChain(ppChainContext.contents)
503
+
504
+
505
+ def _verify_using_custom_ca_certs(
506
+ ssl_context: ssl.SSLContext,
507
+ custom_ca_certs: list[bytes],
508
+ hIntermediateCertStore: HCERTSTORE,
509
+ pPeerCertContext: c_void_p,
510
+ pChainPara: PCERT_CHAIN_PARA, # type: ignore[valid-type]
511
+ server_hostname: str | None,
512
+ chain_flags: int,
513
+ ) -> None:
514
+ hChainEngine = None
515
+ hRootCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)
516
+ try:
517
+ # Add custom CA certs to an in-memory cert store
518
+ for cert_bytes in custom_ca_certs:
519
+ CertAddEncodedCertificateToStore(
520
+ hRootCertStore,
521
+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
522
+ cert_bytes,
523
+ len(cert_bytes),
524
+ CERT_STORE_ADD_USE_EXISTING,
525
+ None,
526
+ )
527
+
528
+ # Create a custom cert chain engine which exclusively trusts
529
+ # certs from our hRootCertStore
530
+ cert_chain_engine_config = CERT_CHAIN_ENGINE_CONFIG()
531
+ cert_chain_engine_config.cbSize = sizeof(cert_chain_engine_config)
532
+ cert_chain_engine_config.hExclusiveRoot = hRootCertStore
533
+ pConfig = pointer(cert_chain_engine_config)
534
+ phChainEngine = pointer(HCERTCHAINENGINE())
535
+ CertCreateCertificateChainEngine(
536
+ pConfig,
537
+ phChainEngine,
538
+ )
539
+ hChainEngine = phChainEngine.contents
540
+
541
+ # Get and verify a cert chain using the custom chain engine
542
+ _get_and_verify_cert_chain(
543
+ ssl_context,
544
+ hChainEngine,
545
+ hIntermediateCertStore,
546
+ pPeerCertContext,
547
+ pChainPara,
548
+ server_hostname,
549
+ chain_flags,
550
+ )
551
+ finally:
552
+ if hChainEngine:
553
+ CertFreeCertificateChainEngine(hChainEngine)
554
+ CertCloseStore(hRootCertStore, 0)
555
+
556
+
557
+ @contextlib.contextmanager
558
+ def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:
559
+ check_hostname = ctx.check_hostname
560
+ verify_mode = ctx.verify_mode
561
+ ctx.check_hostname = False
562
+ _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)
563
+ try:
564
+ yield
565
+ finally:
566
+ ctx.check_hostname = check_hostname
567
+ _set_ssl_context_verify_mode(ctx, verify_mode)
llava/lib/python3.10/site-packages/pip/_vendor/truststore/py.typed ADDED
File without changes
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.49 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/_collections.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/_version.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/connection.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/connectionpool.cpython-310.pyc ADDED
Binary file (25.9 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/fields.cpython-310.pyc ADDED
Binary file (8.16 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/filepost.cpython-310.pyc ADDED
Binary file (2.73 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/poolmanager.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/request.cpython-310.pyc ADDED
Binary file (6.36 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/__pycache__/response.cpython-310.pyc ADDED
Binary file (22.5 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/__init__.py ADDED
File without changes
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/__pycache__/six.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__init__.py ADDED
File without changes
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (189 Bytes). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__pycache__/makefile.cpython-310.pyc ADDED
Binary file (1.29 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/__pycache__/weakref_finalize.cpython-310.pyc ADDED
Binary file (4.89 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ backports.makefile
4
+ ~~~~~~~~~~~~~~~~~~
5
+
6
+ Backports the Python 3 ``socket.makefile`` method for use with anything that
7
+ wants to create a "fake" socket object.
8
+ """
9
+ import io
10
+ from socket import SocketIO
11
+
12
+
13
+ def backport_makefile(
14
+ self, mode="r", buffering=None, encoding=None, errors=None, newline=None
15
+ ):
16
+ """
17
+ Backport of ``socket.makefile`` from Python 3.5.
18
+ """
19
+ if not set(mode) <= {"r", "w", "b"}:
20
+ raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
21
+ writing = "w" in mode
22
+ reading = "r" in mode or not writing
23
+ assert reading or writing
24
+ binary = "b" in mode
25
+ rawmode = ""
26
+ if reading:
27
+ rawmode += "r"
28
+ if writing:
29
+ rawmode += "w"
30
+ raw = SocketIO(self, rawmode)
31
+ self._makefile_refs += 1
32
+ if buffering is None:
33
+ buffering = -1
34
+ if buffering < 0:
35
+ buffering = io.DEFAULT_BUFFER_SIZE
36
+ if buffering == 0:
37
+ if not binary:
38
+ raise ValueError("unbuffered streams must be binary")
39
+ return raw
40
+ if reading and writing:
41
+ buffer = io.BufferedRWPair(raw, raw, buffering)
42
+ elif reading:
43
+ buffer = io.BufferedReader(raw, buffering)
44
+ else:
45
+ assert writing
46
+ buffer = io.BufferedWriter(raw, buffering)
47
+ if binary:
48
+ return buffer
49
+ text = io.TextIOWrapper(buffer, encoding, errors, newline)
50
+ text.mode = mode
51
+ return text
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/backports/weakref_finalize.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ backports.weakref_finalize
4
+ ~~~~~~~~~~~~~~~~~~
5
+
6
+ Backports the Python 3 ``weakref.finalize`` method.
7
+ """
8
+ from __future__ import absolute_import
9
+
10
+ import itertools
11
+ import sys
12
+ from weakref import ref
13
+
14
+ __all__ = ["weakref_finalize"]
15
+
16
+
17
+ class weakref_finalize(object):
18
+ """Class for finalization of weakrefable objects
19
+ finalize(obj, func, *args, **kwargs) returns a callable finalizer
20
+ object which will be called when obj is garbage collected. The
21
+ first time the finalizer is called it evaluates func(*arg, **kwargs)
22
+ and returns the result. After this the finalizer is dead, and
23
+ calling it just returns None.
24
+ When the program exits any remaining finalizers for which the
25
+ atexit attribute is true will be run in reverse order of creation.
26
+ By default atexit is true.
27
+ """
28
+
29
+ # Finalizer objects don't have any state of their own. They are
30
+ # just used as keys to lookup _Info objects in the registry. This
31
+ # ensures that they cannot be part of a ref-cycle.
32
+
33
+ __slots__ = ()
34
+ _registry = {}
35
+ _shutdown = False
36
+ _index_iter = itertools.count()
37
+ _dirty = False
38
+ _registered_with_atexit = False
39
+
40
+ class _Info(object):
41
+ __slots__ = ("weakref", "func", "args", "kwargs", "atexit", "index")
42
+
43
+ def __init__(self, obj, func, *args, **kwargs):
44
+ if not self._registered_with_atexit:
45
+ # We may register the exit function more than once because
46
+ # of a thread race, but that is harmless
47
+ import atexit
48
+
49
+ atexit.register(self._exitfunc)
50
+ weakref_finalize._registered_with_atexit = True
51
+ info = self._Info()
52
+ info.weakref = ref(obj, self)
53
+ info.func = func
54
+ info.args = args
55
+ info.kwargs = kwargs or None
56
+ info.atexit = True
57
+ info.index = next(self._index_iter)
58
+ self._registry[self] = info
59
+ weakref_finalize._dirty = True
60
+
61
+ def __call__(self, _=None):
62
+ """If alive then mark as dead and return func(*args, **kwargs);
63
+ otherwise return None"""
64
+ info = self._registry.pop(self, None)
65
+ if info and not self._shutdown:
66
+ return info.func(*info.args, **(info.kwargs or {}))
67
+
68
+ def detach(self):
69
+ """If alive then mark as dead and return (obj, func, args, kwargs);
70
+ otherwise return None"""
71
+ info = self._registry.get(self)
72
+ obj = info and info.weakref()
73
+ if obj is not None and self._registry.pop(self, None):
74
+ return (obj, info.func, info.args, info.kwargs or {})
75
+
76
+ def peek(self):
77
+ """If alive then return (obj, func, args, kwargs);
78
+ otherwise return None"""
79
+ info = self._registry.get(self)
80
+ obj = info and info.weakref()
81
+ if obj is not None:
82
+ return (obj, info.func, info.args, info.kwargs or {})
83
+
84
+ @property
85
+ def alive(self):
86
+ """Whether finalizer is alive"""
87
+ return self in self._registry
88
+
89
+ @property
90
+ def atexit(self):
91
+ """Whether finalizer should be called at exit"""
92
+ info = self._registry.get(self)
93
+ return bool(info) and info.atexit
94
+
95
+ @atexit.setter
96
+ def atexit(self, value):
97
+ info = self._registry.get(self)
98
+ if info:
99
+ info.atexit = bool(value)
100
+
101
+ def __repr__(self):
102
+ info = self._registry.get(self)
103
+ obj = info and info.weakref()
104
+ if obj is None:
105
+ return "<%s object at %#x; dead>" % (type(self).__name__, id(self))
106
+ else:
107
+ return "<%s object at %#x; for %r at %#x>" % (
108
+ type(self).__name__,
109
+ id(self),
110
+ type(obj).__name__,
111
+ id(obj),
112
+ )
113
+
114
+ @classmethod
115
+ def _select_for_exit(cls):
116
+ # Return live finalizers marked for exit, oldest first
117
+ L = [(f, i) for (f, i) in cls._registry.items() if i.atexit]
118
+ L.sort(key=lambda item: item[1].index)
119
+ return [f for (f, i) in L]
120
+
121
+ @classmethod
122
+ def _exitfunc(cls):
123
+ # At shutdown invoke finalizers for which atexit is true.
124
+ # This is called once all other non-daemonic threads have been
125
+ # joined.
126
+ reenable_gc = False
127
+ try:
128
+ if cls._registry:
129
+ import gc
130
+
131
+ if gc.isenabled():
132
+ reenable_gc = True
133
+ gc.disable()
134
+ pending = None
135
+ while True:
136
+ if pending is None or weakref_finalize._dirty:
137
+ pending = cls._select_for_exit()
138
+ weakref_finalize._dirty = False
139
+ if not pending:
140
+ break
141
+ f = pending.pop()
142
+ try:
143
+ # gc is disabled, so (assuming no daemonic
144
+ # threads) the following is the only line in
145
+ # this function which might trigger creation
146
+ # of a new finalizer
147
+ f()
148
+ except Exception:
149
+ sys.excepthook(*sys.exc_info())
150
+ assert f not in cls._registry
151
+ finally:
152
+ # prevent any more finalizers from executing during shutdown
153
+ weakref_finalize._shutdown = True
154
+ if reenable_gc:
155
+ gc.enable()
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/packages/six.py ADDED
@@ -0,0 +1,1076 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2010-2020 Benjamin Peterson
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ # of this software and associated documentation files (the "Software"), to deal
5
+ # in the Software without restriction, including without limitation the rights
6
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ # copies of the Software, and to permit persons to whom the Software is
8
+ # furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ # SOFTWARE.
20
+
21
+ """Utilities for writing code that runs on Python 2 and 3"""
22
+
23
+ from __future__ import absolute_import
24
+
25
+ import functools
26
+ import itertools
27
+ import operator
28
+ import sys
29
+ import types
30
+
31
+ __author__ = "Benjamin Peterson <benjamin@python.org>"
32
+ __version__ = "1.16.0"
33
+
34
+
35
+ # Useful for very coarse version differentiation.
36
+ PY2 = sys.version_info[0] == 2
37
+ PY3 = sys.version_info[0] == 3
38
+ PY34 = sys.version_info[0:2] >= (3, 4)
39
+
40
+ if PY3:
41
+ string_types = (str,)
42
+ integer_types = (int,)
43
+ class_types = (type,)
44
+ text_type = str
45
+ binary_type = bytes
46
+
47
+ MAXSIZE = sys.maxsize
48
+ else:
49
+ string_types = (basestring,)
50
+ integer_types = (int, long)
51
+ class_types = (type, types.ClassType)
52
+ text_type = unicode
53
+ binary_type = str
54
+
55
+ if sys.platform.startswith("java"):
56
+ # Jython always uses 32 bits.
57
+ MAXSIZE = int((1 << 31) - 1)
58
+ else:
59
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
60
+ class X(object):
61
+ def __len__(self):
62
+ return 1 << 31
63
+
64
+ try:
65
+ len(X())
66
+ except OverflowError:
67
+ # 32-bit
68
+ MAXSIZE = int((1 << 31) - 1)
69
+ else:
70
+ # 64-bit
71
+ MAXSIZE = int((1 << 63) - 1)
72
+ del X
73
+
74
+ if PY34:
75
+ from importlib.util import spec_from_loader
76
+ else:
77
+ spec_from_loader = None
78
+
79
+
80
+ def _add_doc(func, doc):
81
+ """Add documentation to a function."""
82
+ func.__doc__ = doc
83
+
84
+
85
+ def _import_module(name):
86
+ """Import module, returning the module after the last dot."""
87
+ __import__(name)
88
+ return sys.modules[name]
89
+
90
+
91
+ class _LazyDescr(object):
92
+ def __init__(self, name):
93
+ self.name = name
94
+
95
+ def __get__(self, obj, tp):
96
+ result = self._resolve()
97
+ setattr(obj, self.name, result) # Invokes __set__.
98
+ try:
99
+ # This is a bit ugly, but it avoids running this again by
100
+ # removing this descriptor.
101
+ delattr(obj.__class__, self.name)
102
+ except AttributeError:
103
+ pass
104
+ return result
105
+
106
+
107
+ class MovedModule(_LazyDescr):
108
+ def __init__(self, name, old, new=None):
109
+ super(MovedModule, self).__init__(name)
110
+ if PY3:
111
+ if new is None:
112
+ new = name
113
+ self.mod = new
114
+ else:
115
+ self.mod = old
116
+
117
+ def _resolve(self):
118
+ return _import_module(self.mod)
119
+
120
+ def __getattr__(self, attr):
121
+ _module = self._resolve()
122
+ value = getattr(_module, attr)
123
+ setattr(self, attr, value)
124
+ return value
125
+
126
+
127
+ class _LazyModule(types.ModuleType):
128
+ def __init__(self, name):
129
+ super(_LazyModule, self).__init__(name)
130
+ self.__doc__ = self.__class__.__doc__
131
+
132
+ def __dir__(self):
133
+ attrs = ["__doc__", "__name__"]
134
+ attrs += [attr.name for attr in self._moved_attributes]
135
+ return attrs
136
+
137
+ # Subclasses should override this
138
+ _moved_attributes = []
139
+
140
+
141
+ class MovedAttribute(_LazyDescr):
142
+ def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
143
+ super(MovedAttribute, self).__init__(name)
144
+ if PY3:
145
+ if new_mod is None:
146
+ new_mod = name
147
+ self.mod = new_mod
148
+ if new_attr is None:
149
+ if old_attr is None:
150
+ new_attr = name
151
+ else:
152
+ new_attr = old_attr
153
+ self.attr = new_attr
154
+ else:
155
+ self.mod = old_mod
156
+ if old_attr is None:
157
+ old_attr = name
158
+ self.attr = old_attr
159
+
160
+ def _resolve(self):
161
+ module = _import_module(self.mod)
162
+ return getattr(module, self.attr)
163
+
164
+
165
+ class _SixMetaPathImporter(object):
166
+
167
+ """
168
+ A meta path importer to import six.moves and its submodules.
169
+
170
+ This class implements a PEP302 finder and loader. It should be compatible
171
+ with Python 2.5 and all existing versions of Python3
172
+ """
173
+
174
+ def __init__(self, six_module_name):
175
+ self.name = six_module_name
176
+ self.known_modules = {}
177
+
178
+ def _add_module(self, mod, *fullnames):
179
+ for fullname in fullnames:
180
+ self.known_modules[self.name + "." + fullname] = mod
181
+
182
+ def _get_module(self, fullname):
183
+ return self.known_modules[self.name + "." + fullname]
184
+
185
+ def find_module(self, fullname, path=None):
186
+ if fullname in self.known_modules:
187
+ return self
188
+ return None
189
+
190
+ def find_spec(self, fullname, path, target=None):
191
+ if fullname in self.known_modules:
192
+ return spec_from_loader(fullname, self)
193
+ return None
194
+
195
+ def __get_module(self, fullname):
196
+ try:
197
+ return self.known_modules[fullname]
198
+ except KeyError:
199
+ raise ImportError("This loader does not know module " + fullname)
200
+
201
+ def load_module(self, fullname):
202
+ try:
203
+ # in case of a reload
204
+ return sys.modules[fullname]
205
+ except KeyError:
206
+ pass
207
+ mod = self.__get_module(fullname)
208
+ if isinstance(mod, MovedModule):
209
+ mod = mod._resolve()
210
+ else:
211
+ mod.__loader__ = self
212
+ sys.modules[fullname] = mod
213
+ return mod
214
+
215
+ def is_package(self, fullname):
216
+ """
217
+ Return true, if the named module is a package.
218
+
219
+ We need this method to get correct spec objects with
220
+ Python 3.4 (see PEP451)
221
+ """
222
+ return hasattr(self.__get_module(fullname), "__path__")
223
+
224
+ def get_code(self, fullname):
225
+ """Return None
226
+
227
+ Required, if is_package is implemented"""
228
+ self.__get_module(fullname) # eventually raises ImportError
229
+ return None
230
+
231
+ get_source = get_code # same as get_code
232
+
233
+ def create_module(self, spec):
234
+ return self.load_module(spec.name)
235
+
236
+ def exec_module(self, module):
237
+ pass
238
+
239
+
240
+ _importer = _SixMetaPathImporter(__name__)
241
+
242
+
243
+ class _MovedItems(_LazyModule):
244
+
245
+ """Lazy loading of moved objects"""
246
+
247
+ __path__ = [] # mark as package
248
+
249
+
250
+ _moved_attributes = [
251
+ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
252
+ MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
253
+ MovedAttribute(
254
+ "filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"
255
+ ),
256
+ MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
257
+ MovedAttribute("intern", "__builtin__", "sys"),
258
+ MovedAttribute("map", "itertools", "builtins", "imap", "map"),
259
+ MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"),
260
+ MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"),
261
+ MovedAttribute("getoutput", "commands", "subprocess"),
262
+ MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
263
+ MovedAttribute(
264
+ "reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"
265
+ ),
266
+ MovedAttribute("reduce", "__builtin__", "functools"),
267
+ MovedAttribute("shlex_quote", "pipes", "shlex", "quote"),
268
+ MovedAttribute("StringIO", "StringIO", "io"),
269
+ MovedAttribute("UserDict", "UserDict", "collections"),
270
+ MovedAttribute("UserList", "UserList", "collections"),
271
+ MovedAttribute("UserString", "UserString", "collections"),
272
+ MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
273
+ MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
274
+ MovedAttribute(
275
+ "zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"
276
+ ),
277
+ MovedModule("builtins", "__builtin__"),
278
+ MovedModule("configparser", "ConfigParser"),
279
+ MovedModule(
280
+ "collections_abc",
281
+ "collections",
282
+ "collections.abc" if sys.version_info >= (3, 3) else "collections",
283
+ ),
284
+ MovedModule("copyreg", "copy_reg"),
285
+ MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
286
+ MovedModule("dbm_ndbm", "dbm", "dbm.ndbm"),
287
+ MovedModule(
288
+ "_dummy_thread",
289
+ "dummy_thread",
290
+ "_dummy_thread" if sys.version_info < (3, 9) else "_thread",
291
+ ),
292
+ MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
293
+ MovedModule("http_cookies", "Cookie", "http.cookies"),
294
+ MovedModule("html_entities", "htmlentitydefs", "html.entities"),
295
+ MovedModule("html_parser", "HTMLParser", "html.parser"),
296
+ MovedModule("http_client", "httplib", "http.client"),
297
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
298
+ MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"),
299
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
300
+ MovedModule(
301
+ "email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"
302
+ ),
303
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
304
+ MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
305
+ MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
306
+ MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
307
+ MovedModule("cPickle", "cPickle", "pickle"),
308
+ MovedModule("queue", "Queue"),
309
+ MovedModule("reprlib", "repr"),
310
+ MovedModule("socketserver", "SocketServer"),
311
+ MovedModule("_thread", "thread", "_thread"),
312
+ MovedModule("tkinter", "Tkinter"),
313
+ MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
314
+ MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
315
+ MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
316
+ MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
317
+ MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
318
+ MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
319
+ MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
320
+ MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
321
+ MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"),
322
+ MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"),
323
+ MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
324
+ MovedModule("tkinter_font", "tkFont", "tkinter.font"),
325
+ MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
326
+ MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"),
327
+ MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
328
+ MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
329
+ MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
330
+ MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
331
+ MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
332
+ MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
333
+ ]
334
+ # Add windows specific modules.
335
+ if sys.platform == "win32":
336
+ _moved_attributes += [
337
+ MovedModule("winreg", "_winreg"),
338
+ ]
339
+
340
+ for attr in _moved_attributes:
341
+ setattr(_MovedItems, attr.name, attr)
342
+ if isinstance(attr, MovedModule):
343
+ _importer._add_module(attr, "moves." + attr.name)
344
+ del attr
345
+
346
+ _MovedItems._moved_attributes = _moved_attributes
347
+
348
+ moves = _MovedItems(__name__ + ".moves")
349
+ _importer._add_module(moves, "moves")
350
+
351
+
352
+ class Module_six_moves_urllib_parse(_LazyModule):
353
+
354
+ """Lazy loading of moved objects in six.moves.urllib_parse"""
355
+
356
+
357
+ _urllib_parse_moved_attributes = [
358
+ MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
359
+ MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
360
+ MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
361
+ MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
362
+ MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
363
+ MovedAttribute("urljoin", "urlparse", "urllib.parse"),
364
+ MovedAttribute("urlparse", "urlparse", "urllib.parse"),
365
+ MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
366
+ MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
367
+ MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
368
+ MovedAttribute("quote", "urllib", "urllib.parse"),
369
+ MovedAttribute("quote_plus", "urllib", "urllib.parse"),
370
+ MovedAttribute("unquote", "urllib", "urllib.parse"),
371
+ MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
372
+ MovedAttribute(
373
+ "unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"
374
+ ),
375
+ MovedAttribute("urlencode", "urllib", "urllib.parse"),
376
+ MovedAttribute("splitquery", "urllib", "urllib.parse"),
377
+ MovedAttribute("splittag", "urllib", "urllib.parse"),
378
+ MovedAttribute("splituser", "urllib", "urllib.parse"),
379
+ MovedAttribute("splitvalue", "urllib", "urllib.parse"),
380
+ MovedAttribute("uses_fragment", "urlparse", "urllib.parse"),
381
+ MovedAttribute("uses_netloc", "urlparse", "urllib.parse"),
382
+ MovedAttribute("uses_params", "urlparse", "urllib.parse"),
383
+ MovedAttribute("uses_query", "urlparse", "urllib.parse"),
384
+ MovedAttribute("uses_relative", "urlparse", "urllib.parse"),
385
+ ]
386
+ for attr in _urllib_parse_moved_attributes:
387
+ setattr(Module_six_moves_urllib_parse, attr.name, attr)
388
+ del attr
389
+
390
+ Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
391
+
392
+ _importer._add_module(
393
+ Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
394
+ "moves.urllib_parse",
395
+ "moves.urllib.parse",
396
+ )
397
+
398
+
399
+ class Module_six_moves_urllib_error(_LazyModule):
400
+
401
+ """Lazy loading of moved objects in six.moves.urllib_error"""
402
+
403
+
404
+ _urllib_error_moved_attributes = [
405
+ MovedAttribute("URLError", "urllib2", "urllib.error"),
406
+ MovedAttribute("HTTPError", "urllib2", "urllib.error"),
407
+ MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
408
+ ]
409
+ for attr in _urllib_error_moved_attributes:
410
+ setattr(Module_six_moves_urllib_error, attr.name, attr)
411
+ del attr
412
+
413
+ Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
414
+
415
+ _importer._add_module(
416
+ Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
417
+ "moves.urllib_error",
418
+ "moves.urllib.error",
419
+ )
420
+
421
+
422
+ class Module_six_moves_urllib_request(_LazyModule):
423
+
424
+ """Lazy loading of moved objects in six.moves.urllib_request"""
425
+
426
+
427
+ _urllib_request_moved_attributes = [
428
+ MovedAttribute("urlopen", "urllib2", "urllib.request"),
429
+ MovedAttribute("install_opener", "urllib2", "urllib.request"),
430
+ MovedAttribute("build_opener", "urllib2", "urllib.request"),
431
+ MovedAttribute("pathname2url", "urllib", "urllib.request"),
432
+ MovedAttribute("url2pathname", "urllib", "urllib.request"),
433
+ MovedAttribute("getproxies", "urllib", "urllib.request"),
434
+ MovedAttribute("Request", "urllib2", "urllib.request"),
435
+ MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
436
+ MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
437
+ MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
438
+ MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
439
+ MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
440
+ MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
441
+ MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
442
+ MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
443
+ MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
444
+ MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
445
+ MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
446
+ MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
447
+ MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
448
+ MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
449
+ MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
450
+ MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
451
+ MovedAttribute("FileHandler", "urllib2", "urllib.request"),
452
+ MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
453
+ MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
454
+ MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
455
+ MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
456
+ MovedAttribute("urlretrieve", "urllib", "urllib.request"),
457
+ MovedAttribute("urlcleanup", "urllib", "urllib.request"),
458
+ MovedAttribute("URLopener", "urllib", "urllib.request"),
459
+ MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
460
+ MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
461
+ MovedAttribute("parse_http_list", "urllib2", "urllib.request"),
462
+ MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"),
463
+ ]
464
+ for attr in _urllib_request_moved_attributes:
465
+ setattr(Module_six_moves_urllib_request, attr.name, attr)
466
+ del attr
467
+
468
+ Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
469
+
470
+ _importer._add_module(
471
+ Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
472
+ "moves.urllib_request",
473
+ "moves.urllib.request",
474
+ )
475
+
476
+
477
+ class Module_six_moves_urllib_response(_LazyModule):
478
+
479
+ """Lazy loading of moved objects in six.moves.urllib_response"""
480
+
481
+
482
+ _urllib_response_moved_attributes = [
483
+ MovedAttribute("addbase", "urllib", "urllib.response"),
484
+ MovedAttribute("addclosehook", "urllib", "urllib.response"),
485
+ MovedAttribute("addinfo", "urllib", "urllib.response"),
486
+ MovedAttribute("addinfourl", "urllib", "urllib.response"),
487
+ ]
488
+ for attr in _urllib_response_moved_attributes:
489
+ setattr(Module_six_moves_urllib_response, attr.name, attr)
490
+ del attr
491
+
492
+ Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
493
+
494
+ _importer._add_module(
495
+ Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
496
+ "moves.urllib_response",
497
+ "moves.urllib.response",
498
+ )
499
+
500
+
501
+ class Module_six_moves_urllib_robotparser(_LazyModule):
502
+
503
+ """Lazy loading of moved objects in six.moves.urllib_robotparser"""
504
+
505
+
506
+ _urllib_robotparser_moved_attributes = [
507
+ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
508
+ ]
509
+ for attr in _urllib_robotparser_moved_attributes:
510
+ setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
511
+ del attr
512
+
513
+ Module_six_moves_urllib_robotparser._moved_attributes = (
514
+ _urllib_robotparser_moved_attributes
515
+ )
516
+
517
+ _importer._add_module(
518
+ Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
519
+ "moves.urllib_robotparser",
520
+ "moves.urllib.robotparser",
521
+ )
522
+
523
+
524
+ class Module_six_moves_urllib(types.ModuleType):
525
+
526
+ """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
527
+
528
+ __path__ = [] # mark as package
529
+ parse = _importer._get_module("moves.urllib_parse")
530
+ error = _importer._get_module("moves.urllib_error")
531
+ request = _importer._get_module("moves.urllib_request")
532
+ response = _importer._get_module("moves.urllib_response")
533
+ robotparser = _importer._get_module("moves.urllib_robotparser")
534
+
535
+ def __dir__(self):
536
+ return ["parse", "error", "request", "response", "robotparser"]
537
+
538
+
539
+ _importer._add_module(
540
+ Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib"
541
+ )
542
+
543
+
544
+ def add_move(move):
545
+ """Add an item to six.moves."""
546
+ setattr(_MovedItems, move.name, move)
547
+
548
+
549
+ def remove_move(name):
550
+ """Remove item from six.moves."""
551
+ try:
552
+ delattr(_MovedItems, name)
553
+ except AttributeError:
554
+ try:
555
+ del moves.__dict__[name]
556
+ except KeyError:
557
+ raise AttributeError("no such move, %r" % (name,))
558
+
559
+
560
+ if PY3:
561
+ _meth_func = "__func__"
562
+ _meth_self = "__self__"
563
+
564
+ _func_closure = "__closure__"
565
+ _func_code = "__code__"
566
+ _func_defaults = "__defaults__"
567
+ _func_globals = "__globals__"
568
+ else:
569
+ _meth_func = "im_func"
570
+ _meth_self = "im_self"
571
+
572
+ _func_closure = "func_closure"
573
+ _func_code = "func_code"
574
+ _func_defaults = "func_defaults"
575
+ _func_globals = "func_globals"
576
+
577
+
578
+ try:
579
+ advance_iterator = next
580
+ except NameError:
581
+
582
+ def advance_iterator(it):
583
+ return it.next()
584
+
585
+
586
+ next = advance_iterator
587
+
588
+
589
+ try:
590
+ callable = callable
591
+ except NameError:
592
+
593
+ def callable(obj):
594
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
595
+
596
+
597
+ if PY3:
598
+
599
+ def get_unbound_function(unbound):
600
+ return unbound
601
+
602
+ create_bound_method = types.MethodType
603
+
604
+ def create_unbound_method(func, cls):
605
+ return func
606
+
607
+ Iterator = object
608
+ else:
609
+
610
+ def get_unbound_function(unbound):
611
+ return unbound.im_func
612
+
613
+ def create_bound_method(func, obj):
614
+ return types.MethodType(func, obj, obj.__class__)
615
+
616
+ def create_unbound_method(func, cls):
617
+ return types.MethodType(func, None, cls)
618
+
619
+ class Iterator(object):
620
+ def next(self):
621
+ return type(self).__next__(self)
622
+
623
+ callable = callable
624
+ _add_doc(
625
+ get_unbound_function, """Get the function out of a possibly unbound function"""
626
+ )
627
+
628
+
629
+ get_method_function = operator.attrgetter(_meth_func)
630
+ get_method_self = operator.attrgetter(_meth_self)
631
+ get_function_closure = operator.attrgetter(_func_closure)
632
+ get_function_code = operator.attrgetter(_func_code)
633
+ get_function_defaults = operator.attrgetter(_func_defaults)
634
+ get_function_globals = operator.attrgetter(_func_globals)
635
+
636
+
637
+ if PY3:
638
+
639
+ def iterkeys(d, **kw):
640
+ return iter(d.keys(**kw))
641
+
642
+ def itervalues(d, **kw):
643
+ return iter(d.values(**kw))
644
+
645
+ def iteritems(d, **kw):
646
+ return iter(d.items(**kw))
647
+
648
+ def iterlists(d, **kw):
649
+ return iter(d.lists(**kw))
650
+
651
+ viewkeys = operator.methodcaller("keys")
652
+
653
+ viewvalues = operator.methodcaller("values")
654
+
655
+ viewitems = operator.methodcaller("items")
656
+ else:
657
+
658
+ def iterkeys(d, **kw):
659
+ return d.iterkeys(**kw)
660
+
661
+ def itervalues(d, **kw):
662
+ return d.itervalues(**kw)
663
+
664
+ def iteritems(d, **kw):
665
+ return d.iteritems(**kw)
666
+
667
+ def iterlists(d, **kw):
668
+ return d.iterlists(**kw)
669
+
670
+ viewkeys = operator.methodcaller("viewkeys")
671
+
672
+ viewvalues = operator.methodcaller("viewvalues")
673
+
674
+ viewitems = operator.methodcaller("viewitems")
675
+
676
+ _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
677
+ _add_doc(itervalues, "Return an iterator over the values of a dictionary.")
678
+ _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.")
679
+ _add_doc(
680
+ iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary."
681
+ )
682
+
683
+
684
+ if PY3:
685
+
686
+ def b(s):
687
+ return s.encode("latin-1")
688
+
689
+ def u(s):
690
+ return s
691
+
692
+ unichr = chr
693
+ import struct
694
+
695
+ int2byte = struct.Struct(">B").pack
696
+ del struct
697
+ byte2int = operator.itemgetter(0)
698
+ indexbytes = operator.getitem
699
+ iterbytes = iter
700
+ import io
701
+
702
+ StringIO = io.StringIO
703
+ BytesIO = io.BytesIO
704
+ del io
705
+ _assertCountEqual = "assertCountEqual"
706
+ if sys.version_info[1] <= 1:
707
+ _assertRaisesRegex = "assertRaisesRegexp"
708
+ _assertRegex = "assertRegexpMatches"
709
+ _assertNotRegex = "assertNotRegexpMatches"
710
+ else:
711
+ _assertRaisesRegex = "assertRaisesRegex"
712
+ _assertRegex = "assertRegex"
713
+ _assertNotRegex = "assertNotRegex"
714
+ else:
715
+
716
+ def b(s):
717
+ return s
718
+
719
+ # Workaround for standalone backslash
720
+
721
+ def u(s):
722
+ return unicode(s.replace(r"\\", r"\\\\"), "unicode_escape")
723
+
724
+ unichr = unichr
725
+ int2byte = chr
726
+
727
+ def byte2int(bs):
728
+ return ord(bs[0])
729
+
730
+ def indexbytes(buf, i):
731
+ return ord(buf[i])
732
+
733
+ iterbytes = functools.partial(itertools.imap, ord)
734
+ import StringIO
735
+
736
+ StringIO = BytesIO = StringIO.StringIO
737
+ _assertCountEqual = "assertItemsEqual"
738
+ _assertRaisesRegex = "assertRaisesRegexp"
739
+ _assertRegex = "assertRegexpMatches"
740
+ _assertNotRegex = "assertNotRegexpMatches"
741
+ _add_doc(b, """Byte literal""")
742
+ _add_doc(u, """Text literal""")
743
+
744
+
745
+ def assertCountEqual(self, *args, **kwargs):
746
+ return getattr(self, _assertCountEqual)(*args, **kwargs)
747
+
748
+
749
+ def assertRaisesRegex(self, *args, **kwargs):
750
+ return getattr(self, _assertRaisesRegex)(*args, **kwargs)
751
+
752
+
753
+ def assertRegex(self, *args, **kwargs):
754
+ return getattr(self, _assertRegex)(*args, **kwargs)
755
+
756
+
757
+ def assertNotRegex(self, *args, **kwargs):
758
+ return getattr(self, _assertNotRegex)(*args, **kwargs)
759
+
760
+
761
+ if PY3:
762
+ exec_ = getattr(moves.builtins, "exec")
763
+
764
+ def reraise(tp, value, tb=None):
765
+ try:
766
+ if value is None:
767
+ value = tp()
768
+ if value.__traceback__ is not tb:
769
+ raise value.with_traceback(tb)
770
+ raise value
771
+ finally:
772
+ value = None
773
+ tb = None
774
+
775
+ else:
776
+
777
+ def exec_(_code_, _globs_=None, _locs_=None):
778
+ """Execute code in a namespace."""
779
+ if _globs_ is None:
780
+ frame = sys._getframe(1)
781
+ _globs_ = frame.f_globals
782
+ if _locs_ is None:
783
+ _locs_ = frame.f_locals
784
+ del frame
785
+ elif _locs_ is None:
786
+ _locs_ = _globs_
787
+ exec ("""exec _code_ in _globs_, _locs_""")
788
+
789
+ exec_(
790
+ """def reraise(tp, value, tb=None):
791
+ try:
792
+ raise tp, value, tb
793
+ finally:
794
+ tb = None
795
+ """
796
+ )
797
+
798
+
799
+ if sys.version_info[:2] > (3,):
800
+ exec_(
801
+ """def raise_from(value, from_value):
802
+ try:
803
+ raise value from from_value
804
+ finally:
805
+ value = None
806
+ """
807
+ )
808
+ else:
809
+
810
+ def raise_from(value, from_value):
811
+ raise value
812
+
813
+
814
+ print_ = getattr(moves.builtins, "print", None)
815
+ if print_ is None:
816
+
817
+ def print_(*args, **kwargs):
818
+ """The new-style print function for Python 2.4 and 2.5."""
819
+ fp = kwargs.pop("file", sys.stdout)
820
+ if fp is None:
821
+ return
822
+
823
+ def write(data):
824
+ if not isinstance(data, basestring):
825
+ data = str(data)
826
+ # If the file has an encoding, encode unicode with it.
827
+ if (
828
+ isinstance(fp, file)
829
+ and isinstance(data, unicode)
830
+ and fp.encoding is not None
831
+ ):
832
+ errors = getattr(fp, "errors", None)
833
+ if errors is None:
834
+ errors = "strict"
835
+ data = data.encode(fp.encoding, errors)
836
+ fp.write(data)
837
+
838
+ want_unicode = False
839
+ sep = kwargs.pop("sep", None)
840
+ if sep is not None:
841
+ if isinstance(sep, unicode):
842
+ want_unicode = True
843
+ elif not isinstance(sep, str):
844
+ raise TypeError("sep must be None or a string")
845
+ end = kwargs.pop("end", None)
846
+ if end is not None:
847
+ if isinstance(end, unicode):
848
+ want_unicode = True
849
+ elif not isinstance(end, str):
850
+ raise TypeError("end must be None or a string")
851
+ if kwargs:
852
+ raise TypeError("invalid keyword arguments to print()")
853
+ if not want_unicode:
854
+ for arg in args:
855
+ if isinstance(arg, unicode):
856
+ want_unicode = True
857
+ break
858
+ if want_unicode:
859
+ newline = unicode("\n")
860
+ space = unicode(" ")
861
+ else:
862
+ newline = "\n"
863
+ space = " "
864
+ if sep is None:
865
+ sep = space
866
+ if end is None:
867
+ end = newline
868
+ for i, arg in enumerate(args):
869
+ if i:
870
+ write(sep)
871
+ write(arg)
872
+ write(end)
873
+
874
+
875
+ if sys.version_info[:2] < (3, 3):
876
+ _print = print_
877
+
878
+ def print_(*args, **kwargs):
879
+ fp = kwargs.get("file", sys.stdout)
880
+ flush = kwargs.pop("flush", False)
881
+ _print(*args, **kwargs)
882
+ if flush and fp is not None:
883
+ fp.flush()
884
+
885
+
886
+ _add_doc(reraise, """Reraise an exception.""")
887
+
888
+ if sys.version_info[0:2] < (3, 4):
889
+ # This does exactly the same what the :func:`py3:functools.update_wrapper`
890
+ # function does on Python versions after 3.2. It sets the ``__wrapped__``
891
+ # attribute on ``wrapper`` object and it doesn't raise an error if any of
892
+ # the attributes mentioned in ``assigned`` and ``updated`` are missing on
893
+ # ``wrapped`` object.
894
+ def _update_wrapper(
895
+ wrapper,
896
+ wrapped,
897
+ assigned=functools.WRAPPER_ASSIGNMENTS,
898
+ updated=functools.WRAPPER_UPDATES,
899
+ ):
900
+ for attr in assigned:
901
+ try:
902
+ value = getattr(wrapped, attr)
903
+ except AttributeError:
904
+ continue
905
+ else:
906
+ setattr(wrapper, attr, value)
907
+ for attr in updated:
908
+ getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
909
+ wrapper.__wrapped__ = wrapped
910
+ return wrapper
911
+
912
+ _update_wrapper.__doc__ = functools.update_wrapper.__doc__
913
+
914
+ def wraps(
915
+ wrapped,
916
+ assigned=functools.WRAPPER_ASSIGNMENTS,
917
+ updated=functools.WRAPPER_UPDATES,
918
+ ):
919
+ return functools.partial(
920
+ _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated
921
+ )
922
+
923
+ wraps.__doc__ = functools.wraps.__doc__
924
+
925
+ else:
926
+ wraps = functools.wraps
927
+
928
+
929
+ def with_metaclass(meta, *bases):
930
+ """Create a base class with a metaclass."""
931
+ # This requires a bit of explanation: the basic idea is to make a dummy
932
+ # metaclass for one level of class instantiation that replaces itself with
933
+ # the actual metaclass.
934
+ class metaclass(type):
935
+ def __new__(cls, name, this_bases, d):
936
+ if sys.version_info[:2] >= (3, 7):
937
+ # This version introduced PEP 560 that requires a bit
938
+ # of extra care (we mimic what is done by __build_class__).
939
+ resolved_bases = types.resolve_bases(bases)
940
+ if resolved_bases is not bases:
941
+ d["__orig_bases__"] = bases
942
+ else:
943
+ resolved_bases = bases
944
+ return meta(name, resolved_bases, d)
945
+
946
+ @classmethod
947
+ def __prepare__(cls, name, this_bases):
948
+ return meta.__prepare__(name, bases)
949
+
950
+ return type.__new__(metaclass, "temporary_class", (), {})
951
+
952
+
953
+ def add_metaclass(metaclass):
954
+ """Class decorator for creating a class with a metaclass."""
955
+
956
+ def wrapper(cls):
957
+ orig_vars = cls.__dict__.copy()
958
+ slots = orig_vars.get("__slots__")
959
+ if slots is not None:
960
+ if isinstance(slots, str):
961
+ slots = [slots]
962
+ for slots_var in slots:
963
+ orig_vars.pop(slots_var)
964
+ orig_vars.pop("__dict__", None)
965
+ orig_vars.pop("__weakref__", None)
966
+ if hasattr(cls, "__qualname__"):
967
+ orig_vars["__qualname__"] = cls.__qualname__
968
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
969
+
970
+ return wrapper
971
+
972
+
973
+ def ensure_binary(s, encoding="utf-8", errors="strict"):
974
+ """Coerce **s** to six.binary_type.
975
+
976
+ For Python 2:
977
+ - `unicode` -> encoded to `str`
978
+ - `str` -> `str`
979
+
980
+ For Python 3:
981
+ - `str` -> encoded to `bytes`
982
+ - `bytes` -> `bytes`
983
+ """
984
+ if isinstance(s, binary_type):
985
+ return s
986
+ if isinstance(s, text_type):
987
+ return s.encode(encoding, errors)
988
+ raise TypeError("not expecting type '%s'" % type(s))
989
+
990
+
991
+ def ensure_str(s, encoding="utf-8", errors="strict"):
992
+ """Coerce *s* to `str`.
993
+
994
+ For Python 2:
995
+ - `unicode` -> encoded to `str`
996
+ - `str` -> `str`
997
+
998
+ For Python 3:
999
+ - `str` -> `str`
1000
+ - `bytes` -> decoded to `str`
1001
+ """
1002
+ # Optimization: Fast return for the common case.
1003
+ if type(s) is str:
1004
+ return s
1005
+ if PY2 and isinstance(s, text_type):
1006
+ return s.encode(encoding, errors)
1007
+ elif PY3 and isinstance(s, binary_type):
1008
+ return s.decode(encoding, errors)
1009
+ elif not isinstance(s, (text_type, binary_type)):
1010
+ raise TypeError("not expecting type '%s'" % type(s))
1011
+ return s
1012
+
1013
+
1014
+ def ensure_text(s, encoding="utf-8", errors="strict"):
1015
+ """Coerce *s* to six.text_type.
1016
+
1017
+ For Python 2:
1018
+ - `unicode` -> `unicode`
1019
+ - `str` -> `unicode`
1020
+
1021
+ For Python 3:
1022
+ - `str` -> `str`
1023
+ - `bytes` -> decoded to `str`
1024
+ """
1025
+ if isinstance(s, binary_type):
1026
+ return s.decode(encoding, errors)
1027
+ elif isinstance(s, text_type):
1028
+ return s
1029
+ else:
1030
+ raise TypeError("not expecting type '%s'" % type(s))
1031
+
1032
+
1033
+ def python_2_unicode_compatible(klass):
1034
+ """
1035
+ A class decorator that defines __unicode__ and __str__ methods under Python 2.
1036
+ Under Python 3 it does nothing.
1037
+
1038
+ To support Python 2 and 3 with a single code base, define a __str__ method
1039
+ returning text and apply this decorator to the class.
1040
+ """
1041
+ if PY2:
1042
+ if "__str__" not in klass.__dict__:
1043
+ raise ValueError(
1044
+ "@python_2_unicode_compatible cannot be applied "
1045
+ "to %s because it doesn't define __str__()." % klass.__name__
1046
+ )
1047
+ klass.__unicode__ = klass.__str__
1048
+ klass.__str__ = lambda self: self.__unicode__().encode("utf-8")
1049
+ return klass
1050
+
1051
+
1052
+ # Complete the moves implementation.
1053
+ # This code is at the end of this module to speed up module loading.
1054
+ # Turn this module into a package.
1055
+ __path__ = [] # required for PEP 302 and PEP 451
1056
+ __package__ = __name__ # see PEP 366 @ReservedAssignment
1057
+ if globals().get("__spec__") is not None:
1058
+ __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
1059
+ # Remove other six meta path importers, since they cause problems. This can
1060
+ # happen if six is removed from sys.modules and then reloaded. (Setuptools does
1061
+ # this for some reason.)
1062
+ if sys.meta_path:
1063
+ for i, importer in enumerate(sys.meta_path):
1064
+ # Here's some real nastiness: Another "instance" of the six module might
1065
+ # be floating around. Therefore, we can't use isinstance() to check for
1066
+ # the six meta path importer, since the other six instance will have
1067
+ # inserted an importer with different class.
1068
+ if (
1069
+ type(importer).__name__ == "_SixMetaPathImporter"
1070
+ and importer.name == __name__
1071
+ ):
1072
+ del sys.meta_path[i]
1073
+ break
1074
+ del i, importer
1075
+ # Finally, add the importer to the meta path import hook.
1076
+ sys.meta_path.append(_importer)
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/util/__pycache__/retry.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/util/__pycache__/ssltransport.cpython-310.pyc ADDED
Binary file (7.38 kB). View file
 
llava/lib/python3.10/site-packages/pip/_vendor/urllib3/util/__pycache__/timeout.cpython-310.pyc ADDED
Binary file (9.12 kB). View file
 
llava/lib/python3.10/site-packages/setuptools/__init__.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extensions to the 'distutils' for large or complex distributions"""
2
+ # mypy: disable_error_code=override
3
+ # Command.reinitialize_command has an extra **kw param that distutils doesn't have
4
+ # Can't disable on the exact line because distutils doesn't exists on Python 3.12
5
+ # and mypy isn't aware of distutils_hack, causing distutils.core.Command to be Any,
6
+ # and a [unused-ignore] to be raised on 3.12+
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import os
12
+ import re
13
+ import sys
14
+ from abc import abstractmethod
15
+ from collections.abc import Mapping
16
+ from typing import TYPE_CHECKING, TypeVar, overload
17
+
18
+ sys.path.extend(((vendor_path := os.path.join(os.path.dirname(os.path.dirname(__file__)), 'setuptools', '_vendor')) not in sys.path) * [vendor_path]) # fmt: skip
19
+ # workaround for #4476
20
+ sys.modules.pop('backports', None)
21
+
22
+ import _distutils_hack.override # noqa: F401
23
+
24
+ from . import logging, monkey
25
+ from .depends import Require
26
+ from .discovery import PackageFinder, PEP420PackageFinder
27
+ from .dist import Distribution
28
+ from .extension import Extension
29
+ from .version import __version__ as __version__
30
+ from .warnings import SetuptoolsDeprecationWarning
31
+
32
+ import distutils.core
33
+ from distutils.errors import DistutilsOptionError
34
+
35
+ __all__ = [
36
+ 'setup',
37
+ 'Distribution',
38
+ 'Command',
39
+ 'Extension',
40
+ 'Require',
41
+ 'SetuptoolsDeprecationWarning',
42
+ 'find_packages',
43
+ 'find_namespace_packages',
44
+ ]
45
+
46
+ _CommandT = TypeVar("_CommandT", bound="_Command")
47
+
48
+ bootstrap_install_from = None
49
+
50
+ find_packages = PackageFinder.find
51
+ find_namespace_packages = PEP420PackageFinder.find
52
+
53
+
54
+ def _install_setup_requires(attrs):
55
+ # Note: do not use `setuptools.Distribution` directly, as
56
+ # our PEP 517 backend patch `distutils.core.Distribution`.
57
+ class MinimalDistribution(distutils.core.Distribution):
58
+ """
59
+ A minimal version of a distribution for supporting the
60
+ fetch_build_eggs interface.
61
+ """
62
+
63
+ def __init__(self, attrs: Mapping[str, object]) -> None:
64
+ _incl = 'dependency_links', 'setup_requires'
65
+ filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}
66
+ super().__init__(filtered)
67
+ # Prevent accidentally triggering discovery with incomplete set of attrs
68
+ self.set_defaults._disable()
69
+
70
+ def _get_project_config_files(self, filenames=None):
71
+ """Ignore ``pyproject.toml``, they are not related to setup_requires"""
72
+ try:
73
+ cfg, _toml = super()._split_standard_project_metadata(filenames)
74
+ except Exception:
75
+ return filenames, ()
76
+ return cfg, ()
77
+
78
+ def finalize_options(self):
79
+ """
80
+ Disable finalize_options to avoid building the working set.
81
+ Ref #2158.
82
+ """
83
+
84
+ dist = MinimalDistribution(attrs)
85
+
86
+ # Honor setup.cfg's options.
87
+ dist.parse_config_files(ignore_option_errors=True)
88
+ if dist.setup_requires:
89
+ _fetch_build_eggs(dist)
90
+
91
+
92
+ def _fetch_build_eggs(dist: Distribution):
93
+ try:
94
+ dist.fetch_build_eggs(dist.setup_requires)
95
+ except Exception as ex:
96
+ msg = """
97
+ It is possible a package already installed in your system
98
+ contains an version that is invalid according to PEP 440.
99
+ You can try `pip install --use-pep517` as a workaround for this problem,
100
+ or rely on a new virtual environment.
101
+
102
+ If the problem refers to a package that is not installed yet,
103
+ please contact that package's maintainers or distributors.
104
+ """
105
+ if "InvalidVersion" in ex.__class__.__name__:
106
+ if hasattr(ex, "add_note"):
107
+ ex.add_note(msg) # PEP 678
108
+ else:
109
+ dist.announce(f"\n{msg}\n")
110
+ raise
111
+
112
+
113
+ def setup(**attrs):
114
+ logging.configure()
115
+ # Make sure we have any requirements needed to interpret 'attrs'.
116
+ _install_setup_requires(attrs)
117
+ return distutils.core.setup(**attrs)
118
+
119
+
120
+ setup.__doc__ = distutils.core.setup.__doc__
121
+
122
+ if TYPE_CHECKING:
123
+ # Work around a mypy issue where type[T] can't be used as a base: https://github.com/python/mypy/issues/10962
124
+ from distutils.core import Command as _Command
125
+ else:
126
+ _Command = monkey.get_unpatched(distutils.core.Command)
127
+
128
+
129
+ class Command(_Command):
130
+ """
131
+ Setuptools internal actions are organized using a *command design pattern*.
132
+ This means that each action (or group of closely related actions) executed during
133
+ the build should be implemented as a ``Command`` subclass.
134
+
135
+ These commands are abstractions and do not necessarily correspond to a command that
136
+ can (or should) be executed via a terminal, in a CLI fashion (although historically
137
+ they would).
138
+
139
+ When creating a new command from scratch, custom defined classes **SHOULD** inherit
140
+ from ``setuptools.Command`` and implement a few mandatory methods.
141
+ Between these mandatory methods, are listed:
142
+ :meth:`initialize_options`, :meth:`finalize_options` and :meth:`run`.
143
+
144
+ A useful analogy for command classes is to think of them as subroutines with local
145
+ variables called "options". The options are "declared" in :meth:`initialize_options`
146
+ and "defined" (given their final values, aka "finalized") in :meth:`finalize_options`,
147
+ both of which must be defined by every command class. The "body" of the subroutine,
148
+ (where it does all the work) is the :meth:`run` method.
149
+ Between :meth:`initialize_options` and :meth:`finalize_options`, ``setuptools`` may set
150
+ the values for options/attributes based on user's input (or circumstance),
151
+ which means that the implementation should be careful to not overwrite values in
152
+ :meth:`finalize_options` unless necessary.
153
+
154
+ Please note that other commands (or other parts of setuptools) may also overwrite
155
+ the values of the command's options/attributes multiple times during the build
156
+ process.
157
+ Therefore it is important to consistently implement :meth:`initialize_options` and
158
+ :meth:`finalize_options`. For example, all derived attributes (or attributes that
159
+ depend on the value of other attributes) **SHOULD** be recomputed in
160
+ :meth:`finalize_options`.
161
+
162
+ When overwriting existing commands, custom defined classes **MUST** abide by the
163
+ same APIs implemented by the original class. They also **SHOULD** inherit from the
164
+ original class.
165
+ """
166
+
167
+ command_consumes_arguments = False
168
+ distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
169
+
170
+ def __init__(self, dist: Distribution, **kw) -> None:
171
+ """
172
+ Construct the command for dist, updating
173
+ vars(self) with any keyword parameters.
174
+ """
175
+ super().__init__(dist)
176
+ vars(self).update(kw)
177
+
178
+ def _ensure_stringlike(self, option, what, default=None):
179
+ val = getattr(self, option)
180
+ if val is None:
181
+ setattr(self, option, default)
182
+ return default
183
+ elif not isinstance(val, str):
184
+ raise DistutilsOptionError(f"'{option}' must be a {what} (got `{val}`)")
185
+ return val
186
+
187
+ def ensure_string_list(self, option: str) -> None:
188
+ r"""Ensure that 'option' is a list of strings. If 'option' is
189
+ currently a string, we split it either on /,\s*/ or /\s+/, so
190
+ "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
191
+ ["foo", "bar", "baz"].
192
+
193
+ ..
194
+ TODO: This method seems to be similar to the one in ``distutils.cmd``
195
+ Probably it is just here for backward compatibility with old Python versions?
196
+
197
+ :meta private:
198
+ """
199
+ val = getattr(self, option)
200
+ if val is None:
201
+ return
202
+ elif isinstance(val, str):
203
+ setattr(self, option, re.split(r',\s*|\s+', val))
204
+ else:
205
+ if isinstance(val, list):
206
+ ok = all(isinstance(v, str) for v in val)
207
+ else:
208
+ ok = False
209
+ if not ok:
210
+ raise DistutilsOptionError(
211
+ f"'{option}' must be a list of strings (got {val!r})"
212
+ )
213
+
214
+ @overload
215
+ def reinitialize_command(
216
+ self, command: str, reinit_subcommands: bool = False, **kw
217
+ ) -> _Command: ...
218
+ @overload
219
+ def reinitialize_command(
220
+ self, command: _CommandT, reinit_subcommands: bool = False, **kw
221
+ ) -> _CommandT: ...
222
+ def reinitialize_command(
223
+ self, command: str | _Command, reinit_subcommands: bool = False, **kw
224
+ ) -> _Command:
225
+ cmd = _Command.reinitialize_command(self, command, reinit_subcommands)
226
+ vars(cmd).update(kw)
227
+ return cmd # pyright: ignore[reportReturnType] # pypa/distutils#307
228
+
229
+ @abstractmethod
230
+ def initialize_options(self) -> None:
231
+ """
232
+ Set or (reset) all options/attributes/caches used by the command
233
+ to their default values. Note that these values may be overwritten during
234
+ the build.
235
+ """
236
+ raise NotImplementedError
237
+
238
+ @abstractmethod
239
+ def finalize_options(self) -> None:
240
+ """
241
+ Set final values for all options/attributes used by the command.
242
+ Most of the time, each option/attribute/cache should only be set if it does not
243
+ have any value yet (e.g. ``if self.attr is None: self.attr = val``).
244
+ """
245
+ raise NotImplementedError
246
+
247
+ @abstractmethod
248
+ def run(self) -> None:
249
+ """
250
+ Execute the actions intended by the command.
251
+ (Side effects **SHOULD** only take place when :meth:`run` is executed,
252
+ for example, creating new files or writing to the terminal output).
253
+ """
254
+ raise NotImplementedError
255
+
256
+
257
+ def _find_all_simple(path):
258
+ """
259
+ Find all files under 'path'
260
+ """
261
+ results = (
262
+ os.path.join(base, file)
263
+ for base, dirs, files in os.walk(path, followlinks=True)
264
+ for file in files
265
+ )
266
+ return filter(os.path.isfile, results)
267
+
268
+
269
+ def findall(dir=os.curdir):
270
+ """
271
+ Find all files under 'dir' and return the list of full filenames.
272
+ Unless dir is '.', return full filenames with dir prepended.
273
+ """
274
+ files = _find_all_simple(dir)
275
+ if dir == os.curdir:
276
+ make_rel = functools.partial(os.path.relpath, start=dir)
277
+ files = map(make_rel, files)
278
+ return list(files)
279
+
280
+
281
+ class sic(str):
282
+ """Treat this string as-is (https://en.wikipedia.org/wiki/Sic)"""
283
+
284
+
285
+ # Apply monkey patches
286
+ monkey.patch_all()