On branch DiscordProfile
Initial commit
This commit is contained in:
Executable
BIN
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,222 @@
|
||||
# don't import any costly modules
|
||||
import sys
|
||||
import os
|
||||
|
||||
|
||||
is_pypy = '__pypy__' in sys.builtin_module_names
|
||||
|
||||
|
||||
def warn_distutils_present():
|
||||
if 'distutils' not in sys.modules:
|
||||
return
|
||||
if is_pypy and sys.version_info < (3, 7):
|
||||
# PyPy for 3.6 unconditionally imports distutils, so bypass the warning
|
||||
# https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
|
||||
return
|
||||
import warnings
|
||||
|
||||
warnings.warn(
|
||||
"Distutils was imported before Setuptools, but importing Setuptools "
|
||||
"also replaces the `distutils` module in `sys.modules`. This may lead "
|
||||
"to undesirable behaviors or errors. To avoid these issues, avoid "
|
||||
"using distutils directly, ensure that setuptools is installed in the "
|
||||
"traditional way (e.g. not an editable install), and/or make sure "
|
||||
"that setuptools is always imported before distutils."
|
||||
)
|
||||
|
||||
|
||||
def clear_distutils():
|
||||
if 'distutils' not in sys.modules:
|
||||
return
|
||||
import warnings
|
||||
|
||||
warnings.warn("Setuptools is replacing distutils.")
|
||||
mods = [
|
||||
name
|
||||
for name in sys.modules
|
||||
if name == "distutils" or name.startswith("distutils.")
|
||||
]
|
||||
for name in mods:
|
||||
del sys.modules[name]
|
||||
|
||||
|
||||
def enabled():
|
||||
"""
|
||||
Allow selection of distutils by environment variable.
|
||||
"""
|
||||
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
|
||||
return which == 'local'
|
||||
|
||||
|
||||
def ensure_local_distutils():
|
||||
import importlib
|
||||
|
||||
clear_distutils()
|
||||
|
||||
# With the DistutilsMetaFinder in place,
|
||||
# perform an import to cause distutils to be
|
||||
# loaded from setuptools._distutils. Ref #2906.
|
||||
with shim():
|
||||
importlib.import_module('distutils')
|
||||
|
||||
# check that submodules load as expected
|
||||
core = importlib.import_module('distutils.core')
|
||||
assert '_distutils' in core.__file__, core.__file__
|
||||
assert 'setuptools._distutils.log' not in sys.modules
|
||||
|
||||
|
||||
def do_override():
|
||||
"""
|
||||
Ensure that the local copy of distutils is preferred over stdlib.
|
||||
|
||||
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
|
||||
for more motivation.
|
||||
"""
|
||||
if enabled():
|
||||
warn_distutils_present()
|
||||
ensure_local_distutils()
|
||||
|
||||
|
||||
class _TrivialRe:
|
||||
def __init__(self, *patterns):
|
||||
self._patterns = patterns
|
||||
|
||||
def match(self, string):
|
||||
return all(pat in string for pat in self._patterns)
|
||||
|
||||
|
||||
class DistutilsMetaFinder:
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
# optimization: only consider top level modules and those
|
||||
# found in the CPython test suite.
|
||||
if path is not None and not fullname.startswith('test.'):
|
||||
return
|
||||
|
||||
method_name = 'spec_for_{fullname}'.format(**locals())
|
||||
method = getattr(self, method_name, lambda: None)
|
||||
return method()
|
||||
|
||||
def spec_for_distutils(self):
|
||||
if self.is_cpython():
|
||||
return
|
||||
|
||||
import importlib
|
||||
import importlib.abc
|
||||
import importlib.util
|
||||
|
||||
try:
|
||||
mod = importlib.import_module('setuptools._distutils')
|
||||
except Exception:
|
||||
# There are a couple of cases where setuptools._distutils
|
||||
# may not be present:
|
||||
# - An older Setuptools without a local distutils is
|
||||
# taking precedence. Ref #2957.
|
||||
# - Path manipulation during sitecustomize removes
|
||||
# setuptools from the path but only after the hook
|
||||
# has been loaded. Ref #2980.
|
||||
# In either case, fall back to stdlib behavior.
|
||||
return
|
||||
|
||||
class DistutilsLoader(importlib.abc.Loader):
|
||||
def create_module(self, spec):
|
||||
mod.__name__ = 'distutils'
|
||||
return mod
|
||||
|
||||
def exec_module(self, module):
|
||||
pass
|
||||
|
||||
return importlib.util.spec_from_loader(
|
||||
'distutils', DistutilsLoader(), origin=mod.__file__
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def is_cpython():
|
||||
"""
|
||||
Suppress supplying distutils for CPython (build and tests).
|
||||
Ref #2965 and #3007.
|
||||
"""
|
||||
return os.path.isfile('pybuilddir.txt')
|
||||
|
||||
def spec_for_pip(self):
|
||||
"""
|
||||
Ensure stdlib distutils when running under pip.
|
||||
See pypa/pip#8761 for rationale.
|
||||
"""
|
||||
if self.pip_imported_during_build():
|
||||
return
|
||||
clear_distutils()
|
||||
self.spec_for_distutils = lambda: None
|
||||
|
||||
@classmethod
|
||||
def pip_imported_during_build(cls):
|
||||
"""
|
||||
Detect if pip is being imported in a build script. Ref #2355.
|
||||
"""
|
||||
import traceback
|
||||
|
||||
return any(
|
||||
cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def frame_file_is_setup(frame):
|
||||
"""
|
||||
Return True if the indicated frame suggests a setup.py file.
|
||||
"""
|
||||
# some frames may not have __file__ (#2940)
|
||||
return frame.f_globals.get('__file__', '').endswith('setup.py')
|
||||
|
||||
def spec_for_sensitive_tests(self):
|
||||
"""
|
||||
Ensure stdlib distutils when running select tests under CPython.
|
||||
|
||||
python/cpython#91169
|
||||
"""
|
||||
clear_distutils()
|
||||
self.spec_for_distutils = lambda: None
|
||||
|
||||
sensitive_tests = (
|
||||
[
|
||||
'test.test_distutils',
|
||||
'test.test_peg_generator',
|
||||
'test.test_importlib',
|
||||
]
|
||||
if sys.version_info < (3, 10)
|
||||
else [
|
||||
'test.test_distutils',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
for name in DistutilsMetaFinder.sensitive_tests:
|
||||
setattr(
|
||||
DistutilsMetaFinder,
|
||||
f'spec_for_{name}',
|
||||
DistutilsMetaFinder.spec_for_sensitive_tests,
|
||||
)
|
||||
|
||||
|
||||
DISTUTILS_FINDER = DistutilsMetaFinder()
|
||||
|
||||
|
||||
def add_shim():
|
||||
DISTUTILS_FINDER in sys.meta_path or insert_shim()
|
||||
|
||||
|
||||
class shim:
|
||||
def __enter__(self):
|
||||
insert_shim()
|
||||
|
||||
def __exit__(self, exc, value, tb):
|
||||
remove_shim()
|
||||
|
||||
|
||||
def insert_shim():
|
||||
sys.meta_path.insert(0, DISTUTILS_FINDER)
|
||||
|
||||
|
||||
def remove_shim():
|
||||
try:
|
||||
sys.meta_path.remove(DISTUTILS_FINDER)
|
||||
except ValueError:
|
||||
pass
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1 @@
|
||||
__import__('_distutils_hack').do_override()
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,123 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: aiohappyeyeballs
|
||||
Version: 2.6.2
|
||||
Summary: Happy Eyeballs for asyncio
|
||||
License: PSF-2.0
|
||||
License-File: LICENSE
|
||||
Author: J. Nick Koston
|
||||
Author-email: nick@koston.org
|
||||
Requires-Python: >=3.10
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Natural Language :: English
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Topic :: Software Development :: Libraries
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Classifier: License :: OSI Approved :: Python Software Foundation License
|
||||
Project-URL: Bug Tracker, https://github.com/aio-libs/aiohappyeyeballs/issues
|
||||
Project-URL: Changelog, https://github.com/aio-libs/aiohappyeyeballs/blob/main/CHANGELOG.md
|
||||
Project-URL: Documentation, https://aiohappyeyeballs.readthedocs.io
|
||||
Project-URL: Repository, https://github.com/aio-libs/aiohappyeyeballs
|
||||
Description-Content-Type: text/markdown
|
||||
|
||||
# aiohappyeyeballs
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/aio-libs/aiohappyeyeballs/actions/workflows/ci.yml?query=branch%3Amain">
|
||||
<img src="https://img.shields.io/github/actions/workflow/status/aio-libs/aiohappyeyeballs/ci-cd.yml?branch=main&label=CI&logo=github&style=flat-square" alt="CI Status" >
|
||||
</a>
|
||||
<a href="https://aiohappyeyeballs.readthedocs.io">
|
||||
<img src="https://img.shields.io/readthedocs/aiohappyeyeballs.svg?logo=read-the-docs&logoColor=fff&style=flat-square" alt="Documentation Status">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/aio-libs/aiohappyeyeballs">
|
||||
<img src="https://img.shields.io/codecov/c/github/aio-libs/aiohappyeyeballs.svg?logo=codecov&logoColor=fff&style=flat-square" alt="Test coverage percentage">
|
||||
</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://python-poetry.org/">
|
||||
<img src="https://img.shields.io/badge/packaging-poetry-299bd7?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAASCAYAAABrXO8xAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAJJSURBVHgBfZLPa1NBEMe/s7tNXoxW1KJQKaUHkXhQvHgW6UHQQ09CBS/6V3hKc/AP8CqCrUcpmop3Cx48eDB4yEECjVQrlZb80CRN8t6OM/teagVxYZi38+Yz853dJbzoMV3MM8cJUcLMSUKIE8AzQ2PieZzFxEJOHMOgMQQ+dUgSAckNXhapU/NMhDSWLs1B24A8sO1xrN4NECkcAC9ASkiIJc6k5TRiUDPhnyMMdhKc+Zx19l6SgyeW76BEONY9exVQMzKExGKwwPsCzza7KGSSWRWEQhyEaDXp6ZHEr416ygbiKYOd7TEWvvcQIeusHYMJGhTwF9y7sGnSwaWyFAiyoxzqW0PM/RjghPxF2pWReAowTEXnDh0xgcLs8l2YQmOrj3N7ByiqEoH0cARs4u78WgAVkoEDIDoOi3AkcLOHU60RIg5wC4ZuTC7FaHKQm8Hq1fQuSOBvX/sodmNJSB5geaF5CPIkUeecdMxieoRO5jz9bheL6/tXjrwCyX/UYBUcjCaWHljx1xiX6z9xEjkYAzbGVnB8pvLmyXm9ep+W8CmsSHQQY77Zx1zboxAV0w7ybMhQmfqdmmw3nEp1I0Z+FGO6M8LZdoyZnuzzBdjISicKRnpxzI9fPb+0oYXsNdyi+d3h9bm9MWYHFtPeIZfLwzmFDKy1ai3p+PDls1Llz4yyFpferxjnyjJDSEy9CaCx5m2cJPerq6Xm34eTrZt3PqxYO1XOwDYZrFlH1fWnpU38Y9HRze3lj0vOujZcXKuuXm3jP+s3KbZVra7y2EAAAAAASUVORK5CYII=" alt="Poetry">
|
||||
</a>
|
||||
<a href="https://github.com/astral-sh/ruff">
|
||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json" alt="Ruff">
|
||||
</a>
|
||||
<a href="https://github.com/pre-commit/pre-commit">
|
||||
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" alt="pre-commit">
|
||||
</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://pypi.org/project/aiohappyeyeballs/">
|
||||
<img src="https://img.shields.io/pypi/v/aiohappyeyeballs.svg?logo=python&logoColor=fff&style=flat-square" alt="PyPI Version">
|
||||
</a>
|
||||
<img src="https://img.shields.io/pypi/pyversions/aiohappyeyeballs.svg?style=flat-square&logo=python&logoColor=fff" alt="Supported Python versions">
|
||||
<img src="https://img.shields.io/pypi/l/aiohappyeyeballs.svg?style=flat-square" alt="License">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Documentation**: <a href="https://aiohappyeyeballs.readthedocs.io" target="_blank">https://aiohappyeyeballs.readthedocs.io </a>
|
||||
|
||||
**Source Code**: <a href="https://github.com/aio-libs/aiohappyeyeballs" target="_blank">https://github.com/aio-libs/aiohappyeyeballs </a>
|
||||
|
||||
---
|
||||
|
||||
[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs)
|
||||
([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html))
|
||||
|
||||
## Use case
|
||||
|
||||
This library exists to allow connecting with
|
||||
[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs)
|
||||
([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html))
|
||||
when you
|
||||
already have a list of addrinfo and not a DNS name.
|
||||
|
||||
The stdlib version of `loop.create_connection()`
|
||||
will only work when you pass in an unresolved name which
|
||||
is not a good fit when using DNS caching or resolving
|
||||
names via another method such as `zeroconf`.
|
||||
|
||||
## Installation
|
||||
|
||||
Install this via pip (or your favourite package manager):
|
||||
|
||||
`pip install aiohappyeyeballs`
|
||||
|
||||
## License
|
||||
|
||||
[aiohappyeyeballs is licensed under the same terms as cpython itself.](https://github.com/python/cpython/blob/main/LICENSE)
|
||||
|
||||
## Example usage
|
||||
|
||||
```python
|
||||
|
||||
addr_infos = await loop.getaddrinfo("example.org", 80)
|
||||
|
||||
socket = await start_connection(addr_infos)
|
||||
socket = await start_connection(addr_infos, local_addr_infos=local_addr_infos, happy_eyeballs_delay=0.2)
|
||||
|
||||
transport, protocol = await loop.create_connection(
|
||||
MyProtocol, sock=socket, ...)
|
||||
|
||||
# Remove the first address for each family from addr_info
|
||||
pop_addr_infos_interleave(addr_info, 1)
|
||||
|
||||
# Remove all matching address from addr_info
|
||||
remove_addr_infos(addr_info, "dead::beef::")
|
||||
|
||||
# Convert a local_addr to local_addr_infos
|
||||
local_addr_infos = addr_to_addr_infos(("127.0.0.1",0))
|
||||
```
|
||||
|
||||
## Credits
|
||||
|
||||
This package contains code from cpython and is licensed under the same terms as cpython itself.
|
||||
|
||||
This package was created with
|
||||
[Copier](https://copier.readthedocs.io/) and the
|
||||
[browniebroke/pypackage-template](https://github.com/browniebroke/pypackage-template)
|
||||
project template.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
aiohappyeyeballs-2.6.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
aiohappyeyeballs-2.6.2.dist-info/METADATA,sha256=cqs2VY8TwE2e_4qqnW409Si3suvj-aM-8dCiWG2Angk,5888
|
||||
aiohappyeyeballs-2.6.2.dist-info/RECORD,,
|
||||
aiohappyeyeballs-2.6.2.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
|
||||
aiohappyeyeballs-2.6.2.dist-info/licenses/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936
|
||||
aiohappyeyeballs/__init__.py,sha256=Af9ADZj3BWLfGaA7ITOFPlKIenh3ozSNWL3yezSZ2Jw,361
|
||||
aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc,,
|
||||
aiohappyeyeballs/__pycache__/_staggered.cpython-311.pyc,,
|
||||
aiohappyeyeballs/__pycache__/impl.cpython-311.pyc,,
|
||||
aiohappyeyeballs/__pycache__/types.cpython-311.pyc,,
|
||||
aiohappyeyeballs/__pycache__/utils.cpython-311.pyc,,
|
||||
aiohappyeyeballs/_staggered.py,sha256=aj3cSwHEDX88UMfO9bUau9tfrRAszhjg99dpEMiAOGM,6698
|
||||
aiohappyeyeballs/impl.py,sha256=TIkAK4xfACvKBp1s7DAKSobHefUTOC2HGE-n0tOthRk,9667
|
||||
aiohappyeyeballs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
aiohappyeyeballs/types.py,sha256=_8JmHFix6MeM1e7hRP7BleEaGy93GswGtzQv068zKY8,288
|
||||
aiohappyeyeballs/utils.py,sha256=dPAcNcrU_VhaTolTEEA94hgh9ONDN9_dYT4Xo9ORqQw,2922
|
||||
@@ -0,0 +1,4 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: poetry-core 2.4.0
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
@@ -0,0 +1,279 @@
|
||||
A. HISTORY OF THE SOFTWARE
|
||||
==========================
|
||||
|
||||
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||
as a successor of a language called ABC. Guido remains Python's
|
||||
principal author, although it includes many contributions from others.
|
||||
|
||||
In 1995, Guido continued his work on Python at the Corporation for
|
||||
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||
in Reston, Virginia where he released several versions of the
|
||||
software.
|
||||
|
||||
In May 2000, Guido and the Python core development team moved to
|
||||
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||
year, the PythonLabs team moved to Digital Creations, which became
|
||||
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||
https://www.python.org/psf/) was formed, a non-profit organization
|
||||
created specifically to own Python-related Intellectual Property.
|
||||
Zope Corporation was a sponsoring member of the PSF.
|
||||
|
||||
All Python releases are Open Source (see https://opensource.org for
|
||||
the Open Source Definition). Historically, most, but not all, Python
|
||||
releases have also been GPL-compatible; the table below summarizes
|
||||
the various releases.
|
||||
|
||||
Release Derived Year Owner GPL-
|
||||
from compatible? (1)
|
||||
|
||||
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||
1.6 1.5.2 2000 CNRI no
|
||||
2.0 1.6 2000 BeOpen.com no
|
||||
1.6.1 1.6 2001 CNRI yes (2)
|
||||
2.1 2.0+1.6.1 2001 PSF no
|
||||
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||
2.1.2 2.1.1 2002 PSF yes
|
||||
2.1.3 2.1.2 2002 PSF yes
|
||||
2.2 and above 2.1.1 2001-now PSF yes
|
||||
|
||||
Footnotes:
|
||||
|
||||
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||
a modified version without making your changes open source. The
|
||||
GPL-compatible licenses make it possible to combine Python with
|
||||
other software that is released under the GPL; the others don't.
|
||||
|
||||
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||
because its license has a choice of law clause. According to
|
||||
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||
is "not incompatible" with the GPL.
|
||||
|
||||
Thanks to the many outside volunteers who have worked under Guido's
|
||||
direction to make these releases possible.
|
||||
|
||||
|
||||
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||
===============================================================
|
||||
|
||||
Python software and documentation are licensed under the
|
||||
Python Software Foundation License Version 2.
|
||||
|
||||
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||
the documentation are dual licensed under the PSF License Version 2
|
||||
and the Zero-Clause BSD license.
|
||||
|
||||
Some software incorporated into Python is under different licenses.
|
||||
The licenses are listed with code falling under that license.
|
||||
|
||||
|
||||
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||
--------------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||
otherwise using this software ("Python") in source or binary form and
|
||||
its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||
distribute, and otherwise use Python alone or in any derivative version,
|
||||
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
|
||||
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
|
||||
All Rights Reserved" are retained in Python alone or in any derivative version
|
||||
prepared by Licensee.
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python.
|
||||
|
||||
4. PSF is making Python available to Licensee on an "AS IS"
|
||||
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. Nothing in this License Agreement shall be deemed to create any
|
||||
relationship of agency, partnership, or joint venture between PSF and
|
||||
Licensee. This License Agreement does not grant permission to use PSF
|
||||
trademarks or trade name in a trademark sense to endorse or promote
|
||||
products or services of Licensee, or any third party.
|
||||
|
||||
8. By copying, installing or otherwise using Python, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||
-------------------------------------------
|
||||
|
||||
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||
|
||||
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||
Individual or Organization ("Licensee") accessing and otherwise using
|
||||
this software in source or binary form and its associated
|
||||
documentation ("the Software").
|
||||
|
||||
2. Subject to the terms and conditions of this BeOpen Python License
|
||||
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||
and/or display publicly, prepare derivative works, distribute, and
|
||||
otherwise use the Software alone or in any derivative version,
|
||||
provided, however, that the BeOpen Python License is retained in the
|
||||
Software, alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
5. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
6. This License Agreement shall be governed by and interpreted in all
|
||||
respects by the law of the State of California, excluding conflict of
|
||||
law provisions. Nothing in this License Agreement shall be deemed to
|
||||
create any relationship of agency, partnership, or joint venture
|
||||
between BeOpen and Licensee. This License Agreement does not grant
|
||||
permission to use BeOpen trademarks or trade names in a trademark
|
||||
sense to endorse or promote products or services of Licensee, or any
|
||||
third party. As an exception, the "BeOpen Python" logos available at
|
||||
http://www.pythonlabs.com/logos.html may be used according to the
|
||||
permissions granted on that web page.
|
||||
|
||||
7. By copying, installing or otherwise using the software, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||
---------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||
source or binary form and its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||
license to reproduce, analyze, test, perform and/or display publicly,
|
||||
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||
alone or in any derivative version, provided, however, that CNRI's
|
||||
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||
Agreement, Licensee may substitute the following text (omitting the
|
||||
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||
conditions in CNRI's License Agreement. This Agreement together with
|
||||
Python 1.6.1 may be located on the internet using the following
|
||||
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||
Agreement may also be obtained from a proxy server on the internet
|
||||
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python 1.6.1.
|
||||
|
||||
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. This License Agreement shall be governed by the federal
|
||||
intellectual property law of the United States, including without
|
||||
limitation the federal copyright law, and, to the extent such
|
||||
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||
Virginia, excluding Virginia's conflict of law provisions.
|
||||
Notwithstanding the foregoing, with regard to derivative works based
|
||||
on Python 1.6.1 that incorporate non-separable material that was
|
||||
previously distributed under the GNU General Public License (GPL), the
|
||||
law of the Commonwealth of Virginia shall govern this License
|
||||
Agreement only as to issues arising under or with respect to
|
||||
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||
License Agreement shall be deemed to create any relationship of
|
||||
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||
License Agreement does not grant permission to use CNRI trademarks or
|
||||
trade name in a trademark sense to endorse or promote products or
|
||||
services of Licensee, or any third party.
|
||||
|
||||
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||
bound by the terms and conditions of this License Agreement.
|
||||
|
||||
ACCEPT
|
||||
|
||||
|
||||
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||
--------------------------------------------------
|
||||
|
||||
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||
The Netherlands. All rights reserved.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted,
|
||||
provided that the above copyright notice appear in all copies and that
|
||||
both that copyright notice and this permission notice appear in
|
||||
supporting documentation, and that the name of Stichting Mathematisch
|
||||
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||
distribution of the software without specific, written prior
|
||||
permission.
|
||||
|
||||
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
@@ -0,0 +1,14 @@
|
||||
__version__ = "2.6.2"
|
||||
|
||||
from .impl import start_connection
|
||||
from .types import AddrInfoType, SocketFactoryType
|
||||
from .utils import addr_to_addr_infos, pop_addr_infos_interleave, remove_addr_infos
|
||||
|
||||
__all__ = (
|
||||
"AddrInfoType",
|
||||
"SocketFactoryType",
|
||||
"addr_to_addr_infos",
|
||||
"pop_addr_infos_interleave",
|
||||
"remove_addr_infos",
|
||||
"start_connection",
|
||||
)
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,197 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
TypeVar,
|
||||
)
|
||||
|
||||
_T = TypeVar("_T")
|
||||
|
||||
RE_RAISE_EXCEPTIONS = (SystemExit, KeyboardInterrupt)
|
||||
|
||||
|
||||
def _set_result(wait_next: "asyncio.Future[None]") -> None:
|
||||
"""Set the result of a future if it is not already done."""
|
||||
if not wait_next.done():
|
||||
wait_next.set_result(None)
|
||||
|
||||
|
||||
async def _wait_one(
|
||||
futures: "Iterable[asyncio.Future[Any]]",
|
||||
loop: asyncio.AbstractEventLoop,
|
||||
) -> _T:
|
||||
"""Wait for the first future to complete."""
|
||||
wait_next = loop.create_future()
|
||||
|
||||
def _on_completion(fut: "asyncio.Future[Any]") -> None:
|
||||
if not wait_next.done():
|
||||
wait_next.set_result(fut)
|
||||
|
||||
for f in futures:
|
||||
f.add_done_callback(_on_completion)
|
||||
|
||||
try:
|
||||
return await wait_next
|
||||
finally:
|
||||
for f in futures:
|
||||
f.remove_done_callback(_on_completion)
|
||||
|
||||
|
||||
async def staggered_race(
|
||||
coro_fns: Iterable[Callable[[], Awaitable[_T]]],
|
||||
delay: float | None,
|
||||
*,
|
||||
loop: asyncio.AbstractEventLoop | None = None,
|
||||
) -> tuple[_T | None, int | None, list[BaseException | None]]:
|
||||
"""
|
||||
Run coroutines with staggered start times and take the first to finish.
|
||||
|
||||
This method takes an iterable of coroutine functions. The first one is
|
||||
started immediately. From then on, whenever the immediately preceding one
|
||||
fails (raises an exception), or when *delay* seconds has passed, the next
|
||||
coroutine is started. This continues until one of the coroutines complete
|
||||
successfully, in which case all others are cancelled, or until all
|
||||
coroutines fail.
|
||||
|
||||
The coroutines provided should be well-behaved in the following way:
|
||||
|
||||
* They should only ``return`` if completed successfully.
|
||||
|
||||
* They should always raise an exception if they did not complete
|
||||
successfully. In particular, if they handle cancellation, they should
|
||||
probably reraise, like this::
|
||||
|
||||
try:
|
||||
# do work
|
||||
except asyncio.CancelledError:
|
||||
# undo partially completed work
|
||||
raise
|
||||
|
||||
Args:
|
||||
----
|
||||
coro_fns: an iterable of coroutine functions, i.e. callables that
|
||||
return a coroutine object when called. Use ``functools.partial`` or
|
||||
lambdas to pass arguments.
|
||||
|
||||
delay: amount of time, in seconds, between starting coroutines. If
|
||||
``None``, the coroutines will run sequentially.
|
||||
|
||||
loop: the event loop to use. If ``None``, the running loop is used.
|
||||
|
||||
Returns:
|
||||
-------
|
||||
tuple *(winner_result, winner_index, exceptions)* where
|
||||
|
||||
- *winner_result*: the result of the winning coroutine, or ``None``
|
||||
if no coroutines won.
|
||||
|
||||
- *winner_index*: the index of the winning coroutine in
|
||||
``coro_fns``, or ``None`` if no coroutines won. If the winning
|
||||
coroutine may return None on success, *winner_index* can be used
|
||||
to definitively determine whether any coroutine won.
|
||||
|
||||
- *exceptions*: list of exceptions returned by the coroutines.
|
||||
``len(exceptions)`` is equal to the number of coroutines actually
|
||||
started, and the order is the same as in ``coro_fns``. The winning
|
||||
coroutine's entry is ``None``.
|
||||
|
||||
"""
|
||||
loop = loop or asyncio.get_running_loop()
|
||||
exceptions: list[BaseException | None] = []
|
||||
tasks: set[asyncio.Task[tuple[_T, int] | None]] = set()
|
||||
|
||||
async def run_one_coro(
|
||||
coro_fn: Callable[[], Awaitable[_T]],
|
||||
this_index: int,
|
||||
start_next: "asyncio.Future[None]",
|
||||
) -> tuple[_T, int] | None:
|
||||
"""
|
||||
Run a single coroutine.
|
||||
|
||||
If the coroutine fails, set the exception in the exceptions list and
|
||||
start the next coroutine by setting the result of the start_next.
|
||||
|
||||
If the coroutine succeeds, return the result and the index of the
|
||||
coroutine in the coro_fns list.
|
||||
|
||||
If SystemExit or KeyboardInterrupt is raised, re-raise it.
|
||||
"""
|
||||
try:
|
||||
result = await coro_fn()
|
||||
except RE_RAISE_EXCEPTIONS:
|
||||
raise
|
||||
except BaseException as e:
|
||||
exceptions[this_index] = e
|
||||
_set_result(start_next) # Kickstart the next coroutine
|
||||
return None
|
||||
|
||||
return result, this_index
|
||||
|
||||
start_next_timer: asyncio.TimerHandle | None = None
|
||||
start_next: asyncio.Future[None] | None
|
||||
task: asyncio.Task[tuple[_T, int] | None]
|
||||
done: asyncio.Future[None] | asyncio.Task[tuple[_T, int] | None]
|
||||
coro_iter = iter(coro_fns)
|
||||
this_index = -1
|
||||
try:
|
||||
while True:
|
||||
if coro_fn := next(coro_iter, None):
|
||||
this_index += 1
|
||||
exceptions.append(None)
|
||||
start_next = loop.create_future()
|
||||
task = loop.create_task(run_one_coro(coro_fn, this_index, start_next))
|
||||
tasks.add(task)
|
||||
start_next_timer = (
|
||||
loop.call_later(delay, _set_result, start_next) if delay else None
|
||||
)
|
||||
elif not tasks:
|
||||
# We exhausted the coro_fns list and no tasks are running
|
||||
# so we have no winner and all coroutines failed.
|
||||
break
|
||||
|
||||
while tasks or start_next:
|
||||
done = await _wait_one(
|
||||
(*tasks, start_next) if start_next else tasks, loop
|
||||
)
|
||||
if done is start_next:
|
||||
# The current task has failed or the timer has expired
|
||||
# so we need to start the next task.
|
||||
start_next = None
|
||||
if start_next_timer:
|
||||
start_next_timer.cancel()
|
||||
start_next_timer = None
|
||||
|
||||
# Break out of the task waiting loop to start the next
|
||||
# task.
|
||||
break
|
||||
|
||||
if TYPE_CHECKING:
|
||||
assert isinstance(done, asyncio.Task)
|
||||
|
||||
tasks.remove(done)
|
||||
if winner := done.result():
|
||||
return *winner, exceptions
|
||||
finally:
|
||||
# We either have:
|
||||
# - a winner
|
||||
# - all tasks failed
|
||||
# - a KeyboardInterrupt or SystemExit.
|
||||
|
||||
#
|
||||
# If the timer is still running, cancel it.
|
||||
#
|
||||
if start_next_timer:
|
||||
start_next_timer.cancel()
|
||||
|
||||
#
|
||||
# If there are any tasks left, cancel them and than
|
||||
# wait them so they fill the exceptions list.
|
||||
#
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
return None, None, exceptions
|
||||
@@ -0,0 +1,261 @@
|
||||
"""Base implementation."""
|
||||
|
||||
import asyncio
|
||||
import collections
|
||||
import contextlib
|
||||
import functools
|
||||
import itertools
|
||||
import socket
|
||||
from collections.abc import Sequence
|
||||
|
||||
from . import _staggered
|
||||
from .types import AddrInfoType, SocketFactoryType
|
||||
|
||||
|
||||
async def start_connection(
|
||||
addr_infos: Sequence[AddrInfoType],
|
||||
*,
|
||||
local_addr_infos: Sequence[AddrInfoType] | None = None,
|
||||
happy_eyeballs_delay: float | None = None,
|
||||
interleave: int | None = None,
|
||||
loop: asyncio.AbstractEventLoop | None = None,
|
||||
socket_factory: SocketFactoryType | None = None,
|
||||
) -> socket.socket:
|
||||
"""
|
||||
Connect to a TCP server.
|
||||
|
||||
Create a socket connection to a specified destination. The
|
||||
destination is specified as a list of AddrInfoType tuples as
|
||||
returned from getaddrinfo().
|
||||
|
||||
The arguments are, in order:
|
||||
|
||||
* ``family``: the address family, e.g. ``socket.AF_INET`` or
|
||||
``socket.AF_INET6``.
|
||||
* ``type``: the socket type, e.g. ``socket.SOCK_STREAM`` or
|
||||
``socket.SOCK_DGRAM``.
|
||||
* ``proto``: the protocol, e.g. ``socket.IPPROTO_TCP`` or
|
||||
``socket.IPPROTO_UDP``.
|
||||
* ``canonname``: the canonical name of the address, e.g.
|
||||
``"www.python.org"``.
|
||||
* ``sockaddr``: the socket address
|
||||
|
||||
This method is a coroutine which will try to establish the connection
|
||||
in the background. When successful, the coroutine returns a
|
||||
socket.
|
||||
|
||||
The expected use case is to use this method in conjunction with
|
||||
loop.create_connection() to establish a connection to a server::
|
||||
|
||||
socket = await start_connection(addr_infos)
|
||||
transport, protocol = await loop.create_connection(
|
||||
MyProtocol, sock=socket, ...)
|
||||
"""
|
||||
if not addr_infos:
|
||||
raise ValueError("addr_infos must not be empty")
|
||||
|
||||
current_loop = loop or asyncio.get_running_loop()
|
||||
|
||||
single_addr_info = len(addr_infos) == 1
|
||||
|
||||
if happy_eyeballs_delay is not None and interleave is None:
|
||||
# If using happy eyeballs, default to interleave addresses by family
|
||||
interleave = 1
|
||||
|
||||
if interleave and not single_addr_info:
|
||||
addr_infos = _interleave_addrinfos(addr_infos, interleave)
|
||||
|
||||
sock: socket.socket | None = None
|
||||
# uvloop can raise RuntimeError instead of OSError
|
||||
exceptions: list[list[OSError | RuntimeError]] = []
|
||||
if happy_eyeballs_delay is None or single_addr_info:
|
||||
# not using happy eyeballs
|
||||
for addrinfo in addr_infos:
|
||||
try:
|
||||
sock = await _connect_sock(
|
||||
current_loop,
|
||||
exceptions,
|
||||
addrinfo,
|
||||
local_addr_infos,
|
||||
None,
|
||||
socket_factory,
|
||||
)
|
||||
break
|
||||
except (RuntimeError, OSError):
|
||||
continue
|
||||
else: # using happy eyeballs
|
||||
open_sockets: set[socket.socket] = set()
|
||||
try:
|
||||
sock, _, _ = await _staggered.staggered_race(
|
||||
(
|
||||
functools.partial(
|
||||
_connect_sock,
|
||||
current_loop,
|
||||
exceptions,
|
||||
addrinfo,
|
||||
local_addr_infos,
|
||||
open_sockets,
|
||||
socket_factory,
|
||||
)
|
||||
for addrinfo in addr_infos
|
||||
),
|
||||
happy_eyeballs_delay,
|
||||
)
|
||||
finally:
|
||||
# If we have a winner, staggered_race will
|
||||
# cancel the other tasks, however there is a
|
||||
# small race window where any of the other tasks
|
||||
# can be done before they are cancelled which
|
||||
# will leave the socket open. To avoid this problem
|
||||
# we pass a set to _connect_sock to keep track of
|
||||
# the open sockets and close them here if there
|
||||
# are any "runner up" sockets.
|
||||
for s in open_sockets:
|
||||
if s is not sock:
|
||||
with contextlib.suppress(OSError):
|
||||
s.close()
|
||||
open_sockets = None # type: ignore[assignment]
|
||||
|
||||
if sock is None:
|
||||
all_exceptions = [exc for sub in exceptions for exc in sub]
|
||||
try:
|
||||
first_exception = all_exceptions[0]
|
||||
if len(all_exceptions) == 1:
|
||||
raise first_exception
|
||||
else:
|
||||
# If they all have the same str(), raise one.
|
||||
model = str(first_exception)
|
||||
if all(str(exc) == model for exc in all_exceptions):
|
||||
raise first_exception
|
||||
# Raise a combined exception so the user can see all
|
||||
# the various error messages.
|
||||
msg = "Multiple exceptions: {}".format(
|
||||
", ".join(str(exc) for exc in all_exceptions)
|
||||
)
|
||||
# If the errno is the same for all exceptions, raise
|
||||
# an OSError with that errno.
|
||||
if isinstance(first_exception, OSError):
|
||||
first_errno = first_exception.errno
|
||||
if all(
|
||||
isinstance(exc, OSError) and exc.errno == first_errno
|
||||
for exc in all_exceptions
|
||||
):
|
||||
raise OSError(first_errno, msg)
|
||||
elif isinstance(first_exception, RuntimeError) and all(
|
||||
isinstance(exc, RuntimeError) for exc in all_exceptions
|
||||
):
|
||||
raise RuntimeError(msg)
|
||||
# We have a mix of OSError and RuntimeError
|
||||
# so we have to pick which one to raise.
|
||||
# and we raise OSError for compatibility
|
||||
raise OSError(msg)
|
||||
finally:
|
||||
all_exceptions = None # type: ignore[assignment]
|
||||
exceptions = None # type: ignore[assignment]
|
||||
|
||||
return sock
|
||||
|
||||
|
||||
async def _connect_sock(
|
||||
loop: asyncio.AbstractEventLoop,
|
||||
exceptions: list[list[OSError | RuntimeError]],
|
||||
addr_info: AddrInfoType,
|
||||
local_addr_infos: Sequence[AddrInfoType] | None = None,
|
||||
open_sockets: set[socket.socket] | None = None,
|
||||
socket_factory: SocketFactoryType | None = None,
|
||||
) -> socket.socket:
|
||||
"""
|
||||
Create, bind and connect one socket.
|
||||
|
||||
If open_sockets is passed, add the socket to the set of open sockets.
|
||||
Any failure caught here will remove the socket from the set and close it.
|
||||
|
||||
Callers can use this set to close any sockets that are not the winner
|
||||
of all staggered tasks in the result there are runner up sockets aka
|
||||
multiple winners.
|
||||
"""
|
||||
my_exceptions: list[OSError | RuntimeError] = []
|
||||
exceptions.append(my_exceptions)
|
||||
family, type_, proto, _, address = addr_info
|
||||
sock = None
|
||||
try:
|
||||
if socket_factory is not None:
|
||||
sock = socket_factory(addr_info)
|
||||
else:
|
||||
sock = socket.socket(family=family, type=type_, proto=proto)
|
||||
if open_sockets is not None:
|
||||
open_sockets.add(sock)
|
||||
sock.setblocking(False)
|
||||
if local_addr_infos is not None:
|
||||
for lfamily, _, _, _, laddr in local_addr_infos:
|
||||
# skip local addresses of different family
|
||||
if lfamily != family:
|
||||
continue
|
||||
try:
|
||||
sock.bind(laddr)
|
||||
break
|
||||
except OSError as exc:
|
||||
msg = (
|
||||
f"error while attempting to bind on "
|
||||
f"address {laddr!r}: "
|
||||
f"{(exc.strerror or '').lower()}"
|
||||
)
|
||||
exc = OSError(exc.errno, msg)
|
||||
my_exceptions.append(exc)
|
||||
else: # all bind attempts failed
|
||||
if my_exceptions:
|
||||
raise my_exceptions.pop()
|
||||
else:
|
||||
raise OSError(f"no matching local address with {family=} found")
|
||||
await loop.sock_connect(sock, address)
|
||||
return sock
|
||||
except (RuntimeError, OSError) as exc:
|
||||
my_exceptions.append(exc)
|
||||
if sock is not None:
|
||||
if open_sockets is not None:
|
||||
open_sockets.remove(sock)
|
||||
try:
|
||||
sock.close()
|
||||
except OSError as e:
|
||||
my_exceptions.append(e)
|
||||
raise
|
||||
raise
|
||||
except:
|
||||
if sock is not None:
|
||||
if open_sockets is not None:
|
||||
open_sockets.remove(sock)
|
||||
try:
|
||||
sock.close()
|
||||
except OSError as e:
|
||||
my_exceptions.append(e)
|
||||
raise
|
||||
raise
|
||||
finally:
|
||||
exceptions = my_exceptions = None # type: ignore[assignment]
|
||||
|
||||
|
||||
def _interleave_addrinfos(
|
||||
addrinfos: Sequence[AddrInfoType], first_address_family_count: int = 1
|
||||
) -> list[AddrInfoType]:
|
||||
"""Interleave list of addrinfo tuples by family."""
|
||||
# Group addresses by family
|
||||
addrinfos_by_family: collections.OrderedDict[int, list[AddrInfoType]] = (
|
||||
collections.OrderedDict()
|
||||
)
|
||||
for addr in addrinfos:
|
||||
family = addr[0]
|
||||
if family not in addrinfos_by_family:
|
||||
addrinfos_by_family[family] = []
|
||||
addrinfos_by_family[family].append(addr)
|
||||
addrinfos_lists = list(addrinfos_by_family.values())
|
||||
|
||||
reordered: list[AddrInfoType] = []
|
||||
if first_address_family_count > 1:
|
||||
reordered.extend(addrinfos_lists[0][: first_address_family_count - 1])
|
||||
del addrinfos_lists[0][: first_address_family_count - 1]
|
||||
reordered.extend(
|
||||
a
|
||||
for a in itertools.chain.from_iterable(itertools.zip_longest(*addrinfos_lists))
|
||||
if a is not None
|
||||
)
|
||||
return reordered
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Types for aiohappyeyeballs."""
|
||||
|
||||
import socket
|
||||
from collections.abc import Callable
|
||||
|
||||
AddrInfoType = tuple[
|
||||
int | socket.AddressFamily,
|
||||
int | socket.SocketKind,
|
||||
int,
|
||||
str,
|
||||
tuple, # type: ignore[type-arg]
|
||||
]
|
||||
|
||||
SocketFactoryType = Callable[[AddrInfoType], socket.socket]
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Utility functions for aiohappyeyeballs."""
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
|
||||
from .types import AddrInfoType
|
||||
|
||||
|
||||
def addr_to_addr_infos(
|
||||
addr: tuple[str, int, int, int] | tuple[str, int, int] | tuple[str, int] | None,
|
||||
) -> list[AddrInfoType] | None:
|
||||
"""Convert an address tuple to a list of addr_info tuples."""
|
||||
if addr is None:
|
||||
return None
|
||||
host = addr[0]
|
||||
port = addr[1]
|
||||
is_ipv6 = ":" in host
|
||||
if is_ipv6:
|
||||
flowinfo = 0
|
||||
scopeid = 0
|
||||
addr_len = len(addr)
|
||||
if addr_len >= 4:
|
||||
scopeid = addr[3] # type: ignore[misc]
|
||||
if addr_len >= 3:
|
||||
flowinfo = addr[2] # type: ignore[misc]
|
||||
addr = (host, port, flowinfo, scopeid)
|
||||
family = socket.AF_INET6
|
||||
else:
|
||||
addr = (host, port)
|
||||
family = socket.AF_INET
|
||||
return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)]
|
||||
|
||||
|
||||
def pop_addr_infos_interleave(
|
||||
addr_infos: list[AddrInfoType], interleave: int | None = None
|
||||
) -> None:
|
||||
"""
|
||||
Pop addr_info from the list of addr_infos by family up to interleave times.
|
||||
|
||||
The interleave parameter is used to know how many addr_infos for
|
||||
each family should be popped of the top of the list.
|
||||
"""
|
||||
seen: dict[int, int] = {}
|
||||
if interleave is None:
|
||||
interleave = 1
|
||||
to_remove: list[AddrInfoType] = []
|
||||
for addr_info in addr_infos:
|
||||
family = addr_info[0]
|
||||
if family not in seen:
|
||||
seen[family] = 0
|
||||
if seen[family] < interleave:
|
||||
to_remove.append(addr_info)
|
||||
seen[family] += 1
|
||||
for addr_info in to_remove:
|
||||
addr_infos.remove(addr_info)
|
||||
|
||||
|
||||
def _addr_tuple_to_ip_address(
|
||||
addr: tuple[str, int] | tuple[str, int, int, int],
|
||||
) -> tuple[ipaddress.IPv4Address, int] | tuple[ipaddress.IPv6Address, int, int, int]:
|
||||
"""Convert an address tuple to an IPv4Address."""
|
||||
return (ipaddress.ip_address(addr[0]), *addr[1:])
|
||||
|
||||
|
||||
def remove_addr_infos(
|
||||
addr_infos: list[AddrInfoType],
|
||||
addr: tuple[str, int] | tuple[str, int, int, int],
|
||||
) -> None:
|
||||
"""
|
||||
Remove an address from the list of addr_infos.
|
||||
|
||||
The addr value is typically the return value of
|
||||
sock.getpeername().
|
||||
"""
|
||||
bad_addrs_infos: list[AddrInfoType] = []
|
||||
for addr_info in addr_infos:
|
||||
if addr_info[-1] == addr:
|
||||
bad_addrs_infos.append(addr_info)
|
||||
if bad_addrs_infos:
|
||||
for bad_addr_info in bad_addrs_infos:
|
||||
addr_infos.remove(bad_addr_info)
|
||||
return
|
||||
# Slow path in case addr is formatted differently
|
||||
match_addr = _addr_tuple_to_ip_address(addr)
|
||||
for addr_info in addr_infos:
|
||||
if match_addr == _addr_tuple_to_ip_address(addr_info[-1]):
|
||||
bad_addrs_infos.append(addr_info)
|
||||
if bad_addrs_infos:
|
||||
for bad_addr_info in bad_addrs_infos:
|
||||
addr_infos.remove(bad_addr_info)
|
||||
return
|
||||
raise ValueError(f"Address {addr} not found in addr_infos")
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,257 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: aiohttp
|
||||
Version: 3.14.1
|
||||
Summary: Async http client/server framework (asyncio)
|
||||
Maintainer-email: aiohttp team <team@aiohttp.org>
|
||||
License: Apache-2.0 AND MIT
|
||||
Project-URL: Homepage, https://github.com/aio-libs/aiohttp
|
||||
Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org
|
||||
Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org
|
||||
Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
|
||||
Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp
|
||||
Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html
|
||||
Project-URL: Docs: RTD, https://docs.aiohttp.org
|
||||
Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues
|
||||
Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Framework :: AsyncIO
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Operating System :: POSIX
|
||||
Classifier: Operating System :: MacOS :: MacOS X
|
||||
Classifier: Operating System :: Microsoft :: Windows
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Classifier: Programming Language :: Python :: 3.14
|
||||
Classifier: Topic :: Internet :: WWW/HTTP
|
||||
Requires-Python: >=3.10
|
||||
Description-Content-Type: text/x-rst
|
||||
License-File: LICENSE.txt
|
||||
License-File: vendor/llhttp/LICENSE
|
||||
Requires-Dist: aiohappyeyeballs>=2.5.0
|
||||
Requires-Dist: aiosignal>=1.4.0
|
||||
Requires-Dist: async-timeout<6.0,>=4.0; python_version < "3.11"
|
||||
Requires-Dist: attrs>=17.3.0
|
||||
Requires-Dist: frozenlist>=1.1.1
|
||||
Requires-Dist: multidict<7.0,>=4.5
|
||||
Requires-Dist: propcache>=0.2.0
|
||||
Requires-Dist: typing_extensions>=4.4; python_version < "3.13"
|
||||
Requires-Dist: yarl<2.0,>=1.17.0
|
||||
Provides-Extra: speedups
|
||||
Requires-Dist: aiodns>=3.3.0; (sys_platform != "android" and sys_platform != "ios") and extra == "speedups"
|
||||
Requires-Dist: Brotli>=1.2; (platform_python_implementation == "CPython" and sys_platform != "android" and sys_platform != "ios") and extra == "speedups"
|
||||
Requires-Dist: brotlicffi>=1.2; platform_python_implementation != "CPython" and extra == "speedups"
|
||||
Requires-Dist: backports.zstd; (platform_python_implementation == "CPython" and python_version < "3.14" and sys_platform != "android" and sys_platform != "ios") and extra == "speedups"
|
||||
Dynamic: license-file
|
||||
|
||||
==================================
|
||||
Async http client/server framework
|
||||
==================================
|
||||
|
||||
.. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg
|
||||
:height: 64px
|
||||
:width: 64px
|
||||
:alt: aiohttp logo
|
||||
|
||||
|
|
||||
|
||||
.. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg
|
||||
:target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
|
||||
:alt: GitHub Actions status for master branch
|
||||
|
||||
.. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg
|
||||
:target: https://codecov.io/gh/aio-libs/aiohttp
|
||||
:alt: codecov.io status for master branch
|
||||
|
||||
.. image:: https://badge.fury.io/py/aiohttp.svg
|
||||
:target: https://pypi.org/project/aiohttp
|
||||
:alt: Latest PyPI package version
|
||||
|
||||
.. image:: https://img.shields.io/pypi/dm/aiohttp
|
||||
:target: https://pypistats.org/packages/aiohttp
|
||||
:alt: Downloads count
|
||||
|
||||
.. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest
|
||||
:target: https://docs.aiohttp.org/
|
||||
:alt: Latest Read The Docs
|
||||
|
||||
.. image:: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json
|
||||
:target: https://codspeed.io/aio-libs/aiohttp
|
||||
:alt: Codspeed.io status for aiohttp
|
||||
|
||||
|
||||
Key Features
|
||||
============
|
||||
|
||||
- Supports both client and server side of HTTP protocol.
|
||||
- Supports both client and server Web-Sockets out-of-the-box and avoids
|
||||
Callback Hell.
|
||||
- Provides Web-server with middleware and pluggable routing.
|
||||
|
||||
|
||||
Getting started
|
||||
===============
|
||||
|
||||
Client
|
||||
------
|
||||
|
||||
To get something from the web:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import aiohttp
|
||||
import asyncio
|
||||
|
||||
async def main():
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get('http://python.org') as response:
|
||||
|
||||
print("Status:", response.status)
|
||||
print("Content-type:", response.headers['content-type'])
|
||||
|
||||
html = await response.text()
|
||||
print("Body:", html[:15], "...")
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
This prints:
|
||||
|
||||
.. code-block::
|
||||
|
||||
Status: 200
|
||||
Content-type: text/html; charset=utf-8
|
||||
Body: <!doctype html> ...
|
||||
|
||||
Coming from `requests <https://requests.readthedocs.io/>`_ ? Read `why we need so many lines <https://aiohttp.readthedocs.io/en/latest/http_request_lifecycle.html>`_.
|
||||
|
||||
Server
|
||||
------
|
||||
|
||||
An example using a simple server:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# examples/server_simple.py
|
||||
from aiohttp import web
|
||||
|
||||
async def handle(request):
|
||||
name = request.match_info.get('name', "Anonymous")
|
||||
text = "Hello, " + name
|
||||
return web.Response(text=text)
|
||||
|
||||
async def wshandle(request):
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
|
||||
async for msg in ws:
|
||||
if msg.type == web.WSMsgType.text:
|
||||
await ws.send_str("Hello, {}".format(msg.data))
|
||||
elif msg.type == web.WSMsgType.binary:
|
||||
await ws.send_bytes(msg.data)
|
||||
elif msg.type == web.WSMsgType.close:
|
||||
break
|
||||
|
||||
return ws
|
||||
|
||||
|
||||
app = web.Application()
|
||||
app.add_routes([web.get('/', handle),
|
||||
web.get('/echo', wshandle),
|
||||
web.get('/{name}', handle)])
|
||||
|
||||
if __name__ == '__main__':
|
||||
web.run_app(app)
|
||||
|
||||
|
||||
Documentation
|
||||
=============
|
||||
|
||||
https://aiohttp.readthedocs.io/
|
||||
|
||||
|
||||
Demos
|
||||
=====
|
||||
|
||||
https://github.com/aio-libs/aiohttp-demos
|
||||
|
||||
|
||||
External links
|
||||
==============
|
||||
|
||||
* `Third party libraries
|
||||
<http://aiohttp.readthedocs.io/en/latest/third_party.html>`_
|
||||
* `Built with aiohttp
|
||||
<http://aiohttp.readthedocs.io/en/latest/built_with.html>`_
|
||||
* `Powered by aiohttp
|
||||
<http://aiohttp.readthedocs.io/en/latest/powered_by.html>`_
|
||||
|
||||
Feel free to make a Pull Request for adding your link to these pages!
|
||||
|
||||
|
||||
Communication channels
|
||||
======================
|
||||
|
||||
*aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions
|
||||
|
||||
*Matrix*: `#aio-libs:matrix.org <https://matrix.to/#/#aio-libs:matrix.org>`_
|
||||
|
||||
We support `Stack Overflow
|
||||
<https://stackoverflow.com/questions/tagged/aiohttp>`_.
|
||||
Please add *aiohttp* tag to your question there.
|
||||
|
||||
Requirements
|
||||
============
|
||||
|
||||
- attrs_
|
||||
- multidict_
|
||||
- yarl_
|
||||
- frozenlist_
|
||||
|
||||
Optionally you may install the aiodns_ library (highly recommended for sake of speed).
|
||||
|
||||
.. _aiodns: https://pypi.python.org/pypi/aiodns
|
||||
.. _attrs: https://github.com/python-attrs/attrs
|
||||
.. _multidict: https://pypi.python.org/pypi/multidict
|
||||
.. _frozenlist: https://pypi.org/project/frozenlist/
|
||||
.. _yarl: https://pypi.python.org/pypi/yarl
|
||||
.. _async-timeout: https://pypi.python.org/pypi/async_timeout
|
||||
|
||||
|
||||
Keepsafe
|
||||
========
|
||||
|
||||
The aiohttp community would like to thank Keepsafe
|
||||
(https://www.getkeepsafe.com) for its support in the early days of
|
||||
the project.
|
||||
|
||||
|
||||
Source code
|
||||
===========
|
||||
|
||||
The latest developer version is available in a GitHub repository:
|
||||
https://github.com/aio-libs/aiohttp
|
||||
|
||||
Benchmarks
|
||||
==========
|
||||
|
||||
If you are interested in efficiency, the AsyncIO community maintains a
|
||||
list of benchmarks on the official wiki:
|
||||
https://github.com/python/asyncio/wiki/Benchmarks
|
||||
|
||||
--------
|
||||
|
||||
.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
|
||||
:target: https://matrix.to/#/%23aio-libs:matrix.org
|
||||
:alt: Matrix Room — #aio-libs:matrix.org
|
||||
|
||||
.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat
|
||||
:target: https://matrix.to/#/%23aio-libs-space:matrix.org
|
||||
:alt: Matrix Space — #aio-libs-space:matrix.org
|
||||
|
||||
.. image:: https://insights.linuxfoundation.org/api/badge/health-score?project=aiohttp
|
||||
:target: https://insights.linuxfoundation.org/project/aiohttp
|
||||
:alt: LFX Health Score
|
||||
@@ -0,0 +1,139 @@
|
||||
aiohttp-3.14.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
aiohttp-3.14.1.dist-info/METADATA,sha256=lSrt4tDtmd7yhoDSTEq0NNoU8cSDjfDJAuOCCHWKil0,8262
|
||||
aiohttp-3.14.1.dist-info/RECORD,,
|
||||
aiohttp-3.14.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
aiohttp-3.14.1.dist-info/WHEEL,sha256=M5wZqvm0RPz434ksvS2jyqHKJ9fsZFXCH8JlrvbFuNs,190
|
||||
aiohttp-3.14.1.dist-info/licenses/LICENSE.txt,sha256=Lkvl_GxMcqRm_LZl1ybgSaaJGYH-U2xPBLY2Z0lGHSM,11313
|
||||
aiohttp-3.14.1.dist-info/licenses/vendor/llhttp/LICENSE,sha256=YoFo1ou1qKF-C777O9dOMm4e3CBYPXb1L0V8gskhhn0,1069
|
||||
aiohttp-3.14.1.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8
|
||||
aiohttp/.hash/_cparser.pxd.hash,sha256=1xYKvgB1DahaZj6GMSLJ9qi5KmoJDD8ZPp3CIxah0ig,121
|
||||
aiohttp/.hash/_find_header.pxd.hash,sha256=_mbpD6vM-CVCKq3ulUvsOAz5Wdo88wrDzfpOsMQaMNA,125
|
||||
aiohttp/.hash/_http_parser.pyx.hash,sha256=D15N0PIazROldZ2ezxeuuu4VuQP9OxrN8sutpdcL6TA,125
|
||||
aiohttp/.hash/_http_writer.pyx.hash,sha256=eqqhtJepEtpikWbd_gUoZOWyEBUwmHCd1fq2jfIrXSg,125
|
||||
aiohttp/.hash/hdrs.py.hash,sha256=cBtTPqXxWpYN--0v2ukVWjjfVbnT3Csii1PkBJBCz8E,116
|
||||
aiohttp/__init__.py,sha256=1dDCbOmlrF1FnB_LRnU-jVKY1XngQ9guX1ZasoTH-TY,8339
|
||||
aiohttp/__pycache__/__init__.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/_cookie_helpers.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/abc.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/base_protocol.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client_exceptions.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client_middleware_digest_auth.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client_middlewares.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client_proto.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client_reqrep.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/client_ws.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/compression_utils.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/connector.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/cookiejar.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/formdata.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/hdrs.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/helpers.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/http.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/http_exceptions.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/http_parser.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/http_websocket.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/http_writer.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/log.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/multipart.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/payload.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/payload_streamer.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/pytest_plugin.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/resolver.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/streams.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/tcp_helpers.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/test_utils.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/tracing.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/typedefs.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_app.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_exceptions.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_fileresponse.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_log.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_middlewares.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_protocol.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_request.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_response.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_routedef.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_runner.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_server.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/web_ws.cpython-311.pyc,,
|
||||
aiohttp/__pycache__/worker.cpython-311.pyc,,
|
||||
aiohttp/_cookie_helpers.py,sha256=uOe8v5yx9N9N2JHFJiQOjuN2SiIV7D1lxnTfrXc6oEU,14092
|
||||
aiohttp/_cparser.pxd,sha256=nvnwTkOaMAIazM-OUB6H66LpsNNeUG3nFxbSSLQoQEM,4336
|
||||
aiohttp/_find_header.pxd,sha256=0GfwFCPN2zxEKTO1_MA5sYq2UfzsG8kcV3aTqvwlz3g,68
|
||||
aiohttp/_headers.pxi,sha256=n701k28dVPjwRnx5j6LpJhLTfj7dqu2vJt7f0O60Oyg,2007
|
||||
aiohttp/_http_parser.cpython-311-x86_64-linux-gnu.so,sha256=WUGz4lLZe8Hq1WpaBWjgFc7Uq1UYdmvl8YLn3aL0MKY,2913832
|
||||
aiohttp/_http_parser.pyx,sha256=mNLUenKTRZkNlXXc9oxVDeXVJ31gsrI4XR69jrDWxPw,33860
|
||||
aiohttp/_http_writer.cpython-311-x86_64-linux-gnu.so,sha256=F5TEKHD28_o55LurAqvMT8oK0ud7vAgUb-mNaO2CTyE,455168
|
||||
aiohttp/_http_writer.pyx,sha256=FmhqRLv-qyvL2BJvVwk128VFqwYMb1b1vHLPCt3awXA,4823
|
||||
aiohttp/_websocket/.hash/mask.pxd.hash,sha256=Y0zBddk_ck3pi9-BFzMcpkcvCKvwvZ4GTtZFb9u1nxQ,128
|
||||
aiohttp/_websocket/.hash/mask.pyx.hash,sha256=90owpXYM8_kIma4KUcOxhWSk-Uv4NVMBoCYeFM1B3d0,128
|
||||
aiohttp/_websocket/.hash/reader_c.pxd.hash,sha256=DM51AsKpHR3Bl2EIx0eUSy1uvusTDfylNeRCMT66erk,132
|
||||
aiohttp/_websocket/__init__.py,sha256=Mar3R9_vBN_Ea4lsW7iTAVXD7OKswKPGqF5xgSyt77k,44
|
||||
aiohttp/_websocket/__pycache__/__init__.cpython-311.pyc,,
|
||||
aiohttp/_websocket/__pycache__/helpers.cpython-311.pyc,,
|
||||
aiohttp/_websocket/__pycache__/models.cpython-311.pyc,,
|
||||
aiohttp/_websocket/__pycache__/reader.cpython-311.pyc,,
|
||||
aiohttp/_websocket/__pycache__/reader_c.cpython-311.pyc,,
|
||||
aiohttp/_websocket/__pycache__/reader_py.cpython-311.pyc,,
|
||||
aiohttp/_websocket/__pycache__/writer.cpython-311.pyc,,
|
||||
aiohttp/_websocket/helpers.py,sha256=lMDbpiZefmHTGNxjpe6K09ZlF048KxzcOvbh-ZYqvg0,5026
|
||||
aiohttp/_websocket/mask.cpython-311-x86_64-linux-gnu.so,sha256=P3O6pZ1iNQF9ePhc15tyVjA8BBSOwN477q5xGdh7EJ8,229856
|
||||
aiohttp/_websocket/mask.pxd,sha256=sBmZ1Amym9kW4Ge8lj1fLZ7mPPya4LzLdpkQExQXv5M,112
|
||||
aiohttp/_websocket/mask.pyx,sha256=BHjOtV0O0w7xp9p0LNADRJvGmgfPn9sGeJvSs0fL__4,1397
|
||||
aiohttp/_websocket/models.py,sha256=gJLskxkUKakYFsVMdjOclSjt41rQWRCL4RfRB_wmwO0,2952
|
||||
aiohttp/_websocket/reader.py,sha256=eC4qS0c5sOeQ2ebAHLaBpIaTVFaSKX79pY2xvh3Pqyw,1030
|
||||
aiohttp/_websocket/reader_c.cpython-311-x86_64-linux-gnu.so,sha256=8lf3gcF6jhUrKI8ltvHJCy5Y6-tntzPBh9AzBTSsgjg,1832944
|
||||
aiohttp/_websocket/reader_c.pxd,sha256=l-ODGpJpOx4FxpsCtkRyITmmRvBlRo8mv87qNgeQZbo,2683
|
||||
aiohttp/_websocket/reader_c.py,sha256=vf7Y6JB6hpLE17OQ39IhO70ga_DXFYksfv45M5n1wOU,20073
|
||||
aiohttp/_websocket/reader_py.py,sha256=vf7Y6JB6hpLE17OQ39IhO70ga_DXFYksfv45M5n1wOU,20073
|
||||
aiohttp/_websocket/writer.py,sha256=JA4ejOQMCvAvIXe_0f6uRx_aGSO4-zVUc1HJBZ125ak,11259
|
||||
aiohttp/abc.py,sha256=KvpM3wDEWl_iIdNQX3NEnJf3pYAtgxynAvp5s4JkNrU,7536
|
||||
aiohttp/base_protocol.py,sha256=bL6dSlNacbmln20Plez_gqYXTcFeg-V1hkHVDk4s8vU,4688
|
||||
aiohttp/client.py,sha256=PzaLAKgPMytcA75z1ZIEjTBzTWR3U7wT66f38OKTwmI,64312
|
||||
aiohttp/client_exceptions.py,sha256=XvJ57ppYs2IubcY3efBUkSpPElwQDqt3SWU_yssvjyI,11609
|
||||
aiohttp/client_middleware_digest_auth.py,sha256=Z8ufMnBF8RQ_JaVfG3bUbAoRua_kC7RSIexQM2zm9wQ,19042
|
||||
aiohttp/client_middlewares.py,sha256=kP5N9CMzQPMGPIEydeVUiLUTLsw8Vl8Gr4qAWYdu3vM,1918
|
||||
aiohttp/client_proto.py,sha256=u6AZU05mZxAFG4saTaxn5lVN9vy4cmgvF9k7HQG260A,12633
|
||||
aiohttp/client_reqrep.py,sha256=RWyXzuIi0NETNeuNADMbWPGd-mxcpVLsVQM0N582pU8,54704
|
||||
aiohttp/client_ws.py,sha256=PiMLbWN6IBEXGiWuqL1KyQqIAydDGsWMitX_pd8cjLo,19468
|
||||
aiohttp/compression_utils.py,sha256=_HTGK9dZOojGd4kyrk2A5yAt1pzVyKJh4AH5eVH0DQ8,15840
|
||||
aiohttp/connector.py,sha256=0iYWUWjhc8zDYwWd-J4mtfhjojzGRRcbnQbnuwY-njU,70036
|
||||
aiohttp/cookiejar.py,sha256=Y80b6_hSiDi4lN0iOb3X5983VONf-i4GhRH447gzTr0,25815
|
||||
aiohttp/formdata.py,sha256=zRWW2ODYkWeahDOd-hwra-__EUizdB2bf6hAMgkCKhc,6514
|
||||
aiohttp/hdrs.py,sha256=pGrWw6L6-NJqLGr8GiIQzjeaI_J5n857JqAfbOWkBkI,5106
|
||||
aiohttp/helpers.py,sha256=dSbEmGl8XsLU2zwmD0dyp4wHHvHrH5TFaofkSH-OmsA,33017
|
||||
aiohttp/http.py,sha256=CHXxFtOXK85RNijYkfpjvjCbKlJc3hIGRsCFAnh83hk,2077
|
||||
aiohttp/http_exceptions.py,sha256=I1nyopt1sYV0GqpW2ra4pnCmFcOqMoDC4dELghEk2lI,3115
|
||||
aiohttp/http_parser.py,sha256=nrXK1evVj04TjpbOu4tOx4w0yUlzG2PaEFxq0wvmfNY,45170
|
||||
aiohttp/http_websocket.py,sha256=8jVNshtgNPSDnab0Dc1lAO7HFvtT7y79eZKjUXX6e28,983
|
||||
aiohttp/http_writer.py,sha256=bXHXXWkEnySdYX3cCmYCFgNFsnxwPNCs-0nMjSPDRAo,12602
|
||||
aiohttp/log.py,sha256=BbNKx9e3VMIm0xYjZI0IcBBoS7wjdeIeSaiJE7-qK2g,325
|
||||
aiohttp/multipart.py,sha256=CJB4szZ8Zhv4htswXvSDfwY8HjlVGZFyvzGXIYo7b50,44179
|
||||
aiohttp/payload.py,sha256=MXcl_K0gcblkN_YFXE_Up6N7IQwjH8uM4HTfn9Axbmg,41480
|
||||
aiohttp/payload_streamer.py,sha256=PGqJKt_1ca_7i6p1UgU8jrpO1toOt5EQDQMOK9LjtV4,2225
|
||||
aiohttp/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
|
||||
aiohttp/pytest_plugin.py,sha256=eGhRoy0TKNOQ3mtabkpoMgt0JThnVDr406h_kyZkQe8,12976
|
||||
aiohttp/resolver.py,sha256=jmrAUnhayFdSjTsCt2_coosdVmc5RgEB5Agr65Q0sQk,9954
|
||||
aiohttp/streams.py,sha256=k-XDoAfb3P8t5sHvWyEONXzYHoZ4JmJYr_aZB9CQF6c,24127
|
||||
aiohttp/tcp_helpers.py,sha256=BSadqVWaBpMFDRWnhaaR941N9MiDZ7bdTrxgCb0CW-M,961
|
||||
aiohttp/test_utils.py,sha256=RqqoQTTI4VpZDvOcLMmQgxisuRMCIX0qOjG019EtEpM,24636
|
||||
aiohttp/tracing.py,sha256=4mokNTKdX5YuoSrvVnG4D7WTPMwe-UlYHVYxQjRv4Fw,14500
|
||||
aiohttp/typedefs.py,sha256=I-V6S4T73fI_wkJfBYiL7otEeRvVHmSdsk-YYPR6Fj0,1672
|
||||
aiohttp/web.py,sha256=gsyxRSPWV3iZjPUbOR3dIGcp1jm2ltBtXwkPh91co3Q,18426
|
||||
aiohttp/web_app.py,sha256=hmT_DWXKwHMqmFBLE8JHhevLaaTST73ikovIIx_Tw6k,19379
|
||||
aiohttp/web_exceptions.py,sha256=CsEG88dQINYSFpklCE_7bZgL1IVjHoy5dlTSVQGHPRQ,10354
|
||||
aiohttp/web_fileresponse.py,sha256=5vlf-OmfgFxG5O1zGrzk-SPRkbs58izLlbQldT-DHXE,16404
|
||||
aiohttp/web_log.py,sha256=lJCDsZ2xJp7HqSuijaTZyqxJ0oNWPhwxJE1FVGUWwWU,8487
|
||||
aiohttp/web_middlewares.py,sha256=OIfnnCHJgRnKjzDjHoc_VzNcLuVf9y8kv5aTzM2VGvc,4152
|
||||
aiohttp/web_protocol.py,sha256=RyGK7u4Lpl8yC2rSbHcKiYhSDbKSbHuA-GZTaN8q-RY,31092
|
||||
aiohttp/web_request.py,sha256=o99Os7_M_C4poSc58el9q44VGO6VctJaJMFKhi7F6R8,31867
|
||||
aiohttp/web_response.py,sha256=7EjxpTW4a6du5X0utXenUbSO6fbY_MgfINppJUEre-M,30783
|
||||
aiohttp/web_routedef.py,sha256=S_uRfJ87LCM_fFTAIrqYTWiIqDAk0pLLYdUr1vGU9BM,6057
|
||||
aiohttp/web_runner.py,sha256=PGUdZs_d2qzM3Tnb6yCQQoxfwqQZFuVr_NGIJBZq9Ms,12708
|
||||
aiohttp/web_server.py,sha256=LawT47SJuLSIYgkAWL_haFgH6lVyuoD3zyFTvBatvsE,3170
|
||||
aiohttp/web_urldispatcher.py,sha256=lc9Cou6tP8YJTJS2MEQWVcJV9C5dFKTyhdCLjLtkOzU,43893
|
||||
aiohttp/web_ws.py,sha256=fqE-c95dxvwkZfm8M-vKeP5pCteHCmrhAdI-1o4J348,27455
|
||||
aiohttp/worker.py,sha256=osuMCad7kBmL7FeR6EEEdsfkDqOaBDYvAzHMgW_hsIc,8506
|
||||
@@ -0,0 +1,7 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: setuptools (82.0.1)
|
||||
Root-Is-Purelib: false
|
||||
Tag: cp311-cp311-manylinux_2_17_x86_64
|
||||
Tag: cp311-cp311-manylinux2014_x86_64
|
||||
Tag: cp311-cp311-manylinux_2_28_x86_64
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright aio-libs contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright © 2018 Fedor Indutny
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included
|
||||
in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
aiohttp
|
||||
@@ -0,0 +1 @@
|
||||
9ef9f04e439a30021acccf8e501e87eba2e9b0d35e506de71716d248b4284043 /home/runner/work/aiohttp/aiohttp/aiohttp/_cparser.pxd
|
||||
@@ -0,0 +1 @@
|
||||
d067f01423cddb3c442933b5fcc039b18ab651fcec1bc91c577693aafc25cf78 /home/runner/work/aiohttp/aiohttp/aiohttp/_find_header.pxd
|
||||
@@ -0,0 +1 @@
|
||||
98d2d47a729345990d9575dcf68c550de5d5277d60b2b2385d1ebd8eb0d6c4fc /home/runner/work/aiohttp/aiohttp/aiohttp/_http_parser.pyx
|
||||
@@ -0,0 +1 @@
|
||||
16686a44bbfeab2bcbd8126f570935dbc545ab060c6f56f5bc72cf0adddac170 /home/runner/work/aiohttp/aiohttp/aiohttp/_http_writer.pyx
|
||||
@@ -0,0 +1 @@
|
||||
a46ad6c3a2faf8d26a2c6afc1a2210ce379a23f2799fce7b26a01f6ce5a40642 /home/runner/work/aiohttp/aiohttp/aiohttp/hdrs.py
|
||||
@@ -0,0 +1,279 @@
|
||||
__version__ = "3.14.1"
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from . import hdrs as hdrs
|
||||
from .client import (
|
||||
BaseConnector,
|
||||
ClientConnectionError,
|
||||
ClientConnectionResetError,
|
||||
ClientConnectorCertificateError,
|
||||
ClientConnectorDNSError,
|
||||
ClientConnectorError,
|
||||
ClientConnectorSSLError,
|
||||
ClientError,
|
||||
ClientHttpProxyError,
|
||||
ClientOSError,
|
||||
ClientPayloadError,
|
||||
ClientProxyConnectionError,
|
||||
ClientRequest,
|
||||
ClientResponse,
|
||||
ClientResponseError,
|
||||
ClientSession,
|
||||
ClientSSLError,
|
||||
ClientTimeout,
|
||||
ClientWebSocketResponse,
|
||||
ClientWSTimeout,
|
||||
ConnectionTimeoutError,
|
||||
ContentTypeError,
|
||||
Fingerprint,
|
||||
InvalidURL,
|
||||
InvalidUrlClientError,
|
||||
InvalidUrlRedirectClientError,
|
||||
NamedPipeConnector,
|
||||
NonHttpUrlClientError,
|
||||
NonHttpUrlRedirectClientError,
|
||||
RedirectClientError,
|
||||
RequestInfo,
|
||||
ServerConnectionError,
|
||||
ServerDisconnectedError,
|
||||
ServerFingerprintMismatch,
|
||||
ServerTimeoutError,
|
||||
SocketTimeoutError,
|
||||
TCPConnector,
|
||||
TooManyRedirects,
|
||||
UnixConnector,
|
||||
WSMessageTypeError,
|
||||
WSServerHandshakeError,
|
||||
request,
|
||||
)
|
||||
from .client_middleware_digest_auth import DigestAuthMiddleware
|
||||
from .client_middlewares import ClientHandlerType, ClientMiddlewareType
|
||||
from .compression_utils import set_zlib_backend
|
||||
from .connector import (
|
||||
AddrInfoType as AddrInfoType,
|
||||
SocketFactoryType as SocketFactoryType,
|
||||
)
|
||||
from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar
|
||||
from .formdata import FormData as FormData
|
||||
from .helpers import BasicAuth, ChainMapProxy, ETag, encode_basic_auth
|
||||
from .http import (
|
||||
HttpVersion as HttpVersion,
|
||||
HttpVersion10 as HttpVersion10,
|
||||
HttpVersion11 as HttpVersion11,
|
||||
WebSocketError as WebSocketError,
|
||||
WSCloseCode as WSCloseCode,
|
||||
WSMessage as WSMessage,
|
||||
WSMsgType as WSMsgType,
|
||||
)
|
||||
from .multipart import (
|
||||
BadContentDispositionHeader as BadContentDispositionHeader,
|
||||
BadContentDispositionParam as BadContentDispositionParam,
|
||||
BodyPartReader as BodyPartReader,
|
||||
MultipartReader as MultipartReader,
|
||||
MultipartWriter as MultipartWriter,
|
||||
content_disposition_filename as content_disposition_filename,
|
||||
parse_content_disposition as parse_content_disposition,
|
||||
)
|
||||
from .payload import (
|
||||
PAYLOAD_REGISTRY as PAYLOAD_REGISTRY,
|
||||
AsyncIterablePayload as AsyncIterablePayload,
|
||||
BufferedReaderPayload as BufferedReaderPayload,
|
||||
BytesIOPayload as BytesIOPayload,
|
||||
BytesPayload as BytesPayload,
|
||||
IOBasePayload as IOBasePayload,
|
||||
JsonPayload as JsonPayload,
|
||||
Payload as Payload,
|
||||
StringIOPayload as StringIOPayload,
|
||||
StringPayload as StringPayload,
|
||||
TextIOPayload as TextIOPayload,
|
||||
get_payload as get_payload,
|
||||
payload_type as payload_type,
|
||||
)
|
||||
from .payload_streamer import streamer as streamer
|
||||
from .resolver import (
|
||||
AsyncResolver as AsyncResolver,
|
||||
DefaultResolver as DefaultResolver,
|
||||
ThreadedResolver as ThreadedResolver,
|
||||
)
|
||||
from .streams import (
|
||||
EMPTY_PAYLOAD as EMPTY_PAYLOAD,
|
||||
DataQueue as DataQueue,
|
||||
EofStream as EofStream,
|
||||
FlowControlDataQueue as FlowControlDataQueue,
|
||||
StreamReader as StreamReader,
|
||||
)
|
||||
from .tracing import (
|
||||
TraceConfig as TraceConfig,
|
||||
TraceConnectionCreateEndParams as TraceConnectionCreateEndParams,
|
||||
TraceConnectionCreateStartParams as TraceConnectionCreateStartParams,
|
||||
TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams,
|
||||
TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams,
|
||||
TraceConnectionReuseconnParams as TraceConnectionReuseconnParams,
|
||||
TraceDnsCacheHitParams as TraceDnsCacheHitParams,
|
||||
TraceDnsCacheMissParams as TraceDnsCacheMissParams,
|
||||
TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams,
|
||||
TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams,
|
||||
TraceRequestChunkSentParams as TraceRequestChunkSentParams,
|
||||
TraceRequestEndParams as TraceRequestEndParams,
|
||||
TraceRequestExceptionParams as TraceRequestExceptionParams,
|
||||
TraceRequestHeadersSentParams as TraceRequestHeadersSentParams,
|
||||
TraceRequestRedirectParams as TraceRequestRedirectParams,
|
||||
TraceRequestStartParams as TraceRequestStartParams,
|
||||
TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# At runtime these are lazy-loaded at the bottom of the file.
|
||||
from .worker import (
|
||||
GunicornUVLoopWebWorker as GunicornUVLoopWebWorker,
|
||||
GunicornWebWorker as GunicornWebWorker,
|
||||
)
|
||||
|
||||
__all__: tuple[str, ...] = (
|
||||
"hdrs",
|
||||
# client
|
||||
"AddrInfoType",
|
||||
"BaseConnector",
|
||||
"ClientConnectionError",
|
||||
"ClientConnectionResetError",
|
||||
"ClientConnectorCertificateError",
|
||||
"ClientConnectorDNSError",
|
||||
"ClientConnectorError",
|
||||
"ClientConnectorSSLError",
|
||||
"ClientError",
|
||||
"ClientHttpProxyError",
|
||||
"ClientOSError",
|
||||
"ClientPayloadError",
|
||||
"ClientProxyConnectionError",
|
||||
"ClientResponse",
|
||||
"ClientRequest",
|
||||
"ClientResponseError",
|
||||
"ClientSSLError",
|
||||
"ClientSession",
|
||||
"ClientTimeout",
|
||||
"ClientWebSocketResponse",
|
||||
"ClientWSTimeout",
|
||||
"ConnectionTimeoutError",
|
||||
"ContentTypeError",
|
||||
"Fingerprint",
|
||||
"FlowControlDataQueue",
|
||||
"InvalidURL",
|
||||
"InvalidUrlClientError",
|
||||
"InvalidUrlRedirectClientError",
|
||||
"NonHttpUrlClientError",
|
||||
"NonHttpUrlRedirectClientError",
|
||||
"RedirectClientError",
|
||||
"RequestInfo",
|
||||
"ServerConnectionError",
|
||||
"ServerDisconnectedError",
|
||||
"ServerFingerprintMismatch",
|
||||
"ServerTimeoutError",
|
||||
"SocketFactoryType",
|
||||
"SocketTimeoutError",
|
||||
"TCPConnector",
|
||||
"TooManyRedirects",
|
||||
"UnixConnector",
|
||||
"NamedPipeConnector",
|
||||
"WSServerHandshakeError",
|
||||
"request",
|
||||
# client_middleware
|
||||
"ClientMiddlewareType",
|
||||
"ClientHandlerType",
|
||||
# cookiejar
|
||||
"CookieJar",
|
||||
"DummyCookieJar",
|
||||
# formdata
|
||||
"FormData",
|
||||
# helpers
|
||||
"BasicAuth",
|
||||
"ChainMapProxy",
|
||||
"DigestAuthMiddleware",
|
||||
"ETag",
|
||||
"encode_basic_auth",
|
||||
"set_zlib_backend",
|
||||
# http
|
||||
"HttpVersion",
|
||||
"HttpVersion10",
|
||||
"HttpVersion11",
|
||||
"WSMsgType",
|
||||
"WSCloseCode",
|
||||
"WSMessage",
|
||||
"WebSocketError",
|
||||
# multipart
|
||||
"BadContentDispositionHeader",
|
||||
"BadContentDispositionParam",
|
||||
"BodyPartReader",
|
||||
"MultipartReader",
|
||||
"MultipartWriter",
|
||||
"content_disposition_filename",
|
||||
"parse_content_disposition",
|
||||
# payload
|
||||
"AsyncIterablePayload",
|
||||
"BufferedReaderPayload",
|
||||
"BytesIOPayload",
|
||||
"BytesPayload",
|
||||
"IOBasePayload",
|
||||
"JsonPayload",
|
||||
"PAYLOAD_REGISTRY",
|
||||
"Payload",
|
||||
"StringIOPayload",
|
||||
"StringPayload",
|
||||
"TextIOPayload",
|
||||
"get_payload",
|
||||
"payload_type",
|
||||
# payload_streamer
|
||||
"streamer",
|
||||
# resolver
|
||||
"AsyncResolver",
|
||||
"DefaultResolver",
|
||||
"ThreadedResolver",
|
||||
# streams
|
||||
"DataQueue",
|
||||
"EMPTY_PAYLOAD",
|
||||
"EofStream",
|
||||
"StreamReader",
|
||||
# tracing
|
||||
"TraceConfig",
|
||||
"TraceConnectionCreateEndParams",
|
||||
"TraceConnectionCreateStartParams",
|
||||
"TraceConnectionQueuedEndParams",
|
||||
"TraceConnectionQueuedStartParams",
|
||||
"TraceConnectionReuseconnParams",
|
||||
"TraceDnsCacheHitParams",
|
||||
"TraceDnsCacheMissParams",
|
||||
"TraceDnsResolveHostEndParams",
|
||||
"TraceDnsResolveHostStartParams",
|
||||
"TraceRequestChunkSentParams",
|
||||
"TraceRequestEndParams",
|
||||
"TraceRequestExceptionParams",
|
||||
"TraceRequestHeadersSentParams",
|
||||
"TraceRequestRedirectParams",
|
||||
"TraceRequestStartParams",
|
||||
"TraceResponseChunkReceivedParams",
|
||||
# workers (imported lazily with __getattr__)
|
||||
"GunicornUVLoopWebWorker",
|
||||
"GunicornWebWorker",
|
||||
"WSMessageTypeError",
|
||||
)
|
||||
|
||||
|
||||
def __dir__() -> tuple[str, ...]:
|
||||
return __all__ + ("__doc__",)
|
||||
|
||||
|
||||
def __getattr__(name: str) -> object:
|
||||
global GunicornUVLoopWebWorker, GunicornWebWorker
|
||||
|
||||
# Importing gunicorn takes a long time (>100ms), so only import if actually needed.
|
||||
if name in ("GunicornUVLoopWebWorker", "GunicornWebWorker"):
|
||||
try:
|
||||
from .worker import GunicornUVLoopWebWorker as guv, GunicornWebWorker as gw
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
GunicornUVLoopWebWorker = guv # type: ignore[misc]
|
||||
GunicornWebWorker = gw # type: ignore[misc]
|
||||
return guv if name == "GunicornUVLoopWebWorker" else gw
|
||||
|
||||
raise AttributeError(f"module {__name__} has no attribute {name}")
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,361 @@
|
||||
"""
|
||||
Internal cookie handling helpers.
|
||||
|
||||
This module contains internal utilities for cookie parsing and manipulation.
|
||||
These are not part of the public API and may change without notice.
|
||||
"""
|
||||
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
from http.cookies import CookieError, Morsel
|
||||
from typing import cast
|
||||
|
||||
from .log import internal_logger
|
||||
|
||||
__all__ = (
|
||||
"parse_set_cookie_headers",
|
||||
"parse_cookie_header",
|
||||
"preserve_morsel_with_coded_value",
|
||||
)
|
||||
|
||||
# Cookie parsing constants
|
||||
# Allow more characters in cookie names to handle real-world cookies
|
||||
# that don't strictly follow RFC standards (fixes #2683)
|
||||
# RFC 6265 defines cookie-name token as per RFC 2616 Section 2.2,
|
||||
# but many servers send cookies with characters like {} [] () etc.
|
||||
# This makes the cookie parser more tolerant of real-world cookies
|
||||
# while still providing some validation to catch obviously malformed names.
|
||||
_COOKIE_NAME_RE = re.compile(r"^[!#$%&\'()*+\-./0-9:<=>?@A-Z\[\]^_`a-z{|}~]+$")
|
||||
_COOKIE_KNOWN_ATTRS = frozenset( # AKA Morsel._reserved
|
||||
(
|
||||
"path",
|
||||
"domain",
|
||||
"max-age",
|
||||
"expires",
|
||||
"secure",
|
||||
"httponly",
|
||||
"samesite",
|
||||
"partitioned",
|
||||
"version",
|
||||
"comment",
|
||||
)
|
||||
)
|
||||
_COOKIE_BOOL_ATTRS = frozenset( # AKA Morsel._flags
|
||||
("secure", "httponly", "partitioned")
|
||||
)
|
||||
|
||||
# SimpleCookie's pattern for parsing cookies with relaxed validation
|
||||
# Based on http.cookies pattern but extended to allow more characters in cookie names
|
||||
# to handle real-world cookies (fixes #2683)
|
||||
_COOKIE_PATTERN = re.compile(
|
||||
r"""
|
||||
\s* # Optional whitespace at start of cookie
|
||||
(?P<key> # Start of group 'key'
|
||||
# aiohttp has extended to include [] for compatibility with real-world cookies
|
||||
[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\[\]]+ # Any word of at least one letter
|
||||
) # End of group 'key'
|
||||
( # Optional group: there may not be a value.
|
||||
\s*=\s* # Equal Sign
|
||||
(?P<val> # Start of group 'val'
|
||||
"(?:[^\\"]|\\.)*" # Any double-quoted string (properly closed)
|
||||
| # or
|
||||
"[^";]* # Unmatched opening quote (differs from SimpleCookie - issue #7993)
|
||||
| # or
|
||||
# Special case for "expires" attr - RFC 822, RFC 850, RFC 1036, RFC 1123
|
||||
(\w{3,6}day|\w{3}),\s # Day of the week or abbreviated day (with comma)
|
||||
[\w\d\s-]{9,11}\s[\d:]{8}\s # Date and time in specific format
|
||||
(GMT|[+-]\d{4}) # Timezone: GMT or RFC 2822 offset like -0000, +0100
|
||||
# NOTE: RFC 2822 timezone support is an aiohttp extension
|
||||
# for issue #4493 - SimpleCookie does NOT support this
|
||||
| # or
|
||||
# ANSI C asctime() format: "Wed Jun 9 10:18:14 2021"
|
||||
# NOTE: This is an aiohttp extension for issue #4327 - SimpleCookie does NOT support this format
|
||||
\w{3}\s+\w{3}\s+[\s\d]\d\s+\d{2}:\d{2}:\d{2}\s+\d{4}
|
||||
| # or
|
||||
[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=\[\]]* # Any word or empty string
|
||||
) # End of group 'val'
|
||||
)? # End of optional value group
|
||||
\s* # Any number of spaces.
|
||||
(\s+|;|$) # Ending either at space, semicolon, or EOS.
|
||||
""",
|
||||
re.VERBOSE | re.ASCII,
|
||||
)
|
||||
|
||||
|
||||
def preserve_morsel_with_coded_value(cookie: Morsel[str]) -> Morsel[str]:
|
||||
"""
|
||||
Preserve a Morsel's coded_value exactly as received from the server.
|
||||
|
||||
This function ensures that cookie encoding is preserved exactly as sent by
|
||||
the server, which is critical for compatibility with old servers that have
|
||||
strict requirements about cookie formats.
|
||||
|
||||
This addresses the issue described in https://github.com/aio-libs/aiohttp/pull/1453
|
||||
where Python's SimpleCookie would re-encode cookies, breaking authentication
|
||||
with certain servers.
|
||||
|
||||
Args:
|
||||
cookie: A Morsel object from SimpleCookie
|
||||
|
||||
Returns:
|
||||
A Morsel object with preserved coded_value
|
||||
|
||||
"""
|
||||
mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel()))
|
||||
# We use __setstate__ instead of the public set() API because it allows us to
|
||||
# bypass validation and set already validated state. This is more stable than
|
||||
# setting protected attributes directly and unlikely to change since it would
|
||||
# break pickling.
|
||||
try:
|
||||
mrsl_val.__setstate__( # type: ignore[attr-defined]
|
||||
{
|
||||
"key": cookie.key,
|
||||
"value": cookie.value,
|
||||
"coded_value": cookie.coded_value,
|
||||
}
|
||||
)
|
||||
except CookieError:
|
||||
return cookie
|
||||
return mrsl_val
|
||||
|
||||
|
||||
_unquote_sub = re.compile(r"\\(?:([0-3][0-7][0-7])|(.))").sub
|
||||
|
||||
|
||||
def _unquote_replace(m: re.Match[str]) -> str:
|
||||
"""
|
||||
Replace function for _unquote_sub regex substitution.
|
||||
|
||||
Handles escaped characters in cookie values:
|
||||
- Octal sequences are converted to their character representation
|
||||
- Other escaped characters are unescaped by removing the backslash
|
||||
"""
|
||||
if m[1]:
|
||||
return chr(int(m[1], 8))
|
||||
return m[2]
|
||||
|
||||
|
||||
def _unquote(value: str) -> str:
|
||||
"""
|
||||
Unquote a cookie value.
|
||||
|
||||
Vendored from http.cookies._unquote to ensure compatibility.
|
||||
|
||||
Note: The original implementation checked for None, but we've removed
|
||||
that check since all callers already ensure the value is not None.
|
||||
"""
|
||||
# If there aren't any doublequotes,
|
||||
# then there can't be any special characters. See RFC 2109.
|
||||
if len(value) < 2:
|
||||
return value
|
||||
if value[0] != '"' or value[-1] != '"':
|
||||
return value
|
||||
|
||||
# We have to assume that we must decode this string.
|
||||
# Down to work.
|
||||
|
||||
# Remove the "s
|
||||
value = value[1:-1]
|
||||
|
||||
# Check for special sequences. Examples:
|
||||
# \012 --> \n
|
||||
# \" --> "
|
||||
#
|
||||
return _unquote_sub(_unquote_replace, value)
|
||||
|
||||
|
||||
def parse_cookie_header(header: str) -> list[tuple[str, Morsel[str]]]:
|
||||
"""
|
||||
Parse a Cookie header according to RFC 6265 Section 5.4.
|
||||
|
||||
Cookie headers contain only name-value pairs separated by semicolons.
|
||||
There are no attributes in Cookie headers - even names that match
|
||||
attribute names (like 'path' or 'secure') should be treated as cookies.
|
||||
|
||||
This parser uses the same regex-based approach as parse_set_cookie_headers
|
||||
to properly handle quoted values that may contain semicolons. When the
|
||||
regex fails to match a malformed cookie, it falls back to simple parsing
|
||||
to ensure subsequent cookies are not lost
|
||||
https://github.com/aio-libs/aiohttp/issues/11632
|
||||
|
||||
Args:
|
||||
header: The Cookie header value to parse
|
||||
|
||||
Returns:
|
||||
List of (name, Morsel) tuples for compatibility with SimpleCookie.update()
|
||||
"""
|
||||
if not header:
|
||||
return []
|
||||
|
||||
cookies: list[tuple[str, Morsel[str]]] = []
|
||||
morsel: Morsel[str]
|
||||
i = 0
|
||||
n = len(header)
|
||||
|
||||
invalid_names = []
|
||||
while i < n:
|
||||
# Use the same pattern as parse_set_cookie_headers to find cookies
|
||||
match = _COOKIE_PATTERN.match(header, i)
|
||||
if not match:
|
||||
# Fallback for malformed cookies https://github.com/aio-libs/aiohttp/issues/11632
|
||||
# Find next semicolon to skip or attempt simple key=value parsing
|
||||
next_semi = header.find(";", i)
|
||||
eq_pos = header.find("=", i)
|
||||
|
||||
# Try to extract key=value if '=' comes before ';'
|
||||
if eq_pos != -1 and (next_semi == -1 or eq_pos < next_semi):
|
||||
end_pos = next_semi if next_semi != -1 else n
|
||||
key = header[i:eq_pos].strip()
|
||||
value = header[eq_pos + 1 : end_pos].strip()
|
||||
|
||||
# Validate the name (same as regex path)
|
||||
if not _COOKIE_NAME_RE.match(key):
|
||||
invalid_names.append(key)
|
||||
else:
|
||||
morsel = Morsel()
|
||||
try:
|
||||
morsel.__setstate__( # type: ignore[attr-defined]
|
||||
{
|
||||
"key": key,
|
||||
"value": _unquote(value),
|
||||
"coded_value": value,
|
||||
}
|
||||
)
|
||||
except CookieError:
|
||||
pass
|
||||
else:
|
||||
cookies.append((key, morsel))
|
||||
|
||||
# Move to next cookie or end
|
||||
i = next_semi + 1 if next_semi != -1 else n
|
||||
continue
|
||||
|
||||
key = match.group("key")
|
||||
value = match.group("val") or ""
|
||||
i = match.end(0)
|
||||
|
||||
# Validate the name
|
||||
if not key or not _COOKIE_NAME_RE.match(key):
|
||||
invalid_names.append(key)
|
||||
continue
|
||||
|
||||
# Create new morsel
|
||||
morsel = Morsel()
|
||||
# Preserve the original value as coded_value (with quotes if present)
|
||||
# We use __setstate__ instead of the public set() API because it allows us to
|
||||
# bypass validation and set already validated state. This is more stable than
|
||||
# setting protected attributes directly and unlikely to change since it would
|
||||
# break pickling.
|
||||
try:
|
||||
morsel.__setstate__( # type: ignore[attr-defined]
|
||||
{"key": key, "value": _unquote(value), "coded_value": value}
|
||||
)
|
||||
except CookieError:
|
||||
continue
|
||||
|
||||
cookies.append((key, morsel))
|
||||
|
||||
if invalid_names:
|
||||
internal_logger.debug(
|
||||
"Cannot load cookie. Illegal cookie names: %r", invalid_names
|
||||
)
|
||||
|
||||
return cookies
|
||||
|
||||
|
||||
def parse_set_cookie_headers(headers: Sequence[str]) -> list[tuple[str, Morsel[str]]]:
|
||||
"""
|
||||
Parse cookie headers using a vendored version of SimpleCookie parsing.
|
||||
|
||||
This implementation is based on SimpleCookie.__parse_string to ensure
|
||||
compatibility with how SimpleCookie parses cookies, including handling
|
||||
of malformed cookies with missing semicolons.
|
||||
|
||||
This function is used for both Cookie and Set-Cookie headers in order to be
|
||||
forgiving. Ideally we would have followed RFC 6265 Section 5.2 (for Cookie
|
||||
headers) and RFC 6265 Section 4.2.1 (for Set-Cookie headers), but the
|
||||
real world data makes it impossible since we need to be a bit more forgiving.
|
||||
|
||||
NOTE: This implementation differs from SimpleCookie in handling unmatched quotes.
|
||||
SimpleCookie will stop parsing when it encounters a cookie value with an unmatched
|
||||
quote (e.g., 'cookie="value'), causing subsequent cookies to be silently dropped.
|
||||
This implementation handles unmatched quotes more gracefully to prevent cookie loss.
|
||||
See https://github.com/aio-libs/aiohttp/issues/7993
|
||||
"""
|
||||
parsed_cookies: list[tuple[str, Morsel[str]]] = []
|
||||
|
||||
for header in headers:
|
||||
if not header:
|
||||
continue
|
||||
|
||||
# Parse cookie string using SimpleCookie's algorithm
|
||||
i = 0
|
||||
n = len(header)
|
||||
current_morsel: Morsel[str] | None = None
|
||||
morsel_seen = False
|
||||
|
||||
while 0 <= i < n:
|
||||
# Start looking for a cookie
|
||||
match = _COOKIE_PATTERN.match(header, i)
|
||||
if not match:
|
||||
# No more cookies
|
||||
break
|
||||
|
||||
key, value = match.group("key"), match.group("val")
|
||||
i = match.end(0)
|
||||
lower_key = key.lower()
|
||||
|
||||
if key[0] == "$":
|
||||
if not morsel_seen:
|
||||
# We ignore attributes which pertain to the cookie
|
||||
# mechanism as a whole, such as "$Version".
|
||||
continue
|
||||
# Process as attribute
|
||||
if current_morsel is not None:
|
||||
attr_lower_key = lower_key[1:]
|
||||
if attr_lower_key in _COOKIE_KNOWN_ATTRS:
|
||||
current_morsel[attr_lower_key] = value or ""
|
||||
elif lower_key in _COOKIE_KNOWN_ATTRS:
|
||||
if not morsel_seen:
|
||||
# Invalid cookie string - attribute before cookie
|
||||
break
|
||||
if lower_key in _COOKIE_BOOL_ATTRS:
|
||||
# Boolean attribute with any value should be True
|
||||
if current_morsel is not None and current_morsel.isReservedKey(key):
|
||||
current_morsel[lower_key] = True
|
||||
elif value is None:
|
||||
# Invalid cookie string - non-boolean attribute without value
|
||||
break
|
||||
elif current_morsel is not None:
|
||||
# Regular attribute with value
|
||||
current_morsel[lower_key] = _unquote(value)
|
||||
elif value is not None:
|
||||
# This is a cookie name=value pair
|
||||
# Validate the name
|
||||
if key in _COOKIE_KNOWN_ATTRS or not _COOKIE_NAME_RE.match(key):
|
||||
internal_logger.warning(
|
||||
"Can not load cookies: Illegal cookie name %r", key
|
||||
)
|
||||
current_morsel = None
|
||||
else:
|
||||
# Create new morsel
|
||||
current_morsel = Morsel()
|
||||
# Preserve the original value as coded_value (with quotes if present)
|
||||
try:
|
||||
current_morsel.__setstate__( # type: ignore[attr-defined]
|
||||
{
|
||||
"key": key,
|
||||
"value": _unquote(value),
|
||||
"coded_value": value,
|
||||
}
|
||||
)
|
||||
except CookieError:
|
||||
current_morsel = None
|
||||
else:
|
||||
parsed_cookies.append((key, current_morsel))
|
||||
morsel_seen = True
|
||||
else:
|
||||
# Invalid cookie string - no value for non-attribute
|
||||
break
|
||||
|
||||
return parsed_cookies
|
||||
@@ -0,0 +1,159 @@
|
||||
from libc.stdint cimport int32_t, uint8_t, uint16_t, uint64_t
|
||||
|
||||
|
||||
cdef extern from "llhttp.h":
|
||||
|
||||
struct llhttp__internal_s:
|
||||
int32_t _index
|
||||
void* _span_pos0
|
||||
void* _span_cb0
|
||||
int32_t error
|
||||
const char* reason
|
||||
const char* error_pos
|
||||
void* data
|
||||
void* _current
|
||||
uint64_t content_length
|
||||
uint8_t type
|
||||
uint8_t method
|
||||
uint8_t http_major
|
||||
uint8_t http_minor
|
||||
uint8_t header_state
|
||||
uint8_t lenient_flags
|
||||
uint8_t upgrade
|
||||
uint8_t finish
|
||||
uint16_t flags
|
||||
uint16_t status_code
|
||||
void* settings
|
||||
|
||||
ctypedef llhttp__internal_s llhttp__internal_t
|
||||
ctypedef llhttp__internal_t llhttp_t
|
||||
|
||||
ctypedef int (*llhttp_data_cb)(llhttp_t*, const char *at, size_t length) except -1
|
||||
ctypedef int (*llhttp_cb)(llhttp_t*) except -1
|
||||
|
||||
struct llhttp_settings_s:
|
||||
llhttp_cb on_message_begin
|
||||
llhttp_data_cb on_url
|
||||
llhttp_data_cb on_status
|
||||
llhttp_data_cb on_header_field
|
||||
llhttp_data_cb on_header_value
|
||||
llhttp_cb on_headers_complete
|
||||
llhttp_data_cb on_body
|
||||
llhttp_cb on_message_complete
|
||||
llhttp_cb on_chunk_header
|
||||
llhttp_cb on_chunk_complete
|
||||
|
||||
llhttp_cb on_url_complete
|
||||
llhttp_cb on_status_complete
|
||||
llhttp_cb on_header_field_complete
|
||||
llhttp_cb on_header_value_complete
|
||||
|
||||
ctypedef llhttp_settings_s llhttp_settings_t
|
||||
|
||||
enum llhttp_errno:
|
||||
HPE_OK,
|
||||
HPE_INTERNAL,
|
||||
HPE_STRICT,
|
||||
HPE_LF_EXPECTED,
|
||||
HPE_UNEXPECTED_CONTENT_LENGTH,
|
||||
HPE_CLOSED_CONNECTION,
|
||||
HPE_INVALID_METHOD,
|
||||
HPE_INVALID_URL,
|
||||
HPE_INVALID_CONSTANT,
|
||||
HPE_INVALID_VERSION,
|
||||
HPE_INVALID_HEADER_TOKEN,
|
||||
HPE_INVALID_CONTENT_LENGTH,
|
||||
HPE_INVALID_CHUNK_SIZE,
|
||||
HPE_INVALID_STATUS,
|
||||
HPE_INVALID_EOF_STATE,
|
||||
HPE_INVALID_TRANSFER_ENCODING,
|
||||
HPE_CB_MESSAGE_BEGIN,
|
||||
HPE_CB_HEADERS_COMPLETE,
|
||||
HPE_CB_MESSAGE_COMPLETE,
|
||||
HPE_CB_CHUNK_HEADER,
|
||||
HPE_CB_CHUNK_COMPLETE,
|
||||
HPE_PAUSED,
|
||||
HPE_PAUSED_UPGRADE,
|
||||
HPE_USER
|
||||
|
||||
ctypedef llhttp_errno llhttp_errno_t
|
||||
|
||||
enum llhttp_flags:
|
||||
F_CHUNKED,
|
||||
F_CONTENT_LENGTH
|
||||
|
||||
enum llhttp_type:
|
||||
HTTP_REQUEST,
|
||||
HTTP_RESPONSE,
|
||||
HTTP_BOTH
|
||||
|
||||
enum llhttp_method:
|
||||
HTTP_DELETE,
|
||||
HTTP_GET,
|
||||
HTTP_HEAD,
|
||||
HTTP_POST,
|
||||
HTTP_PUT,
|
||||
HTTP_CONNECT,
|
||||
HTTP_OPTIONS,
|
||||
HTTP_TRACE,
|
||||
HTTP_COPY,
|
||||
HTTP_LOCK,
|
||||
HTTP_MKCOL,
|
||||
HTTP_MOVE,
|
||||
HTTP_PROPFIND,
|
||||
HTTP_PROPPATCH,
|
||||
HTTP_SEARCH,
|
||||
HTTP_UNLOCK,
|
||||
HTTP_BIND,
|
||||
HTTP_REBIND,
|
||||
HTTP_UNBIND,
|
||||
HTTP_ACL,
|
||||
HTTP_REPORT,
|
||||
HTTP_MKACTIVITY,
|
||||
HTTP_CHECKOUT,
|
||||
HTTP_MERGE,
|
||||
HTTP_MSEARCH,
|
||||
HTTP_NOTIFY,
|
||||
HTTP_SUBSCRIBE,
|
||||
HTTP_UNSUBSCRIBE,
|
||||
HTTP_PATCH,
|
||||
HTTP_PURGE,
|
||||
HTTP_MKCALENDAR,
|
||||
HTTP_LINK,
|
||||
HTTP_UNLINK,
|
||||
HTTP_SOURCE,
|
||||
HTTP_PRI,
|
||||
HTTP_DESCRIBE,
|
||||
HTTP_ANNOUNCE,
|
||||
HTTP_SETUP,
|
||||
HTTP_PLAY,
|
||||
HTTP_PAUSE,
|
||||
HTTP_TEARDOWN,
|
||||
HTTP_GET_PARAMETER,
|
||||
HTTP_SET_PARAMETER,
|
||||
HTTP_REDIRECT,
|
||||
HTTP_RECORD,
|
||||
HTTP_FLUSH
|
||||
|
||||
ctypedef llhttp_method llhttp_method_t;
|
||||
|
||||
void llhttp_settings_init(llhttp_settings_t* settings)
|
||||
void llhttp_init(llhttp_t* parser, llhttp_type type,
|
||||
const llhttp_settings_t* settings)
|
||||
|
||||
llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len)
|
||||
|
||||
int llhttp_should_keep_alive(const llhttp_t* parser)
|
||||
|
||||
void llhttp_resume(llhttp_t* parser)
|
||||
void llhttp_resume_after_upgrade(llhttp_t* parser)
|
||||
|
||||
llhttp_errno_t llhttp_get_errno(const llhttp_t* parser)
|
||||
const char* llhttp_get_error_reason(const llhttp_t* parser)
|
||||
const char* llhttp_get_error_pos(const llhttp_t* parser)
|
||||
|
||||
const char* llhttp_method_name(llhttp_method_t method)
|
||||
|
||||
void llhttp_set_lenient_headers(llhttp_t* parser, int enabled)
|
||||
void llhttp_set_lenient_optional_cr_before_lf(llhttp_t* parser, int enabled)
|
||||
void llhttp_set_lenient_spaces_after_chunk_size(llhttp_t* parser, int enabled)
|
||||
@@ -0,0 +1,2 @@
|
||||
cdef extern from "_find_header.h":
|
||||
int find_header(char *, int)
|
||||
@@ -0,0 +1,83 @@
|
||||
# The file is autogenerated from aiohttp/hdrs.py
|
||||
# Run ./tools/gen.py to update it after the origin changing.
|
||||
|
||||
from . import hdrs
|
||||
cdef tuple headers = (
|
||||
hdrs.ACCEPT,
|
||||
hdrs.ACCEPT_CHARSET,
|
||||
hdrs.ACCEPT_ENCODING,
|
||||
hdrs.ACCEPT_LANGUAGE,
|
||||
hdrs.ACCEPT_RANGES,
|
||||
hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
|
||||
hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
|
||||
hdrs.ACCESS_CONTROL_ALLOW_METHODS,
|
||||
hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
|
||||
hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
|
||||
hdrs.ACCESS_CONTROL_MAX_AGE,
|
||||
hdrs.ACCESS_CONTROL_REQUEST_HEADERS,
|
||||
hdrs.ACCESS_CONTROL_REQUEST_METHOD,
|
||||
hdrs.AGE,
|
||||
hdrs.ALLOW,
|
||||
hdrs.AUTHORIZATION,
|
||||
hdrs.CACHE_CONTROL,
|
||||
hdrs.CONNECTION,
|
||||
hdrs.CONTENT_DISPOSITION,
|
||||
hdrs.CONTENT_ENCODING,
|
||||
hdrs.CONTENT_LANGUAGE,
|
||||
hdrs.CONTENT_LENGTH,
|
||||
hdrs.CONTENT_LOCATION,
|
||||
hdrs.CONTENT_MD5,
|
||||
hdrs.CONTENT_RANGE,
|
||||
hdrs.CONTENT_TRANSFER_ENCODING,
|
||||
hdrs.CONTENT_TYPE,
|
||||
hdrs.COOKIE,
|
||||
hdrs.DATE,
|
||||
hdrs.DESTINATION,
|
||||
hdrs.DIGEST,
|
||||
hdrs.ETAG,
|
||||
hdrs.EXPECT,
|
||||
hdrs.EXPIRES,
|
||||
hdrs.FORWARDED,
|
||||
hdrs.FROM,
|
||||
hdrs.HOST,
|
||||
hdrs.IF_MATCH,
|
||||
hdrs.IF_MODIFIED_SINCE,
|
||||
hdrs.IF_NONE_MATCH,
|
||||
hdrs.IF_RANGE,
|
||||
hdrs.IF_UNMODIFIED_SINCE,
|
||||
hdrs.KEEP_ALIVE,
|
||||
hdrs.LAST_EVENT_ID,
|
||||
hdrs.LAST_MODIFIED,
|
||||
hdrs.LINK,
|
||||
hdrs.LOCATION,
|
||||
hdrs.MAX_FORWARDS,
|
||||
hdrs.ORIGIN,
|
||||
hdrs.PRAGMA,
|
||||
hdrs.PROXY_AUTHENTICATE,
|
||||
hdrs.PROXY_AUTHORIZATION,
|
||||
hdrs.RANGE,
|
||||
hdrs.REFERER,
|
||||
hdrs.RETRY_AFTER,
|
||||
hdrs.SEC_WEBSOCKET_ACCEPT,
|
||||
hdrs.SEC_WEBSOCKET_EXTENSIONS,
|
||||
hdrs.SEC_WEBSOCKET_KEY,
|
||||
hdrs.SEC_WEBSOCKET_KEY1,
|
||||
hdrs.SEC_WEBSOCKET_PROTOCOL,
|
||||
hdrs.SEC_WEBSOCKET_VERSION,
|
||||
hdrs.SERVER,
|
||||
hdrs.SET_COOKIE,
|
||||
hdrs.TE,
|
||||
hdrs.TRAILER,
|
||||
hdrs.TRANSFER_ENCODING,
|
||||
hdrs.URI,
|
||||
hdrs.UPGRADE,
|
||||
hdrs.USER_AGENT,
|
||||
hdrs.VARY,
|
||||
hdrs.VIA,
|
||||
hdrs.WWW_AUTHENTICATE,
|
||||
hdrs.WANT_DIGEST,
|
||||
hdrs.WARNING,
|
||||
hdrs.X_FORWARDED_FOR,
|
||||
hdrs.X_FORWARDED_HOST,
|
||||
hdrs.X_FORWARDED_PROTO,
|
||||
)
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,965 @@
|
||||
# Based on https://github.com/MagicStack/httptools
|
||||
#
|
||||
|
||||
from cpython cimport (
|
||||
Py_buffer,
|
||||
PyBUF_SIMPLE,
|
||||
PyBuffer_Release,
|
||||
PyBytes_AsString,
|
||||
PyBytes_AsStringAndSize,
|
||||
PyObject_GetBuffer,
|
||||
)
|
||||
from cpython.mem cimport PyMem_Free, PyMem_Malloc
|
||||
from libc.limits cimport ULLONG_MAX
|
||||
from libc.string cimport memcpy
|
||||
|
||||
from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy
|
||||
from yarl import URL as _URL
|
||||
|
||||
from aiohttp import hdrs
|
||||
from aiohttp.helpers import DEBUG, set_exception
|
||||
|
||||
from .http_exceptions import (
|
||||
BadHttpMessage,
|
||||
BadHttpMethod,
|
||||
BadStatusLine,
|
||||
ContentLengthError,
|
||||
InvalidHeader,
|
||||
InvalidURLError,
|
||||
LineTooLong,
|
||||
PayloadEncodingError,
|
||||
TransferEncodingError,
|
||||
)
|
||||
from .http_parser import DeflateBuffer as _DeflateBuffer
|
||||
from .http_writer import (
|
||||
HttpVersion as _HttpVersion,
|
||||
HttpVersion10 as _HttpVersion10,
|
||||
HttpVersion11 as _HttpVersion11,
|
||||
)
|
||||
from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader
|
||||
|
||||
cimport cython
|
||||
|
||||
from aiohttp cimport _cparser as cparser
|
||||
|
||||
include "_headers.pxi"
|
||||
|
||||
from aiohttp cimport _find_header
|
||||
|
||||
|
||||
cdef frozenset ALLOWED_UPGRADES = frozenset({"websocket"})
|
||||
DEF DEFAULT_FREELIST_SIZE = 250
|
||||
|
||||
cdef extern from "Python.h":
|
||||
int PyByteArray_Resize(object, Py_ssize_t) except -1
|
||||
Py_ssize_t PyByteArray_Size(object) except -1
|
||||
char* PyByteArray_AsString(object)
|
||||
|
||||
__all__ = ('HttpRequestParser', 'HttpResponseParser',
|
||||
'RawRequestMessage', 'RawResponseMessage')
|
||||
|
||||
cdef object URL = _URL
|
||||
cdef object URL_build = URL.build
|
||||
cdef object CIMultiDict = _CIMultiDict
|
||||
cdef object CIMultiDictProxy = _CIMultiDictProxy
|
||||
cdef object HttpVersion = _HttpVersion
|
||||
cdef object HttpVersion10 = _HttpVersion10
|
||||
cdef object HttpVersion11 = _HttpVersion11
|
||||
cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1
|
||||
cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING
|
||||
cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD
|
||||
cdef object StreamReader = _StreamReader
|
||||
cdef object DeflateBuffer = _DeflateBuffer
|
||||
cdef tuple EMPTY_FEED_DATA_RESULT = ((), False, b"")
|
||||
|
||||
# RFC 9110 singleton headers — duplicates are rejected in strict mode.
|
||||
# In lax mode (response parser default), the check is skipped entirely
|
||||
# since real-world servers (e.g. Google APIs, Werkzeug) commonly send
|
||||
# duplicate headers like Content-Type or Server.
|
||||
cdef frozenset SINGLETON_HEADERS = frozenset({
|
||||
hdrs.CONTENT_LENGTH,
|
||||
hdrs.CONTENT_LOCATION,
|
||||
hdrs.CONTENT_RANGE,
|
||||
hdrs.CONTENT_TYPE,
|
||||
hdrs.ETAG,
|
||||
hdrs.HOST,
|
||||
hdrs.MAX_FORWARDS,
|
||||
hdrs.SERVER,
|
||||
hdrs.TRANSFER_ENCODING,
|
||||
hdrs.USER_AGENT,
|
||||
})
|
||||
|
||||
cdef inline object extend(object buf, const char* at, size_t length):
|
||||
cdef Py_ssize_t s
|
||||
cdef char* ptr
|
||||
s = PyByteArray_Size(buf)
|
||||
PyByteArray_Resize(buf, s + length)
|
||||
ptr = PyByteArray_AsString(buf)
|
||||
memcpy(ptr + s, at, length)
|
||||
|
||||
|
||||
DEF METHODS_COUNT = 46;
|
||||
|
||||
cdef list _http_method = []
|
||||
|
||||
for i in range(METHODS_COUNT):
|
||||
_http_method.append(
|
||||
cparser.llhttp_method_name(<cparser.llhttp_method_t> i).decode('ascii'))
|
||||
|
||||
|
||||
cdef inline str http_method_str(int i):
|
||||
if i < METHODS_COUNT:
|
||||
return <str>_http_method[i]
|
||||
else:
|
||||
return "<unknown>"
|
||||
|
||||
cdef inline object find_header(bytes raw_header):
|
||||
cdef Py_ssize_t size
|
||||
cdef char *buf
|
||||
cdef int idx
|
||||
PyBytes_AsStringAndSize(raw_header, &buf, &size)
|
||||
idx = _find_header.find_header(buf, size)
|
||||
if idx == -1:
|
||||
return raw_header.decode('utf-8', 'surrogateescape')
|
||||
return headers[idx]
|
||||
|
||||
|
||||
@cython.freelist(DEFAULT_FREELIST_SIZE)
|
||||
cdef class RawRequestMessage:
|
||||
cdef readonly str method
|
||||
cdef readonly str path
|
||||
cdef readonly object version # HttpVersion
|
||||
cdef readonly object headers # CIMultiDict
|
||||
cdef readonly object raw_headers # tuple
|
||||
cdef readonly object should_close
|
||||
cdef readonly object compression
|
||||
cdef readonly object upgrade
|
||||
cdef readonly object chunked
|
||||
cdef readonly object url # yarl.URL
|
||||
|
||||
def __init__(self, method, path, version, headers, raw_headers,
|
||||
should_close, compression, upgrade, chunked, url):
|
||||
self.method = method
|
||||
self.path = path
|
||||
self.version = version
|
||||
self.headers = headers
|
||||
self.raw_headers = raw_headers
|
||||
self.should_close = should_close
|
||||
self.compression = compression
|
||||
self.upgrade = upgrade
|
||||
self.chunked = chunked
|
||||
self.url = url
|
||||
|
||||
def __repr__(self):
|
||||
info = []
|
||||
info.append(("method", self.method))
|
||||
info.append(("path", self.path))
|
||||
info.append(("version", self.version))
|
||||
info.append(("headers", self.headers))
|
||||
info.append(("raw_headers", self.raw_headers))
|
||||
info.append(("should_close", self.should_close))
|
||||
info.append(("compression", self.compression))
|
||||
info.append(("upgrade", self.upgrade))
|
||||
info.append(("chunked", self.chunked))
|
||||
info.append(("url", self.url))
|
||||
sinfo = ', '.join(name + '=' + repr(val) for name, val in info)
|
||||
return '<RawRequestMessage(' + sinfo + ')>'
|
||||
|
||||
def _replace(self, **dct):
|
||||
cdef RawRequestMessage ret
|
||||
ret = _new_request_message(self.method,
|
||||
self.path,
|
||||
self.version,
|
||||
self.headers,
|
||||
self.raw_headers,
|
||||
self.should_close,
|
||||
self.compression,
|
||||
self.upgrade,
|
||||
self.chunked,
|
||||
self.url)
|
||||
if "method" in dct:
|
||||
ret.method = dct["method"]
|
||||
if "path" in dct:
|
||||
ret.path = dct["path"]
|
||||
if "version" in dct:
|
||||
ret.version = dct["version"]
|
||||
if "headers" in dct:
|
||||
ret.headers = dct["headers"]
|
||||
if "raw_headers" in dct:
|
||||
ret.raw_headers = dct["raw_headers"]
|
||||
if "should_close" in dct:
|
||||
ret.should_close = dct["should_close"]
|
||||
if "compression" in dct:
|
||||
ret.compression = dct["compression"]
|
||||
if "upgrade" in dct:
|
||||
ret.upgrade = dct["upgrade"]
|
||||
if "chunked" in dct:
|
||||
ret.chunked = dct["chunked"]
|
||||
if "url" in dct:
|
||||
ret.url = dct["url"]
|
||||
return ret
|
||||
|
||||
cdef _new_request_message(str method,
|
||||
str path,
|
||||
object version,
|
||||
object headers,
|
||||
object raw_headers,
|
||||
bint should_close,
|
||||
object compression,
|
||||
bint upgrade,
|
||||
bint chunked,
|
||||
object url):
|
||||
cdef RawRequestMessage ret
|
||||
ret = RawRequestMessage.__new__(RawRequestMessage)
|
||||
ret.method = method
|
||||
ret.path = path
|
||||
ret.version = version
|
||||
ret.headers = headers
|
||||
ret.raw_headers = raw_headers
|
||||
ret.should_close = should_close
|
||||
ret.compression = compression
|
||||
ret.upgrade = upgrade
|
||||
ret.chunked = chunked
|
||||
ret.url = url
|
||||
return ret
|
||||
|
||||
|
||||
@cython.freelist(DEFAULT_FREELIST_SIZE)
|
||||
cdef class RawResponseMessage:
|
||||
cdef readonly object version # HttpVersion
|
||||
cdef readonly int code
|
||||
cdef readonly str reason
|
||||
cdef readonly object headers # CIMultiDict
|
||||
cdef readonly object raw_headers # tuple
|
||||
cdef readonly object should_close
|
||||
cdef readonly object compression
|
||||
cdef readonly object upgrade
|
||||
cdef readonly object chunked
|
||||
|
||||
def __init__(self, version, code, reason, headers, raw_headers,
|
||||
should_close, compression, upgrade, chunked):
|
||||
self.version = version
|
||||
self.code = code
|
||||
self.reason = reason
|
||||
self.headers = headers
|
||||
self.raw_headers = raw_headers
|
||||
self.should_close = should_close
|
||||
self.compression = compression
|
||||
self.upgrade = upgrade
|
||||
self.chunked = chunked
|
||||
|
||||
def __repr__(self):
|
||||
info = []
|
||||
info.append(("version", self.version))
|
||||
info.append(("code", self.code))
|
||||
info.append(("reason", self.reason))
|
||||
info.append(("headers", self.headers))
|
||||
info.append(("raw_headers", self.raw_headers))
|
||||
info.append(("should_close", self.should_close))
|
||||
info.append(("compression", self.compression))
|
||||
info.append(("upgrade", self.upgrade))
|
||||
info.append(("chunked", self.chunked))
|
||||
sinfo = ', '.join(name + '=' + repr(val) for name, val in info)
|
||||
return '<RawResponseMessage(' + sinfo + ')>'
|
||||
|
||||
|
||||
cdef _new_response_message(object version,
|
||||
int code,
|
||||
str reason,
|
||||
object headers,
|
||||
object raw_headers,
|
||||
bint should_close,
|
||||
object compression,
|
||||
bint upgrade,
|
||||
bint chunked):
|
||||
cdef RawResponseMessage ret
|
||||
ret = RawResponseMessage.__new__(RawResponseMessage)
|
||||
ret.version = version
|
||||
ret.code = code
|
||||
ret.reason = reason
|
||||
ret.headers = headers
|
||||
ret.raw_headers = raw_headers
|
||||
ret.should_close = should_close
|
||||
ret.compression = compression
|
||||
ret.upgrade = upgrade
|
||||
ret.chunked = chunked
|
||||
return ret
|
||||
|
||||
|
||||
@cython.internal
|
||||
cdef class HttpParser:
|
||||
|
||||
cdef:
|
||||
cparser.llhttp_t* _cparser
|
||||
cparser.llhttp_settings_t* _csettings
|
||||
|
||||
bytes _raw_name
|
||||
object _name
|
||||
bytes _raw_value
|
||||
bint _has_value
|
||||
int _header_name_size
|
||||
|
||||
readonly object protocol
|
||||
object _loop
|
||||
object _timer
|
||||
|
||||
size_t _max_line_size
|
||||
size_t _max_field_size
|
||||
size_t _max_headers
|
||||
bint _response_with_body
|
||||
bint _read_until_eof
|
||||
bint _lax
|
||||
|
||||
bytes _tail
|
||||
bint _started
|
||||
object _url
|
||||
bytearray _buf
|
||||
str _path
|
||||
str _reason
|
||||
list _headers
|
||||
set _seen_singletons
|
||||
list _raw_headers
|
||||
bint _upgraded
|
||||
list _messages
|
||||
bint _more_data_available
|
||||
bint _paused
|
||||
Py_ssize_t _msg_in_flight
|
||||
Py_ssize_t _max_msg_queue_size
|
||||
bint _eof_pending
|
||||
object _payload
|
||||
unsigned long long _content_length_expected
|
||||
bint _payload_error
|
||||
object _payload_exception
|
||||
object _last_error
|
||||
bint _auto_decompress
|
||||
int _limit
|
||||
|
||||
str _content_encoding
|
||||
|
||||
Py_buffer py_buf
|
||||
|
||||
def __cinit__(self):
|
||||
self._cparser = <cparser.llhttp_t*> \
|
||||
PyMem_Malloc(sizeof(cparser.llhttp_t))
|
||||
if self._cparser is NULL:
|
||||
raise MemoryError()
|
||||
|
||||
self._csettings = <cparser.llhttp_settings_t*> \
|
||||
PyMem_Malloc(sizeof(cparser.llhttp_settings_t))
|
||||
if self._csettings is NULL:
|
||||
raise MemoryError()
|
||||
|
||||
def __dealloc__(self):
|
||||
PyMem_Free(self._cparser)
|
||||
PyMem_Free(self._csettings)
|
||||
|
||||
cdef _init(
|
||||
self, cparser.llhttp_type mode,
|
||||
object protocol, object loop, int limit,
|
||||
object timer=None,
|
||||
size_t max_line_size=8190, size_t max_headers=128,
|
||||
size_t max_field_size=8190, payload_exception=None,
|
||||
bint response_with_body=True, bint read_until_eof=False,
|
||||
bint auto_decompress=True,
|
||||
Py_ssize_t max_msg_queue_size=0,
|
||||
):
|
||||
cparser.llhttp_settings_init(self._csettings)
|
||||
cparser.llhttp_init(self._cparser, mode, self._csettings)
|
||||
self._cparser.data = <void*>self
|
||||
self._cparser.content_length = 0
|
||||
self._content_length_expected = 0
|
||||
|
||||
self.protocol = protocol
|
||||
self._loop = loop
|
||||
self._timer = timer
|
||||
|
||||
self._buf = bytearray()
|
||||
self._more_data_available = False
|
||||
self._paused = False
|
||||
self._msg_in_flight = 0
|
||||
self._max_msg_queue_size = max_msg_queue_size
|
||||
self._eof_pending = False
|
||||
self._payload = None
|
||||
self._payload_error = 0
|
||||
self._payload_exception = payload_exception
|
||||
self._messages = []
|
||||
|
||||
self._raw_name = b""
|
||||
self._raw_value = b""
|
||||
self._tail = b""
|
||||
self._has_value = False
|
||||
self._header_name_size = 0
|
||||
|
||||
self._max_line_size = max_line_size
|
||||
self._max_headers = max_headers
|
||||
self._max_field_size = max_field_size
|
||||
self._response_with_body = response_with_body
|
||||
self._read_until_eof = read_until_eof
|
||||
self._upgraded = False
|
||||
self._auto_decompress = auto_decompress
|
||||
self._content_encoding = None
|
||||
self._lax = False
|
||||
self._seen_singletons = set()
|
||||
|
||||
self._csettings.on_url = cb_on_url
|
||||
self._csettings.on_status = cb_on_status
|
||||
self._csettings.on_header_field = cb_on_header_field
|
||||
self._csettings.on_header_value = cb_on_header_value
|
||||
self._csettings.on_headers_complete = cb_on_headers_complete
|
||||
self._csettings.on_body = cb_on_body
|
||||
self._csettings.on_message_begin = cb_on_message_begin
|
||||
self._csettings.on_message_complete = cb_on_message_complete
|
||||
self._csettings.on_chunk_header = cb_on_chunk_header
|
||||
self._csettings.on_chunk_complete = cb_on_chunk_complete
|
||||
|
||||
self._last_error = None
|
||||
self._limit = limit
|
||||
|
||||
cdef _process_header(self):
|
||||
cdef str value
|
||||
if self._raw_name != b"":
|
||||
name = find_header(self._raw_name)
|
||||
value = self._raw_value.decode('utf-8', 'surrogateescape')
|
||||
|
||||
# reject null bytes in header values - matches the Python parser
|
||||
# check at http_parser.py. llhttp in lenient mode doesn't reject
|
||||
# these itself, so we need to catch them here.
|
||||
# ref: RFC 9110 section 5.5 (CTL chars forbidden in field values)
|
||||
if "\x00" in value:
|
||||
raise InvalidHeader(self._raw_value)
|
||||
|
||||
if not self._lax and name in SINGLETON_HEADERS:
|
||||
if name in self._seen_singletons:
|
||||
raise BadHttpMessage(f"Duplicate '{name}' header found.")
|
||||
self._seen_singletons.add(name)
|
||||
self._headers.append((name, value))
|
||||
if len(self._headers) > self._max_headers:
|
||||
raise BadHttpMessage("Too many headers received")
|
||||
|
||||
if name is CONTENT_ENCODING:
|
||||
self._content_encoding = value
|
||||
|
||||
self._has_value = False
|
||||
self._header_name_size = 0
|
||||
self._raw_headers.append((self._raw_name, self._raw_value))
|
||||
self._raw_name = b""
|
||||
self._raw_value = b""
|
||||
|
||||
cdef _on_header_field(self, char* at, size_t length):
|
||||
if self._has_value:
|
||||
self._process_header()
|
||||
|
||||
if self._raw_name == b"":
|
||||
self._raw_name = at[:length]
|
||||
else:
|
||||
self._raw_name += at[:length]
|
||||
|
||||
cdef _on_header_value(self, char* at, size_t length):
|
||||
if self._raw_value == b"":
|
||||
self._raw_value = at[:length]
|
||||
else:
|
||||
self._raw_value += at[:length]
|
||||
self._has_value = True
|
||||
|
||||
cdef _on_headers_complete(self):
|
||||
cdef str h_upg
|
||||
cdef str enc
|
||||
|
||||
self._process_header()
|
||||
|
||||
http_version = self.http_version()
|
||||
should_close = not cparser.llhttp_should_keep_alive(self._cparser)
|
||||
upgrade = self._cparser.upgrade
|
||||
chunked = self._cparser.flags & cparser.F_CHUNKED
|
||||
|
||||
raw_headers = tuple(self._raw_headers)
|
||||
headers = CIMultiDictProxy(CIMultiDict(self._headers))
|
||||
|
||||
if self._cparser.type == cparser.HTTP_REQUEST:
|
||||
if http_version == HttpVersion11 and hdrs.HOST not in headers:
|
||||
raise BadHttpMessage("Missing 'Host' header in request.")
|
||||
h_upg = headers.get("upgrade", "")
|
||||
if (upgrade and h_upg.isascii() and h_upg.lower() in ALLOWED_UPGRADES) or self._cparser.method == cparser.HTTP_CONNECT:
|
||||
self._upgraded = True
|
||||
else:
|
||||
if upgrade and self._cparser.status_code == 101:
|
||||
self._upgraded = True
|
||||
|
||||
# do not support old websocket spec
|
||||
if SEC_WEBSOCKET_KEY1 in headers:
|
||||
raise InvalidHeader(SEC_WEBSOCKET_KEY1)
|
||||
|
||||
encoding = None
|
||||
enc = self._content_encoding
|
||||
if enc is not None:
|
||||
self._content_encoding = None
|
||||
if enc.isascii() and enc.lower() in {"gzip", "deflate", "br", "zstd"}:
|
||||
encoding = enc
|
||||
|
||||
if self._cparser.type == cparser.HTTP_REQUEST:
|
||||
method = http_method_str(self._cparser.method)
|
||||
msg = _new_request_message(
|
||||
method, self._path,
|
||||
http_version, headers, raw_headers,
|
||||
should_close, encoding, upgrade, chunked, self._url)
|
||||
else:
|
||||
msg = _new_response_message(
|
||||
http_version, self._cparser.status_code, self._reason,
|
||||
headers, raw_headers, should_close, encoding,
|
||||
upgrade, chunked)
|
||||
|
||||
if (
|
||||
self._response_with_body
|
||||
and (
|
||||
ULLONG_MAX > self._cparser.content_length > 0 or chunked or
|
||||
self._cparser.method == cparser.HTTP_CONNECT or
|
||||
(self._cparser.status_code >= 199 and
|
||||
self._cparser.content_length == 0 and
|
||||
self._read_until_eof)
|
||||
)
|
||||
):
|
||||
payload = StreamReader(
|
||||
self.protocol, timer=self._timer, loop=self._loop,
|
||||
limit=self._limit)
|
||||
else:
|
||||
payload = EMPTY_PAYLOAD
|
||||
|
||||
self._payload = payload
|
||||
self._content_length_expected = self._cparser.content_length
|
||||
if encoding is not None and self._auto_decompress:
|
||||
self._payload = DeflateBuffer(payload, encoding, max_decompress_size=self._limit)
|
||||
|
||||
self._messages.append((msg, payload))
|
||||
|
||||
cdef _on_message_complete(self):
|
||||
self._payload.feed_eof()
|
||||
self._payload = None
|
||||
|
||||
cdef _on_chunk_header(self):
|
||||
self._payload.begin_http_chunk_receiving()
|
||||
|
||||
cdef _on_chunk_complete(self):
|
||||
self._payload.end_http_chunk_receiving()
|
||||
|
||||
cdef object _on_status_complete(self):
|
||||
pass
|
||||
|
||||
cdef inline http_version(self):
|
||||
cdef cparser.llhttp_t* parser = self._cparser
|
||||
|
||||
if parser.http_major == 1:
|
||||
if parser.http_minor == 0:
|
||||
return HttpVersion10
|
||||
elif parser.http_minor == 1:
|
||||
return HttpVersion11
|
||||
|
||||
return HttpVersion(parser.http_major, parser.http_minor)
|
||||
|
||||
### Public API ###
|
||||
|
||||
def pause_reading(self):
|
||||
assert self._payload is not None
|
||||
self._paused = True
|
||||
|
||||
def message_consumed(self):
|
||||
# Protocol drained a queued message; free a slot for parsing.
|
||||
if self._msg_in_flight > 0:
|
||||
self._msg_in_flight -= 1
|
||||
|
||||
def feed_eof(self):
|
||||
cdef bytes desc
|
||||
|
||||
if self._payload is not None:
|
||||
if self._cparser.flags & cparser.F_CHUNKED:
|
||||
raise TransferEncodingError(
|
||||
"Not enough data to satisfy transfer length header.")
|
||||
elif self._cparser.flags & cparser.F_CONTENT_LENGTH:
|
||||
received = self._content_length_expected - self._cparser.content_length
|
||||
raise ContentLengthError(
|
||||
f"Not enough data to satisfy content length header "
|
||||
f"(received {received} of {self._content_length_expected} bytes).")
|
||||
elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK:
|
||||
desc = cparser.llhttp_get_error_reason(self._cparser)
|
||||
raise PayloadEncodingError(desc.decode('latin-1'))
|
||||
else:
|
||||
self._eof_pending = True
|
||||
while self._more_data_available:
|
||||
if self._paused:
|
||||
self._paused = False
|
||||
return # Will resume via feed_data(b"") later
|
||||
self._more_data_available = self._payload.feed_data(b"", 0)
|
||||
self._payload.feed_eof()
|
||||
self._payload = None
|
||||
self._more_data_available = False
|
||||
self._eof_pending = False
|
||||
elif self._started:
|
||||
self._on_headers_complete()
|
||||
if self._messages:
|
||||
return self._messages[-1][0]
|
||||
|
||||
def feed_data(self, incoming_data):
|
||||
cdef:
|
||||
size_t data_len
|
||||
size_t nb
|
||||
char* base
|
||||
cdef cparser.llhttp_errno_t errno
|
||||
cdef bytes data
|
||||
|
||||
# Proactor loop sends bytearray.
|
||||
# Ensure cython sees `data` as bytes
|
||||
if type(incoming_data) is not bytes:
|
||||
data = bytes(incoming_data)
|
||||
else:
|
||||
data = incoming_data
|
||||
|
||||
if self._tail:
|
||||
data, self._tail = self._tail + data, b""
|
||||
|
||||
if self._more_data_available:
|
||||
result = cb_on_body(self._cparser, b"", 0)
|
||||
if result is cparser.HPE_PAUSED:
|
||||
self._tail = data
|
||||
return EMPTY_FEED_DATA_RESULT
|
||||
|
||||
if self._eof_pending:
|
||||
self._payload.feed_eof()
|
||||
self._payload = None
|
||||
self._eof_pending = False
|
||||
# We can't have new messages here, otherwise we wouldn't have
|
||||
# received EOF.
|
||||
return EMPTY_FEED_DATA_RESULT
|
||||
|
||||
PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE)
|
||||
# Cache buffer pointer before PyBuffer_Release to avoid use-after-release.
|
||||
base = <char*>self.py_buf.buf
|
||||
data_len = <size_t>self.py_buf.len
|
||||
|
||||
errno = cparser.llhttp_execute(
|
||||
self._cparser,
|
||||
base,
|
||||
data_len)
|
||||
|
||||
if errno is cparser.HPE_PAUSED_UPGRADE:
|
||||
cparser.llhttp_resume_after_upgrade(self._cparser)
|
||||
nb = cparser.llhttp_get_error_pos(self._cparser) - base
|
||||
elif errno is cparser.HPE_PAUSED:
|
||||
cparser.llhttp_resume(self._cparser)
|
||||
pos = cparser.llhttp_get_error_pos(self._cparser) - base
|
||||
self._tail = data[pos:]
|
||||
|
||||
PyBuffer_Release(&self.py_buf)
|
||||
|
||||
if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED, cparser.HPE_PAUSED_UPGRADE):
|
||||
if self._payload_error == 0:
|
||||
if self._last_error is not None:
|
||||
ex = self._last_error
|
||||
self._last_error = None
|
||||
else:
|
||||
after = cparser.llhttp_get_error_pos(self._cparser)
|
||||
before = data[:after - base]
|
||||
after_b = after.split(b"\r\n", 1)[0]
|
||||
before = before.rsplit(b"\r\n", 1)[-1]
|
||||
data = before + after_b
|
||||
pointer = " " * (len(repr(before))-1) + "^"
|
||||
ex = parser_error_from_errno(self._cparser, data, pointer)
|
||||
self._payload = None
|
||||
raise ex
|
||||
|
||||
if self._messages:
|
||||
messages = self._messages
|
||||
self._messages = []
|
||||
else:
|
||||
messages = ()
|
||||
|
||||
if self._upgraded:
|
||||
return messages, True, data[nb:]
|
||||
if not messages: # Shortcut to reduce Python overhead
|
||||
return EMPTY_FEED_DATA_RESULT
|
||||
return messages, False, b""
|
||||
|
||||
def set_upgraded(self, val):
|
||||
self._upgraded = val
|
||||
|
||||
|
||||
cdef class HttpRequestParser(HttpParser):
|
||||
|
||||
def __init__(
|
||||
self, protocol, loop, int limit, timer=None,
|
||||
size_t max_line_size=8190, size_t max_headers=128,
|
||||
size_t max_field_size=8190, payload_exception=None,
|
||||
bint response_with_body=True, bint read_until_eof=False,
|
||||
bint auto_decompress=True, Py_ssize_t max_msg_queue_size=0,
|
||||
):
|
||||
self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer,
|
||||
max_line_size, max_headers, max_field_size,
|
||||
payload_exception, response_with_body, read_until_eof,
|
||||
auto_decompress, max_msg_queue_size)
|
||||
|
||||
cdef object _on_status_complete(self):
|
||||
cdef int idx1, idx2
|
||||
if not self._buf:
|
||||
return
|
||||
self._path = self._buf.decode('utf-8', 'surrogateescape')
|
||||
try:
|
||||
idx3 = len(self._path)
|
||||
if self._cparser.method == cparser.HTTP_CONNECT:
|
||||
# authority-form,
|
||||
# https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
|
||||
self._url = URL.build(authority=self._path, encoded=True)
|
||||
elif idx3 > 1 and self._path[0] == '/':
|
||||
# origin-form,
|
||||
# https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
|
||||
idx1 = self._path.find("?")
|
||||
if idx1 == -1:
|
||||
query = ""
|
||||
idx2 = self._path.find("#")
|
||||
if idx2 == -1:
|
||||
path = self._path
|
||||
fragment = ""
|
||||
else:
|
||||
path = self._path[0: idx2]
|
||||
fragment = self._path[idx2+1:]
|
||||
|
||||
else:
|
||||
path = self._path[0:idx1]
|
||||
idx1 += 1
|
||||
idx2 = self._path.find("#", idx1+1)
|
||||
if idx2 == -1:
|
||||
query = self._path[idx1:]
|
||||
fragment = ""
|
||||
else:
|
||||
query = self._path[idx1: idx2]
|
||||
fragment = self._path[idx2+1:]
|
||||
|
||||
self._url = URL.build(
|
||||
path=path,
|
||||
query_string=query,
|
||||
fragment=fragment,
|
||||
encoded=True,
|
||||
)
|
||||
else:
|
||||
# absolute-form for proxy maybe,
|
||||
# https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
|
||||
self._url = URL(self._path, encoded=True)
|
||||
finally:
|
||||
PyByteArray_Resize(self._buf, 0)
|
||||
|
||||
|
||||
cdef class HttpResponseParser(HttpParser):
|
||||
|
||||
def __init__(
|
||||
self, protocol, loop, int limit, timer=None,
|
||||
size_t max_line_size=8190, size_t max_headers=128,
|
||||
size_t max_field_size=8190, payload_exception=None,
|
||||
bint response_with_body=True, bint read_until_eof=False,
|
||||
bint auto_decompress=True
|
||||
):
|
||||
self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer,
|
||||
max_line_size, max_headers, max_field_size,
|
||||
payload_exception, response_with_body, read_until_eof,
|
||||
auto_decompress)
|
||||
# Use strict parsing on dev mode, so users are warned about broken servers.
|
||||
if not DEBUG:
|
||||
cparser.llhttp_set_lenient_headers(self._cparser, 1)
|
||||
cparser.llhttp_set_lenient_optional_cr_before_lf(self._cparser, 1)
|
||||
cparser.llhttp_set_lenient_spaces_after_chunk_size(self._cparser, 1)
|
||||
self._lax = True
|
||||
|
||||
cdef object _on_status_complete(self):
|
||||
if self._buf:
|
||||
self._reason = self._buf.decode('utf-8', 'surrogateescape')
|
||||
PyByteArray_Resize(self._buf, 0)
|
||||
else:
|
||||
self._reason = self._reason or ''
|
||||
|
||||
cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
|
||||
pyparser._started = True
|
||||
pyparser._headers = []
|
||||
pyparser._seen_singletons = set()
|
||||
pyparser._raw_headers = []
|
||||
PyByteArray_Resize(pyparser._buf, 0)
|
||||
pyparser._path = None
|
||||
pyparser._reason = None
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_url(cparser.llhttp_t* parser,
|
||||
const char *at, size_t length) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
try:
|
||||
if len(pyparser._buf) + length > pyparser._max_line_size:
|
||||
status = pyparser._buf + at[:length]
|
||||
raise LineTooLong(status[:100] + b"...", pyparser._max_line_size)
|
||||
extend(pyparser._buf, at, length)
|
||||
except BaseException as ex:
|
||||
pyparser._last_error = ex
|
||||
return -1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_status(cparser.llhttp_t* parser,
|
||||
const char *at, size_t length) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
try:
|
||||
if len(pyparser._buf) + length > pyparser._max_line_size:
|
||||
reason = pyparser._buf + at[:length]
|
||||
raise LineTooLong(reason[:100] + b"...", pyparser._max_line_size)
|
||||
extend(pyparser._buf, at, length)
|
||||
except BaseException as ex:
|
||||
pyparser._last_error = ex
|
||||
return -1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_header_field(cparser.llhttp_t* parser,
|
||||
const char *at, size_t length) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
cdef Py_ssize_t size
|
||||
try:
|
||||
pyparser._on_status_complete()
|
||||
size = len(pyparser._raw_name) + length
|
||||
if size > pyparser._max_field_size:
|
||||
name = pyparser._raw_name + at[:length]
|
||||
raise LineTooLong(name[:100] + b"...", pyparser._max_field_size)
|
||||
pyparser._header_name_size = size
|
||||
pyparser._on_header_field(at, length)
|
||||
except BaseException as ex:
|
||||
pyparser._last_error = ex
|
||||
return -1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_header_value(cparser.llhttp_t* parser,
|
||||
const char *at, size_t length) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
cdef Py_ssize_t size
|
||||
try:
|
||||
size = len(pyparser._raw_value) + length
|
||||
if pyparser._header_name_size + size > pyparser._max_field_size:
|
||||
value = pyparser._raw_value + at[:length]
|
||||
raise LineTooLong(value[:100] + b"...", pyparser._max_field_size)
|
||||
pyparser._on_header_value(at, length)
|
||||
except BaseException as ex:
|
||||
pyparser._last_error = ex
|
||||
return -1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
try:
|
||||
pyparser._on_status_complete()
|
||||
pyparser._on_headers_complete()
|
||||
except BaseException as exc:
|
||||
pyparser._last_error = exc
|
||||
return -1
|
||||
else:
|
||||
if pyparser._upgraded or pyparser._cparser.method == cparser.HTTP_CONNECT:
|
||||
return 2
|
||||
if not pyparser._response_with_body:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_body(cparser.llhttp_t* parser,
|
||||
const char *at, size_t length) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
cdef bytes body = at[:length]
|
||||
while body or pyparser._more_data_available:
|
||||
try:
|
||||
pyparser._more_data_available = pyparser._payload.feed_data(body, length)
|
||||
except BaseException as underlying_exc:
|
||||
reraised_exc = underlying_exc
|
||||
if pyparser._payload_exception is not None:
|
||||
reraised_exc = pyparser._payload_exception(str(underlying_exc))
|
||||
|
||||
set_exception(pyparser._payload, reraised_exc, underlying_exc)
|
||||
|
||||
pyparser._payload_error = 1
|
||||
pyparser._paused = False
|
||||
return -1
|
||||
body = b""
|
||||
length = 0
|
||||
|
||||
if pyparser._paused:
|
||||
pyparser._paused = False
|
||||
return cparser.HPE_PAUSED
|
||||
pyparser._paused = False
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
try:
|
||||
pyparser._started = False
|
||||
pyparser._on_message_complete()
|
||||
except BaseException as exc:
|
||||
pyparser._last_error = exc
|
||||
return -1
|
||||
else:
|
||||
if pyparser._max_msg_queue_size:
|
||||
pyparser._msg_in_flight += 1
|
||||
if pyparser._msg_in_flight >= pyparser._max_msg_queue_size:
|
||||
# Queue full: pause llhttp between messages. feed_data() buffers
|
||||
# the remainder as tail; resumes once the queue drains.
|
||||
return cparser.HPE_PAUSED
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
try:
|
||||
pyparser._on_chunk_header()
|
||||
except BaseException as exc:
|
||||
pyparser._last_error = exc
|
||||
return -1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1:
|
||||
cdef HttpParser pyparser = <HttpParser>parser.data
|
||||
try:
|
||||
pyparser._on_chunk_complete()
|
||||
except BaseException as exc:
|
||||
pyparser._last_error = exc
|
||||
return -1
|
||||
else:
|
||||
return 0
|
||||
|
||||
|
||||
cdef parser_error_from_errno(cparser.llhttp_t* parser, data, pointer):
|
||||
cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser)
|
||||
cdef bytes desc = cparser.llhttp_get_error_reason(parser)
|
||||
|
||||
err_msg = "{}:\n\n {!r}\n {}".format(desc.decode("latin-1"), data, pointer)
|
||||
|
||||
if errno in {cparser.HPE_CB_MESSAGE_BEGIN,
|
||||
cparser.HPE_CB_HEADERS_COMPLETE,
|
||||
cparser.HPE_CB_MESSAGE_COMPLETE,
|
||||
cparser.HPE_CB_CHUNK_HEADER,
|
||||
cparser.HPE_CB_CHUNK_COMPLETE,
|
||||
cparser.HPE_INVALID_HEADER_TOKEN,
|
||||
cparser.HPE_INVALID_CONTENT_LENGTH,
|
||||
cparser.HPE_INVALID_CHUNK_SIZE,
|
||||
cparser.HPE_INVALID_EOF_STATE,
|
||||
cparser.HPE_INVALID_TRANSFER_ENCODING}:
|
||||
return BadHttpMessage(err_msg)
|
||||
elif errno == cparser.HPE_INVALID_METHOD:
|
||||
if data.startswith(b"\x16\x03"):
|
||||
return BadHttpMethod(error="Received HTTPS traffic on an HTTP port")
|
||||
return BadHttpMethod(error=err_msg)
|
||||
elif errno in {cparser.HPE_INVALID_STATUS,
|
||||
cparser.HPE_INVALID_VERSION,
|
||||
cparser.HPE_INVALID_CONSTANT}:
|
||||
return BadStatusLine(error=f"Bad status line:\n {err_msg}")
|
||||
elif errno == cparser.HPE_INVALID_URL:
|
||||
return InvalidURLError(err_msg)
|
||||
|
||||
return BadHttpMessage(err_msg)
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,164 @@
|
||||
from cpython.bytes cimport PyBytes_FromStringAndSize
|
||||
from cpython.exc cimport PyErr_NoMemory
|
||||
from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc
|
||||
from cpython.object cimport PyObject_Str
|
||||
from libc.stdint cimport uint8_t, uint64_t
|
||||
from libc.string cimport memcpy
|
||||
|
||||
from multidict import istr
|
||||
|
||||
DEF BUF_SIZE = 16 * 1024 # 16KiB
|
||||
|
||||
cdef object _istr = istr
|
||||
|
||||
|
||||
# ----------------- writer ---------------------------
|
||||
|
||||
cdef struct Writer:
|
||||
char *buf
|
||||
Py_ssize_t size
|
||||
Py_ssize_t pos
|
||||
bint heap_allocated
|
||||
|
||||
cdef inline void _init_writer(Writer* writer, char *buf):
|
||||
writer.buf = buf
|
||||
writer.size = BUF_SIZE
|
||||
writer.pos = 0
|
||||
writer.heap_allocated = 0
|
||||
|
||||
|
||||
cdef inline void _release_writer(Writer* writer):
|
||||
if writer.heap_allocated:
|
||||
PyMem_Free(writer.buf)
|
||||
|
||||
|
||||
cdef inline int _write_byte(Writer* writer, uint8_t ch):
|
||||
cdef char * buf
|
||||
cdef Py_ssize_t size
|
||||
|
||||
if writer.pos == writer.size:
|
||||
# reallocate
|
||||
size = writer.size + BUF_SIZE
|
||||
if not writer.heap_allocated:
|
||||
buf = <char*>PyMem_Malloc(size)
|
||||
if buf == NULL:
|
||||
PyErr_NoMemory()
|
||||
return -1
|
||||
memcpy(buf, writer.buf, writer.size)
|
||||
else:
|
||||
buf = <char*>PyMem_Realloc(writer.buf, size)
|
||||
if buf == NULL:
|
||||
PyErr_NoMemory()
|
||||
return -1
|
||||
writer.buf = buf
|
||||
writer.size = size
|
||||
writer.heap_allocated = 1
|
||||
writer.buf[writer.pos] = <char>ch
|
||||
writer.pos += 1
|
||||
return 0
|
||||
|
||||
|
||||
cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol):
|
||||
cdef uint64_t utf = <uint64_t> symbol
|
||||
|
||||
if utf < 0x80:
|
||||
return _write_byte(writer, <uint8_t>utf)
|
||||
elif utf < 0x800:
|
||||
if _write_byte(writer, <uint8_t>(0xc0 | (utf >> 6))) < 0:
|
||||
return -1
|
||||
return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
|
||||
elif 0xD800 <= utf <= 0xDFFF:
|
||||
# surogate pair, ignored
|
||||
return 0
|
||||
elif utf < 0x10000:
|
||||
if _write_byte(writer, <uint8_t>(0xe0 | (utf >> 12))) < 0:
|
||||
return -1
|
||||
if _write_byte(writer, <uint8_t>(0x80 | ((utf >> 6) & 0x3f))) < 0:
|
||||
return -1
|
||||
return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
|
||||
elif utf > 0x10FFFF:
|
||||
# symbol is too large
|
||||
return 0
|
||||
else:
|
||||
if _write_byte(writer, <uint8_t>(0xf0 | (utf >> 18))) < 0:
|
||||
return -1
|
||||
if _write_byte(writer,
|
||||
<uint8_t>(0x80 | ((utf >> 12) & 0x3f))) < 0:
|
||||
return -1
|
||||
if _write_byte(writer,
|
||||
<uint8_t>(0x80 | ((utf >> 6) & 0x3f))) < 0:
|
||||
return -1
|
||||
return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
|
||||
|
||||
|
||||
cdef inline int _write_str(Writer* writer, str s):
|
||||
cdef Py_UCS4 ch
|
||||
for ch in s:
|
||||
if _write_utf8(writer, ch) < 0:
|
||||
return -1
|
||||
|
||||
|
||||
cdef inline int _write_str_raise_on_nlcr(Writer* writer, object s):
|
||||
cdef Py_UCS4 ch
|
||||
cdef str out_str
|
||||
if type(s) is str:
|
||||
out_str = <str>s
|
||||
elif type(s) is _istr:
|
||||
out_str = PyObject_Str(s)
|
||||
elif not isinstance(s, str):
|
||||
raise TypeError("Cannot serialize non-str key {!r}".format(s))
|
||||
else:
|
||||
out_str = str(s)
|
||||
|
||||
for ch in out_str:
|
||||
# https://www.rfc-editor.org/info/rfc9110/#section-5.5-5
|
||||
# https://www.rfc-editor.org/info/rfc9112/#section-4-3
|
||||
if (ch < 0x20 and ch != 0x09) or ch == 0x7F:
|
||||
raise ValueError(
|
||||
"Forbidden control character detected in headers. "
|
||||
"Potential header injection attack."
|
||||
)
|
||||
if _write_utf8(writer, ch) < 0:
|
||||
return -1
|
||||
|
||||
|
||||
# --------------- _serialize_headers ----------------------
|
||||
|
||||
def _serialize_headers(str status_line, headers):
|
||||
cdef Writer writer
|
||||
cdef object key
|
||||
cdef object val
|
||||
cdef char buf[BUF_SIZE]
|
||||
|
||||
_init_writer(&writer, buf)
|
||||
|
||||
try:
|
||||
if _write_str_raise_on_nlcr(&writer, status_line) < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b'\r') < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b'\n') < 0:
|
||||
raise
|
||||
|
||||
for key, val in headers.items():
|
||||
if _write_str_raise_on_nlcr(&writer, key) < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b':') < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b' ') < 0:
|
||||
raise
|
||||
if _write_str_raise_on_nlcr(&writer, val) < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b'\r') < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b'\n') < 0:
|
||||
raise
|
||||
|
||||
if _write_byte(&writer, b'\r') < 0:
|
||||
raise
|
||||
if _write_byte(&writer, b'\n') < 0:
|
||||
raise
|
||||
|
||||
return PyBytes_FromStringAndSize(writer.buf, writer.pos)
|
||||
finally:
|
||||
_release_writer(&writer)
|
||||
@@ -0,0 +1 @@
|
||||
b01999d409b29bd916e067bc963d5f2d9ee63cfc9ae0bccb769910131417bf93 /home/runner/work/aiohttp/aiohttp/aiohttp/_websocket/mask.pxd
|
||||
@@ -0,0 +1 @@
|
||||
0478ceb55d0ed30ef1a7da742cd003449bc69a07cf9fdb06789bd2b347cbfffe /home/runner/work/aiohttp/aiohttp/aiohttp/_websocket/mask.pyx
|
||||
@@ -0,0 +1 @@
|
||||
97e3831a92693b1e05c69b02b644722139a646f065468f26bfceea36079065ba /home/runner/work/aiohttp/aiohttp/aiohttp/_websocket/reader_c.pxd
|
||||
@@ -0,0 +1 @@
|
||||
"""WebSocket protocol versions 13 and 8."""
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user