Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- videollama2/lib/python3.10/site-packages/setuptools/__init__.py +286 -0
- videollama2/lib/python3.10/site-packages/setuptools/_shutil.py +53 -0
- videollama2/lib/python3.10/site-packages/setuptools/cli.exe +0 -0
- videollama2/lib/python3.10/site-packages/setuptools/version.py +6 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/__init__.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/__main__.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/auth.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/client.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/connection.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/datastructures.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/exceptions.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/frames.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/headers.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/http.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/http11.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/imports.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/protocol.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/server.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/streams.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/typing.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/uri.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/utils.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/__pycache__/version.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/auth.py +4 -0
- videollama2/lib/python3.10/site-packages/websockets/connection.py +13 -0
- videollama2/lib/python3.10/site-packages/websockets/datastructures.py +200 -0
- videollama2/lib/python3.10/site-packages/websockets/extensions/__init__.py +4 -0
- videollama2/lib/python3.10/site-packages/websockets/extensions/__pycache__/base.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/extensions/base.py +133 -0
- videollama2/lib/python3.10/site-packages/websockets/extensions/permessage_deflate.py +660 -0
- videollama2/lib/python3.10/site-packages/websockets/frames.py +449 -0
- videollama2/lib/python3.10/site-packages/websockets/http.py +30 -0
- videollama2/lib/python3.10/site-packages/websockets/http11.py +364 -0
- videollama2/lib/python3.10/site-packages/websockets/imports.py +99 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__init__.py +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/__init__.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/async_timeout.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/auth.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/client.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/compatibility.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/framing.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/handshake.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/http.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/server.cpython-310.pyc +0 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/async_timeout.py +265 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/auth.py +184 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/client.py +713 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/compatibility.py +33 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/framing.py +176 -0
- videollama2/lib/python3.10/site-packages/websockets/legacy/handshake.py +165 -0
videollama2/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()
|
videollama2/lib/python3.10/site-packages/setuptools/_shutil.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convenience layer on top of stdlib's shutil and os"""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import stat
|
| 5 |
+
from typing import Callable, TypeVar
|
| 6 |
+
|
| 7 |
+
from .compat import py311
|
| 8 |
+
|
| 9 |
+
from distutils import log
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from os import chmod # pyright: ignore[reportAssignmentType]
|
| 13 |
+
# Losing type-safety w/ pyright, but that's ok
|
| 14 |
+
except ImportError: # pragma: no cover
|
| 15 |
+
# Jython compatibility
|
| 16 |
+
def chmod(*args: object, **kwargs: object) -> None: # type: ignore[misc] # Mypy reuses the imported definition anyway
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_T = TypeVar("_T")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def attempt_chmod_verbose(path, mode):
|
| 24 |
+
log.debug("changing mode of %s to %o", path, mode)
|
| 25 |
+
try:
|
| 26 |
+
chmod(path, mode)
|
| 27 |
+
except OSError as e: # pragma: no cover
|
| 28 |
+
log.debug("chmod failed: %s", e)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Must match shutil._OnExcCallback
|
| 32 |
+
def _auto_chmod(
|
| 33 |
+
func: Callable[..., _T], arg: str, exc: BaseException
|
| 34 |
+
) -> _T: # pragma: no cover
|
| 35 |
+
"""shutils onexc callback to automatically call chmod for certain functions."""
|
| 36 |
+
# Only retry for scenarios known to have an issue
|
| 37 |
+
if func in [os.unlink, os.remove] and os.name == 'nt':
|
| 38 |
+
attempt_chmod_verbose(arg, stat.S_IWRITE)
|
| 39 |
+
return func(arg)
|
| 40 |
+
raise exc
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def rmtree(path, ignore_errors=False, onexc=_auto_chmod):
|
| 44 |
+
"""
|
| 45 |
+
Similar to ``shutil.rmtree`` but automatically executes ``chmod``
|
| 46 |
+
for well know Windows failure scenarios.
|
| 47 |
+
"""
|
| 48 |
+
return py311.shutil_rmtree(path, ignore_errors, onexc)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def rmdir(path, **opts):
|
| 52 |
+
if os.path.isdir(path):
|
| 53 |
+
rmtree(path, **opts)
|
videollama2/lib/python3.10/site-packages/setuptools/cli.exe
ADDED
|
Binary file (11.8 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/setuptools/version.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._importlib import metadata
|
| 2 |
+
|
| 3 |
+
try:
|
| 4 |
+
__version__ = metadata.version('setuptools') or '0.dev0+unknown'
|
| 5 |
+
except Exception:
|
| 6 |
+
__version__ = '0.dev0+unknown'
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/__main__.cpython-310.pyc
ADDED
|
Binary file (3.55 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/auth.cpython-310.pyc
ADDED
|
Binary file (242 Bytes). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/client.cpython-310.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/connection.cpython-310.pyc
ADDED
|
Binary file (486 Bytes). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/datastructures.cpython-310.pyc
ADDED
|
Binary file (7.2 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/exceptions.cpython-310.pyc
ADDED
|
Binary file (12.7 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/frames.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/headers.cpython-310.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/http.cpython-310.pyc
ADDED
|
Binary file (636 Bytes). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/http11.cpython-310.pyc
ADDED
|
Binary file (9.09 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/imports.cpython-310.pyc
ADDED
|
Binary file (2.7 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/protocol.cpython-310.pyc
ADDED
|
Binary file (16 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/server.cpython-310.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/streams.cpython-310.pyc
ADDED
|
Binary file (4.24 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/typing.cpython-310.pyc
ADDED
|
Binary file (733 Bytes). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/uri.cpython-310.pyc
ADDED
|
Binary file (2.89 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (1.5 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/__pycache__/version.cpython-310.pyc
ADDED
|
Binary file (1.6 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/auth.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
# See #940 for why lazy_import isn't used here for backwards compatibility.
|
| 4 |
+
from .legacy.auth import *
|
videollama2/lib/python3.10/site-packages/websockets/connection.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
# lazy_import doesn't support this use case.
|
| 6 |
+
from .protocol import SEND_EOF, Protocol as Connection, Side, State # noqa: F401
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
warnings.warn(
|
| 10 |
+
"websockets.connection was renamed to websockets.protocol "
|
| 11 |
+
"and Connection was renamed to Protocol",
|
| 12 |
+
DeprecationWarning,
|
| 13 |
+
)
|
videollama2/lib/python3.10/site-packages/websockets/datastructures.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
Iterable,
|
| 8 |
+
Iterator,
|
| 9 |
+
List,
|
| 10 |
+
Mapping,
|
| 11 |
+
MutableMapping,
|
| 12 |
+
Tuple,
|
| 13 |
+
Union,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if sys.version_info[:2] >= (3, 8):
|
| 18 |
+
from typing import Protocol
|
| 19 |
+
else: # pragma: no cover
|
| 20 |
+
Protocol = object # mypy will report errors on Python 3.7.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = ["Headers", "HeadersLike", "MultipleValuesError"]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MultipleValuesError(LookupError):
|
| 27 |
+
"""
|
| 28 |
+
Exception raised when :class:`Headers` has more than one value for a key.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __str__(self) -> str:
|
| 33 |
+
# Implement the same logic as KeyError_str in Objects/exceptions.c.
|
| 34 |
+
if len(self.args) == 1:
|
| 35 |
+
return repr(self.args[0])
|
| 36 |
+
return super().__str__()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Headers(MutableMapping[str, str]):
|
| 40 |
+
"""
|
| 41 |
+
Efficient data structure for manipulating HTTP headers.
|
| 42 |
+
|
| 43 |
+
A :class:`list` of ``(name, values)`` is inefficient for lookups.
|
| 44 |
+
|
| 45 |
+
A :class:`dict` doesn't suffice because header names are case-insensitive
|
| 46 |
+
and multiple occurrences of headers with the same name are possible.
|
| 47 |
+
|
| 48 |
+
:class:`Headers` stores HTTP headers in a hybrid data structure to provide
|
| 49 |
+
efficient insertions and lookups while preserving the original data.
|
| 50 |
+
|
| 51 |
+
In order to account for multiple values with minimal hassle,
|
| 52 |
+
:class:`Headers` follows this logic:
|
| 53 |
+
|
| 54 |
+
- When getting a header with ``headers[name]``:
|
| 55 |
+
- if there's no value, :exc:`KeyError` is raised;
|
| 56 |
+
- if there's exactly one value, it's returned;
|
| 57 |
+
- if there's more than one value, :exc:`MultipleValuesError` is raised.
|
| 58 |
+
|
| 59 |
+
- When setting a header with ``headers[name] = value``, the value is
|
| 60 |
+
appended to the list of values for that header.
|
| 61 |
+
|
| 62 |
+
- When deleting a header with ``del headers[name]``, all values for that
|
| 63 |
+
header are removed (this is slow).
|
| 64 |
+
|
| 65 |
+
Other methods for manipulating headers are consistent with this logic.
|
| 66 |
+
|
| 67 |
+
As long as no header occurs multiple times, :class:`Headers` behaves like
|
| 68 |
+
:class:`dict`, except keys are lower-cased to provide case-insensitivity.
|
| 69 |
+
|
| 70 |
+
Two methods support manipulating multiple values explicitly:
|
| 71 |
+
|
| 72 |
+
- :meth:`get_all` returns a list of all values for a header;
|
| 73 |
+
- :meth:`raw_items` returns an iterator of ``(name, values)`` pairs.
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
__slots__ = ["_dict", "_list"]
|
| 78 |
+
|
| 79 |
+
# Like dict, Headers accepts an optional "mapping or iterable" argument.
|
| 80 |
+
def __init__(self, *args: HeadersLike, **kwargs: str) -> None:
|
| 81 |
+
self._dict: Dict[str, List[str]] = {}
|
| 82 |
+
self._list: List[Tuple[str, str]] = []
|
| 83 |
+
self.update(*args, **kwargs)
|
| 84 |
+
|
| 85 |
+
def __str__(self) -> str:
|
| 86 |
+
return "".join(f"{key}: {value}\r\n" for key, value in self._list) + "\r\n"
|
| 87 |
+
|
| 88 |
+
def __repr__(self) -> str:
|
| 89 |
+
return f"{self.__class__.__name__}({self._list!r})"
|
| 90 |
+
|
| 91 |
+
def copy(self) -> Headers:
|
| 92 |
+
copy = self.__class__()
|
| 93 |
+
copy._dict = self._dict.copy()
|
| 94 |
+
copy._list = self._list.copy()
|
| 95 |
+
return copy
|
| 96 |
+
|
| 97 |
+
def serialize(self) -> bytes:
|
| 98 |
+
# Since headers only contain ASCII characters, we can keep this simple.
|
| 99 |
+
return str(self).encode()
|
| 100 |
+
|
| 101 |
+
# Collection methods
|
| 102 |
+
|
| 103 |
+
def __contains__(self, key: object) -> bool:
|
| 104 |
+
return isinstance(key, str) and key.lower() in self._dict
|
| 105 |
+
|
| 106 |
+
def __iter__(self) -> Iterator[str]:
|
| 107 |
+
return iter(self._dict)
|
| 108 |
+
|
| 109 |
+
def __len__(self) -> int:
|
| 110 |
+
return len(self._dict)
|
| 111 |
+
|
| 112 |
+
# MutableMapping methods
|
| 113 |
+
|
| 114 |
+
def __getitem__(self, key: str) -> str:
|
| 115 |
+
value = self._dict[key.lower()]
|
| 116 |
+
if len(value) == 1:
|
| 117 |
+
return value[0]
|
| 118 |
+
else:
|
| 119 |
+
raise MultipleValuesError(key)
|
| 120 |
+
|
| 121 |
+
def __setitem__(self, key: str, value: str) -> None:
|
| 122 |
+
self._dict.setdefault(key.lower(), []).append(value)
|
| 123 |
+
self._list.append((key, value))
|
| 124 |
+
|
| 125 |
+
def __delitem__(self, key: str) -> None:
|
| 126 |
+
key_lower = key.lower()
|
| 127 |
+
self._dict.__delitem__(key_lower)
|
| 128 |
+
# This is inefficient. Fortunately deleting HTTP headers is uncommon.
|
| 129 |
+
self._list = [(k, v) for k, v in self._list if k.lower() != key_lower]
|
| 130 |
+
|
| 131 |
+
def __eq__(self, other: Any) -> bool:
|
| 132 |
+
if not isinstance(other, Headers):
|
| 133 |
+
return NotImplemented
|
| 134 |
+
return self._dict == other._dict
|
| 135 |
+
|
| 136 |
+
def clear(self) -> None:
|
| 137 |
+
"""
|
| 138 |
+
Remove all headers.
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
self._dict = {}
|
| 142 |
+
self._list = []
|
| 143 |
+
|
| 144 |
+
def update(self, *args: HeadersLike, **kwargs: str) -> None:
|
| 145 |
+
"""
|
| 146 |
+
Update from a :class:`Headers` instance and/or keyword arguments.
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
args = tuple(
|
| 150 |
+
arg.raw_items() if isinstance(arg, Headers) else arg for arg in args
|
| 151 |
+
)
|
| 152 |
+
super().update(*args, **kwargs)
|
| 153 |
+
|
| 154 |
+
# Methods for handling multiple values
|
| 155 |
+
|
| 156 |
+
def get_all(self, key: str) -> List[str]:
|
| 157 |
+
"""
|
| 158 |
+
Return the (possibly empty) list of all values for a header.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
key: header name.
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
return self._dict.get(key.lower(), [])
|
| 165 |
+
|
| 166 |
+
def raw_items(self) -> Iterator[Tuple[str, str]]:
|
| 167 |
+
"""
|
| 168 |
+
Return an iterator of all values as ``(name, value)`` pairs.
|
| 169 |
+
|
| 170 |
+
"""
|
| 171 |
+
return iter(self._list)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# copy of _typeshed.SupportsKeysAndGetItem.
|
| 175 |
+
class SupportsKeysAndGetItem(Protocol): # pragma: no cover
|
| 176 |
+
"""
|
| 177 |
+
Dict-like types with ``keys() -> str`` and ``__getitem__(key: str) -> str`` methods.
|
| 178 |
+
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
def keys(self) -> Iterable[str]:
|
| 182 |
+
...
|
| 183 |
+
|
| 184 |
+
def __getitem__(self, key: str) -> str:
|
| 185 |
+
...
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
HeadersLike = Union[
|
| 189 |
+
Headers,
|
| 190 |
+
Mapping[str, str],
|
| 191 |
+
Iterable[Tuple[str, str]],
|
| 192 |
+
SupportsKeysAndGetItem,
|
| 193 |
+
]
|
| 194 |
+
"""
|
| 195 |
+
Types accepted where :class:`Headers` is expected.
|
| 196 |
+
|
| 197 |
+
In addition to :class:`Headers` itself, this includes dict-like types where both
|
| 198 |
+
keys and values are :class:`str`.
|
| 199 |
+
|
| 200 |
+
"""
|
videollama2/lib/python3.10/site-packages/websockets/extensions/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base import *
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"]
|
videollama2/lib/python3.10/site-packages/websockets/extensions/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (4.07 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/extensions/base.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import List, Optional, Sequence, Tuple
|
| 4 |
+
|
| 5 |
+
from .. import frames
|
| 6 |
+
from ..typing import ExtensionName, ExtensionParameter
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Extension:
|
| 13 |
+
"""
|
| 14 |
+
Base class for extensions.
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
name: ExtensionName
|
| 19 |
+
"""Extension identifier."""
|
| 20 |
+
|
| 21 |
+
def decode(
|
| 22 |
+
self,
|
| 23 |
+
frame: frames.Frame,
|
| 24 |
+
*,
|
| 25 |
+
max_size: Optional[int] = None,
|
| 26 |
+
) -> frames.Frame:
|
| 27 |
+
"""
|
| 28 |
+
Decode an incoming frame.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
frame (Frame): incoming frame.
|
| 32 |
+
max_size: maximum payload size in bytes.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
Frame: Decoded frame.
|
| 36 |
+
|
| 37 |
+
Raises:
|
| 38 |
+
PayloadTooBig: if decoding the payload exceeds ``max_size``.
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
raise NotImplementedError
|
| 42 |
+
|
| 43 |
+
def encode(self, frame: frames.Frame) -> frames.Frame:
|
| 44 |
+
"""
|
| 45 |
+
Encode an outgoing frame.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
frame (Frame): outgoing frame.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
Frame: Encoded frame.
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
raise NotImplementedError
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ClientExtensionFactory:
|
| 58 |
+
"""
|
| 59 |
+
Base class for client-side extension factories.
|
| 60 |
+
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
name: ExtensionName
|
| 64 |
+
"""Extension identifier."""
|
| 65 |
+
|
| 66 |
+
def get_request_params(self) -> List[ExtensionParameter]:
|
| 67 |
+
"""
|
| 68 |
+
Build parameters to send to the server for this extension.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
List[ExtensionParameter]: Parameters to send to the server.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
raise NotImplementedError
|
| 75 |
+
|
| 76 |
+
def process_response_params(
|
| 77 |
+
self,
|
| 78 |
+
params: Sequence[ExtensionParameter],
|
| 79 |
+
accepted_extensions: Sequence[Extension],
|
| 80 |
+
) -> Extension:
|
| 81 |
+
"""
|
| 82 |
+
Process parameters received from the server.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
params (Sequence[ExtensionParameter]): parameters received from
|
| 86 |
+
the server for this extension.
|
| 87 |
+
accepted_extensions (Sequence[Extension]): list of previously
|
| 88 |
+
accepted extensions.
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
Extension: An extension instance.
|
| 92 |
+
|
| 93 |
+
Raises:
|
| 94 |
+
NegotiationError: if parameters aren't acceptable.
|
| 95 |
+
|
| 96 |
+
"""
|
| 97 |
+
raise NotImplementedError
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class ServerExtensionFactory:
|
| 101 |
+
"""
|
| 102 |
+
Base class for server-side extension factories.
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
name: ExtensionName
|
| 107 |
+
"""Extension identifier."""
|
| 108 |
+
|
| 109 |
+
def process_request_params(
|
| 110 |
+
self,
|
| 111 |
+
params: Sequence[ExtensionParameter],
|
| 112 |
+
accepted_extensions: Sequence[Extension],
|
| 113 |
+
) -> Tuple[List[ExtensionParameter], Extension]:
|
| 114 |
+
"""
|
| 115 |
+
Process parameters received from the client.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
params (Sequence[ExtensionParameter]): parameters received from
|
| 119 |
+
the client for this extension.
|
| 120 |
+
accepted_extensions (Sequence[Extension]): list of previously
|
| 121 |
+
accepted extensions.
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
Tuple[List[ExtensionParameter], Extension]: To accept the offer,
|
| 125 |
+
parameters to send to the client for this extension and an
|
| 126 |
+
extension instance.
|
| 127 |
+
|
| 128 |
+
Raises:
|
| 129 |
+
NegotiationError: to reject the offer, if parameters received from
|
| 130 |
+
the client aren't acceptable.
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
raise NotImplementedError
|
videollama2/lib/python3.10/site-packages/websockets/extensions/permessage_deflate.py
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import dataclasses
|
| 4 |
+
import zlib
|
| 5 |
+
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
|
| 6 |
+
|
| 7 |
+
from .. import exceptions, frames
|
| 8 |
+
from ..typing import ExtensionName, ExtensionParameter
|
| 9 |
+
from .base import ClientExtensionFactory, Extension, ServerExtensionFactory
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"PerMessageDeflate",
|
| 14 |
+
"ClientPerMessageDeflateFactory",
|
| 15 |
+
"enable_client_permessage_deflate",
|
| 16 |
+
"ServerPerMessageDeflateFactory",
|
| 17 |
+
"enable_server_permessage_deflate",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
_EMPTY_UNCOMPRESSED_BLOCK = b"\x00\x00\xff\xff"
|
| 21 |
+
|
| 22 |
+
_MAX_WINDOW_BITS_VALUES = [str(bits) for bits in range(8, 16)]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class PerMessageDeflate(Extension):
|
| 26 |
+
"""
|
| 27 |
+
Per-Message Deflate extension.
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
name = ExtensionName("permessage-deflate")
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
remote_no_context_takeover: bool,
|
| 36 |
+
local_no_context_takeover: bool,
|
| 37 |
+
remote_max_window_bits: int,
|
| 38 |
+
local_max_window_bits: int,
|
| 39 |
+
compress_settings: Optional[Dict[Any, Any]] = None,
|
| 40 |
+
) -> None:
|
| 41 |
+
"""
|
| 42 |
+
Configure the Per-Message Deflate extension.
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
if compress_settings is None:
|
| 46 |
+
compress_settings = {}
|
| 47 |
+
|
| 48 |
+
assert remote_no_context_takeover in [False, True]
|
| 49 |
+
assert local_no_context_takeover in [False, True]
|
| 50 |
+
assert 8 <= remote_max_window_bits <= 15
|
| 51 |
+
assert 8 <= local_max_window_bits <= 15
|
| 52 |
+
assert "wbits" not in compress_settings
|
| 53 |
+
|
| 54 |
+
self.remote_no_context_takeover = remote_no_context_takeover
|
| 55 |
+
self.local_no_context_takeover = local_no_context_takeover
|
| 56 |
+
self.remote_max_window_bits = remote_max_window_bits
|
| 57 |
+
self.local_max_window_bits = local_max_window_bits
|
| 58 |
+
self.compress_settings = compress_settings
|
| 59 |
+
|
| 60 |
+
if not self.remote_no_context_takeover:
|
| 61 |
+
self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits)
|
| 62 |
+
|
| 63 |
+
if not self.local_no_context_takeover:
|
| 64 |
+
self.encoder = zlib.compressobj(
|
| 65 |
+
wbits=-self.local_max_window_bits, **self.compress_settings
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# To handle continuation frames properly, we must keep track of
|
| 69 |
+
# whether that initial frame was encoded.
|
| 70 |
+
self.decode_cont_data = False
|
| 71 |
+
# There's no need for self.encode_cont_data because we always encode
|
| 72 |
+
# outgoing frames, so it would always be True.
|
| 73 |
+
|
| 74 |
+
def __repr__(self) -> str:
|
| 75 |
+
return (
|
| 76 |
+
f"PerMessageDeflate("
|
| 77 |
+
f"remote_no_context_takeover={self.remote_no_context_takeover}, "
|
| 78 |
+
f"local_no_context_takeover={self.local_no_context_takeover}, "
|
| 79 |
+
f"remote_max_window_bits={self.remote_max_window_bits}, "
|
| 80 |
+
f"local_max_window_bits={self.local_max_window_bits})"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def decode(
|
| 84 |
+
self,
|
| 85 |
+
frame: frames.Frame,
|
| 86 |
+
*,
|
| 87 |
+
max_size: Optional[int] = None,
|
| 88 |
+
) -> frames.Frame:
|
| 89 |
+
"""
|
| 90 |
+
Decode an incoming frame.
|
| 91 |
+
|
| 92 |
+
"""
|
| 93 |
+
# Skip control frames.
|
| 94 |
+
if frame.opcode in frames.CTRL_OPCODES:
|
| 95 |
+
return frame
|
| 96 |
+
|
| 97 |
+
# Handle continuation data frames:
|
| 98 |
+
# - skip if the message isn't encoded
|
| 99 |
+
# - reset "decode continuation data" flag if it's a final frame
|
| 100 |
+
if frame.opcode is frames.OP_CONT:
|
| 101 |
+
if not self.decode_cont_data:
|
| 102 |
+
return frame
|
| 103 |
+
if frame.fin:
|
| 104 |
+
self.decode_cont_data = False
|
| 105 |
+
|
| 106 |
+
# Handle text and binary data frames:
|
| 107 |
+
# - skip if the message isn't encoded
|
| 108 |
+
# - unset the rsv1 flag on the first frame of a compressed message
|
| 109 |
+
# - set "decode continuation data" flag if it's a non-final frame
|
| 110 |
+
else:
|
| 111 |
+
if not frame.rsv1:
|
| 112 |
+
return frame
|
| 113 |
+
frame = dataclasses.replace(frame, rsv1=False)
|
| 114 |
+
if not frame.fin:
|
| 115 |
+
self.decode_cont_data = True
|
| 116 |
+
|
| 117 |
+
# Re-initialize per-message decoder.
|
| 118 |
+
if self.remote_no_context_takeover:
|
| 119 |
+
self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits)
|
| 120 |
+
|
| 121 |
+
# Uncompress data. Protect against zip bombs by preventing zlib from
|
| 122 |
+
# decompressing more than max_length bytes (except when the limit is
|
| 123 |
+
# disabled with max_size = None).
|
| 124 |
+
data = frame.data
|
| 125 |
+
if frame.fin:
|
| 126 |
+
data += _EMPTY_UNCOMPRESSED_BLOCK
|
| 127 |
+
max_length = 0 if max_size is None else max_size
|
| 128 |
+
try:
|
| 129 |
+
data = self.decoder.decompress(data, max_length)
|
| 130 |
+
except zlib.error as exc:
|
| 131 |
+
raise exceptions.ProtocolError("decompression failed") from exc
|
| 132 |
+
if self.decoder.unconsumed_tail:
|
| 133 |
+
raise exceptions.PayloadTooBig(f"over size limit (? > {max_size} bytes)")
|
| 134 |
+
|
| 135 |
+
# Allow garbage collection of the decoder if it won't be reused.
|
| 136 |
+
if frame.fin and self.remote_no_context_takeover:
|
| 137 |
+
del self.decoder
|
| 138 |
+
|
| 139 |
+
return dataclasses.replace(frame, data=data)
|
| 140 |
+
|
| 141 |
+
def encode(self, frame: frames.Frame) -> frames.Frame:
|
| 142 |
+
"""
|
| 143 |
+
Encode an outgoing frame.
|
| 144 |
+
|
| 145 |
+
"""
|
| 146 |
+
# Skip control frames.
|
| 147 |
+
if frame.opcode in frames.CTRL_OPCODES:
|
| 148 |
+
return frame
|
| 149 |
+
|
| 150 |
+
# Since we always encode messages, there's no "encode continuation
|
| 151 |
+
# data" flag similar to "decode continuation data" at this time.
|
| 152 |
+
|
| 153 |
+
if frame.opcode is not frames.OP_CONT:
|
| 154 |
+
# Set the rsv1 flag on the first frame of a compressed message.
|
| 155 |
+
frame = dataclasses.replace(frame, rsv1=True)
|
| 156 |
+
# Re-initialize per-message decoder.
|
| 157 |
+
if self.local_no_context_takeover:
|
| 158 |
+
self.encoder = zlib.compressobj(
|
| 159 |
+
wbits=-self.local_max_window_bits, **self.compress_settings
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Compress data.
|
| 163 |
+
data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH)
|
| 164 |
+
if frame.fin and data.endswith(_EMPTY_UNCOMPRESSED_BLOCK):
|
| 165 |
+
data = data[:-4]
|
| 166 |
+
|
| 167 |
+
# Allow garbage collection of the encoder if it won't be reused.
|
| 168 |
+
if frame.fin and self.local_no_context_takeover:
|
| 169 |
+
del self.encoder
|
| 170 |
+
|
| 171 |
+
return dataclasses.replace(frame, data=data)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _build_parameters(
|
| 175 |
+
server_no_context_takeover: bool,
|
| 176 |
+
client_no_context_takeover: bool,
|
| 177 |
+
server_max_window_bits: Optional[int],
|
| 178 |
+
client_max_window_bits: Optional[Union[int, bool]],
|
| 179 |
+
) -> List[ExtensionParameter]:
|
| 180 |
+
"""
|
| 181 |
+
Build a list of ``(name, value)`` pairs for some compression parameters.
|
| 182 |
+
|
| 183 |
+
"""
|
| 184 |
+
params: List[ExtensionParameter] = []
|
| 185 |
+
if server_no_context_takeover:
|
| 186 |
+
params.append(("server_no_context_takeover", None))
|
| 187 |
+
if client_no_context_takeover:
|
| 188 |
+
params.append(("client_no_context_takeover", None))
|
| 189 |
+
if server_max_window_bits:
|
| 190 |
+
params.append(("server_max_window_bits", str(server_max_window_bits)))
|
| 191 |
+
if client_max_window_bits is True: # only in handshake requests
|
| 192 |
+
params.append(("client_max_window_bits", None))
|
| 193 |
+
elif client_max_window_bits:
|
| 194 |
+
params.append(("client_max_window_bits", str(client_max_window_bits)))
|
| 195 |
+
return params
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _extract_parameters(
|
| 199 |
+
params: Sequence[ExtensionParameter], *, is_server: bool
|
| 200 |
+
) -> Tuple[bool, bool, Optional[int], Optional[Union[int, bool]]]:
|
| 201 |
+
"""
|
| 202 |
+
Extract compression parameters from a list of ``(name, value)`` pairs.
|
| 203 |
+
|
| 204 |
+
If ``is_server`` is :obj:`True`, ``client_max_window_bits`` may be
|
| 205 |
+
provided without a value. This is only allowed in handshake requests.
|
| 206 |
+
|
| 207 |
+
"""
|
| 208 |
+
server_no_context_takeover: bool = False
|
| 209 |
+
client_no_context_takeover: bool = False
|
| 210 |
+
server_max_window_bits: Optional[int] = None
|
| 211 |
+
client_max_window_bits: Optional[Union[int, bool]] = None
|
| 212 |
+
|
| 213 |
+
for name, value in params:
|
| 214 |
+
if name == "server_no_context_takeover":
|
| 215 |
+
if server_no_context_takeover:
|
| 216 |
+
raise exceptions.DuplicateParameter(name)
|
| 217 |
+
if value is None:
|
| 218 |
+
server_no_context_takeover = True
|
| 219 |
+
else:
|
| 220 |
+
raise exceptions.InvalidParameterValue(name, value)
|
| 221 |
+
|
| 222 |
+
elif name == "client_no_context_takeover":
|
| 223 |
+
if client_no_context_takeover:
|
| 224 |
+
raise exceptions.DuplicateParameter(name)
|
| 225 |
+
if value is None:
|
| 226 |
+
client_no_context_takeover = True
|
| 227 |
+
else:
|
| 228 |
+
raise exceptions.InvalidParameterValue(name, value)
|
| 229 |
+
|
| 230 |
+
elif name == "server_max_window_bits":
|
| 231 |
+
if server_max_window_bits is not None:
|
| 232 |
+
raise exceptions.DuplicateParameter(name)
|
| 233 |
+
if value in _MAX_WINDOW_BITS_VALUES:
|
| 234 |
+
server_max_window_bits = int(value)
|
| 235 |
+
else:
|
| 236 |
+
raise exceptions.InvalidParameterValue(name, value)
|
| 237 |
+
|
| 238 |
+
elif name == "client_max_window_bits":
|
| 239 |
+
if client_max_window_bits is not None:
|
| 240 |
+
raise exceptions.DuplicateParameter(name)
|
| 241 |
+
if is_server and value is None: # only in handshake requests
|
| 242 |
+
client_max_window_bits = True
|
| 243 |
+
elif value in _MAX_WINDOW_BITS_VALUES:
|
| 244 |
+
client_max_window_bits = int(value)
|
| 245 |
+
else:
|
| 246 |
+
raise exceptions.InvalidParameterValue(name, value)
|
| 247 |
+
|
| 248 |
+
else:
|
| 249 |
+
raise exceptions.InvalidParameterName(name)
|
| 250 |
+
|
| 251 |
+
return (
|
| 252 |
+
server_no_context_takeover,
|
| 253 |
+
client_no_context_takeover,
|
| 254 |
+
server_max_window_bits,
|
| 255 |
+
client_max_window_bits,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class ClientPerMessageDeflateFactory(ClientExtensionFactory):
|
| 260 |
+
"""
|
| 261 |
+
Client-side extension factory for the Per-Message Deflate extension.
|
| 262 |
+
|
| 263 |
+
Parameters behave as described in `section 7.1 of RFC 7692`_.
|
| 264 |
+
|
| 265 |
+
.. _section 7.1 of RFC 7692: https://www.rfc-editor.org/rfc/rfc7692.html#section-7.1
|
| 266 |
+
|
| 267 |
+
Set them to :obj:`True` to include them in the negotiation offer without a
|
| 268 |
+
value or to an integer value to include them with this value.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
server_no_context_takeover: prevent server from using context takeover.
|
| 272 |
+
client_no_context_takeover: prevent client from using context takeover.
|
| 273 |
+
server_max_window_bits: maximum size of the server's LZ77 sliding window
|
| 274 |
+
in bits, between 8 and 15.
|
| 275 |
+
client_max_window_bits: maximum size of the client's LZ77 sliding window
|
| 276 |
+
in bits, between 8 and 15, or :obj:`True` to indicate support without
|
| 277 |
+
setting a limit.
|
| 278 |
+
compress_settings: additional keyword arguments for :func:`zlib.compressobj`,
|
| 279 |
+
excluding ``wbits``.
|
| 280 |
+
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
name = ExtensionName("permessage-deflate")
|
| 284 |
+
|
| 285 |
+
def __init__(
|
| 286 |
+
self,
|
| 287 |
+
server_no_context_takeover: bool = False,
|
| 288 |
+
client_no_context_takeover: bool = False,
|
| 289 |
+
server_max_window_bits: Optional[int] = None,
|
| 290 |
+
client_max_window_bits: Optional[Union[int, bool]] = True,
|
| 291 |
+
compress_settings: Optional[Dict[str, Any]] = None,
|
| 292 |
+
) -> None:
|
| 293 |
+
"""
|
| 294 |
+
Configure the Per-Message Deflate extension factory.
|
| 295 |
+
|
| 296 |
+
"""
|
| 297 |
+
if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15):
|
| 298 |
+
raise ValueError("server_max_window_bits must be between 8 and 15")
|
| 299 |
+
if not (
|
| 300 |
+
client_max_window_bits is None
|
| 301 |
+
or client_max_window_bits is True
|
| 302 |
+
or 8 <= client_max_window_bits <= 15
|
| 303 |
+
):
|
| 304 |
+
raise ValueError("client_max_window_bits must be between 8 and 15")
|
| 305 |
+
if compress_settings is not None and "wbits" in compress_settings:
|
| 306 |
+
raise ValueError(
|
| 307 |
+
"compress_settings must not include wbits, "
|
| 308 |
+
"set client_max_window_bits instead"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
self.server_no_context_takeover = server_no_context_takeover
|
| 312 |
+
self.client_no_context_takeover = client_no_context_takeover
|
| 313 |
+
self.server_max_window_bits = server_max_window_bits
|
| 314 |
+
self.client_max_window_bits = client_max_window_bits
|
| 315 |
+
self.compress_settings = compress_settings
|
| 316 |
+
|
| 317 |
+
def get_request_params(self) -> List[ExtensionParameter]:
|
| 318 |
+
"""
|
| 319 |
+
Build request parameters.
|
| 320 |
+
|
| 321 |
+
"""
|
| 322 |
+
return _build_parameters(
|
| 323 |
+
self.server_no_context_takeover,
|
| 324 |
+
self.client_no_context_takeover,
|
| 325 |
+
self.server_max_window_bits,
|
| 326 |
+
self.client_max_window_bits,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
def process_response_params(
|
| 330 |
+
self,
|
| 331 |
+
params: Sequence[ExtensionParameter],
|
| 332 |
+
accepted_extensions: Sequence[Extension],
|
| 333 |
+
) -> PerMessageDeflate:
|
| 334 |
+
"""
|
| 335 |
+
Process response parameters.
|
| 336 |
+
|
| 337 |
+
Return an extension instance.
|
| 338 |
+
|
| 339 |
+
"""
|
| 340 |
+
if any(other.name == self.name for other in accepted_extensions):
|
| 341 |
+
raise exceptions.NegotiationError(f"received duplicate {self.name}")
|
| 342 |
+
|
| 343 |
+
# Request parameters are available in instance variables.
|
| 344 |
+
|
| 345 |
+
# Load response parameters in local variables.
|
| 346 |
+
(
|
| 347 |
+
server_no_context_takeover,
|
| 348 |
+
client_no_context_takeover,
|
| 349 |
+
server_max_window_bits,
|
| 350 |
+
client_max_window_bits,
|
| 351 |
+
) = _extract_parameters(params, is_server=False)
|
| 352 |
+
|
| 353 |
+
# After comparing the request and the response, the final
|
| 354 |
+
# configuration must be available in the local variables.
|
| 355 |
+
|
| 356 |
+
# server_no_context_takeover
|
| 357 |
+
#
|
| 358 |
+
# Req. Resp. Result
|
| 359 |
+
# ------ ------ --------------------------------------------------
|
| 360 |
+
# False False False
|
| 361 |
+
# False True True
|
| 362 |
+
# True False Error!
|
| 363 |
+
# True True True
|
| 364 |
+
|
| 365 |
+
if self.server_no_context_takeover:
|
| 366 |
+
if not server_no_context_takeover:
|
| 367 |
+
raise exceptions.NegotiationError("expected server_no_context_takeover")
|
| 368 |
+
|
| 369 |
+
# client_no_context_takeover
|
| 370 |
+
#
|
| 371 |
+
# Req. Resp. Result
|
| 372 |
+
# ------ ------ --------------------------------------------------
|
| 373 |
+
# False False False
|
| 374 |
+
# False True True
|
| 375 |
+
# True False True - must change value
|
| 376 |
+
# True True True
|
| 377 |
+
|
| 378 |
+
if self.client_no_context_takeover:
|
| 379 |
+
if not client_no_context_takeover:
|
| 380 |
+
client_no_context_takeover = True
|
| 381 |
+
|
| 382 |
+
# server_max_window_bits
|
| 383 |
+
|
| 384 |
+
# Req. Resp. Result
|
| 385 |
+
# ------ ------ --------------------------------------------------
|
| 386 |
+
# None None None
|
| 387 |
+
# None 8≤M≤15 M
|
| 388 |
+
# 8≤N≤15 None Error!
|
| 389 |
+
# 8≤N≤15 8≤M≤N M
|
| 390 |
+
# 8≤N≤15 N<M≤15 Error!
|
| 391 |
+
|
| 392 |
+
if self.server_max_window_bits is None:
|
| 393 |
+
pass
|
| 394 |
+
|
| 395 |
+
else:
|
| 396 |
+
if server_max_window_bits is None:
|
| 397 |
+
raise exceptions.NegotiationError("expected server_max_window_bits")
|
| 398 |
+
elif server_max_window_bits > self.server_max_window_bits:
|
| 399 |
+
raise exceptions.NegotiationError("unsupported server_max_window_bits")
|
| 400 |
+
|
| 401 |
+
# client_max_window_bits
|
| 402 |
+
|
| 403 |
+
# Req. Resp. Result
|
| 404 |
+
# ------ ------ --------------------------------------------------
|
| 405 |
+
# None None None
|
| 406 |
+
# None 8≤M≤15 Error!
|
| 407 |
+
# True None None
|
| 408 |
+
# True 8≤M≤15 M
|
| 409 |
+
# 8≤N≤15 None N - must change value
|
| 410 |
+
# 8≤N≤15 8≤M≤N M
|
| 411 |
+
# 8≤N≤15 N<M≤15 Error!
|
| 412 |
+
|
| 413 |
+
if self.client_max_window_bits is None:
|
| 414 |
+
if client_max_window_bits is not None:
|
| 415 |
+
raise exceptions.NegotiationError("unexpected client_max_window_bits")
|
| 416 |
+
|
| 417 |
+
elif self.client_max_window_bits is True:
|
| 418 |
+
pass
|
| 419 |
+
|
| 420 |
+
else:
|
| 421 |
+
if client_max_window_bits is None:
|
| 422 |
+
client_max_window_bits = self.client_max_window_bits
|
| 423 |
+
elif client_max_window_bits > self.client_max_window_bits:
|
| 424 |
+
raise exceptions.NegotiationError("unsupported client_max_window_bits")
|
| 425 |
+
|
| 426 |
+
return PerMessageDeflate(
|
| 427 |
+
server_no_context_takeover, # remote_no_context_takeover
|
| 428 |
+
client_no_context_takeover, # local_no_context_takeover
|
| 429 |
+
server_max_window_bits or 15, # remote_max_window_bits
|
| 430 |
+
client_max_window_bits or 15, # local_max_window_bits
|
| 431 |
+
self.compress_settings,
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def enable_client_permessage_deflate(
|
| 436 |
+
extensions: Optional[Sequence[ClientExtensionFactory]],
|
| 437 |
+
) -> Sequence[ClientExtensionFactory]:
|
| 438 |
+
"""
|
| 439 |
+
Enable Per-Message Deflate with default settings in client extensions.
|
| 440 |
+
|
| 441 |
+
If the extension is already present, perhaps with non-default settings,
|
| 442 |
+
the configuration isn't changed.
|
| 443 |
+
|
| 444 |
+
"""
|
| 445 |
+
if extensions is None:
|
| 446 |
+
extensions = []
|
| 447 |
+
if not any(
|
| 448 |
+
extension_factory.name == ClientPerMessageDeflateFactory.name
|
| 449 |
+
for extension_factory in extensions
|
| 450 |
+
):
|
| 451 |
+
extensions = list(extensions) + [
|
| 452 |
+
ClientPerMessageDeflateFactory(
|
| 453 |
+
compress_settings={"memLevel": 5},
|
| 454 |
+
)
|
| 455 |
+
]
|
| 456 |
+
return extensions
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class ServerPerMessageDeflateFactory(ServerExtensionFactory):
|
| 460 |
+
"""
|
| 461 |
+
Server-side extension factory for the Per-Message Deflate extension.
|
| 462 |
+
|
| 463 |
+
Parameters behave as described in `section 7.1 of RFC 7692`_.
|
| 464 |
+
|
| 465 |
+
.. _section 7.1 of RFC 7692: https://www.rfc-editor.org/rfc/rfc7692.html#section-7.1
|
| 466 |
+
|
| 467 |
+
Set them to :obj:`True` to include them in the negotiation offer without a
|
| 468 |
+
value or to an integer value to include them with this value.
|
| 469 |
+
|
| 470 |
+
Args:
|
| 471 |
+
server_no_context_takeover: prevent server from using context takeover.
|
| 472 |
+
client_no_context_takeover: prevent client from using context takeover.
|
| 473 |
+
server_max_window_bits: maximum size of the server's LZ77 sliding window
|
| 474 |
+
in bits, between 8 and 15.
|
| 475 |
+
client_max_window_bits: maximum size of the client's LZ77 sliding window
|
| 476 |
+
in bits, between 8 and 15.
|
| 477 |
+
compress_settings: additional keyword arguments for :func:`zlib.compressobj`,
|
| 478 |
+
excluding ``wbits``.
|
| 479 |
+
require_client_max_window_bits: do not enable compression at all if
|
| 480 |
+
client doesn't advertise support for ``client_max_window_bits``;
|
| 481 |
+
the default behavior is to enable compression without enforcing
|
| 482 |
+
``client_max_window_bits``.
|
| 483 |
+
|
| 484 |
+
"""
|
| 485 |
+
|
| 486 |
+
name = ExtensionName("permessage-deflate")
|
| 487 |
+
|
| 488 |
+
def __init__(
|
| 489 |
+
self,
|
| 490 |
+
server_no_context_takeover: bool = False,
|
| 491 |
+
client_no_context_takeover: bool = False,
|
| 492 |
+
server_max_window_bits: Optional[int] = None,
|
| 493 |
+
client_max_window_bits: Optional[int] = None,
|
| 494 |
+
compress_settings: Optional[Dict[str, Any]] = None,
|
| 495 |
+
require_client_max_window_bits: bool = False,
|
| 496 |
+
) -> None:
|
| 497 |
+
"""
|
| 498 |
+
Configure the Per-Message Deflate extension factory.
|
| 499 |
+
|
| 500 |
+
"""
|
| 501 |
+
if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15):
|
| 502 |
+
raise ValueError("server_max_window_bits must be between 8 and 15")
|
| 503 |
+
if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15):
|
| 504 |
+
raise ValueError("client_max_window_bits must be between 8 and 15")
|
| 505 |
+
if compress_settings is not None and "wbits" in compress_settings:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
"compress_settings must not include wbits, "
|
| 508 |
+
"set server_max_window_bits instead"
|
| 509 |
+
)
|
| 510 |
+
if client_max_window_bits is None and require_client_max_window_bits:
|
| 511 |
+
raise ValueError(
|
| 512 |
+
"require_client_max_window_bits is enabled, "
|
| 513 |
+
"but client_max_window_bits isn't configured"
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
self.server_no_context_takeover = server_no_context_takeover
|
| 517 |
+
self.client_no_context_takeover = client_no_context_takeover
|
| 518 |
+
self.server_max_window_bits = server_max_window_bits
|
| 519 |
+
self.client_max_window_bits = client_max_window_bits
|
| 520 |
+
self.compress_settings = compress_settings
|
| 521 |
+
self.require_client_max_window_bits = require_client_max_window_bits
|
| 522 |
+
|
| 523 |
+
def process_request_params(
|
| 524 |
+
self,
|
| 525 |
+
params: Sequence[ExtensionParameter],
|
| 526 |
+
accepted_extensions: Sequence[Extension],
|
| 527 |
+
) -> Tuple[List[ExtensionParameter], PerMessageDeflate]:
|
| 528 |
+
"""
|
| 529 |
+
Process request parameters.
|
| 530 |
+
|
| 531 |
+
Return response params and an extension instance.
|
| 532 |
+
|
| 533 |
+
"""
|
| 534 |
+
if any(other.name == self.name for other in accepted_extensions):
|
| 535 |
+
raise exceptions.NegotiationError(f"skipped duplicate {self.name}")
|
| 536 |
+
|
| 537 |
+
# Load request parameters in local variables.
|
| 538 |
+
(
|
| 539 |
+
server_no_context_takeover,
|
| 540 |
+
client_no_context_takeover,
|
| 541 |
+
server_max_window_bits,
|
| 542 |
+
client_max_window_bits,
|
| 543 |
+
) = _extract_parameters(params, is_server=True)
|
| 544 |
+
|
| 545 |
+
# Configuration parameters are available in instance variables.
|
| 546 |
+
|
| 547 |
+
# After comparing the request and the configuration, the response must
|
| 548 |
+
# be available in the local variables.
|
| 549 |
+
|
| 550 |
+
# server_no_context_takeover
|
| 551 |
+
#
|
| 552 |
+
# Config Req. Resp.
|
| 553 |
+
# ------ ------ --------------------------------------------------
|
| 554 |
+
# False False False
|
| 555 |
+
# False True True
|
| 556 |
+
# True False True - must change value to True
|
| 557 |
+
# True True True
|
| 558 |
+
|
| 559 |
+
if self.server_no_context_takeover:
|
| 560 |
+
if not server_no_context_takeover:
|
| 561 |
+
server_no_context_takeover = True
|
| 562 |
+
|
| 563 |
+
# client_no_context_takeover
|
| 564 |
+
#
|
| 565 |
+
# Config Req. Resp.
|
| 566 |
+
# ------ ------ --------------------------------------------------
|
| 567 |
+
# False False False
|
| 568 |
+
# False True True (or False)
|
| 569 |
+
# True False True - must change value to True
|
| 570 |
+
# True True True (or False)
|
| 571 |
+
|
| 572 |
+
if self.client_no_context_takeover:
|
| 573 |
+
if not client_no_context_takeover:
|
| 574 |
+
client_no_context_takeover = True
|
| 575 |
+
|
| 576 |
+
# server_max_window_bits
|
| 577 |
+
|
| 578 |
+
# Config Req. Resp.
|
| 579 |
+
# ------ ------ --------------------------------------------------
|
| 580 |
+
# None None None
|
| 581 |
+
# None 8≤M≤15 M
|
| 582 |
+
# 8≤N≤15 None N - must change value
|
| 583 |
+
# 8≤N≤15 8≤M≤N M
|
| 584 |
+
# 8≤N≤15 N<M≤15 N - must change value
|
| 585 |
+
|
| 586 |
+
if self.server_max_window_bits is None:
|
| 587 |
+
pass
|
| 588 |
+
|
| 589 |
+
else:
|
| 590 |
+
if server_max_window_bits is None:
|
| 591 |
+
server_max_window_bits = self.server_max_window_bits
|
| 592 |
+
elif server_max_window_bits > self.server_max_window_bits:
|
| 593 |
+
server_max_window_bits = self.server_max_window_bits
|
| 594 |
+
|
| 595 |
+
# client_max_window_bits
|
| 596 |
+
|
| 597 |
+
# Config Req. Resp.
|
| 598 |
+
# ------ ------ --------------------------------------------------
|
| 599 |
+
# None None None
|
| 600 |
+
# None True None - must change value
|
| 601 |
+
# None 8≤M≤15 M (or None)
|
| 602 |
+
# 8≤N≤15 None None or Error!
|
| 603 |
+
# 8≤N≤15 True N - must change value
|
| 604 |
+
# 8≤N≤15 8≤M≤N M (or None)
|
| 605 |
+
# 8≤N≤15 N<M≤15 N
|
| 606 |
+
|
| 607 |
+
if self.client_max_window_bits is None:
|
| 608 |
+
if client_max_window_bits is True:
|
| 609 |
+
client_max_window_bits = self.client_max_window_bits
|
| 610 |
+
|
| 611 |
+
else:
|
| 612 |
+
if client_max_window_bits is None:
|
| 613 |
+
if self.require_client_max_window_bits:
|
| 614 |
+
raise exceptions.NegotiationError("required client_max_window_bits")
|
| 615 |
+
elif client_max_window_bits is True:
|
| 616 |
+
client_max_window_bits = self.client_max_window_bits
|
| 617 |
+
elif self.client_max_window_bits < client_max_window_bits:
|
| 618 |
+
client_max_window_bits = self.client_max_window_bits
|
| 619 |
+
|
| 620 |
+
return (
|
| 621 |
+
_build_parameters(
|
| 622 |
+
server_no_context_takeover,
|
| 623 |
+
client_no_context_takeover,
|
| 624 |
+
server_max_window_bits,
|
| 625 |
+
client_max_window_bits,
|
| 626 |
+
),
|
| 627 |
+
PerMessageDeflate(
|
| 628 |
+
client_no_context_takeover, # remote_no_context_takeover
|
| 629 |
+
server_no_context_takeover, # local_no_context_takeover
|
| 630 |
+
client_max_window_bits or 15, # remote_max_window_bits
|
| 631 |
+
server_max_window_bits or 15, # local_max_window_bits
|
| 632 |
+
self.compress_settings,
|
| 633 |
+
),
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def enable_server_permessage_deflate(
|
| 638 |
+
extensions: Optional[Sequence[ServerExtensionFactory]],
|
| 639 |
+
) -> Sequence[ServerExtensionFactory]:
|
| 640 |
+
"""
|
| 641 |
+
Enable Per-Message Deflate with default settings in server extensions.
|
| 642 |
+
|
| 643 |
+
If the extension is already present, perhaps with non-default settings,
|
| 644 |
+
the configuration isn't changed.
|
| 645 |
+
|
| 646 |
+
"""
|
| 647 |
+
if extensions is None:
|
| 648 |
+
extensions = []
|
| 649 |
+
if not any(
|
| 650 |
+
ext_factory.name == ServerPerMessageDeflateFactory.name
|
| 651 |
+
for ext_factory in extensions
|
| 652 |
+
):
|
| 653 |
+
extensions = list(extensions) + [
|
| 654 |
+
ServerPerMessageDeflateFactory(
|
| 655 |
+
server_max_window_bits=12,
|
| 656 |
+
client_max_window_bits=12,
|
| 657 |
+
compress_settings={"memLevel": 5},
|
| 658 |
+
)
|
| 659 |
+
]
|
| 660 |
+
return extensions
|
videollama2/lib/python3.10/site-packages/websockets/frames.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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um
|
| 5 |
+
import io
|
| 6 |
+
import secrets
|
| 7 |
+
import struct
|
| 8 |
+
from typing import Callable, Generator, Optional, Sequence, Tuple
|
| 9 |
+
|
| 10 |
+
from . import exceptions, extensions
|
| 11 |
+
from .typing import Data
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
from .speedups import apply_mask
|
| 16 |
+
except ImportError:
|
| 17 |
+
from .utils import apply_mask
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"Opcode",
|
| 22 |
+
"OP_CONT",
|
| 23 |
+
"OP_TEXT",
|
| 24 |
+
"OP_BINARY",
|
| 25 |
+
"OP_CLOSE",
|
| 26 |
+
"OP_PING",
|
| 27 |
+
"OP_PONG",
|
| 28 |
+
"DATA_OPCODES",
|
| 29 |
+
"CTRL_OPCODES",
|
| 30 |
+
"Frame",
|
| 31 |
+
"prepare_data",
|
| 32 |
+
"prepare_ctrl",
|
| 33 |
+
"Close",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Opcode(enum.IntEnum):
|
| 38 |
+
"""Opcode values for WebSocket frames."""
|
| 39 |
+
|
| 40 |
+
CONT, TEXT, BINARY = 0x00, 0x01, 0x02
|
| 41 |
+
CLOSE, PING, PONG = 0x08, 0x09, 0x0A
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
OP_CONT = Opcode.CONT
|
| 45 |
+
OP_TEXT = Opcode.TEXT
|
| 46 |
+
OP_BINARY = Opcode.BINARY
|
| 47 |
+
OP_CLOSE = Opcode.CLOSE
|
| 48 |
+
OP_PING = Opcode.PING
|
| 49 |
+
OP_PONG = Opcode.PONG
|
| 50 |
+
|
| 51 |
+
DATA_OPCODES = OP_CONT, OP_TEXT, OP_BINARY
|
| 52 |
+
CTRL_OPCODES = OP_CLOSE, OP_PING, OP_PONG
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# See https://www.iana.org/assignments/websocket/websocket.xhtml
|
| 56 |
+
CLOSE_CODES = {
|
| 57 |
+
1000: "OK",
|
| 58 |
+
1001: "going away",
|
| 59 |
+
1002: "protocol error",
|
| 60 |
+
1003: "unsupported type",
|
| 61 |
+
# 1004 is reserved
|
| 62 |
+
1005: "no status code [internal]",
|
| 63 |
+
1006: "connection closed abnormally [internal]",
|
| 64 |
+
1007: "invalid data",
|
| 65 |
+
1008: "policy violation",
|
| 66 |
+
1009: "message too big",
|
| 67 |
+
1010: "extension required",
|
| 68 |
+
1011: "unexpected error",
|
| 69 |
+
1012: "service restart",
|
| 70 |
+
1013: "try again later",
|
| 71 |
+
1014: "bad gateway",
|
| 72 |
+
1015: "TLS failure [internal]",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# Close code that are allowed in a close frame.
|
| 77 |
+
# Using a set optimizes `code in EXTERNAL_CLOSE_CODES`.
|
| 78 |
+
EXTERNAL_CLOSE_CODES = {
|
| 79 |
+
1000,
|
| 80 |
+
1001,
|
| 81 |
+
1002,
|
| 82 |
+
1003,
|
| 83 |
+
1007,
|
| 84 |
+
1008,
|
| 85 |
+
1009,
|
| 86 |
+
1010,
|
| 87 |
+
1011,
|
| 88 |
+
1012,
|
| 89 |
+
1013,
|
| 90 |
+
1014,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
OK_CLOSE_CODES = {
|
| 94 |
+
1000,
|
| 95 |
+
1001,
|
| 96 |
+
1005,
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
BytesLike = bytes, bytearray, memoryview
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclasses.dataclass
|
| 104 |
+
class Frame:
|
| 105 |
+
"""
|
| 106 |
+
WebSocket frame.
|
| 107 |
+
|
| 108 |
+
Attributes:
|
| 109 |
+
opcode: Opcode.
|
| 110 |
+
data: Payload data.
|
| 111 |
+
fin: FIN bit.
|
| 112 |
+
rsv1: RSV1 bit.
|
| 113 |
+
rsv2: RSV2 bit.
|
| 114 |
+
rsv3: RSV3 bit.
|
| 115 |
+
|
| 116 |
+
Only these fields are needed. The MASK bit, payload length and masking-key
|
| 117 |
+
are handled on the fly when parsing and serializing frames.
|
| 118 |
+
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
opcode: Opcode
|
| 122 |
+
data: bytes
|
| 123 |
+
fin: bool = True
|
| 124 |
+
rsv1: bool = False
|
| 125 |
+
rsv2: bool = False
|
| 126 |
+
rsv3: bool = False
|
| 127 |
+
|
| 128 |
+
def __str__(self) -> str:
|
| 129 |
+
"""
|
| 130 |
+
Return a human-readable representation of a frame.
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
coding = None
|
| 134 |
+
length = f"{len(self.data)} byte{'' if len(self.data) == 1 else 's'}"
|
| 135 |
+
non_final = "" if self.fin else "continued"
|
| 136 |
+
|
| 137 |
+
if self.opcode is OP_TEXT:
|
| 138 |
+
# Decoding only the beginning and the end is needlessly hard.
|
| 139 |
+
# Decode the entire payload then elide later if necessary.
|
| 140 |
+
data = repr(self.data.decode())
|
| 141 |
+
elif self.opcode is OP_BINARY:
|
| 142 |
+
# We'll show at most the first 16 bytes and the last 8 bytes.
|
| 143 |
+
# Encode just what we need, plus two dummy bytes to elide later.
|
| 144 |
+
binary = self.data
|
| 145 |
+
if len(binary) > 25:
|
| 146 |
+
binary = b"".join([binary[:16], b"\x00\x00", binary[-8:]])
|
| 147 |
+
data = " ".join(f"{byte:02x}" for byte in binary)
|
| 148 |
+
elif self.opcode is OP_CLOSE:
|
| 149 |
+
data = str(Close.parse(self.data))
|
| 150 |
+
elif self.data:
|
| 151 |
+
# We don't know if a Continuation frame contains text or binary.
|
| 152 |
+
# Ping and Pong frames could contain UTF-8.
|
| 153 |
+
# Attempt to decode as UTF-8 and display it as text; fallback to
|
| 154 |
+
# binary. If self.data is a memoryview, it has no decode() method,
|
| 155 |
+
# which raises AttributeError.
|
| 156 |
+
try:
|
| 157 |
+
data = repr(self.data.decode())
|
| 158 |
+
coding = "text"
|
| 159 |
+
except (UnicodeDecodeError, AttributeError):
|
| 160 |
+
binary = self.data
|
| 161 |
+
if len(binary) > 25:
|
| 162 |
+
binary = b"".join([binary[:16], b"\x00\x00", binary[-8:]])
|
| 163 |
+
data = " ".join(f"{byte:02x}" for byte in binary)
|
| 164 |
+
coding = "binary"
|
| 165 |
+
else:
|
| 166 |
+
data = "''"
|
| 167 |
+
|
| 168 |
+
if len(data) > 75:
|
| 169 |
+
data = data[:48] + "..." + data[-24:]
|
| 170 |
+
|
| 171 |
+
metadata = ", ".join(filter(None, [coding, length, non_final]))
|
| 172 |
+
|
| 173 |
+
return f"{self.opcode.name} {data} [{metadata}]"
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def parse(
|
| 177 |
+
cls,
|
| 178 |
+
read_exact: Callable[[int], Generator[None, None, bytes]],
|
| 179 |
+
*,
|
| 180 |
+
mask: bool,
|
| 181 |
+
max_size: Optional[int] = None,
|
| 182 |
+
extensions: Optional[Sequence[extensions.Extension]] = None,
|
| 183 |
+
) -> Generator[None, None, Frame]:
|
| 184 |
+
"""
|
| 185 |
+
Parse a WebSocket frame.
|
| 186 |
+
|
| 187 |
+
This is a generator-based coroutine.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
read_exact: generator-based coroutine that reads the requested
|
| 191 |
+
bytes or raises an exception if there isn't enough data.
|
| 192 |
+
mask: whether the frame should be masked i.e. whether the read
|
| 193 |
+
happens on the server side.
|
| 194 |
+
max_size: maximum payload size in bytes.
|
| 195 |
+
extensions: list of extensions, applied in reverse order.
|
| 196 |
+
|
| 197 |
+
Raises:
|
| 198 |
+
EOFError: if the connection is closed without a full WebSocket frame.
|
| 199 |
+
UnicodeDecodeError: if the frame contains invalid UTF-8.
|
| 200 |
+
PayloadTooBig: if the frame's payload size exceeds ``max_size``.
|
| 201 |
+
ProtocolError: if the frame contains incorrect values.
|
| 202 |
+
|
| 203 |
+
"""
|
| 204 |
+
# Read the header.
|
| 205 |
+
data = yield from read_exact(2)
|
| 206 |
+
head1, head2 = struct.unpack("!BB", data)
|
| 207 |
+
|
| 208 |
+
# While not Pythonic, this is marginally faster than calling bool().
|
| 209 |
+
fin = True if head1 & 0b10000000 else False
|
| 210 |
+
rsv1 = True if head1 & 0b01000000 else False
|
| 211 |
+
rsv2 = True if head1 & 0b00100000 else False
|
| 212 |
+
rsv3 = True if head1 & 0b00010000 else False
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
opcode = Opcode(head1 & 0b00001111)
|
| 216 |
+
except ValueError as exc:
|
| 217 |
+
raise exceptions.ProtocolError("invalid opcode") from exc
|
| 218 |
+
|
| 219 |
+
if (True if head2 & 0b10000000 else False) != mask:
|
| 220 |
+
raise exceptions.ProtocolError("incorrect masking")
|
| 221 |
+
|
| 222 |
+
length = head2 & 0b01111111
|
| 223 |
+
if length == 126:
|
| 224 |
+
data = yield from read_exact(2)
|
| 225 |
+
(length,) = struct.unpack("!H", data)
|
| 226 |
+
elif length == 127:
|
| 227 |
+
data = yield from read_exact(8)
|
| 228 |
+
(length,) = struct.unpack("!Q", data)
|
| 229 |
+
if max_size is not None and length > max_size:
|
| 230 |
+
raise exceptions.PayloadTooBig(
|
| 231 |
+
f"over size limit ({length} > {max_size} bytes)"
|
| 232 |
+
)
|
| 233 |
+
if mask:
|
| 234 |
+
mask_bytes = yield from read_exact(4)
|
| 235 |
+
|
| 236 |
+
# Read the data.
|
| 237 |
+
data = yield from read_exact(length)
|
| 238 |
+
if mask:
|
| 239 |
+
data = apply_mask(data, mask_bytes)
|
| 240 |
+
|
| 241 |
+
frame = cls(opcode, data, fin, rsv1, rsv2, rsv3)
|
| 242 |
+
|
| 243 |
+
if extensions is None:
|
| 244 |
+
extensions = []
|
| 245 |
+
for extension in reversed(extensions):
|
| 246 |
+
frame = extension.decode(frame, max_size=max_size)
|
| 247 |
+
|
| 248 |
+
frame.check()
|
| 249 |
+
|
| 250 |
+
return frame
|
| 251 |
+
|
| 252 |
+
def serialize(
|
| 253 |
+
self,
|
| 254 |
+
*,
|
| 255 |
+
mask: bool,
|
| 256 |
+
extensions: Optional[Sequence[extensions.Extension]] = None,
|
| 257 |
+
) -> bytes:
|
| 258 |
+
"""
|
| 259 |
+
Serialize a WebSocket frame.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
mask: whether the frame should be masked i.e. whether the write
|
| 263 |
+
happens on the client side.
|
| 264 |
+
extensions: list of extensions, applied in order.
|
| 265 |
+
|
| 266 |
+
Raises:
|
| 267 |
+
ProtocolError: if the frame contains incorrect values.
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
self.check()
|
| 271 |
+
|
| 272 |
+
if extensions is None:
|
| 273 |
+
extensions = []
|
| 274 |
+
for extension in extensions:
|
| 275 |
+
self = extension.encode(self)
|
| 276 |
+
|
| 277 |
+
output = io.BytesIO()
|
| 278 |
+
|
| 279 |
+
# Prepare the header.
|
| 280 |
+
head1 = (
|
| 281 |
+
(0b10000000 if self.fin else 0)
|
| 282 |
+
| (0b01000000 if self.rsv1 else 0)
|
| 283 |
+
| (0b00100000 if self.rsv2 else 0)
|
| 284 |
+
| (0b00010000 if self.rsv3 else 0)
|
| 285 |
+
| self.opcode
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
head2 = 0b10000000 if mask else 0
|
| 289 |
+
|
| 290 |
+
length = len(self.data)
|
| 291 |
+
if length < 126:
|
| 292 |
+
output.write(struct.pack("!BB", head1, head2 | length))
|
| 293 |
+
elif length < 65536:
|
| 294 |
+
output.write(struct.pack("!BBH", head1, head2 | 126, length))
|
| 295 |
+
else:
|
| 296 |
+
output.write(struct.pack("!BBQ", head1, head2 | 127, length))
|
| 297 |
+
|
| 298 |
+
if mask:
|
| 299 |
+
mask_bytes = secrets.token_bytes(4)
|
| 300 |
+
output.write(mask_bytes)
|
| 301 |
+
|
| 302 |
+
# Prepare the data.
|
| 303 |
+
if mask:
|
| 304 |
+
data = apply_mask(self.data, mask_bytes)
|
| 305 |
+
else:
|
| 306 |
+
data = self.data
|
| 307 |
+
output.write(data)
|
| 308 |
+
|
| 309 |
+
return output.getvalue()
|
| 310 |
+
|
| 311 |
+
def check(self) -> None:
|
| 312 |
+
"""
|
| 313 |
+
Check that reserved bits and opcode have acceptable values.
|
| 314 |
+
|
| 315 |
+
Raises:
|
| 316 |
+
ProtocolError: if a reserved bit or the opcode is invalid.
|
| 317 |
+
|
| 318 |
+
"""
|
| 319 |
+
if self.rsv1 or self.rsv2 or self.rsv3:
|
| 320 |
+
raise exceptions.ProtocolError("reserved bits must be 0")
|
| 321 |
+
|
| 322 |
+
if self.opcode in CTRL_OPCODES:
|
| 323 |
+
if len(self.data) > 125:
|
| 324 |
+
raise exceptions.ProtocolError("control frame too long")
|
| 325 |
+
if not self.fin:
|
| 326 |
+
raise exceptions.ProtocolError("fragmented control frame")
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def prepare_data(data: Data) -> Tuple[int, bytes]:
|
| 330 |
+
"""
|
| 331 |
+
Convert a string or byte-like object to an opcode and a bytes-like object.
|
| 332 |
+
|
| 333 |
+
This function is designed for data frames.
|
| 334 |
+
|
| 335 |
+
If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes`
|
| 336 |
+
object encoding ``data`` in UTF-8.
|
| 337 |
+
|
| 338 |
+
If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like
|
| 339 |
+
object.
|
| 340 |
+
|
| 341 |
+
Raises:
|
| 342 |
+
TypeError: if ``data`` doesn't have a supported type.
|
| 343 |
+
|
| 344 |
+
"""
|
| 345 |
+
if isinstance(data, str):
|
| 346 |
+
return OP_TEXT, data.encode("utf-8")
|
| 347 |
+
elif isinstance(data, BytesLike):
|
| 348 |
+
return OP_BINARY, data
|
| 349 |
+
else:
|
| 350 |
+
raise TypeError("data must be str or bytes-like")
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def prepare_ctrl(data: Data) -> bytes:
|
| 354 |
+
"""
|
| 355 |
+
Convert a string or byte-like object to bytes.
|
| 356 |
+
|
| 357 |
+
This function is designed for ping and pong frames.
|
| 358 |
+
|
| 359 |
+
If ``data`` is a :class:`str`, return a :class:`bytes` object encoding
|
| 360 |
+
``data`` in UTF-8.
|
| 361 |
+
|
| 362 |
+
If ``data`` is a bytes-like object, return a :class:`bytes` object.
|
| 363 |
+
|
| 364 |
+
Raises:
|
| 365 |
+
TypeError: if ``data`` doesn't have a supported type.
|
| 366 |
+
|
| 367 |
+
"""
|
| 368 |
+
if isinstance(data, str):
|
| 369 |
+
return data.encode("utf-8")
|
| 370 |
+
elif isinstance(data, BytesLike):
|
| 371 |
+
return bytes(data)
|
| 372 |
+
else:
|
| 373 |
+
raise TypeError("data must be str or bytes-like")
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@dataclasses.dataclass
|
| 377 |
+
class Close:
|
| 378 |
+
"""
|
| 379 |
+
Code and reason for WebSocket close frames.
|
| 380 |
+
|
| 381 |
+
Attributes:
|
| 382 |
+
code: Close code.
|
| 383 |
+
reason: Close reason.
|
| 384 |
+
|
| 385 |
+
"""
|
| 386 |
+
|
| 387 |
+
code: int
|
| 388 |
+
reason: str
|
| 389 |
+
|
| 390 |
+
def __str__(self) -> str:
|
| 391 |
+
"""
|
| 392 |
+
Return a human-readable representation of a close code and reason.
|
| 393 |
+
|
| 394 |
+
"""
|
| 395 |
+
if 3000 <= self.code < 4000:
|
| 396 |
+
explanation = "registered"
|
| 397 |
+
elif 4000 <= self.code < 5000:
|
| 398 |
+
explanation = "private use"
|
| 399 |
+
else:
|
| 400 |
+
explanation = CLOSE_CODES.get(self.code, "unknown")
|
| 401 |
+
result = f"{self.code} ({explanation})"
|
| 402 |
+
|
| 403 |
+
if self.reason:
|
| 404 |
+
result = f"{result} {self.reason}"
|
| 405 |
+
|
| 406 |
+
return result
|
| 407 |
+
|
| 408 |
+
@classmethod
|
| 409 |
+
def parse(cls, data: bytes) -> Close:
|
| 410 |
+
"""
|
| 411 |
+
Parse the payload of a close frame.
|
| 412 |
+
|
| 413 |
+
Args:
|
| 414 |
+
data: payload of the close frame.
|
| 415 |
+
|
| 416 |
+
Raises:
|
| 417 |
+
ProtocolError: if data is ill-formed.
|
| 418 |
+
UnicodeDecodeError: if the reason isn't valid UTF-8.
|
| 419 |
+
|
| 420 |
+
"""
|
| 421 |
+
if len(data) >= 2:
|
| 422 |
+
(code,) = struct.unpack("!H", data[:2])
|
| 423 |
+
reason = data[2:].decode("utf-8")
|
| 424 |
+
close = cls(code, reason)
|
| 425 |
+
close.check()
|
| 426 |
+
return close
|
| 427 |
+
elif len(data) == 0:
|
| 428 |
+
return cls(1005, "")
|
| 429 |
+
else:
|
| 430 |
+
raise exceptions.ProtocolError("close frame too short")
|
| 431 |
+
|
| 432 |
+
def serialize(self) -> bytes:
|
| 433 |
+
"""
|
| 434 |
+
Serialize the payload of a close frame.
|
| 435 |
+
|
| 436 |
+
"""
|
| 437 |
+
self.check()
|
| 438 |
+
return struct.pack("!H", self.code) + self.reason.encode("utf-8")
|
| 439 |
+
|
| 440 |
+
def check(self) -> None:
|
| 441 |
+
"""
|
| 442 |
+
Check that the close code has a valid value for a close frame.
|
| 443 |
+
|
| 444 |
+
Raises:
|
| 445 |
+
ProtocolError: if the close code is invalid.
|
| 446 |
+
|
| 447 |
+
"""
|
| 448 |
+
if not (self.code in EXTERNAL_CLOSE_CODES or 3000 <= self.code < 5000):
|
| 449 |
+
raise exceptions.ProtocolError("invalid status code")
|
videollama2/lib/python3.10/site-packages/websockets/http.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from .imports import lazy_import
|
| 6 |
+
from .version import version as websockets_version
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# For backwards compatibility:
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
lazy_import(
|
| 13 |
+
globals(),
|
| 14 |
+
# Headers and MultipleValuesError used to be defined in this module.
|
| 15 |
+
aliases={
|
| 16 |
+
"Headers": ".datastructures",
|
| 17 |
+
"MultipleValuesError": ".datastructures",
|
| 18 |
+
},
|
| 19 |
+
deprecated_aliases={
|
| 20 |
+
"read_request": ".legacy.http",
|
| 21 |
+
"read_response": ".legacy.http",
|
| 22 |
+
},
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
__all__ = ["USER_AGENT"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
PYTHON_VERSION = "{}.{}".format(*sys.version_info)
|
| 30 |
+
USER_AGENT = f"Python/{PYTHON_VERSION} websockets/{websockets_version}"
|
videollama2/lib/python3.10/site-packages/websockets/http11.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import dataclasses
|
| 4 |
+
import re
|
| 5 |
+
import warnings
|
| 6 |
+
from typing import Callable, Generator, Optional
|
| 7 |
+
|
| 8 |
+
from . import datastructures, exceptions
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Maximum total size of headers is around 128 * 8 KiB = 1 MiB.
|
| 12 |
+
MAX_HEADERS = 128
|
| 13 |
+
|
| 14 |
+
# Limit request line and header lines. 8KiB is the most common default
|
| 15 |
+
# configuration of popular HTTP servers.
|
| 16 |
+
MAX_LINE = 8192
|
| 17 |
+
|
| 18 |
+
# Support for HTTP response bodies is intended to read an error message
|
| 19 |
+
# returned by a server. It isn't designed to perform large file transfers.
|
| 20 |
+
MAX_BODY = 2**20 # 1 MiB
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def d(value: bytes) -> str:
|
| 24 |
+
"""
|
| 25 |
+
Decode a bytestring for interpolating into an error message.
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
return value.decode(errors="backslashreplace")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# See https://www.rfc-editor.org/rfc/rfc7230.html#appendix-B.
|
| 32 |
+
|
| 33 |
+
# Regex for validating header names.
|
| 34 |
+
|
| 35 |
+
_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+")
|
| 36 |
+
|
| 37 |
+
# Regex for validating header values.
|
| 38 |
+
|
| 39 |
+
# We don't attempt to support obsolete line folding.
|
| 40 |
+
|
| 41 |
+
# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff).
|
| 42 |
+
|
| 43 |
+
# The ABNF is complicated because it attempts to express that optional
|
| 44 |
+
# whitespace is ignored. We strip whitespace and don't revalidate that.
|
| 45 |
+
|
| 46 |
+
# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189
|
| 47 |
+
|
| 48 |
+
_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclasses.dataclass
|
| 52 |
+
class Request:
|
| 53 |
+
"""
|
| 54 |
+
WebSocket handshake request.
|
| 55 |
+
|
| 56 |
+
Attributes:
|
| 57 |
+
path: Request path, including optional query.
|
| 58 |
+
headers: Request headers.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
path: str
|
| 62 |
+
headers: datastructures.Headers
|
| 63 |
+
# body isn't useful is the context of this library.
|
| 64 |
+
|
| 65 |
+
_exception: Optional[Exception] = None
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def exception(self) -> Optional[Exception]: # pragma: no cover
|
| 69 |
+
warnings.warn(
|
| 70 |
+
"Request.exception is deprecated; "
|
| 71 |
+
"use ServerProtocol.handshake_exc instead",
|
| 72 |
+
DeprecationWarning,
|
| 73 |
+
)
|
| 74 |
+
return self._exception
|
| 75 |
+
|
| 76 |
+
@classmethod
|
| 77 |
+
def parse(
|
| 78 |
+
cls,
|
| 79 |
+
read_line: Callable[[int], Generator[None, None, bytes]],
|
| 80 |
+
) -> Generator[None, None, Request]:
|
| 81 |
+
"""
|
| 82 |
+
Parse a WebSocket handshake request.
|
| 83 |
+
|
| 84 |
+
This is a generator-based coroutine.
|
| 85 |
+
|
| 86 |
+
The request path isn't URL-decoded or validated in any way.
|
| 87 |
+
|
| 88 |
+
The request path and headers are expected to contain only ASCII
|
| 89 |
+
characters. Other characters are represented with surrogate escapes.
|
| 90 |
+
|
| 91 |
+
:meth:`parse` doesn't attempt to read the request body because
|
| 92 |
+
WebSocket handshake requests don't have one. If the request contains a
|
| 93 |
+
body, it may be read from the data stream after :meth:`parse` returns.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
read_line: generator-based coroutine that reads a LF-terminated
|
| 97 |
+
line or raises an exception if there isn't enough data
|
| 98 |
+
|
| 99 |
+
Raises:
|
| 100 |
+
EOFError: if the connection is closed without a full HTTP request.
|
| 101 |
+
SecurityError: if the request exceeds a security limit.
|
| 102 |
+
ValueError: if the request isn't well formatted.
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
# https://www.rfc-editor.org/rfc/rfc7230.html#section-3.1.1
|
| 106 |
+
|
| 107 |
+
# Parsing is simple because fixed values are expected for method and
|
| 108 |
+
# version and because path isn't checked. Since WebSocket software tends
|
| 109 |
+
# to implement HTTP/1.1 strictly, there's little need for lenient parsing.
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
request_line = yield from parse_line(read_line)
|
| 113 |
+
except EOFError as exc:
|
| 114 |
+
raise EOFError("connection closed while reading HTTP request line") from exc
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
method, raw_path, version = request_line.split(b" ", 2)
|
| 118 |
+
except ValueError: # not enough values to unpack (expected 3, got 1-2)
|
| 119 |
+
raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None
|
| 120 |
+
|
| 121 |
+
if method != b"GET":
|
| 122 |
+
raise ValueError(f"unsupported HTTP method: {d(method)}")
|
| 123 |
+
if version != b"HTTP/1.1":
|
| 124 |
+
raise ValueError(f"unsupported HTTP version: {d(version)}")
|
| 125 |
+
path = raw_path.decode("ascii", "surrogateescape")
|
| 126 |
+
|
| 127 |
+
headers = yield from parse_headers(read_line)
|
| 128 |
+
|
| 129 |
+
# https://www.rfc-editor.org/rfc/rfc7230.html#section-3.3.3
|
| 130 |
+
|
| 131 |
+
if "Transfer-Encoding" in headers:
|
| 132 |
+
raise NotImplementedError("transfer codings aren't supported")
|
| 133 |
+
|
| 134 |
+
if "Content-Length" in headers:
|
| 135 |
+
raise ValueError("unsupported request body")
|
| 136 |
+
|
| 137 |
+
return cls(path, headers)
|
| 138 |
+
|
| 139 |
+
def serialize(self) -> bytes:
|
| 140 |
+
"""
|
| 141 |
+
Serialize a WebSocket handshake request.
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
# Since the request line and headers only contain ASCII characters,
|
| 145 |
+
# we can keep this simple.
|
| 146 |
+
request = f"GET {self.path} HTTP/1.1\r\n".encode()
|
| 147 |
+
request += self.headers.serialize()
|
| 148 |
+
return request
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dataclasses.dataclass
|
| 152 |
+
class Response:
|
| 153 |
+
"""
|
| 154 |
+
WebSocket handshake response.
|
| 155 |
+
|
| 156 |
+
Attributes:
|
| 157 |
+
status_code: Response code.
|
| 158 |
+
reason_phrase: Response reason.
|
| 159 |
+
headers: Response headers.
|
| 160 |
+
body: Response body, if any.
|
| 161 |
+
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
status_code: int
|
| 165 |
+
reason_phrase: str
|
| 166 |
+
headers: datastructures.Headers
|
| 167 |
+
body: Optional[bytes] = None
|
| 168 |
+
|
| 169 |
+
_exception: Optional[Exception] = None
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def exception(self) -> Optional[Exception]: # pragma: no cover
|
| 173 |
+
warnings.warn(
|
| 174 |
+
"Response.exception is deprecated; "
|
| 175 |
+
"use ClientProtocol.handshake_exc instead",
|
| 176 |
+
DeprecationWarning,
|
| 177 |
+
)
|
| 178 |
+
return self._exception
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def parse(
|
| 182 |
+
cls,
|
| 183 |
+
read_line: Callable[[int], Generator[None, None, bytes]],
|
| 184 |
+
read_exact: Callable[[int], Generator[None, None, bytes]],
|
| 185 |
+
read_to_eof: Callable[[int], Generator[None, None, bytes]],
|
| 186 |
+
) -> Generator[None, None, Response]:
|
| 187 |
+
"""
|
| 188 |
+
Parse a WebSocket handshake response.
|
| 189 |
+
|
| 190 |
+
This is a generator-based coroutine.
|
| 191 |
+
|
| 192 |
+
The reason phrase and headers are expected to contain only ASCII
|
| 193 |
+
characters. Other characters are represented with surrogate escapes.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
read_line: generator-based coroutine that reads a LF-terminated
|
| 197 |
+
line or raises an exception if there isn't enough data.
|
| 198 |
+
read_exact: generator-based coroutine that reads the requested
|
| 199 |
+
bytes or raises an exception if there isn't enough data.
|
| 200 |
+
read_to_eof: generator-based coroutine that reads until the end
|
| 201 |
+
of the stream.
|
| 202 |
+
|
| 203 |
+
Raises:
|
| 204 |
+
EOFError: if the connection is closed without a full HTTP response.
|
| 205 |
+
SecurityError: if the response exceeds a security limit.
|
| 206 |
+
LookupError: if the response isn't well formatted.
|
| 207 |
+
ValueError: if the response isn't well formatted.
|
| 208 |
+
|
| 209 |
+
"""
|
| 210 |
+
# https://www.rfc-editor.org/rfc/rfc7230.html#section-3.1.2
|
| 211 |
+
|
| 212 |
+
try:
|
| 213 |
+
status_line = yield from parse_line(read_line)
|
| 214 |
+
except EOFError as exc:
|
| 215 |
+
raise EOFError("connection closed while reading HTTP status line") from exc
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
version, raw_status_code, raw_reason = status_line.split(b" ", 2)
|
| 219 |
+
except ValueError: # not enough values to unpack (expected 3, got 1-2)
|
| 220 |
+
raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None
|
| 221 |
+
|
| 222 |
+
if version != b"HTTP/1.1":
|
| 223 |
+
raise ValueError(f"unsupported HTTP version: {d(version)}")
|
| 224 |
+
try:
|
| 225 |
+
status_code = int(raw_status_code)
|
| 226 |
+
except ValueError: # invalid literal for int() with base 10
|
| 227 |
+
raise ValueError(
|
| 228 |
+
f"invalid HTTP status code: {d(raw_status_code)}"
|
| 229 |
+
) from None
|
| 230 |
+
if not 100 <= status_code < 1000:
|
| 231 |
+
raise ValueError(f"unsupported HTTP status code: {d(raw_status_code)}")
|
| 232 |
+
if not _value_re.fullmatch(raw_reason):
|
| 233 |
+
raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}")
|
| 234 |
+
reason = raw_reason.decode()
|
| 235 |
+
|
| 236 |
+
headers = yield from parse_headers(read_line)
|
| 237 |
+
|
| 238 |
+
# https://www.rfc-editor.org/rfc/rfc7230.html#section-3.3.3
|
| 239 |
+
|
| 240 |
+
if "Transfer-Encoding" in headers:
|
| 241 |
+
raise NotImplementedError("transfer codings aren't supported")
|
| 242 |
+
|
| 243 |
+
# Since websockets only does GET requests (no HEAD, no CONNECT), all
|
| 244 |
+
# responses except 1xx, 204, and 304 include a message body.
|
| 245 |
+
if 100 <= status_code < 200 or status_code == 204 or status_code == 304:
|
| 246 |
+
body = None
|
| 247 |
+
else:
|
| 248 |
+
content_length: Optional[int]
|
| 249 |
+
try:
|
| 250 |
+
# MultipleValuesError is sufficiently unlikely that we don't
|
| 251 |
+
# attempt to handle it. Instead we document that its parent
|
| 252 |
+
# class, LookupError, may be raised.
|
| 253 |
+
raw_content_length = headers["Content-Length"]
|
| 254 |
+
except KeyError:
|
| 255 |
+
content_length = None
|
| 256 |
+
else:
|
| 257 |
+
content_length = int(raw_content_length)
|
| 258 |
+
|
| 259 |
+
if content_length is None:
|
| 260 |
+
try:
|
| 261 |
+
body = yield from read_to_eof(MAX_BODY)
|
| 262 |
+
except RuntimeError:
|
| 263 |
+
raise exceptions.SecurityError(
|
| 264 |
+
f"body too large: over {MAX_BODY} bytes"
|
| 265 |
+
)
|
| 266 |
+
elif content_length > MAX_BODY:
|
| 267 |
+
raise exceptions.SecurityError(
|
| 268 |
+
f"body too large: {content_length} bytes"
|
| 269 |
+
)
|
| 270 |
+
else:
|
| 271 |
+
body = yield from read_exact(content_length)
|
| 272 |
+
|
| 273 |
+
return cls(status_code, reason, headers, body)
|
| 274 |
+
|
| 275 |
+
def serialize(self) -> bytes:
|
| 276 |
+
"""
|
| 277 |
+
Serialize a WebSocket handshake response.
|
| 278 |
+
|
| 279 |
+
"""
|
| 280 |
+
# Since the status line and headers only contain ASCII characters,
|
| 281 |
+
# we can keep this simple.
|
| 282 |
+
response = f"HTTP/1.1 {self.status_code} {self.reason_phrase}\r\n".encode()
|
| 283 |
+
response += self.headers.serialize()
|
| 284 |
+
if self.body is not None:
|
| 285 |
+
response += self.body
|
| 286 |
+
return response
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def parse_headers(
|
| 290 |
+
read_line: Callable[[int], Generator[None, None, bytes]],
|
| 291 |
+
) -> Generator[None, None, datastructures.Headers]:
|
| 292 |
+
"""
|
| 293 |
+
Parse HTTP headers.
|
| 294 |
+
|
| 295 |
+
Non-ASCII characters are represented with surrogate escapes.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
read_line: generator-based coroutine that reads a LF-terminated line
|
| 299 |
+
or raises an exception if there isn't enough data.
|
| 300 |
+
|
| 301 |
+
Raises:
|
| 302 |
+
EOFError: if the connection is closed without complete headers.
|
| 303 |
+
SecurityError: if the request exceeds a security limit.
|
| 304 |
+
ValueError: if the request isn't well formatted.
|
| 305 |
+
|
| 306 |
+
"""
|
| 307 |
+
# https://www.rfc-editor.org/rfc/rfc7230.html#section-3.2
|
| 308 |
+
|
| 309 |
+
# We don't attempt to support obsolete line folding.
|
| 310 |
+
|
| 311 |
+
headers = datastructures.Headers()
|
| 312 |
+
for _ in range(MAX_HEADERS + 1):
|
| 313 |
+
try:
|
| 314 |
+
line = yield from parse_line(read_line)
|
| 315 |
+
except EOFError as exc:
|
| 316 |
+
raise EOFError("connection closed while reading HTTP headers") from exc
|
| 317 |
+
if line == b"":
|
| 318 |
+
break
|
| 319 |
+
|
| 320 |
+
try:
|
| 321 |
+
raw_name, raw_value = line.split(b":", 1)
|
| 322 |
+
except ValueError: # not enough values to unpack (expected 2, got 1)
|
| 323 |
+
raise ValueError(f"invalid HTTP header line: {d(line)}") from None
|
| 324 |
+
if not _token_re.fullmatch(raw_name):
|
| 325 |
+
raise ValueError(f"invalid HTTP header name: {d(raw_name)}")
|
| 326 |
+
raw_value = raw_value.strip(b" \t")
|
| 327 |
+
if not _value_re.fullmatch(raw_value):
|
| 328 |
+
raise ValueError(f"invalid HTTP header value: {d(raw_value)}")
|
| 329 |
+
|
| 330 |
+
name = raw_name.decode("ascii") # guaranteed to be ASCII at this point
|
| 331 |
+
value = raw_value.decode("ascii", "surrogateescape")
|
| 332 |
+
headers[name] = value
|
| 333 |
+
|
| 334 |
+
else:
|
| 335 |
+
raise exceptions.SecurityError("too many HTTP headers")
|
| 336 |
+
|
| 337 |
+
return headers
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def parse_line(
|
| 341 |
+
read_line: Callable[[int], Generator[None, None, bytes]],
|
| 342 |
+
) -> Generator[None, None, bytes]:
|
| 343 |
+
"""
|
| 344 |
+
Parse a single line.
|
| 345 |
+
|
| 346 |
+
CRLF is stripped from the return value.
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
read_line: generator-based coroutine that reads a LF-terminated line
|
| 350 |
+
or raises an exception if there isn't enough data.
|
| 351 |
+
|
| 352 |
+
Raises:
|
| 353 |
+
EOFError: if the connection is closed without a CRLF.
|
| 354 |
+
SecurityError: if the response exceeds a security limit.
|
| 355 |
+
|
| 356 |
+
"""
|
| 357 |
+
try:
|
| 358 |
+
line = yield from read_line(MAX_LINE)
|
| 359 |
+
except RuntimeError:
|
| 360 |
+
raise exceptions.SecurityError("line too long")
|
| 361 |
+
# Not mandatory but safe - https://www.rfc-editor.org/rfc/rfc7230.html#section-3.5
|
| 362 |
+
if not line.endswith(b"\r\n"):
|
| 363 |
+
raise EOFError("line without CRLF")
|
| 364 |
+
return line[:-2]
|
videollama2/lib/python3.10/site-packages/websockets/imports.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Any, Dict, Iterable, Optional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["lazy_import"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def import_name(name: str, source: str, namespace: Dict[str, Any]) -> Any:
|
| 11 |
+
"""
|
| 12 |
+
Import ``name`` from ``source`` in ``namespace``.
|
| 13 |
+
|
| 14 |
+
There are two use cases:
|
| 15 |
+
|
| 16 |
+
- ``name`` is an object defined in ``source``;
|
| 17 |
+
- ``name`` is a submodule of ``source``.
|
| 18 |
+
|
| 19 |
+
Neither :func:`__import__` nor :func:`~importlib.import_module` does
|
| 20 |
+
exactly this. :func:`__import__` is closer to the intended behavior.
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
level = 0
|
| 24 |
+
while source[level] == ".":
|
| 25 |
+
level += 1
|
| 26 |
+
assert level < len(source), "importing from parent isn't supported"
|
| 27 |
+
module = __import__(source[level:], namespace, None, [name], level)
|
| 28 |
+
return getattr(module, name)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def lazy_import(
|
| 32 |
+
namespace: Dict[str, Any],
|
| 33 |
+
aliases: Optional[Dict[str, str]] = None,
|
| 34 |
+
deprecated_aliases: Optional[Dict[str, str]] = None,
|
| 35 |
+
) -> None:
|
| 36 |
+
"""
|
| 37 |
+
Provide lazy, module-level imports.
|
| 38 |
+
|
| 39 |
+
Typical use::
|
| 40 |
+
|
| 41 |
+
__getattr__, __dir__ = lazy_import(
|
| 42 |
+
globals(),
|
| 43 |
+
aliases={
|
| 44 |
+
"<name>": "<source module>",
|
| 45 |
+
...
|
| 46 |
+
},
|
| 47 |
+
deprecated_aliases={
|
| 48 |
+
...,
|
| 49 |
+
}
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
This function defines ``__getattr__`` and ``__dir__`` per :pep:`562`.
|
| 53 |
+
|
| 54 |
+
"""
|
| 55 |
+
if aliases is None:
|
| 56 |
+
aliases = {}
|
| 57 |
+
if deprecated_aliases is None:
|
| 58 |
+
deprecated_aliases = {}
|
| 59 |
+
|
| 60 |
+
namespace_set = set(namespace)
|
| 61 |
+
aliases_set = set(aliases)
|
| 62 |
+
deprecated_aliases_set = set(deprecated_aliases)
|
| 63 |
+
|
| 64 |
+
assert not namespace_set & aliases_set, "namespace conflict"
|
| 65 |
+
assert not namespace_set & deprecated_aliases_set, "namespace conflict"
|
| 66 |
+
assert not aliases_set & deprecated_aliases_set, "namespace conflict"
|
| 67 |
+
|
| 68 |
+
package = namespace["__name__"]
|
| 69 |
+
|
| 70 |
+
def __getattr__(name: str) -> Any:
|
| 71 |
+
assert aliases is not None # mypy cannot figure this out
|
| 72 |
+
try:
|
| 73 |
+
source = aliases[name]
|
| 74 |
+
except KeyError:
|
| 75 |
+
pass
|
| 76 |
+
else:
|
| 77 |
+
return import_name(name, source, namespace)
|
| 78 |
+
|
| 79 |
+
assert deprecated_aliases is not None # mypy cannot figure this out
|
| 80 |
+
try:
|
| 81 |
+
source = deprecated_aliases[name]
|
| 82 |
+
except KeyError:
|
| 83 |
+
pass
|
| 84 |
+
else:
|
| 85 |
+
warnings.warn(
|
| 86 |
+
f"{package}.{name} is deprecated",
|
| 87 |
+
DeprecationWarning,
|
| 88 |
+
stacklevel=2,
|
| 89 |
+
)
|
| 90 |
+
return import_name(name, source, namespace)
|
| 91 |
+
|
| 92 |
+
raise AttributeError(f"module {package!r} has no attribute {name!r}")
|
| 93 |
+
|
| 94 |
+
namespace["__getattr__"] = __getattr__
|
| 95 |
+
|
| 96 |
+
def __dir__() -> Iterable[str]:
|
| 97 |
+
return sorted(namespace_set | aliases_set | deprecated_aliases_set)
|
| 98 |
+
|
| 99 |
+
namespace["__dir__"] = __dir__
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__init__.py
ADDED
|
File without changes
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (174 Bytes). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/async_timeout.cpython-310.pyc
ADDED
|
Binary file (7.13 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/auth.cpython-310.pyc
ADDED
|
Binary file (5.91 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/client.cpython-310.pyc
ADDED
|
Binary file (19.7 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/compatibility.cpython-310.pyc
ADDED
|
Binary file (878 Bytes). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/framing.cpython-310.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/handshake.cpython-310.pyc
ADDED
|
Binary file (4.9 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/http.cpython-310.pyc
ADDED
|
Binary file (5.09 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/__pycache__/server.cpython-310.pyc
ADDED
|
Binary file (34.7 kB). View file
|
|
|
videollama2/lib/python3.10/site-packages/websockets/legacy/async_timeout.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# From https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py
|
| 2 |
+
# Licensed under the Apache License (Apache-2.0)
|
| 3 |
+
|
| 4 |
+
import asyncio
|
| 5 |
+
import enum
|
| 6 |
+
import sys
|
| 7 |
+
import warnings
|
| 8 |
+
from types import TracebackType
|
| 9 |
+
from typing import Optional, Type
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# From https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py
|
| 13 |
+
# Licensed under the Python Software Foundation License (PSF-2.0)
|
| 14 |
+
|
| 15 |
+
if sys.version_info >= (3, 11):
|
| 16 |
+
from typing import final
|
| 17 |
+
else:
|
| 18 |
+
# @final exists in 3.8+, but we backport it for all versions
|
| 19 |
+
# before 3.11 to keep support for the __final__ attribute.
|
| 20 |
+
# See https://bugs.python.org/issue46342
|
| 21 |
+
def final(f):
|
| 22 |
+
"""This decorator can be used to indicate to type checkers that
|
| 23 |
+
the decorated method cannot be overridden, and decorated class
|
| 24 |
+
cannot be subclassed. For example:
|
| 25 |
+
|
| 26 |
+
class Base:
|
| 27 |
+
@final
|
| 28 |
+
def done(self) -> None:
|
| 29 |
+
...
|
| 30 |
+
class Sub(Base):
|
| 31 |
+
def done(self) -> None: # Error reported by type checker
|
| 32 |
+
...
|
| 33 |
+
@final
|
| 34 |
+
class Leaf:
|
| 35 |
+
...
|
| 36 |
+
class Other(Leaf): # Error reported by type checker
|
| 37 |
+
...
|
| 38 |
+
|
| 39 |
+
There is no runtime checking of these properties. The decorator
|
| 40 |
+
sets the ``__final__`` attribute to ``True`` on the decorated object
|
| 41 |
+
to allow runtime introspection.
|
| 42 |
+
"""
|
| 43 |
+
try:
|
| 44 |
+
f.__final__ = True
|
| 45 |
+
except (AttributeError, TypeError):
|
| 46 |
+
# Skip the attribute silently if it is not writable.
|
| 47 |
+
# AttributeError happens if the object has __slots__ or a
|
| 48 |
+
# read-only property, TypeError if it's a builtin class.
|
| 49 |
+
pass
|
| 50 |
+
return f
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# End https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py
|
| 54 |
+
|
| 55 |
+
__version__ = "4.0.2"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
__all__ = ("timeout", "timeout_at", "Timeout")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def timeout(delay: Optional[float]) -> "Timeout":
|
| 62 |
+
"""timeout context manager.
|
| 63 |
+
|
| 64 |
+
Useful in cases when you want to apply timeout logic around block
|
| 65 |
+
of code or in cases when asyncio.wait_for is not suitable. For example:
|
| 66 |
+
|
| 67 |
+
>>> async with timeout(0.001):
|
| 68 |
+
... async with aiohttp.get('https://github.com') as r:
|
| 69 |
+
... await r.text()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
delay - value in seconds or None to disable timeout logic
|
| 73 |
+
"""
|
| 74 |
+
loop = asyncio.get_running_loop()
|
| 75 |
+
if delay is not None:
|
| 76 |
+
deadline = loop.time() + delay # type: Optional[float]
|
| 77 |
+
else:
|
| 78 |
+
deadline = None
|
| 79 |
+
return Timeout(deadline, loop)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def timeout_at(deadline: Optional[float]) -> "Timeout":
|
| 83 |
+
"""Schedule the timeout at absolute time.
|
| 84 |
+
|
| 85 |
+
deadline argument points on the time in the same clock system
|
| 86 |
+
as loop.time().
|
| 87 |
+
|
| 88 |
+
Please note: it is not POSIX time but a time with
|
| 89 |
+
undefined starting base, e.g. the time of the system power on.
|
| 90 |
+
|
| 91 |
+
>>> async with timeout_at(loop.time() + 10):
|
| 92 |
+
... async with aiohttp.get('https://github.com') as r:
|
| 93 |
+
... await r.text()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
"""
|
| 97 |
+
loop = asyncio.get_running_loop()
|
| 98 |
+
return Timeout(deadline, loop)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class _State(enum.Enum):
|
| 102 |
+
INIT = "INIT"
|
| 103 |
+
ENTER = "ENTER"
|
| 104 |
+
TIMEOUT = "TIMEOUT"
|
| 105 |
+
EXIT = "EXIT"
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@final
|
| 109 |
+
class Timeout:
|
| 110 |
+
# Internal class, please don't instantiate it directly
|
| 111 |
+
# Use timeout() and timeout_at() public factories instead.
|
| 112 |
+
#
|
| 113 |
+
# Implementation note: `async with timeout()` is preferred
|
| 114 |
+
# over `with timeout()`.
|
| 115 |
+
# While technically the Timeout class implementation
|
| 116 |
+
# doesn't need to be async at all,
|
| 117 |
+
# the `async with` statement explicitly points that
|
| 118 |
+
# the context manager should be used from async function context.
|
| 119 |
+
#
|
| 120 |
+
# This design allows to avoid many silly misusages.
|
| 121 |
+
#
|
| 122 |
+
# TimeoutError is raised immediately when scheduled
|
| 123 |
+
# if the deadline is passed.
|
| 124 |
+
# The purpose is to time out as soon as possible
|
| 125 |
+
# without waiting for the next await expression.
|
| 126 |
+
|
| 127 |
+
__slots__ = ("_deadline", "_loop", "_state", "_timeout_handler")
|
| 128 |
+
|
| 129 |
+
def __init__(
|
| 130 |
+
self, deadline: Optional[float], loop: asyncio.AbstractEventLoop
|
| 131 |
+
) -> None:
|
| 132 |
+
self._loop = loop
|
| 133 |
+
self._state = _State.INIT
|
| 134 |
+
|
| 135 |
+
self._timeout_handler = None # type: Optional[asyncio.Handle]
|
| 136 |
+
if deadline is None:
|
| 137 |
+
self._deadline = None # type: Optional[float]
|
| 138 |
+
else:
|
| 139 |
+
self.update(deadline)
|
| 140 |
+
|
| 141 |
+
def __enter__(self) -> "Timeout":
|
| 142 |
+
warnings.warn(
|
| 143 |
+
"with timeout() is deprecated, use async with timeout() instead",
|
| 144 |
+
DeprecationWarning,
|
| 145 |
+
stacklevel=2,
|
| 146 |
+
)
|
| 147 |
+
self._do_enter()
|
| 148 |
+
return self
|
| 149 |
+
|
| 150 |
+
def __exit__(
|
| 151 |
+
self,
|
| 152 |
+
exc_type: Optional[Type[BaseException]],
|
| 153 |
+
exc_val: Optional[BaseException],
|
| 154 |
+
exc_tb: Optional[TracebackType],
|
| 155 |
+
) -> Optional[bool]:
|
| 156 |
+
self._do_exit(exc_type)
|
| 157 |
+
return None
|
| 158 |
+
|
| 159 |
+
async def __aenter__(self) -> "Timeout":
|
| 160 |
+
self._do_enter()
|
| 161 |
+
return self
|
| 162 |
+
|
| 163 |
+
async def __aexit__(
|
| 164 |
+
self,
|
| 165 |
+
exc_type: Optional[Type[BaseException]],
|
| 166 |
+
exc_val: Optional[BaseException],
|
| 167 |
+
exc_tb: Optional[TracebackType],
|
| 168 |
+
) -> Optional[bool]:
|
| 169 |
+
self._do_exit(exc_type)
|
| 170 |
+
return None
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def expired(self) -> bool:
|
| 174 |
+
"""Is timeout expired during execution?"""
|
| 175 |
+
return self._state == _State.TIMEOUT
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def deadline(self) -> Optional[float]:
|
| 179 |
+
return self._deadline
|
| 180 |
+
|
| 181 |
+
def reject(self) -> None:
|
| 182 |
+
"""Reject scheduled timeout if any."""
|
| 183 |
+
# cancel is maybe better name but
|
| 184 |
+
# task.cancel() raises CancelledError in asyncio world.
|
| 185 |
+
if self._state not in (_State.INIT, _State.ENTER):
|
| 186 |
+
raise RuntimeError(f"invalid state {self._state.value}")
|
| 187 |
+
self._reject()
|
| 188 |
+
|
| 189 |
+
def _reject(self) -> None:
|
| 190 |
+
if self._timeout_handler is not None:
|
| 191 |
+
self._timeout_handler.cancel()
|
| 192 |
+
self._timeout_handler = None
|
| 193 |
+
|
| 194 |
+
def shift(self, delay: float) -> None:
|
| 195 |
+
"""Advance timeout on delay seconds.
|
| 196 |
+
|
| 197 |
+
The delay can be negative.
|
| 198 |
+
|
| 199 |
+
Raise RuntimeError if shift is called when deadline is not scheduled
|
| 200 |
+
"""
|
| 201 |
+
deadline = self._deadline
|
| 202 |
+
if deadline is None:
|
| 203 |
+
raise RuntimeError("cannot shift timeout if deadline is not scheduled")
|
| 204 |
+
self.update(deadline + delay)
|
| 205 |
+
|
| 206 |
+
def update(self, deadline: float) -> None:
|
| 207 |
+
"""Set deadline to absolute value.
|
| 208 |
+
|
| 209 |
+
deadline argument points on the time in the same clock system
|
| 210 |
+
as loop.time().
|
| 211 |
+
|
| 212 |
+
If new deadline is in the past the timeout is raised immediately.
|
| 213 |
+
|
| 214 |
+
Please note: it is not POSIX time but a time with
|
| 215 |
+
undefined starting base, e.g. the time of the system power on.
|
| 216 |
+
"""
|
| 217 |
+
if self._state == _State.EXIT:
|
| 218 |
+
raise RuntimeError("cannot reschedule after exit from context manager")
|
| 219 |
+
if self._state == _State.TIMEOUT:
|
| 220 |
+
raise RuntimeError("cannot reschedule expired timeout")
|
| 221 |
+
if self._timeout_handler is not None:
|
| 222 |
+
self._timeout_handler.cancel()
|
| 223 |
+
self._deadline = deadline
|
| 224 |
+
if self._state != _State.INIT:
|
| 225 |
+
self._reschedule()
|
| 226 |
+
|
| 227 |
+
def _reschedule(self) -> None:
|
| 228 |
+
assert self._state == _State.ENTER
|
| 229 |
+
deadline = self._deadline
|
| 230 |
+
if deadline is None:
|
| 231 |
+
return
|
| 232 |
+
|
| 233 |
+
now = self._loop.time()
|
| 234 |
+
if self._timeout_handler is not None:
|
| 235 |
+
self._timeout_handler.cancel()
|
| 236 |
+
|
| 237 |
+
task = asyncio.current_task()
|
| 238 |
+
if deadline <= now:
|
| 239 |
+
self._timeout_handler = self._loop.call_soon(self._on_timeout, task)
|
| 240 |
+
else:
|
| 241 |
+
self._timeout_handler = self._loop.call_at(deadline, self._on_timeout, task)
|
| 242 |
+
|
| 243 |
+
def _do_enter(self) -> None:
|
| 244 |
+
if self._state != _State.INIT:
|
| 245 |
+
raise RuntimeError(f"invalid state {self._state.value}")
|
| 246 |
+
self._state = _State.ENTER
|
| 247 |
+
self._reschedule()
|
| 248 |
+
|
| 249 |
+
def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None:
|
| 250 |
+
if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT:
|
| 251 |
+
self._timeout_handler = None
|
| 252 |
+
raise asyncio.TimeoutError
|
| 253 |
+
# timeout has not expired
|
| 254 |
+
self._state = _State.EXIT
|
| 255 |
+
self._reject()
|
| 256 |
+
return None
|
| 257 |
+
|
| 258 |
+
def _on_timeout(self, task: "asyncio.Task[None]") -> None:
|
| 259 |
+
task.cancel()
|
| 260 |
+
self._state = _State.TIMEOUT
|
| 261 |
+
# drop the reference early
|
| 262 |
+
self._timeout_handler = None
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# End https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py
|
videollama2/lib/python3.10/site-packages/websockets/legacy/auth.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import hmac
|
| 5 |
+
import http
|
| 6 |
+
from typing import Any, Awaitable, Callable, Iterable, Optional, Tuple, Union, cast
|
| 7 |
+
|
| 8 |
+
from ..datastructures import Headers
|
| 9 |
+
from ..exceptions import InvalidHeader
|
| 10 |
+
from ..headers import build_www_authenticate_basic, parse_authorization_basic
|
| 11 |
+
from .server import HTTPResponse, WebSocketServerProtocol
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"]
|
| 15 |
+
|
| 16 |
+
Credentials = Tuple[str, str]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def is_credentials(value: Any) -> bool:
|
| 20 |
+
try:
|
| 21 |
+
username, password = value
|
| 22 |
+
except (TypeError, ValueError):
|
| 23 |
+
return False
|
| 24 |
+
else:
|
| 25 |
+
return isinstance(username, str) and isinstance(password, str)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol):
|
| 29 |
+
"""
|
| 30 |
+
WebSocket server protocol that enforces HTTP Basic Auth.
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
realm: str = ""
|
| 35 |
+
"""
|
| 36 |
+
Scope of protection.
|
| 37 |
+
|
| 38 |
+
If provided, it should contain only ASCII characters because the
|
| 39 |
+
encoding of non-ASCII characters is undefined.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
username: Optional[str] = None
|
| 43 |
+
"""Username of the authenticated user."""
|
| 44 |
+
|
| 45 |
+
def __init__(
|
| 46 |
+
self,
|
| 47 |
+
*args: Any,
|
| 48 |
+
realm: Optional[str] = None,
|
| 49 |
+
check_credentials: Optional[Callable[[str, str], Awaitable[bool]]] = None,
|
| 50 |
+
**kwargs: Any,
|
| 51 |
+
) -> None:
|
| 52 |
+
if realm is not None:
|
| 53 |
+
self.realm = realm # shadow class attribute
|
| 54 |
+
self._check_credentials = check_credentials
|
| 55 |
+
super().__init__(*args, **kwargs)
|
| 56 |
+
|
| 57 |
+
async def check_credentials(self, username: str, password: str) -> bool:
|
| 58 |
+
"""
|
| 59 |
+
Check whether credentials are authorized.
|
| 60 |
+
|
| 61 |
+
This coroutine may be overridden in a subclass, for example to
|
| 62 |
+
authenticate against a database or an external service.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
username: HTTP Basic Auth username.
|
| 66 |
+
password: HTTP Basic Auth password.
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
bool: :obj:`True` if the handshake should continue;
|
| 70 |
+
:obj:`False` if it should fail with an HTTP 401 error.
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
if self._check_credentials is not None:
|
| 74 |
+
return await self._check_credentials(username, password)
|
| 75 |
+
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
async def process_request(
|
| 79 |
+
self,
|
| 80 |
+
path: str,
|
| 81 |
+
request_headers: Headers,
|
| 82 |
+
) -> Optional[HTTPResponse]:
|
| 83 |
+
"""
|
| 84 |
+
Check HTTP Basic Auth and return an HTTP 401 response if needed.
|
| 85 |
+
|
| 86 |
+
"""
|
| 87 |
+
try:
|
| 88 |
+
authorization = request_headers["Authorization"]
|
| 89 |
+
except KeyError:
|
| 90 |
+
return (
|
| 91 |
+
http.HTTPStatus.UNAUTHORIZED,
|
| 92 |
+
[("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
|
| 93 |
+
b"Missing credentials\n",
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
username, password = parse_authorization_basic(authorization)
|
| 98 |
+
except InvalidHeader:
|
| 99 |
+
return (
|
| 100 |
+
http.HTTPStatus.UNAUTHORIZED,
|
| 101 |
+
[("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
|
| 102 |
+
b"Unsupported credentials\n",
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if not await self.check_credentials(username, password):
|
| 106 |
+
return (
|
| 107 |
+
http.HTTPStatus.UNAUTHORIZED,
|
| 108 |
+
[("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
|
| 109 |
+
b"Invalid credentials\n",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
self.username = username
|
| 113 |
+
|
| 114 |
+
return await super().process_request(path, request_headers)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def basic_auth_protocol_factory(
|
| 118 |
+
realm: Optional[str] = None,
|
| 119 |
+
credentials: Optional[Union[Credentials, Iterable[Credentials]]] = None,
|
| 120 |
+
check_credentials: Optional[Callable[[str, str], Awaitable[bool]]] = None,
|
| 121 |
+
create_protocol: Optional[Callable[..., BasicAuthWebSocketServerProtocol]] = None,
|
| 122 |
+
) -> Callable[..., BasicAuthWebSocketServerProtocol]:
|
| 123 |
+
"""
|
| 124 |
+
Protocol factory that enforces HTTP Basic Auth.
|
| 125 |
+
|
| 126 |
+
:func:`basic_auth_protocol_factory` is designed to integrate with
|
| 127 |
+
:func:`~websockets.server.serve` like this::
|
| 128 |
+
|
| 129 |
+
websockets.serve(
|
| 130 |
+
...,
|
| 131 |
+
create_protocol=websockets.basic_auth_protocol_factory(
|
| 132 |
+
realm="my dev server",
|
| 133 |
+
credentials=("hello", "iloveyou"),
|
| 134 |
+
)
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
realm: Scope of protection. It should contain only ASCII characters
|
| 139 |
+
because the encoding of non-ASCII characters is undefined.
|
| 140 |
+
Refer to section 2.2 of :rfc:`7235` for details.
|
| 141 |
+
credentials: Hard coded authorized credentials. It can be a
|
| 142 |
+
``(username, password)`` pair or a list of such pairs.
|
| 143 |
+
check_credentials: Coroutine that verifies credentials.
|
| 144 |
+
It receives ``username`` and ``password`` arguments
|
| 145 |
+
and returns a :class:`bool`. One of ``credentials`` or
|
| 146 |
+
``check_credentials`` must be provided but not both.
|
| 147 |
+
create_protocol: Factory that creates the protocol. By default, this
|
| 148 |
+
is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced
|
| 149 |
+
by a subclass.
|
| 150 |
+
Raises:
|
| 151 |
+
TypeError: If the ``credentials`` or ``check_credentials`` argument is
|
| 152 |
+
wrong.
|
| 153 |
+
|
| 154 |
+
"""
|
| 155 |
+
if (credentials is None) == (check_credentials is None):
|
| 156 |
+
raise TypeError("provide either credentials or check_credentials")
|
| 157 |
+
|
| 158 |
+
if credentials is not None:
|
| 159 |
+
if is_credentials(credentials):
|
| 160 |
+
credentials_list = [cast(Credentials, credentials)]
|
| 161 |
+
elif isinstance(credentials, Iterable):
|
| 162 |
+
credentials_list = list(credentials)
|
| 163 |
+
if not all(is_credentials(item) for item in credentials_list):
|
| 164 |
+
raise TypeError(f"invalid credentials argument: {credentials}")
|
| 165 |
+
else:
|
| 166 |
+
raise TypeError(f"invalid credentials argument: {credentials}")
|
| 167 |
+
|
| 168 |
+
credentials_dict = dict(credentials_list)
|
| 169 |
+
|
| 170 |
+
async def check_credentials(username: str, password: str) -> bool:
|
| 171 |
+
try:
|
| 172 |
+
expected_password = credentials_dict[username]
|
| 173 |
+
except KeyError:
|
| 174 |
+
return False
|
| 175 |
+
return hmac.compare_digest(expected_password, password)
|
| 176 |
+
|
| 177 |
+
if create_protocol is None:
|
| 178 |
+
create_protocol = BasicAuthWebSocketServerProtocol
|
| 179 |
+
|
| 180 |
+
return functools.partial(
|
| 181 |
+
create_protocol,
|
| 182 |
+
realm=realm,
|
| 183 |
+
check_credentials=check_credentials,
|
| 184 |
+
)
|
videollama2/lib/python3.10/site-packages/websockets/legacy/client.py
ADDED
|
@@ -0,0 +1,713 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import functools
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
import urllib.parse
|
| 8 |
+
import warnings
|
| 9 |
+
from types import TracebackType
|
| 10 |
+
from typing import (
|
| 11 |
+
Any,
|
| 12 |
+
AsyncIterator,
|
| 13 |
+
Callable,
|
| 14 |
+
Generator,
|
| 15 |
+
List,
|
| 16 |
+
Optional,
|
| 17 |
+
Sequence,
|
| 18 |
+
Tuple,
|
| 19 |
+
Type,
|
| 20 |
+
cast,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
from ..datastructures import Headers, HeadersLike
|
| 24 |
+
from ..exceptions import (
|
| 25 |
+
InvalidHandshake,
|
| 26 |
+
InvalidHeader,
|
| 27 |
+
InvalidMessage,
|
| 28 |
+
InvalidStatusCode,
|
| 29 |
+
NegotiationError,
|
| 30 |
+
RedirectHandshake,
|
| 31 |
+
SecurityError,
|
| 32 |
+
)
|
| 33 |
+
from ..extensions import ClientExtensionFactory, Extension
|
| 34 |
+
from ..extensions.permessage_deflate import enable_client_permessage_deflate
|
| 35 |
+
from ..headers import (
|
| 36 |
+
build_authorization_basic,
|
| 37 |
+
build_extension,
|
| 38 |
+
build_host,
|
| 39 |
+
build_subprotocol,
|
| 40 |
+
parse_extension,
|
| 41 |
+
parse_subprotocol,
|
| 42 |
+
validate_subprotocols,
|
| 43 |
+
)
|
| 44 |
+
from ..http import USER_AGENT
|
| 45 |
+
from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol
|
| 46 |
+
from ..uri import WebSocketURI, parse_uri
|
| 47 |
+
from .compatibility import asyncio_timeout
|
| 48 |
+
from .handshake import build_request, check_response
|
| 49 |
+
from .http import read_response
|
| 50 |
+
from .protocol import WebSocketCommonProtocol
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
__all__ = ["connect", "unix_connect", "WebSocketClientProtocol"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class WebSocketClientProtocol(WebSocketCommonProtocol):
|
| 57 |
+
"""
|
| 58 |
+
WebSocket client connection.
|
| 59 |
+
|
| 60 |
+
:class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send`
|
| 61 |
+
coroutines for receiving and sending messages.
|
| 62 |
+
|
| 63 |
+
It supports asynchronous iteration to receive incoming messages::
|
| 64 |
+
|
| 65 |
+
async for message in websocket:
|
| 66 |
+
await process(message)
|
| 67 |
+
|
| 68 |
+
The iterator exits normally when the connection is closed with close code
|
| 69 |
+
1000 (OK) or 1001 (going away) or without a close code. It raises
|
| 70 |
+
a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection
|
| 71 |
+
is closed with any other code.
|
| 72 |
+
|
| 73 |
+
See :func:`connect` for the documentation of ``logger``, ``origin``,
|
| 74 |
+
``extensions``, ``subprotocols``, ``extra_headers``, and
|
| 75 |
+
``user_agent_header``.
|
| 76 |
+
|
| 77 |
+
See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
|
| 78 |
+
documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
|
| 79 |
+
``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
|
| 80 |
+
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
is_client = True
|
| 84 |
+
side = "client"
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
*,
|
| 89 |
+
logger: Optional[LoggerLike] = None,
|
| 90 |
+
origin: Optional[Origin] = None,
|
| 91 |
+
extensions: Optional[Sequence[ClientExtensionFactory]] = None,
|
| 92 |
+
subprotocols: Optional[Sequence[Subprotocol]] = None,
|
| 93 |
+
extra_headers: Optional[HeadersLike] = None,
|
| 94 |
+
user_agent_header: Optional[str] = USER_AGENT,
|
| 95 |
+
**kwargs: Any,
|
| 96 |
+
) -> None:
|
| 97 |
+
if logger is None:
|
| 98 |
+
logger = logging.getLogger("websockets.client")
|
| 99 |
+
super().__init__(logger=logger, **kwargs)
|
| 100 |
+
self.origin = origin
|
| 101 |
+
self.available_extensions = extensions
|
| 102 |
+
self.available_subprotocols = subprotocols
|
| 103 |
+
self.extra_headers = extra_headers
|
| 104 |
+
self.user_agent_header = user_agent_header
|
| 105 |
+
|
| 106 |
+
def write_http_request(self, path: str, headers: Headers) -> None:
|
| 107 |
+
"""
|
| 108 |
+
Write request line and headers to the HTTP request.
|
| 109 |
+
|
| 110 |
+
"""
|
| 111 |
+
self.path = path
|
| 112 |
+
self.request_headers = headers
|
| 113 |
+
|
| 114 |
+
if self.debug:
|
| 115 |
+
self.logger.debug("> GET %s HTTP/1.1", path)
|
| 116 |
+
for key, value in headers.raw_items():
|
| 117 |
+
self.logger.debug("> %s: %s", key, value)
|
| 118 |
+
|
| 119 |
+
# Since the path and headers only contain ASCII characters,
|
| 120 |
+
# we can keep this simple.
|
| 121 |
+
request = f"GET {path} HTTP/1.1\r\n"
|
| 122 |
+
request += str(headers)
|
| 123 |
+
|
| 124 |
+
self.transport.write(request.encode())
|
| 125 |
+
|
| 126 |
+
async def read_http_response(self) -> Tuple[int, Headers]:
|
| 127 |
+
"""
|
| 128 |
+
Read status line and headers from the HTTP response.
|
| 129 |
+
|
| 130 |
+
If the response contains a body, it may be read from ``self.reader``
|
| 131 |
+
after this coroutine returns.
|
| 132 |
+
|
| 133 |
+
Raises:
|
| 134 |
+
InvalidMessage: If the HTTP message is malformed or isn't an
|
| 135 |
+
HTTP/1.1 GET response.
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
try:
|
| 139 |
+
status_code, reason, headers = await read_response(self.reader)
|
| 140 |
+
# Remove this branch when dropping support for Python < 3.8
|
| 141 |
+
# because CancelledError no longer inherits Exception.
|
| 142 |
+
except asyncio.CancelledError: # pragma: no cover
|
| 143 |
+
raise
|
| 144 |
+
except Exception as exc:
|
| 145 |
+
raise InvalidMessage("did not receive a valid HTTP response") from exc
|
| 146 |
+
|
| 147 |
+
if self.debug:
|
| 148 |
+
self.logger.debug("< HTTP/1.1 %d %s", status_code, reason)
|
| 149 |
+
for key, value in headers.raw_items():
|
| 150 |
+
self.logger.debug("< %s: %s", key, value)
|
| 151 |
+
|
| 152 |
+
self.response_headers = headers
|
| 153 |
+
|
| 154 |
+
return status_code, self.response_headers
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def process_extensions(
|
| 158 |
+
headers: Headers,
|
| 159 |
+
available_extensions: Optional[Sequence[ClientExtensionFactory]],
|
| 160 |
+
) -> List[Extension]:
|
| 161 |
+
"""
|
| 162 |
+
Handle the Sec-WebSocket-Extensions HTTP response header.
|
| 163 |
+
|
| 164 |
+
Check that each extension is supported, as well as its parameters.
|
| 165 |
+
|
| 166 |
+
Return the list of accepted extensions.
|
| 167 |
+
|
| 168 |
+
Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the
|
| 169 |
+
connection.
|
| 170 |
+
|
| 171 |
+
:rfc:`6455` leaves the rules up to the specification of each
|
| 172 |
+
:extension.
|
| 173 |
+
|
| 174 |
+
To provide this level of flexibility, for each extension accepted by
|
| 175 |
+
the server, we check for a match with each extension available in the
|
| 176 |
+
client configuration. If no match is found, an exception is raised.
|
| 177 |
+
|
| 178 |
+
If several variants of the same extension are accepted by the server,
|
| 179 |
+
it may be configured several times, which won't make sense in general.
|
| 180 |
+
Extensions must implement their own requirements. For this purpose,
|
| 181 |
+
the list of previously accepted extensions is provided.
|
| 182 |
+
|
| 183 |
+
Other requirements, for example related to mandatory extensions or the
|
| 184 |
+
order of extensions, may be implemented by overriding this method.
|
| 185 |
+
|
| 186 |
+
"""
|
| 187 |
+
accepted_extensions: List[Extension] = []
|
| 188 |
+
|
| 189 |
+
header_values = headers.get_all("Sec-WebSocket-Extensions")
|
| 190 |
+
|
| 191 |
+
if header_values:
|
| 192 |
+
if available_extensions is None:
|
| 193 |
+
raise InvalidHandshake("no extensions supported")
|
| 194 |
+
|
| 195 |
+
parsed_header_values: List[ExtensionHeader] = sum(
|
| 196 |
+
[parse_extension(header_value) for header_value in header_values], []
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
for name, response_params in parsed_header_values:
|
| 200 |
+
for extension_factory in available_extensions:
|
| 201 |
+
# Skip non-matching extensions based on their name.
|
| 202 |
+
if extension_factory.name != name:
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
# Skip non-matching extensions based on their params.
|
| 206 |
+
try:
|
| 207 |
+
extension = extension_factory.process_response_params(
|
| 208 |
+
response_params, accepted_extensions
|
| 209 |
+
)
|
| 210 |
+
except NegotiationError:
|
| 211 |
+
continue
|
| 212 |
+
|
| 213 |
+
# Add matching extension to the final list.
|
| 214 |
+
accepted_extensions.append(extension)
|
| 215 |
+
|
| 216 |
+
# Break out of the loop once we have a match.
|
| 217 |
+
break
|
| 218 |
+
|
| 219 |
+
# If we didn't break from the loop, no extension in our list
|
| 220 |
+
# matched what the server sent. Fail the connection.
|
| 221 |
+
else:
|
| 222 |
+
raise NegotiationError(
|
| 223 |
+
f"Unsupported extension: "
|
| 224 |
+
f"name = {name}, params = {response_params}"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
return accepted_extensions
|
| 228 |
+
|
| 229 |
+
@staticmethod
|
| 230 |
+
def process_subprotocol(
|
| 231 |
+
headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]]
|
| 232 |
+
) -> Optional[Subprotocol]:
|
| 233 |
+
"""
|
| 234 |
+
Handle the Sec-WebSocket-Protocol HTTP response header.
|
| 235 |
+
|
| 236 |
+
Check that it contains exactly one supported subprotocol.
|
| 237 |
+
|
| 238 |
+
Return the selected subprotocol.
|
| 239 |
+
|
| 240 |
+
"""
|
| 241 |
+
subprotocol: Optional[Subprotocol] = None
|
| 242 |
+
|
| 243 |
+
header_values = headers.get_all("Sec-WebSocket-Protocol")
|
| 244 |
+
|
| 245 |
+
if header_values:
|
| 246 |
+
if available_subprotocols is None:
|
| 247 |
+
raise InvalidHandshake("no subprotocols supported")
|
| 248 |
+
|
| 249 |
+
parsed_header_values: Sequence[Subprotocol] = sum(
|
| 250 |
+
[parse_subprotocol(header_value) for header_value in header_values], []
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
if len(parsed_header_values) > 1:
|
| 254 |
+
subprotocols = ", ".join(parsed_header_values)
|
| 255 |
+
raise InvalidHandshake(f"multiple subprotocols: {subprotocols}")
|
| 256 |
+
|
| 257 |
+
subprotocol = parsed_header_values[0]
|
| 258 |
+
|
| 259 |
+
if subprotocol not in available_subprotocols:
|
| 260 |
+
raise NegotiationError(f"unsupported subprotocol: {subprotocol}")
|
| 261 |
+
|
| 262 |
+
return subprotocol
|
| 263 |
+
|
| 264 |
+
async def handshake(
|
| 265 |
+
self,
|
| 266 |
+
wsuri: WebSocketURI,
|
| 267 |
+
origin: Optional[Origin] = None,
|
| 268 |
+
available_extensions: Optional[Sequence[ClientExtensionFactory]] = None,
|
| 269 |
+
available_subprotocols: Optional[Sequence[Subprotocol]] = None,
|
| 270 |
+
extra_headers: Optional[HeadersLike] = None,
|
| 271 |
+
) -> None:
|
| 272 |
+
"""
|
| 273 |
+
Perform the client side of the opening handshake.
|
| 274 |
+
|
| 275 |
+
Args:
|
| 276 |
+
wsuri: URI of the WebSocket server.
|
| 277 |
+
origin: Value of the ``Origin`` header.
|
| 278 |
+
extensions: List of supported extensions, in order in which they
|
| 279 |
+
should be negotiated and run.
|
| 280 |
+
subprotocols: List of supported subprotocols, in order of decreasing
|
| 281 |
+
preference.
|
| 282 |
+
extra_headers: Arbitrary HTTP headers to add to the handshake request.
|
| 283 |
+
|
| 284 |
+
Raises:
|
| 285 |
+
InvalidHandshake: If the handshake fails.
|
| 286 |
+
|
| 287 |
+
"""
|
| 288 |
+
request_headers = Headers()
|
| 289 |
+
|
| 290 |
+
request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure)
|
| 291 |
+
|
| 292 |
+
if wsuri.user_info:
|
| 293 |
+
request_headers["Authorization"] = build_authorization_basic(
|
| 294 |
+
*wsuri.user_info
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
if origin is not None:
|
| 298 |
+
request_headers["Origin"] = origin
|
| 299 |
+
|
| 300 |
+
key = build_request(request_headers)
|
| 301 |
+
|
| 302 |
+
if available_extensions is not None:
|
| 303 |
+
extensions_header = build_extension(
|
| 304 |
+
[
|
| 305 |
+
(extension_factory.name, extension_factory.get_request_params())
|
| 306 |
+
for extension_factory in available_extensions
|
| 307 |
+
]
|
| 308 |
+
)
|
| 309 |
+
request_headers["Sec-WebSocket-Extensions"] = extensions_header
|
| 310 |
+
|
| 311 |
+
if available_subprotocols is not None:
|
| 312 |
+
protocol_header = build_subprotocol(available_subprotocols)
|
| 313 |
+
request_headers["Sec-WebSocket-Protocol"] = protocol_header
|
| 314 |
+
|
| 315 |
+
if self.extra_headers is not None:
|
| 316 |
+
request_headers.update(self.extra_headers)
|
| 317 |
+
|
| 318 |
+
if self.user_agent_header is not None:
|
| 319 |
+
request_headers.setdefault("User-Agent", self.user_agent_header)
|
| 320 |
+
|
| 321 |
+
self.write_http_request(wsuri.resource_name, request_headers)
|
| 322 |
+
|
| 323 |
+
status_code, response_headers = await self.read_http_response()
|
| 324 |
+
if status_code in (301, 302, 303, 307, 308):
|
| 325 |
+
if "Location" not in response_headers:
|
| 326 |
+
raise InvalidHeader("Location")
|
| 327 |
+
raise RedirectHandshake(response_headers["Location"])
|
| 328 |
+
elif status_code != 101:
|
| 329 |
+
raise InvalidStatusCode(status_code, response_headers)
|
| 330 |
+
|
| 331 |
+
check_response(response_headers, key)
|
| 332 |
+
|
| 333 |
+
self.extensions = self.process_extensions(
|
| 334 |
+
response_headers, available_extensions
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
self.subprotocol = self.process_subprotocol(
|
| 338 |
+
response_headers, available_subprotocols
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
self.connection_open()
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class Connect:
|
| 345 |
+
"""
|
| 346 |
+
Connect to the WebSocket server at ``uri``.
|
| 347 |
+
|
| 348 |
+
Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which
|
| 349 |
+
can then be used to send and receive messages.
|
| 350 |
+
|
| 351 |
+
:func:`connect` can be used as a asynchronous context manager::
|
| 352 |
+
|
| 353 |
+
async with websockets.connect(...) as websocket:
|
| 354 |
+
...
|
| 355 |
+
|
| 356 |
+
The connection is closed automatically when exiting the context.
|
| 357 |
+
|
| 358 |
+
:func:`connect` can be used as an infinite asynchronous iterator to
|
| 359 |
+
reconnect automatically on errors::
|
| 360 |
+
|
| 361 |
+
async for websocket in websockets.connect(...):
|
| 362 |
+
try:
|
| 363 |
+
...
|
| 364 |
+
except websockets.ConnectionClosed:
|
| 365 |
+
continue
|
| 366 |
+
|
| 367 |
+
The connection is closed automatically after each iteration of the loop.
|
| 368 |
+
|
| 369 |
+
If an error occurs while establishing the connection, :func:`connect`
|
| 370 |
+
retries with exponential backoff. The backoff delay starts at three
|
| 371 |
+
seconds and increases up to one minute.
|
| 372 |
+
|
| 373 |
+
If an error occurs in the body of the loop, you can handle the exception
|
| 374 |
+
and :func:`connect` will reconnect with the next iteration; or you can
|
| 375 |
+
let the exception bubble up and break out of the loop. This lets you
|
| 376 |
+
decide which errors trigger a reconnection and which errors are fatal.
|
| 377 |
+
|
| 378 |
+
Args:
|
| 379 |
+
uri: URI of the WebSocket server.
|
| 380 |
+
create_protocol: Factory for the :class:`asyncio.Protocol` managing
|
| 381 |
+
the connection. It defaults to :class:`WebSocketClientProtocol`.
|
| 382 |
+
Set it to a wrapper or a subclass to customize connection handling.
|
| 383 |
+
logger: Logger for this client.
|
| 384 |
+
It defaults to ``logging.getLogger("websockets.client")``.
|
| 385 |
+
See the :doc:`logging guide <../../topics/logging>` for details.
|
| 386 |
+
compression: The "permessage-deflate" extension is enabled by default.
|
| 387 |
+
Set ``compression`` to :obj:`None` to disable it. See the
|
| 388 |
+
:doc:`compression guide <../../topics/compression>` for details.
|
| 389 |
+
origin: Value of the ``Origin`` header, for servers that require it.
|
| 390 |
+
extensions: List of supported extensions, in order in which they
|
| 391 |
+
should be negotiated and run.
|
| 392 |
+
subprotocols: List of supported subprotocols, in order of decreasing
|
| 393 |
+
preference.
|
| 394 |
+
extra_headers: Arbitrary HTTP headers to add to the handshake request.
|
| 395 |
+
user_agent_header: Value of the ``User-Agent`` request header.
|
| 396 |
+
It defaults to ``"Python/x.y.z websockets/X.Y"``.
|
| 397 |
+
Setting it to :obj:`None` removes the header.
|
| 398 |
+
open_timeout: Timeout for opening the connection in seconds.
|
| 399 |
+
:obj:`None` disables the timeout.
|
| 400 |
+
|
| 401 |
+
See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the
|
| 402 |
+
documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``,
|
| 403 |
+
``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``.
|
| 404 |
+
|
| 405 |
+
Any other keyword arguments are passed the event loop's
|
| 406 |
+
:meth:`~asyncio.loop.create_connection` method.
|
| 407 |
+
|
| 408 |
+
For example:
|
| 409 |
+
|
| 410 |
+
* You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS
|
| 411 |
+
settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't
|
| 412 |
+
provided, a TLS context is created
|
| 413 |
+
with :func:`~ssl.create_default_context`.
|
| 414 |
+
|
| 415 |
+
* You can set ``host`` and ``port`` to connect to a different host and
|
| 416 |
+
port from those found in ``uri``. This only changes the destination of
|
| 417 |
+
the TCP connection. The host name from ``uri`` is still used in the TLS
|
| 418 |
+
handshake for secure connections and in the ``Host`` header.
|
| 419 |
+
|
| 420 |
+
Raises:
|
| 421 |
+
InvalidURI: If ``uri`` isn't a valid WebSocket URI.
|
| 422 |
+
OSError: If the TCP connection fails.
|
| 423 |
+
InvalidHandshake: If the opening handshake fails.
|
| 424 |
+
~asyncio.TimeoutError: If the opening handshake times out.
|
| 425 |
+
|
| 426 |
+
"""
|
| 427 |
+
|
| 428 |
+
MAX_REDIRECTS_ALLOWED = 10
|
| 429 |
+
|
| 430 |
+
def __init__(
|
| 431 |
+
self,
|
| 432 |
+
uri: str,
|
| 433 |
+
*,
|
| 434 |
+
create_protocol: Optional[Callable[..., WebSocketClientProtocol]] = None,
|
| 435 |
+
logger: Optional[LoggerLike] = None,
|
| 436 |
+
compression: Optional[str] = "deflate",
|
| 437 |
+
origin: Optional[Origin] = None,
|
| 438 |
+
extensions: Optional[Sequence[ClientExtensionFactory]] = None,
|
| 439 |
+
subprotocols: Optional[Sequence[Subprotocol]] = None,
|
| 440 |
+
extra_headers: Optional[HeadersLike] = None,
|
| 441 |
+
user_agent_header: Optional[str] = USER_AGENT,
|
| 442 |
+
open_timeout: Optional[float] = 10,
|
| 443 |
+
ping_interval: Optional[float] = 20,
|
| 444 |
+
ping_timeout: Optional[float] = 20,
|
| 445 |
+
close_timeout: Optional[float] = None,
|
| 446 |
+
max_size: Optional[int] = 2**20,
|
| 447 |
+
max_queue: Optional[int] = 2**5,
|
| 448 |
+
read_limit: int = 2**16,
|
| 449 |
+
write_limit: int = 2**16,
|
| 450 |
+
**kwargs: Any,
|
| 451 |
+
) -> None:
|
| 452 |
+
# Backwards compatibility: close_timeout used to be called timeout.
|
| 453 |
+
timeout: Optional[float] = kwargs.pop("timeout", None)
|
| 454 |
+
if timeout is None:
|
| 455 |
+
timeout = 10
|
| 456 |
+
else:
|
| 457 |
+
warnings.warn("rename timeout to close_timeout", DeprecationWarning)
|
| 458 |
+
# If both are specified, timeout is ignored.
|
| 459 |
+
if close_timeout is None:
|
| 460 |
+
close_timeout = timeout
|
| 461 |
+
|
| 462 |
+
# Backwards compatibility: create_protocol used to be called klass.
|
| 463 |
+
klass: Optional[Type[WebSocketClientProtocol]] = kwargs.pop("klass", None)
|
| 464 |
+
if klass is None:
|
| 465 |
+
klass = WebSocketClientProtocol
|
| 466 |
+
else:
|
| 467 |
+
warnings.warn("rename klass to create_protocol", DeprecationWarning)
|
| 468 |
+
# If both are specified, klass is ignored.
|
| 469 |
+
if create_protocol is None:
|
| 470 |
+
create_protocol = klass
|
| 471 |
+
|
| 472 |
+
# Backwards compatibility: recv() used to return None on closed connections
|
| 473 |
+
legacy_recv: bool = kwargs.pop("legacy_recv", False)
|
| 474 |
+
|
| 475 |
+
# Backwards compatibility: the loop parameter used to be supported.
|
| 476 |
+
_loop: Optional[asyncio.AbstractEventLoop] = kwargs.pop("loop", None)
|
| 477 |
+
if _loop is None:
|
| 478 |
+
loop = asyncio.get_event_loop()
|
| 479 |
+
else:
|
| 480 |
+
loop = _loop
|
| 481 |
+
warnings.warn("remove loop argument", DeprecationWarning)
|
| 482 |
+
|
| 483 |
+
wsuri = parse_uri(uri)
|
| 484 |
+
if wsuri.secure:
|
| 485 |
+
kwargs.setdefault("ssl", True)
|
| 486 |
+
elif kwargs.get("ssl") is not None:
|
| 487 |
+
raise ValueError(
|
| 488 |
+
"connect() received a ssl argument for a ws:// URI, "
|
| 489 |
+
"use a wss:// URI to enable TLS"
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
if compression == "deflate":
|
| 493 |
+
extensions = enable_client_permessage_deflate(extensions)
|
| 494 |
+
elif compression is not None:
|
| 495 |
+
raise ValueError(f"unsupported compression: {compression}")
|
| 496 |
+
|
| 497 |
+
if subprotocols is not None:
|
| 498 |
+
validate_subprotocols(subprotocols)
|
| 499 |
+
|
| 500 |
+
factory = functools.partial(
|
| 501 |
+
create_protocol,
|
| 502 |
+
logger=logger,
|
| 503 |
+
origin=origin,
|
| 504 |
+
extensions=extensions,
|
| 505 |
+
subprotocols=subprotocols,
|
| 506 |
+
extra_headers=extra_headers,
|
| 507 |
+
user_agent_header=user_agent_header,
|
| 508 |
+
ping_interval=ping_interval,
|
| 509 |
+
ping_timeout=ping_timeout,
|
| 510 |
+
close_timeout=close_timeout,
|
| 511 |
+
max_size=max_size,
|
| 512 |
+
max_queue=max_queue,
|
| 513 |
+
read_limit=read_limit,
|
| 514 |
+
write_limit=write_limit,
|
| 515 |
+
host=wsuri.host,
|
| 516 |
+
port=wsuri.port,
|
| 517 |
+
secure=wsuri.secure,
|
| 518 |
+
legacy_recv=legacy_recv,
|
| 519 |
+
loop=_loop,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
if kwargs.pop("unix", False):
|
| 523 |
+
path: Optional[str] = kwargs.pop("path", None)
|
| 524 |
+
create_connection = functools.partial(
|
| 525 |
+
loop.create_unix_connection, factory, path, **kwargs
|
| 526 |
+
)
|
| 527 |
+
else:
|
| 528 |
+
host: Optional[str]
|
| 529 |
+
port: Optional[int]
|
| 530 |
+
if kwargs.get("sock") is None:
|
| 531 |
+
host, port = wsuri.host, wsuri.port
|
| 532 |
+
else:
|
| 533 |
+
# If sock is given, host and port shouldn't be specified.
|
| 534 |
+
host, port = None, None
|
| 535 |
+
if kwargs.get("ssl"):
|
| 536 |
+
kwargs.setdefault("server_hostname", wsuri.host)
|
| 537 |
+
# If host and port are given, override values from the URI.
|
| 538 |
+
host = kwargs.pop("host", host)
|
| 539 |
+
port = kwargs.pop("port", port)
|
| 540 |
+
create_connection = functools.partial(
|
| 541 |
+
loop.create_connection, factory, host, port, **kwargs
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
self.open_timeout = open_timeout
|
| 545 |
+
if logger is None:
|
| 546 |
+
logger = logging.getLogger("websockets.client")
|
| 547 |
+
self.logger = logger
|
| 548 |
+
|
| 549 |
+
# This is a coroutine function.
|
| 550 |
+
self._create_connection = create_connection
|
| 551 |
+
self._uri = uri
|
| 552 |
+
self._wsuri = wsuri
|
| 553 |
+
|
| 554 |
+
def handle_redirect(self, uri: str) -> None:
|
| 555 |
+
# Update the state of this instance to connect to a new URI.
|
| 556 |
+
old_uri = self._uri
|
| 557 |
+
old_wsuri = self._wsuri
|
| 558 |
+
new_uri = urllib.parse.urljoin(old_uri, uri)
|
| 559 |
+
new_wsuri = parse_uri(new_uri)
|
| 560 |
+
|
| 561 |
+
# Forbid TLS downgrade.
|
| 562 |
+
if old_wsuri.secure and not new_wsuri.secure:
|
| 563 |
+
raise SecurityError("redirect from WSS to WS")
|
| 564 |
+
|
| 565 |
+
same_origin = (
|
| 566 |
+
old_wsuri.host == new_wsuri.host and old_wsuri.port == new_wsuri.port
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# Rewrite the host and port arguments for cross-origin redirects.
|
| 570 |
+
# This preserves connection overrides with the host and port
|
| 571 |
+
# arguments if the redirect points to the same host and port.
|
| 572 |
+
if not same_origin:
|
| 573 |
+
# Replace the host and port argument passed to the protocol factory.
|
| 574 |
+
factory = self._create_connection.args[0]
|
| 575 |
+
factory = functools.partial(
|
| 576 |
+
factory.func,
|
| 577 |
+
*factory.args,
|
| 578 |
+
**dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port),
|
| 579 |
+
)
|
| 580 |
+
# Replace the host and port argument passed to create_connection.
|
| 581 |
+
self._create_connection = functools.partial(
|
| 582 |
+
self._create_connection.func,
|
| 583 |
+
*(factory, new_wsuri.host, new_wsuri.port),
|
| 584 |
+
**self._create_connection.keywords,
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
# Set the new WebSocket URI. This suffices for same-origin redirects.
|
| 588 |
+
self._uri = new_uri
|
| 589 |
+
self._wsuri = new_wsuri
|
| 590 |
+
|
| 591 |
+
# async for ... in connect(...):
|
| 592 |
+
|
| 593 |
+
BACKOFF_MIN = 1.92
|
| 594 |
+
BACKOFF_MAX = 60.0
|
| 595 |
+
BACKOFF_FACTOR = 1.618
|
| 596 |
+
BACKOFF_INITIAL = 5
|
| 597 |
+
|
| 598 |
+
async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]:
|
| 599 |
+
backoff_delay = self.BACKOFF_MIN
|
| 600 |
+
while True:
|
| 601 |
+
try:
|
| 602 |
+
async with self as protocol:
|
| 603 |
+
yield protocol
|
| 604 |
+
# Remove this branch when dropping support for Python < 3.8
|
| 605 |
+
# because CancelledError no longer inherits Exception.
|
| 606 |
+
except asyncio.CancelledError: # pragma: no cover
|
| 607 |
+
raise
|
| 608 |
+
except Exception:
|
| 609 |
+
# Add a random initial delay between 0 and 5 seconds.
|
| 610 |
+
# See 7.2.3. Recovering from Abnormal Closure in RFC 6544.
|
| 611 |
+
if backoff_delay == self.BACKOFF_MIN:
|
| 612 |
+
initial_delay = random.random() * self.BACKOFF_INITIAL
|
| 613 |
+
self.logger.info(
|
| 614 |
+
"! connect failed; reconnecting in %.1f seconds",
|
| 615 |
+
initial_delay,
|
| 616 |
+
exc_info=True,
|
| 617 |
+
)
|
| 618 |
+
await asyncio.sleep(initial_delay)
|
| 619 |
+
else:
|
| 620 |
+
self.logger.info(
|
| 621 |
+
"! connect failed again; retrying in %d seconds",
|
| 622 |
+
int(backoff_delay),
|
| 623 |
+
exc_info=True,
|
| 624 |
+
)
|
| 625 |
+
await asyncio.sleep(int(backoff_delay))
|
| 626 |
+
# Increase delay with truncated exponential backoff.
|
| 627 |
+
backoff_delay = backoff_delay * self.BACKOFF_FACTOR
|
| 628 |
+
backoff_delay = min(backoff_delay, self.BACKOFF_MAX)
|
| 629 |
+
continue
|
| 630 |
+
else:
|
| 631 |
+
# Connection succeeded - reset backoff delay
|
| 632 |
+
backoff_delay = self.BACKOFF_MIN
|
| 633 |
+
|
| 634 |
+
# async with connect(...) as ...:
|
| 635 |
+
|
| 636 |
+
async def __aenter__(self) -> WebSocketClientProtocol:
|
| 637 |
+
return await self
|
| 638 |
+
|
| 639 |
+
async def __aexit__(
|
| 640 |
+
self,
|
| 641 |
+
exc_type: Optional[Type[BaseException]],
|
| 642 |
+
exc_value: Optional[BaseException],
|
| 643 |
+
traceback: Optional[TracebackType],
|
| 644 |
+
) -> None:
|
| 645 |
+
await self.protocol.close()
|
| 646 |
+
|
| 647 |
+
# ... = await connect(...)
|
| 648 |
+
|
| 649 |
+
def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]:
|
| 650 |
+
# Create a suitable iterator by calling __await__ on a coroutine.
|
| 651 |
+
return self.__await_impl_timeout__().__await__()
|
| 652 |
+
|
| 653 |
+
async def __await_impl_timeout__(self) -> WebSocketClientProtocol:
|
| 654 |
+
async with asyncio_timeout(self.open_timeout):
|
| 655 |
+
return await self.__await_impl__()
|
| 656 |
+
|
| 657 |
+
async def __await_impl__(self) -> WebSocketClientProtocol:
|
| 658 |
+
for redirects in range(self.MAX_REDIRECTS_ALLOWED):
|
| 659 |
+
_transport, _protocol = await self._create_connection()
|
| 660 |
+
protocol = cast(WebSocketClientProtocol, _protocol)
|
| 661 |
+
try:
|
| 662 |
+
await protocol.handshake(
|
| 663 |
+
self._wsuri,
|
| 664 |
+
origin=protocol.origin,
|
| 665 |
+
available_extensions=protocol.available_extensions,
|
| 666 |
+
available_subprotocols=protocol.available_subprotocols,
|
| 667 |
+
extra_headers=protocol.extra_headers,
|
| 668 |
+
)
|
| 669 |
+
except RedirectHandshake as exc:
|
| 670 |
+
protocol.fail_connection()
|
| 671 |
+
await protocol.wait_closed()
|
| 672 |
+
self.handle_redirect(exc.uri)
|
| 673 |
+
# Avoid leaking a connected socket when the handshake fails.
|
| 674 |
+
except (Exception, asyncio.CancelledError):
|
| 675 |
+
protocol.fail_connection()
|
| 676 |
+
await protocol.wait_closed()
|
| 677 |
+
raise
|
| 678 |
+
else:
|
| 679 |
+
self.protocol = protocol
|
| 680 |
+
return protocol
|
| 681 |
+
else:
|
| 682 |
+
raise SecurityError("too many redirects")
|
| 683 |
+
|
| 684 |
+
# ... = yield from connect(...) - remove when dropping Python < 3.10
|
| 685 |
+
|
| 686 |
+
__iter__ = __await__
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
connect = Connect
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def unix_connect(
|
| 693 |
+
path: Optional[str] = None,
|
| 694 |
+
uri: str = "ws://localhost/",
|
| 695 |
+
**kwargs: Any,
|
| 696 |
+
) -> Connect:
|
| 697 |
+
"""
|
| 698 |
+
Similar to :func:`connect`, but for connecting to a Unix socket.
|
| 699 |
+
|
| 700 |
+
This function builds upon the event loop's
|
| 701 |
+
:meth:`~asyncio.loop.create_unix_connection` method.
|
| 702 |
+
|
| 703 |
+
It is only available on Unix.
|
| 704 |
+
|
| 705 |
+
It's mainly useful for debugging servers listening on Unix sockets.
|
| 706 |
+
|
| 707 |
+
Args:
|
| 708 |
+
path: File system path to the Unix socket.
|
| 709 |
+
uri: URI of the WebSocket server; the host is used in the TLS
|
| 710 |
+
handshake for secure connections and in the ``Host`` header.
|
| 711 |
+
|
| 712 |
+
"""
|
| 713 |
+
return connect(uri=uri, path=path, unix=True, **kwargs)
|
videollama2/lib/python3.10/site-packages/websockets/legacy/compatibility.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import sys
|
| 5 |
+
from typing import Any, Dict
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ["asyncio_timeout", "loop_if_py_lt_38"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if sys.version_info[:2] >= (3, 8):
|
| 12 |
+
|
| 13 |
+
def loop_if_py_lt_38(loop: asyncio.AbstractEventLoop) -> Dict[str, Any]:
|
| 14 |
+
"""
|
| 15 |
+
Helper for the removal of the loop argument in Python 3.10.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
return {}
|
| 19 |
+
|
| 20 |
+
else:
|
| 21 |
+
|
| 22 |
+
def loop_if_py_lt_38(loop: asyncio.AbstractEventLoop) -> Dict[str, Any]:
|
| 23 |
+
"""
|
| 24 |
+
Helper for the removal of the loop argument in Python 3.10.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
return {"loop": loop}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if sys.version_info[:2] >= (3, 11):
|
| 31 |
+
from asyncio import timeout as asyncio_timeout # noqa: F401
|
| 32 |
+
else:
|
| 33 |
+
from .async_timeout import timeout as asyncio_timeout # noqa: F401
|
videollama2/lib/python3.10/site-packages/websockets/legacy/framing.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
from typing import Any, Awaitable, Callable, NamedTuple, Optional, Sequence, Tuple
|
| 5 |
+
|
| 6 |
+
from .. import extensions, frames
|
| 7 |
+
from ..exceptions import PayloadTooBig, ProtocolError
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from ..speedups import apply_mask
|
| 12 |
+
except ImportError:
|
| 13 |
+
from ..utils import apply_mask
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Frame(NamedTuple):
|
| 17 |
+
fin: bool
|
| 18 |
+
opcode: frames.Opcode
|
| 19 |
+
data: bytes
|
| 20 |
+
rsv1: bool = False
|
| 21 |
+
rsv2: bool = False
|
| 22 |
+
rsv3: bool = False
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def new_frame(self) -> frames.Frame:
|
| 26 |
+
return frames.Frame(
|
| 27 |
+
self.opcode,
|
| 28 |
+
self.data,
|
| 29 |
+
self.fin,
|
| 30 |
+
self.rsv1,
|
| 31 |
+
self.rsv2,
|
| 32 |
+
self.rsv3,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def __str__(self) -> str:
|
| 36 |
+
return str(self.new_frame)
|
| 37 |
+
|
| 38 |
+
def check(self) -> None:
|
| 39 |
+
return self.new_frame.check()
|
| 40 |
+
|
| 41 |
+
@classmethod
|
| 42 |
+
async def read(
|
| 43 |
+
cls,
|
| 44 |
+
reader: Callable[[int], Awaitable[bytes]],
|
| 45 |
+
*,
|
| 46 |
+
mask: bool,
|
| 47 |
+
max_size: Optional[int] = None,
|
| 48 |
+
extensions: Optional[Sequence[extensions.Extension]] = None,
|
| 49 |
+
) -> Frame:
|
| 50 |
+
"""
|
| 51 |
+
Read a WebSocket frame.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
reader: Coroutine that reads exactly the requested number of
|
| 55 |
+
bytes, unless the end of file is reached.
|
| 56 |
+
mask: Whether the frame should be masked i.e. whether the read
|
| 57 |
+
happens on the server side.
|
| 58 |
+
max_size: Maximum payload size in bytes.
|
| 59 |
+
extensions: List of extensions, applied in reverse order.
|
| 60 |
+
|
| 61 |
+
Raises:
|
| 62 |
+
PayloadTooBig: If the frame exceeds ``max_size``.
|
| 63 |
+
ProtocolError: If the frame contains incorrect values.
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
# Read the header.
|
| 68 |
+
data = await reader(2)
|
| 69 |
+
head1, head2 = struct.unpack("!BB", data)
|
| 70 |
+
|
| 71 |
+
# While not Pythonic, this is marginally faster than calling bool().
|
| 72 |
+
fin = True if head1 & 0b10000000 else False
|
| 73 |
+
rsv1 = True if head1 & 0b01000000 else False
|
| 74 |
+
rsv2 = True if head1 & 0b00100000 else False
|
| 75 |
+
rsv3 = True if head1 & 0b00010000 else False
|
| 76 |
+
|
| 77 |
+
try:
|
| 78 |
+
opcode = frames.Opcode(head1 & 0b00001111)
|
| 79 |
+
except ValueError as exc:
|
| 80 |
+
raise ProtocolError("invalid opcode") from exc
|
| 81 |
+
|
| 82 |
+
if (True if head2 & 0b10000000 else False) != mask:
|
| 83 |
+
raise ProtocolError("incorrect masking")
|
| 84 |
+
|
| 85 |
+
length = head2 & 0b01111111
|
| 86 |
+
if length == 126:
|
| 87 |
+
data = await reader(2)
|
| 88 |
+
(length,) = struct.unpack("!H", data)
|
| 89 |
+
elif length == 127:
|
| 90 |
+
data = await reader(8)
|
| 91 |
+
(length,) = struct.unpack("!Q", data)
|
| 92 |
+
if max_size is not None and length > max_size:
|
| 93 |
+
raise PayloadTooBig(f"over size limit ({length} > {max_size} bytes)")
|
| 94 |
+
if mask:
|
| 95 |
+
mask_bits = await reader(4)
|
| 96 |
+
|
| 97 |
+
# Read the data.
|
| 98 |
+
data = await reader(length)
|
| 99 |
+
if mask:
|
| 100 |
+
data = apply_mask(data, mask_bits)
|
| 101 |
+
|
| 102 |
+
new_frame = frames.Frame(opcode, data, fin, rsv1, rsv2, rsv3)
|
| 103 |
+
|
| 104 |
+
if extensions is None:
|
| 105 |
+
extensions = []
|
| 106 |
+
for extension in reversed(extensions):
|
| 107 |
+
new_frame = extension.decode(new_frame, max_size=max_size)
|
| 108 |
+
|
| 109 |
+
new_frame.check()
|
| 110 |
+
|
| 111 |
+
return cls(
|
| 112 |
+
new_frame.fin,
|
| 113 |
+
new_frame.opcode,
|
| 114 |
+
new_frame.data,
|
| 115 |
+
new_frame.rsv1,
|
| 116 |
+
new_frame.rsv2,
|
| 117 |
+
new_frame.rsv3,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def write(
|
| 121 |
+
self,
|
| 122 |
+
write: Callable[[bytes], Any],
|
| 123 |
+
*,
|
| 124 |
+
mask: bool,
|
| 125 |
+
extensions: Optional[Sequence[extensions.Extension]] = None,
|
| 126 |
+
) -> None:
|
| 127 |
+
"""
|
| 128 |
+
Write a WebSocket frame.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
frame: Frame to write.
|
| 132 |
+
write: Function that writes bytes.
|
| 133 |
+
mask: Whether the frame should be masked i.e. whether the write
|
| 134 |
+
happens on the client side.
|
| 135 |
+
extensions: List of extensions, applied in order.
|
| 136 |
+
|
| 137 |
+
Raises:
|
| 138 |
+
ProtocolError: If the frame contains incorrect values.
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
# The frame is written in a single call to write in order to prevent
|
| 142 |
+
# TCP fragmentation. See #68 for details. This also makes it safe to
|
| 143 |
+
# send frames concurrently from multiple coroutines.
|
| 144 |
+
write(self.new_frame.serialize(mask=mask, extensions=extensions))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# Backwards compatibility with previously documented public APIs
|
| 148 |
+
from ..frames import ( # noqa: E402, F401, I001
|
| 149 |
+
Close,
|
| 150 |
+
prepare_ctrl as encode_data,
|
| 151 |
+
prepare_data,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def parse_close(data: bytes) -> Tuple[int, str]:
|
| 156 |
+
"""
|
| 157 |
+
Parse the payload from a close frame.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
Close code and reason.
|
| 161 |
+
|
| 162 |
+
Raises:
|
| 163 |
+
ProtocolError: If data is ill-formed.
|
| 164 |
+
UnicodeDecodeError: If the reason isn't valid UTF-8.
|
| 165 |
+
|
| 166 |
+
"""
|
| 167 |
+
close = Close.parse(data)
|
| 168 |
+
return close.code, close.reason
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def serialize_close(code: int, reason: str) -> bytes:
|
| 172 |
+
"""
|
| 173 |
+
Serialize the payload for a close frame.
|
| 174 |
+
|
| 175 |
+
"""
|
| 176 |
+
return Close(code, reason).serialize()
|
videollama2/lib/python3.10/site-packages/websockets/legacy/handshake.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import binascii
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
from ..datastructures import Headers, MultipleValuesError
|
| 8 |
+
from ..exceptions import InvalidHeader, InvalidHeaderValue, InvalidUpgrade
|
| 9 |
+
from ..headers import parse_connection, parse_upgrade
|
| 10 |
+
from ..typing import ConnectionOption, UpgradeProtocol
|
| 11 |
+
from ..utils import accept_key as accept, generate_key
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["build_request", "check_request", "build_response", "check_response"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def build_request(headers: Headers) -> str:
|
| 18 |
+
"""
|
| 19 |
+
Build a handshake request to send to the server.
|
| 20 |
+
|
| 21 |
+
Update request headers passed in argument.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
headers: Handshake request headers.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
str: ``key`` that must be passed to :func:`check_response`.
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
key = generate_key()
|
| 31 |
+
headers["Upgrade"] = "websocket"
|
| 32 |
+
headers["Connection"] = "Upgrade"
|
| 33 |
+
headers["Sec-WebSocket-Key"] = key
|
| 34 |
+
headers["Sec-WebSocket-Version"] = "13"
|
| 35 |
+
return key
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def check_request(headers: Headers) -> str:
|
| 39 |
+
"""
|
| 40 |
+
Check a handshake request received from the client.
|
| 41 |
+
|
| 42 |
+
This function doesn't verify that the request is an HTTP/1.1 or higher GET
|
| 43 |
+
request and doesn't perform ``Host`` and ``Origin`` checks. These controls
|
| 44 |
+
are usually performed earlier in the HTTP request handling code. They're
|
| 45 |
+
the responsibility of the caller.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
headers: Handshake request headers.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
str: ``key`` that must be passed to :func:`build_response`.
|
| 52 |
+
|
| 53 |
+
Raises:
|
| 54 |
+
InvalidHandshake: If the handshake request is invalid.
|
| 55 |
+
Then, the server must return a 400 Bad Request error.
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
connection: List[ConnectionOption] = sum(
|
| 59 |
+
[parse_connection(value) for value in headers.get_all("Connection")], []
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if not any(value.lower() == "upgrade" for value in connection):
|
| 63 |
+
raise InvalidUpgrade("Connection", ", ".join(connection))
|
| 64 |
+
|
| 65 |
+
upgrade: List[UpgradeProtocol] = sum(
|
| 66 |
+
[parse_upgrade(value) for value in headers.get_all("Upgrade")], []
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# For compatibility with non-strict implementations, ignore case when
|
| 70 |
+
# checking the Upgrade header. The RFC always uses "websocket", except
|
| 71 |
+
# in section 11.2. (IANA registration) where it uses "WebSocket".
|
| 72 |
+
if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
|
| 73 |
+
raise InvalidUpgrade("Upgrade", ", ".join(upgrade))
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
s_w_key = headers["Sec-WebSocket-Key"]
|
| 77 |
+
except KeyError as exc:
|
| 78 |
+
raise InvalidHeader("Sec-WebSocket-Key") from exc
|
| 79 |
+
except MultipleValuesError as exc:
|
| 80 |
+
raise InvalidHeader(
|
| 81 |
+
"Sec-WebSocket-Key", "more than one Sec-WebSocket-Key header found"
|
| 82 |
+
) from exc
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
raw_key = base64.b64decode(s_w_key.encode(), validate=True)
|
| 86 |
+
except binascii.Error as exc:
|
| 87 |
+
raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) from exc
|
| 88 |
+
if len(raw_key) != 16:
|
| 89 |
+
raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key)
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
s_w_version = headers["Sec-WebSocket-Version"]
|
| 93 |
+
except KeyError as exc:
|
| 94 |
+
raise InvalidHeader("Sec-WebSocket-Version") from exc
|
| 95 |
+
except MultipleValuesError as exc:
|
| 96 |
+
raise InvalidHeader(
|
| 97 |
+
"Sec-WebSocket-Version", "more than one Sec-WebSocket-Version header found"
|
| 98 |
+
) from exc
|
| 99 |
+
|
| 100 |
+
if s_w_version != "13":
|
| 101 |
+
raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version)
|
| 102 |
+
|
| 103 |
+
return s_w_key
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def build_response(headers: Headers, key: str) -> None:
|
| 107 |
+
"""
|
| 108 |
+
Build a handshake response to send to the client.
|
| 109 |
+
|
| 110 |
+
Update response headers passed in argument.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
headers: Handshake response headers.
|
| 114 |
+
key: Returned by :func:`check_request`.
|
| 115 |
+
|
| 116 |
+
"""
|
| 117 |
+
headers["Upgrade"] = "websocket"
|
| 118 |
+
headers["Connection"] = "Upgrade"
|
| 119 |
+
headers["Sec-WebSocket-Accept"] = accept(key)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def check_response(headers: Headers, key: str) -> None:
|
| 123 |
+
"""
|
| 124 |
+
Check a handshake response received from the server.
|
| 125 |
+
|
| 126 |
+
This function doesn't verify that the response is an HTTP/1.1 or higher
|
| 127 |
+
response with a 101 status code. These controls are the responsibility of
|
| 128 |
+
the caller.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
headers: Handshake response headers.
|
| 132 |
+
key: Returned by :func:`build_request`.
|
| 133 |
+
|
| 134 |
+
Raises:
|
| 135 |
+
InvalidHandshake: If the handshake response is invalid.
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
connection: List[ConnectionOption] = sum(
|
| 139 |
+
[parse_connection(value) for value in headers.get_all("Connection")], []
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
if not any(value.lower() == "upgrade" for value in connection):
|
| 143 |
+
raise InvalidUpgrade("Connection", " ".join(connection))
|
| 144 |
+
|
| 145 |
+
upgrade: List[UpgradeProtocol] = sum(
|
| 146 |
+
[parse_upgrade(value) for value in headers.get_all("Upgrade")], []
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# For compatibility with non-strict implementations, ignore case when
|
| 150 |
+
# checking the Upgrade header. The RFC always uses "websocket", except
|
| 151 |
+
# in section 11.2. (IANA registration) where it uses "WebSocket".
|
| 152 |
+
if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"):
|
| 153 |
+
raise InvalidUpgrade("Upgrade", ", ".join(upgrade))
|
| 154 |
+
|
| 155 |
+
try:
|
| 156 |
+
s_w_accept = headers["Sec-WebSocket-Accept"]
|
| 157 |
+
except KeyError as exc:
|
| 158 |
+
raise InvalidHeader("Sec-WebSocket-Accept") from exc
|
| 159 |
+
except MultipleValuesError as exc:
|
| 160 |
+
raise InvalidHeader(
|
| 161 |
+
"Sec-WebSocket-Accept", "more than one Sec-WebSocket-Accept header found"
|
| 162 |
+
) from exc
|
| 163 |
+
|
| 164 |
+
if s_w_accept != accept(key):
|
| 165 |
+
raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept)
|