jam134 commited on
Commit
8016d4f
·
verified ·
1 Parent(s): 804a52f

Upload 546 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/INSTALLER +1 -0
  2. runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/METADATA +291 -0
  3. runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/RECORD +26 -0
  4. runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/WHEEL +4 -0
  5. runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/LICENSE +202 -0
  6. runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/NOTICE +2 -0
  7. runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/INSTALLER +1 -0
  8. runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/LICENSE.txt +13 -0
  9. runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/METADATA +253 -0
  10. runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/RECORD +117 -0
  11. runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/WHEEL +5 -0
  12. runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/top_level.txt +1 -0
  13. runtime/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash +1 -0
  14. runtime/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash +1 -0
  15. runtime/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash +1 -0
  16. runtime/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash +1 -0
  17. runtime/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash +1 -0
  18. runtime/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash +1 -0
  19. runtime/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash +1 -0
  20. runtime/Lib/site-packages/aiohttp/.hash/hdrs.py.hash +1 -0
  21. runtime/Lib/site-packages/aiohttp/__init__.py +216 -0
  22. runtime/Lib/site-packages/aiohttp/_cparser.pxd +190 -0
  23. runtime/Lib/site-packages/aiohttp/_find_header.pxd +2 -0
  24. runtime/Lib/site-packages/aiohttp/_headers.pxi +83 -0
  25. runtime/Lib/site-packages/aiohttp/_helpers.cp39-win_amd64.pyd +0 -0
  26. runtime/Lib/site-packages/aiohttp/_helpers.pyi +6 -0
  27. runtime/Lib/site-packages/aiohttp/_helpers.pyx +35 -0
  28. runtime/Lib/site-packages/aiohttp/_http_parser.cp39-win_amd64.pyd +0 -0
  29. runtime/Lib/site-packages/aiohttp/_http_parser.pyx +832 -0
  30. runtime/Lib/site-packages/aiohttp/_http_writer.cp39-win_amd64.pyd +0 -0
  31. runtime/Lib/site-packages/aiohttp/_http_writer.pyx +163 -0
  32. runtime/Lib/site-packages/aiohttp/_websocket.cp39-win_amd64.pyd +0 -0
  33. runtime/Lib/site-packages/aiohttp/_websocket.pyx +56 -0
  34. runtime/Lib/site-packages/aiohttp/abc.py +207 -0
  35. runtime/Lib/site-packages/aiohttp/base_protocol.py +87 -0
  36. runtime/Lib/site-packages/aiohttp/client.py +1305 -0
  37. runtime/Lib/site-packages/aiohttp/client_exceptions.py +342 -0
  38. runtime/Lib/site-packages/aiohttp/client_proto.py +251 -0
  39. runtime/Lib/site-packages/aiohttp/client_reqrep.py +1134 -0
  40. runtime/Lib/site-packages/aiohttp/client_ws.py +300 -0
  41. runtime/Lib/site-packages/aiohttp/connector.py +1453 -0
  42. runtime/Lib/site-packages/aiohttp/cookiejar.py +411 -0
  43. runtime/Lib/site-packages/aiohttp/formdata.py +172 -0
  44. runtime/Lib/site-packages/aiohttp/hdrs.py +114 -0
  45. runtime/Lib/site-packages/aiohttp/helpers.py +877 -0
  46. runtime/Lib/site-packages/aiohttp/http.py +70 -0
  47. runtime/Lib/site-packages/aiohttp/http_exceptions.py +105 -0
  48. runtime/Lib/site-packages/aiohttp/http_parser.py +969 -0
  49. runtime/Lib/site-packages/aiohttp/http_websocket.py +701 -0
  50. runtime/Lib/site-packages/aiohttp/http_writer.py +200 -0
runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/METADATA ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: aiofiles
3
+ Version: 23.2.1
4
+ Summary: File support for asyncio.
5
+ Project-URL: Changelog, https://github.com/Tinche/aiofiles#history
6
+ Project-URL: Bug Tracker, https://github.com/Tinche/aiofiles/issues
7
+ Project-URL: repository, https://github.com/Tinche/aiofiles
8
+ Author-email: Tin Tvrtkovic <tinchester@gmail.com>
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3.7
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: Implementation :: CPython
23
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
24
+ Requires-Python: >=3.7
25
+ Description-Content-Type: text/markdown
26
+
27
+ # aiofiles: file support for asyncio
28
+
29
+ [![PyPI](https://img.shields.io/pypi/v/aiofiles.svg)](https://pypi.python.org/pypi/aiofiles)
30
+ [![Build](https://github.com/Tinche/aiofiles/workflows/CI/badge.svg)](https://github.com/Tinche/aiofiles/actions)
31
+ [![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/Tinche/882f02e3df32136c847ba90d2688f06e/raw/covbadge.json)](https://github.com/Tinche/aiofiles/actions/workflows/main.yml)
32
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/aiofiles.svg)](https://github.com/Tinche/aiofiles)
33
+ [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
34
+
35
+ **aiofiles** is an Apache2 licensed library, written in Python, for handling local
36
+ disk files in asyncio applications.
37
+
38
+ Ordinary local file IO is blocking, and cannot easily and portably be made
39
+ asynchronous. This means doing file IO may interfere with asyncio applications,
40
+ which shouldn't block the executing thread. aiofiles helps with this by
41
+ introducing asynchronous versions of files that support delegating operations to
42
+ a separate thread pool.
43
+
44
+ ```python
45
+ async with aiofiles.open('filename', mode='r') as f:
46
+ contents = await f.read()
47
+ print(contents)
48
+ 'My file contents'
49
+ ```
50
+
51
+ Asynchronous iteration is also supported.
52
+
53
+ ```python
54
+ async with aiofiles.open('filename') as f:
55
+ async for line in f:
56
+ ...
57
+ ```
58
+
59
+ Asynchronous interface to tempfile module.
60
+
61
+ ```python
62
+ async with aiofiles.tempfile.TemporaryFile('wb') as f:
63
+ await f.write(b'Hello, World!')
64
+ ```
65
+
66
+ ## Features
67
+
68
+ - a file API very similar to Python's standard, blocking API
69
+ - support for buffered and unbuffered binary files, and buffered text files
70
+ - support for `async`/`await` ([PEP 492](https://peps.python.org/pep-0492/)) constructs
71
+ - async interface to tempfile module
72
+
73
+ ## Installation
74
+
75
+ To install aiofiles, simply:
76
+
77
+ ```bash
78
+ $ pip install aiofiles
79
+ ```
80
+
81
+ ## Usage
82
+
83
+ Files are opened using the `aiofiles.open()` coroutine, which in addition to
84
+ mirroring the builtin `open` accepts optional `loop` and `executor`
85
+ arguments. If `loop` is absent, the default loop will be used, as per the
86
+ set asyncio policy. If `executor` is not specified, the default event loop
87
+ executor will be used.
88
+
89
+ In case of success, an asynchronous file object is returned with an
90
+ API identical to an ordinary file, except the following methods are coroutines
91
+ and delegate to an executor:
92
+
93
+ - `close`
94
+ - `flush`
95
+ - `isatty`
96
+ - `read`
97
+ - `readall`
98
+ - `read1`
99
+ - `readinto`
100
+ - `readline`
101
+ - `readlines`
102
+ - `seek`
103
+ - `seekable`
104
+ - `tell`
105
+ - `truncate`
106
+ - `writable`
107
+ - `write`
108
+ - `writelines`
109
+
110
+ In case of failure, one of the usual exceptions will be raised.
111
+
112
+ `aiofiles.stdin`, `aiofiles.stdout`, `aiofiles.stderr`,
113
+ `aiofiles.stdin_bytes`, `aiofiles.stdout_bytes`, and
114
+ `aiofiles.stderr_bytes` provide async access to `sys.stdin`,
115
+ `sys.stdout`, `sys.stderr`, and their corresponding `.buffer` properties.
116
+
117
+ The `aiofiles.os` module contains executor-enabled coroutine versions of
118
+ several useful `os` functions that deal with files:
119
+
120
+ - `stat`
121
+ - `statvfs`
122
+ - `sendfile`
123
+ - `rename`
124
+ - `renames`
125
+ - `replace`
126
+ - `remove`
127
+ - `unlink`
128
+ - `mkdir`
129
+ - `makedirs`
130
+ - `rmdir`
131
+ - `removedirs`
132
+ - `link`
133
+ - `symlink`
134
+ - `readlink`
135
+ - `listdir`
136
+ - `scandir`
137
+ - `access`
138
+ - `path.exists`
139
+ - `path.isfile`
140
+ - `path.isdir`
141
+ - `path.islink`
142
+ - `path.ismount`
143
+ - `path.getsize`
144
+ - `path.getatime`
145
+ - `path.getctime`
146
+ - `path.samefile`
147
+ - `path.sameopenfile`
148
+
149
+ ### Tempfile
150
+
151
+ **aiofiles.tempfile** implements the following interfaces:
152
+
153
+ - TemporaryFile
154
+ - NamedTemporaryFile
155
+ - SpooledTemporaryFile
156
+ - TemporaryDirectory
157
+
158
+ Results return wrapped with a context manager allowing use with async with and async for.
159
+
160
+ ```python
161
+ async with aiofiles.tempfile.NamedTemporaryFile('wb+') as f:
162
+ await f.write(b'Line1\n Line2')
163
+ await f.seek(0)
164
+ async for line in f:
165
+ print(line)
166
+
167
+ async with aiofiles.tempfile.TemporaryDirectory() as d:
168
+ filename = os.path.join(d, "file.ext")
169
+ ```
170
+
171
+ ### Writing tests for aiofiles
172
+
173
+ Real file IO can be mocked by patching `aiofiles.threadpool.sync_open`
174
+ as desired. The return type also needs to be registered with the
175
+ `aiofiles.threadpool.wrap` dispatcher:
176
+
177
+ ```python
178
+ aiofiles.threadpool.wrap.register(mock.MagicMock)(
179
+ lambda *args, **kwargs: threadpool.AsyncBufferedIOBase(*args, **kwargs))
180
+
181
+ async def test_stuff():
182
+ data = 'data'
183
+ mock_file = mock.MagicMock()
184
+
185
+ with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file) as mock_open:
186
+ async with aiofiles.open('filename', 'w') as f:
187
+ await f.write(data)
188
+
189
+ mock_file.write.assert_called_once_with(data)
190
+ ```
191
+
192
+ ### History
193
+
194
+ #### 23.2.1 (2023-08-09)
195
+
196
+ - Import `os.statvfs` conditionally to fix importing on non-UNIX systems.
197
+ [#171](https://github.com/Tinche/aiofiles/issues/171) [#172](https://github.com/Tinche/aiofiles/pull/172)
198
+
199
+ #### 23.2.0 (2023-08-09)
200
+
201
+ - aiofiles is now tested on Python 3.12 too.
202
+ [#166](https://github.com/Tinche/aiofiles/issues/166) [#168](https://github.com/Tinche/aiofiles/pull/168)
203
+ - On Python 3.12, `aiofiles.tempfile.NamedTemporaryFile` now accepts a `delete_on_close` argument, just like the stdlib version.
204
+ - On Python 3.12, `aiofiles.tempfile.NamedTemporaryFile` no longer exposes a `delete` attribute, just like the stdlib version.
205
+ - Added `aiofiles.os.statvfs` and `aiofiles.os.path.ismount`.
206
+ [#162](https://github.com/Tinche/aiofiles/pull/162)
207
+ - Use [PDM](https://pdm.fming.dev/latest/) instead of Poetry.
208
+ [#169](https://github.com/Tinche/aiofiles/pull/169)
209
+
210
+ #### 23.1.0 (2023-02-09)
211
+
212
+ - Added `aiofiles.os.access`.
213
+ [#146](https://github.com/Tinche/aiofiles/pull/146)
214
+ - Removed `aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.softspace`.
215
+ [#151](https://github.com/Tinche/aiofiles/pull/151)
216
+ - Added `aiofiles.stdin`, `aiofiles.stdin_bytes`, and other stdio streams.
217
+ [#154](https://github.com/Tinche/aiofiles/pull/154)
218
+ - Transition to `asyncio.get_running_loop` (vs `asyncio.get_event_loop`) internally.
219
+
220
+ #### 22.1.0 (2022-09-04)
221
+
222
+ - Added `aiofiles.os.path.islink`.
223
+ [#126](https://github.com/Tinche/aiofiles/pull/126)
224
+ - Added `aiofiles.os.readlink`.
225
+ [#125](https://github.com/Tinche/aiofiles/pull/125)
226
+ - Added `aiofiles.os.symlink`.
227
+ [#124](https://github.com/Tinche/aiofiles/pull/124)
228
+ - Added `aiofiles.os.unlink`.
229
+ [#123](https://github.com/Tinche/aiofiles/pull/123)
230
+ - Added `aiofiles.os.link`.
231
+ [#121](https://github.com/Tinche/aiofiles/pull/121)
232
+ - Added `aiofiles.os.renames`.
233
+ [#120](https://github.com/Tinche/aiofiles/pull/120)
234
+ - Added `aiofiles.os.{listdir, scandir}`.
235
+ [#143](https://github.com/Tinche/aiofiles/pull/143)
236
+ - Switched to CalVer.
237
+ - Dropped Python 3.6 support. If you require it, use version 0.8.0.
238
+ - aiofiles is now tested on Python 3.11.
239
+
240
+ #### 0.8.0 (2021-11-27)
241
+
242
+ - aiofiles is now tested on Python 3.10.
243
+ - Added `aiofiles.os.replace`.
244
+ [#107](https://github.com/Tinche/aiofiles/pull/107)
245
+ - Added `aiofiles.os.{makedirs, removedirs}`.
246
+ - Added `aiofiles.os.path.{exists, isfile, isdir, getsize, getatime, getctime, samefile, sameopenfile}`.
247
+ [#63](https://github.com/Tinche/aiofiles/pull/63)
248
+ - Added `suffix`, `prefix`, `dir` args to `aiofiles.tempfile.TemporaryDirectory`.
249
+ [#116](https://github.com/Tinche/aiofiles/pull/116)
250
+
251
+ #### 0.7.0 (2021-05-17)
252
+
253
+ - Added the `aiofiles.tempfile` module for async temporary files.
254
+ [#56](https://github.com/Tinche/aiofiles/pull/56)
255
+ - Switched to Poetry and GitHub actions.
256
+ - Dropped 3.5 support.
257
+
258
+ #### 0.6.0 (2020-10-27)
259
+
260
+ - `aiofiles` is now tested on ppc64le.
261
+ - Added `name` and `mode` properties to async file objects.
262
+ [#82](https://github.com/Tinche/aiofiles/pull/82)
263
+ - Fixed a DeprecationWarning internally.
264
+ [#75](https://github.com/Tinche/aiofiles/pull/75)
265
+ - Python 3.9 support and tests.
266
+
267
+ #### 0.5.0 (2020-04-12)
268
+
269
+ - Python 3.8 support. Code base modernization (using `async/await` instead of `asyncio.coroutine`/`yield from`).
270
+ - Added `aiofiles.os.remove`, `aiofiles.os.rename`, `aiofiles.os.mkdir`, `aiofiles.os.rmdir`.
271
+ [#62](https://github.com/Tinche/aiofiles/pull/62)
272
+
273
+ #### 0.4.0 (2018-08-11)
274
+
275
+ - Python 3.7 support.
276
+ - Removed Python 3.3/3.4 support. If you use these versions, stick to aiofiles 0.3.x.
277
+
278
+ #### 0.3.2 (2017-09-23)
279
+
280
+ - The LICENSE is now included in the sdist.
281
+ [#31](https://github.com/Tinche/aiofiles/pull/31)
282
+
283
+ #### 0.3.1 (2017-03-10)
284
+
285
+ - Introduced a changelog.
286
+ - `aiofiles.os.sendfile` will now work if the standard `os` module contains a `sendfile` function.
287
+
288
+ ### Contributing
289
+
290
+ Contributions are very welcome. Tests can be run with `tox`, please ensure
291
+ the coverage at least stays the same before you submit a pull request.
runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/RECORD ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles-23.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ aiofiles-23.2.1.dist-info/METADATA,sha256=cot28p_PNjdl_MK--l9Qu2e6QOv9OxdHrKbjLmYf9Uw,9673
3
+ aiofiles-23.2.1.dist-info/RECORD,,
4
+ aiofiles-23.2.1.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87
5
+ aiofiles-23.2.1.dist-info/licenses/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325
6
+ aiofiles-23.2.1.dist-info/licenses/NOTICE,sha256=EExY0dRQvWR0wJ2LZLwBgnM6YKw9jCU-M0zegpRSD_E,55
7
+ aiofiles/__init__.py,sha256=1iAMJQyJtX3LGIS0AoFTJeO1aJ_RK2jpBSBhg0VoIrE,344
8
+ aiofiles/__pycache__/__init__.cpython-39.pyc,,
9
+ aiofiles/__pycache__/base.cpython-39.pyc,,
10
+ aiofiles/__pycache__/os.cpython-39.pyc,,
11
+ aiofiles/__pycache__/ospath.cpython-39.pyc,,
12
+ aiofiles/base.py,sha256=rZwA151Ji8XlBkzvDmcF1CgDTY2iKNuJMfvNlM0s0E0,2684
13
+ aiofiles/os.py,sha256=zuFGaIyGCGUuFb7trFFEm6SLdCRqTFsSV0mY6SO8z3M,970
14
+ aiofiles/ospath.py,sha256=zqG2VFzRb6yYiIOWipqsdgvZmoMTFvZmBdkxkAl1FT4,764
15
+ aiofiles/tempfile/__init__.py,sha256=hFSNTOjOUv371Ozdfy6FIxeln46Nm3xOVh4ZR3Q94V0,10244
16
+ aiofiles/tempfile/__pycache__/__init__.cpython-39.pyc,,
17
+ aiofiles/tempfile/__pycache__/temptypes.cpython-39.pyc,,
18
+ aiofiles/tempfile/temptypes.py,sha256=ddEvNjMLVlr7WUILCe6ypTqw77yREeIonTk16Uw_NVs,2093
19
+ aiofiles/threadpool/__init__.py,sha256=c_aexl1t193iKdPZaolPEEbHDrQ0RrsH_HTAToMPQBo,3171
20
+ aiofiles/threadpool/__pycache__/__init__.cpython-39.pyc,,
21
+ aiofiles/threadpool/__pycache__/binary.cpython-39.pyc,,
22
+ aiofiles/threadpool/__pycache__/text.cpython-39.pyc,,
23
+ aiofiles/threadpool/__pycache__/utils.cpython-39.pyc,,
24
+ aiofiles/threadpool/binary.py,sha256=hp-km9VCRu0MLz_wAEUfbCz7OL7xtn9iGAawabpnp5U,2315
25
+ aiofiles/threadpool/text.py,sha256=fNmpw2PEkj0BZSldipJXAgZqVGLxALcfOMiuDQ54Eas,1223
26
+ aiofiles/threadpool/utils.py,sha256=B59dSZwO_WZs2dFFycKeA91iD2Xq2nNw1EFF8YMBI5k,1868
runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.17.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
runtime/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/NOTICE ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Asyncio support for files
2
+ Copyright 2016 Tin Tvrtkovic
runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright aio-libs contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/METADATA ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: aiohttp
3
+ Version: 3.8.3
4
+ Summary: Async http client/server framework (asyncio)
5
+ Home-page: https://github.com/aio-libs/aiohttp
6
+ Maintainer: aiohttp team <team@aiohttp.org>
7
+ Maintainer-email: team@aiohttp.org
8
+ License: Apache 2
9
+ Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby
10
+ Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
11
+ Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp
12
+ Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html
13
+ Project-URL: Docs: RTD, https://docs.aiohttp.org
14
+ Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues
15
+ Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: Framework :: AsyncIO
18
+ Classifier: Intended Audience :: Developers
19
+ Classifier: License :: OSI Approved :: Apache Software License
20
+ Classifier: Operating System :: POSIX
21
+ Classifier: Operating System :: MacOS :: MacOS X
22
+ Classifier: Operating System :: Microsoft :: Windows
23
+ Classifier: Programming Language :: Python
24
+ Classifier: Programming Language :: Python :: 3
25
+ Classifier: Programming Language :: Python :: 3.6
26
+ Classifier: Programming Language :: Python :: 3.7
27
+ Classifier: Programming Language :: Python :: 3.8
28
+ Classifier: Programming Language :: Python :: 3.9
29
+ Classifier: Programming Language :: Python :: 3.10
30
+ Classifier: Topic :: Internet :: WWW/HTTP
31
+ Requires-Python: >=3.6
32
+ Description-Content-Type: text/x-rst
33
+ License-File: LICENSE.txt
34
+ Requires-Dist: attrs (>=17.3.0)
35
+ Requires-Dist: charset-normalizer (<3.0,>=2.0)
36
+ Requires-Dist: multidict (<7.0,>=4.5)
37
+ Requires-Dist: async-timeout (<5.0,>=4.0.0a3)
38
+ Requires-Dist: yarl (<2.0,>=1.0)
39
+ Requires-Dist: frozenlist (>=1.1.1)
40
+ Requires-Dist: aiosignal (>=1.1.2)
41
+ Requires-Dist: idna-ssl (>=1.0) ; python_version < "3.7"
42
+ Requires-Dist: asynctest (==0.13.0) ; python_version < "3.8"
43
+ Requires-Dist: typing-extensions (>=3.7.4) ; python_version < "3.8"
44
+ Provides-Extra: speedups
45
+ Requires-Dist: aiodns ; extra == 'speedups'
46
+ Requires-Dist: Brotli ; extra == 'speedups'
47
+ Requires-Dist: cchardet ; (python_version < "3.10") and extra == 'speedups'
48
+
49
+ ==================================
50
+ Async http client/server framework
51
+ ==================================
52
+
53
+ .. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg
54
+ :height: 64px
55
+ :width: 64px
56
+ :alt: aiohttp logo
57
+
58
+ |
59
+
60
+ .. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg
61
+ :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI
62
+ :alt: GitHub Actions status for master branch
63
+
64
+ .. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg
65
+ :target: https://codecov.io/gh/aio-libs/aiohttp
66
+ :alt: codecov.io status for master branch
67
+
68
+ .. image:: https://badge.fury.io/py/aiohttp.svg
69
+ :target: https://pypi.org/project/aiohttp
70
+ :alt: Latest PyPI package version
71
+
72
+ .. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest
73
+ :target: https://docs.aiohttp.org/
74
+ :alt: Latest Read The Docs
75
+
76
+ .. image:: https://img.shields.io/discourse/status?server=https%3A%2F%2Faio-libs.discourse.group
77
+ :target: https://aio-libs.discourse.group
78
+ :alt: Discourse status
79
+
80
+ .. image:: https://badges.gitter.im/Join%20Chat.svg
81
+ :target: https://gitter.im/aio-libs/Lobby
82
+ :alt: Chat on Gitter
83
+
84
+
85
+ Key Features
86
+ ============
87
+
88
+ - Supports both client and server side of HTTP protocol.
89
+ - Supports both client and server Web-Sockets out-of-the-box and avoids
90
+ Callback Hell.
91
+ - Provides Web-server with middlewares and plugable routing.
92
+
93
+
94
+ Getting started
95
+ ===============
96
+
97
+ Client
98
+ ------
99
+
100
+ To get something from the web:
101
+
102
+ .. code-block:: python
103
+
104
+ import aiohttp
105
+ import asyncio
106
+
107
+ async def main():
108
+
109
+ async with aiohttp.ClientSession() as session:
110
+ async with session.get('http://python.org') as response:
111
+
112
+ print("Status:", response.status)
113
+ print("Content-type:", response.headers['content-type'])
114
+
115
+ html = await response.text()
116
+ print("Body:", html[:15], "...")
117
+
118
+ asyncio.run(main())
119
+
120
+ This prints:
121
+
122
+ .. code-block::
123
+
124
+ Status: 200
125
+ Content-type: text/html; charset=utf-8
126
+ Body: <!doctype html> ...
127
+
128
+ Coming from `requests <https://requests.readthedocs.io/>`_ ? Read `why we need so many lines <https://aiohttp.readthedocs.io/en/latest/http_request_lifecycle.html>`_.
129
+
130
+ Server
131
+ ------
132
+
133
+ An example using a simple server:
134
+
135
+ .. code-block:: python
136
+
137
+ # examples/server_simple.py
138
+ from aiohttp import web
139
+
140
+ async def handle(request):
141
+ name = request.match_info.get('name', "Anonymous")
142
+ text = "Hello, " + name
143
+ return web.Response(text=text)
144
+
145
+ async def wshandle(request):
146
+ ws = web.WebSocketResponse()
147
+ await ws.prepare(request)
148
+
149
+ async for msg in ws:
150
+ if msg.type == web.WSMsgType.text:
151
+ await ws.send_str("Hello, {}".format(msg.data))
152
+ elif msg.type == web.WSMsgType.binary:
153
+ await ws.send_bytes(msg.data)
154
+ elif msg.type == web.WSMsgType.close:
155
+ break
156
+
157
+ return ws
158
+
159
+
160
+ app = web.Application()
161
+ app.add_routes([web.get('/', handle),
162
+ web.get('/echo', wshandle),
163
+ web.get('/{name}', handle)])
164
+
165
+ if __name__ == '__main__':
166
+ web.run_app(app)
167
+
168
+
169
+ Documentation
170
+ =============
171
+
172
+ https://aiohttp.readthedocs.io/
173
+
174
+
175
+ Demos
176
+ =====
177
+
178
+ https://github.com/aio-libs/aiohttp-demos
179
+
180
+
181
+ External links
182
+ ==============
183
+
184
+ * `Third party libraries
185
+ <http://aiohttp.readthedocs.io/en/latest/third_party.html>`_
186
+ * `Built with aiohttp
187
+ <http://aiohttp.readthedocs.io/en/latest/built_with.html>`_
188
+ * `Powered by aiohttp
189
+ <http://aiohttp.readthedocs.io/en/latest/powered_by.html>`_
190
+
191
+ Feel free to make a Pull Request for adding your link to these pages!
192
+
193
+
194
+ Communication channels
195
+ ======================
196
+
197
+ *aio-libs discourse group*: https://aio-libs.discourse.group
198
+
199
+ *gitter chat* https://gitter.im/aio-libs/Lobby
200
+
201
+ We support `Stack Overflow
202
+ <https://stackoverflow.com/questions/tagged/aiohttp>`_.
203
+ Please add *aiohttp* tag to your question there.
204
+
205
+ Requirements
206
+ ============
207
+
208
+ - Python >= 3.6
209
+ - async-timeout_
210
+ - attrs_
211
+ - charset-normalizer_
212
+ - multidict_
213
+ - yarl_
214
+ - frozenlist_
215
+
216
+ Optionally you may install the cChardet_ and aiodns_ libraries (highly
217
+ recommended for sake of speed).
218
+
219
+ .. _charset-normalizer: https://pypi.org/project/charset-normalizer
220
+ .. _aiodns: https://pypi.python.org/pypi/aiodns
221
+ .. _attrs: https://github.com/python-attrs/attrs
222
+ .. _multidict: https://pypi.python.org/pypi/multidict
223
+ .. _frozenlist: https://pypi.org/project/frozenlist/
224
+ .. _yarl: https://pypi.python.org/pypi/yarl
225
+ .. _async-timeout: https://pypi.python.org/pypi/async_timeout
226
+ .. _cChardet: https://pypi.python.org/pypi/cchardet
227
+
228
+ License
229
+ =======
230
+
231
+ ``aiohttp`` is offered under the Apache 2 license.
232
+
233
+
234
+ Keepsafe
235
+ ========
236
+
237
+ The aiohttp community would like to thank Keepsafe
238
+ (https://www.getkeepsafe.com) for its support in the early days of
239
+ the project.
240
+
241
+
242
+ Source code
243
+ ===========
244
+
245
+ The latest developer version is available in a GitHub repository:
246
+ https://github.com/aio-libs/aiohttp
247
+
248
+ Benchmarks
249
+ ==========
250
+
251
+ If you are interested in efficiency, the AsyncIO community maintains a
252
+ list of benchmarks on the official wiki:
253
+ https://github.com/python/asyncio/wiki/Benchmarks
runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/RECORD ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohttp-3.8.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ aiohttp-3.8.3.dist-info/LICENSE.txt,sha256=wUk-nxDVnR-6n53ygAjhVX4zz5-6yM4SY6ozk5goA94,601
3
+ aiohttp-3.8.3.dist-info/METADATA,sha256=tGcxB-KseArVRgBQmGjX9g9YQehDdkqeIAeueYZI4-I,7355
4
+ aiohttp-3.8.3.dist-info/RECORD,,
5
+ aiohttp-3.8.3.dist-info/WHEEL,sha256=fVcVlLzi8CGi_Ul8vjMdn8gER25dn5GBg9E6k9z41-Y,100
6
+ aiohttp-3.8.3.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8
7
+ aiohttp/.hash/_cparser.pxd.hash,sha256=1tLMUc3IzMppOVKW99LKG1TD6szTXGSaCfHgiPOL9aA,108
8
+ aiohttp/.hash/_find_header.pxd.hash,sha256=TxG5w4etbVd6sfm5JWbdf5PW6LnuXRQnlMoFBVGKN2E,112
9
+ aiohttp/.hash/_helpers.pyi.hash,sha256=D1pTrCkUaJ3by1XeGH_nE-amt7XdjfRHcm9oRtoGhHQ,108
10
+ aiohttp/.hash/_helpers.pyx.hash,sha256=MA4zlNd5xukP4VDAbnoId0Azv8HxCpwLWie2gSMPLsw,108
11
+ aiohttp/.hash/_http_parser.pyx.hash,sha256=H1bEygSJvt4Oc3GhF_yMpoO4ZYENKF9uqxK8Qtuz_w4,112
12
+ aiohttp/.hash/_http_writer.pyx.hash,sha256=oqW0CdYfKNwSX0PKREN8Qz_Mi4aaioGCIPbEvsaEgaM,112
13
+ aiohttp/.hash/_websocket.pyx.hash,sha256=8AcsJ5Tb8lZ9_QVXor_1Xbtl5igK1iP5rtEZZ0iA2AE,110
14
+ aiohttp/.hash/hdrs.py.hash,sha256=Vfr7WRlz3YbkgRFBfXksCI8mA7PXUMhs37jnv0kiqWQ,103
15
+ aiohttp/__init__.py,sha256=gxZp0SS_nojwQuZlN2VCg-_hnKTRo0V5cerhuI5YGfM,7086
16
+ aiohttp/__pycache__/__init__.cpython-39.pyc,,
17
+ aiohttp/__pycache__/abc.cpython-39.pyc,,
18
+ aiohttp/__pycache__/base_protocol.cpython-39.pyc,,
19
+ aiohttp/__pycache__/client.cpython-39.pyc,,
20
+ aiohttp/__pycache__/client_exceptions.cpython-39.pyc,,
21
+ aiohttp/__pycache__/client_proto.cpython-39.pyc,,
22
+ aiohttp/__pycache__/client_reqrep.cpython-39.pyc,,
23
+ aiohttp/__pycache__/client_ws.cpython-39.pyc,,
24
+ aiohttp/__pycache__/connector.cpython-39.pyc,,
25
+ aiohttp/__pycache__/cookiejar.cpython-39.pyc,,
26
+ aiohttp/__pycache__/formdata.cpython-39.pyc,,
27
+ aiohttp/__pycache__/hdrs.cpython-39.pyc,,
28
+ aiohttp/__pycache__/helpers.cpython-39.pyc,,
29
+ aiohttp/__pycache__/http.cpython-39.pyc,,
30
+ aiohttp/__pycache__/http_exceptions.cpython-39.pyc,,
31
+ aiohttp/__pycache__/http_parser.cpython-39.pyc,,
32
+ aiohttp/__pycache__/http_websocket.cpython-39.pyc,,
33
+ aiohttp/__pycache__/http_writer.cpython-39.pyc,,
34
+ aiohttp/__pycache__/locks.cpython-39.pyc,,
35
+ aiohttp/__pycache__/log.cpython-39.pyc,,
36
+ aiohttp/__pycache__/multipart.cpython-39.pyc,,
37
+ aiohttp/__pycache__/payload.cpython-39.pyc,,
38
+ aiohttp/__pycache__/payload_streamer.cpython-39.pyc,,
39
+ aiohttp/__pycache__/pytest_plugin.cpython-39.pyc,,
40
+ aiohttp/__pycache__/resolver.cpython-39.pyc,,
41
+ aiohttp/__pycache__/streams.cpython-39.pyc,,
42
+ aiohttp/__pycache__/tcp_helpers.cpython-39.pyc,,
43
+ aiohttp/__pycache__/test_utils.cpython-39.pyc,,
44
+ aiohttp/__pycache__/tracing.cpython-39.pyc,,
45
+ aiohttp/__pycache__/typedefs.cpython-39.pyc,,
46
+ aiohttp/__pycache__/web.cpython-39.pyc,,
47
+ aiohttp/__pycache__/web_app.cpython-39.pyc,,
48
+ aiohttp/__pycache__/web_exceptions.cpython-39.pyc,,
49
+ aiohttp/__pycache__/web_fileresponse.cpython-39.pyc,,
50
+ aiohttp/__pycache__/web_log.cpython-39.pyc,,
51
+ aiohttp/__pycache__/web_middlewares.cpython-39.pyc,,
52
+ aiohttp/__pycache__/web_protocol.cpython-39.pyc,,
53
+ aiohttp/__pycache__/web_request.cpython-39.pyc,,
54
+ aiohttp/__pycache__/web_response.cpython-39.pyc,,
55
+ aiohttp/__pycache__/web_routedef.cpython-39.pyc,,
56
+ aiohttp/__pycache__/web_runner.cpython-39.pyc,,
57
+ aiohttp/__pycache__/web_server.cpython-39.pyc,,
58
+ aiohttp/__pycache__/web_urldispatcher.cpython-39.pyc,,
59
+ aiohttp/__pycache__/web_ws.cpython-39.pyc,,
60
+ aiohttp/__pycache__/worker.cpython-39.pyc,,
61
+ aiohttp/_cparser.pxd,sha256=rEtEshtn54wSf_ZCJ0EBjRyVBkIOv_oh17BcaNOd6V8,5188
62
+ aiohttp/_find_header.pxd,sha256=BFUSmxhemBtblqxzjzH3x03FfxaWlTyuAIOz8YZ5_nM,70
63
+ aiohttp/_headers.pxi,sha256=1MhCe6Un_KI1tpO85HnDfzVO94BhcirLanAOys5FIHA,2090
64
+ aiohttp/_helpers.cp39-win_amd64.pyd,sha256=gp6JR4Aq7ASFjtDMZtHeRmPJqsx8BAcmHJO2FvDbl-s,39936
65
+ aiohttp/_helpers.pyi,sha256=2Hd5IC0Zf4YTEJ412suyyhsh1kVyVDv5g4stgyo2Ksc,208
66
+ aiohttp/_helpers.pyx,sha256=tgl7fZh0QMT6cjf4jSJ8iaO6DdQD3GON2-SH4N5_ETg,1084
67
+ aiohttp/_http_parser.cp39-win_amd64.pyd,sha256=nI7VbDlSEaS1JDb3nxKUTRpBOegQ7_lrPNNXdTq8-4U,215552
68
+ aiohttp/_http_parser.pyx,sha256=1AHorYdvPR_sEjQSnCWT9kwGZKWFapVRZT910TUx7OM,28168
69
+ aiohttp/_http_writer.cp39-win_amd64.pyd,sha256=HWVHF1eexC1jSC23fwNSkDRaPXMzD87sNVpQ6NbAMxc,35840
70
+ aiohttp/_http_writer.pyx,sha256=8CBLytO2rx1kdpWe9HYSznhLXdeZWyE-3xI7jaGasag,4738
71
+ aiohttp/_websocket.cp39-win_amd64.pyd,sha256=DeqLzmD7z0deDznivKGkpUG4r-wOiJ4UHGh1MTes8Dg,24064
72
+ aiohttp/_websocket.pyx,sha256=o9J7yi9c2-jTBjE3dUkXxhDWKvRWJz5GZfyLsgJQa38,1617
73
+ aiohttp/abc.py,sha256=h_4OTYoks0wu64YIpvNPMFkFaVqh1cJ7HdygN1fAKp8,5712
74
+ aiohttp/base_protocol.py,sha256=27NXvLdbmi-e4JHwV3OjOCsRnq7W799LMulG3t2Ok0Q,2763
75
+ aiohttp/client.py,sha256=vP-rZMty2GJbMeWqnwITHZQjdqtFTTGEJGGW9Ndv1gg,46342
76
+ aiohttp/client_exceptions.py,sha256=k-ys_A4QQW-IH4-fQIAYgBj6Zjjf2METxILp2cElMuk,9612
77
+ aiohttp/client_proto.py,sha256=3Cx_gH0ZZNNkVCzhnysBe09zbLhnN9jZX3gvqsp_SbE,8421
78
+ aiohttp/client_reqrep.py,sha256=DKI4Wq2DyHgr6k1IVnKbRoOwvHQXxo3emKYJEy8oIa0,38107
79
+ aiohttp/client_ws.py,sha256=70XQ5cWdvbwgA6tko-1GfhbSJ70bAHjm1OE4mWtWDw4,10816
80
+ aiohttp/connector.py,sha256=h5hT-7KZ02NUBQ2OT3wCvyO0h7TZfl7ENFNBgRJUKEM,52630
81
+ aiohttp/cookiejar.py,sha256=Y4wGOTP86Cnl90mQtuts0DLuYdSVmZK1_wzsjMnvIyw,13925
82
+ aiohttp/formdata.py,sha256=iySnD63XJwo4l1TT_KZiJGNzzmn0RtvvF2_FnJM32Uo,6278
83
+ aiohttp/hdrs.py,sha256=ygDnAqYCot8NMQyjck2r9CzpTspAOXpHknNl-yxIybY,4838
84
+ aiohttp/helpers.py,sha256=knT9IHBgmIqMuF2BuGR_rS7aAfw3lrkkVzVwv3Rm1Cw,27238
85
+ aiohttp/http.py,sha256=YPu2yu8TQAiQfIiu9JpE4ICmE0D4ljADgLXtNFlEJnc,1870
86
+ aiohttp/http_exceptions.py,sha256=rLwhCbFrOpQ_ntr3GnxaxD3oRnTTNM1utmDDBUbdVTU,2691
87
+ aiohttp/http_parser.py,sha256=gokMNEZeTCHfA52a7LwiGxEShLHAOfSxbCq-8QWh9QU,34061
88
+ aiohttp/http_websocket.py,sha256=a7yQM4cQcM-DxhRITp8dT_0jfWxqbU-yTWTgqH8Zfpc,26000
89
+ aiohttp/http_writer.py,sha256=VFpYiYZ41yj8lEjYGCB6C3WeGyuRgs8Tx2uJhiBuCdU,6152
90
+ aiohttp/locks.py,sha256=vp1Z4zx0SvooSffw88dkZ-7qpk2CqRf5vWh2dpKagTA,1177
91
+ aiohttp/log.py,sha256=zYUTvXsMQ9Sz1yNN8kXwd5Qxu49a1FzjZ_wQqriEc8M,333
92
+ aiohttp/multipart.py,sha256=DqB2JIhnmhpmC3x5KuYaDGPfS6a1yMixnyVRsVSOcDI,33274
93
+ aiohttp/payload.py,sha256=5RuKdJJj1WYwIo_vp-4Jdcn5ZoTzrAYna90DG0xNpXQ,14099
94
+ aiohttp/payload_streamer.py,sha256=6bbqsfgysHzfUTJIUlqad1wRklVuLmNHVtScv_mWhGY,2187
95
+ aiohttp/py.typed,sha256=3VVwXUAWVEVX7sDwyYDnW5ZdBC9_Z9AJAFfLCleUW0k,8
96
+ aiohttp/pytest_plugin.py,sha256=26CllzLUw-JGrwfXYIK-XGbDMCDwbIaomV7Sk4WZVG4,12163
97
+ aiohttp/resolver.py,sha256=UWM-6HJkOLwkGveoesBnGv-pJePtpE7js6ujYi7XHoc,5252
98
+ aiohttp/streams.py,sha256=yWdQ0wIGIQCfI9OGdhzImtQKcUBRNfQ9Dw2pzXm-dCM,21418
99
+ aiohttp/tcp_helpers.py,sha256=K-hhGh3jd6qCEnHJo8LvFyfJwBjh99UKI7A0aSRVhj4,998
100
+ aiohttp/test_utils.py,sha256=gs74TWcysSMuhfAvae0Dy-jKkWVKBWKp2nLt_qfi3x0,22140
101
+ aiohttp/tracing.py,sha256=qOwPt4vyGRVlebUUSuOJ5Vc9cc4ZGOOPr5TuweOSoVE,15649
102
+ aiohttp/typedefs.py,sha256=E-iS7tNE3CrcMAjz5uiwr_Zlp4CKpCU99hzAKw08g14,1830
103
+ aiohttp/web.py,sha256=lzB4xbNvgULFAN6uxb1Yg63qAyIFgapIHYGk3z7uZeU,18669
104
+ aiohttp/web_app.py,sha256=QEkoioPMr8vLTFGgzGEdOWkX5xM9b44neR-cYyfjs6c,17727
105
+ aiohttp/web_exceptions.py,sha256=ZhwkxigtA1hmmxkVQTH9cTRgU_cz5wb-0Enm-dlj_v4,10539
106
+ aiohttp/web_fileresponse.py,sha256=tRRZyBNPL579Ac8Q2mSF7qjHIkV42z9VyVEkvQLOJlQ,11072
107
+ aiohttp/web_log.py,sha256=IxdzjN1glBIssfpWBv6cS9TtyyAaJF0hJHCqt7IxEtE,7765
108
+ aiohttp/web_middlewares.py,sha256=qmHNhOdhTtJZjChDiBlF9M-SGxF3vz2koDnxMPrlNCA,4256
109
+ aiohttp/web_protocol.py,sha256=VVlY1FBTEg5JxtDhYO7bvfamylBEpKffdJFSN9_6cC8,23078
110
+ aiohttp/web_request.py,sha256=nOKHoJdzco_41mfGHUclYrdoZKazD8dCiAbd0UOwQzU,29069
111
+ aiohttp/web_response.py,sha256=Ont7UsoFinG6fpLwuVTOLHHZDWZ5VM0uGFCOiUII-pk,28296
112
+ aiohttp/web_routedef.py,sha256=KrQtG7OzlE1ylPZf54yDJjBLl36nGvYl8Z9mA6SWayk,6368
113
+ aiohttp/web_runner.py,sha256=OGDcOLBeCZuOPNeTa7wi8bLll_7kzviMAx7vRgKs4UE,11538
114
+ aiohttp/web_server.py,sha256=peGS1H8OvZEd4LuB_hqTA_6HQhc4stFeYQIh4XCmZ2A,2112
115
+ aiohttp/web_urldispatcher.py,sha256=r6lC1U7puKU45VHcvQW5mJ6ienTBCi01ouz077kiJHQ,40703
116
+ aiohttp/web_ws.py,sha256=MqL1XuwXeh_xf3X9oAwvNGvVA3zvxcykR_O26EKkL0A,17631
117
+ aiohttp/worker.py,sha256=WlC9ItbJ3NPCHUFIJcbEGOQkC9kWcumURyxfcKYtqws,9032
runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.37.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp39-cp39-win_amd64
5
+
runtime/Lib/site-packages/aiohttp-3.8.3.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ aiohttp
runtime/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ ac4b44b21b67e78c127ff6422741018d1c9506420ebffa21d7b05c68d39de95f *D:/a/aiohttp/aiohttp/aiohttp/_cparser.pxd
runtime/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ 0455129b185e981b5b96ac738f31f7c74dc57f1696953cae0083b3f18679fe73 *D:/a/aiohttp/aiohttp/aiohttp/_find_header.pxd
runtime/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ d87779202d197f8613109e35dacbb2ca1b21d64572543bf9838b2d832a362ac7 *D:/a/aiohttp/aiohttp/aiohttp/_helpers.pyi
runtime/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ b6097b7d987440c4fa7237f88d227c89a3ba0dd403dc638ddbe487e0de7f1138 *D:/a/aiohttp/aiohttp/aiohttp/_helpers.pyx
runtime/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ d401e8ad876f3d1fec1234129c2593f64c0664a5856a9551653f75d13531ece3 *D:/a/aiohttp/aiohttp/aiohttp/_http_parser.pyx
runtime/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ f0204bcad3b6af1d6476959ef47612ce784b5dd7995b213edf123b8da19ab1a8 *D:/a/aiohttp/aiohttp/aiohttp/_http_writer.pyx
runtime/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ a3d27bca2f5cdbe8d3063137754917c610d62af456273e4665fc8bb202506b7f *D:/a/aiohttp/aiohttp/aiohttp/_websocket.pyx
runtime/Lib/site-packages/aiohttp/.hash/hdrs.py.hash ADDED
@@ -0,0 +1 @@
 
 
1
+ ca00e702a602a2df0d310ca3724dabf42ce94eca40397a47927365fb2c48c9b6 *D:/a/aiohttp/aiohttp/aiohttp/hdrs.py
runtime/Lib/site-packages/aiohttp/__init__.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __version__ = "3.8.3"
2
+
3
+ from typing import Tuple
4
+
5
+ from . import hdrs as hdrs
6
+ from .client import (
7
+ BaseConnector as BaseConnector,
8
+ ClientConnectionError as ClientConnectionError,
9
+ ClientConnectorCertificateError as ClientConnectorCertificateError,
10
+ ClientConnectorError as ClientConnectorError,
11
+ ClientConnectorSSLError as ClientConnectorSSLError,
12
+ ClientError as ClientError,
13
+ ClientHttpProxyError as ClientHttpProxyError,
14
+ ClientOSError as ClientOSError,
15
+ ClientPayloadError as ClientPayloadError,
16
+ ClientProxyConnectionError as ClientProxyConnectionError,
17
+ ClientRequest as ClientRequest,
18
+ ClientResponse as ClientResponse,
19
+ ClientResponseError as ClientResponseError,
20
+ ClientSession as ClientSession,
21
+ ClientSSLError as ClientSSLError,
22
+ ClientTimeout as ClientTimeout,
23
+ ClientWebSocketResponse as ClientWebSocketResponse,
24
+ ContentTypeError as ContentTypeError,
25
+ Fingerprint as Fingerprint,
26
+ InvalidURL as InvalidURL,
27
+ NamedPipeConnector as NamedPipeConnector,
28
+ RequestInfo as RequestInfo,
29
+ ServerConnectionError as ServerConnectionError,
30
+ ServerDisconnectedError as ServerDisconnectedError,
31
+ ServerFingerprintMismatch as ServerFingerprintMismatch,
32
+ ServerTimeoutError as ServerTimeoutError,
33
+ TCPConnector as TCPConnector,
34
+ TooManyRedirects as TooManyRedirects,
35
+ UnixConnector as UnixConnector,
36
+ WSServerHandshakeError as WSServerHandshakeError,
37
+ request as request,
38
+ )
39
+ from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar
40
+ from .formdata import FormData as FormData
41
+ from .helpers import BasicAuth, ChainMapProxy, ETag
42
+ from .http import (
43
+ HttpVersion as HttpVersion,
44
+ HttpVersion10 as HttpVersion10,
45
+ HttpVersion11 as HttpVersion11,
46
+ WebSocketError as WebSocketError,
47
+ WSCloseCode as WSCloseCode,
48
+ WSMessage as WSMessage,
49
+ WSMsgType as WSMsgType,
50
+ )
51
+ from .multipart import (
52
+ BadContentDispositionHeader as BadContentDispositionHeader,
53
+ BadContentDispositionParam as BadContentDispositionParam,
54
+ BodyPartReader as BodyPartReader,
55
+ MultipartReader as MultipartReader,
56
+ MultipartWriter as MultipartWriter,
57
+ content_disposition_filename as content_disposition_filename,
58
+ parse_content_disposition as parse_content_disposition,
59
+ )
60
+ from .payload import (
61
+ PAYLOAD_REGISTRY as PAYLOAD_REGISTRY,
62
+ AsyncIterablePayload as AsyncIterablePayload,
63
+ BufferedReaderPayload as BufferedReaderPayload,
64
+ BytesIOPayload as BytesIOPayload,
65
+ BytesPayload as BytesPayload,
66
+ IOBasePayload as IOBasePayload,
67
+ JsonPayload as JsonPayload,
68
+ Payload as Payload,
69
+ StringIOPayload as StringIOPayload,
70
+ StringPayload as StringPayload,
71
+ TextIOPayload as TextIOPayload,
72
+ get_payload as get_payload,
73
+ payload_type as payload_type,
74
+ )
75
+ from .payload_streamer import streamer as streamer
76
+ from .resolver import (
77
+ AsyncResolver as AsyncResolver,
78
+ DefaultResolver as DefaultResolver,
79
+ ThreadedResolver as ThreadedResolver,
80
+ )
81
+ from .streams import (
82
+ EMPTY_PAYLOAD as EMPTY_PAYLOAD,
83
+ DataQueue as DataQueue,
84
+ EofStream as EofStream,
85
+ FlowControlDataQueue as FlowControlDataQueue,
86
+ StreamReader as StreamReader,
87
+ )
88
+ from .tracing import (
89
+ TraceConfig as TraceConfig,
90
+ TraceConnectionCreateEndParams as TraceConnectionCreateEndParams,
91
+ TraceConnectionCreateStartParams as TraceConnectionCreateStartParams,
92
+ TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams,
93
+ TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams,
94
+ TraceConnectionReuseconnParams as TraceConnectionReuseconnParams,
95
+ TraceDnsCacheHitParams as TraceDnsCacheHitParams,
96
+ TraceDnsCacheMissParams as TraceDnsCacheMissParams,
97
+ TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams,
98
+ TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams,
99
+ TraceRequestChunkSentParams as TraceRequestChunkSentParams,
100
+ TraceRequestEndParams as TraceRequestEndParams,
101
+ TraceRequestExceptionParams as TraceRequestExceptionParams,
102
+ TraceRequestRedirectParams as TraceRequestRedirectParams,
103
+ TraceRequestStartParams as TraceRequestStartParams,
104
+ TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams,
105
+ )
106
+
107
+ __all__: Tuple[str, ...] = (
108
+ "hdrs",
109
+ # client
110
+ "BaseConnector",
111
+ "ClientConnectionError",
112
+ "ClientConnectorCertificateError",
113
+ "ClientConnectorError",
114
+ "ClientConnectorSSLError",
115
+ "ClientError",
116
+ "ClientHttpProxyError",
117
+ "ClientOSError",
118
+ "ClientPayloadError",
119
+ "ClientProxyConnectionError",
120
+ "ClientResponse",
121
+ "ClientRequest",
122
+ "ClientResponseError",
123
+ "ClientSSLError",
124
+ "ClientSession",
125
+ "ClientTimeout",
126
+ "ClientWebSocketResponse",
127
+ "ContentTypeError",
128
+ "Fingerprint",
129
+ "InvalidURL",
130
+ "RequestInfo",
131
+ "ServerConnectionError",
132
+ "ServerDisconnectedError",
133
+ "ServerFingerprintMismatch",
134
+ "ServerTimeoutError",
135
+ "TCPConnector",
136
+ "TooManyRedirects",
137
+ "UnixConnector",
138
+ "NamedPipeConnector",
139
+ "WSServerHandshakeError",
140
+ "request",
141
+ # cookiejar
142
+ "CookieJar",
143
+ "DummyCookieJar",
144
+ # formdata
145
+ "FormData",
146
+ # helpers
147
+ "BasicAuth",
148
+ "ChainMapProxy",
149
+ "ETag",
150
+ # http
151
+ "HttpVersion",
152
+ "HttpVersion10",
153
+ "HttpVersion11",
154
+ "WSMsgType",
155
+ "WSCloseCode",
156
+ "WSMessage",
157
+ "WebSocketError",
158
+ # multipart
159
+ "BadContentDispositionHeader",
160
+ "BadContentDispositionParam",
161
+ "BodyPartReader",
162
+ "MultipartReader",
163
+ "MultipartWriter",
164
+ "content_disposition_filename",
165
+ "parse_content_disposition",
166
+ # payload
167
+ "AsyncIterablePayload",
168
+ "BufferedReaderPayload",
169
+ "BytesIOPayload",
170
+ "BytesPayload",
171
+ "IOBasePayload",
172
+ "JsonPayload",
173
+ "PAYLOAD_REGISTRY",
174
+ "Payload",
175
+ "StringIOPayload",
176
+ "StringPayload",
177
+ "TextIOPayload",
178
+ "get_payload",
179
+ "payload_type",
180
+ # payload_streamer
181
+ "streamer",
182
+ # resolver
183
+ "AsyncResolver",
184
+ "DefaultResolver",
185
+ "ThreadedResolver",
186
+ # streams
187
+ "DataQueue",
188
+ "EMPTY_PAYLOAD",
189
+ "EofStream",
190
+ "FlowControlDataQueue",
191
+ "StreamReader",
192
+ # tracing
193
+ "TraceConfig",
194
+ "TraceConnectionCreateEndParams",
195
+ "TraceConnectionCreateStartParams",
196
+ "TraceConnectionQueuedEndParams",
197
+ "TraceConnectionQueuedStartParams",
198
+ "TraceConnectionReuseconnParams",
199
+ "TraceDnsCacheHitParams",
200
+ "TraceDnsCacheMissParams",
201
+ "TraceDnsResolveHostEndParams",
202
+ "TraceDnsResolveHostStartParams",
203
+ "TraceRequestChunkSentParams",
204
+ "TraceRequestEndParams",
205
+ "TraceRequestExceptionParams",
206
+ "TraceRequestRedirectParams",
207
+ "TraceRequestStartParams",
208
+ "TraceResponseChunkReceivedParams",
209
+ )
210
+
211
+ try:
212
+ from .worker import GunicornUVLoopWebWorker, GunicornWebWorker
213
+
214
+ __all__ += ("GunicornWebWorker", "GunicornUVLoopWebWorker")
215
+ except ImportError: # pragma: no cover
216
+ pass
runtime/Lib/site-packages/aiohttp/_cparser.pxd ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc.stdint cimport (
2
+ int8_t,
3
+ int16_t,
4
+ int32_t,
5
+ int64_t,
6
+ uint8_t,
7
+ uint16_t,
8
+ uint32_t,
9
+ uint64_t,
10
+ )
11
+
12
+
13
+ cdef extern from "../vendor/llhttp/build/llhttp.h":
14
+
15
+ struct llhttp__internal_s:
16
+ int32_t _index
17
+ void* _span_pos0
18
+ void* _span_cb0
19
+ int32_t error
20
+ const char* reason
21
+ const char* error_pos
22
+ void* data
23
+ void* _current
24
+ uint64_t content_length
25
+ uint8_t type
26
+ uint8_t method
27
+ uint8_t http_major
28
+ uint8_t http_minor
29
+ uint8_t header_state
30
+ uint8_t lenient_flags
31
+ uint8_t upgrade
32
+ uint8_t finish
33
+ uint16_t flags
34
+ uint16_t status_code
35
+ void* settings
36
+
37
+ ctypedef llhttp__internal_s llhttp__internal_t
38
+ ctypedef llhttp__internal_t llhttp_t
39
+
40
+ ctypedef int (*llhttp_data_cb)(llhttp_t*, const char *at, size_t length) except -1
41
+ ctypedef int (*llhttp_cb)(llhttp_t*) except -1
42
+
43
+ struct llhttp_settings_s:
44
+ llhttp_cb on_message_begin
45
+ llhttp_data_cb on_url
46
+ llhttp_data_cb on_status
47
+ llhttp_data_cb on_header_field
48
+ llhttp_data_cb on_header_value
49
+ llhttp_cb on_headers_complete
50
+ llhttp_data_cb on_body
51
+ llhttp_cb on_message_complete
52
+ llhttp_cb on_chunk_header
53
+ llhttp_cb on_chunk_complete
54
+
55
+ llhttp_cb on_url_complete
56
+ llhttp_cb on_status_complete
57
+ llhttp_cb on_header_field_complete
58
+ llhttp_cb on_header_value_complete
59
+
60
+ ctypedef llhttp_settings_s llhttp_settings_t
61
+
62
+ enum llhttp_errno:
63
+ HPE_OK,
64
+ HPE_INTERNAL,
65
+ HPE_STRICT,
66
+ HPE_LF_EXPECTED,
67
+ HPE_UNEXPECTED_CONTENT_LENGTH,
68
+ HPE_CLOSED_CONNECTION,
69
+ HPE_INVALID_METHOD,
70
+ HPE_INVALID_URL,
71
+ HPE_INVALID_CONSTANT,
72
+ HPE_INVALID_VERSION,
73
+ HPE_INVALID_HEADER_TOKEN,
74
+ HPE_INVALID_CONTENT_LENGTH,
75
+ HPE_INVALID_CHUNK_SIZE,
76
+ HPE_INVALID_STATUS,
77
+ HPE_INVALID_EOF_STATE,
78
+ HPE_INVALID_TRANSFER_ENCODING,
79
+ HPE_CB_MESSAGE_BEGIN,
80
+ HPE_CB_HEADERS_COMPLETE,
81
+ HPE_CB_MESSAGE_COMPLETE,
82
+ HPE_CB_CHUNK_HEADER,
83
+ HPE_CB_CHUNK_COMPLETE,
84
+ HPE_PAUSED,
85
+ HPE_PAUSED_UPGRADE,
86
+ HPE_USER
87
+
88
+ ctypedef llhttp_errno llhttp_errno_t
89
+
90
+ enum llhttp_flags:
91
+ F_CONNECTION_KEEP_ALIVE,
92
+ F_CONNECTION_CLOSE,
93
+ F_CONNECTION_UPGRADE,
94
+ F_CHUNKED,
95
+ F_UPGRADE,
96
+ F_CONTENT_LENGTH,
97
+ F_SKIPBODY,
98
+ F_TRAILING,
99
+ F_TRANSFER_ENCODING
100
+
101
+ enum llhttp_lenient_flags:
102
+ LENIENT_HEADERS,
103
+ LENIENT_CHUNKED_LENGTH
104
+
105
+ enum llhttp_type:
106
+ HTTP_REQUEST,
107
+ HTTP_RESPONSE,
108
+ HTTP_BOTH
109
+
110
+ enum llhttp_finish_t:
111
+ HTTP_FINISH_SAFE,
112
+ HTTP_FINISH_SAFE_WITH_CB,
113
+ HTTP_FINISH_UNSAFE
114
+
115
+ enum llhttp_method:
116
+ HTTP_DELETE,
117
+ HTTP_GET,
118
+ HTTP_HEAD,
119
+ HTTP_POST,
120
+ HTTP_PUT,
121
+ HTTP_CONNECT,
122
+ HTTP_OPTIONS,
123
+ HTTP_TRACE,
124
+ HTTP_COPY,
125
+ HTTP_LOCK,
126
+ HTTP_MKCOL,
127
+ HTTP_MOVE,
128
+ HTTP_PROPFIND,
129
+ HTTP_PROPPATCH,
130
+ HTTP_SEARCH,
131
+ HTTP_UNLOCK,
132
+ HTTP_BIND,
133
+ HTTP_REBIND,
134
+ HTTP_UNBIND,
135
+ HTTP_ACL,
136
+ HTTP_REPORT,
137
+ HTTP_MKACTIVITY,
138
+ HTTP_CHECKOUT,
139
+ HTTP_MERGE,
140
+ HTTP_MSEARCH,
141
+ HTTP_NOTIFY,
142
+ HTTP_SUBSCRIBE,
143
+ HTTP_UNSUBSCRIBE,
144
+ HTTP_PATCH,
145
+ HTTP_PURGE,
146
+ HTTP_MKCALENDAR,
147
+ HTTP_LINK,
148
+ HTTP_UNLINK,
149
+ HTTP_SOURCE,
150
+ HTTP_PRI,
151
+ HTTP_DESCRIBE,
152
+ HTTP_ANNOUNCE,
153
+ HTTP_SETUP,
154
+ HTTP_PLAY,
155
+ HTTP_PAUSE,
156
+ HTTP_TEARDOWN,
157
+ HTTP_GET_PARAMETER,
158
+ HTTP_SET_PARAMETER,
159
+ HTTP_REDIRECT,
160
+ HTTP_RECORD,
161
+ HTTP_FLUSH
162
+
163
+ ctypedef llhttp_method llhttp_method_t;
164
+
165
+ void llhttp_settings_init(llhttp_settings_t* settings)
166
+ void llhttp_init(llhttp_t* parser, llhttp_type type,
167
+ const llhttp_settings_t* settings)
168
+
169
+ llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len)
170
+ llhttp_errno_t llhttp_finish(llhttp_t* parser)
171
+
172
+ int llhttp_message_needs_eof(const llhttp_t* parser)
173
+
174
+ int llhttp_should_keep_alive(const llhttp_t* parser)
175
+
176
+ void llhttp_pause(llhttp_t* parser)
177
+ void llhttp_resume(llhttp_t* parser)
178
+
179
+ void llhttp_resume_after_upgrade(llhttp_t* parser)
180
+
181
+ llhttp_errno_t llhttp_get_errno(const llhttp_t* parser)
182
+ const char* llhttp_get_error_reason(const llhttp_t* parser)
183
+ void llhttp_set_error_reason(llhttp_t* parser, const char* reason)
184
+ const char* llhttp_get_error_pos(const llhttp_t* parser)
185
+ const char* llhttp_errno_name(llhttp_errno_t err)
186
+
187
+ const char* llhttp_method_name(llhttp_method_t method)
188
+
189
+ void llhttp_set_lenient_headers(llhttp_t* parser, int enabled)
190
+ void llhttp_set_lenient_chunked_length(llhttp_t* parser, int enabled)
runtime/Lib/site-packages/aiohttp/_find_header.pxd ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ cdef extern from "_find_header.h":
2
+ int find_header(char *, int)
runtime/Lib/site-packages/aiohttp/_headers.pxi ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The file is autogenerated from aiohttp/hdrs.py
2
+ # Run ./tools/gen.py to update it after the origin changing.
3
+
4
+ from . import hdrs
5
+ cdef tuple headers = (
6
+ hdrs.ACCEPT,
7
+ hdrs.ACCEPT_CHARSET,
8
+ hdrs.ACCEPT_ENCODING,
9
+ hdrs.ACCEPT_LANGUAGE,
10
+ hdrs.ACCEPT_RANGES,
11
+ hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS,
12
+ hdrs.ACCESS_CONTROL_ALLOW_HEADERS,
13
+ hdrs.ACCESS_CONTROL_ALLOW_METHODS,
14
+ hdrs.ACCESS_CONTROL_ALLOW_ORIGIN,
15
+ hdrs.ACCESS_CONTROL_EXPOSE_HEADERS,
16
+ hdrs.ACCESS_CONTROL_MAX_AGE,
17
+ hdrs.ACCESS_CONTROL_REQUEST_HEADERS,
18
+ hdrs.ACCESS_CONTROL_REQUEST_METHOD,
19
+ hdrs.AGE,
20
+ hdrs.ALLOW,
21
+ hdrs.AUTHORIZATION,
22
+ hdrs.CACHE_CONTROL,
23
+ hdrs.CONNECTION,
24
+ hdrs.CONTENT_DISPOSITION,
25
+ hdrs.CONTENT_ENCODING,
26
+ hdrs.CONTENT_LANGUAGE,
27
+ hdrs.CONTENT_LENGTH,
28
+ hdrs.CONTENT_LOCATION,
29
+ hdrs.CONTENT_MD5,
30
+ hdrs.CONTENT_RANGE,
31
+ hdrs.CONTENT_TRANSFER_ENCODING,
32
+ hdrs.CONTENT_TYPE,
33
+ hdrs.COOKIE,
34
+ hdrs.DATE,
35
+ hdrs.DESTINATION,
36
+ hdrs.DIGEST,
37
+ hdrs.ETAG,
38
+ hdrs.EXPECT,
39
+ hdrs.EXPIRES,
40
+ hdrs.FORWARDED,
41
+ hdrs.FROM,
42
+ hdrs.HOST,
43
+ hdrs.IF_MATCH,
44
+ hdrs.IF_MODIFIED_SINCE,
45
+ hdrs.IF_NONE_MATCH,
46
+ hdrs.IF_RANGE,
47
+ hdrs.IF_UNMODIFIED_SINCE,
48
+ hdrs.KEEP_ALIVE,
49
+ hdrs.LAST_EVENT_ID,
50
+ hdrs.LAST_MODIFIED,
51
+ hdrs.LINK,
52
+ hdrs.LOCATION,
53
+ hdrs.MAX_FORWARDS,
54
+ hdrs.ORIGIN,
55
+ hdrs.PRAGMA,
56
+ hdrs.PROXY_AUTHENTICATE,
57
+ hdrs.PROXY_AUTHORIZATION,
58
+ hdrs.RANGE,
59
+ hdrs.REFERER,
60
+ hdrs.RETRY_AFTER,
61
+ hdrs.SEC_WEBSOCKET_ACCEPT,
62
+ hdrs.SEC_WEBSOCKET_EXTENSIONS,
63
+ hdrs.SEC_WEBSOCKET_KEY,
64
+ hdrs.SEC_WEBSOCKET_KEY1,
65
+ hdrs.SEC_WEBSOCKET_PROTOCOL,
66
+ hdrs.SEC_WEBSOCKET_VERSION,
67
+ hdrs.SERVER,
68
+ hdrs.SET_COOKIE,
69
+ hdrs.TE,
70
+ hdrs.TRAILER,
71
+ hdrs.TRANSFER_ENCODING,
72
+ hdrs.URI,
73
+ hdrs.UPGRADE,
74
+ hdrs.USER_AGENT,
75
+ hdrs.VARY,
76
+ hdrs.VIA,
77
+ hdrs.WWW_AUTHENTICATE,
78
+ hdrs.WANT_DIGEST,
79
+ hdrs.WARNING,
80
+ hdrs.X_FORWARDED_FOR,
81
+ hdrs.X_FORWARDED_HOST,
82
+ hdrs.X_FORWARDED_PROTO,
83
+ )
runtime/Lib/site-packages/aiohttp/_helpers.cp39-win_amd64.pyd ADDED
Binary file (39.9 kB). View file
 
runtime/Lib/site-packages/aiohttp/_helpers.pyi ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ class reify:
4
+ def __init__(self, wrapped: Any) -> None: ...
5
+ def __get__(self, inst: Any, owner: Any) -> Any: ...
6
+ def __set__(self, inst: Any, value: Any) -> None: ...
runtime/Lib/site-packages/aiohttp/_helpers.pyx ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cdef class reify:
2
+ """Use as a class method decorator. It operates almost exactly like
3
+ the Python `@property` decorator, but it puts the result of the
4
+ method it decorates into the instance dict after the first call,
5
+ effectively replacing the function it decorates with an instance
6
+ variable. It is, in Python parlance, a data descriptor.
7
+
8
+ """
9
+
10
+ cdef object wrapped
11
+ cdef object name
12
+
13
+ def __init__(self, wrapped):
14
+ self.wrapped = wrapped
15
+ self.name = wrapped.__name__
16
+
17
+ @property
18
+ def __doc__(self):
19
+ return self.wrapped.__doc__
20
+
21
+ def __get__(self, inst, owner):
22
+ try:
23
+ try:
24
+ return inst._cache[self.name]
25
+ except KeyError:
26
+ val = self.wrapped(inst)
27
+ inst._cache[self.name] = val
28
+ return val
29
+ except AttributeError:
30
+ if inst is None:
31
+ return self
32
+ raise
33
+
34
+ def __set__(self, inst, value):
35
+ raise AttributeError("reified property is read-only")
runtime/Lib/site-packages/aiohttp/_http_parser.cp39-win_amd64.pyd ADDED
Binary file (216 kB). View file
 
runtime/Lib/site-packages/aiohttp/_http_parser.pyx ADDED
@@ -0,0 +1,832 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #cython: language_level=3
2
+ #
3
+ # Based on https://github.com/MagicStack/httptools
4
+ #
5
+ from __future__ import absolute_import, print_function
6
+
7
+ from cpython cimport (
8
+ Py_buffer,
9
+ PyBUF_SIMPLE,
10
+ PyBuffer_Release,
11
+ PyBytes_AsString,
12
+ PyBytes_AsStringAndSize,
13
+ PyObject_GetBuffer,
14
+ )
15
+ from cpython.mem cimport PyMem_Free, PyMem_Malloc
16
+ from libc.limits cimport ULLONG_MAX
17
+ from libc.string cimport memcpy
18
+
19
+ from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy
20
+ from yarl import URL as _URL
21
+
22
+ from aiohttp import hdrs
23
+
24
+ from .http_exceptions import (
25
+ BadHttpMessage,
26
+ BadStatusLine,
27
+ ContentLengthError,
28
+ InvalidHeader,
29
+ InvalidURLError,
30
+ LineTooLong,
31
+ PayloadEncodingError,
32
+ TransferEncodingError,
33
+ )
34
+ from .http_parser import DeflateBuffer as _DeflateBuffer
35
+ from .http_writer import (
36
+ HttpVersion as _HttpVersion,
37
+ HttpVersion10 as _HttpVersion10,
38
+ HttpVersion11 as _HttpVersion11,
39
+ )
40
+ from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader
41
+
42
+ cimport cython
43
+
44
+ from aiohttp cimport _cparser as cparser
45
+
46
+ include "_headers.pxi"
47
+
48
+ from aiohttp cimport _find_header
49
+
50
+ DEF DEFAULT_FREELIST_SIZE = 250
51
+
52
+ cdef extern from "Python.h":
53
+ int PyByteArray_Resize(object, Py_ssize_t) except -1
54
+ Py_ssize_t PyByteArray_Size(object) except -1
55
+ char* PyByteArray_AsString(object)
56
+
57
+ __all__ = ('HttpRequestParser', 'HttpResponseParser',
58
+ 'RawRequestMessage', 'RawResponseMessage')
59
+
60
+ cdef object URL = _URL
61
+ cdef object URL_build = URL.build
62
+ cdef object CIMultiDict = _CIMultiDict
63
+ cdef object CIMultiDictProxy = _CIMultiDictProxy
64
+ cdef object HttpVersion = _HttpVersion
65
+ cdef object HttpVersion10 = _HttpVersion10
66
+ cdef object HttpVersion11 = _HttpVersion11
67
+ cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1
68
+ cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING
69
+ cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD
70
+ cdef object StreamReader = _StreamReader
71
+ cdef object DeflateBuffer = _DeflateBuffer
72
+
73
+
74
+ cdef inline object extend(object buf, const char* at, size_t length):
75
+ cdef Py_ssize_t s
76
+ cdef char* ptr
77
+ s = PyByteArray_Size(buf)
78
+ PyByteArray_Resize(buf, s + length)
79
+ ptr = PyByteArray_AsString(buf)
80
+ memcpy(ptr + s, at, length)
81
+
82
+
83
+ DEF METHODS_COUNT = 46;
84
+
85
+ cdef list _http_method = []
86
+
87
+ for i in range(METHODS_COUNT):
88
+ _http_method.append(
89
+ cparser.llhttp_method_name(<cparser.llhttp_method_t> i).decode('ascii'))
90
+
91
+
92
+ cdef inline str http_method_str(int i):
93
+ if i < METHODS_COUNT:
94
+ return <str>_http_method[i]
95
+ else:
96
+ return "<unknown>"
97
+
98
+ cdef inline object find_header(bytes raw_header):
99
+ cdef Py_ssize_t size
100
+ cdef char *buf
101
+ cdef int idx
102
+ PyBytes_AsStringAndSize(raw_header, &buf, &size)
103
+ idx = _find_header.find_header(buf, size)
104
+ if idx == -1:
105
+ return raw_header.decode('utf-8', 'surrogateescape')
106
+ return headers[idx]
107
+
108
+
109
+ @cython.freelist(DEFAULT_FREELIST_SIZE)
110
+ cdef class RawRequestMessage:
111
+ cdef readonly str method
112
+ cdef readonly str path
113
+ cdef readonly object version # HttpVersion
114
+ cdef readonly object headers # CIMultiDict
115
+ cdef readonly object raw_headers # tuple
116
+ cdef readonly object should_close
117
+ cdef readonly object compression
118
+ cdef readonly object upgrade
119
+ cdef readonly object chunked
120
+ cdef readonly object url # yarl.URL
121
+
122
+ def __init__(self, method, path, version, headers, raw_headers,
123
+ should_close, compression, upgrade, chunked, url):
124
+ self.method = method
125
+ self.path = path
126
+ self.version = version
127
+ self.headers = headers
128
+ self.raw_headers = raw_headers
129
+ self.should_close = should_close
130
+ self.compression = compression
131
+ self.upgrade = upgrade
132
+ self.chunked = chunked
133
+ self.url = url
134
+
135
+ def __repr__(self):
136
+ info = []
137
+ info.append(("method", self.method))
138
+ info.append(("path", self.path))
139
+ info.append(("version", self.version))
140
+ info.append(("headers", self.headers))
141
+ info.append(("raw_headers", self.raw_headers))
142
+ info.append(("should_close", self.should_close))
143
+ info.append(("compression", self.compression))
144
+ info.append(("upgrade", self.upgrade))
145
+ info.append(("chunked", self.chunked))
146
+ info.append(("url", self.url))
147
+ sinfo = ', '.join(name + '=' + repr(val) for name, val in info)
148
+ return '<RawRequestMessage(' + sinfo + ')>'
149
+
150
+ def _replace(self, **dct):
151
+ cdef RawRequestMessage ret
152
+ ret = _new_request_message(self.method,
153
+ self.path,
154
+ self.version,
155
+ self.headers,
156
+ self.raw_headers,
157
+ self.should_close,
158
+ self.compression,
159
+ self.upgrade,
160
+ self.chunked,
161
+ self.url)
162
+ if "method" in dct:
163
+ ret.method = dct["method"]
164
+ if "path" in dct:
165
+ ret.path = dct["path"]
166
+ if "version" in dct:
167
+ ret.version = dct["version"]
168
+ if "headers" in dct:
169
+ ret.headers = dct["headers"]
170
+ if "raw_headers" in dct:
171
+ ret.raw_headers = dct["raw_headers"]
172
+ if "should_close" in dct:
173
+ ret.should_close = dct["should_close"]
174
+ if "compression" in dct:
175
+ ret.compression = dct["compression"]
176
+ if "upgrade" in dct:
177
+ ret.upgrade = dct["upgrade"]
178
+ if "chunked" in dct:
179
+ ret.chunked = dct["chunked"]
180
+ if "url" in dct:
181
+ ret.url = dct["url"]
182
+ return ret
183
+
184
+ cdef _new_request_message(str method,
185
+ str path,
186
+ object version,
187
+ object headers,
188
+ object raw_headers,
189
+ bint should_close,
190
+ object compression,
191
+ bint upgrade,
192
+ bint chunked,
193
+ object url):
194
+ cdef RawRequestMessage ret
195
+ ret = RawRequestMessage.__new__(RawRequestMessage)
196
+ ret.method = method
197
+ ret.path = path
198
+ ret.version = version
199
+ ret.headers = headers
200
+ ret.raw_headers = raw_headers
201
+ ret.should_close = should_close
202
+ ret.compression = compression
203
+ ret.upgrade = upgrade
204
+ ret.chunked = chunked
205
+ ret.url = url
206
+ return ret
207
+
208
+
209
+ @cython.freelist(DEFAULT_FREELIST_SIZE)
210
+ cdef class RawResponseMessage:
211
+ cdef readonly object version # HttpVersion
212
+ cdef readonly int code
213
+ cdef readonly str reason
214
+ cdef readonly object headers # CIMultiDict
215
+ cdef readonly object raw_headers # tuple
216
+ cdef readonly object should_close
217
+ cdef readonly object compression
218
+ cdef readonly object upgrade
219
+ cdef readonly object chunked
220
+
221
+ def __init__(self, version, code, reason, headers, raw_headers,
222
+ should_close, compression, upgrade, chunked):
223
+ self.version = version
224
+ self.code = code
225
+ self.reason = reason
226
+ self.headers = headers
227
+ self.raw_headers = raw_headers
228
+ self.should_close = should_close
229
+ self.compression = compression
230
+ self.upgrade = upgrade
231
+ self.chunked = chunked
232
+
233
+ def __repr__(self):
234
+ info = []
235
+ info.append(("version", self.version))
236
+ info.append(("code", self.code))
237
+ info.append(("reason", self.reason))
238
+ info.append(("headers", self.headers))
239
+ info.append(("raw_headers", self.raw_headers))
240
+ info.append(("should_close", self.should_close))
241
+ info.append(("compression", self.compression))
242
+ info.append(("upgrade", self.upgrade))
243
+ info.append(("chunked", self.chunked))
244
+ sinfo = ', '.join(name + '=' + repr(val) for name, val in info)
245
+ return '<RawResponseMessage(' + sinfo + ')>'
246
+
247
+
248
+ cdef _new_response_message(object version,
249
+ int code,
250
+ str reason,
251
+ object headers,
252
+ object raw_headers,
253
+ bint should_close,
254
+ object compression,
255
+ bint upgrade,
256
+ bint chunked):
257
+ cdef RawResponseMessage ret
258
+ ret = RawResponseMessage.__new__(RawResponseMessage)
259
+ ret.version = version
260
+ ret.code = code
261
+ ret.reason = reason
262
+ ret.headers = headers
263
+ ret.raw_headers = raw_headers
264
+ ret.should_close = should_close
265
+ ret.compression = compression
266
+ ret.upgrade = upgrade
267
+ ret.chunked = chunked
268
+ return ret
269
+
270
+
271
+ @cython.internal
272
+ cdef class HttpParser:
273
+
274
+ cdef:
275
+ cparser.llhttp_t* _cparser
276
+ cparser.llhttp_settings_t* _csettings
277
+
278
+ bytearray _raw_name
279
+ bytearray _raw_value
280
+ bint _has_value
281
+
282
+ object _protocol
283
+ object _loop
284
+ object _timer
285
+
286
+ size_t _max_line_size
287
+ size_t _max_field_size
288
+ size_t _max_headers
289
+ bint _response_with_body
290
+ bint _read_until_eof
291
+
292
+ bint _started
293
+ object _url
294
+ bytearray _buf
295
+ str _path
296
+ str _reason
297
+ object _headers
298
+ list _raw_headers
299
+ bint _upgraded
300
+ list _messages
301
+ object _payload
302
+ bint _payload_error
303
+ object _payload_exception
304
+ object _last_error
305
+ bint _auto_decompress
306
+ int _limit
307
+
308
+ str _content_encoding
309
+
310
+ Py_buffer py_buf
311
+
312
+ def __cinit__(self):
313
+ self._cparser = <cparser.llhttp_t*> \
314
+ PyMem_Malloc(sizeof(cparser.llhttp_t))
315
+ if self._cparser is NULL:
316
+ raise MemoryError()
317
+
318
+ self._csettings = <cparser.llhttp_settings_t*> \
319
+ PyMem_Malloc(sizeof(cparser.llhttp_settings_t))
320
+ if self._csettings is NULL:
321
+ raise MemoryError()
322
+
323
+ def __dealloc__(self):
324
+ PyMem_Free(self._cparser)
325
+ PyMem_Free(self._csettings)
326
+
327
+ cdef _init(
328
+ self, cparser.llhttp_type mode,
329
+ object protocol, object loop, int limit,
330
+ object timer=None,
331
+ size_t max_line_size=8190, size_t max_headers=32768,
332
+ size_t max_field_size=8190, payload_exception=None,
333
+ bint response_with_body=True, bint read_until_eof=False,
334
+ bint auto_decompress=True,
335
+ ):
336
+ cparser.llhttp_settings_init(self._csettings)
337
+ cparser.llhttp_init(self._cparser, mode, self._csettings)
338
+ self._cparser.data = <void*>self
339
+ self._cparser.content_length = 0
340
+
341
+ self._protocol = protocol
342
+ self._loop = loop
343
+ self._timer = timer
344
+
345
+ self._buf = bytearray()
346
+ self._payload = None
347
+ self._payload_error = 0
348
+ self._payload_exception = payload_exception
349
+ self._messages = []
350
+
351
+ self._raw_name = bytearray()
352
+ self._raw_value = bytearray()
353
+ self._has_value = False
354
+
355
+ self._max_line_size = max_line_size
356
+ self._max_headers = max_headers
357
+ self._max_field_size = max_field_size
358
+ self._response_with_body = response_with_body
359
+ self._read_until_eof = read_until_eof
360
+ self._upgraded = False
361
+ self._auto_decompress = auto_decompress
362
+ self._content_encoding = None
363
+
364
+ self._csettings.on_url = cb_on_url
365
+ self._csettings.on_status = cb_on_status
366
+ self._csettings.on_header_field = cb_on_header_field
367
+ self._csettings.on_header_value = cb_on_header_value
368
+ self._csettings.on_headers_complete = cb_on_headers_complete
369
+ self._csettings.on_body = cb_on_body
370
+ self._csettings.on_message_begin = cb_on_message_begin
371
+ self._csettings.on_message_complete = cb_on_message_complete
372
+ self._csettings.on_chunk_header = cb_on_chunk_header
373
+ self._csettings.on_chunk_complete = cb_on_chunk_complete
374
+
375
+ self._last_error = None
376
+ self._limit = limit
377
+
378
+ cdef _process_header(self):
379
+ if self._raw_name:
380
+ raw_name = bytes(self._raw_name)
381
+ raw_value = bytes(self._raw_value)
382
+
383
+ name = find_header(raw_name)
384
+ value = raw_value.decode('utf-8', 'surrogateescape')
385
+
386
+ self._headers.add(name, value)
387
+
388
+ if name is CONTENT_ENCODING:
389
+ self._content_encoding = value
390
+
391
+ PyByteArray_Resize(self._raw_name, 0)
392
+ PyByteArray_Resize(self._raw_value, 0)
393
+ self._has_value = False
394
+ self._raw_headers.append((raw_name, raw_value))
395
+
396
+ cdef _on_header_field(self, char* at, size_t length):
397
+ cdef Py_ssize_t size
398
+ cdef char *buf
399
+ if self._has_value:
400
+ self._process_header()
401
+
402
+ size = PyByteArray_Size(self._raw_name)
403
+ PyByteArray_Resize(self._raw_name, size + length)
404
+ buf = PyByteArray_AsString(self._raw_name)
405
+ memcpy(buf + size, at, length)
406
+
407
+ cdef _on_header_value(self, char* at, size_t length):
408
+ cdef Py_ssize_t size
409
+ cdef char *buf
410
+
411
+ size = PyByteArray_Size(self._raw_value)
412
+ PyByteArray_Resize(self._raw_value, size + length)
413
+ buf = PyByteArray_AsString(self._raw_value)
414
+ memcpy(buf + size, at, length)
415
+ self._has_value = True
416
+
417
+ cdef _on_headers_complete(self):
418
+ self._process_header()
419
+
420
+ method = http_method_str(self._cparser.method)
421
+ should_close = not cparser.llhttp_should_keep_alive(self._cparser)
422
+ upgrade = self._cparser.upgrade
423
+ chunked = self._cparser.flags & cparser.F_CHUNKED
424
+
425
+ raw_headers = tuple(self._raw_headers)
426
+ headers = CIMultiDictProxy(self._headers)
427
+
428
+ if upgrade or self._cparser.method == cparser.HTTP_CONNECT:
429
+ self._upgraded = True
430
+
431
+ # do not support old websocket spec
432
+ if SEC_WEBSOCKET_KEY1 in headers:
433
+ raise InvalidHeader(SEC_WEBSOCKET_KEY1)
434
+
435
+ encoding = None
436
+ enc = self._content_encoding
437
+ if enc is not None:
438
+ self._content_encoding = None
439
+ enc = enc.lower()
440
+ if enc in ('gzip', 'deflate', 'br'):
441
+ encoding = enc
442
+
443
+ if self._cparser.type == cparser.HTTP_REQUEST:
444
+ msg = _new_request_message(
445
+ method, self._path,
446
+ self.http_version(), headers, raw_headers,
447
+ should_close, encoding, upgrade, chunked, self._url)
448
+ else:
449
+ msg = _new_response_message(
450
+ self.http_version(), self._cparser.status_code, self._reason,
451
+ headers, raw_headers, should_close, encoding,
452
+ upgrade, chunked)
453
+
454
+ if (
455
+ ULLONG_MAX > self._cparser.content_length > 0 or chunked or
456
+ self._cparser.method == cparser.HTTP_CONNECT or
457
+ (self._cparser.status_code >= 199 and
458
+ self._cparser.content_length == 0 and
459
+ self._read_until_eof)
460
+ ):
461
+ payload = StreamReader(
462
+ self._protocol, timer=self._timer, loop=self._loop,
463
+ limit=self._limit)
464
+ else:
465
+ payload = EMPTY_PAYLOAD
466
+
467
+ self._payload = payload
468
+ if encoding is not None and self._auto_decompress:
469
+ self._payload = DeflateBuffer(payload, encoding)
470
+
471
+ if not self._response_with_body:
472
+ payload = EMPTY_PAYLOAD
473
+
474
+ self._messages.append((msg, payload))
475
+
476
+ cdef _on_message_complete(self):
477
+ self._payload.feed_eof()
478
+ self._payload = None
479
+
480
+ cdef _on_chunk_header(self):
481
+ self._payload.begin_http_chunk_receiving()
482
+
483
+ cdef _on_chunk_complete(self):
484
+ self._payload.end_http_chunk_receiving()
485
+
486
+ cdef object _on_status_complete(self):
487
+ pass
488
+
489
+ cdef inline http_version(self):
490
+ cdef cparser.llhttp_t* parser = self._cparser
491
+
492
+ if parser.http_major == 1:
493
+ if parser.http_minor == 0:
494
+ return HttpVersion10
495
+ elif parser.http_minor == 1:
496
+ return HttpVersion11
497
+
498
+ return HttpVersion(parser.http_major, parser.http_minor)
499
+
500
+ ### Public API ###
501
+
502
+ def feed_eof(self):
503
+ cdef bytes desc
504
+
505
+ if self._payload is not None:
506
+ if self._cparser.flags & cparser.F_CHUNKED:
507
+ raise TransferEncodingError(
508
+ "Not enough data for satisfy transfer length header.")
509
+ elif self._cparser.flags & cparser.F_CONTENT_LENGTH:
510
+ raise ContentLengthError(
511
+ "Not enough data for satisfy content length header.")
512
+ elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK:
513
+ desc = cparser.llhttp_get_error_reason(self._cparser)
514
+ raise PayloadEncodingError(desc.decode('latin-1'))
515
+ else:
516
+ self._payload.feed_eof()
517
+ elif self._started:
518
+ self._on_headers_complete()
519
+ if self._messages:
520
+ return self._messages[-1][0]
521
+
522
+ def feed_data(self, data):
523
+ cdef:
524
+ size_t data_len
525
+ size_t nb
526
+ cdef cparser.llhttp_errno_t errno
527
+
528
+ PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE)
529
+ data_len = <size_t>self.py_buf.len
530
+
531
+ errno = cparser.llhttp_execute(
532
+ self._cparser,
533
+ <char*>self.py_buf.buf,
534
+ data_len)
535
+
536
+ if errno is cparser.HPE_PAUSED_UPGRADE:
537
+ cparser.llhttp_resume_after_upgrade(self._cparser)
538
+
539
+ nb = cparser.llhttp_get_error_pos(self._cparser) - <char*>self.py_buf.buf
540
+
541
+ PyBuffer_Release(&self.py_buf)
542
+
543
+ if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE):
544
+ if self._payload_error == 0:
545
+ if self._last_error is not None:
546
+ ex = self._last_error
547
+ self._last_error = None
548
+ else:
549
+ ex = parser_error_from_errno(self._cparser)
550
+ self._payload = None
551
+ raise ex
552
+
553
+ if self._messages:
554
+ messages = self._messages
555
+ self._messages = []
556
+ else:
557
+ messages = ()
558
+
559
+ if self._upgraded:
560
+ return messages, True, data[nb:]
561
+ else:
562
+ return messages, False, b''
563
+
564
+ def set_upgraded(self, val):
565
+ self._upgraded = val
566
+
567
+
568
+ cdef class HttpRequestParser(HttpParser):
569
+
570
+ def __init__(
571
+ self, protocol, loop, int limit, timer=None,
572
+ size_t max_line_size=8190, size_t max_headers=32768,
573
+ size_t max_field_size=8190, payload_exception=None,
574
+ bint response_with_body=True, bint read_until_eof=False,
575
+ bint auto_decompress=True,
576
+ ):
577
+ self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer,
578
+ max_line_size, max_headers, max_field_size,
579
+ payload_exception, response_with_body, read_until_eof,
580
+ auto_decompress)
581
+
582
+ cdef object _on_status_complete(self):
583
+ cdef int idx1, idx2
584
+ if not self._buf:
585
+ return
586
+ self._path = self._buf.decode('utf-8', 'surrogateescape')
587
+ try:
588
+ idx3 = len(self._path)
589
+ if self._cparser.method == cparser.HTTP_CONNECT:
590
+ # authority-form,
591
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
592
+ self._url = URL.build(authority=self._path, encoded=True)
593
+ elif idx3 > 1 and self._path[0] == '/':
594
+ # origin-form,
595
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
596
+ idx1 = self._path.find("?")
597
+ if idx1 == -1:
598
+ query = ""
599
+ idx2 = self._path.find("#")
600
+ if idx2 == -1:
601
+ path = self._path
602
+ fragment = ""
603
+ else:
604
+ path = self._path[0: idx2]
605
+ fragment = self._path[idx2+1:]
606
+
607
+ else:
608
+ path = self._path[0:idx1]
609
+ idx1 += 1
610
+ idx2 = self._path.find("#", idx1+1)
611
+ if idx2 == -1:
612
+ query = self._path[idx1:]
613
+ fragment = ""
614
+ else:
615
+ query = self._path[idx1: idx2]
616
+ fragment = self._path[idx2+1:]
617
+
618
+ self._url = URL.build(
619
+ path=path,
620
+ query_string=query,
621
+ fragment=fragment,
622
+ encoded=True,
623
+ )
624
+ else:
625
+ # absolute-form for proxy maybe,
626
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
627
+ self._url = URL(self._path, encoded=True)
628
+ finally:
629
+ PyByteArray_Resize(self._buf, 0)
630
+
631
+
632
+ cdef class HttpResponseParser(HttpParser):
633
+
634
+ def __init__(
635
+ self, protocol, loop, int limit, timer=None,
636
+ size_t max_line_size=8190, size_t max_headers=32768,
637
+ size_t max_field_size=8190, payload_exception=None,
638
+ bint response_with_body=True, bint read_until_eof=False,
639
+ bint auto_decompress=True
640
+ ):
641
+ self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer,
642
+ max_line_size, max_headers, max_field_size,
643
+ payload_exception, response_with_body, read_until_eof,
644
+ auto_decompress)
645
+
646
+ cdef object _on_status_complete(self):
647
+ if self._buf:
648
+ self._reason = self._buf.decode('utf-8', 'surrogateescape')
649
+ PyByteArray_Resize(self._buf, 0)
650
+ else:
651
+ self._reason = self._reason or ''
652
+
653
+ cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1:
654
+ cdef HttpParser pyparser = <HttpParser>parser.data
655
+
656
+ pyparser._started = True
657
+ pyparser._headers = CIMultiDict()
658
+ pyparser._raw_headers = []
659
+ PyByteArray_Resize(pyparser._buf, 0)
660
+ pyparser._path = None
661
+ pyparser._reason = None
662
+ return 0
663
+
664
+
665
+ cdef int cb_on_url(cparser.llhttp_t* parser,
666
+ const char *at, size_t length) except -1:
667
+ cdef HttpParser pyparser = <HttpParser>parser.data
668
+ try:
669
+ if length > pyparser._max_line_size:
670
+ raise LineTooLong(
671
+ 'Status line is too long', pyparser._max_line_size, length)
672
+ extend(pyparser._buf, at, length)
673
+ except BaseException as ex:
674
+ pyparser._last_error = ex
675
+ return -1
676
+ else:
677
+ return 0
678
+
679
+
680
+ cdef int cb_on_status(cparser.llhttp_t* parser,
681
+ const char *at, size_t length) except -1:
682
+ cdef HttpParser pyparser = <HttpParser>parser.data
683
+ cdef str reason
684
+ try:
685
+ if length > pyparser._max_line_size:
686
+ raise LineTooLong(
687
+ 'Status line is too long', pyparser._max_line_size, length)
688
+ extend(pyparser._buf, at, length)
689
+ except BaseException as ex:
690
+ pyparser._last_error = ex
691
+ return -1
692
+ else:
693
+ return 0
694
+
695
+
696
+ cdef int cb_on_header_field(cparser.llhttp_t* parser,
697
+ const char *at, size_t length) except -1:
698
+ cdef HttpParser pyparser = <HttpParser>parser.data
699
+ cdef Py_ssize_t size
700
+ try:
701
+ pyparser._on_status_complete()
702
+ size = len(pyparser._raw_name) + length
703
+ if size > pyparser._max_field_size:
704
+ raise LineTooLong(
705
+ 'Header name is too long', pyparser._max_field_size, size)
706
+ pyparser._on_header_field(at, length)
707
+ except BaseException as ex:
708
+ pyparser._last_error = ex
709
+ return -1
710
+ else:
711
+ return 0
712
+
713
+
714
+ cdef int cb_on_header_value(cparser.llhttp_t* parser,
715
+ const char *at, size_t length) except -1:
716
+ cdef HttpParser pyparser = <HttpParser>parser.data
717
+ cdef Py_ssize_t size
718
+ try:
719
+ size = len(pyparser._raw_value) + length
720
+ if size > pyparser._max_field_size:
721
+ raise LineTooLong(
722
+ 'Header value is too long', pyparser._max_field_size, size)
723
+ pyparser._on_header_value(at, length)
724
+ except BaseException as ex:
725
+ pyparser._last_error = ex
726
+ return -1
727
+ else:
728
+ return 0
729
+
730
+
731
+ cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1:
732
+ cdef HttpParser pyparser = <HttpParser>parser.data
733
+ try:
734
+ pyparser._on_status_complete()
735
+ pyparser._on_headers_complete()
736
+ except BaseException as exc:
737
+ pyparser._last_error = exc
738
+ return -1
739
+ else:
740
+ if (
741
+ pyparser._cparser.upgrade or
742
+ pyparser._cparser.method == cparser.HTTP_CONNECT
743
+ ):
744
+ return 2
745
+ else:
746
+ return 0
747
+
748
+
749
+ cdef int cb_on_body(cparser.llhttp_t* parser,
750
+ const char *at, size_t length) except -1:
751
+ cdef HttpParser pyparser = <HttpParser>parser.data
752
+ cdef bytes body = at[:length]
753
+ try:
754
+ pyparser._payload.feed_data(body, length)
755
+ except BaseException as exc:
756
+ if pyparser._payload_exception is not None:
757
+ pyparser._payload.set_exception(pyparser._payload_exception(str(exc)))
758
+ else:
759
+ pyparser._payload.set_exception(exc)
760
+ pyparser._payload_error = 1
761
+ return -1
762
+ else:
763
+ return 0
764
+
765
+
766
+ cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1:
767
+ cdef HttpParser pyparser = <HttpParser>parser.data
768
+ try:
769
+ pyparser._started = False
770
+ pyparser._on_message_complete()
771
+ except BaseException as exc:
772
+ pyparser._last_error = exc
773
+ return -1
774
+ else:
775
+ return 0
776
+
777
+
778
+ cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1:
779
+ cdef HttpParser pyparser = <HttpParser>parser.data
780
+ try:
781
+ pyparser._on_chunk_header()
782
+ except BaseException as exc:
783
+ pyparser._last_error = exc
784
+ return -1
785
+ else:
786
+ return 0
787
+
788
+
789
+ cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1:
790
+ cdef HttpParser pyparser = <HttpParser>parser.data
791
+ try:
792
+ pyparser._on_chunk_complete()
793
+ except BaseException as exc:
794
+ pyparser._last_error = exc
795
+ return -1
796
+ else:
797
+ return 0
798
+
799
+
800
+ cdef parser_error_from_errno(cparser.llhttp_t* parser):
801
+ cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser)
802
+ cdef bytes desc = cparser.llhttp_get_error_reason(parser)
803
+
804
+ if errno in (cparser.HPE_CB_MESSAGE_BEGIN,
805
+ cparser.HPE_CB_HEADERS_COMPLETE,
806
+ cparser.HPE_CB_MESSAGE_COMPLETE,
807
+ cparser.HPE_CB_CHUNK_HEADER,
808
+ cparser.HPE_CB_CHUNK_COMPLETE,
809
+ cparser.HPE_INVALID_CONSTANT,
810
+ cparser.HPE_INVALID_HEADER_TOKEN,
811
+ cparser.HPE_INVALID_CONTENT_LENGTH,
812
+ cparser.HPE_INVALID_CHUNK_SIZE,
813
+ cparser.HPE_INVALID_EOF_STATE,
814
+ cparser.HPE_INVALID_TRANSFER_ENCODING):
815
+ cls = BadHttpMessage
816
+
817
+ elif errno == cparser.HPE_INVALID_STATUS:
818
+ cls = BadStatusLine
819
+
820
+ elif errno == cparser.HPE_INVALID_METHOD:
821
+ cls = BadStatusLine
822
+
823
+ elif errno == cparser.HPE_INVALID_VERSION:
824
+ cls = BadStatusLine
825
+
826
+ elif errno == cparser.HPE_INVALID_URL:
827
+ cls = InvalidURLError
828
+
829
+ else:
830
+ cls = BadHttpMessage
831
+
832
+ return cls(desc.decode('latin-1'))
runtime/Lib/site-packages/aiohttp/_http_writer.cp39-win_amd64.pyd ADDED
Binary file (35.8 kB). View file
 
runtime/Lib/site-packages/aiohttp/_http_writer.pyx ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cpython.bytes cimport PyBytes_FromStringAndSize
2
+ from cpython.exc cimport PyErr_NoMemory
3
+ from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc
4
+ from cpython.object cimport PyObject_Str
5
+ from libc.stdint cimport uint8_t, uint64_t
6
+ from libc.string cimport memcpy
7
+
8
+ from multidict import istr
9
+
10
+ DEF BUF_SIZE = 16 * 1024 # 16KiB
11
+ cdef char BUFFER[BUF_SIZE]
12
+
13
+ cdef object _istr = istr
14
+
15
+
16
+ # ----------------- writer ---------------------------
17
+
18
+ cdef struct Writer:
19
+ char *buf
20
+ Py_ssize_t size
21
+ Py_ssize_t pos
22
+
23
+
24
+ cdef inline void _init_writer(Writer* writer):
25
+ writer.buf = &BUFFER[0]
26
+ writer.size = BUF_SIZE
27
+ writer.pos = 0
28
+
29
+
30
+ cdef inline void _release_writer(Writer* writer):
31
+ if writer.buf != BUFFER:
32
+ PyMem_Free(writer.buf)
33
+
34
+
35
+ cdef inline int _write_byte(Writer* writer, uint8_t ch):
36
+ cdef char * buf
37
+ cdef Py_ssize_t size
38
+
39
+ if writer.pos == writer.size:
40
+ # reallocate
41
+ size = writer.size + BUF_SIZE
42
+ if writer.buf == BUFFER:
43
+ buf = <char*>PyMem_Malloc(size)
44
+ if buf == NULL:
45
+ PyErr_NoMemory()
46
+ return -1
47
+ memcpy(buf, writer.buf, writer.size)
48
+ else:
49
+ buf = <char*>PyMem_Realloc(writer.buf, size)
50
+ if buf == NULL:
51
+ PyErr_NoMemory()
52
+ return -1
53
+ writer.buf = buf
54
+ writer.size = size
55
+ writer.buf[writer.pos] = <char>ch
56
+ writer.pos += 1
57
+ return 0
58
+
59
+
60
+ cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol):
61
+ cdef uint64_t utf = <uint64_t> symbol
62
+
63
+ if utf < 0x80:
64
+ return _write_byte(writer, <uint8_t>utf)
65
+ elif utf < 0x800:
66
+ if _write_byte(writer, <uint8_t>(0xc0 | (utf >> 6))) < 0:
67
+ return -1
68
+ return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
69
+ elif 0xD800 <= utf <= 0xDFFF:
70
+ # surogate pair, ignored
71
+ return 0
72
+ elif utf < 0x10000:
73
+ if _write_byte(writer, <uint8_t>(0xe0 | (utf >> 12))) < 0:
74
+ return -1
75
+ if _write_byte(writer, <uint8_t>(0x80 | ((utf >> 6) & 0x3f))) < 0:
76
+ return -1
77
+ return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
78
+ elif utf > 0x10FFFF:
79
+ # symbol is too large
80
+ return 0
81
+ else:
82
+ if _write_byte(writer, <uint8_t>(0xf0 | (utf >> 18))) < 0:
83
+ return -1
84
+ if _write_byte(writer,
85
+ <uint8_t>(0x80 | ((utf >> 12) & 0x3f))) < 0:
86
+ return -1
87
+ if _write_byte(writer,
88
+ <uint8_t>(0x80 | ((utf >> 6) & 0x3f))) < 0:
89
+ return -1
90
+ return _write_byte(writer, <uint8_t>(0x80 | (utf & 0x3f)))
91
+
92
+
93
+ cdef inline int _write_str(Writer* writer, str s):
94
+ cdef Py_UCS4 ch
95
+ for ch in s:
96
+ if _write_utf8(writer, ch) < 0:
97
+ return -1
98
+
99
+
100
+ # --------------- _serialize_headers ----------------------
101
+
102
+ cdef str to_str(object s):
103
+ typ = type(s)
104
+ if typ is str:
105
+ return <str>s
106
+ elif typ is _istr:
107
+ return PyObject_Str(s)
108
+ elif not isinstance(s, str):
109
+ raise TypeError("Cannot serialize non-str key {!r}".format(s))
110
+ else:
111
+ return str(s)
112
+
113
+
114
+ cdef void _safe_header(str string) except *:
115
+ if "\r" in string or "\n" in string:
116
+ raise ValueError(
117
+ "Newline or carriage return character detected in HTTP status message or "
118
+ "header. This is a potential security issue."
119
+ )
120
+
121
+
122
+ def _serialize_headers(str status_line, headers):
123
+ cdef Writer writer
124
+ cdef object key
125
+ cdef object val
126
+ cdef bytes ret
127
+
128
+ _init_writer(&writer)
129
+
130
+ for key, val in headers.items():
131
+ _safe_header(to_str(key))
132
+ _safe_header(to_str(val))
133
+
134
+ try:
135
+ if _write_str(&writer, status_line) < 0:
136
+ raise
137
+ if _write_byte(&writer, b'\r') < 0:
138
+ raise
139
+ if _write_byte(&writer, b'\n') < 0:
140
+ raise
141
+
142
+ for key, val in headers.items():
143
+ if _write_str(&writer, to_str(key)) < 0:
144
+ raise
145
+ if _write_byte(&writer, b':') < 0:
146
+ raise
147
+ if _write_byte(&writer, b' ') < 0:
148
+ raise
149
+ if _write_str(&writer, to_str(val)) < 0:
150
+ raise
151
+ if _write_byte(&writer, b'\r') < 0:
152
+ raise
153
+ if _write_byte(&writer, b'\n') < 0:
154
+ raise
155
+
156
+ if _write_byte(&writer, b'\r') < 0:
157
+ raise
158
+ if _write_byte(&writer, b'\n') < 0:
159
+ raise
160
+
161
+ return PyBytes_FromStringAndSize(writer.buf, writer.pos)
162
+ finally:
163
+ _release_writer(&writer)
runtime/Lib/site-packages/aiohttp/_websocket.cp39-win_amd64.pyd ADDED
Binary file (24.1 kB). View file
 
runtime/Lib/site-packages/aiohttp/_websocket.pyx ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cpython cimport PyBytes_AsString
2
+
3
+
4
+ #from cpython cimport PyByteArray_AsString # cython still not exports that
5
+ cdef extern from "Python.h":
6
+ char* PyByteArray_AsString(bytearray ba) except NULL
7
+
8
+ from libc.stdint cimport uint32_t, uint64_t, uintmax_t
9
+
10
+
11
+ def _websocket_mask_cython(object mask, object data):
12
+ """Note, this function mutates its `data` argument
13
+ """
14
+ cdef:
15
+ Py_ssize_t data_len, i
16
+ # bit operations on signed integers are implementation-specific
17
+ unsigned char * in_buf
18
+ const unsigned char * mask_buf
19
+ uint32_t uint32_msk
20
+ uint64_t uint64_msk
21
+
22
+ assert len(mask) == 4
23
+
24
+ if not isinstance(mask, bytes):
25
+ mask = bytes(mask)
26
+
27
+ if isinstance(data, bytearray):
28
+ data = <bytearray>data
29
+ else:
30
+ data = bytearray(data)
31
+
32
+ data_len = len(data)
33
+ in_buf = <unsigned char*>PyByteArray_AsString(data)
34
+ mask_buf = <const unsigned char*>PyBytes_AsString(mask)
35
+ uint32_msk = (<uint32_t*>mask_buf)[0]
36
+
37
+ # TODO: align in_data ptr to achieve even faster speeds
38
+ # does it need in python ?! malloc() always aligns to sizeof(long) bytes
39
+
40
+ if sizeof(size_t) >= 8:
41
+ uint64_msk = uint32_msk
42
+ uint64_msk = (uint64_msk << 32) | uint32_msk
43
+
44
+ while data_len >= 8:
45
+ (<uint64_t*>in_buf)[0] ^= uint64_msk
46
+ in_buf += 8
47
+ data_len -= 8
48
+
49
+
50
+ while data_len >= 4:
51
+ (<uint32_t*>in_buf)[0] ^= uint32_msk
52
+ in_buf += 4
53
+ data_len -= 4
54
+
55
+ for i in range(0, data_len):
56
+ in_buf[i] ^= mask_buf[i]
runtime/Lib/site-packages/aiohttp/abc.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Sized
5
+ from http.cookies import BaseCookie, Morsel
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ Awaitable,
10
+ Callable,
11
+ Dict,
12
+ Generator,
13
+ Iterable,
14
+ List,
15
+ Optional,
16
+ Tuple,
17
+ )
18
+
19
+ from multidict import CIMultiDict
20
+ from yarl import URL
21
+
22
+ from .helpers import get_running_loop
23
+ from .typedefs import LooseCookies
24
+
25
+ if TYPE_CHECKING: # pragma: no cover
26
+ from .web_app import Application
27
+ from .web_exceptions import HTTPException
28
+ from .web_request import BaseRequest, Request
29
+ from .web_response import StreamResponse
30
+ else:
31
+ BaseRequest = Request = Application = StreamResponse = None
32
+ HTTPException = None
33
+
34
+
35
+ class AbstractRouter(ABC):
36
+ def __init__(self) -> None:
37
+ self._frozen = False
38
+
39
+ def post_init(self, app: Application) -> None:
40
+ """Post init stage.
41
+
42
+ Not an abstract method for sake of backward compatibility,
43
+ but if the router wants to be aware of the application
44
+ it can override this.
45
+ """
46
+
47
+ @property
48
+ def frozen(self) -> bool:
49
+ return self._frozen
50
+
51
+ def freeze(self) -> None:
52
+ """Freeze router."""
53
+ self._frozen = True
54
+
55
+ @abstractmethod
56
+ async def resolve(self, request: Request) -> "AbstractMatchInfo":
57
+ """Return MATCH_INFO for given request"""
58
+
59
+
60
+ class AbstractMatchInfo(ABC):
61
+ @property # pragma: no branch
62
+ @abstractmethod
63
+ def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]:
64
+ """Execute matched request handler"""
65
+
66
+ @property
67
+ @abstractmethod
68
+ def expect_handler(self) -> Callable[[Request], Awaitable[None]]:
69
+ """Expect handler for 100-continue processing"""
70
+
71
+ @property # pragma: no branch
72
+ @abstractmethod
73
+ def http_exception(self) -> Optional[HTTPException]:
74
+ """HTTPException instance raised on router's resolving, or None"""
75
+
76
+ @abstractmethod # pragma: no branch
77
+ def get_info(self) -> Dict[str, Any]:
78
+ """Return a dict with additional info useful for introspection"""
79
+
80
+ @property # pragma: no branch
81
+ @abstractmethod
82
+ def apps(self) -> Tuple[Application, ...]:
83
+ """Stack of nested applications.
84
+
85
+ Top level application is left-most element.
86
+
87
+ """
88
+
89
+ @abstractmethod
90
+ def add_app(self, app: Application) -> None:
91
+ """Add application to the nested apps stack."""
92
+
93
+ @abstractmethod
94
+ def freeze(self) -> None:
95
+ """Freeze the match info.
96
+
97
+ The method is called after route resolution.
98
+
99
+ After the call .add_app() is forbidden.
100
+
101
+ """
102
+
103
+
104
+ class AbstractView(ABC):
105
+ """Abstract class based view."""
106
+
107
+ def __init__(self, request: Request) -> None:
108
+ self._request = request
109
+
110
+ @property
111
+ def request(self) -> Request:
112
+ """Request instance."""
113
+ return self._request
114
+
115
+ @abstractmethod
116
+ def __await__(self) -> Generator[Any, None, StreamResponse]:
117
+ """Execute the view handler."""
118
+
119
+
120
+ class AbstractResolver(ABC):
121
+ """Abstract DNS resolver."""
122
+
123
+ @abstractmethod
124
+ async def resolve(self, host: str, port: int, family: int) -> List[Dict[str, Any]]:
125
+ """Return IP address for given hostname"""
126
+
127
+ @abstractmethod
128
+ async def close(self) -> None:
129
+ """Release resolver"""
130
+
131
+
132
+ if TYPE_CHECKING: # pragma: no cover
133
+ IterableBase = Iterable[Morsel[str]]
134
+ else:
135
+ IterableBase = Iterable
136
+
137
+
138
+ ClearCookiePredicate = Callable[["Morsel[str]"], bool]
139
+
140
+
141
+ class AbstractCookieJar(Sized, IterableBase):
142
+ """Abstract Cookie Jar."""
143
+
144
+ def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
145
+ self._loop = get_running_loop(loop)
146
+
147
+ @abstractmethod
148
+ def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
149
+ """Clear all cookies if no predicate is passed."""
150
+
151
+ @abstractmethod
152
+ def clear_domain(self, domain: str) -> None:
153
+ """Clear all cookies for domain and all subdomains."""
154
+
155
+ @abstractmethod
156
+ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
157
+ """Update cookies."""
158
+
159
+ @abstractmethod
160
+ def filter_cookies(self, request_url: URL) -> "BaseCookie[str]":
161
+ """Return the jar's cookies filtered by their attributes."""
162
+
163
+
164
+ class AbstractStreamWriter(ABC):
165
+ """Abstract stream writer."""
166
+
167
+ buffer_size = 0
168
+ output_size = 0
169
+ length: Optional[int] = 0
170
+
171
+ @abstractmethod
172
+ async def write(self, chunk: bytes) -> None:
173
+ """Write chunk into stream."""
174
+
175
+ @abstractmethod
176
+ async def write_eof(self, chunk: bytes = b"") -> None:
177
+ """Write last chunk."""
178
+
179
+ @abstractmethod
180
+ async def drain(self) -> None:
181
+ """Flush the write buffer."""
182
+
183
+ @abstractmethod
184
+ def enable_compression(self, encoding: str = "deflate") -> None:
185
+ """Enable HTTP body compression"""
186
+
187
+ @abstractmethod
188
+ def enable_chunking(self) -> None:
189
+ """Enable HTTP chunked mode"""
190
+
191
+ @abstractmethod
192
+ async def write_headers(
193
+ self, status_line: str, headers: "CIMultiDict[str]"
194
+ ) -> None:
195
+ """Write HTTP headers"""
196
+
197
+
198
+ class AbstractAccessLogger(ABC):
199
+ """Abstract writer to access log."""
200
+
201
+ def __init__(self, logger: logging.Logger, log_format: str) -> None:
202
+ self.logger = logger
203
+ self.log_format = log_format
204
+
205
+ @abstractmethod
206
+ def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None:
207
+ """Emit log to logger."""
runtime/Lib/site-packages/aiohttp/base_protocol.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import Optional, cast
3
+
4
+ from .tcp_helpers import tcp_nodelay
5
+
6
+
7
+ class BaseProtocol(asyncio.Protocol):
8
+ __slots__ = (
9
+ "_loop",
10
+ "_paused",
11
+ "_drain_waiter",
12
+ "_connection_lost",
13
+ "_reading_paused",
14
+ "transport",
15
+ )
16
+
17
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
18
+ self._loop: asyncio.AbstractEventLoop = loop
19
+ self._paused = False
20
+ self._drain_waiter: Optional[asyncio.Future[None]] = None
21
+ self._connection_lost = False
22
+ self._reading_paused = False
23
+
24
+ self.transport: Optional[asyncio.Transport] = None
25
+
26
+ def pause_writing(self) -> None:
27
+ assert not self._paused
28
+ self._paused = True
29
+
30
+ def resume_writing(self) -> None:
31
+ assert self._paused
32
+ self._paused = False
33
+
34
+ waiter = self._drain_waiter
35
+ if waiter is not None:
36
+ self._drain_waiter = None
37
+ if not waiter.done():
38
+ waiter.set_result(None)
39
+
40
+ def pause_reading(self) -> None:
41
+ if not self._reading_paused and self.transport is not None:
42
+ try:
43
+ self.transport.pause_reading()
44
+ except (AttributeError, NotImplementedError, RuntimeError):
45
+ pass
46
+ self._reading_paused = True
47
+
48
+ def resume_reading(self) -> None:
49
+ if self._reading_paused and self.transport is not None:
50
+ try:
51
+ self.transport.resume_reading()
52
+ except (AttributeError, NotImplementedError, RuntimeError):
53
+ pass
54
+ self._reading_paused = False
55
+
56
+ def connection_made(self, transport: asyncio.BaseTransport) -> None:
57
+ tr = cast(asyncio.Transport, transport)
58
+ tcp_nodelay(tr, True)
59
+ self.transport = tr
60
+
61
+ def connection_lost(self, exc: Optional[BaseException]) -> None:
62
+ self._connection_lost = True
63
+ # Wake up the writer if currently paused.
64
+ self.transport = None
65
+ if not self._paused:
66
+ return
67
+ waiter = self._drain_waiter
68
+ if waiter is None:
69
+ return
70
+ self._drain_waiter = None
71
+ if waiter.done():
72
+ return
73
+ if exc is None:
74
+ waiter.set_result(None)
75
+ else:
76
+ waiter.set_exception(exc)
77
+
78
+ async def _drain_helper(self) -> None:
79
+ if self._connection_lost:
80
+ raise ConnectionResetError("Connection lost")
81
+ if not self._paused:
82
+ return
83
+ waiter = self._drain_waiter
84
+ if waiter is None:
85
+ waiter = self._loop.create_future()
86
+ self._drain_waiter = waiter
87
+ await asyncio.shield(waiter)
runtime/Lib/site-packages/aiohttp/client.py ADDED
@@ -0,0 +1,1305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP Client for asyncio."""
2
+
3
+ import asyncio
4
+ import base64
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import sys
9
+ import traceback
10
+ import warnings
11
+ from contextlib import suppress
12
+ from types import SimpleNamespace, TracebackType
13
+ from typing import (
14
+ Any,
15
+ Awaitable,
16
+ Callable,
17
+ Coroutine,
18
+ FrozenSet,
19
+ Generator,
20
+ Generic,
21
+ Iterable,
22
+ List,
23
+ Mapping,
24
+ Optional,
25
+ Set,
26
+ Tuple,
27
+ Type,
28
+ TypeVar,
29
+ Union,
30
+ )
31
+
32
+ import attr
33
+ from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
34
+ from yarl import URL
35
+
36
+ from . import hdrs, http, payload
37
+ from .abc import AbstractCookieJar
38
+ from .client_exceptions import (
39
+ ClientConnectionError as ClientConnectionError,
40
+ ClientConnectorCertificateError as ClientConnectorCertificateError,
41
+ ClientConnectorError as ClientConnectorError,
42
+ ClientConnectorSSLError as ClientConnectorSSLError,
43
+ ClientError as ClientError,
44
+ ClientHttpProxyError as ClientHttpProxyError,
45
+ ClientOSError as ClientOSError,
46
+ ClientPayloadError as ClientPayloadError,
47
+ ClientProxyConnectionError as ClientProxyConnectionError,
48
+ ClientResponseError as ClientResponseError,
49
+ ClientSSLError as ClientSSLError,
50
+ ContentTypeError as ContentTypeError,
51
+ InvalidURL as InvalidURL,
52
+ ServerConnectionError as ServerConnectionError,
53
+ ServerDisconnectedError as ServerDisconnectedError,
54
+ ServerFingerprintMismatch as ServerFingerprintMismatch,
55
+ ServerTimeoutError as ServerTimeoutError,
56
+ TooManyRedirects as TooManyRedirects,
57
+ WSServerHandshakeError as WSServerHandshakeError,
58
+ )
59
+ from .client_reqrep import (
60
+ ClientRequest as ClientRequest,
61
+ ClientResponse as ClientResponse,
62
+ Fingerprint as Fingerprint,
63
+ RequestInfo as RequestInfo,
64
+ _merge_ssl_params,
65
+ )
66
+ from .client_ws import ClientWebSocketResponse as ClientWebSocketResponse
67
+ from .connector import (
68
+ BaseConnector as BaseConnector,
69
+ NamedPipeConnector as NamedPipeConnector,
70
+ TCPConnector as TCPConnector,
71
+ UnixConnector as UnixConnector,
72
+ )
73
+ from .cookiejar import CookieJar
74
+ from .helpers import (
75
+ DEBUG,
76
+ PY_36,
77
+ BasicAuth,
78
+ TimeoutHandle,
79
+ ceil_timeout,
80
+ get_env_proxy_for_url,
81
+ get_running_loop,
82
+ sentinel,
83
+ strip_auth_from_url,
84
+ )
85
+ from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter
86
+ from .http_websocket import WSHandshakeError, WSMessage, ws_ext_gen, ws_ext_parse
87
+ from .streams import FlowControlDataQueue
88
+ from .tracing import Trace, TraceConfig
89
+ from .typedefs import Final, JSONEncoder, LooseCookies, LooseHeaders, StrOrURL
90
+
91
+ __all__ = (
92
+ # client_exceptions
93
+ "ClientConnectionError",
94
+ "ClientConnectorCertificateError",
95
+ "ClientConnectorError",
96
+ "ClientConnectorSSLError",
97
+ "ClientError",
98
+ "ClientHttpProxyError",
99
+ "ClientOSError",
100
+ "ClientPayloadError",
101
+ "ClientProxyConnectionError",
102
+ "ClientResponseError",
103
+ "ClientSSLError",
104
+ "ContentTypeError",
105
+ "InvalidURL",
106
+ "ServerConnectionError",
107
+ "ServerDisconnectedError",
108
+ "ServerFingerprintMismatch",
109
+ "ServerTimeoutError",
110
+ "TooManyRedirects",
111
+ "WSServerHandshakeError",
112
+ # client_reqrep
113
+ "ClientRequest",
114
+ "ClientResponse",
115
+ "Fingerprint",
116
+ "RequestInfo",
117
+ # connector
118
+ "BaseConnector",
119
+ "TCPConnector",
120
+ "UnixConnector",
121
+ "NamedPipeConnector",
122
+ # client_ws
123
+ "ClientWebSocketResponse",
124
+ # client
125
+ "ClientSession",
126
+ "ClientTimeout",
127
+ "request",
128
+ )
129
+
130
+
131
+ try:
132
+ from ssl import SSLContext
133
+ except ImportError: # pragma: no cover
134
+ SSLContext = object # type: ignore[misc,assignment]
135
+
136
+
137
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
138
+ class ClientTimeout:
139
+ total: Optional[float] = None
140
+ connect: Optional[float] = None
141
+ sock_read: Optional[float] = None
142
+ sock_connect: Optional[float] = None
143
+
144
+ # pool_queue_timeout: Optional[float] = None
145
+ # dns_resolution_timeout: Optional[float] = None
146
+ # socket_connect_timeout: Optional[float] = None
147
+ # connection_acquiring_timeout: Optional[float] = None
148
+ # new_connection_timeout: Optional[float] = None
149
+ # http_header_timeout: Optional[float] = None
150
+ # response_body_timeout: Optional[float] = None
151
+
152
+ # to create a timeout specific for a single request, either
153
+ # - create a completely new one to overwrite the default
154
+ # - or use http://www.attrs.org/en/stable/api.html#attr.evolve
155
+ # to overwrite the defaults
156
+
157
+
158
+ # 5 Minute default read timeout
159
+ DEFAULT_TIMEOUT: Final[ClientTimeout] = ClientTimeout(total=5 * 60)
160
+
161
+ _RetType = TypeVar("_RetType")
162
+
163
+
164
+ class ClientSession:
165
+ """First-class interface for making HTTP requests."""
166
+
167
+ ATTRS = frozenset(
168
+ [
169
+ "_base_url",
170
+ "_source_traceback",
171
+ "_connector",
172
+ "requote_redirect_url",
173
+ "_loop",
174
+ "_cookie_jar",
175
+ "_connector_owner",
176
+ "_default_auth",
177
+ "_version",
178
+ "_json_serialize",
179
+ "_requote_redirect_url",
180
+ "_timeout",
181
+ "_raise_for_status",
182
+ "_auto_decompress",
183
+ "_trust_env",
184
+ "_default_headers",
185
+ "_skip_auto_headers",
186
+ "_request_class",
187
+ "_response_class",
188
+ "_ws_response_class",
189
+ "_trace_configs",
190
+ "_read_bufsize",
191
+ ]
192
+ )
193
+
194
+ _source_traceback = None # type: Optional[traceback.StackSummary]
195
+ _connector = None # type: Optional[BaseConnector]
196
+
197
+ def __init__(
198
+ self,
199
+ base_url: Optional[StrOrURL] = None,
200
+ *,
201
+ connector: Optional[BaseConnector] = None,
202
+ loop: Optional[asyncio.AbstractEventLoop] = None,
203
+ cookies: Optional[LooseCookies] = None,
204
+ headers: Optional[LooseHeaders] = None,
205
+ skip_auto_headers: Optional[Iterable[str]] = None,
206
+ auth: Optional[BasicAuth] = None,
207
+ json_serialize: JSONEncoder = json.dumps,
208
+ request_class: Type[ClientRequest] = ClientRequest,
209
+ response_class: Type[ClientResponse] = ClientResponse,
210
+ ws_response_class: Type[ClientWebSocketResponse] = ClientWebSocketResponse,
211
+ version: HttpVersion = http.HttpVersion11,
212
+ cookie_jar: Optional[AbstractCookieJar] = None,
213
+ connector_owner: bool = True,
214
+ raise_for_status: bool = False,
215
+ read_timeout: Union[float, object] = sentinel,
216
+ conn_timeout: Optional[float] = None,
217
+ timeout: Union[object, ClientTimeout] = sentinel,
218
+ auto_decompress: bool = True,
219
+ trust_env: bool = False,
220
+ requote_redirect_url: bool = True,
221
+ trace_configs: Optional[List[TraceConfig]] = None,
222
+ read_bufsize: int = 2**16,
223
+ ) -> None:
224
+ if loop is None:
225
+ if connector is not None:
226
+ loop = connector._loop
227
+
228
+ loop = get_running_loop(loop)
229
+
230
+ if base_url is None or isinstance(base_url, URL):
231
+ self._base_url: Optional[URL] = base_url
232
+ else:
233
+ self._base_url = URL(base_url)
234
+ assert (
235
+ self._base_url.origin() == self._base_url
236
+ ), "Only absolute URLs without path part are supported"
237
+
238
+ if connector is None:
239
+ connector = TCPConnector(loop=loop)
240
+
241
+ if connector._loop is not loop:
242
+ raise RuntimeError("Session and connector has to use same event loop")
243
+
244
+ self._loop = loop
245
+
246
+ if loop.get_debug():
247
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
248
+
249
+ if cookie_jar is None:
250
+ cookie_jar = CookieJar(loop=loop)
251
+ self._cookie_jar = cookie_jar
252
+
253
+ if cookies is not None:
254
+ self._cookie_jar.update_cookies(cookies)
255
+
256
+ self._connector = connector
257
+ self._connector_owner = connector_owner
258
+ self._default_auth = auth
259
+ self._version = version
260
+ self._json_serialize = json_serialize
261
+ if timeout is sentinel:
262
+ self._timeout = DEFAULT_TIMEOUT
263
+ if read_timeout is not sentinel:
264
+ warnings.warn(
265
+ "read_timeout is deprecated, " "use timeout argument instead",
266
+ DeprecationWarning,
267
+ stacklevel=2,
268
+ )
269
+ self._timeout = attr.evolve(self._timeout, total=read_timeout)
270
+ if conn_timeout is not None:
271
+ self._timeout = attr.evolve(self._timeout, connect=conn_timeout)
272
+ warnings.warn(
273
+ "conn_timeout is deprecated, " "use timeout argument instead",
274
+ DeprecationWarning,
275
+ stacklevel=2,
276
+ )
277
+ else:
278
+ self._timeout = timeout # type: ignore[assignment]
279
+ if read_timeout is not sentinel:
280
+ raise ValueError(
281
+ "read_timeout and timeout parameters "
282
+ "conflict, please setup "
283
+ "timeout.read"
284
+ )
285
+ if conn_timeout is not None:
286
+ raise ValueError(
287
+ "conn_timeout and timeout parameters "
288
+ "conflict, please setup "
289
+ "timeout.connect"
290
+ )
291
+ self._raise_for_status = raise_for_status
292
+ self._auto_decompress = auto_decompress
293
+ self._trust_env = trust_env
294
+ self._requote_redirect_url = requote_redirect_url
295
+ self._read_bufsize = read_bufsize
296
+
297
+ # Convert to list of tuples
298
+ if headers:
299
+ real_headers: CIMultiDict[str] = CIMultiDict(headers)
300
+ else:
301
+ real_headers = CIMultiDict()
302
+ self._default_headers: CIMultiDict[str] = real_headers
303
+ if skip_auto_headers is not None:
304
+ self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers)
305
+ else:
306
+ self._skip_auto_headers = frozenset()
307
+
308
+ self._request_class = request_class
309
+ self._response_class = response_class
310
+ self._ws_response_class = ws_response_class
311
+
312
+ self._trace_configs = trace_configs or []
313
+ for trace_config in self._trace_configs:
314
+ trace_config.freeze()
315
+
316
+ def __init_subclass__(cls: Type["ClientSession"]) -> None:
317
+ warnings.warn(
318
+ "Inheritance class {} from ClientSession "
319
+ "is discouraged".format(cls.__name__),
320
+ DeprecationWarning,
321
+ stacklevel=2,
322
+ )
323
+
324
+ if DEBUG:
325
+
326
+ def __setattr__(self, name: str, val: Any) -> None:
327
+ if name not in self.ATTRS:
328
+ warnings.warn(
329
+ "Setting custom ClientSession.{} attribute "
330
+ "is discouraged".format(name),
331
+ DeprecationWarning,
332
+ stacklevel=2,
333
+ )
334
+ super().__setattr__(name, val)
335
+
336
+ def __del__(self, _warnings: Any = warnings) -> None:
337
+ if not self.closed:
338
+ if PY_36:
339
+ kwargs = {"source": self}
340
+ else:
341
+ kwargs = {}
342
+ _warnings.warn(
343
+ f"Unclosed client session {self!r}", ResourceWarning, **kwargs
344
+ )
345
+ context = {"client_session": self, "message": "Unclosed client session"}
346
+ if self._source_traceback is not None:
347
+ context["source_traceback"] = self._source_traceback
348
+ self._loop.call_exception_handler(context)
349
+
350
+ def request(
351
+ self, method: str, url: StrOrURL, **kwargs: Any
352
+ ) -> "_RequestContextManager":
353
+ """Perform HTTP request."""
354
+ return _RequestContextManager(self._request(method, url, **kwargs))
355
+
356
+ def _build_url(self, str_or_url: StrOrURL) -> URL:
357
+ url = URL(str_or_url)
358
+ if self._base_url is None:
359
+ return url
360
+ else:
361
+ assert not url.is_absolute() and url.path.startswith("/")
362
+ return self._base_url.join(url)
363
+
364
+ async def _request(
365
+ self,
366
+ method: str,
367
+ str_or_url: StrOrURL,
368
+ *,
369
+ params: Optional[Mapping[str, str]] = None,
370
+ data: Any = None,
371
+ json: Any = None,
372
+ cookies: Optional[LooseCookies] = None,
373
+ headers: Optional[LooseHeaders] = None,
374
+ skip_auto_headers: Optional[Iterable[str]] = None,
375
+ auth: Optional[BasicAuth] = None,
376
+ allow_redirects: bool = True,
377
+ max_redirects: int = 10,
378
+ compress: Optional[str] = None,
379
+ chunked: Optional[bool] = None,
380
+ expect100: bool = False,
381
+ raise_for_status: Optional[bool] = None,
382
+ read_until_eof: bool = True,
383
+ proxy: Optional[StrOrURL] = None,
384
+ proxy_auth: Optional[BasicAuth] = None,
385
+ timeout: Union[ClientTimeout, object] = sentinel,
386
+ verify_ssl: Optional[bool] = None,
387
+ fingerprint: Optional[bytes] = None,
388
+ ssl_context: Optional[SSLContext] = None,
389
+ ssl: Optional[Union[SSLContext, bool, Fingerprint]] = None,
390
+ proxy_headers: Optional[LooseHeaders] = None,
391
+ trace_request_ctx: Optional[SimpleNamespace] = None,
392
+ read_bufsize: Optional[int] = None,
393
+ ) -> ClientResponse:
394
+
395
+ # NOTE: timeout clamps existing connect and read timeouts. We cannot
396
+ # set the default to None because we need to detect if the user wants
397
+ # to use the existing timeouts by setting timeout to None.
398
+
399
+ if self.closed:
400
+ raise RuntimeError("Session is closed")
401
+
402
+ ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
403
+
404
+ if data is not None and json is not None:
405
+ raise ValueError(
406
+ "data and json parameters can not be used at the same time"
407
+ )
408
+ elif json is not None:
409
+ data = payload.JsonPayload(json, dumps=self._json_serialize)
410
+
411
+ if not isinstance(chunked, bool) and chunked is not None:
412
+ warnings.warn("Chunk size is deprecated #1615", DeprecationWarning)
413
+
414
+ redirects = 0
415
+ history = []
416
+ version = self._version
417
+
418
+ # Merge with default headers and transform to CIMultiDict
419
+ headers = self._prepare_headers(headers)
420
+ proxy_headers = self._prepare_headers(proxy_headers)
421
+
422
+ try:
423
+ url = self._build_url(str_or_url)
424
+ except ValueError as e:
425
+ raise InvalidURL(str_or_url) from e
426
+
427
+ skip_headers = set(self._skip_auto_headers)
428
+ if skip_auto_headers is not None:
429
+ for i in skip_auto_headers:
430
+ skip_headers.add(istr(i))
431
+
432
+ if proxy is not None:
433
+ try:
434
+ proxy = URL(proxy)
435
+ except ValueError as e:
436
+ raise InvalidURL(proxy) from e
437
+
438
+ if timeout is sentinel:
439
+ real_timeout: ClientTimeout = self._timeout
440
+ else:
441
+ if not isinstance(timeout, ClientTimeout):
442
+ real_timeout = ClientTimeout(total=timeout) # type: ignore[arg-type]
443
+ else:
444
+ real_timeout = timeout
445
+ # timeout is cumulative for all request operations
446
+ # (request, redirects, responses, data consuming)
447
+ tm = TimeoutHandle(self._loop, real_timeout.total)
448
+ handle = tm.start()
449
+
450
+ if read_bufsize is None:
451
+ read_bufsize = self._read_bufsize
452
+
453
+ traces = [
454
+ Trace(
455
+ self,
456
+ trace_config,
457
+ trace_config.trace_config_ctx(trace_request_ctx=trace_request_ctx),
458
+ )
459
+ for trace_config in self._trace_configs
460
+ ]
461
+
462
+ for trace in traces:
463
+ await trace.send_request_start(method, url.update_query(params), headers)
464
+
465
+ timer = tm.timer()
466
+ try:
467
+ with timer:
468
+ while True:
469
+ url, auth_from_url = strip_auth_from_url(url)
470
+ if auth and auth_from_url:
471
+ raise ValueError(
472
+ "Cannot combine AUTH argument with "
473
+ "credentials encoded in URL"
474
+ )
475
+
476
+ if auth is None:
477
+ auth = auth_from_url
478
+ if auth is None:
479
+ auth = self._default_auth
480
+ # It would be confusing if we support explicit
481
+ # Authorization header with auth argument
482
+ if (
483
+ headers is not None
484
+ and auth is not None
485
+ and hdrs.AUTHORIZATION in headers
486
+ ):
487
+ raise ValueError(
488
+ "Cannot combine AUTHORIZATION header "
489
+ "with AUTH argument or credentials "
490
+ "encoded in URL"
491
+ )
492
+
493
+ all_cookies = self._cookie_jar.filter_cookies(url)
494
+
495
+ if cookies is not None:
496
+ tmp_cookie_jar = CookieJar()
497
+ tmp_cookie_jar.update_cookies(cookies)
498
+ req_cookies = tmp_cookie_jar.filter_cookies(url)
499
+ if req_cookies:
500
+ all_cookies.load(req_cookies)
501
+
502
+ if proxy is not None:
503
+ proxy = URL(proxy)
504
+ elif self._trust_env:
505
+ with suppress(LookupError):
506
+ proxy, proxy_auth = get_env_proxy_for_url(url)
507
+
508
+ req = self._request_class(
509
+ method,
510
+ url,
511
+ params=params,
512
+ headers=headers,
513
+ skip_auto_headers=skip_headers,
514
+ data=data,
515
+ cookies=all_cookies,
516
+ auth=auth,
517
+ version=version,
518
+ compress=compress,
519
+ chunked=chunked,
520
+ expect100=expect100,
521
+ loop=self._loop,
522
+ response_class=self._response_class,
523
+ proxy=proxy,
524
+ proxy_auth=proxy_auth,
525
+ timer=timer,
526
+ session=self,
527
+ ssl=ssl,
528
+ proxy_headers=proxy_headers,
529
+ traces=traces,
530
+ )
531
+
532
+ # connection timeout
533
+ try:
534
+ async with ceil_timeout(real_timeout.connect):
535
+ assert self._connector is not None
536
+ conn = await self._connector.connect(
537
+ req, traces=traces, timeout=real_timeout
538
+ )
539
+ except asyncio.TimeoutError as exc:
540
+ raise ServerTimeoutError(
541
+ "Connection timeout " "to host {}".format(url)
542
+ ) from exc
543
+
544
+ assert conn.transport is not None
545
+
546
+ assert conn.protocol is not None
547
+ conn.protocol.set_response_params(
548
+ timer=timer,
549
+ skip_payload=method.upper() == "HEAD",
550
+ read_until_eof=read_until_eof,
551
+ auto_decompress=self._auto_decompress,
552
+ read_timeout=real_timeout.sock_read,
553
+ read_bufsize=read_bufsize,
554
+ )
555
+
556
+ try:
557
+ try:
558
+ resp = await req.send(conn)
559
+ try:
560
+ await resp.start(conn)
561
+ except BaseException:
562
+ resp.close()
563
+ raise
564
+ except BaseException:
565
+ conn.close()
566
+ raise
567
+ except ClientError:
568
+ raise
569
+ except OSError as exc:
570
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
571
+ raise
572
+ raise ClientOSError(*exc.args) from exc
573
+
574
+ self._cookie_jar.update_cookies(resp.cookies, resp.url)
575
+
576
+ # redirects
577
+ if resp.status in (301, 302, 303, 307, 308) and allow_redirects:
578
+
579
+ for trace in traces:
580
+ await trace.send_request_redirect(
581
+ method, url.update_query(params), headers, resp
582
+ )
583
+
584
+ redirects += 1
585
+ history.append(resp)
586
+ if max_redirects and redirects >= max_redirects:
587
+ resp.close()
588
+ raise TooManyRedirects(
589
+ history[0].request_info, tuple(history)
590
+ )
591
+
592
+ # For 301 and 302, mimic IE, now changed in RFC
593
+ # https://github.com/kennethreitz/requests/pull/269
594
+ if (resp.status == 303 and resp.method != hdrs.METH_HEAD) or (
595
+ resp.status in (301, 302) and resp.method == hdrs.METH_POST
596
+ ):
597
+ method = hdrs.METH_GET
598
+ data = None
599
+ if headers.get(hdrs.CONTENT_LENGTH):
600
+ headers.pop(hdrs.CONTENT_LENGTH)
601
+
602
+ r_url = resp.headers.get(hdrs.LOCATION) or resp.headers.get(
603
+ hdrs.URI
604
+ )
605
+ if r_url is None:
606
+ # see github.com/aio-libs/aiohttp/issues/2022
607
+ break
608
+ else:
609
+ # reading from correct redirection
610
+ # response is forbidden
611
+ resp.release()
612
+
613
+ try:
614
+ parsed_url = URL(
615
+ r_url, encoded=not self._requote_redirect_url
616
+ )
617
+
618
+ except ValueError as e:
619
+ raise InvalidURL(r_url) from e
620
+
621
+ scheme = parsed_url.scheme
622
+ if scheme not in ("http", "https", ""):
623
+ resp.close()
624
+ raise ValueError("Can redirect only to http or https")
625
+ elif not scheme:
626
+ parsed_url = url.join(parsed_url)
627
+
628
+ if url.origin() != parsed_url.origin():
629
+ auth = None
630
+ headers.pop(hdrs.AUTHORIZATION, None)
631
+
632
+ url = parsed_url
633
+ params = None
634
+ resp.release()
635
+ continue
636
+
637
+ break
638
+
639
+ # check response status
640
+ if raise_for_status is None:
641
+ raise_for_status = self._raise_for_status
642
+ if raise_for_status:
643
+ resp.raise_for_status()
644
+
645
+ # register connection
646
+ if handle is not None:
647
+ if resp.connection is not None:
648
+ resp.connection.add_callback(handle.cancel)
649
+ else:
650
+ handle.cancel()
651
+
652
+ resp._history = tuple(history)
653
+
654
+ for trace in traces:
655
+ await trace.send_request_end(
656
+ method, url.update_query(params), headers, resp
657
+ )
658
+ return resp
659
+
660
+ except BaseException as e:
661
+ # cleanup timer
662
+ tm.close()
663
+ if handle:
664
+ handle.cancel()
665
+ handle = None
666
+
667
+ for trace in traces:
668
+ await trace.send_request_exception(
669
+ method, url.update_query(params), headers, e
670
+ )
671
+ raise
672
+
673
+ def ws_connect(
674
+ self,
675
+ url: StrOrURL,
676
+ *,
677
+ method: str = hdrs.METH_GET,
678
+ protocols: Iterable[str] = (),
679
+ timeout: float = 10.0,
680
+ receive_timeout: Optional[float] = None,
681
+ autoclose: bool = True,
682
+ autoping: bool = True,
683
+ heartbeat: Optional[float] = None,
684
+ auth: Optional[BasicAuth] = None,
685
+ origin: Optional[str] = None,
686
+ params: Optional[Mapping[str, str]] = None,
687
+ headers: Optional[LooseHeaders] = None,
688
+ proxy: Optional[StrOrURL] = None,
689
+ proxy_auth: Optional[BasicAuth] = None,
690
+ ssl: Union[SSLContext, bool, None, Fingerprint] = None,
691
+ verify_ssl: Optional[bool] = None,
692
+ fingerprint: Optional[bytes] = None,
693
+ ssl_context: Optional[SSLContext] = None,
694
+ proxy_headers: Optional[LooseHeaders] = None,
695
+ compress: int = 0,
696
+ max_msg_size: int = 4 * 1024 * 1024,
697
+ ) -> "_WSRequestContextManager":
698
+ """Initiate websocket connection."""
699
+ return _WSRequestContextManager(
700
+ self._ws_connect(
701
+ url,
702
+ method=method,
703
+ protocols=protocols,
704
+ timeout=timeout,
705
+ receive_timeout=receive_timeout,
706
+ autoclose=autoclose,
707
+ autoping=autoping,
708
+ heartbeat=heartbeat,
709
+ auth=auth,
710
+ origin=origin,
711
+ params=params,
712
+ headers=headers,
713
+ proxy=proxy,
714
+ proxy_auth=proxy_auth,
715
+ ssl=ssl,
716
+ verify_ssl=verify_ssl,
717
+ fingerprint=fingerprint,
718
+ ssl_context=ssl_context,
719
+ proxy_headers=proxy_headers,
720
+ compress=compress,
721
+ max_msg_size=max_msg_size,
722
+ )
723
+ )
724
+
725
+ async def _ws_connect(
726
+ self,
727
+ url: StrOrURL,
728
+ *,
729
+ method: str = hdrs.METH_GET,
730
+ protocols: Iterable[str] = (),
731
+ timeout: float = 10.0,
732
+ receive_timeout: Optional[float] = None,
733
+ autoclose: bool = True,
734
+ autoping: bool = True,
735
+ heartbeat: Optional[float] = None,
736
+ auth: Optional[BasicAuth] = None,
737
+ origin: Optional[str] = None,
738
+ params: Optional[Mapping[str, str]] = None,
739
+ headers: Optional[LooseHeaders] = None,
740
+ proxy: Optional[StrOrURL] = None,
741
+ proxy_auth: Optional[BasicAuth] = None,
742
+ ssl: Union[SSLContext, bool, None, Fingerprint] = None,
743
+ verify_ssl: Optional[bool] = None,
744
+ fingerprint: Optional[bytes] = None,
745
+ ssl_context: Optional[SSLContext] = None,
746
+ proxy_headers: Optional[LooseHeaders] = None,
747
+ compress: int = 0,
748
+ max_msg_size: int = 4 * 1024 * 1024,
749
+ ) -> ClientWebSocketResponse:
750
+
751
+ if headers is None:
752
+ real_headers: CIMultiDict[str] = CIMultiDict()
753
+ else:
754
+ real_headers = CIMultiDict(headers)
755
+
756
+ default_headers = {
757
+ hdrs.UPGRADE: "websocket",
758
+ hdrs.CONNECTION: "upgrade",
759
+ hdrs.SEC_WEBSOCKET_VERSION: "13",
760
+ }
761
+
762
+ for key, value in default_headers.items():
763
+ real_headers.setdefault(key, value)
764
+
765
+ sec_key = base64.b64encode(os.urandom(16))
766
+ real_headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode()
767
+
768
+ if protocols:
769
+ real_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ",".join(protocols)
770
+ if origin is not None:
771
+ real_headers[hdrs.ORIGIN] = origin
772
+ if compress:
773
+ extstr = ws_ext_gen(compress=compress)
774
+ real_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr
775
+
776
+ ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
777
+
778
+ # send request
779
+ resp = await self.request(
780
+ method,
781
+ url,
782
+ params=params,
783
+ headers=real_headers,
784
+ read_until_eof=False,
785
+ auth=auth,
786
+ proxy=proxy,
787
+ proxy_auth=proxy_auth,
788
+ ssl=ssl,
789
+ proxy_headers=proxy_headers,
790
+ )
791
+
792
+ try:
793
+ # check handshake
794
+ if resp.status != 101:
795
+ raise WSServerHandshakeError(
796
+ resp.request_info,
797
+ resp.history,
798
+ message="Invalid response status",
799
+ status=resp.status,
800
+ headers=resp.headers,
801
+ )
802
+
803
+ if resp.headers.get(hdrs.UPGRADE, "").lower() != "websocket":
804
+ raise WSServerHandshakeError(
805
+ resp.request_info,
806
+ resp.history,
807
+ message="Invalid upgrade header",
808
+ status=resp.status,
809
+ headers=resp.headers,
810
+ )
811
+
812
+ if resp.headers.get(hdrs.CONNECTION, "").lower() != "upgrade":
813
+ raise WSServerHandshakeError(
814
+ resp.request_info,
815
+ resp.history,
816
+ message="Invalid connection header",
817
+ status=resp.status,
818
+ headers=resp.headers,
819
+ )
820
+
821
+ # key calculation
822
+ r_key = resp.headers.get(hdrs.SEC_WEBSOCKET_ACCEPT, "")
823
+ match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()).decode()
824
+ if r_key != match:
825
+ raise WSServerHandshakeError(
826
+ resp.request_info,
827
+ resp.history,
828
+ message="Invalid challenge response",
829
+ status=resp.status,
830
+ headers=resp.headers,
831
+ )
832
+
833
+ # websocket protocol
834
+ protocol = None
835
+ if protocols and hdrs.SEC_WEBSOCKET_PROTOCOL in resp.headers:
836
+ resp_protocols = [
837
+ proto.strip()
838
+ for proto in resp.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",")
839
+ ]
840
+
841
+ for proto in resp_protocols:
842
+ if proto in protocols:
843
+ protocol = proto
844
+ break
845
+
846
+ # websocket compress
847
+ notakeover = False
848
+ if compress:
849
+ compress_hdrs = resp.headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS)
850
+ if compress_hdrs:
851
+ try:
852
+ compress, notakeover = ws_ext_parse(compress_hdrs)
853
+ except WSHandshakeError as exc:
854
+ raise WSServerHandshakeError(
855
+ resp.request_info,
856
+ resp.history,
857
+ message=exc.args[0],
858
+ status=resp.status,
859
+ headers=resp.headers,
860
+ ) from exc
861
+ else:
862
+ compress = 0
863
+ notakeover = False
864
+
865
+ conn = resp.connection
866
+ assert conn is not None
867
+ conn_proto = conn.protocol
868
+ assert conn_proto is not None
869
+ transport = conn.transport
870
+ assert transport is not None
871
+ reader: FlowControlDataQueue[WSMessage] = FlowControlDataQueue(
872
+ conn_proto, 2**16, loop=self._loop
873
+ )
874
+ conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader)
875
+ writer = WebSocketWriter(
876
+ conn_proto,
877
+ transport,
878
+ use_mask=True,
879
+ compress=compress,
880
+ notakeover=notakeover,
881
+ )
882
+ except BaseException:
883
+ resp.close()
884
+ raise
885
+ else:
886
+ return self._ws_response_class(
887
+ reader,
888
+ writer,
889
+ protocol,
890
+ resp,
891
+ timeout,
892
+ autoclose,
893
+ autoping,
894
+ self._loop,
895
+ receive_timeout=receive_timeout,
896
+ heartbeat=heartbeat,
897
+ compress=compress,
898
+ client_notakeover=notakeover,
899
+ )
900
+
901
+ def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]":
902
+ """Add default headers and transform it to CIMultiDict"""
903
+ # Convert headers to MultiDict
904
+ result = CIMultiDict(self._default_headers)
905
+ if headers:
906
+ if not isinstance(headers, (MultiDictProxy, MultiDict)):
907
+ headers = CIMultiDict(headers)
908
+ added_names: Set[str] = set()
909
+ for key, value in headers.items():
910
+ if key in added_names:
911
+ result.add(key, value)
912
+ else:
913
+ result[key] = value
914
+ added_names.add(key)
915
+ return result
916
+
917
+ def get(
918
+ self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any
919
+ ) -> "_RequestContextManager":
920
+ """Perform HTTP GET request."""
921
+ return _RequestContextManager(
922
+ self._request(hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs)
923
+ )
924
+
925
+ def options(
926
+ self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any
927
+ ) -> "_RequestContextManager":
928
+ """Perform HTTP OPTIONS request."""
929
+ return _RequestContextManager(
930
+ self._request(
931
+ hdrs.METH_OPTIONS, url, allow_redirects=allow_redirects, **kwargs
932
+ )
933
+ )
934
+
935
+ def head(
936
+ self, url: StrOrURL, *, allow_redirects: bool = False, **kwargs: Any
937
+ ) -> "_RequestContextManager":
938
+ """Perform HTTP HEAD request."""
939
+ return _RequestContextManager(
940
+ self._request(
941
+ hdrs.METH_HEAD, url, allow_redirects=allow_redirects, **kwargs
942
+ )
943
+ )
944
+
945
+ def post(
946
+ self, url: StrOrURL, *, data: Any = None, **kwargs: Any
947
+ ) -> "_RequestContextManager":
948
+ """Perform HTTP POST request."""
949
+ return _RequestContextManager(
950
+ self._request(hdrs.METH_POST, url, data=data, **kwargs)
951
+ )
952
+
953
+ def put(
954
+ self, url: StrOrURL, *, data: Any = None, **kwargs: Any
955
+ ) -> "_RequestContextManager":
956
+ """Perform HTTP PUT request."""
957
+ return _RequestContextManager(
958
+ self._request(hdrs.METH_PUT, url, data=data, **kwargs)
959
+ )
960
+
961
+ def patch(
962
+ self, url: StrOrURL, *, data: Any = None, **kwargs: Any
963
+ ) -> "_RequestContextManager":
964
+ """Perform HTTP PATCH request."""
965
+ return _RequestContextManager(
966
+ self._request(hdrs.METH_PATCH, url, data=data, **kwargs)
967
+ )
968
+
969
+ def delete(self, url: StrOrURL, **kwargs: Any) -> "_RequestContextManager":
970
+ """Perform HTTP DELETE request."""
971
+ return _RequestContextManager(self._request(hdrs.METH_DELETE, url, **kwargs))
972
+
973
+ async def close(self) -> None:
974
+ """Close underlying connector.
975
+
976
+ Release all acquired resources.
977
+ """
978
+ if not self.closed:
979
+ if self._connector is not None and self._connector_owner:
980
+ await self._connector.close()
981
+ self._connector = None
982
+
983
+ @property
984
+ def closed(self) -> bool:
985
+ """Is client session closed.
986
+
987
+ A readonly property.
988
+ """
989
+ return self._connector is None or self._connector.closed
990
+
991
+ @property
992
+ def connector(self) -> Optional[BaseConnector]:
993
+ """Connector instance used for the session."""
994
+ return self._connector
995
+
996
+ @property
997
+ def cookie_jar(self) -> AbstractCookieJar:
998
+ """The session cookies."""
999
+ return self._cookie_jar
1000
+
1001
+ @property
1002
+ def version(self) -> Tuple[int, int]:
1003
+ """The session HTTP protocol version."""
1004
+ return self._version
1005
+
1006
+ @property
1007
+ def requote_redirect_url(self) -> bool:
1008
+ """Do URL requoting on redirection handling."""
1009
+ return self._requote_redirect_url
1010
+
1011
+ @requote_redirect_url.setter
1012
+ def requote_redirect_url(self, val: bool) -> None:
1013
+ """Do URL requoting on redirection handling."""
1014
+ warnings.warn(
1015
+ "session.requote_redirect_url modification " "is deprecated #2778",
1016
+ DeprecationWarning,
1017
+ stacklevel=2,
1018
+ )
1019
+ self._requote_redirect_url = val
1020
+
1021
+ @property
1022
+ def loop(self) -> asyncio.AbstractEventLoop:
1023
+ """Session's loop."""
1024
+ warnings.warn(
1025
+ "client.loop property is deprecated", DeprecationWarning, stacklevel=2
1026
+ )
1027
+ return self._loop
1028
+
1029
+ @property
1030
+ def timeout(self) -> ClientTimeout:
1031
+ """Timeout for the session."""
1032
+ return self._timeout
1033
+
1034
+ @property
1035
+ def headers(self) -> "CIMultiDict[str]":
1036
+ """The default headers of the client session."""
1037
+ return self._default_headers
1038
+
1039
+ @property
1040
+ def skip_auto_headers(self) -> FrozenSet[istr]:
1041
+ """Headers for which autogeneration should be skipped"""
1042
+ return self._skip_auto_headers
1043
+
1044
+ @property
1045
+ def auth(self) -> Optional[BasicAuth]:
1046
+ """An object that represents HTTP Basic Authorization"""
1047
+ return self._default_auth
1048
+
1049
+ @property
1050
+ def json_serialize(self) -> JSONEncoder:
1051
+ """Json serializer callable"""
1052
+ return self._json_serialize
1053
+
1054
+ @property
1055
+ def connector_owner(self) -> bool:
1056
+ """Should connector be closed on session closing"""
1057
+ return self._connector_owner
1058
+
1059
+ @property
1060
+ def raise_for_status(
1061
+ self,
1062
+ ) -> Union[bool, Callable[[ClientResponse], Awaitable[None]]]:
1063
+ """Should `ClientResponse.raise_for_status()` be called for each response."""
1064
+ return self._raise_for_status
1065
+
1066
+ @property
1067
+ def auto_decompress(self) -> bool:
1068
+ """Should the body response be automatically decompressed."""
1069
+ return self._auto_decompress
1070
+
1071
+ @property
1072
+ def trust_env(self) -> bool:
1073
+ """
1074
+ Should proxies information from environment or netrc be trusted.
1075
+
1076
+ Information is from HTTP_PROXY / HTTPS_PROXY environment variables
1077
+ or ~/.netrc file if present.
1078
+ """
1079
+ return self._trust_env
1080
+
1081
+ @property
1082
+ def trace_configs(self) -> List[TraceConfig]:
1083
+ """A list of TraceConfig instances used for client tracing"""
1084
+ return self._trace_configs
1085
+
1086
+ def detach(self) -> None:
1087
+ """Detach connector from session without closing the former.
1088
+
1089
+ Session is switched to closed state anyway.
1090
+ """
1091
+ self._connector = None
1092
+
1093
+ def __enter__(self) -> None:
1094
+ raise TypeError("Use async with instead")
1095
+
1096
+ def __exit__(
1097
+ self,
1098
+ exc_type: Optional[Type[BaseException]],
1099
+ exc_val: Optional[BaseException],
1100
+ exc_tb: Optional[TracebackType],
1101
+ ) -> None:
1102
+ # __exit__ should exist in pair with __enter__ but never executed
1103
+ pass # pragma: no cover
1104
+
1105
+ async def __aenter__(self) -> "ClientSession":
1106
+ return self
1107
+
1108
+ async def __aexit__(
1109
+ self,
1110
+ exc_type: Optional[Type[BaseException]],
1111
+ exc_val: Optional[BaseException],
1112
+ exc_tb: Optional[TracebackType],
1113
+ ) -> None:
1114
+ await self.close()
1115
+
1116
+
1117
+ class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]):
1118
+
1119
+ __slots__ = ("_coro", "_resp")
1120
+
1121
+ def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None:
1122
+ self._coro = coro
1123
+
1124
+ def send(self, arg: None) -> "asyncio.Future[Any]":
1125
+ return self._coro.send(arg)
1126
+
1127
+ def throw(self, arg: BaseException) -> None: # type: ignore[arg-type,override]
1128
+ self._coro.throw(arg)
1129
+
1130
+ def close(self) -> None:
1131
+ return self._coro.close()
1132
+
1133
+ def __await__(self) -> Generator[Any, None, _RetType]:
1134
+ ret = self._coro.__await__()
1135
+ return ret
1136
+
1137
+ def __iter__(self) -> Generator[Any, None, _RetType]:
1138
+ return self.__await__()
1139
+
1140
+ async def __aenter__(self) -> _RetType:
1141
+ self._resp = await self._coro
1142
+ return self._resp
1143
+
1144
+
1145
+ class _RequestContextManager(_BaseRequestContextManager[ClientResponse]):
1146
+ __slots__ = ()
1147
+
1148
+ async def __aexit__(
1149
+ self,
1150
+ exc_type: Optional[Type[BaseException]],
1151
+ exc: Optional[BaseException],
1152
+ tb: Optional[TracebackType],
1153
+ ) -> None:
1154
+ # We're basing behavior on the exception as it can be caused by
1155
+ # user code unrelated to the status of the connection. If you
1156
+ # would like to close a connection you must do that
1157
+ # explicitly. Otherwise connection error handling should kick in
1158
+ # and close/recycle the connection as required.
1159
+ self._resp.release()
1160
+
1161
+
1162
+ class _WSRequestContextManager(_BaseRequestContextManager[ClientWebSocketResponse]):
1163
+ __slots__ = ()
1164
+
1165
+ async def __aexit__(
1166
+ self,
1167
+ exc_type: Optional[Type[BaseException]],
1168
+ exc: Optional[BaseException],
1169
+ tb: Optional[TracebackType],
1170
+ ) -> None:
1171
+ await self._resp.close()
1172
+
1173
+
1174
+ class _SessionRequestContextManager:
1175
+
1176
+ __slots__ = ("_coro", "_resp", "_session")
1177
+
1178
+ def __init__(
1179
+ self,
1180
+ coro: Coroutine["asyncio.Future[Any]", None, ClientResponse],
1181
+ session: ClientSession,
1182
+ ) -> None:
1183
+ self._coro = coro
1184
+ self._resp: Optional[ClientResponse] = None
1185
+ self._session = session
1186
+
1187
+ async def __aenter__(self) -> ClientResponse:
1188
+ try:
1189
+ self._resp = await self._coro
1190
+ except BaseException:
1191
+ await self._session.close()
1192
+ raise
1193
+ else:
1194
+ return self._resp
1195
+
1196
+ async def __aexit__(
1197
+ self,
1198
+ exc_type: Optional[Type[BaseException]],
1199
+ exc: Optional[BaseException],
1200
+ tb: Optional[TracebackType],
1201
+ ) -> None:
1202
+ assert self._resp is not None
1203
+ self._resp.close()
1204
+ await self._session.close()
1205
+
1206
+
1207
+ def request(
1208
+ method: str,
1209
+ url: StrOrURL,
1210
+ *,
1211
+ params: Optional[Mapping[str, str]] = None,
1212
+ data: Any = None,
1213
+ json: Any = None,
1214
+ headers: Optional[LooseHeaders] = None,
1215
+ skip_auto_headers: Optional[Iterable[str]] = None,
1216
+ auth: Optional[BasicAuth] = None,
1217
+ allow_redirects: bool = True,
1218
+ max_redirects: int = 10,
1219
+ compress: Optional[str] = None,
1220
+ chunked: Optional[bool] = None,
1221
+ expect100: bool = False,
1222
+ raise_for_status: Optional[bool] = None,
1223
+ read_until_eof: bool = True,
1224
+ proxy: Optional[StrOrURL] = None,
1225
+ proxy_auth: Optional[BasicAuth] = None,
1226
+ timeout: Union[ClientTimeout, object] = sentinel,
1227
+ cookies: Optional[LooseCookies] = None,
1228
+ version: HttpVersion = http.HttpVersion11,
1229
+ connector: Optional[BaseConnector] = None,
1230
+ read_bufsize: Optional[int] = None,
1231
+ loop: Optional[asyncio.AbstractEventLoop] = None,
1232
+ ) -> _SessionRequestContextManager:
1233
+ """Constructs and sends a request.
1234
+
1235
+ Returns response object.
1236
+ method - HTTP method
1237
+ url - request url
1238
+ params - (optional) Dictionary or bytes to be sent in the query
1239
+ string of the new request
1240
+ data - (optional) Dictionary, bytes, or file-like object to
1241
+ send in the body of the request
1242
+ json - (optional) Any json compatible python object
1243
+ headers - (optional) Dictionary of HTTP Headers to send with
1244
+ the request
1245
+ cookies - (optional) Dict object to send with the request
1246
+ auth - (optional) BasicAuth named tuple represent HTTP Basic Auth
1247
+ auth - aiohttp.helpers.BasicAuth
1248
+ allow_redirects - (optional) If set to False, do not follow
1249
+ redirects
1250
+ version - Request HTTP version.
1251
+ compress - Set to True if request has to be compressed
1252
+ with deflate encoding.
1253
+ chunked - Set to chunk size for chunked transfer encoding.
1254
+ expect100 - Expect 100-continue response from server.
1255
+ connector - BaseConnector sub-class instance to support
1256
+ connection pooling.
1257
+ read_until_eof - Read response until eof if response
1258
+ does not have Content-Length header.
1259
+ loop - Optional event loop.
1260
+ timeout - Optional ClientTimeout settings structure, 5min
1261
+ total timeout by default.
1262
+ Usage::
1263
+ >>> import aiohttp
1264
+ >>> resp = await aiohttp.request('GET', 'http://python.org/')
1265
+ >>> resp
1266
+ <ClientResponse(python.org/) [200]>
1267
+ >>> data = await resp.read()
1268
+ """
1269
+ connector_owner = False
1270
+ if connector is None:
1271
+ connector_owner = True
1272
+ connector = TCPConnector(loop=loop, force_close=True)
1273
+
1274
+ session = ClientSession(
1275
+ loop=loop,
1276
+ cookies=cookies,
1277
+ version=version,
1278
+ timeout=timeout,
1279
+ connector=connector,
1280
+ connector_owner=connector_owner,
1281
+ )
1282
+
1283
+ return _SessionRequestContextManager(
1284
+ session._request(
1285
+ method,
1286
+ url,
1287
+ params=params,
1288
+ data=data,
1289
+ json=json,
1290
+ headers=headers,
1291
+ skip_auto_headers=skip_auto_headers,
1292
+ auth=auth,
1293
+ allow_redirects=allow_redirects,
1294
+ max_redirects=max_redirects,
1295
+ compress=compress,
1296
+ chunked=chunked,
1297
+ expect100=expect100,
1298
+ raise_for_status=raise_for_status,
1299
+ read_until_eof=read_until_eof,
1300
+ proxy=proxy,
1301
+ proxy_auth=proxy_auth,
1302
+ read_bufsize=read_bufsize,
1303
+ ),
1304
+ session,
1305
+ )
runtime/Lib/site-packages/aiohttp/client_exceptions.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP related errors."""
2
+
3
+ import asyncio
4
+ import warnings
5
+ from typing import TYPE_CHECKING, Any, Optional, Tuple, Union
6
+
7
+ from .http_parser import RawResponseMessage
8
+ from .typedefs import LooseHeaders
9
+
10
+ try:
11
+ import ssl
12
+
13
+ SSLContext = ssl.SSLContext
14
+ except ImportError: # pragma: no cover
15
+ ssl = SSLContext = None # type: ignore[assignment]
16
+
17
+
18
+ if TYPE_CHECKING: # pragma: no cover
19
+ from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo
20
+ else:
21
+ RequestInfo = ClientResponse = ConnectionKey = None
22
+
23
+ __all__ = (
24
+ "ClientError",
25
+ "ClientConnectionError",
26
+ "ClientOSError",
27
+ "ClientConnectorError",
28
+ "ClientProxyConnectionError",
29
+ "ClientSSLError",
30
+ "ClientConnectorSSLError",
31
+ "ClientConnectorCertificateError",
32
+ "ServerConnectionError",
33
+ "ServerTimeoutError",
34
+ "ServerDisconnectedError",
35
+ "ServerFingerprintMismatch",
36
+ "ClientResponseError",
37
+ "ClientHttpProxyError",
38
+ "WSServerHandshakeError",
39
+ "ContentTypeError",
40
+ "ClientPayloadError",
41
+ "InvalidURL",
42
+ )
43
+
44
+
45
+ class ClientError(Exception):
46
+ """Base class for client connection errors."""
47
+
48
+
49
+ class ClientResponseError(ClientError):
50
+ """Connection error during reading response.
51
+
52
+ request_info: instance of RequestInfo
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ request_info: RequestInfo,
58
+ history: Tuple[ClientResponse, ...],
59
+ *,
60
+ code: Optional[int] = None,
61
+ status: Optional[int] = None,
62
+ message: str = "",
63
+ headers: Optional[LooseHeaders] = None,
64
+ ) -> None:
65
+ self.request_info = request_info
66
+ if code is not None:
67
+ if status is not None:
68
+ raise ValueError(
69
+ "Both code and status arguments are provided; "
70
+ "code is deprecated, use status instead"
71
+ )
72
+ warnings.warn(
73
+ "code argument is deprecated, use status instead",
74
+ DeprecationWarning,
75
+ stacklevel=2,
76
+ )
77
+ if status is not None:
78
+ self.status = status
79
+ elif code is not None:
80
+ self.status = code
81
+ else:
82
+ self.status = 0
83
+ self.message = message
84
+ self.headers = headers
85
+ self.history = history
86
+ self.args = (request_info, history)
87
+
88
+ def __str__(self) -> str:
89
+ return "{}, message={!r}, url={!r}".format(
90
+ self.status,
91
+ self.message,
92
+ self.request_info.real_url,
93
+ )
94
+
95
+ def __repr__(self) -> str:
96
+ args = f"{self.request_info!r}, {self.history!r}"
97
+ if self.status != 0:
98
+ args += f", status={self.status!r}"
99
+ if self.message != "":
100
+ args += f", message={self.message!r}"
101
+ if self.headers is not None:
102
+ args += f", headers={self.headers!r}"
103
+ return f"{type(self).__name__}({args})"
104
+
105
+ @property
106
+ def code(self) -> int:
107
+ warnings.warn(
108
+ "code property is deprecated, use status instead",
109
+ DeprecationWarning,
110
+ stacklevel=2,
111
+ )
112
+ return self.status
113
+
114
+ @code.setter
115
+ def code(self, value: int) -> None:
116
+ warnings.warn(
117
+ "code property is deprecated, use status instead",
118
+ DeprecationWarning,
119
+ stacklevel=2,
120
+ )
121
+ self.status = value
122
+
123
+
124
+ class ContentTypeError(ClientResponseError):
125
+ """ContentType found is not valid."""
126
+
127
+
128
+ class WSServerHandshakeError(ClientResponseError):
129
+ """websocket server handshake error."""
130
+
131
+
132
+ class ClientHttpProxyError(ClientResponseError):
133
+ """HTTP proxy error.
134
+
135
+ Raised in :class:`aiohttp.connector.TCPConnector` if
136
+ proxy responds with status other than ``200 OK``
137
+ on ``CONNECT`` request.
138
+ """
139
+
140
+
141
+ class TooManyRedirects(ClientResponseError):
142
+ """Client was redirected too many times."""
143
+
144
+
145
+ class ClientConnectionError(ClientError):
146
+ """Base class for client socket errors."""
147
+
148
+
149
+ class ClientOSError(ClientConnectionError, OSError):
150
+ """OSError error."""
151
+
152
+
153
+ class ClientConnectorError(ClientOSError):
154
+ """Client connector error.
155
+
156
+ Raised in :class:`aiohttp.connector.TCPConnector` if
157
+ a connection can not be established.
158
+ """
159
+
160
+ def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None:
161
+ self._conn_key = connection_key
162
+ self._os_error = os_error
163
+ super().__init__(os_error.errno, os_error.strerror)
164
+ self.args = (connection_key, os_error)
165
+
166
+ @property
167
+ def os_error(self) -> OSError:
168
+ return self._os_error
169
+
170
+ @property
171
+ def host(self) -> str:
172
+ return self._conn_key.host
173
+
174
+ @property
175
+ def port(self) -> Optional[int]:
176
+ return self._conn_key.port
177
+
178
+ @property
179
+ def ssl(self) -> Union[SSLContext, None, bool, "Fingerprint"]:
180
+ return self._conn_key.ssl
181
+
182
+ def __str__(self) -> str:
183
+ return "Cannot connect to host {0.host}:{0.port} ssl:{1} [{2}]".format(
184
+ self, self.ssl if self.ssl is not None else "default", self.strerror
185
+ )
186
+
187
+ # OSError.__reduce__ does too much black magick
188
+ __reduce__ = BaseException.__reduce__
189
+
190
+
191
+ class ClientProxyConnectionError(ClientConnectorError):
192
+ """Proxy connection error.
193
+
194
+ Raised in :class:`aiohttp.connector.TCPConnector` if
195
+ connection to proxy can not be established.
196
+ """
197
+
198
+
199
+ class UnixClientConnectorError(ClientConnectorError):
200
+ """Unix connector error.
201
+
202
+ Raised in :py:class:`aiohttp.connector.UnixConnector`
203
+ if connection to unix socket can not be established.
204
+ """
205
+
206
+ def __init__(
207
+ self, path: str, connection_key: ConnectionKey, os_error: OSError
208
+ ) -> None:
209
+ self._path = path
210
+ super().__init__(connection_key, os_error)
211
+
212
+ @property
213
+ def path(self) -> str:
214
+ return self._path
215
+
216
+ def __str__(self) -> str:
217
+ return "Cannot connect to unix socket {0.path} ssl:{1} [{2}]".format(
218
+ self, self.ssl if self.ssl is not None else "default", self.strerror
219
+ )
220
+
221
+
222
+ class ServerConnectionError(ClientConnectionError):
223
+ """Server connection errors."""
224
+
225
+
226
+ class ServerDisconnectedError(ServerConnectionError):
227
+ """Server disconnected."""
228
+
229
+ def __init__(self, message: Union[RawResponseMessage, str, None] = None) -> None:
230
+ if message is None:
231
+ message = "Server disconnected"
232
+
233
+ self.args = (message,)
234
+ self.message = message
235
+
236
+
237
+ class ServerTimeoutError(ServerConnectionError, asyncio.TimeoutError):
238
+ """Server timeout error."""
239
+
240
+
241
+ class ServerFingerprintMismatch(ServerConnectionError):
242
+ """SSL certificate does not match expected fingerprint."""
243
+
244
+ def __init__(self, expected: bytes, got: bytes, host: str, port: int) -> None:
245
+ self.expected = expected
246
+ self.got = got
247
+ self.host = host
248
+ self.port = port
249
+ self.args = (expected, got, host, port)
250
+
251
+ def __repr__(self) -> str:
252
+ return "<{} expected={!r} got={!r} host={!r} port={!r}>".format(
253
+ self.__class__.__name__, self.expected, self.got, self.host, self.port
254
+ )
255
+
256
+
257
+ class ClientPayloadError(ClientError):
258
+ """Response payload error."""
259
+
260
+
261
+ class InvalidURL(ClientError, ValueError):
262
+ """Invalid URL.
263
+
264
+ URL used for fetching is malformed, e.g. it doesn't contains host
265
+ part.
266
+ """
267
+
268
+ # Derive from ValueError for backward compatibility
269
+
270
+ def __init__(self, url: Any) -> None:
271
+ # The type of url is not yarl.URL because the exception can be raised
272
+ # on URL(url) call
273
+ super().__init__(url)
274
+
275
+ @property
276
+ def url(self) -> Any:
277
+ return self.args[0]
278
+
279
+ def __repr__(self) -> str:
280
+ return f"<{self.__class__.__name__} {self.url}>"
281
+
282
+
283
+ class ClientSSLError(ClientConnectorError):
284
+ """Base error for ssl.*Errors."""
285
+
286
+
287
+ if ssl is not None:
288
+ cert_errors = (ssl.CertificateError,)
289
+ cert_errors_bases = (
290
+ ClientSSLError,
291
+ ssl.CertificateError,
292
+ )
293
+
294
+ ssl_errors = (ssl.SSLError,)
295
+ ssl_error_bases = (ClientSSLError, ssl.SSLError)
296
+ else: # pragma: no cover
297
+ cert_errors = tuple()
298
+ cert_errors_bases = (
299
+ ClientSSLError,
300
+ ValueError,
301
+ )
302
+
303
+ ssl_errors = tuple()
304
+ ssl_error_bases = (ClientSSLError,)
305
+
306
+
307
+ class ClientConnectorSSLError(*ssl_error_bases): # type: ignore[misc]
308
+ """Response ssl error."""
309
+
310
+
311
+ class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc]
312
+ """Response certificate error."""
313
+
314
+ def __init__(
315
+ self, connection_key: ConnectionKey, certificate_error: Exception
316
+ ) -> None:
317
+ self._conn_key = connection_key
318
+ self._certificate_error = certificate_error
319
+ self.args = (connection_key, certificate_error)
320
+
321
+ @property
322
+ def certificate_error(self) -> Exception:
323
+ return self._certificate_error
324
+
325
+ @property
326
+ def host(self) -> str:
327
+ return self._conn_key.host
328
+
329
+ @property
330
+ def port(self) -> Optional[int]:
331
+ return self._conn_key.port
332
+
333
+ @property
334
+ def ssl(self) -> bool:
335
+ return self._conn_key.is_ssl
336
+
337
+ def __str__(self) -> str:
338
+ return (
339
+ "Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} "
340
+ "[{0.certificate_error.__class__.__name__}: "
341
+ "{0.certificate_error.args}]".format(self)
342
+ )
runtime/Lib/site-packages/aiohttp/client_proto.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from contextlib import suppress
3
+ from typing import Any, Optional, Tuple
4
+
5
+ from .base_protocol import BaseProtocol
6
+ from .client_exceptions import (
7
+ ClientOSError,
8
+ ClientPayloadError,
9
+ ServerDisconnectedError,
10
+ ServerTimeoutError,
11
+ )
12
+ from .helpers import BaseTimerContext
13
+ from .http import HttpResponseParser, RawResponseMessage
14
+ from .streams import EMPTY_PAYLOAD, DataQueue, StreamReader
15
+
16
+
17
+ class ResponseHandler(BaseProtocol, DataQueue[Tuple[RawResponseMessage, StreamReader]]):
18
+ """Helper class to adapt between Protocol and StreamReader."""
19
+
20
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
21
+ BaseProtocol.__init__(self, loop=loop)
22
+ DataQueue.__init__(self, loop)
23
+
24
+ self._should_close = False
25
+
26
+ self._payload: Optional[StreamReader] = None
27
+ self._skip_payload = False
28
+ self._payload_parser = None
29
+
30
+ self._timer = None
31
+
32
+ self._tail = b""
33
+ self._upgraded = False
34
+ self._parser: Optional[HttpResponseParser] = None
35
+
36
+ self._read_timeout: Optional[float] = None
37
+ self._read_timeout_handle: Optional[asyncio.TimerHandle] = None
38
+
39
+ @property
40
+ def upgraded(self) -> bool:
41
+ return self._upgraded
42
+
43
+ @property
44
+ def should_close(self) -> bool:
45
+ if self._payload is not None and not self._payload.is_eof() or self._upgraded:
46
+ return True
47
+
48
+ return (
49
+ self._should_close
50
+ or self._upgraded
51
+ or self.exception() is not None
52
+ or self._payload_parser is not None
53
+ or len(self) > 0
54
+ or bool(self._tail)
55
+ )
56
+
57
+ def force_close(self) -> None:
58
+ self._should_close = True
59
+
60
+ def close(self) -> None:
61
+ transport = self.transport
62
+ if transport is not None:
63
+ transport.close()
64
+ self.transport = None
65
+ self._payload = None
66
+ self._drop_timeout()
67
+
68
+ def is_connected(self) -> bool:
69
+ return self.transport is not None and not self.transport.is_closing()
70
+
71
+ def connection_lost(self, exc: Optional[BaseException]) -> None:
72
+ self._drop_timeout()
73
+
74
+ if self._payload_parser is not None:
75
+ with suppress(Exception):
76
+ self._payload_parser.feed_eof()
77
+
78
+ uncompleted = None
79
+ if self._parser is not None:
80
+ try:
81
+ uncompleted = self._parser.feed_eof()
82
+ except Exception:
83
+ if self._payload is not None:
84
+ self._payload.set_exception(
85
+ ClientPayloadError("Response payload is not completed")
86
+ )
87
+
88
+ if not self.is_eof():
89
+ if isinstance(exc, OSError):
90
+ exc = ClientOSError(*exc.args)
91
+ if exc is None:
92
+ exc = ServerDisconnectedError(uncompleted)
93
+ # assigns self._should_close to True as side effect,
94
+ # we do it anyway below
95
+ self.set_exception(exc)
96
+
97
+ self._should_close = True
98
+ self._parser = None
99
+ self._payload = None
100
+ self._payload_parser = None
101
+ self._reading_paused = False
102
+
103
+ super().connection_lost(exc)
104
+
105
+ def eof_received(self) -> None:
106
+ # should call parser.feed_eof() most likely
107
+ self._drop_timeout()
108
+
109
+ def pause_reading(self) -> None:
110
+ super().pause_reading()
111
+ self._drop_timeout()
112
+
113
+ def resume_reading(self) -> None:
114
+ super().resume_reading()
115
+ self._reschedule_timeout()
116
+
117
+ def set_exception(self, exc: BaseException) -> None:
118
+ self._should_close = True
119
+ self._drop_timeout()
120
+ super().set_exception(exc)
121
+
122
+ def set_parser(self, parser: Any, payload: Any) -> None:
123
+ # TODO: actual types are:
124
+ # parser: WebSocketReader
125
+ # payload: FlowControlDataQueue
126
+ # but they are not generi enough
127
+ # Need an ABC for both types
128
+ self._payload = payload
129
+ self._payload_parser = parser
130
+
131
+ self._drop_timeout()
132
+
133
+ if self._tail:
134
+ data, self._tail = self._tail, b""
135
+ self.data_received(data)
136
+
137
+ def set_response_params(
138
+ self,
139
+ *,
140
+ timer: Optional[BaseTimerContext] = None,
141
+ skip_payload: bool = False,
142
+ read_until_eof: bool = False,
143
+ auto_decompress: bool = True,
144
+ read_timeout: Optional[float] = None,
145
+ read_bufsize: int = 2**16,
146
+ ) -> None:
147
+ self._skip_payload = skip_payload
148
+
149
+ self._read_timeout = read_timeout
150
+ self._reschedule_timeout()
151
+
152
+ self._parser = HttpResponseParser(
153
+ self,
154
+ self._loop,
155
+ read_bufsize,
156
+ timer=timer,
157
+ payload_exception=ClientPayloadError,
158
+ response_with_body=not skip_payload,
159
+ read_until_eof=read_until_eof,
160
+ auto_decompress=auto_decompress,
161
+ )
162
+
163
+ if self._tail:
164
+ data, self._tail = self._tail, b""
165
+ self.data_received(data)
166
+
167
+ def _drop_timeout(self) -> None:
168
+ if self._read_timeout_handle is not None:
169
+ self._read_timeout_handle.cancel()
170
+ self._read_timeout_handle = None
171
+
172
+ def _reschedule_timeout(self) -> None:
173
+ timeout = self._read_timeout
174
+ if self._read_timeout_handle is not None:
175
+ self._read_timeout_handle.cancel()
176
+
177
+ if timeout:
178
+ self._read_timeout_handle = self._loop.call_later(
179
+ timeout, self._on_read_timeout
180
+ )
181
+ else:
182
+ self._read_timeout_handle = None
183
+
184
+ def _on_read_timeout(self) -> None:
185
+ exc = ServerTimeoutError("Timeout on reading data from socket")
186
+ self.set_exception(exc)
187
+ if self._payload is not None:
188
+ self._payload.set_exception(exc)
189
+
190
+ def data_received(self, data: bytes) -> None:
191
+ self._reschedule_timeout()
192
+
193
+ if not data:
194
+ return
195
+
196
+ # custom payload parser
197
+ if self._payload_parser is not None:
198
+ eof, tail = self._payload_parser.feed_data(data)
199
+ if eof:
200
+ self._payload = None
201
+ self._payload_parser = None
202
+
203
+ if tail:
204
+ self.data_received(tail)
205
+ return
206
+ else:
207
+ if self._upgraded or self._parser is None:
208
+ # i.e. websocket connection, websocket parser is not set yet
209
+ self._tail += data
210
+ else:
211
+ # parse http messages
212
+ try:
213
+ messages, upgraded, tail = self._parser.feed_data(data)
214
+ except BaseException as exc:
215
+ if self.transport is not None:
216
+ # connection.release() could be called BEFORE
217
+ # data_received(), the transport is already
218
+ # closed in this case
219
+ self.transport.close()
220
+ # should_close is True after the call
221
+ self.set_exception(exc)
222
+ return
223
+
224
+ self._upgraded = upgraded
225
+
226
+ payload: Optional[StreamReader] = None
227
+ for message, payload in messages:
228
+ if message.should_close:
229
+ self._should_close = True
230
+
231
+ self._payload = payload
232
+
233
+ if self._skip_payload or message.code in (204, 304):
234
+ self.feed_data((message, EMPTY_PAYLOAD), 0)
235
+ else:
236
+ self.feed_data((message, payload), 0)
237
+ if payload is not None:
238
+ # new message(s) was processed
239
+ # register timeout handler unsubscribing
240
+ # either on end-of-stream or immediately for
241
+ # EMPTY_PAYLOAD
242
+ if payload is not EMPTY_PAYLOAD:
243
+ payload.on_eof(self._drop_timeout)
244
+ else:
245
+ self._drop_timeout()
246
+
247
+ if tail:
248
+ if upgraded:
249
+ self.data_received(tail)
250
+ else:
251
+ self._tail = tail
runtime/Lib/site-packages/aiohttp/client_reqrep.py ADDED
@@ -0,0 +1,1134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import codecs
3
+ import functools
4
+ import io
5
+ import re
6
+ import sys
7
+ import traceback
8
+ import warnings
9
+ from hashlib import md5, sha1, sha256
10
+ from http.cookies import CookieError, Morsel, SimpleCookie
11
+ from types import MappingProxyType, TracebackType
12
+ from typing import (
13
+ TYPE_CHECKING,
14
+ Any,
15
+ Dict,
16
+ Iterable,
17
+ List,
18
+ Mapping,
19
+ Optional,
20
+ Tuple,
21
+ Type,
22
+ Union,
23
+ cast,
24
+ )
25
+
26
+ import attr
27
+ from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
28
+ from yarl import URL
29
+
30
+ from . import hdrs, helpers, http, multipart, payload
31
+ from .abc import AbstractStreamWriter
32
+ from .client_exceptions import (
33
+ ClientConnectionError,
34
+ ClientOSError,
35
+ ClientResponseError,
36
+ ContentTypeError,
37
+ InvalidURL,
38
+ ServerFingerprintMismatch,
39
+ )
40
+ from .formdata import FormData
41
+ from .helpers import (
42
+ PY_36,
43
+ BaseTimerContext,
44
+ BasicAuth,
45
+ HeadersMixin,
46
+ TimerNoop,
47
+ noop,
48
+ reify,
49
+ set_result,
50
+ )
51
+ from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11, StreamWriter
52
+ from .log import client_logger
53
+ from .streams import StreamReader
54
+ from .typedefs import (
55
+ DEFAULT_JSON_DECODER,
56
+ JSONDecoder,
57
+ LooseCookies,
58
+ LooseHeaders,
59
+ RawHeaders,
60
+ )
61
+
62
+ try:
63
+ import ssl
64
+ from ssl import SSLContext
65
+ except ImportError: # pragma: no cover
66
+ ssl = None # type: ignore[assignment]
67
+ SSLContext = object # type: ignore[misc,assignment]
68
+
69
+ try:
70
+ import cchardet as chardet
71
+ except ImportError: # pragma: no cover
72
+ import charset_normalizer as chardet # type: ignore[no-redef]
73
+
74
+
75
+ __all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint")
76
+
77
+
78
+ if TYPE_CHECKING: # pragma: no cover
79
+ from .client import ClientSession
80
+ from .connector import Connection
81
+ from .tracing import Trace
82
+
83
+
84
+ json_re = re.compile(r"^application/(?:[\w.+-]+?\+)?json")
85
+
86
+
87
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
88
+ class ContentDisposition:
89
+ type: Optional[str]
90
+ parameters: "MappingProxyType[str, str]"
91
+ filename: Optional[str]
92
+
93
+
94
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
95
+ class RequestInfo:
96
+ url: URL
97
+ method: str
98
+ headers: "CIMultiDictProxy[str]"
99
+ real_url: URL = attr.ib()
100
+
101
+ @real_url.default
102
+ def real_url_default(self) -> URL:
103
+ return self.url
104
+
105
+
106
+ class Fingerprint:
107
+ HASHFUNC_BY_DIGESTLEN = {
108
+ 16: md5,
109
+ 20: sha1,
110
+ 32: sha256,
111
+ }
112
+
113
+ def __init__(self, fingerprint: bytes) -> None:
114
+ digestlen = len(fingerprint)
115
+ hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen)
116
+ if not hashfunc:
117
+ raise ValueError("fingerprint has invalid length")
118
+ elif hashfunc is md5 or hashfunc is sha1:
119
+ raise ValueError(
120
+ "md5 and sha1 are insecure and " "not supported. Use sha256."
121
+ )
122
+ self._hashfunc = hashfunc
123
+ self._fingerprint = fingerprint
124
+
125
+ @property
126
+ def fingerprint(self) -> bytes:
127
+ return self._fingerprint
128
+
129
+ def check(self, transport: asyncio.Transport) -> None:
130
+ if not transport.get_extra_info("sslcontext"):
131
+ return
132
+ sslobj = transport.get_extra_info("ssl_object")
133
+ cert = sslobj.getpeercert(binary_form=True)
134
+ got = self._hashfunc(cert).digest()
135
+ if got != self._fingerprint:
136
+ host, port, *_ = transport.get_extra_info("peername")
137
+ raise ServerFingerprintMismatch(self._fingerprint, got, host, port)
138
+
139
+
140
+ if ssl is not None:
141
+ SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None))
142
+ else: # pragma: no cover
143
+ SSL_ALLOWED_TYPES = type(None)
144
+
145
+
146
+ def _merge_ssl_params(
147
+ ssl: Union["SSLContext", bool, Fingerprint, None],
148
+ verify_ssl: Optional[bool],
149
+ ssl_context: Optional["SSLContext"],
150
+ fingerprint: Optional[bytes],
151
+ ) -> Union["SSLContext", bool, Fingerprint, None]:
152
+ if verify_ssl is not None and not verify_ssl:
153
+ warnings.warn(
154
+ "verify_ssl is deprecated, use ssl=False instead",
155
+ DeprecationWarning,
156
+ stacklevel=3,
157
+ )
158
+ if ssl is not None:
159
+ raise ValueError(
160
+ "verify_ssl, ssl_context, fingerprint and ssl "
161
+ "parameters are mutually exclusive"
162
+ )
163
+ else:
164
+ ssl = False
165
+ if ssl_context is not None:
166
+ warnings.warn(
167
+ "ssl_context is deprecated, use ssl=context instead",
168
+ DeprecationWarning,
169
+ stacklevel=3,
170
+ )
171
+ if ssl is not None:
172
+ raise ValueError(
173
+ "verify_ssl, ssl_context, fingerprint and ssl "
174
+ "parameters are mutually exclusive"
175
+ )
176
+ else:
177
+ ssl = ssl_context
178
+ if fingerprint is not None:
179
+ warnings.warn(
180
+ "fingerprint is deprecated, " "use ssl=Fingerprint(fingerprint) instead",
181
+ DeprecationWarning,
182
+ stacklevel=3,
183
+ )
184
+ if ssl is not None:
185
+ raise ValueError(
186
+ "verify_ssl, ssl_context, fingerprint and ssl "
187
+ "parameters are mutually exclusive"
188
+ )
189
+ else:
190
+ ssl = Fingerprint(fingerprint)
191
+ if not isinstance(ssl, SSL_ALLOWED_TYPES):
192
+ raise TypeError(
193
+ "ssl should be SSLContext, bool, Fingerprint or None, "
194
+ "got {!r} instead.".format(ssl)
195
+ )
196
+ return ssl
197
+
198
+
199
+ @attr.s(auto_attribs=True, slots=True, frozen=True)
200
+ class ConnectionKey:
201
+ # the key should contain an information about used proxy / TLS
202
+ # to prevent reusing wrong connections from a pool
203
+ host: str
204
+ port: Optional[int]
205
+ is_ssl: bool
206
+ ssl: Union[SSLContext, None, bool, Fingerprint]
207
+ proxy: Optional[URL]
208
+ proxy_auth: Optional[BasicAuth]
209
+ proxy_headers_hash: Optional[int] # hash(CIMultiDict)
210
+
211
+
212
+ def _is_expected_content_type(
213
+ response_content_type: str, expected_content_type: str
214
+ ) -> bool:
215
+ if expected_content_type == "application/json":
216
+ return json_re.match(response_content_type) is not None
217
+ return expected_content_type in response_content_type
218
+
219
+
220
+ class ClientRequest:
221
+ GET_METHODS = {
222
+ hdrs.METH_GET,
223
+ hdrs.METH_HEAD,
224
+ hdrs.METH_OPTIONS,
225
+ hdrs.METH_TRACE,
226
+ }
227
+ POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT}
228
+ ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE})
229
+
230
+ DEFAULT_HEADERS = {
231
+ hdrs.ACCEPT: "*/*",
232
+ hdrs.ACCEPT_ENCODING: "gzip, deflate",
233
+ }
234
+
235
+ body = b""
236
+ auth = None
237
+ response = None
238
+
239
+ _writer = None # async task for streaming data
240
+ _continue = None # waiter future for '100 Continue' response
241
+
242
+ # N.B.
243
+ # Adding __del__ method with self._writer closing doesn't make sense
244
+ # because _writer is instance method, thus it keeps a reference to self.
245
+ # Until writer has finished finalizer will not be called.
246
+
247
+ def __init__(
248
+ self,
249
+ method: str,
250
+ url: URL,
251
+ *,
252
+ params: Optional[Mapping[str, str]] = None,
253
+ headers: Optional[LooseHeaders] = None,
254
+ skip_auto_headers: Iterable[str] = frozenset(),
255
+ data: Any = None,
256
+ cookies: Optional[LooseCookies] = None,
257
+ auth: Optional[BasicAuth] = None,
258
+ version: http.HttpVersion = http.HttpVersion11,
259
+ compress: Optional[str] = None,
260
+ chunked: Optional[bool] = None,
261
+ expect100: bool = False,
262
+ loop: Optional[asyncio.AbstractEventLoop] = None,
263
+ response_class: Optional[Type["ClientResponse"]] = None,
264
+ proxy: Optional[URL] = None,
265
+ proxy_auth: Optional[BasicAuth] = None,
266
+ timer: Optional[BaseTimerContext] = None,
267
+ session: Optional["ClientSession"] = None,
268
+ ssl: Union[SSLContext, bool, Fingerprint, None] = None,
269
+ proxy_headers: Optional[LooseHeaders] = None,
270
+ traces: Optional[List["Trace"]] = None,
271
+ ):
272
+
273
+ if loop is None:
274
+ loop = asyncio.get_event_loop()
275
+
276
+ assert isinstance(url, URL), url
277
+ assert isinstance(proxy, (URL, type(None))), proxy
278
+ # FIXME: session is None in tests only, need to fix tests
279
+ # assert session is not None
280
+ self._session = cast("ClientSession", session)
281
+ if params:
282
+ q = MultiDict(url.query)
283
+ url2 = url.with_query(params)
284
+ q.extend(url2.query)
285
+ url = url.with_query(q)
286
+ self.original_url = url
287
+ self.url = url.with_fragment(None)
288
+ self.method = method.upper()
289
+ self.chunked = chunked
290
+ self.compress = compress
291
+ self.loop = loop
292
+ self.length = None
293
+ if response_class is None:
294
+ real_response_class = ClientResponse
295
+ else:
296
+ real_response_class = response_class
297
+ self.response_class: Type[ClientResponse] = real_response_class
298
+ self._timer = timer if timer is not None else TimerNoop()
299
+ self._ssl = ssl
300
+
301
+ if loop.get_debug():
302
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
303
+
304
+ self.update_version(version)
305
+ self.update_host(url)
306
+ self.update_headers(headers)
307
+ self.update_auto_headers(skip_auto_headers)
308
+ self.update_cookies(cookies)
309
+ self.update_content_encoding(data)
310
+ self.update_auth(auth)
311
+ self.update_proxy(proxy, proxy_auth, proxy_headers)
312
+
313
+ self.update_body_from_data(data)
314
+ if data is not None or self.method not in self.GET_METHODS:
315
+ self.update_transfer_encoding()
316
+ self.update_expect_continue(expect100)
317
+ if traces is None:
318
+ traces = []
319
+ self._traces = traces
320
+
321
+ def is_ssl(self) -> bool:
322
+ return self.url.scheme in ("https", "wss")
323
+
324
+ @property
325
+ def ssl(self) -> Union["SSLContext", None, bool, Fingerprint]:
326
+ return self._ssl
327
+
328
+ @property
329
+ def connection_key(self) -> ConnectionKey:
330
+ proxy_headers = self.proxy_headers
331
+ if proxy_headers:
332
+ h: Optional[int] = hash(tuple((k, v) for k, v in proxy_headers.items()))
333
+ else:
334
+ h = None
335
+ return ConnectionKey(
336
+ self.host,
337
+ self.port,
338
+ self.is_ssl(),
339
+ self.ssl,
340
+ self.proxy,
341
+ self.proxy_auth,
342
+ h,
343
+ )
344
+
345
+ @property
346
+ def host(self) -> str:
347
+ ret = self.url.raw_host
348
+ assert ret is not None
349
+ return ret
350
+
351
+ @property
352
+ def port(self) -> Optional[int]:
353
+ return self.url.port
354
+
355
+ @property
356
+ def request_info(self) -> RequestInfo:
357
+ headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers)
358
+ return RequestInfo(self.url, self.method, headers, self.original_url)
359
+
360
+ def update_host(self, url: URL) -> None:
361
+ """Update destination host, port and connection type (ssl)."""
362
+ # get host/port
363
+ if not url.raw_host:
364
+ raise InvalidURL(url)
365
+
366
+ # basic auth info
367
+ username, password = url.user, url.password
368
+ if username:
369
+ self.auth = helpers.BasicAuth(username, password or "")
370
+
371
+ def update_version(self, version: Union[http.HttpVersion, str]) -> None:
372
+ """Convert request version to two elements tuple.
373
+
374
+ parser HTTP version '1.1' => (1, 1)
375
+ """
376
+ if isinstance(version, str):
377
+ v = [part.strip() for part in version.split(".", 1)]
378
+ try:
379
+ version = http.HttpVersion(int(v[0]), int(v[1]))
380
+ except ValueError:
381
+ raise ValueError(
382
+ f"Can not parse http version number: {version}"
383
+ ) from None
384
+ self.version = version
385
+
386
+ def update_headers(self, headers: Optional[LooseHeaders]) -> None:
387
+ """Update request headers."""
388
+ self.headers: CIMultiDict[str] = CIMultiDict()
389
+
390
+ # add host
391
+ netloc = cast(str, self.url.raw_host)
392
+ if helpers.is_ipv6_address(netloc):
393
+ netloc = f"[{netloc}]"
394
+ if self.url.port is not None and not self.url.is_default_port():
395
+ netloc += ":" + str(self.url.port)
396
+ self.headers[hdrs.HOST] = netloc
397
+
398
+ if headers:
399
+ if isinstance(headers, (dict, MultiDictProxy, MultiDict)):
400
+ headers = headers.items() # type: ignore[assignment]
401
+
402
+ for key, value in headers: # type: ignore[misc]
403
+ # A special case for Host header
404
+ if key.lower() == "host":
405
+ self.headers[key] = value
406
+ else:
407
+ self.headers.add(key, value)
408
+
409
+ def update_auto_headers(self, skip_auto_headers: Iterable[str]) -> None:
410
+ self.skip_auto_headers = CIMultiDict(
411
+ (hdr, None) for hdr in sorted(skip_auto_headers)
412
+ )
413
+ used_headers = self.headers.copy()
414
+ used_headers.extend(self.skip_auto_headers) # type: ignore[arg-type]
415
+
416
+ for hdr, val in self.DEFAULT_HEADERS.items():
417
+ if hdr not in used_headers:
418
+ self.headers.add(hdr, val)
419
+
420
+ if hdrs.USER_AGENT not in used_headers:
421
+ self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE
422
+
423
+ def update_cookies(self, cookies: Optional[LooseCookies]) -> None:
424
+ """Update request cookies header."""
425
+ if not cookies:
426
+ return
427
+
428
+ c: SimpleCookie[str] = SimpleCookie()
429
+ if hdrs.COOKIE in self.headers:
430
+ c.load(self.headers.get(hdrs.COOKIE, ""))
431
+ del self.headers[hdrs.COOKIE]
432
+
433
+ if isinstance(cookies, Mapping):
434
+ iter_cookies = cookies.items()
435
+ else:
436
+ iter_cookies = cookies # type: ignore[assignment]
437
+ for name, value in iter_cookies:
438
+ if isinstance(value, Morsel):
439
+ # Preserve coded_value
440
+ mrsl_val = value.get(value.key, Morsel())
441
+ mrsl_val.set(value.key, value.value, value.coded_value)
442
+ c[name] = mrsl_val
443
+ else:
444
+ c[name] = value # type: ignore[assignment]
445
+
446
+ self.headers[hdrs.COOKIE] = c.output(header="", sep=";").strip()
447
+
448
+ def update_content_encoding(self, data: Any) -> None:
449
+ """Set request content encoding."""
450
+ if data is None:
451
+ return
452
+
453
+ enc = self.headers.get(hdrs.CONTENT_ENCODING, "").lower()
454
+ if enc:
455
+ if self.compress:
456
+ raise ValueError(
457
+ "compress can not be set " "if Content-Encoding header is set"
458
+ )
459
+ elif self.compress:
460
+ if not isinstance(self.compress, str):
461
+ self.compress = "deflate"
462
+ self.headers[hdrs.CONTENT_ENCODING] = self.compress
463
+ self.chunked = True # enable chunked, no need to deal with length
464
+
465
+ def update_transfer_encoding(self) -> None:
466
+ """Analyze transfer-encoding header."""
467
+ te = self.headers.get(hdrs.TRANSFER_ENCODING, "").lower()
468
+
469
+ if "chunked" in te:
470
+ if self.chunked:
471
+ raise ValueError(
472
+ "chunked can not be set "
473
+ 'if "Transfer-Encoding: chunked" header is set'
474
+ )
475
+
476
+ elif self.chunked:
477
+ if hdrs.CONTENT_LENGTH in self.headers:
478
+ raise ValueError(
479
+ "chunked can not be set " "if Content-Length header is set"
480
+ )
481
+
482
+ self.headers[hdrs.TRANSFER_ENCODING] = "chunked"
483
+ else:
484
+ if hdrs.CONTENT_LENGTH not in self.headers:
485
+ self.headers[hdrs.CONTENT_LENGTH] = str(len(self.body))
486
+
487
+ def update_auth(self, auth: Optional[BasicAuth]) -> None:
488
+ """Set basic auth."""
489
+ if auth is None:
490
+ auth = self.auth
491
+ if auth is None:
492
+ return
493
+
494
+ if not isinstance(auth, helpers.BasicAuth):
495
+ raise TypeError("BasicAuth() tuple is required instead")
496
+
497
+ self.headers[hdrs.AUTHORIZATION] = auth.encode()
498
+
499
+ def update_body_from_data(self, body: Any) -> None:
500
+ if body is None:
501
+ return
502
+
503
+ # FormData
504
+ if isinstance(body, FormData):
505
+ body = body()
506
+
507
+ try:
508
+ body = payload.PAYLOAD_REGISTRY.get(body, disposition=None)
509
+ except payload.LookupError:
510
+ body = FormData(body)()
511
+
512
+ self.body = body
513
+
514
+ # enable chunked encoding if needed
515
+ if not self.chunked:
516
+ if hdrs.CONTENT_LENGTH not in self.headers:
517
+ size = body.size
518
+ if size is None:
519
+ self.chunked = True
520
+ else:
521
+ if hdrs.CONTENT_LENGTH not in self.headers:
522
+ self.headers[hdrs.CONTENT_LENGTH] = str(size)
523
+
524
+ # copy payload headers
525
+ assert body.headers
526
+ for (key, value) in body.headers.items():
527
+ if key in self.headers:
528
+ continue
529
+ if key in self.skip_auto_headers:
530
+ continue
531
+ self.headers[key] = value
532
+
533
+ def update_expect_continue(self, expect: bool = False) -> None:
534
+ if expect:
535
+ self.headers[hdrs.EXPECT] = "100-continue"
536
+ elif self.headers.get(hdrs.EXPECT, "").lower() == "100-continue":
537
+ expect = True
538
+
539
+ if expect:
540
+ self._continue = self.loop.create_future()
541
+
542
+ def update_proxy(
543
+ self,
544
+ proxy: Optional[URL],
545
+ proxy_auth: Optional[BasicAuth],
546
+ proxy_headers: Optional[LooseHeaders],
547
+ ) -> None:
548
+ if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth):
549
+ raise ValueError("proxy_auth must be None or BasicAuth() tuple")
550
+ self.proxy = proxy
551
+ self.proxy_auth = proxy_auth
552
+ self.proxy_headers = proxy_headers
553
+
554
+ def keep_alive(self) -> bool:
555
+ if self.version < HttpVersion10:
556
+ # keep alive not supported at all
557
+ return False
558
+ if self.version == HttpVersion10:
559
+ if self.headers.get(hdrs.CONNECTION) == "keep-alive":
560
+ return True
561
+ else: # no headers means we close for Http 1.0
562
+ return False
563
+ elif self.headers.get(hdrs.CONNECTION) == "close":
564
+ return False
565
+
566
+ return True
567
+
568
+ async def write_bytes(
569
+ self, writer: AbstractStreamWriter, conn: "Connection"
570
+ ) -> None:
571
+ """Support coroutines that yields bytes objects."""
572
+ # 100 response
573
+ if self._continue is not None:
574
+ await writer.drain()
575
+ await self._continue
576
+
577
+ protocol = conn.protocol
578
+ assert protocol is not None
579
+ try:
580
+ if isinstance(self.body, payload.Payload):
581
+ await self.body.write(writer)
582
+ else:
583
+ if isinstance(self.body, (bytes, bytearray)):
584
+ self.body = (self.body,) # type: ignore[assignment]
585
+
586
+ for chunk in self.body:
587
+ await writer.write(chunk) # type: ignore[arg-type]
588
+
589
+ await writer.write_eof()
590
+ except OSError as exc:
591
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
592
+ protocol.set_exception(exc)
593
+ else:
594
+ new_exc = ClientOSError(
595
+ exc.errno, "Can not write request body for %s" % self.url
596
+ )
597
+ new_exc.__context__ = exc
598
+ new_exc.__cause__ = exc
599
+ protocol.set_exception(new_exc)
600
+ except asyncio.CancelledError as exc:
601
+ if not conn.closed:
602
+ protocol.set_exception(exc)
603
+ except Exception as exc:
604
+ protocol.set_exception(exc)
605
+ finally:
606
+ self._writer = None
607
+
608
+ async def send(self, conn: "Connection") -> "ClientResponse":
609
+ # Specify request target:
610
+ # - CONNECT request must send authority form URI
611
+ # - not CONNECT proxy must send absolute form URI
612
+ # - most common is origin form URI
613
+ if self.method == hdrs.METH_CONNECT:
614
+ connect_host = self.url.raw_host
615
+ assert connect_host is not None
616
+ if helpers.is_ipv6_address(connect_host):
617
+ connect_host = f"[{connect_host}]"
618
+ path = f"{connect_host}:{self.url.port}"
619
+ elif self.proxy and not self.is_ssl():
620
+ path = str(self.url)
621
+ else:
622
+ path = self.url.raw_path
623
+ if self.url.raw_query_string:
624
+ path += "?" + self.url.raw_query_string
625
+
626
+ protocol = conn.protocol
627
+ assert protocol is not None
628
+ writer = StreamWriter(
629
+ protocol,
630
+ self.loop,
631
+ on_chunk_sent=functools.partial(
632
+ self._on_chunk_request_sent, self.method, self.url
633
+ ),
634
+ on_headers_sent=functools.partial(
635
+ self._on_headers_request_sent, self.method, self.url
636
+ ),
637
+ )
638
+
639
+ if self.compress:
640
+ writer.enable_compression(self.compress)
641
+
642
+ if self.chunked is not None:
643
+ writer.enable_chunking()
644
+
645
+ # set default content-type
646
+ if (
647
+ self.method in self.POST_METHODS
648
+ and hdrs.CONTENT_TYPE not in self.skip_auto_headers
649
+ and hdrs.CONTENT_TYPE not in self.headers
650
+ ):
651
+ self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream"
652
+
653
+ # set the connection header
654
+ connection = self.headers.get(hdrs.CONNECTION)
655
+ if not connection:
656
+ if self.keep_alive():
657
+ if self.version == HttpVersion10:
658
+ connection = "keep-alive"
659
+ else:
660
+ if self.version == HttpVersion11:
661
+ connection = "close"
662
+
663
+ if connection is not None:
664
+ self.headers[hdrs.CONNECTION] = connection
665
+
666
+ # status + headers
667
+ status_line = "{0} {1} HTTP/{2[0]}.{2[1]}".format(
668
+ self.method, path, self.version
669
+ )
670
+ await writer.write_headers(status_line, self.headers)
671
+
672
+ self._writer = self.loop.create_task(self.write_bytes(writer, conn))
673
+
674
+ response_class = self.response_class
675
+ assert response_class is not None
676
+ self.response = response_class(
677
+ self.method,
678
+ self.original_url,
679
+ writer=self._writer,
680
+ continue100=self._continue,
681
+ timer=self._timer,
682
+ request_info=self.request_info,
683
+ traces=self._traces,
684
+ loop=self.loop,
685
+ session=self._session,
686
+ )
687
+ return self.response
688
+
689
+ async def close(self) -> None:
690
+ if self._writer is not None:
691
+ try:
692
+ await self._writer
693
+ finally:
694
+ self._writer = None
695
+
696
+ def terminate(self) -> None:
697
+ if self._writer is not None:
698
+ if not self.loop.is_closed():
699
+ self._writer.cancel()
700
+ self._writer = None
701
+
702
+ async def _on_chunk_request_sent(self, method: str, url: URL, chunk: bytes) -> None:
703
+ for trace in self._traces:
704
+ await trace.send_request_chunk_sent(method, url, chunk)
705
+
706
+ async def _on_headers_request_sent(
707
+ self, method: str, url: URL, headers: "CIMultiDict[str]"
708
+ ) -> None:
709
+ for trace in self._traces:
710
+ await trace.send_request_headers(method, url, headers)
711
+
712
+
713
+ class ClientResponse(HeadersMixin):
714
+
715
+ # from the Status-Line of the response
716
+ version = None # HTTP-Version
717
+ status: int = None # type: ignore[assignment] # Status-Code
718
+ reason = None # Reason-Phrase
719
+
720
+ content: StreamReader = None # type: ignore[assignment] # Payload stream
721
+ _headers: "CIMultiDictProxy[str]" = None # type: ignore[assignment]
722
+ _raw_headers: RawHeaders = None # type: ignore[assignment] # Response raw headers
723
+
724
+ _connection = None # current connection
725
+ _source_traceback = None
726
+ # setted up by ClientRequest after ClientResponse object creation
727
+ # post-init stage allows to not change ctor signature
728
+ _closed = True # to allow __del__ for non-initialized properly response
729
+ _released = False
730
+
731
+ def __init__(
732
+ self,
733
+ method: str,
734
+ url: URL,
735
+ *,
736
+ writer: "asyncio.Task[None]",
737
+ continue100: Optional["asyncio.Future[bool]"],
738
+ timer: BaseTimerContext,
739
+ request_info: RequestInfo,
740
+ traces: List["Trace"],
741
+ loop: asyncio.AbstractEventLoop,
742
+ session: "ClientSession",
743
+ ) -> None:
744
+ assert isinstance(url, URL)
745
+
746
+ self.method = method
747
+ self.cookies: SimpleCookie[str] = SimpleCookie()
748
+
749
+ self._real_url = url
750
+ self._url = url.with_fragment(None)
751
+ self._body: Any = None
752
+ self._writer: Optional[asyncio.Task[None]] = writer
753
+ self._continue = continue100 # None by default
754
+ self._closed = True
755
+ self._history: Tuple[ClientResponse, ...] = ()
756
+ self._request_info = request_info
757
+ self._timer = timer if timer is not None else TimerNoop()
758
+ self._cache: Dict[str, Any] = {}
759
+ self._traces = traces
760
+ self._loop = loop
761
+ # store a reference to session #1985
762
+ self._session: Optional[ClientSession] = session
763
+ if loop.get_debug():
764
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
765
+
766
+ @reify
767
+ def url(self) -> URL:
768
+ return self._url
769
+
770
+ @reify
771
+ def url_obj(self) -> URL:
772
+ warnings.warn("Deprecated, use .url #1654", DeprecationWarning, stacklevel=2)
773
+ return self._url
774
+
775
+ @reify
776
+ def real_url(self) -> URL:
777
+ return self._real_url
778
+
779
+ @reify
780
+ def host(self) -> str:
781
+ assert self._url.host is not None
782
+ return self._url.host
783
+
784
+ @reify
785
+ def headers(self) -> "CIMultiDictProxy[str]":
786
+ return self._headers
787
+
788
+ @reify
789
+ def raw_headers(self) -> RawHeaders:
790
+ return self._raw_headers
791
+
792
+ @reify
793
+ def request_info(self) -> RequestInfo:
794
+ return self._request_info
795
+
796
+ @reify
797
+ def content_disposition(self) -> Optional[ContentDisposition]:
798
+ raw = self._headers.get(hdrs.CONTENT_DISPOSITION)
799
+ if raw is None:
800
+ return None
801
+ disposition_type, params_dct = multipart.parse_content_disposition(raw)
802
+ params = MappingProxyType(params_dct)
803
+ filename = multipart.content_disposition_filename(params)
804
+ return ContentDisposition(disposition_type, params, filename)
805
+
806
+ def __del__(self, _warnings: Any = warnings) -> None:
807
+ if self._closed:
808
+ return
809
+
810
+ if self._connection is not None:
811
+ self._connection.release()
812
+ self._cleanup_writer()
813
+
814
+ if self._loop.get_debug():
815
+ if PY_36:
816
+ kwargs = {"source": self}
817
+ else:
818
+ kwargs = {}
819
+ _warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs)
820
+ context = {"client_response": self, "message": "Unclosed response"}
821
+ if self._source_traceback:
822
+ context["source_traceback"] = self._source_traceback
823
+ self._loop.call_exception_handler(context)
824
+
825
+ def __repr__(self) -> str:
826
+ out = io.StringIO()
827
+ ascii_encodable_url = str(self.url)
828
+ if self.reason:
829
+ ascii_encodable_reason = self.reason.encode(
830
+ "ascii", "backslashreplace"
831
+ ).decode("ascii")
832
+ else:
833
+ ascii_encodable_reason = self.reason
834
+ print(
835
+ "<ClientResponse({}) [{} {}]>".format(
836
+ ascii_encodable_url, self.status, ascii_encodable_reason
837
+ ),
838
+ file=out,
839
+ )
840
+ print(self.headers, file=out)
841
+ return out.getvalue()
842
+
843
+ @property
844
+ def connection(self) -> Optional["Connection"]:
845
+ return self._connection
846
+
847
+ @reify
848
+ def history(self) -> Tuple["ClientResponse", ...]:
849
+ """A sequence of of responses, if redirects occurred."""
850
+ return self._history
851
+
852
+ @reify
853
+ def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]":
854
+ links_str = ", ".join(self.headers.getall("link", []))
855
+
856
+ if not links_str:
857
+ return MultiDictProxy(MultiDict())
858
+
859
+ links: MultiDict[MultiDictProxy[Union[str, URL]]] = MultiDict()
860
+
861
+ for val in re.split(r",(?=\s*<)", links_str):
862
+ match = re.match(r"\s*<(.*)>(.*)", val)
863
+ if match is None: # pragma: no cover
864
+ # the check exists to suppress mypy error
865
+ continue
866
+ url, params_str = match.groups()
867
+ params = params_str.split(";")[1:]
868
+
869
+ link: MultiDict[Union[str, URL]] = MultiDict()
870
+
871
+ for param in params:
872
+ match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M)
873
+ if match is None: # pragma: no cover
874
+ # the check exists to suppress mypy error
875
+ continue
876
+ key, _, value, _ = match.groups()
877
+
878
+ link.add(key, value)
879
+
880
+ key = link.get("rel", url) # type: ignore[assignment]
881
+
882
+ link.add("url", self.url.join(URL(url)))
883
+
884
+ links.add(key, MultiDictProxy(link))
885
+
886
+ return MultiDictProxy(links)
887
+
888
+ async def start(self, connection: "Connection") -> "ClientResponse":
889
+ """Start response processing."""
890
+ self._closed = False
891
+ self._protocol = connection.protocol
892
+ self._connection = connection
893
+
894
+ with self._timer:
895
+ while True:
896
+ # read response
897
+ try:
898
+ protocol = self._protocol
899
+ message, payload = await protocol.read() # type: ignore[union-attr]
900
+ except http.HttpProcessingError as exc:
901
+ raise ClientResponseError(
902
+ self.request_info,
903
+ self.history,
904
+ status=exc.code,
905
+ message=exc.message,
906
+ headers=exc.headers,
907
+ ) from exc
908
+
909
+ if message.code < 100 or message.code > 199 or message.code == 101:
910
+ break
911
+
912
+ if self._continue is not None:
913
+ set_result(self._continue, True)
914
+ self._continue = None
915
+
916
+ # payload eof handler
917
+ payload.on_eof(self._response_eof)
918
+
919
+ # response status
920
+ self.version = message.version
921
+ self.status = message.code
922
+ self.reason = message.reason
923
+
924
+ # headers
925
+ self._headers = message.headers # type is CIMultiDictProxy
926
+ self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes]
927
+
928
+ # payload
929
+ self.content = payload
930
+
931
+ # cookies
932
+ for hdr in self.headers.getall(hdrs.SET_COOKIE, ()):
933
+ try:
934
+ self.cookies.load(hdr)
935
+ except CookieError as exc:
936
+ client_logger.warning("Can not load response cookies: %s", exc)
937
+ return self
938
+
939
+ def _response_eof(self) -> None:
940
+ if self._closed:
941
+ return
942
+
943
+ if self._connection is not None:
944
+ # websocket, protocol could be None because
945
+ # connection could be detached
946
+ if (
947
+ self._connection.protocol is not None
948
+ and self._connection.protocol.upgraded
949
+ ):
950
+ return
951
+
952
+ self._connection.release()
953
+ self._connection = None
954
+
955
+ self._closed = True
956
+ self._cleanup_writer()
957
+
958
+ @property
959
+ def closed(self) -> bool:
960
+ return self._closed
961
+
962
+ def close(self) -> None:
963
+ if not self._released:
964
+ self._notify_content()
965
+ if self._closed:
966
+ return
967
+
968
+ self._closed = True
969
+ if self._loop is None or self._loop.is_closed():
970
+ return
971
+
972
+ if self._connection is not None:
973
+ self._connection.close()
974
+ self._connection = None
975
+ self._cleanup_writer()
976
+
977
+ def release(self) -> Any:
978
+ if not self._released:
979
+ self._notify_content()
980
+ if self._closed:
981
+ return noop()
982
+
983
+ self._closed = True
984
+ if self._connection is not None:
985
+ self._connection.release()
986
+ self._connection = None
987
+
988
+ self._cleanup_writer()
989
+ return noop()
990
+
991
+ @property
992
+ def ok(self) -> bool:
993
+ """Returns ``True`` if ``status`` is less than ``400``, ``False`` if not.
994
+
995
+ This is **not** a check for ``200 OK`` but a check that the response
996
+ status is under 400.
997
+ """
998
+ return 400 > self.status
999
+
1000
+ def raise_for_status(self) -> None:
1001
+ if not self.ok:
1002
+ # reason should always be not None for a started response
1003
+ assert self.reason is not None
1004
+ self.release()
1005
+ raise ClientResponseError(
1006
+ self.request_info,
1007
+ self.history,
1008
+ status=self.status,
1009
+ message=self.reason,
1010
+ headers=self.headers,
1011
+ )
1012
+
1013
+ def _cleanup_writer(self) -> None:
1014
+ if self._writer is not None:
1015
+ self._writer.cancel()
1016
+ self._writer = None
1017
+ self._session = None
1018
+
1019
+ def _notify_content(self) -> None:
1020
+ content = self.content
1021
+ if content and content.exception() is None:
1022
+ content.set_exception(ClientConnectionError("Connection closed"))
1023
+ self._released = True
1024
+
1025
+ async def wait_for_close(self) -> None:
1026
+ if self._writer is not None:
1027
+ try:
1028
+ await self._writer
1029
+ finally:
1030
+ self._writer = None
1031
+ self.release()
1032
+
1033
+ async def read(self) -> bytes:
1034
+ """Read response payload."""
1035
+ if self._body is None:
1036
+ try:
1037
+ self._body = await self.content.read()
1038
+ for trace in self._traces:
1039
+ await trace.send_response_chunk_received(
1040
+ self.method, self.url, self._body
1041
+ )
1042
+ except BaseException:
1043
+ self.close()
1044
+ raise
1045
+ elif self._released:
1046
+ raise ClientConnectionError("Connection closed")
1047
+
1048
+ return self._body # type: ignore[no-any-return]
1049
+
1050
+ def get_encoding(self) -> str:
1051
+ ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower()
1052
+ mimetype = helpers.parse_mimetype(ctype)
1053
+
1054
+ encoding = mimetype.parameters.get("charset")
1055
+ if encoding:
1056
+ try:
1057
+ codecs.lookup(encoding)
1058
+ except LookupError:
1059
+ encoding = None
1060
+ if not encoding:
1061
+ if mimetype.type == "application" and (
1062
+ mimetype.subtype == "json" or mimetype.subtype == "rdap"
1063
+ ):
1064
+ # RFC 7159 states that the default encoding is UTF-8.
1065
+ # RFC 7483 defines application/rdap+json
1066
+ encoding = "utf-8"
1067
+ elif self._body is None:
1068
+ raise RuntimeError(
1069
+ "Cannot guess the encoding of " "a not yet read body"
1070
+ )
1071
+ else:
1072
+ encoding = chardet.detect(self._body)["encoding"]
1073
+ if not encoding:
1074
+ encoding = "utf-8"
1075
+
1076
+ return encoding
1077
+
1078
+ async def text(self, encoding: Optional[str] = None, errors: str = "strict") -> str:
1079
+ """Read response payload and decode."""
1080
+ if self._body is None:
1081
+ await self.read()
1082
+
1083
+ if encoding is None:
1084
+ encoding = self.get_encoding()
1085
+
1086
+ return self._body.decode( # type: ignore[no-any-return,union-attr]
1087
+ encoding, errors=errors
1088
+ )
1089
+
1090
+ async def json(
1091
+ self,
1092
+ *,
1093
+ encoding: Optional[str] = None,
1094
+ loads: JSONDecoder = DEFAULT_JSON_DECODER,
1095
+ content_type: Optional[str] = "application/json",
1096
+ ) -> Any:
1097
+ """Read and decodes JSON response."""
1098
+ if self._body is None:
1099
+ await self.read()
1100
+
1101
+ if content_type:
1102
+ ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower()
1103
+ if not _is_expected_content_type(ctype, content_type):
1104
+ raise ContentTypeError(
1105
+ self.request_info,
1106
+ self.history,
1107
+ message=(
1108
+ "Attempt to decode JSON with " "unexpected mimetype: %s" % ctype
1109
+ ),
1110
+ headers=self.headers,
1111
+ )
1112
+
1113
+ stripped = self._body.strip() # type: ignore[union-attr]
1114
+ if not stripped:
1115
+ return None
1116
+
1117
+ if encoding is None:
1118
+ encoding = self.get_encoding()
1119
+
1120
+ return loads(stripped.decode(encoding))
1121
+
1122
+ async def __aenter__(self) -> "ClientResponse":
1123
+ return self
1124
+
1125
+ async def __aexit__(
1126
+ self,
1127
+ exc_type: Optional[Type[BaseException]],
1128
+ exc_val: Optional[BaseException],
1129
+ exc_tb: Optional[TracebackType],
1130
+ ) -> None:
1131
+ # similar to _RequestContextManager, we do not need to check
1132
+ # for exceptions, response object can close connection
1133
+ # if state is broken
1134
+ self.release()
runtime/Lib/site-packages/aiohttp/client_ws.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebSocket client for asyncio."""
2
+
3
+ import asyncio
4
+ from typing import Any, Optional, cast
5
+
6
+ import async_timeout
7
+
8
+ from .client_exceptions import ClientError
9
+ from .client_reqrep import ClientResponse
10
+ from .helpers import call_later, set_result
11
+ from .http import (
12
+ WS_CLOSED_MESSAGE,
13
+ WS_CLOSING_MESSAGE,
14
+ WebSocketError,
15
+ WSCloseCode,
16
+ WSMessage,
17
+ WSMsgType,
18
+ )
19
+ from .http_websocket import WebSocketWriter # WSMessage
20
+ from .streams import EofStream, FlowControlDataQueue
21
+ from .typedefs import (
22
+ DEFAULT_JSON_DECODER,
23
+ DEFAULT_JSON_ENCODER,
24
+ JSONDecoder,
25
+ JSONEncoder,
26
+ )
27
+
28
+
29
+ class ClientWebSocketResponse:
30
+ def __init__(
31
+ self,
32
+ reader: "FlowControlDataQueue[WSMessage]",
33
+ writer: WebSocketWriter,
34
+ protocol: Optional[str],
35
+ response: ClientResponse,
36
+ timeout: float,
37
+ autoclose: bool,
38
+ autoping: bool,
39
+ loop: asyncio.AbstractEventLoop,
40
+ *,
41
+ receive_timeout: Optional[float] = None,
42
+ heartbeat: Optional[float] = None,
43
+ compress: int = 0,
44
+ client_notakeover: bool = False,
45
+ ) -> None:
46
+ self._response = response
47
+ self._conn = response.connection
48
+
49
+ self._writer = writer
50
+ self._reader = reader
51
+ self._protocol = protocol
52
+ self._closed = False
53
+ self._closing = False
54
+ self._close_code: Optional[int] = None
55
+ self._timeout = timeout
56
+ self._receive_timeout = receive_timeout
57
+ self._autoclose = autoclose
58
+ self._autoping = autoping
59
+ self._heartbeat = heartbeat
60
+ self._heartbeat_cb: Optional[asyncio.TimerHandle] = None
61
+ if heartbeat is not None:
62
+ self._pong_heartbeat = heartbeat / 2.0
63
+ self._pong_response_cb: Optional[asyncio.TimerHandle] = None
64
+ self._loop = loop
65
+ self._waiting: Optional[asyncio.Future[bool]] = None
66
+ self._exception: Optional[BaseException] = None
67
+ self._compress = compress
68
+ self._client_notakeover = client_notakeover
69
+
70
+ self._reset_heartbeat()
71
+
72
+ def _cancel_heartbeat(self) -> None:
73
+ if self._pong_response_cb is not None:
74
+ self._pong_response_cb.cancel()
75
+ self._pong_response_cb = None
76
+
77
+ if self._heartbeat_cb is not None:
78
+ self._heartbeat_cb.cancel()
79
+ self._heartbeat_cb = None
80
+
81
+ def _reset_heartbeat(self) -> None:
82
+ self._cancel_heartbeat()
83
+
84
+ if self._heartbeat is not None:
85
+ self._heartbeat_cb = call_later(
86
+ self._send_heartbeat, self._heartbeat, self._loop
87
+ )
88
+
89
+ def _send_heartbeat(self) -> None:
90
+ if self._heartbeat is not None and not self._closed:
91
+ # fire-and-forget a task is not perfect but maybe ok for
92
+ # sending ping. Otherwise we need a long-living heartbeat
93
+ # task in the class.
94
+ self._loop.create_task(self._writer.ping())
95
+
96
+ if self._pong_response_cb is not None:
97
+ self._pong_response_cb.cancel()
98
+ self._pong_response_cb = call_later(
99
+ self._pong_not_received, self._pong_heartbeat, self._loop
100
+ )
101
+
102
+ def _pong_not_received(self) -> None:
103
+ if not self._closed:
104
+ self._closed = True
105
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
106
+ self._exception = asyncio.TimeoutError()
107
+ self._response.close()
108
+
109
+ @property
110
+ def closed(self) -> bool:
111
+ return self._closed
112
+
113
+ @property
114
+ def close_code(self) -> Optional[int]:
115
+ return self._close_code
116
+
117
+ @property
118
+ def protocol(self) -> Optional[str]:
119
+ return self._protocol
120
+
121
+ @property
122
+ def compress(self) -> int:
123
+ return self._compress
124
+
125
+ @property
126
+ def client_notakeover(self) -> bool:
127
+ return self._client_notakeover
128
+
129
+ def get_extra_info(self, name: str, default: Any = None) -> Any:
130
+ """extra info from connection transport"""
131
+ conn = self._response.connection
132
+ if conn is None:
133
+ return default
134
+ transport = conn.transport
135
+ if transport is None:
136
+ return default
137
+ return transport.get_extra_info(name, default)
138
+
139
+ def exception(self) -> Optional[BaseException]:
140
+ return self._exception
141
+
142
+ async def ping(self, message: bytes = b"") -> None:
143
+ await self._writer.ping(message)
144
+
145
+ async def pong(self, message: bytes = b"") -> None:
146
+ await self._writer.pong(message)
147
+
148
+ async def send_str(self, data: str, compress: Optional[int] = None) -> None:
149
+ if not isinstance(data, str):
150
+ raise TypeError("data argument must be str (%r)" % type(data))
151
+ await self._writer.send(data, binary=False, compress=compress)
152
+
153
+ async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None:
154
+ if not isinstance(data, (bytes, bytearray, memoryview)):
155
+ raise TypeError("data argument must be byte-ish (%r)" % type(data))
156
+ await self._writer.send(data, binary=True, compress=compress)
157
+
158
+ async def send_json(
159
+ self,
160
+ data: Any,
161
+ compress: Optional[int] = None,
162
+ *,
163
+ dumps: JSONEncoder = DEFAULT_JSON_ENCODER,
164
+ ) -> None:
165
+ await self.send_str(dumps(data), compress=compress)
166
+
167
+ async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bool:
168
+ # we need to break `receive()` cycle first,
169
+ # `close()` may be called from different task
170
+ if self._waiting is not None and not self._closed:
171
+ self._reader.feed_data(WS_CLOSING_MESSAGE, 0)
172
+ await self._waiting
173
+
174
+ if not self._closed:
175
+ self._cancel_heartbeat()
176
+ self._closed = True
177
+ try:
178
+ await self._writer.close(code, message)
179
+ except asyncio.CancelledError:
180
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
181
+ self._response.close()
182
+ raise
183
+ except Exception as exc:
184
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
185
+ self._exception = exc
186
+ self._response.close()
187
+ return True
188
+
189
+ if self._closing:
190
+ self._response.close()
191
+ return True
192
+
193
+ while True:
194
+ try:
195
+ async with async_timeout.timeout(self._timeout):
196
+ msg = await self._reader.read()
197
+ except asyncio.CancelledError:
198
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
199
+ self._response.close()
200
+ raise
201
+ except Exception as exc:
202
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
203
+ self._exception = exc
204
+ self._response.close()
205
+ return True
206
+
207
+ if msg.type == WSMsgType.CLOSE:
208
+ self._close_code = msg.data
209
+ self._response.close()
210
+ return True
211
+ else:
212
+ return False
213
+
214
+ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
215
+ while True:
216
+ if self._waiting is not None:
217
+ raise RuntimeError("Concurrent call to receive() is not allowed")
218
+
219
+ if self._closed:
220
+ return WS_CLOSED_MESSAGE
221
+ elif self._closing:
222
+ await self.close()
223
+ return WS_CLOSED_MESSAGE
224
+
225
+ try:
226
+ self._waiting = self._loop.create_future()
227
+ try:
228
+ async with async_timeout.timeout(timeout or self._receive_timeout):
229
+ msg = await self._reader.read()
230
+ self._reset_heartbeat()
231
+ finally:
232
+ waiter = self._waiting
233
+ self._waiting = None
234
+ set_result(waiter, True)
235
+ except (asyncio.CancelledError, asyncio.TimeoutError):
236
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
237
+ raise
238
+ except EofStream:
239
+ self._close_code = WSCloseCode.OK
240
+ await self.close()
241
+ return WSMessage(WSMsgType.CLOSED, None, None)
242
+ except ClientError:
243
+ self._closed = True
244
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
245
+ return WS_CLOSED_MESSAGE
246
+ except WebSocketError as exc:
247
+ self._close_code = exc.code
248
+ await self.close(code=exc.code)
249
+ return WSMessage(WSMsgType.ERROR, exc, None)
250
+ except Exception as exc:
251
+ self._exception = exc
252
+ self._closing = True
253
+ self._close_code = WSCloseCode.ABNORMAL_CLOSURE
254
+ await self.close()
255
+ return WSMessage(WSMsgType.ERROR, exc, None)
256
+
257
+ if msg.type == WSMsgType.CLOSE:
258
+ self._closing = True
259
+ self._close_code = msg.data
260
+ if not self._closed and self._autoclose:
261
+ await self.close()
262
+ elif msg.type == WSMsgType.CLOSING:
263
+ self._closing = True
264
+ elif msg.type == WSMsgType.PING and self._autoping:
265
+ await self.pong(msg.data)
266
+ continue
267
+ elif msg.type == WSMsgType.PONG and self._autoping:
268
+ continue
269
+
270
+ return msg
271
+
272
+ async def receive_str(self, *, timeout: Optional[float] = None) -> str:
273
+ msg = await self.receive(timeout)
274
+ if msg.type != WSMsgType.TEXT:
275
+ raise TypeError(f"Received message {msg.type}:{msg.data!r} is not str")
276
+ return cast(str, msg.data)
277
+
278
+ async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes:
279
+ msg = await self.receive(timeout)
280
+ if msg.type != WSMsgType.BINARY:
281
+ raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes")
282
+ return cast(bytes, msg.data)
283
+
284
+ async def receive_json(
285
+ self,
286
+ *,
287
+ loads: JSONDecoder = DEFAULT_JSON_DECODER,
288
+ timeout: Optional[float] = None,
289
+ ) -> Any:
290
+ data = await self.receive_str(timeout=timeout)
291
+ return loads(data)
292
+
293
+ def __aiter__(self) -> "ClientWebSocketResponse":
294
+ return self
295
+
296
+ async def __anext__(self) -> WSMessage:
297
+ msg = await self.receive()
298
+ if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
299
+ raise StopAsyncIteration
300
+ return msg
runtime/Lib/site-packages/aiohttp/connector.py ADDED
@@ -0,0 +1,1453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import functools
3
+ import random
4
+ import sys
5
+ import traceback
6
+ import warnings
7
+ from collections import defaultdict, deque
8
+ from contextlib import suppress
9
+ from http.cookies import SimpleCookie
10
+ from itertools import cycle, islice
11
+ from time import monotonic
12
+ from types import TracebackType
13
+ from typing import (
14
+ TYPE_CHECKING,
15
+ Any,
16
+ Awaitable,
17
+ Callable,
18
+ DefaultDict,
19
+ Dict,
20
+ Iterator,
21
+ List,
22
+ Optional,
23
+ Set,
24
+ Tuple,
25
+ Type,
26
+ Union,
27
+ cast,
28
+ )
29
+
30
+ import attr
31
+
32
+ from . import hdrs, helpers
33
+ from .abc import AbstractResolver
34
+ from .client_exceptions import (
35
+ ClientConnectionError,
36
+ ClientConnectorCertificateError,
37
+ ClientConnectorError,
38
+ ClientConnectorSSLError,
39
+ ClientHttpProxyError,
40
+ ClientProxyConnectionError,
41
+ ServerFingerprintMismatch,
42
+ UnixClientConnectorError,
43
+ cert_errors,
44
+ ssl_errors,
45
+ )
46
+ from .client_proto import ResponseHandler
47
+ from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params
48
+ from .helpers import (
49
+ PY_36,
50
+ ceil_timeout,
51
+ get_running_loop,
52
+ is_ip_address,
53
+ noop,
54
+ sentinel,
55
+ )
56
+ from .http import RESPONSES
57
+ from .locks import EventResultOrError
58
+ from .resolver import DefaultResolver
59
+
60
+ try:
61
+ import ssl
62
+
63
+ SSLContext = ssl.SSLContext
64
+ except ImportError: # pragma: no cover
65
+ ssl = None # type: ignore[assignment]
66
+ SSLContext = object # type: ignore[misc,assignment]
67
+
68
+
69
+ __all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector")
70
+
71
+
72
+ if TYPE_CHECKING: # pragma: no cover
73
+ from .client import ClientTimeout
74
+ from .client_reqrep import ConnectionKey
75
+ from .tracing import Trace
76
+
77
+
78
+ class _DeprecationWaiter:
79
+ __slots__ = ("_awaitable", "_awaited")
80
+
81
+ def __init__(self, awaitable: Awaitable[Any]) -> None:
82
+ self._awaitable = awaitable
83
+ self._awaited = False
84
+
85
+ def __await__(self) -> Any:
86
+ self._awaited = True
87
+ return self._awaitable.__await__()
88
+
89
+ def __del__(self) -> None:
90
+ if not self._awaited:
91
+ warnings.warn(
92
+ "Connector.close() is a coroutine, "
93
+ "please use await connector.close()",
94
+ DeprecationWarning,
95
+ )
96
+
97
+
98
+ class Connection:
99
+
100
+ _source_traceback = None
101
+ _transport = None
102
+
103
+ def __init__(
104
+ self,
105
+ connector: "BaseConnector",
106
+ key: "ConnectionKey",
107
+ protocol: ResponseHandler,
108
+ loop: asyncio.AbstractEventLoop,
109
+ ) -> None:
110
+ self._key = key
111
+ self._connector = connector
112
+ self._loop = loop
113
+ self._protocol: Optional[ResponseHandler] = protocol
114
+ self._callbacks: List[Callable[[], None]] = []
115
+
116
+ if loop.get_debug():
117
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
118
+
119
+ def __repr__(self) -> str:
120
+ return f"Connection<{self._key}>"
121
+
122
+ def __del__(self, _warnings: Any = warnings) -> None:
123
+ if self._protocol is not None:
124
+ if PY_36:
125
+ kwargs = {"source": self}
126
+ else:
127
+ kwargs = {}
128
+ _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs)
129
+ if self._loop.is_closed():
130
+ return
131
+
132
+ self._connector._release(self._key, self._protocol, should_close=True)
133
+
134
+ context = {"client_connection": self, "message": "Unclosed connection"}
135
+ if self._source_traceback is not None:
136
+ context["source_traceback"] = self._source_traceback
137
+ self._loop.call_exception_handler(context)
138
+
139
+ @property
140
+ def loop(self) -> asyncio.AbstractEventLoop:
141
+ warnings.warn(
142
+ "connector.loop property is deprecated", DeprecationWarning, stacklevel=2
143
+ )
144
+ return self._loop
145
+
146
+ @property
147
+ def transport(self) -> Optional[asyncio.Transport]:
148
+ if self._protocol is None:
149
+ return None
150
+ return self._protocol.transport
151
+
152
+ @property
153
+ def protocol(self) -> Optional[ResponseHandler]:
154
+ return self._protocol
155
+
156
+ def add_callback(self, callback: Callable[[], None]) -> None:
157
+ if callback is not None:
158
+ self._callbacks.append(callback)
159
+
160
+ def _notify_release(self) -> None:
161
+ callbacks, self._callbacks = self._callbacks[:], []
162
+
163
+ for cb in callbacks:
164
+ with suppress(Exception):
165
+ cb()
166
+
167
+ def close(self) -> None:
168
+ self._notify_release()
169
+
170
+ if self._protocol is not None:
171
+ self._connector._release(self._key, self._protocol, should_close=True)
172
+ self._protocol = None
173
+
174
+ def release(self) -> None:
175
+ self._notify_release()
176
+
177
+ if self._protocol is not None:
178
+ self._connector._release(
179
+ self._key, self._protocol, should_close=self._protocol.should_close
180
+ )
181
+ self._protocol = None
182
+
183
+ @property
184
+ def closed(self) -> bool:
185
+ return self._protocol is None or not self._protocol.is_connected()
186
+
187
+
188
+ class _TransportPlaceholder:
189
+ """placeholder for BaseConnector.connect function"""
190
+
191
+ def close(self) -> None:
192
+ pass
193
+
194
+
195
+ class BaseConnector:
196
+ """Base connector class.
197
+
198
+ keepalive_timeout - (optional) Keep-alive timeout.
199
+ force_close - Set to True to force close and do reconnect
200
+ after each request (and between redirects).
201
+ limit - The total number of simultaneous connections.
202
+ limit_per_host - Number of simultaneous connections to one host.
203
+ enable_cleanup_closed - Enables clean-up closed ssl transports.
204
+ Disabled by default.
205
+ loop - Optional event loop.
206
+ """
207
+
208
+ _closed = True # prevent AttributeError in __del__ if ctor was failed
209
+ _source_traceback = None
210
+
211
+ # abort transport after 2 seconds (cleanup broken connections)
212
+ _cleanup_closed_period = 2.0
213
+
214
+ def __init__(
215
+ self,
216
+ *,
217
+ keepalive_timeout: Union[object, None, float] = sentinel,
218
+ force_close: bool = False,
219
+ limit: int = 100,
220
+ limit_per_host: int = 0,
221
+ enable_cleanup_closed: bool = False,
222
+ loop: Optional[asyncio.AbstractEventLoop] = None,
223
+ ) -> None:
224
+
225
+ if force_close:
226
+ if keepalive_timeout is not None and keepalive_timeout is not sentinel:
227
+ raise ValueError(
228
+ "keepalive_timeout cannot " "be set if force_close is True"
229
+ )
230
+ else:
231
+ if keepalive_timeout is sentinel:
232
+ keepalive_timeout = 15.0
233
+
234
+ loop = get_running_loop(loop)
235
+
236
+ self._closed = False
237
+ if loop.get_debug():
238
+ self._source_traceback = traceback.extract_stack(sys._getframe(1))
239
+
240
+ self._conns: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] = {}
241
+ self._limit = limit
242
+ self._limit_per_host = limit_per_host
243
+ self._acquired: Set[ResponseHandler] = set()
244
+ self._acquired_per_host: DefaultDict[
245
+ ConnectionKey, Set[ResponseHandler]
246
+ ] = defaultdict(set)
247
+ self._keepalive_timeout = cast(float, keepalive_timeout)
248
+ self._force_close = force_close
249
+
250
+ # {host_key: FIFO list of waiters}
251
+ self._waiters = defaultdict(deque) # type: ignore[var-annotated]
252
+
253
+ self._loop = loop
254
+ self._factory = functools.partial(ResponseHandler, loop=loop)
255
+
256
+ self.cookies: SimpleCookie[str] = SimpleCookie()
257
+
258
+ # start keep-alive connection cleanup task
259
+ self._cleanup_handle: Optional[asyncio.TimerHandle] = None
260
+
261
+ # start cleanup closed transports task
262
+ self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None
263
+ self._cleanup_closed_disabled = not enable_cleanup_closed
264
+ self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = []
265
+ self._cleanup_closed()
266
+
267
+ def __del__(self, _warnings: Any = warnings) -> None:
268
+ if self._closed:
269
+ return
270
+ if not self._conns:
271
+ return
272
+
273
+ conns = [repr(c) for c in self._conns.values()]
274
+
275
+ self._close()
276
+
277
+ if PY_36:
278
+ kwargs = {"source": self}
279
+ else:
280
+ kwargs = {}
281
+ _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs)
282
+ context = {
283
+ "connector": self,
284
+ "connections": conns,
285
+ "message": "Unclosed connector",
286
+ }
287
+ if self._source_traceback is not None:
288
+ context["source_traceback"] = self._source_traceback
289
+ self._loop.call_exception_handler(context)
290
+
291
+ def __enter__(self) -> "BaseConnector":
292
+ warnings.warn(
293
+ '"with Connector():" is deprecated, '
294
+ 'use "async with Connector():" instead',
295
+ DeprecationWarning,
296
+ )
297
+ return self
298
+
299
+ def __exit__(self, *exc: Any) -> None:
300
+ self._close()
301
+
302
+ async def __aenter__(self) -> "BaseConnector":
303
+ return self
304
+
305
+ async def __aexit__(
306
+ self,
307
+ exc_type: Optional[Type[BaseException]] = None,
308
+ exc_value: Optional[BaseException] = None,
309
+ exc_traceback: Optional[TracebackType] = None,
310
+ ) -> None:
311
+ await self.close()
312
+
313
+ @property
314
+ def force_close(self) -> bool:
315
+ """Ultimately close connection on releasing if True."""
316
+ return self._force_close
317
+
318
+ @property
319
+ def limit(self) -> int:
320
+ """The total number for simultaneous connections.
321
+
322
+ If limit is 0 the connector has no limit.
323
+ The default limit size is 100.
324
+ """
325
+ return self._limit
326
+
327
+ @property
328
+ def limit_per_host(self) -> int:
329
+ """The limit for simultaneous connections to the same endpoint.
330
+
331
+ Endpoints are the same if they are have equal
332
+ (host, port, is_ssl) triple.
333
+ """
334
+ return self._limit_per_host
335
+
336
+ def _cleanup(self) -> None:
337
+ """Cleanup unused transports."""
338
+ if self._cleanup_handle:
339
+ self._cleanup_handle.cancel()
340
+ # _cleanup_handle should be unset, otherwise _release() will not
341
+ # recreate it ever!
342
+ self._cleanup_handle = None
343
+
344
+ now = self._loop.time()
345
+ timeout = self._keepalive_timeout
346
+
347
+ if self._conns:
348
+ connections = {}
349
+ deadline = now - timeout
350
+ for key, conns in self._conns.items():
351
+ alive = []
352
+ for proto, use_time in conns:
353
+ if proto.is_connected():
354
+ if use_time - deadline < 0:
355
+ transport = proto.transport
356
+ proto.close()
357
+ if key.is_ssl and not self._cleanup_closed_disabled:
358
+ self._cleanup_closed_transports.append(transport)
359
+ else:
360
+ alive.append((proto, use_time))
361
+ else:
362
+ transport = proto.transport
363
+ proto.close()
364
+ if key.is_ssl and not self._cleanup_closed_disabled:
365
+ self._cleanup_closed_transports.append(transport)
366
+
367
+ if alive:
368
+ connections[key] = alive
369
+
370
+ self._conns = connections
371
+
372
+ if self._conns:
373
+ self._cleanup_handle = helpers.weakref_handle(
374
+ self, "_cleanup", timeout, self._loop
375
+ )
376
+
377
+ def _drop_acquired_per_host(
378
+ self, key: "ConnectionKey", val: ResponseHandler
379
+ ) -> None:
380
+ acquired_per_host = self._acquired_per_host
381
+ if key not in acquired_per_host:
382
+ return
383
+ conns = acquired_per_host[key]
384
+ conns.remove(val)
385
+ if not conns:
386
+ del self._acquired_per_host[key]
387
+
388
+ def _cleanup_closed(self) -> None:
389
+ """Double confirmation for transport close.
390
+
391
+ Some broken ssl servers may leave socket open without proper close.
392
+ """
393
+ if self._cleanup_closed_handle:
394
+ self._cleanup_closed_handle.cancel()
395
+
396
+ for transport in self._cleanup_closed_transports:
397
+ if transport is not None:
398
+ transport.abort()
399
+
400
+ self._cleanup_closed_transports = []
401
+
402
+ if not self._cleanup_closed_disabled:
403
+ self._cleanup_closed_handle = helpers.weakref_handle(
404
+ self, "_cleanup_closed", self._cleanup_closed_period, self._loop
405
+ )
406
+
407
+ def close(self) -> Awaitable[None]:
408
+ """Close all opened transports."""
409
+ self._close()
410
+ return _DeprecationWaiter(noop())
411
+
412
+ def _close(self) -> None:
413
+ if self._closed:
414
+ return
415
+
416
+ self._closed = True
417
+
418
+ try:
419
+ if self._loop.is_closed():
420
+ return
421
+
422
+ # cancel cleanup task
423
+ if self._cleanup_handle:
424
+ self._cleanup_handle.cancel()
425
+
426
+ # cancel cleanup close task
427
+ if self._cleanup_closed_handle:
428
+ self._cleanup_closed_handle.cancel()
429
+
430
+ for data in self._conns.values():
431
+ for proto, t0 in data:
432
+ proto.close()
433
+
434
+ for proto in self._acquired:
435
+ proto.close()
436
+
437
+ for transport in self._cleanup_closed_transports:
438
+ if transport is not None:
439
+ transport.abort()
440
+
441
+ finally:
442
+ self._conns.clear()
443
+ self._acquired.clear()
444
+ self._waiters.clear()
445
+ self._cleanup_handle = None
446
+ self._cleanup_closed_transports.clear()
447
+ self._cleanup_closed_handle = None
448
+
449
+ @property
450
+ def closed(self) -> bool:
451
+ """Is connector closed.
452
+
453
+ A readonly property.
454
+ """
455
+ return self._closed
456
+
457
+ def _available_connections(self, key: "ConnectionKey") -> int:
458
+ """
459
+ Return number of available connections.
460
+
461
+ The limit, limit_per_host and the connection key are taken into account.
462
+
463
+ If it returns less than 1 means that there are no connections
464
+ available.
465
+ """
466
+ if self._limit:
467
+ # total calc available connections
468
+ available = self._limit - len(self._acquired)
469
+
470
+ # check limit per host
471
+ if (
472
+ self._limit_per_host
473
+ and available > 0
474
+ and key in self._acquired_per_host
475
+ ):
476
+ acquired = self._acquired_per_host.get(key)
477
+ assert acquired is not None
478
+ available = self._limit_per_host - len(acquired)
479
+
480
+ elif self._limit_per_host and key in self._acquired_per_host:
481
+ # check limit per host
482
+ acquired = self._acquired_per_host.get(key)
483
+ assert acquired is not None
484
+ available = self._limit_per_host - len(acquired)
485
+ else:
486
+ available = 1
487
+
488
+ return available
489
+
490
+ async def connect(
491
+ self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
492
+ ) -> Connection:
493
+ """Get from pool or create new connection."""
494
+ key = req.connection_key
495
+ available = self._available_connections(key)
496
+
497
+ # Wait if there are no available connections or if there are/were
498
+ # waiters (i.e. don't steal connection from a waiter about to wake up)
499
+ if available <= 0 or key in self._waiters:
500
+ fut = self._loop.create_future()
501
+
502
+ # This connection will now count towards the limit.
503
+ self._waiters[key].append(fut)
504
+
505
+ if traces:
506
+ for trace in traces:
507
+ await trace.send_connection_queued_start()
508
+
509
+ try:
510
+ await fut
511
+ except BaseException as e:
512
+ if key in self._waiters:
513
+ # remove a waiter even if it was cancelled, normally it's
514
+ # removed when it's notified
515
+ try:
516
+ self._waiters[key].remove(fut)
517
+ except ValueError: # fut may no longer be in list
518
+ pass
519
+
520
+ raise e
521
+ finally:
522
+ if key in self._waiters and not self._waiters[key]:
523
+ del self._waiters[key]
524
+
525
+ if traces:
526
+ for trace in traces:
527
+ await trace.send_connection_queued_end()
528
+
529
+ proto = self._get(key)
530
+ if proto is None:
531
+ placeholder = cast(ResponseHandler, _TransportPlaceholder())
532
+ self._acquired.add(placeholder)
533
+ self._acquired_per_host[key].add(placeholder)
534
+
535
+ if traces:
536
+ for trace in traces:
537
+ await trace.send_connection_create_start()
538
+
539
+ try:
540
+ proto = await self._create_connection(req, traces, timeout)
541
+ if self._closed:
542
+ proto.close()
543
+ raise ClientConnectionError("Connector is closed.")
544
+ except BaseException:
545
+ if not self._closed:
546
+ self._acquired.remove(placeholder)
547
+ self._drop_acquired_per_host(key, placeholder)
548
+ self._release_waiter()
549
+ raise
550
+ else:
551
+ if not self._closed:
552
+ self._acquired.remove(placeholder)
553
+ self._drop_acquired_per_host(key, placeholder)
554
+
555
+ if traces:
556
+ for trace in traces:
557
+ await trace.send_connection_create_end()
558
+ else:
559
+ if traces:
560
+ # Acquire the connection to prevent race conditions with limits
561
+ placeholder = cast(ResponseHandler, _TransportPlaceholder())
562
+ self._acquired.add(placeholder)
563
+ self._acquired_per_host[key].add(placeholder)
564
+ for trace in traces:
565
+ await trace.send_connection_reuseconn()
566
+ self._acquired.remove(placeholder)
567
+ self._drop_acquired_per_host(key, placeholder)
568
+
569
+ self._acquired.add(proto)
570
+ self._acquired_per_host[key].add(proto)
571
+ return Connection(self, key, proto, self._loop)
572
+
573
+ def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]:
574
+ try:
575
+ conns = self._conns[key]
576
+ except KeyError:
577
+ return None
578
+
579
+ t1 = self._loop.time()
580
+ while conns:
581
+ proto, t0 = conns.pop()
582
+ if proto.is_connected():
583
+ if t1 - t0 > self._keepalive_timeout:
584
+ transport = proto.transport
585
+ proto.close()
586
+ # only for SSL transports
587
+ if key.is_ssl and not self._cleanup_closed_disabled:
588
+ self._cleanup_closed_transports.append(transport)
589
+ else:
590
+ if not conns:
591
+ # The very last connection was reclaimed: drop the key
592
+ del self._conns[key]
593
+ return proto
594
+ else:
595
+ transport = proto.transport
596
+ proto.close()
597
+ if key.is_ssl and not self._cleanup_closed_disabled:
598
+ self._cleanup_closed_transports.append(transport)
599
+
600
+ # No more connections: drop the key
601
+ del self._conns[key]
602
+ return None
603
+
604
+ def _release_waiter(self) -> None:
605
+ """
606
+ Iterates over all waiters until one to be released is found.
607
+
608
+ The one to be released is not finsihed and
609
+ belongs to a host that has available connections.
610
+ """
611
+ if not self._waiters:
612
+ return
613
+
614
+ # Having the dict keys ordered this avoids to iterate
615
+ # at the same order at each call.
616
+ queues = list(self._waiters.keys())
617
+ random.shuffle(queues)
618
+
619
+ for key in queues:
620
+ if self._available_connections(key) < 1:
621
+ continue
622
+
623
+ waiters = self._waiters[key]
624
+ while waiters:
625
+ waiter = waiters.popleft()
626
+ if not waiter.done():
627
+ waiter.set_result(None)
628
+ return
629
+
630
+ def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None:
631
+ if self._closed:
632
+ # acquired connection is already released on connector closing
633
+ return
634
+
635
+ try:
636
+ self._acquired.remove(proto)
637
+ self._drop_acquired_per_host(key, proto)
638
+ except KeyError: # pragma: no cover
639
+ # this may be result of undetermenistic order of objects
640
+ # finalization due garbage collection.
641
+ pass
642
+ else:
643
+ self._release_waiter()
644
+
645
+ def _release(
646
+ self,
647
+ key: "ConnectionKey",
648
+ protocol: ResponseHandler,
649
+ *,
650
+ should_close: bool = False,
651
+ ) -> None:
652
+ if self._closed:
653
+ # acquired connection is already released on connector closing
654
+ return
655
+
656
+ self._release_acquired(key, protocol)
657
+
658
+ if self._force_close:
659
+ should_close = True
660
+
661
+ if should_close or protocol.should_close:
662
+ transport = protocol.transport
663
+ protocol.close()
664
+
665
+ if key.is_ssl and not self._cleanup_closed_disabled:
666
+ self._cleanup_closed_transports.append(transport)
667
+ else:
668
+ conns = self._conns.get(key)
669
+ if conns is None:
670
+ conns = self._conns[key] = []
671
+ conns.append((protocol, self._loop.time()))
672
+
673
+ if self._cleanup_handle is None:
674
+ self._cleanup_handle = helpers.weakref_handle(
675
+ self, "_cleanup", self._keepalive_timeout, self._loop
676
+ )
677
+
678
+ async def _create_connection(
679
+ self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
680
+ ) -> ResponseHandler:
681
+ raise NotImplementedError()
682
+
683
+
684
+ class _DNSCacheTable:
685
+ def __init__(self, ttl: Optional[float] = None) -> None:
686
+ self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] = {}
687
+ self._timestamps: Dict[Tuple[str, int], float] = {}
688
+ self._ttl = ttl
689
+
690
+ def __contains__(self, host: object) -> bool:
691
+ return host in self._addrs_rr
692
+
693
+ def add(self, key: Tuple[str, int], addrs: List[Dict[str, Any]]) -> None:
694
+ self._addrs_rr[key] = (cycle(addrs), len(addrs))
695
+
696
+ if self._ttl:
697
+ self._timestamps[key] = monotonic()
698
+
699
+ def remove(self, key: Tuple[str, int]) -> None:
700
+ self._addrs_rr.pop(key, None)
701
+
702
+ if self._ttl:
703
+ self._timestamps.pop(key, None)
704
+
705
+ def clear(self) -> None:
706
+ self._addrs_rr.clear()
707
+ self._timestamps.clear()
708
+
709
+ def next_addrs(self, key: Tuple[str, int]) -> List[Dict[str, Any]]:
710
+ loop, length = self._addrs_rr[key]
711
+ addrs = list(islice(loop, length))
712
+ # Consume one more element to shift internal state of `cycle`
713
+ next(loop)
714
+ return addrs
715
+
716
+ def expired(self, key: Tuple[str, int]) -> bool:
717
+ if self._ttl is None:
718
+ return False
719
+
720
+ return self._timestamps[key] + self._ttl < monotonic()
721
+
722
+
723
+ class TCPConnector(BaseConnector):
724
+ """TCP connector.
725
+
726
+ verify_ssl - Set to True to check ssl certifications.
727
+ fingerprint - Pass the binary sha256
728
+ digest of the expected certificate in DER format to verify
729
+ that the certificate the server presents matches. See also
730
+ https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning
731
+ resolver - Enable DNS lookups and use this
732
+ resolver
733
+ use_dns_cache - Use memory cache for DNS lookups.
734
+ ttl_dns_cache - Max seconds having cached a DNS entry, None forever.
735
+ family - socket address family
736
+ local_addr - local tuple of (host, port) to bind socket to
737
+
738
+ keepalive_timeout - (optional) Keep-alive timeout.
739
+ force_close - Set to True to force close and do reconnect
740
+ after each request (and between redirects).
741
+ limit - The total number of simultaneous connections.
742
+ limit_per_host - Number of simultaneous connections to one host.
743
+ enable_cleanup_closed - Enables clean-up closed ssl transports.
744
+ Disabled by default.
745
+ loop - Optional event loop.
746
+ """
747
+
748
+ def __init__(
749
+ self,
750
+ *,
751
+ verify_ssl: bool = True,
752
+ fingerprint: Optional[bytes] = None,
753
+ use_dns_cache: bool = True,
754
+ ttl_dns_cache: Optional[int] = 10,
755
+ family: int = 0,
756
+ ssl_context: Optional[SSLContext] = None,
757
+ ssl: Union[None, bool, Fingerprint, SSLContext] = None,
758
+ local_addr: Optional[Tuple[str, int]] = None,
759
+ resolver: Optional[AbstractResolver] = None,
760
+ keepalive_timeout: Union[None, float, object] = sentinel,
761
+ force_close: bool = False,
762
+ limit: int = 100,
763
+ limit_per_host: int = 0,
764
+ enable_cleanup_closed: bool = False,
765
+ loop: Optional[asyncio.AbstractEventLoop] = None,
766
+ ):
767
+ super().__init__(
768
+ keepalive_timeout=keepalive_timeout,
769
+ force_close=force_close,
770
+ limit=limit,
771
+ limit_per_host=limit_per_host,
772
+ enable_cleanup_closed=enable_cleanup_closed,
773
+ loop=loop,
774
+ )
775
+
776
+ self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint)
777
+ if resolver is None:
778
+ resolver = DefaultResolver(loop=self._loop)
779
+ self._resolver = resolver
780
+
781
+ self._use_dns_cache = use_dns_cache
782
+ self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache)
783
+ self._throttle_dns_events: Dict[Tuple[str, int], EventResultOrError] = {}
784
+ self._family = family
785
+ self._local_addr = local_addr
786
+
787
+ def close(self) -> Awaitable[None]:
788
+ """Close all ongoing DNS calls."""
789
+ for ev in self._throttle_dns_events.values():
790
+ ev.cancel()
791
+
792
+ return super().close()
793
+
794
+ @property
795
+ def family(self) -> int:
796
+ """Socket family like AF_INET."""
797
+ return self._family
798
+
799
+ @property
800
+ def use_dns_cache(self) -> bool:
801
+ """True if local DNS caching is enabled."""
802
+ return self._use_dns_cache
803
+
804
+ def clear_dns_cache(
805
+ self, host: Optional[str] = None, port: Optional[int] = None
806
+ ) -> None:
807
+ """Remove specified host/port or clear all dns local cache."""
808
+ if host is not None and port is not None:
809
+ self._cached_hosts.remove((host, port))
810
+ elif host is not None or port is not None:
811
+ raise ValueError("either both host and port " "or none of them are allowed")
812
+ else:
813
+ self._cached_hosts.clear()
814
+
815
+ async def _resolve_host(
816
+ self, host: str, port: int, traces: Optional[List["Trace"]] = None
817
+ ) -> List[Dict[str, Any]]:
818
+ if is_ip_address(host):
819
+ return [
820
+ {
821
+ "hostname": host,
822
+ "host": host,
823
+ "port": port,
824
+ "family": self._family,
825
+ "proto": 0,
826
+ "flags": 0,
827
+ }
828
+ ]
829
+
830
+ if not self._use_dns_cache:
831
+
832
+ if traces:
833
+ for trace in traces:
834
+ await trace.send_dns_resolvehost_start(host)
835
+
836
+ res = await self._resolver.resolve(host, port, family=self._family)
837
+
838
+ if traces:
839
+ for trace in traces:
840
+ await trace.send_dns_resolvehost_end(host)
841
+
842
+ return res
843
+
844
+ key = (host, port)
845
+
846
+ if (key in self._cached_hosts) and (not self._cached_hosts.expired(key)):
847
+ # get result early, before any await (#4014)
848
+ result = self._cached_hosts.next_addrs(key)
849
+
850
+ if traces:
851
+ for trace in traces:
852
+ await trace.send_dns_cache_hit(host)
853
+ return result
854
+
855
+ if key in self._throttle_dns_events:
856
+ # get event early, before any await (#4014)
857
+ event = self._throttle_dns_events[key]
858
+ if traces:
859
+ for trace in traces:
860
+ await trace.send_dns_cache_hit(host)
861
+ await event.wait()
862
+ else:
863
+ # update dict early, before any await (#4014)
864
+ self._throttle_dns_events[key] = EventResultOrError(self._loop)
865
+ if traces:
866
+ for trace in traces:
867
+ await trace.send_dns_cache_miss(host)
868
+ try:
869
+
870
+ if traces:
871
+ for trace in traces:
872
+ await trace.send_dns_resolvehost_start(host)
873
+
874
+ addrs = await self._resolver.resolve(host, port, family=self._family)
875
+ if traces:
876
+ for trace in traces:
877
+ await trace.send_dns_resolvehost_end(host)
878
+
879
+ self._cached_hosts.add(key, addrs)
880
+ self._throttle_dns_events[key].set()
881
+ except BaseException as e:
882
+ # any DNS exception, independently of the implementation
883
+ # is set for the waiters to raise the same exception.
884
+ self._throttle_dns_events[key].set(exc=e)
885
+ raise
886
+ finally:
887
+ self._throttle_dns_events.pop(key)
888
+
889
+ return self._cached_hosts.next_addrs(key)
890
+
891
+ async def _create_connection(
892
+ self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
893
+ ) -> ResponseHandler:
894
+ """Create connection.
895
+
896
+ Has same keyword arguments as BaseEventLoop.create_connection.
897
+ """
898
+ if req.proxy:
899
+ _, proto = await self._create_proxy_connection(req, traces, timeout)
900
+ else:
901
+ _, proto = await self._create_direct_connection(req, traces, timeout)
902
+
903
+ return proto
904
+
905
+ @staticmethod
906
+ @functools.lru_cache(None)
907
+ def _make_ssl_context(verified: bool) -> SSLContext:
908
+ if verified:
909
+ return ssl.create_default_context()
910
+ else:
911
+ sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
912
+ sslcontext.options |= ssl.OP_NO_SSLv2
913
+ sslcontext.options |= ssl.OP_NO_SSLv3
914
+ sslcontext.check_hostname = False
915
+ sslcontext.verify_mode = ssl.CERT_NONE
916
+ try:
917
+ sslcontext.options |= ssl.OP_NO_COMPRESSION
918
+ except AttributeError as attr_err:
919
+ warnings.warn(
920
+ "{!s}: The Python interpreter is compiled "
921
+ "against OpenSSL < 1.0.0. Ref: "
922
+ "https://docs.python.org/3/library/ssl.html"
923
+ "#ssl.OP_NO_COMPRESSION".format(attr_err),
924
+ )
925
+ sslcontext.set_default_verify_paths()
926
+ return sslcontext
927
+
928
+ def _get_ssl_context(self, req: "ClientRequest") -> Optional[SSLContext]:
929
+ """Logic to get the correct SSL context
930
+
931
+ 0. if req.ssl is false, return None
932
+
933
+ 1. if ssl_context is specified in req, use it
934
+ 2. if _ssl_context is specified in self, use it
935
+ 3. otherwise:
936
+ 1. if verify_ssl is not specified in req, use self.ssl_context
937
+ (will generate a default context according to self.verify_ssl)
938
+ 2. if verify_ssl is True in req, generate a default SSL context
939
+ 3. if verify_ssl is False in req, generate a SSL context that
940
+ won't verify
941
+ """
942
+ if req.is_ssl():
943
+ if ssl is None: # pragma: no cover
944
+ raise RuntimeError("SSL is not supported.")
945
+ sslcontext = req.ssl
946
+ if isinstance(sslcontext, ssl.SSLContext):
947
+ return sslcontext
948
+ if sslcontext is not None:
949
+ # not verified or fingerprinted
950
+ return self._make_ssl_context(False)
951
+ sslcontext = self._ssl
952
+ if isinstance(sslcontext, ssl.SSLContext):
953
+ return sslcontext
954
+ if sslcontext is not None:
955
+ # not verified or fingerprinted
956
+ return self._make_ssl_context(False)
957
+ return self._make_ssl_context(True)
958
+ else:
959
+ return None
960
+
961
+ def _get_fingerprint(self, req: "ClientRequest") -> Optional["Fingerprint"]:
962
+ ret = req.ssl
963
+ if isinstance(ret, Fingerprint):
964
+ return ret
965
+ ret = self._ssl
966
+ if isinstance(ret, Fingerprint):
967
+ return ret
968
+ return None
969
+
970
+ async def _wrap_create_connection(
971
+ self,
972
+ *args: Any,
973
+ req: "ClientRequest",
974
+ timeout: "ClientTimeout",
975
+ client_error: Type[Exception] = ClientConnectorError,
976
+ **kwargs: Any,
977
+ ) -> Tuple[asyncio.Transport, ResponseHandler]:
978
+ try:
979
+ async with ceil_timeout(timeout.sock_connect):
980
+ return await self._loop.create_connection(*args, **kwargs) # type: ignore[return-value] # noqa
981
+ except cert_errors as exc:
982
+ raise ClientConnectorCertificateError(req.connection_key, exc) from exc
983
+ except ssl_errors as exc:
984
+ raise ClientConnectorSSLError(req.connection_key, exc) from exc
985
+ except OSError as exc:
986
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
987
+ raise
988
+ raise client_error(req.connection_key, exc) from exc
989
+
990
+ def _fail_on_no_start_tls(self, req: "ClientRequest") -> None:
991
+ """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``.
992
+
993
+ One case is that :py:meth:`asyncio.loop.start_tls` is not yet
994
+ implemented under Python 3.6. It is necessary for TLS-in-TLS so
995
+ that it is possible to send HTTPS queries through HTTPS proxies.
996
+
997
+ This doesn't affect regular HTTP requests, though.
998
+ """
999
+ if not req.is_ssl():
1000
+ return
1001
+
1002
+ proxy_url = req.proxy
1003
+ assert proxy_url is not None
1004
+ if proxy_url.scheme != "https":
1005
+ return
1006
+
1007
+ self._check_loop_for_start_tls()
1008
+
1009
+ def _check_loop_for_start_tls(self) -> None:
1010
+ try:
1011
+ self._loop.start_tls
1012
+ except AttributeError as attr_exc:
1013
+ raise RuntimeError(
1014
+ "An HTTPS request is being sent through an HTTPS proxy. "
1015
+ "This needs support for TLS in TLS but it is not implemented "
1016
+ "in your runtime for the stdlib asyncio.\n\n"
1017
+ "Please upgrade to Python 3.7 or higher. For more details, "
1018
+ "please see:\n"
1019
+ "* https://bugs.python.org/issue37179\n"
1020
+ "* https://github.com/python/cpython/pull/28073\n"
1021
+ "* https://docs.aiohttp.org/en/stable/"
1022
+ "client_advanced.html#proxy-support\n"
1023
+ "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
1024
+ ) from attr_exc
1025
+
1026
+ def _loop_supports_start_tls(self) -> bool:
1027
+ try:
1028
+ self._check_loop_for_start_tls()
1029
+ except RuntimeError:
1030
+ return False
1031
+ else:
1032
+ return True
1033
+
1034
+ def _warn_about_tls_in_tls(
1035
+ self,
1036
+ underlying_transport: asyncio.Transport,
1037
+ req: "ClientRequest",
1038
+ ) -> None:
1039
+ """Issue a warning if the requested URL has HTTPS scheme."""
1040
+ if req.request_info.url.scheme != "https":
1041
+ return
1042
+
1043
+ asyncio_supports_tls_in_tls = getattr(
1044
+ underlying_transport,
1045
+ "_start_tls_compatible",
1046
+ False,
1047
+ )
1048
+
1049
+ if asyncio_supports_tls_in_tls:
1050
+ return
1051
+
1052
+ warnings.warn(
1053
+ "An HTTPS request is being sent through an HTTPS proxy. "
1054
+ "This support for TLS in TLS is known to be disabled "
1055
+ "in the stdlib asyncio. This is why you'll probably see "
1056
+ "an error in the log below.\n\n"
1057
+ "It is possible to enable it via monkeypatching under "
1058
+ "Python 3.7 or higher. For more details, see:\n"
1059
+ "* https://bugs.python.org/issue37179\n"
1060
+ "* https://github.com/python/cpython/pull/28073\n\n"
1061
+ "You can temporarily patch this as follows:\n"
1062
+ "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n"
1063
+ "* https://github.com/aio-libs/aiohttp/discussions/6044\n",
1064
+ RuntimeWarning,
1065
+ source=self,
1066
+ # Why `4`? At least 3 of the calls in the stack originate
1067
+ # from the methods in this class.
1068
+ stacklevel=3,
1069
+ )
1070
+
1071
+ async def _start_tls_connection(
1072
+ self,
1073
+ underlying_transport: asyncio.Transport,
1074
+ req: "ClientRequest",
1075
+ timeout: "ClientTimeout",
1076
+ client_error: Type[Exception] = ClientConnectorError,
1077
+ ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1078
+ """Wrap the raw TCP transport with TLS."""
1079
+ tls_proto = self._factory() # Create a brand new proto for TLS
1080
+
1081
+ # Safety of the `cast()` call here is based on the fact that
1082
+ # internally `_get_ssl_context()` only returns `None` when
1083
+ # `req.is_ssl()` evaluates to `False` which is never gonna happen
1084
+ # in this code path. Of course, it's rather fragile
1085
+ # maintainability-wise but this is to be solved separately.
1086
+ sslcontext = cast(ssl.SSLContext, self._get_ssl_context(req))
1087
+
1088
+ try:
1089
+ async with ceil_timeout(timeout.sock_connect):
1090
+ try:
1091
+ tls_transport = await self._loop.start_tls(
1092
+ underlying_transport,
1093
+ tls_proto,
1094
+ sslcontext,
1095
+ server_hostname=req.host,
1096
+ ssl_handshake_timeout=timeout.total,
1097
+ )
1098
+ except BaseException:
1099
+ # We need to close the underlying transport since
1100
+ # `start_tls()` probably failed before it had a
1101
+ # chance to do this:
1102
+ underlying_transport.close()
1103
+ raise
1104
+ except cert_errors as exc:
1105
+ raise ClientConnectorCertificateError(req.connection_key, exc) from exc
1106
+ except ssl_errors as exc:
1107
+ raise ClientConnectorSSLError(req.connection_key, exc) from exc
1108
+ except OSError as exc:
1109
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1110
+ raise
1111
+ raise client_error(req.connection_key, exc) from exc
1112
+ except TypeError as type_err:
1113
+ # Example cause looks like this:
1114
+ # TypeError: transport <asyncio.sslproto._SSLProtocolTransport
1115
+ # object at 0x7f760615e460> is not supported by start_tls()
1116
+
1117
+ raise ClientConnectionError(
1118
+ "Cannot initialize a TLS-in-TLS connection to host "
1119
+ f"{req.host!s}:{req.port:d} through an underlying connection "
1120
+ f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} "
1121
+ f"[{type_err!s}]"
1122
+ ) from type_err
1123
+ else:
1124
+ tls_proto.connection_made(
1125
+ tls_transport
1126
+ ) # Kick the state machine of the new TLS protocol
1127
+
1128
+ return tls_transport, tls_proto
1129
+
1130
+ async def _create_direct_connection(
1131
+ self,
1132
+ req: "ClientRequest",
1133
+ traces: List["Trace"],
1134
+ timeout: "ClientTimeout",
1135
+ *,
1136
+ client_error: Type[Exception] = ClientConnectorError,
1137
+ ) -> Tuple[asyncio.Transport, ResponseHandler]:
1138
+ sslcontext = self._get_ssl_context(req)
1139
+ fingerprint = self._get_fingerprint(req)
1140
+
1141
+ host = req.url.raw_host
1142
+ assert host is not None
1143
+ port = req.port
1144
+ assert port is not None
1145
+ host_resolved = asyncio.ensure_future(
1146
+ self._resolve_host(host, port, traces=traces), loop=self._loop
1147
+ )
1148
+ try:
1149
+ # Cancelling this lookup should not cancel the underlying lookup
1150
+ # or else the cancel event will get broadcast to all the waiters
1151
+ # across all connections.
1152
+ hosts = await asyncio.shield(host_resolved)
1153
+ except asyncio.CancelledError:
1154
+
1155
+ def drop_exception(fut: "asyncio.Future[List[Dict[str, Any]]]") -> None:
1156
+ with suppress(Exception, asyncio.CancelledError):
1157
+ fut.result()
1158
+
1159
+ host_resolved.add_done_callback(drop_exception)
1160
+ raise
1161
+ except OSError as exc:
1162
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1163
+ raise
1164
+ # in case of proxy it is not ClientProxyConnectionError
1165
+ # it is problem of resolving proxy ip itself
1166
+ raise ClientConnectorError(req.connection_key, exc) from exc
1167
+
1168
+ last_exc: Optional[Exception] = None
1169
+
1170
+ for hinfo in hosts:
1171
+ host = hinfo["host"]
1172
+ port = hinfo["port"]
1173
+
1174
+ try:
1175
+ transp, proto = await self._wrap_create_connection(
1176
+ self._factory,
1177
+ host,
1178
+ port,
1179
+ timeout=timeout,
1180
+ ssl=sslcontext,
1181
+ family=hinfo["family"],
1182
+ proto=hinfo["proto"],
1183
+ flags=hinfo["flags"],
1184
+ server_hostname=hinfo["hostname"] if sslcontext else None,
1185
+ local_addr=self._local_addr,
1186
+ req=req,
1187
+ client_error=client_error,
1188
+ )
1189
+ except ClientConnectorError as exc:
1190
+ last_exc = exc
1191
+ continue
1192
+
1193
+ if req.is_ssl() and fingerprint:
1194
+ try:
1195
+ fingerprint.check(transp)
1196
+ except ServerFingerprintMismatch as exc:
1197
+ transp.close()
1198
+ if not self._cleanup_closed_disabled:
1199
+ self._cleanup_closed_transports.append(transp)
1200
+ last_exc = exc
1201
+ continue
1202
+
1203
+ return transp, proto
1204
+ else:
1205
+ assert last_exc is not None
1206
+ raise last_exc
1207
+
1208
+ async def _create_proxy_connection(
1209
+ self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
1210
+ ) -> Tuple[asyncio.BaseTransport, ResponseHandler]:
1211
+ self._fail_on_no_start_tls(req)
1212
+ runtime_has_start_tls = self._loop_supports_start_tls()
1213
+
1214
+ headers: Dict[str, str] = {}
1215
+ if req.proxy_headers is not None:
1216
+ headers = req.proxy_headers # type: ignore[assignment]
1217
+ headers[hdrs.HOST] = req.headers[hdrs.HOST]
1218
+
1219
+ url = req.proxy
1220
+ assert url is not None
1221
+ proxy_req = ClientRequest(
1222
+ hdrs.METH_GET,
1223
+ url,
1224
+ headers=headers,
1225
+ auth=req.proxy_auth,
1226
+ loop=self._loop,
1227
+ ssl=req.ssl,
1228
+ )
1229
+
1230
+ # create connection to proxy server
1231
+ transport, proto = await self._create_direct_connection(
1232
+ proxy_req, [], timeout, client_error=ClientProxyConnectionError
1233
+ )
1234
+
1235
+ # Many HTTP proxies has buggy keepalive support. Let's not
1236
+ # reuse connection but close it after processing every
1237
+ # response.
1238
+ proto.force_close()
1239
+
1240
+ auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None)
1241
+ if auth is not None:
1242
+ if not req.is_ssl():
1243
+ req.headers[hdrs.PROXY_AUTHORIZATION] = auth
1244
+ else:
1245
+ proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth
1246
+
1247
+ if req.is_ssl():
1248
+ if runtime_has_start_tls:
1249
+ self._warn_about_tls_in_tls(transport, req)
1250
+
1251
+ # For HTTPS requests over HTTP proxy
1252
+ # we must notify proxy to tunnel connection
1253
+ # so we send CONNECT command:
1254
+ # CONNECT www.python.org:443 HTTP/1.1
1255
+ # Host: www.python.org
1256
+ #
1257
+ # next we must do TLS handshake and so on
1258
+ # to do this we must wrap raw socket into secure one
1259
+ # asyncio handles this perfectly
1260
+ proxy_req.method = hdrs.METH_CONNECT
1261
+ proxy_req.url = req.url
1262
+ key = attr.evolve(
1263
+ req.connection_key, proxy=None, proxy_auth=None, proxy_headers_hash=None
1264
+ )
1265
+ conn = Connection(self, key, proto, self._loop)
1266
+ proxy_resp = await proxy_req.send(conn)
1267
+ try:
1268
+ protocol = conn._protocol
1269
+ assert protocol is not None
1270
+
1271
+ # read_until_eof=True will ensure the connection isn't closed
1272
+ # once the response is received and processed allowing
1273
+ # START_TLS to work on the connection below.
1274
+ protocol.set_response_params(read_until_eof=runtime_has_start_tls)
1275
+ resp = await proxy_resp.start(conn)
1276
+ except BaseException:
1277
+ proxy_resp.close()
1278
+ conn.close()
1279
+ raise
1280
+ else:
1281
+ conn._protocol = None
1282
+ conn._transport = None
1283
+ try:
1284
+ if resp.status != 200:
1285
+ message = resp.reason
1286
+ if message is None:
1287
+ message = RESPONSES[resp.status][0]
1288
+ raise ClientHttpProxyError(
1289
+ proxy_resp.request_info,
1290
+ resp.history,
1291
+ status=resp.status,
1292
+ message=message,
1293
+ headers=resp.headers,
1294
+ )
1295
+ if not runtime_has_start_tls:
1296
+ rawsock = transport.get_extra_info("socket", default=None)
1297
+ if rawsock is None:
1298
+ raise RuntimeError(
1299
+ "Transport does not expose socket instance"
1300
+ )
1301
+ # Duplicate the socket, so now we can close proxy transport
1302
+ rawsock = rawsock.dup()
1303
+ except BaseException:
1304
+ # It shouldn't be closed in `finally` because it's fed to
1305
+ # `loop.start_tls()` and the docs say not to touch it after
1306
+ # passing there.
1307
+ transport.close()
1308
+ raise
1309
+ finally:
1310
+ if not runtime_has_start_tls:
1311
+ transport.close()
1312
+
1313
+ if not runtime_has_start_tls:
1314
+ # HTTP proxy with support for upgrade to HTTPS
1315
+ sslcontext = self._get_ssl_context(req)
1316
+ return await self._wrap_create_connection(
1317
+ self._factory,
1318
+ timeout=timeout,
1319
+ ssl=sslcontext,
1320
+ sock=rawsock,
1321
+ server_hostname=req.host,
1322
+ req=req,
1323
+ )
1324
+
1325
+ return await self._start_tls_connection(
1326
+ # Access the old transport for the last time before it's
1327
+ # closed and forgotten forever:
1328
+ transport,
1329
+ req=req,
1330
+ timeout=timeout,
1331
+ )
1332
+ finally:
1333
+ proxy_resp.close()
1334
+
1335
+ return transport, proto
1336
+
1337
+
1338
+ class UnixConnector(BaseConnector):
1339
+ """Unix socket connector.
1340
+
1341
+ path - Unix socket path.
1342
+ keepalive_timeout - (optional) Keep-alive timeout.
1343
+ force_close - Set to True to force close and do reconnect
1344
+ after each request (and between redirects).
1345
+ limit - The total number of simultaneous connections.
1346
+ limit_per_host - Number of simultaneous connections to one host.
1347
+ loop - Optional event loop.
1348
+ """
1349
+
1350
+ def __init__(
1351
+ self,
1352
+ path: str,
1353
+ force_close: bool = False,
1354
+ keepalive_timeout: Union[object, float, None] = sentinel,
1355
+ limit: int = 100,
1356
+ limit_per_host: int = 0,
1357
+ loop: Optional[asyncio.AbstractEventLoop] = None,
1358
+ ) -> None:
1359
+ super().__init__(
1360
+ force_close=force_close,
1361
+ keepalive_timeout=keepalive_timeout,
1362
+ limit=limit,
1363
+ limit_per_host=limit_per_host,
1364
+ loop=loop,
1365
+ )
1366
+ self._path = path
1367
+
1368
+ @property
1369
+ def path(self) -> str:
1370
+ """Path to unix socket."""
1371
+ return self._path
1372
+
1373
+ async def _create_connection(
1374
+ self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
1375
+ ) -> ResponseHandler:
1376
+ try:
1377
+ async with ceil_timeout(timeout.sock_connect):
1378
+ _, proto = await self._loop.create_unix_connection(
1379
+ self._factory, self._path
1380
+ )
1381
+ except OSError as exc:
1382
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1383
+ raise
1384
+ raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc
1385
+
1386
+ return cast(ResponseHandler, proto)
1387
+
1388
+
1389
+ class NamedPipeConnector(BaseConnector):
1390
+ """Named pipe connector.
1391
+
1392
+ Only supported by the proactor event loop.
1393
+ See also: https://docs.python.org/3.7/library/asyncio-eventloop.html
1394
+
1395
+ path - Windows named pipe path.
1396
+ keepalive_timeout - (optional) Keep-alive timeout.
1397
+ force_close - Set to True to force close and do reconnect
1398
+ after each request (and between redirects).
1399
+ limit - The total number of simultaneous connections.
1400
+ limit_per_host - Number of simultaneous connections to one host.
1401
+ loop - Optional event loop.
1402
+ """
1403
+
1404
+ def __init__(
1405
+ self,
1406
+ path: str,
1407
+ force_close: bool = False,
1408
+ keepalive_timeout: Union[object, float, None] = sentinel,
1409
+ limit: int = 100,
1410
+ limit_per_host: int = 0,
1411
+ loop: Optional[asyncio.AbstractEventLoop] = None,
1412
+ ) -> None:
1413
+ super().__init__(
1414
+ force_close=force_close,
1415
+ keepalive_timeout=keepalive_timeout,
1416
+ limit=limit,
1417
+ limit_per_host=limit_per_host,
1418
+ loop=loop,
1419
+ )
1420
+ if not isinstance(
1421
+ self._loop, asyncio.ProactorEventLoop # type: ignore[attr-defined]
1422
+ ):
1423
+ raise RuntimeError(
1424
+ "Named Pipes only available in proactor " "loop under windows"
1425
+ )
1426
+ self._path = path
1427
+
1428
+ @property
1429
+ def path(self) -> str:
1430
+ """Path to the named pipe."""
1431
+ return self._path
1432
+
1433
+ async def _create_connection(
1434
+ self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout"
1435
+ ) -> ResponseHandler:
1436
+ try:
1437
+ async with ceil_timeout(timeout.sock_connect):
1438
+ _, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined] # noqa: E501
1439
+ self._factory, self._path
1440
+ )
1441
+ # the drain is required so that the connection_made is called
1442
+ # and transport is set otherwise it is not set before the
1443
+ # `assert conn.transport is not None`
1444
+ # in client.py's _request method
1445
+ await asyncio.sleep(0)
1446
+ # other option is to manually set transport like
1447
+ # `proto.transport = trans`
1448
+ except OSError as exc:
1449
+ if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
1450
+ raise
1451
+ raise ClientConnectorError(req.connection_key, exc) from exc
1452
+
1453
+ return cast(ResponseHandler, proto)
runtime/Lib/site-packages/aiohttp/cookiejar.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import contextlib
3
+ import datetime
4
+ import os # noqa
5
+ import pathlib
6
+ import pickle
7
+ import re
8
+ from collections import defaultdict
9
+ from http.cookies import BaseCookie, Morsel, SimpleCookie
10
+ from typing import ( # noqa
11
+ DefaultDict,
12
+ Dict,
13
+ Iterable,
14
+ Iterator,
15
+ List,
16
+ Mapping,
17
+ Optional,
18
+ Set,
19
+ Tuple,
20
+ Union,
21
+ cast,
22
+ )
23
+
24
+ from yarl import URL
25
+
26
+ from .abc import AbstractCookieJar, ClearCookiePredicate
27
+ from .helpers import is_ip_address, next_whole_second
28
+ from .typedefs import LooseCookies, PathLike, StrOrURL
29
+
30
+ __all__ = ("CookieJar", "DummyCookieJar")
31
+
32
+
33
+ CookieItem = Union[str, "Morsel[str]"]
34
+
35
+
36
+ class CookieJar(AbstractCookieJar):
37
+ """Implements cookie storage adhering to RFC 6265."""
38
+
39
+ DATE_TOKENS_RE = re.compile(
40
+ r"[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*"
41
+ r"(?P<token>[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)"
42
+ )
43
+
44
+ DATE_HMS_TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})")
45
+
46
+ DATE_DAY_OF_MONTH_RE = re.compile(r"(\d{1,2})")
47
+
48
+ DATE_MONTH_RE = re.compile(
49
+ "(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|" "(aug)|(sep)|(oct)|(nov)|(dec)",
50
+ re.I,
51
+ )
52
+
53
+ DATE_YEAR_RE = re.compile(r"(\d{2,4})")
54
+
55
+ MAX_TIME = datetime.datetime.max.replace(tzinfo=datetime.timezone.utc)
56
+
57
+ MAX_32BIT_TIME = datetime.datetime.utcfromtimestamp(2**31 - 1)
58
+
59
+ def __init__(
60
+ self,
61
+ *,
62
+ unsafe: bool = False,
63
+ quote_cookie: bool = True,
64
+ treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None,
65
+ loop: Optional[asyncio.AbstractEventLoop] = None,
66
+ ) -> None:
67
+ super().__init__(loop=loop)
68
+ self._cookies: DefaultDict[str, SimpleCookie[str]] = defaultdict(SimpleCookie)
69
+ self._host_only_cookies: Set[Tuple[str, str]] = set()
70
+ self._unsafe = unsafe
71
+ self._quote_cookie = quote_cookie
72
+ if treat_as_secure_origin is None:
73
+ treat_as_secure_origin = []
74
+ elif isinstance(treat_as_secure_origin, URL):
75
+ treat_as_secure_origin = [treat_as_secure_origin.origin()]
76
+ elif isinstance(treat_as_secure_origin, str):
77
+ treat_as_secure_origin = [URL(treat_as_secure_origin).origin()]
78
+ else:
79
+ treat_as_secure_origin = [
80
+ URL(url).origin() if isinstance(url, str) else url.origin()
81
+ for url in treat_as_secure_origin
82
+ ]
83
+ self._treat_as_secure_origin = treat_as_secure_origin
84
+ self._next_expiration = next_whole_second()
85
+ self._expirations: Dict[Tuple[str, str], datetime.datetime] = {}
86
+ # #4515: datetime.max may not be representable on 32-bit platforms
87
+ self._max_time = self.MAX_TIME
88
+ try:
89
+ self._max_time.timestamp()
90
+ except OverflowError:
91
+ self._max_time = self.MAX_32BIT_TIME
92
+
93
+ def save(self, file_path: PathLike) -> None:
94
+ file_path = pathlib.Path(file_path)
95
+ with file_path.open(mode="wb") as f:
96
+ pickle.dump(self._cookies, f, pickle.HIGHEST_PROTOCOL)
97
+
98
+ def load(self, file_path: PathLike) -> None:
99
+ file_path = pathlib.Path(file_path)
100
+ with file_path.open(mode="rb") as f:
101
+ self._cookies = pickle.load(f)
102
+
103
+ def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
104
+ if predicate is None:
105
+ self._next_expiration = next_whole_second()
106
+ self._cookies.clear()
107
+ self._host_only_cookies.clear()
108
+ self._expirations.clear()
109
+ return
110
+
111
+ to_del = []
112
+ now = datetime.datetime.now(datetime.timezone.utc)
113
+ for domain, cookie in self._cookies.items():
114
+ for name, morsel in cookie.items():
115
+ key = (domain, name)
116
+ if (
117
+ key in self._expirations and self._expirations[key] <= now
118
+ ) or predicate(morsel):
119
+ to_del.append(key)
120
+
121
+ for domain, name in to_del:
122
+ key = (domain, name)
123
+ self._host_only_cookies.discard(key)
124
+ if key in self._expirations:
125
+ del self._expirations[(domain, name)]
126
+ self._cookies[domain].pop(name, None)
127
+
128
+ next_expiration = min(self._expirations.values(), default=self._max_time)
129
+ try:
130
+ self._next_expiration = next_expiration.replace(
131
+ microsecond=0
132
+ ) + datetime.timedelta(seconds=1)
133
+ except OverflowError:
134
+ self._next_expiration = self._max_time
135
+
136
+ def clear_domain(self, domain: str) -> None:
137
+ self.clear(lambda x: self._is_domain_match(domain, x["domain"]))
138
+
139
+ def __iter__(self) -> "Iterator[Morsel[str]]":
140
+ self._do_expiration()
141
+ for val in self._cookies.values():
142
+ yield from val.values()
143
+
144
+ def __len__(self) -> int:
145
+ return sum(1 for i in self)
146
+
147
+ def _do_expiration(self) -> None:
148
+ self.clear(lambda x: False)
149
+
150
+ def _expire_cookie(self, when: datetime.datetime, domain: str, name: str) -> None:
151
+ self._next_expiration = min(self._next_expiration, when)
152
+ self._expirations[(domain, name)] = when
153
+
154
+ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
155
+ """Update cookies."""
156
+ hostname = response_url.raw_host
157
+
158
+ if not self._unsafe and is_ip_address(hostname):
159
+ # Don't accept cookies from IPs
160
+ return
161
+
162
+ if isinstance(cookies, Mapping):
163
+ cookies = cookies.items()
164
+
165
+ for name, cookie in cookies:
166
+ if not isinstance(cookie, Morsel):
167
+ tmp: SimpleCookie[str] = SimpleCookie()
168
+ tmp[name] = cookie # type: ignore[assignment]
169
+ cookie = tmp[name]
170
+
171
+ domain = cookie["domain"]
172
+
173
+ # ignore domains with trailing dots
174
+ if domain.endswith("."):
175
+ domain = ""
176
+ del cookie["domain"]
177
+
178
+ if not domain and hostname is not None:
179
+ # Set the cookie's domain to the response hostname
180
+ # and set its host-only-flag
181
+ self._host_only_cookies.add((hostname, name))
182
+ domain = cookie["domain"] = hostname
183
+
184
+ if domain.startswith("."):
185
+ # Remove leading dot
186
+ domain = domain[1:]
187
+ cookie["domain"] = domain
188
+
189
+ if hostname and not self._is_domain_match(domain, hostname):
190
+ # Setting cookies for different domains is not allowed
191
+ continue
192
+
193
+ path = cookie["path"]
194
+ if not path or not path.startswith("/"):
195
+ # Set the cookie's path to the response path
196
+ path = response_url.path
197
+ if not path.startswith("/"):
198
+ path = "/"
199
+ else:
200
+ # Cut everything from the last slash to the end
201
+ path = "/" + path[1 : path.rfind("/")]
202
+ cookie["path"] = path
203
+
204
+ max_age = cookie["max-age"]
205
+ if max_age:
206
+ try:
207
+ delta_seconds = int(max_age)
208
+ try:
209
+ max_age_expiration = datetime.datetime.now(
210
+ datetime.timezone.utc
211
+ ) + datetime.timedelta(seconds=delta_seconds)
212
+ except OverflowError:
213
+ max_age_expiration = self._max_time
214
+ self._expire_cookie(max_age_expiration, domain, name)
215
+ except ValueError:
216
+ cookie["max-age"] = ""
217
+
218
+ else:
219
+ expires = cookie["expires"]
220
+ if expires:
221
+ expire_time = self._parse_date(expires)
222
+ if expire_time:
223
+ self._expire_cookie(expire_time, domain, name)
224
+ else:
225
+ cookie["expires"] = ""
226
+
227
+ self._cookies[domain][name] = cookie
228
+
229
+ self._do_expiration()
230
+
231
+ def filter_cookies(
232
+ self, request_url: URL = URL()
233
+ ) -> Union["BaseCookie[str]", "SimpleCookie[str]"]:
234
+ """Returns this jar's cookies filtered by their attributes."""
235
+ self._do_expiration()
236
+ request_url = URL(request_url)
237
+ filtered: Union["SimpleCookie[str]", "BaseCookie[str]"] = (
238
+ SimpleCookie() if self._quote_cookie else BaseCookie()
239
+ )
240
+ hostname = request_url.raw_host or ""
241
+ request_origin = URL()
242
+ with contextlib.suppress(ValueError):
243
+ request_origin = request_url.origin()
244
+
245
+ is_not_secure = (
246
+ request_url.scheme not in ("https", "wss")
247
+ and request_origin not in self._treat_as_secure_origin
248
+ )
249
+
250
+ for cookie in self:
251
+ name = cookie.key
252
+ domain = cookie["domain"]
253
+
254
+ # Send shared cookies
255
+ if not domain:
256
+ filtered[name] = cookie.value
257
+ continue
258
+
259
+ if not self._unsafe and is_ip_address(hostname):
260
+ continue
261
+
262
+ if (domain, name) in self._host_only_cookies:
263
+ if domain != hostname:
264
+ continue
265
+ elif not self._is_domain_match(domain, hostname):
266
+ continue
267
+
268
+ if not self._is_path_match(request_url.path, cookie["path"]):
269
+ continue
270
+
271
+ if is_not_secure and cookie["secure"]:
272
+ continue
273
+
274
+ # It's critical we use the Morsel so the coded_value
275
+ # (based on cookie version) is preserved
276
+ mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel()))
277
+ mrsl_val.set(cookie.key, cookie.value, cookie.coded_value)
278
+ filtered[name] = mrsl_val
279
+
280
+ return filtered
281
+
282
+ @staticmethod
283
+ def _is_domain_match(domain: str, hostname: str) -> bool:
284
+ """Implements domain matching adhering to RFC 6265."""
285
+ if hostname == domain:
286
+ return True
287
+
288
+ if not hostname.endswith(domain):
289
+ return False
290
+
291
+ non_matching = hostname[: -len(domain)]
292
+
293
+ if not non_matching.endswith("."):
294
+ return False
295
+
296
+ return not is_ip_address(hostname)
297
+
298
+ @staticmethod
299
+ def _is_path_match(req_path: str, cookie_path: str) -> bool:
300
+ """Implements path matching adhering to RFC 6265."""
301
+ if not req_path.startswith("/"):
302
+ req_path = "/"
303
+
304
+ if req_path == cookie_path:
305
+ return True
306
+
307
+ if not req_path.startswith(cookie_path):
308
+ return False
309
+
310
+ if cookie_path.endswith("/"):
311
+ return True
312
+
313
+ non_matching = req_path[len(cookie_path) :]
314
+
315
+ return non_matching.startswith("/")
316
+
317
+ @classmethod
318
+ def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]:
319
+ """Implements date string parsing adhering to RFC 6265."""
320
+ if not date_str:
321
+ return None
322
+
323
+ found_time = False
324
+ found_day = False
325
+ found_month = False
326
+ found_year = False
327
+
328
+ hour = minute = second = 0
329
+ day = 0
330
+ month = 0
331
+ year = 0
332
+
333
+ for token_match in cls.DATE_TOKENS_RE.finditer(date_str):
334
+
335
+ token = token_match.group("token")
336
+
337
+ if not found_time:
338
+ time_match = cls.DATE_HMS_TIME_RE.match(token)
339
+ if time_match:
340
+ found_time = True
341
+ hour, minute, second = (int(s) for s in time_match.groups())
342
+ continue
343
+
344
+ if not found_day:
345
+ day_match = cls.DATE_DAY_OF_MONTH_RE.match(token)
346
+ if day_match:
347
+ found_day = True
348
+ day = int(day_match.group())
349
+ continue
350
+
351
+ if not found_month:
352
+ month_match = cls.DATE_MONTH_RE.match(token)
353
+ if month_match:
354
+ found_month = True
355
+ assert month_match.lastindex is not None
356
+ month = month_match.lastindex
357
+ continue
358
+
359
+ if not found_year:
360
+ year_match = cls.DATE_YEAR_RE.match(token)
361
+ if year_match:
362
+ found_year = True
363
+ year = int(year_match.group())
364
+
365
+ if 70 <= year <= 99:
366
+ year += 1900
367
+ elif 0 <= year <= 69:
368
+ year += 2000
369
+
370
+ if False in (found_day, found_month, found_year, found_time):
371
+ return None
372
+
373
+ if not 1 <= day <= 31:
374
+ return None
375
+
376
+ if year < 1601 or hour > 23 or minute > 59 or second > 59:
377
+ return None
378
+
379
+ return datetime.datetime(
380
+ year, month, day, hour, minute, second, tzinfo=datetime.timezone.utc
381
+ )
382
+
383
+
384
+ class DummyCookieJar(AbstractCookieJar):
385
+ """Implements a dummy cookie storage.
386
+
387
+ It can be used with the ClientSession when no cookie processing is needed.
388
+
389
+ """
390
+
391
+ def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
392
+ super().__init__(loop=loop)
393
+
394
+ def __iter__(self) -> "Iterator[Morsel[str]]":
395
+ while False:
396
+ yield None
397
+
398
+ def __len__(self) -> int:
399
+ return 0
400
+
401
+ def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None:
402
+ pass
403
+
404
+ def clear_domain(self, domain: str) -> None:
405
+ pass
406
+
407
+ def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None:
408
+ pass
409
+
410
+ def filter_cookies(self, request_url: URL) -> "BaseCookie[str]":
411
+ return SimpleCookie()
runtime/Lib/site-packages/aiohttp/formdata.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from typing import Any, Iterable, List, Optional
3
+ from urllib.parse import urlencode
4
+
5
+ from multidict import MultiDict, MultiDictProxy
6
+
7
+ from . import hdrs, multipart, payload
8
+ from .helpers import guess_filename
9
+ from .payload import Payload
10
+
11
+ __all__ = ("FormData",)
12
+
13
+
14
+ class FormData:
15
+ """Helper class for form body generation.
16
+
17
+ Supports multipart/form-data and application/x-www-form-urlencoded.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ fields: Iterable[Any] = (),
23
+ quote_fields: bool = True,
24
+ charset: Optional[str] = None,
25
+ ) -> None:
26
+ self._writer = multipart.MultipartWriter("form-data")
27
+ self._fields: List[Any] = []
28
+ self._is_multipart = False
29
+ self._is_processed = False
30
+ self._quote_fields = quote_fields
31
+ self._charset = charset
32
+
33
+ if isinstance(fields, dict):
34
+ fields = list(fields.items())
35
+ elif not isinstance(fields, (list, tuple)):
36
+ fields = (fields,)
37
+ self.add_fields(*fields)
38
+
39
+ @property
40
+ def is_multipart(self) -> bool:
41
+ return self._is_multipart
42
+
43
+ def add_field(
44
+ self,
45
+ name: str,
46
+ value: Any,
47
+ *,
48
+ content_type: Optional[str] = None,
49
+ filename: Optional[str] = None,
50
+ content_transfer_encoding: Optional[str] = None,
51
+ ) -> None:
52
+
53
+ if isinstance(value, io.IOBase):
54
+ self._is_multipart = True
55
+ elif isinstance(value, (bytes, bytearray, memoryview)):
56
+ if filename is None and content_transfer_encoding is None:
57
+ filename = name
58
+
59
+ type_options: MultiDict[str] = MultiDict({"name": name})
60
+ if filename is not None and not isinstance(filename, str):
61
+ raise TypeError(
62
+ "filename must be an instance of str. " "Got: %s" % filename
63
+ )
64
+ if filename is None and isinstance(value, io.IOBase):
65
+ filename = guess_filename(value, name)
66
+ if filename is not None:
67
+ type_options["filename"] = filename
68
+ self._is_multipart = True
69
+
70
+ headers = {}
71
+ if content_type is not None:
72
+ if not isinstance(content_type, str):
73
+ raise TypeError(
74
+ "content_type must be an instance of str. " "Got: %s" % content_type
75
+ )
76
+ headers[hdrs.CONTENT_TYPE] = content_type
77
+ self._is_multipart = True
78
+ if content_transfer_encoding is not None:
79
+ if not isinstance(content_transfer_encoding, str):
80
+ raise TypeError(
81
+ "content_transfer_encoding must be an instance"
82
+ " of str. Got: %s" % content_transfer_encoding
83
+ )
84
+ headers[hdrs.CONTENT_TRANSFER_ENCODING] = content_transfer_encoding
85
+ self._is_multipart = True
86
+
87
+ self._fields.append((type_options, headers, value))
88
+
89
+ def add_fields(self, *fields: Any) -> None:
90
+ to_add = list(fields)
91
+
92
+ while to_add:
93
+ rec = to_add.pop(0)
94
+
95
+ if isinstance(rec, io.IOBase):
96
+ k = guess_filename(rec, "unknown")
97
+ self.add_field(k, rec) # type: ignore[arg-type]
98
+
99
+ elif isinstance(rec, (MultiDictProxy, MultiDict)):
100
+ to_add.extend(rec.items())
101
+
102
+ elif isinstance(rec, (list, tuple)) and len(rec) == 2:
103
+ k, fp = rec
104
+ self.add_field(k, fp) # type: ignore[arg-type]
105
+
106
+ else:
107
+ raise TypeError(
108
+ "Only io.IOBase, multidict and (name, file) "
109
+ "pairs allowed, use .add_field() for passing "
110
+ "more complex parameters, got {!r}".format(rec)
111
+ )
112
+
113
+ def _gen_form_urlencoded(self) -> payload.BytesPayload:
114
+ # form data (x-www-form-urlencoded)
115
+ data = []
116
+ for type_options, _, value in self._fields:
117
+ data.append((type_options["name"], value))
118
+
119
+ charset = self._charset if self._charset is not None else "utf-8"
120
+
121
+ if charset == "utf-8":
122
+ content_type = "application/x-www-form-urlencoded"
123
+ else:
124
+ content_type = "application/x-www-form-urlencoded; " "charset=%s" % charset
125
+
126
+ return payload.BytesPayload(
127
+ urlencode(data, doseq=True, encoding=charset).encode(),
128
+ content_type=content_type,
129
+ )
130
+
131
+ def _gen_form_data(self) -> multipart.MultipartWriter:
132
+ """Encode a list of fields using the multipart/form-data MIME format"""
133
+ if self._is_processed:
134
+ raise RuntimeError("Form data has been processed already")
135
+ for dispparams, headers, value in self._fields:
136
+ try:
137
+ if hdrs.CONTENT_TYPE in headers:
138
+ part = payload.get_payload(
139
+ value,
140
+ content_type=headers[hdrs.CONTENT_TYPE],
141
+ headers=headers,
142
+ encoding=self._charset,
143
+ )
144
+ else:
145
+ part = payload.get_payload(
146
+ value, headers=headers, encoding=self._charset
147
+ )
148
+ except Exception as exc:
149
+ raise TypeError(
150
+ "Can not serialize value type: %r\n "
151
+ "headers: %r\n value: %r" % (type(value), headers, value)
152
+ ) from exc
153
+
154
+ if dispparams:
155
+ part.set_content_disposition(
156
+ "form-data", quote_fields=self._quote_fields, **dispparams
157
+ )
158
+ # FIXME cgi.FieldStorage doesn't likes body parts with
159
+ # Content-Length which were sent via chunked transfer encoding
160
+ assert part.headers is not None
161
+ part.headers.popall(hdrs.CONTENT_LENGTH, None)
162
+
163
+ self._writer.append_payload(part)
164
+
165
+ self._is_processed = True
166
+ return self._writer
167
+
168
+ def __call__(self) -> Payload:
169
+ if self._is_multipart:
170
+ return self._gen_form_data()
171
+ else:
172
+ return self._gen_form_urlencoded()
runtime/Lib/site-packages/aiohttp/hdrs.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP Headers constants."""
2
+
3
+ # After changing the file content call ./tools/gen.py
4
+ # to regenerate the headers parser
5
+ import sys
6
+ from typing import Set
7
+
8
+ from multidict import istr
9
+
10
+ if sys.version_info >= (3, 8):
11
+ from typing import Final
12
+ else:
13
+ from typing_extensions import Final
14
+
15
+ METH_ANY: Final[str] = "*"
16
+ METH_CONNECT: Final[str] = "CONNECT"
17
+ METH_HEAD: Final[str] = "HEAD"
18
+ METH_GET: Final[str] = "GET"
19
+ METH_DELETE: Final[str] = "DELETE"
20
+ METH_OPTIONS: Final[str] = "OPTIONS"
21
+ METH_PATCH: Final[str] = "PATCH"
22
+ METH_POST: Final[str] = "POST"
23
+ METH_PUT: Final[str] = "PUT"
24
+ METH_TRACE: Final[str] = "TRACE"
25
+
26
+ METH_ALL: Final[Set[str]] = {
27
+ METH_CONNECT,
28
+ METH_HEAD,
29
+ METH_GET,
30
+ METH_DELETE,
31
+ METH_OPTIONS,
32
+ METH_PATCH,
33
+ METH_POST,
34
+ METH_PUT,
35
+ METH_TRACE,
36
+ }
37
+
38
+ ACCEPT: Final[istr] = istr("Accept")
39
+ ACCEPT_CHARSET: Final[istr] = istr("Accept-Charset")
40
+ ACCEPT_ENCODING: Final[istr] = istr("Accept-Encoding")
41
+ ACCEPT_LANGUAGE: Final[istr] = istr("Accept-Language")
42
+ ACCEPT_RANGES: Final[istr] = istr("Accept-Ranges")
43
+ ACCESS_CONTROL_MAX_AGE: Final[istr] = istr("Access-Control-Max-Age")
44
+ ACCESS_CONTROL_ALLOW_CREDENTIALS: Final[istr] = istr("Access-Control-Allow-Credentials")
45
+ ACCESS_CONTROL_ALLOW_HEADERS: Final[istr] = istr("Access-Control-Allow-Headers")
46
+ ACCESS_CONTROL_ALLOW_METHODS: Final[istr] = istr("Access-Control-Allow-Methods")
47
+ ACCESS_CONTROL_ALLOW_ORIGIN: Final[istr] = istr("Access-Control-Allow-Origin")
48
+ ACCESS_CONTROL_EXPOSE_HEADERS: Final[istr] = istr("Access-Control-Expose-Headers")
49
+ ACCESS_CONTROL_REQUEST_HEADERS: Final[istr] = istr("Access-Control-Request-Headers")
50
+ ACCESS_CONTROL_REQUEST_METHOD: Final[istr] = istr("Access-Control-Request-Method")
51
+ AGE: Final[istr] = istr("Age")
52
+ ALLOW: Final[istr] = istr("Allow")
53
+ AUTHORIZATION: Final[istr] = istr("Authorization")
54
+ CACHE_CONTROL: Final[istr] = istr("Cache-Control")
55
+ CONNECTION: Final[istr] = istr("Connection")
56
+ CONTENT_DISPOSITION: Final[istr] = istr("Content-Disposition")
57
+ CONTENT_ENCODING: Final[istr] = istr("Content-Encoding")
58
+ CONTENT_LANGUAGE: Final[istr] = istr("Content-Language")
59
+ CONTENT_LENGTH: Final[istr] = istr("Content-Length")
60
+ CONTENT_LOCATION: Final[istr] = istr("Content-Location")
61
+ CONTENT_MD5: Final[istr] = istr("Content-MD5")
62
+ CONTENT_RANGE: Final[istr] = istr("Content-Range")
63
+ CONTENT_TRANSFER_ENCODING: Final[istr] = istr("Content-Transfer-Encoding")
64
+ CONTENT_TYPE: Final[istr] = istr("Content-Type")
65
+ COOKIE: Final[istr] = istr("Cookie")
66
+ DATE: Final[istr] = istr("Date")
67
+ DESTINATION: Final[istr] = istr("Destination")
68
+ DIGEST: Final[istr] = istr("Digest")
69
+ ETAG: Final[istr] = istr("Etag")
70
+ EXPECT: Final[istr] = istr("Expect")
71
+ EXPIRES: Final[istr] = istr("Expires")
72
+ FORWARDED: Final[istr] = istr("Forwarded")
73
+ FROM: Final[istr] = istr("From")
74
+ HOST: Final[istr] = istr("Host")
75
+ IF_MATCH: Final[istr] = istr("If-Match")
76
+ IF_MODIFIED_SINCE: Final[istr] = istr("If-Modified-Since")
77
+ IF_NONE_MATCH: Final[istr] = istr("If-None-Match")
78
+ IF_RANGE: Final[istr] = istr("If-Range")
79
+ IF_UNMODIFIED_SINCE: Final[istr] = istr("If-Unmodified-Since")
80
+ KEEP_ALIVE: Final[istr] = istr("Keep-Alive")
81
+ LAST_EVENT_ID: Final[istr] = istr("Last-Event-ID")
82
+ LAST_MODIFIED: Final[istr] = istr("Last-Modified")
83
+ LINK: Final[istr] = istr("Link")
84
+ LOCATION: Final[istr] = istr("Location")
85
+ MAX_FORWARDS: Final[istr] = istr("Max-Forwards")
86
+ ORIGIN: Final[istr] = istr("Origin")
87
+ PRAGMA: Final[istr] = istr("Pragma")
88
+ PROXY_AUTHENTICATE: Final[istr] = istr("Proxy-Authenticate")
89
+ PROXY_AUTHORIZATION: Final[istr] = istr("Proxy-Authorization")
90
+ RANGE: Final[istr] = istr("Range")
91
+ REFERER: Final[istr] = istr("Referer")
92
+ RETRY_AFTER: Final[istr] = istr("Retry-After")
93
+ SEC_WEBSOCKET_ACCEPT: Final[istr] = istr("Sec-WebSocket-Accept")
94
+ SEC_WEBSOCKET_VERSION: Final[istr] = istr("Sec-WebSocket-Version")
95
+ SEC_WEBSOCKET_PROTOCOL: Final[istr] = istr("Sec-WebSocket-Protocol")
96
+ SEC_WEBSOCKET_EXTENSIONS: Final[istr] = istr("Sec-WebSocket-Extensions")
97
+ SEC_WEBSOCKET_KEY: Final[istr] = istr("Sec-WebSocket-Key")
98
+ SEC_WEBSOCKET_KEY1: Final[istr] = istr("Sec-WebSocket-Key1")
99
+ SERVER: Final[istr] = istr("Server")
100
+ SET_COOKIE: Final[istr] = istr("Set-Cookie")
101
+ TE: Final[istr] = istr("TE")
102
+ TRAILER: Final[istr] = istr("Trailer")
103
+ TRANSFER_ENCODING: Final[istr] = istr("Transfer-Encoding")
104
+ UPGRADE: Final[istr] = istr("Upgrade")
105
+ URI: Final[istr] = istr("URI")
106
+ USER_AGENT: Final[istr] = istr("User-Agent")
107
+ VARY: Final[istr] = istr("Vary")
108
+ VIA: Final[istr] = istr("Via")
109
+ WANT_DIGEST: Final[istr] = istr("Want-Digest")
110
+ WARNING: Final[istr] = istr("Warning")
111
+ WWW_AUTHENTICATE: Final[istr] = istr("WWW-Authenticate")
112
+ X_FORWARDED_FOR: Final[istr] = istr("X-Forwarded-For")
113
+ X_FORWARDED_HOST: Final[istr] = istr("X-Forwarded-Host")
114
+ X_FORWARDED_PROTO: Final[istr] = istr("X-Forwarded-Proto")
runtime/Lib/site-packages/aiohttp/helpers.py ADDED
@@ -0,0 +1,877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Various helper functions"""
2
+
3
+ import asyncio
4
+ import base64
5
+ import binascii
6
+ import datetime
7
+ import functools
8
+ import inspect
9
+ import netrc
10
+ import os
11
+ import platform
12
+ import re
13
+ import sys
14
+ import time
15
+ import warnings
16
+ import weakref
17
+ from collections import namedtuple
18
+ from contextlib import suppress
19
+ from email.parser import HeaderParser
20
+ from email.utils import parsedate
21
+ from math import ceil
22
+ from pathlib import Path
23
+ from types import TracebackType
24
+ from typing import (
25
+ Any,
26
+ Callable,
27
+ ContextManager,
28
+ Dict,
29
+ Generator,
30
+ Generic,
31
+ Iterable,
32
+ Iterator,
33
+ List,
34
+ Mapping,
35
+ Optional,
36
+ Pattern,
37
+ Set,
38
+ Tuple,
39
+ Type,
40
+ TypeVar,
41
+ Union,
42
+ cast,
43
+ )
44
+ from urllib.parse import quote
45
+ from urllib.request import getproxies, proxy_bypass
46
+
47
+ import async_timeout
48
+ import attr
49
+ from multidict import MultiDict, MultiDictProxy
50
+ from yarl import URL
51
+
52
+ from . import hdrs
53
+ from .log import client_logger, internal_logger
54
+ from .typedefs import PathLike, Protocol # noqa
55
+
56
+ __all__ = ("BasicAuth", "ChainMapProxy", "ETag")
57
+
58
+ IS_MACOS = platform.system() == "Darwin"
59
+ IS_WINDOWS = platform.system() == "Windows"
60
+
61
+ PY_36 = sys.version_info >= (3, 6)
62
+ PY_37 = sys.version_info >= (3, 7)
63
+ PY_38 = sys.version_info >= (3, 8)
64
+ PY_310 = sys.version_info >= (3, 10)
65
+
66
+ if sys.version_info < (3, 7):
67
+ import idna_ssl
68
+
69
+ idna_ssl.patch_match_hostname()
70
+
71
+ def all_tasks(
72
+ loop: Optional[asyncio.AbstractEventLoop] = None,
73
+ ) -> Set["asyncio.Task[Any]"]:
74
+ tasks = list(asyncio.Task.all_tasks(loop))
75
+ return {t for t in tasks if not t.done()}
76
+
77
+ else:
78
+ all_tasks = asyncio.all_tasks
79
+
80
+
81
+ _T = TypeVar("_T")
82
+ _S = TypeVar("_S")
83
+
84
+
85
+ sentinel: Any = object()
86
+ NO_EXTENSIONS: bool = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS"))
87
+
88
+ # N.B. sys.flags.dev_mode is available on Python 3.7+, use getattr
89
+ # for compatibility with older versions
90
+ DEBUG: bool = getattr(sys.flags, "dev_mode", False) or (
91
+ not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG"))
92
+ )
93
+
94
+
95
+ CHAR = {chr(i) for i in range(0, 128)}
96
+ CTL = {chr(i) for i in range(0, 32)} | {
97
+ chr(127),
98
+ }
99
+ SEPARATORS = {
100
+ "(",
101
+ ")",
102
+ "<",
103
+ ">",
104
+ "@",
105
+ ",",
106
+ ";",
107
+ ":",
108
+ "\\",
109
+ '"',
110
+ "/",
111
+ "[",
112
+ "]",
113
+ "?",
114
+ "=",
115
+ "{",
116
+ "}",
117
+ " ",
118
+ chr(9),
119
+ }
120
+ TOKEN = CHAR ^ CTL ^ SEPARATORS
121
+
122
+
123
+ class noop:
124
+ def __await__(self) -> Generator[None, None, None]:
125
+ yield
126
+
127
+
128
+ class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])):
129
+ """Http basic authentication helper."""
130
+
131
+ def __new__(
132
+ cls, login: str, password: str = "", encoding: str = "latin1"
133
+ ) -> "BasicAuth":
134
+ if login is None:
135
+ raise ValueError("None is not allowed as login value")
136
+
137
+ if password is None:
138
+ raise ValueError("None is not allowed as password value")
139
+
140
+ if ":" in login:
141
+ raise ValueError('A ":" is not allowed in login (RFC 1945#section-11.1)')
142
+
143
+ return super().__new__(cls, login, password, encoding)
144
+
145
+ @classmethod
146
+ def decode(cls, auth_header: str, encoding: str = "latin1") -> "BasicAuth":
147
+ """Create a BasicAuth object from an Authorization HTTP header."""
148
+ try:
149
+ auth_type, encoded_credentials = auth_header.split(" ", 1)
150
+ except ValueError:
151
+ raise ValueError("Could not parse authorization header.")
152
+
153
+ if auth_type.lower() != "basic":
154
+ raise ValueError("Unknown authorization method %s" % auth_type)
155
+
156
+ try:
157
+ decoded = base64.b64decode(
158
+ encoded_credentials.encode("ascii"), validate=True
159
+ ).decode(encoding)
160
+ except binascii.Error:
161
+ raise ValueError("Invalid base64 encoding.")
162
+
163
+ try:
164
+ # RFC 2617 HTTP Authentication
165
+ # https://www.ietf.org/rfc/rfc2617.txt
166
+ # the colon must be present, but the username and password may be
167
+ # otherwise blank.
168
+ username, password = decoded.split(":", 1)
169
+ except ValueError:
170
+ raise ValueError("Invalid credentials.")
171
+
172
+ return cls(username, password, encoding=encoding)
173
+
174
+ @classmethod
175
+ def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]:
176
+ """Create BasicAuth from url."""
177
+ if not isinstance(url, URL):
178
+ raise TypeError("url should be yarl.URL instance")
179
+ if url.user is None:
180
+ return None
181
+ return cls(url.user, url.password or "", encoding=encoding)
182
+
183
+ def encode(self) -> str:
184
+ """Encode credentials."""
185
+ creds = (f"{self.login}:{self.password}").encode(self.encoding)
186
+ return "Basic %s" % base64.b64encode(creds).decode(self.encoding)
187
+
188
+
189
+ def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
190
+ auth = BasicAuth.from_url(url)
191
+ if auth is None:
192
+ return url, None
193
+ else:
194
+ return url.with_user(None), auth
195
+
196
+
197
+ def netrc_from_env() -> Optional[netrc.netrc]:
198
+ """Load netrc from file.
199
+
200
+ Attempt to load it from the path specified by the env-var
201
+ NETRC or in the default location in the user's home directory.
202
+
203
+ Returns None if it couldn't be found or fails to parse.
204
+ """
205
+ netrc_env = os.environ.get("NETRC")
206
+
207
+ if netrc_env is not None:
208
+ netrc_path = Path(netrc_env)
209
+ else:
210
+ try:
211
+ home_dir = Path.home()
212
+ except RuntimeError as e: # pragma: no cover
213
+ # if pathlib can't resolve home, it may raise a RuntimeError
214
+ client_logger.debug(
215
+ "Could not resolve home directory when "
216
+ "trying to look for .netrc file: %s",
217
+ e,
218
+ )
219
+ return None
220
+
221
+ netrc_path = home_dir / ("_netrc" if IS_WINDOWS else ".netrc")
222
+
223
+ try:
224
+ return netrc.netrc(str(netrc_path))
225
+ except netrc.NetrcParseError as e:
226
+ client_logger.warning("Could not parse .netrc file: %s", e)
227
+ except OSError as e:
228
+ # we couldn't read the file (doesn't exist, permissions, etc.)
229
+ if netrc_env or netrc_path.is_file():
230
+ # only warn if the environment wanted us to load it,
231
+ # or it appears like the default file does actually exist
232
+ client_logger.warning("Could not read .netrc file: %s", e)
233
+
234
+ return None
235
+
236
+
237
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
238
+ class ProxyInfo:
239
+ proxy: URL
240
+ proxy_auth: Optional[BasicAuth]
241
+
242
+
243
+ def proxies_from_env() -> Dict[str, ProxyInfo]:
244
+ proxy_urls = {
245
+ k: URL(v)
246
+ for k, v in getproxies().items()
247
+ if k in ("http", "https", "ws", "wss")
248
+ }
249
+ netrc_obj = netrc_from_env()
250
+ stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()}
251
+ ret = {}
252
+ for proto, val in stripped.items():
253
+ proxy, auth = val
254
+ if proxy.scheme in ("https", "wss"):
255
+ client_logger.warning(
256
+ "%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy
257
+ )
258
+ continue
259
+ if netrc_obj and auth is None:
260
+ auth_from_netrc = None
261
+ if proxy.host is not None:
262
+ auth_from_netrc = netrc_obj.authenticators(proxy.host)
263
+ if auth_from_netrc is not None:
264
+ # auth_from_netrc is a (`user`, `account`, `password`) tuple,
265
+ # `user` and `account` both can be username,
266
+ # if `user` is None, use `account`
267
+ *logins, password = auth_from_netrc
268
+ login = logins[0] if logins[0] else logins[-1]
269
+ auth = BasicAuth(cast(str, login), cast(str, password))
270
+ ret[proto] = ProxyInfo(proxy, auth)
271
+ return ret
272
+
273
+
274
+ def current_task(
275
+ loop: Optional[asyncio.AbstractEventLoop] = None,
276
+ ) -> "Optional[asyncio.Task[Any]]":
277
+ if sys.version_info >= (3, 7):
278
+ return asyncio.current_task(loop=loop)
279
+ else:
280
+ return asyncio.Task.current_task(loop=loop)
281
+
282
+
283
+ def get_running_loop(
284
+ loop: Optional[asyncio.AbstractEventLoop] = None,
285
+ ) -> asyncio.AbstractEventLoop:
286
+ if loop is None:
287
+ loop = asyncio.get_event_loop()
288
+ if not loop.is_running():
289
+ warnings.warn(
290
+ "The object should be created within an async function",
291
+ DeprecationWarning,
292
+ stacklevel=3,
293
+ )
294
+ if loop.get_debug():
295
+ internal_logger.warning(
296
+ "The object should be created within an async function", stack_info=True
297
+ )
298
+ return loop
299
+
300
+
301
+ def isasyncgenfunction(obj: Any) -> bool:
302
+ func = getattr(inspect, "isasyncgenfunction", None)
303
+ if func is not None:
304
+ return func(obj) # type: ignore[no-any-return]
305
+ else:
306
+ return False
307
+
308
+
309
+ def get_env_proxy_for_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
310
+ """Get a permitted proxy for the given URL from the env."""
311
+ if url.host is not None and proxy_bypass(url.host):
312
+ raise LookupError(f"Proxying is disallowed for `{url.host!r}`")
313
+
314
+ proxies_in_env = proxies_from_env()
315
+ try:
316
+ proxy_info = proxies_in_env[url.scheme]
317
+ except KeyError:
318
+ raise LookupError(f"No proxies found for `{url!s}` in the env")
319
+ else:
320
+ return proxy_info.proxy, proxy_info.proxy_auth
321
+
322
+
323
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
324
+ class MimeType:
325
+ type: str
326
+ subtype: str
327
+ suffix: str
328
+ parameters: "MultiDictProxy[str]"
329
+
330
+
331
+ @functools.lru_cache(maxsize=56)
332
+ def parse_mimetype(mimetype: str) -> MimeType:
333
+ """Parses a MIME type into its components.
334
+
335
+ mimetype is a MIME type string.
336
+
337
+ Returns a MimeType object.
338
+
339
+ Example:
340
+
341
+ >>> parse_mimetype('text/html; charset=utf-8')
342
+ MimeType(type='text', subtype='html', suffix='',
343
+ parameters={'charset': 'utf-8'})
344
+
345
+ """
346
+ if not mimetype:
347
+ return MimeType(
348
+ type="", subtype="", suffix="", parameters=MultiDictProxy(MultiDict())
349
+ )
350
+
351
+ parts = mimetype.split(";")
352
+ params: MultiDict[str] = MultiDict()
353
+ for item in parts[1:]:
354
+ if not item:
355
+ continue
356
+ key, value = cast(
357
+ Tuple[str, str], item.split("=", 1) if "=" in item else (item, "")
358
+ )
359
+ params.add(key.lower().strip(), value.strip(' "'))
360
+
361
+ fulltype = parts[0].strip().lower()
362
+ if fulltype == "*":
363
+ fulltype = "*/*"
364
+
365
+ mtype, stype = (
366
+ cast(Tuple[str, str], fulltype.split("/", 1))
367
+ if "/" in fulltype
368
+ else (fulltype, "")
369
+ )
370
+ stype, suffix = (
371
+ cast(Tuple[str, str], stype.split("+", 1)) if "+" in stype else (stype, "")
372
+ )
373
+
374
+ return MimeType(
375
+ type=mtype, subtype=stype, suffix=suffix, parameters=MultiDictProxy(params)
376
+ )
377
+
378
+
379
+ def guess_filename(obj: Any, default: Optional[str] = None) -> Optional[str]:
380
+ name = getattr(obj, "name", None)
381
+ if name and isinstance(name, str) and name[0] != "<" and name[-1] != ">":
382
+ return Path(name).name
383
+ return default
384
+
385
+
386
+ not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]")
387
+ QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"}
388
+
389
+
390
+ def quoted_string(content: str) -> str:
391
+ """Return 7-bit content as quoted-string.
392
+
393
+ Format content into a quoted-string as defined in RFC5322 for
394
+ Internet Message Format. Notice that this is not the 8-bit HTTP
395
+ format, but the 7-bit email format. Content must be in usascii or
396
+ a ValueError is raised.
397
+ """
398
+ if not (QCONTENT > set(content)):
399
+ raise ValueError(f"bad content for quoted-string {content!r}")
400
+ return not_qtext_re.sub(lambda x: "\\" + x.group(0), content)
401
+
402
+
403
+ def content_disposition_header(
404
+ disptype: str, quote_fields: bool = True, _charset: str = "utf-8", **params: str
405
+ ) -> str:
406
+ """Sets ``Content-Disposition`` header for MIME.
407
+
408
+ This is the MIME payload Content-Disposition header from RFC 2183
409
+ and RFC 7579 section 4.2, not the HTTP Content-Disposition from
410
+ RFC 6266.
411
+
412
+ disptype is a disposition type: inline, attachment, form-data.
413
+ Should be valid extension token (see RFC 2183)
414
+
415
+ quote_fields performs value quoting to 7-bit MIME headers
416
+ according to RFC 7578. Set to quote_fields to False if recipient
417
+ can take 8-bit file names and field values.
418
+
419
+ _charset specifies the charset to use when quote_fields is True.
420
+
421
+ params is a dict with disposition params.
422
+ """
423
+ if not disptype or not (TOKEN > set(disptype)):
424
+ raise ValueError("bad content disposition type {!r}" "".format(disptype))
425
+
426
+ value = disptype
427
+ if params:
428
+ lparams = []
429
+ for key, val in params.items():
430
+ if not key or not (TOKEN > set(key)):
431
+ raise ValueError(
432
+ "bad content disposition parameter" " {!r}={!r}".format(key, val)
433
+ )
434
+ if quote_fields:
435
+ if key.lower() == "filename":
436
+ qval = quote(val, "", encoding=_charset)
437
+ lparams.append((key, '"%s"' % qval))
438
+ else:
439
+ try:
440
+ qval = quoted_string(val)
441
+ except ValueError:
442
+ qval = "".join(
443
+ (_charset, "''", quote(val, "", encoding=_charset))
444
+ )
445
+ lparams.append((key + "*", qval))
446
+ else:
447
+ lparams.append((key, '"%s"' % qval))
448
+ else:
449
+ qval = val.replace("\\", "\\\\").replace('"', '\\"')
450
+ lparams.append((key, '"%s"' % qval))
451
+ sparams = "; ".join("=".join(pair) for pair in lparams)
452
+ value = "; ".join((value, sparams))
453
+ return value
454
+
455
+
456
+ class _TSelf(Protocol, Generic[_T]):
457
+ _cache: Dict[str, _T]
458
+
459
+
460
+ class reify(Generic[_T]):
461
+ """Use as a class method decorator.
462
+
463
+ It operates almost exactly like
464
+ the Python `@property` decorator, but it puts the result of the
465
+ method it decorates into the instance dict after the first call,
466
+ effectively replacing the function it decorates with an instance
467
+ variable. It is, in Python parlance, a data descriptor.
468
+ """
469
+
470
+ def __init__(self, wrapped: Callable[..., _T]) -> None:
471
+ self.wrapped = wrapped
472
+ self.__doc__ = wrapped.__doc__
473
+ self.name = wrapped.__name__
474
+
475
+ def __get__(self, inst: _TSelf[_T], owner: Optional[Type[Any]] = None) -> _T:
476
+ try:
477
+ try:
478
+ return inst._cache[self.name]
479
+ except KeyError:
480
+ val = self.wrapped(inst)
481
+ inst._cache[self.name] = val
482
+ return val
483
+ except AttributeError:
484
+ if inst is None:
485
+ return self
486
+ raise
487
+
488
+ def __set__(self, inst: _TSelf[_T], value: _T) -> None:
489
+ raise AttributeError("reified property is read-only")
490
+
491
+
492
+ reify_py = reify
493
+
494
+ try:
495
+ from ._helpers import reify as reify_c
496
+
497
+ if not NO_EXTENSIONS:
498
+ reify = reify_c # type: ignore[misc,assignment]
499
+ except ImportError:
500
+ pass
501
+
502
+ _ipv4_pattern = (
503
+ r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}"
504
+ r"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
505
+ )
506
+ _ipv6_pattern = (
507
+ r"^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}"
508
+ r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)"
509
+ r"((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})"
510
+ r"(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}"
511
+ r"(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}"
512
+ r"[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)"
513
+ r"(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}"
514
+ r":|:(:[A-F0-9]{1,4}){7})$"
515
+ )
516
+ _ipv4_regex = re.compile(_ipv4_pattern)
517
+ _ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE)
518
+ _ipv4_regexb = re.compile(_ipv4_pattern.encode("ascii"))
519
+ _ipv6_regexb = re.compile(_ipv6_pattern.encode("ascii"), flags=re.IGNORECASE)
520
+
521
+
522
+ def _is_ip_address(
523
+ regex: Pattern[str], regexb: Pattern[bytes], host: Optional[Union[str, bytes]]
524
+ ) -> bool:
525
+ if host is None:
526
+ return False
527
+ if isinstance(host, str):
528
+ return bool(regex.match(host))
529
+ elif isinstance(host, (bytes, bytearray, memoryview)):
530
+ return bool(regexb.match(host))
531
+ else:
532
+ raise TypeError(f"{host} [{type(host)}] is not a str or bytes")
533
+
534
+
535
+ is_ipv4_address = functools.partial(_is_ip_address, _ipv4_regex, _ipv4_regexb)
536
+ is_ipv6_address = functools.partial(_is_ip_address, _ipv6_regex, _ipv6_regexb)
537
+
538
+
539
+ def is_ip_address(host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool:
540
+ return is_ipv4_address(host) or is_ipv6_address(host)
541
+
542
+
543
+ def next_whole_second() -> datetime.datetime:
544
+ """Return current time rounded up to the next whole second."""
545
+ return datetime.datetime.now(datetime.timezone.utc).replace(
546
+ microsecond=0
547
+ ) + datetime.timedelta(seconds=0)
548
+
549
+
550
+ _cached_current_datetime: Optional[int] = None
551
+ _cached_formatted_datetime = ""
552
+
553
+
554
+ def rfc822_formatted_time() -> str:
555
+ global _cached_current_datetime
556
+ global _cached_formatted_datetime
557
+
558
+ now = int(time.time())
559
+ if now != _cached_current_datetime:
560
+ # Weekday and month names for HTTP date/time formatting;
561
+ # always English!
562
+ # Tuples are constants stored in codeobject!
563
+ _weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
564
+ _monthname = (
565
+ "", # Dummy so we can use 1-based month numbers
566
+ "Jan",
567
+ "Feb",
568
+ "Mar",
569
+ "Apr",
570
+ "May",
571
+ "Jun",
572
+ "Jul",
573
+ "Aug",
574
+ "Sep",
575
+ "Oct",
576
+ "Nov",
577
+ "Dec",
578
+ )
579
+
580
+ year, month, day, hh, mm, ss, wd, *tail = time.gmtime(now)
581
+ _cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
582
+ _weekdayname[wd],
583
+ day,
584
+ _monthname[month],
585
+ year,
586
+ hh,
587
+ mm,
588
+ ss,
589
+ )
590
+ _cached_current_datetime = now
591
+ return _cached_formatted_datetime
592
+
593
+
594
+ def _weakref_handle(info: "Tuple[weakref.ref[object], str]") -> None:
595
+ ref, name = info
596
+ ob = ref()
597
+ if ob is not None:
598
+ with suppress(Exception):
599
+ getattr(ob, name)()
600
+
601
+
602
+ def weakref_handle(
603
+ ob: object, name: str, timeout: float, loop: asyncio.AbstractEventLoop
604
+ ) -> Optional[asyncio.TimerHandle]:
605
+ if timeout is not None and timeout > 0:
606
+ when = loop.time() + timeout
607
+ if timeout >= 5:
608
+ when = ceil(when)
609
+
610
+ return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name))
611
+ return None
612
+
613
+
614
+ def call_later(
615
+ cb: Callable[[], Any], timeout: float, loop: asyncio.AbstractEventLoop
616
+ ) -> Optional[asyncio.TimerHandle]:
617
+ if timeout is not None and timeout > 0:
618
+ when = loop.time() + timeout
619
+ if timeout > 5:
620
+ when = ceil(when)
621
+ return loop.call_at(when, cb)
622
+ return None
623
+
624
+
625
+ class TimeoutHandle:
626
+ """Timeout handle"""
627
+
628
+ def __init__(
629
+ self, loop: asyncio.AbstractEventLoop, timeout: Optional[float]
630
+ ) -> None:
631
+ self._timeout = timeout
632
+ self._loop = loop
633
+ self._callbacks: List[
634
+ Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]]
635
+ ] = []
636
+
637
+ def register(
638
+ self, callback: Callable[..., None], *args: Any, **kwargs: Any
639
+ ) -> None:
640
+ self._callbacks.append((callback, args, kwargs))
641
+
642
+ def close(self) -> None:
643
+ self._callbacks.clear()
644
+
645
+ def start(self) -> Optional[asyncio.Handle]:
646
+ timeout = self._timeout
647
+ if timeout is not None and timeout > 0:
648
+ when = self._loop.time() + timeout
649
+ if timeout >= 5:
650
+ when = ceil(when)
651
+ return self._loop.call_at(when, self.__call__)
652
+ else:
653
+ return None
654
+
655
+ def timer(self) -> "BaseTimerContext":
656
+ if self._timeout is not None and self._timeout > 0:
657
+ timer = TimerContext(self._loop)
658
+ self.register(timer.timeout)
659
+ return timer
660
+ else:
661
+ return TimerNoop()
662
+
663
+ def __call__(self) -> None:
664
+ for cb, args, kwargs in self._callbacks:
665
+ with suppress(Exception):
666
+ cb(*args, **kwargs)
667
+
668
+ self._callbacks.clear()
669
+
670
+
671
+ class BaseTimerContext(ContextManager["BaseTimerContext"]):
672
+ pass
673
+
674
+
675
+ class TimerNoop(BaseTimerContext):
676
+ def __enter__(self) -> BaseTimerContext:
677
+ return self
678
+
679
+ def __exit__(
680
+ self,
681
+ exc_type: Optional[Type[BaseException]],
682
+ exc_val: Optional[BaseException],
683
+ exc_tb: Optional[TracebackType],
684
+ ) -> None:
685
+ return
686
+
687
+
688
+ class TimerContext(BaseTimerContext):
689
+ """Low resolution timeout context manager"""
690
+
691
+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
692
+ self._loop = loop
693
+ self._tasks: List[asyncio.Task[Any]] = []
694
+ self._cancelled = False
695
+
696
+ def __enter__(self) -> BaseTimerContext:
697
+ task = current_task(loop=self._loop)
698
+
699
+ if task is None:
700
+ raise RuntimeError(
701
+ "Timeout context manager should be used " "inside a task"
702
+ )
703
+
704
+ if self._cancelled:
705
+ raise asyncio.TimeoutError from None
706
+
707
+ self._tasks.append(task)
708
+ return self
709
+
710
+ def __exit__(
711
+ self,
712
+ exc_type: Optional[Type[BaseException]],
713
+ exc_val: Optional[BaseException],
714
+ exc_tb: Optional[TracebackType],
715
+ ) -> Optional[bool]:
716
+ if self._tasks:
717
+ self._tasks.pop()
718
+
719
+ if exc_type is asyncio.CancelledError and self._cancelled:
720
+ raise asyncio.TimeoutError from None
721
+ return None
722
+
723
+ def timeout(self) -> None:
724
+ if not self._cancelled:
725
+ for task in set(self._tasks):
726
+ task.cancel()
727
+
728
+ self._cancelled = True
729
+
730
+
731
+ def ceil_timeout(delay: Optional[float]) -> async_timeout.Timeout:
732
+ if delay is None or delay <= 0:
733
+ return async_timeout.timeout(None)
734
+
735
+ loop = get_running_loop()
736
+ now = loop.time()
737
+ when = now + delay
738
+ if delay > 5:
739
+ when = ceil(when)
740
+ return async_timeout.timeout_at(when)
741
+
742
+
743
+ class HeadersMixin:
744
+
745
+ ATTRS = frozenset(["_content_type", "_content_dict", "_stored_content_type"])
746
+
747
+ _content_type: Optional[str] = None
748
+ _content_dict: Optional[Dict[str, str]] = None
749
+ _stored_content_type = sentinel
750
+
751
+ def _parse_content_type(self, raw: str) -> None:
752
+ self._stored_content_type = raw
753
+ if raw is None:
754
+ # default value according to RFC 2616
755
+ self._content_type = "application/octet-stream"
756
+ self._content_dict = {}
757
+ else:
758
+ msg = HeaderParser().parsestr("Content-Type: " + raw)
759
+ self._content_type = msg.get_content_type()
760
+ params = msg.get_params()
761
+ self._content_dict = dict(params[1:]) # First element is content type again
762
+
763
+ @property
764
+ def content_type(self) -> str:
765
+ """The value of content part for Content-Type HTTP header."""
766
+ raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]
767
+ if self._stored_content_type != raw:
768
+ self._parse_content_type(raw)
769
+ return self._content_type # type: ignore[return-value]
770
+
771
+ @property
772
+ def charset(self) -> Optional[str]:
773
+ """The value of charset part for Content-Type HTTP header."""
774
+ raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined]
775
+ if self._stored_content_type != raw:
776
+ self._parse_content_type(raw)
777
+ return self._content_dict.get("charset") # type: ignore[union-attr]
778
+
779
+ @property
780
+ def content_length(self) -> Optional[int]:
781
+ """The value of Content-Length HTTP header."""
782
+ content_length = self._headers.get( # type: ignore[attr-defined]
783
+ hdrs.CONTENT_LENGTH
784
+ )
785
+
786
+ if content_length is not None:
787
+ return int(content_length)
788
+ else:
789
+ return None
790
+
791
+
792
+ def set_result(fut: "asyncio.Future[_T]", result: _T) -> None:
793
+ if not fut.done():
794
+ fut.set_result(result)
795
+
796
+
797
+ def set_exception(fut: "asyncio.Future[_T]", exc: BaseException) -> None:
798
+ if not fut.done():
799
+ fut.set_exception(exc)
800
+
801
+
802
+ class ChainMapProxy(Mapping[str, Any]):
803
+ __slots__ = ("_maps",)
804
+
805
+ def __init__(self, maps: Iterable[Mapping[str, Any]]) -> None:
806
+ self._maps = tuple(maps)
807
+
808
+ def __init_subclass__(cls) -> None:
809
+ raise TypeError(
810
+ "Inheritance class {} from ChainMapProxy "
811
+ "is forbidden".format(cls.__name__)
812
+ )
813
+
814
+ def __getitem__(self, key: str) -> Any:
815
+ for mapping in self._maps:
816
+ try:
817
+ return mapping[key]
818
+ except KeyError:
819
+ pass
820
+ raise KeyError(key)
821
+
822
+ def get(self, key: str, default: Any = None) -> Any:
823
+ return self[key] if key in self else default
824
+
825
+ def __len__(self) -> int:
826
+ # reuses stored hash values if possible
827
+ return len(set().union(*self._maps)) # type: ignore[arg-type]
828
+
829
+ def __iter__(self) -> Iterator[str]:
830
+ d: Dict[str, Any] = {}
831
+ for mapping in reversed(self._maps):
832
+ # reuses stored hash values if possible
833
+ d.update(mapping)
834
+ return iter(d)
835
+
836
+ def __contains__(self, key: object) -> bool:
837
+ return any(key in m for m in self._maps)
838
+
839
+ def __bool__(self) -> bool:
840
+ return any(self._maps)
841
+
842
+ def __repr__(self) -> str:
843
+ content = ", ".join(map(repr, self._maps))
844
+ return f"ChainMapProxy({content})"
845
+
846
+
847
+ # https://tools.ietf.org/html/rfc7232#section-2.3
848
+ _ETAGC = r"[!#-}\x80-\xff]+"
849
+ _ETAGC_RE = re.compile(_ETAGC)
850
+ _QUOTED_ETAG = rf'(W/)?"({_ETAGC})"'
851
+ QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG)
852
+ LIST_QUOTED_ETAG_RE = re.compile(rf"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)")
853
+
854
+ ETAG_ANY = "*"
855
+
856
+
857
+ @attr.s(auto_attribs=True, frozen=True, slots=True)
858
+ class ETag:
859
+ value: str
860
+ is_weak: bool = False
861
+
862
+
863
+ def validate_etag_value(value: str) -> None:
864
+ if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value):
865
+ raise ValueError(
866
+ f"Value {value!r} is not a valid etag. Maybe it contains '\"'?"
867
+ )
868
+
869
+
870
+ def parse_http_date(date_str: Optional[str]) -> Optional[datetime.datetime]:
871
+ """Process a date string, return a datetime object"""
872
+ if date_str is not None:
873
+ timetuple = parsedate(date_str)
874
+ if timetuple is not None:
875
+ with suppress(ValueError):
876
+ return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc)
877
+ return None
runtime/Lib/site-packages/aiohttp/http.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import http.server
2
+ import sys
3
+ from typing import Mapping, Tuple
4
+
5
+ from . import __version__
6
+ from .http_exceptions import HttpProcessingError as HttpProcessingError
7
+ from .http_parser import (
8
+ HeadersParser as HeadersParser,
9
+ HttpParser as HttpParser,
10
+ HttpRequestParser as HttpRequestParser,
11
+ HttpResponseParser as HttpResponseParser,
12
+ RawRequestMessage as RawRequestMessage,
13
+ RawResponseMessage as RawResponseMessage,
14
+ )
15
+ from .http_websocket import (
16
+ WS_CLOSED_MESSAGE as WS_CLOSED_MESSAGE,
17
+ WS_CLOSING_MESSAGE as WS_CLOSING_MESSAGE,
18
+ WS_KEY as WS_KEY,
19
+ WebSocketError as WebSocketError,
20
+ WebSocketReader as WebSocketReader,
21
+ WebSocketWriter as WebSocketWriter,
22
+ WSCloseCode as WSCloseCode,
23
+ WSMessage as WSMessage,
24
+ WSMsgType as WSMsgType,
25
+ ws_ext_gen as ws_ext_gen,
26
+ ws_ext_parse as ws_ext_parse,
27
+ )
28
+ from .http_writer import (
29
+ HttpVersion as HttpVersion,
30
+ HttpVersion10 as HttpVersion10,
31
+ HttpVersion11 as HttpVersion11,
32
+ StreamWriter as StreamWriter,
33
+ )
34
+
35
+ __all__ = (
36
+ "HttpProcessingError",
37
+ "RESPONSES",
38
+ "SERVER_SOFTWARE",
39
+ # .http_writer
40
+ "StreamWriter",
41
+ "HttpVersion",
42
+ "HttpVersion10",
43
+ "HttpVersion11",
44
+ # .http_parser
45
+ "HeadersParser",
46
+ "HttpParser",
47
+ "HttpRequestParser",
48
+ "HttpResponseParser",
49
+ "RawRequestMessage",
50
+ "RawResponseMessage",
51
+ # .http_websocket
52
+ "WS_CLOSED_MESSAGE",
53
+ "WS_CLOSING_MESSAGE",
54
+ "WS_KEY",
55
+ "WebSocketReader",
56
+ "WebSocketWriter",
57
+ "ws_ext_gen",
58
+ "ws_ext_parse",
59
+ "WSMessage",
60
+ "WebSocketError",
61
+ "WSMsgType",
62
+ "WSCloseCode",
63
+ )
64
+
65
+
66
+ SERVER_SOFTWARE: str = "Python/{0[0]}.{0[1]} aiohttp/{1}".format(
67
+ sys.version_info, __version__
68
+ )
69
+
70
+ RESPONSES: Mapping[int, Tuple[str, str]] = http.server.BaseHTTPRequestHandler.responses
runtime/Lib/site-packages/aiohttp/http_exceptions.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Low-level http related exceptions."""
2
+
3
+
4
+ from typing import Optional, Union
5
+
6
+ from .typedefs import _CIMultiDict
7
+
8
+ __all__ = ("HttpProcessingError",)
9
+
10
+
11
+ class HttpProcessingError(Exception):
12
+ """HTTP error.
13
+
14
+ Shortcut for raising HTTP errors with custom code, message and headers.
15
+
16
+ code: HTTP Error code.
17
+ message: (optional) Error message.
18
+ headers: (optional) Headers to be sent in response, a list of pairs
19
+ """
20
+
21
+ code = 0
22
+ message = ""
23
+ headers = None
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ code: Optional[int] = None,
29
+ message: str = "",
30
+ headers: Optional[_CIMultiDict] = None,
31
+ ) -> None:
32
+ if code is not None:
33
+ self.code = code
34
+ self.headers = headers
35
+ self.message = message
36
+
37
+ def __str__(self) -> str:
38
+ return f"{self.code}, message={self.message!r}"
39
+
40
+ def __repr__(self) -> str:
41
+ return f"<{self.__class__.__name__}: {self}>"
42
+
43
+
44
+ class BadHttpMessage(HttpProcessingError):
45
+
46
+ code = 400
47
+ message = "Bad Request"
48
+
49
+ def __init__(self, message: str, *, headers: Optional[_CIMultiDict] = None) -> None:
50
+ super().__init__(message=message, headers=headers)
51
+ self.args = (message,)
52
+
53
+
54
+ class HttpBadRequest(BadHttpMessage):
55
+
56
+ code = 400
57
+ message = "Bad Request"
58
+
59
+
60
+ class PayloadEncodingError(BadHttpMessage):
61
+ """Base class for payload errors"""
62
+
63
+
64
+ class ContentEncodingError(PayloadEncodingError):
65
+ """Content encoding error."""
66
+
67
+
68
+ class TransferEncodingError(PayloadEncodingError):
69
+ """transfer encoding error."""
70
+
71
+
72
+ class ContentLengthError(PayloadEncodingError):
73
+ """Not enough data for satisfy content length header."""
74
+
75
+
76
+ class LineTooLong(BadHttpMessage):
77
+ def __init__(
78
+ self, line: str, limit: str = "Unknown", actual_size: str = "Unknown"
79
+ ) -> None:
80
+ super().__init__(
81
+ f"Got more than {limit} bytes ({actual_size}) when reading {line}."
82
+ )
83
+ self.args = (line, limit, actual_size)
84
+
85
+
86
+ class InvalidHeader(BadHttpMessage):
87
+ def __init__(self, hdr: Union[bytes, str]) -> None:
88
+ if isinstance(hdr, bytes):
89
+ hdr = hdr.decode("utf-8", "surrogateescape")
90
+ super().__init__(f"Invalid HTTP Header: {hdr}")
91
+ self.hdr = hdr
92
+ self.args = (hdr,)
93
+
94
+
95
+ class BadStatusLine(BadHttpMessage):
96
+ def __init__(self, line: str = "") -> None:
97
+ if not isinstance(line, str):
98
+ line = repr(line)
99
+ super().__init__(f"Bad status line {line!r}")
100
+ self.args = (line,)
101
+ self.line = line
102
+
103
+
104
+ class InvalidURLError(BadHttpMessage):
105
+ pass
runtime/Lib/site-packages/aiohttp/http_parser.py ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import asyncio
3
+ import collections
4
+ import re
5
+ import string
6
+ import zlib
7
+ from contextlib import suppress
8
+ from enum import IntEnum
9
+ from typing import (
10
+ Any,
11
+ Generic,
12
+ List,
13
+ NamedTuple,
14
+ Optional,
15
+ Pattern,
16
+ Set,
17
+ Tuple,
18
+ Type,
19
+ TypeVar,
20
+ Union,
21
+ cast,
22
+ )
23
+
24
+ from multidict import CIMultiDict, CIMultiDictProxy, istr
25
+ from yarl import URL
26
+
27
+ from . import hdrs
28
+ from .base_protocol import BaseProtocol
29
+ from .helpers import NO_EXTENSIONS, BaseTimerContext
30
+ from .http_exceptions import (
31
+ BadHttpMessage,
32
+ BadStatusLine,
33
+ ContentEncodingError,
34
+ ContentLengthError,
35
+ InvalidHeader,
36
+ LineTooLong,
37
+ TransferEncodingError,
38
+ )
39
+ from .http_writer import HttpVersion, HttpVersion10
40
+ from .log import internal_logger
41
+ from .streams import EMPTY_PAYLOAD, StreamReader
42
+ from .typedefs import Final, RawHeaders
43
+
44
+ try:
45
+ import brotli
46
+
47
+ HAS_BROTLI = True
48
+ except ImportError: # pragma: no cover
49
+ HAS_BROTLI = False
50
+
51
+
52
+ __all__ = (
53
+ "HeadersParser",
54
+ "HttpParser",
55
+ "HttpRequestParser",
56
+ "HttpResponseParser",
57
+ "RawRequestMessage",
58
+ "RawResponseMessage",
59
+ )
60
+
61
+ ASCIISET: Final[Set[str]] = set(string.printable)
62
+
63
+ # See https://tools.ietf.org/html/rfc7230#section-3.1.1
64
+ # and https://tools.ietf.org/html/rfc7230#appendix-B
65
+ #
66
+ # method = token
67
+ # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
68
+ # "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
69
+ # token = 1*tchar
70
+ METHRE: Final[Pattern[str]] = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+")
71
+ VERSRE: Final[Pattern[str]] = re.compile(r"HTTP/(\d+).(\d+)")
72
+ HDRRE: Final[Pattern[bytes]] = re.compile(rb"[\x00-\x1F\x7F()<>@,;:\[\]={} \t\\\\\"]")
73
+
74
+
75
+ class RawRequestMessage(NamedTuple):
76
+ method: str
77
+ path: str
78
+ version: HttpVersion
79
+ headers: "CIMultiDictProxy[str]"
80
+ raw_headers: RawHeaders
81
+ should_close: bool
82
+ compression: Optional[str]
83
+ upgrade: bool
84
+ chunked: bool
85
+ url: URL
86
+
87
+
88
+ RawResponseMessage = collections.namedtuple(
89
+ "RawResponseMessage",
90
+ [
91
+ "version",
92
+ "code",
93
+ "reason",
94
+ "headers",
95
+ "raw_headers",
96
+ "should_close",
97
+ "compression",
98
+ "upgrade",
99
+ "chunked",
100
+ ],
101
+ )
102
+
103
+
104
+ _MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage)
105
+
106
+
107
+ class ParseState(IntEnum):
108
+
109
+ PARSE_NONE = 0
110
+ PARSE_LENGTH = 1
111
+ PARSE_CHUNKED = 2
112
+ PARSE_UNTIL_EOF = 3
113
+
114
+
115
+ class ChunkState(IntEnum):
116
+ PARSE_CHUNKED_SIZE = 0
117
+ PARSE_CHUNKED_CHUNK = 1
118
+ PARSE_CHUNKED_CHUNK_EOF = 2
119
+ PARSE_MAYBE_TRAILERS = 3
120
+ PARSE_TRAILERS = 4
121
+
122
+
123
+ class HeadersParser:
124
+ def __init__(
125
+ self,
126
+ max_line_size: int = 8190,
127
+ max_headers: int = 32768,
128
+ max_field_size: int = 8190,
129
+ ) -> None:
130
+ self.max_line_size = max_line_size
131
+ self.max_headers = max_headers
132
+ self.max_field_size = max_field_size
133
+
134
+ def parse_headers(
135
+ self, lines: List[bytes]
136
+ ) -> Tuple["CIMultiDictProxy[str]", RawHeaders]:
137
+ headers: CIMultiDict[str] = CIMultiDict()
138
+ raw_headers = []
139
+
140
+ lines_idx = 1
141
+ line = lines[1]
142
+ line_count = len(lines)
143
+
144
+ while line:
145
+ # Parse initial header name : value pair.
146
+ try:
147
+ bname, bvalue = line.split(b":", 1)
148
+ except ValueError:
149
+ raise InvalidHeader(line) from None
150
+
151
+ bname = bname.strip(b" \t")
152
+ bvalue = bvalue.lstrip()
153
+ if HDRRE.search(bname):
154
+ raise InvalidHeader(bname)
155
+ if len(bname) > self.max_field_size:
156
+ raise LineTooLong(
157
+ "request header name {}".format(
158
+ bname.decode("utf8", "xmlcharrefreplace")
159
+ ),
160
+ str(self.max_field_size),
161
+ str(len(bname)),
162
+ )
163
+
164
+ header_length = len(bvalue)
165
+
166
+ # next line
167
+ lines_idx += 1
168
+ line = lines[lines_idx]
169
+
170
+ # consume continuation lines
171
+ continuation = line and line[0] in (32, 9) # (' ', '\t')
172
+
173
+ if continuation:
174
+ bvalue_lst = [bvalue]
175
+ while continuation:
176
+ header_length += len(line)
177
+ if header_length > self.max_field_size:
178
+ raise LineTooLong(
179
+ "request header field {}".format(
180
+ bname.decode("utf8", "xmlcharrefreplace")
181
+ ),
182
+ str(self.max_field_size),
183
+ str(header_length),
184
+ )
185
+ bvalue_lst.append(line)
186
+
187
+ # next line
188
+ lines_idx += 1
189
+ if lines_idx < line_count:
190
+ line = lines[lines_idx]
191
+ if line:
192
+ continuation = line[0] in (32, 9) # (' ', '\t')
193
+ else:
194
+ line = b""
195
+ break
196
+ bvalue = b"".join(bvalue_lst)
197
+ else:
198
+ if header_length > self.max_field_size:
199
+ raise LineTooLong(
200
+ "request header field {}".format(
201
+ bname.decode("utf8", "xmlcharrefreplace")
202
+ ),
203
+ str(self.max_field_size),
204
+ str(header_length),
205
+ )
206
+
207
+ bvalue = bvalue.strip()
208
+ name = bname.decode("utf-8", "surrogateescape")
209
+ value = bvalue.decode("utf-8", "surrogateescape")
210
+
211
+ headers.add(name, value)
212
+ raw_headers.append((bname, bvalue))
213
+
214
+ return (CIMultiDictProxy(headers), tuple(raw_headers))
215
+
216
+
217
+ class HttpParser(abc.ABC, Generic[_MsgT]):
218
+ def __init__(
219
+ self,
220
+ protocol: Optional[BaseProtocol] = None,
221
+ loop: Optional[asyncio.AbstractEventLoop] = None,
222
+ limit: int = 2**16,
223
+ max_line_size: int = 8190,
224
+ max_headers: int = 32768,
225
+ max_field_size: int = 8190,
226
+ timer: Optional[BaseTimerContext] = None,
227
+ code: Optional[int] = None,
228
+ method: Optional[str] = None,
229
+ readall: bool = False,
230
+ payload_exception: Optional[Type[BaseException]] = None,
231
+ response_with_body: bool = True,
232
+ read_until_eof: bool = False,
233
+ auto_decompress: bool = True,
234
+ ) -> None:
235
+ self.protocol = protocol
236
+ self.loop = loop
237
+ self.max_line_size = max_line_size
238
+ self.max_headers = max_headers
239
+ self.max_field_size = max_field_size
240
+ self.timer = timer
241
+ self.code = code
242
+ self.method = method
243
+ self.readall = readall
244
+ self.payload_exception = payload_exception
245
+ self.response_with_body = response_with_body
246
+ self.read_until_eof = read_until_eof
247
+
248
+ self._lines: List[bytes] = []
249
+ self._tail = b""
250
+ self._upgraded = False
251
+ self._payload = None
252
+ self._payload_parser: Optional[HttpPayloadParser] = None
253
+ self._auto_decompress = auto_decompress
254
+ self._limit = limit
255
+ self._headers_parser = HeadersParser(max_line_size, max_headers, max_field_size)
256
+
257
+ @abc.abstractmethod
258
+ def parse_message(self, lines: List[bytes]) -> _MsgT:
259
+ pass
260
+
261
+ def feed_eof(self) -> Optional[_MsgT]:
262
+ if self._payload_parser is not None:
263
+ self._payload_parser.feed_eof()
264
+ self._payload_parser = None
265
+ else:
266
+ # try to extract partial message
267
+ if self._tail:
268
+ self._lines.append(self._tail)
269
+
270
+ if self._lines:
271
+ if self._lines[-1] != "\r\n":
272
+ self._lines.append(b"")
273
+ with suppress(Exception):
274
+ return self.parse_message(self._lines)
275
+ return None
276
+
277
+ def feed_data(
278
+ self,
279
+ data: bytes,
280
+ SEP: bytes = b"\r\n",
281
+ EMPTY: bytes = b"",
282
+ CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH,
283
+ METH_CONNECT: str = hdrs.METH_CONNECT,
284
+ SEC_WEBSOCKET_KEY1: istr = hdrs.SEC_WEBSOCKET_KEY1,
285
+ ) -> Tuple[List[Tuple[_MsgT, StreamReader]], bool, bytes]:
286
+
287
+ messages = []
288
+
289
+ if self._tail:
290
+ data, self._tail = self._tail + data, b""
291
+
292
+ data_len = len(data)
293
+ start_pos = 0
294
+ loop = self.loop
295
+
296
+ while start_pos < data_len:
297
+
298
+ # read HTTP message (request/response line + headers), \r\n\r\n
299
+ # and split by lines
300
+ if self._payload_parser is None and not self._upgraded:
301
+ pos = data.find(SEP, start_pos)
302
+ # consume \r\n
303
+ if pos == start_pos and not self._lines:
304
+ start_pos = pos + 2
305
+ continue
306
+
307
+ if pos >= start_pos:
308
+ # line found
309
+ self._lines.append(data[start_pos:pos])
310
+ start_pos = pos + 2
311
+
312
+ # \r\n\r\n found
313
+ if self._lines[-1] == EMPTY:
314
+ try:
315
+ msg: _MsgT = self.parse_message(self._lines)
316
+ finally:
317
+ self._lines.clear()
318
+
319
+ def get_content_length() -> Optional[int]:
320
+ # payload length
321
+ length_hdr = msg.headers.get(CONTENT_LENGTH)
322
+ if length_hdr is None:
323
+ return None
324
+
325
+ try:
326
+ length = int(length_hdr)
327
+ except ValueError:
328
+ raise InvalidHeader(CONTENT_LENGTH)
329
+
330
+ if length < 0:
331
+ raise InvalidHeader(CONTENT_LENGTH)
332
+
333
+ return length
334
+
335
+ length = get_content_length()
336
+ # do not support old websocket spec
337
+ if SEC_WEBSOCKET_KEY1 in msg.headers:
338
+ raise InvalidHeader(SEC_WEBSOCKET_KEY1)
339
+
340
+ self._upgraded = msg.upgrade
341
+
342
+ method = getattr(msg, "method", self.method)
343
+
344
+ assert self.protocol is not None
345
+ # calculate payload
346
+ if (
347
+ (length is not None and length > 0)
348
+ or msg.chunked
349
+ and not msg.upgrade
350
+ ):
351
+ payload = StreamReader(
352
+ self.protocol,
353
+ timer=self.timer,
354
+ loop=loop,
355
+ limit=self._limit,
356
+ )
357
+ payload_parser = HttpPayloadParser(
358
+ payload,
359
+ length=length,
360
+ chunked=msg.chunked,
361
+ method=method,
362
+ compression=msg.compression,
363
+ code=self.code,
364
+ readall=self.readall,
365
+ response_with_body=self.response_with_body,
366
+ auto_decompress=self._auto_decompress,
367
+ )
368
+ if not payload_parser.done:
369
+ self._payload_parser = payload_parser
370
+ elif method == METH_CONNECT:
371
+ assert isinstance(msg, RawRequestMessage)
372
+ payload = StreamReader(
373
+ self.protocol,
374
+ timer=self.timer,
375
+ loop=loop,
376
+ limit=self._limit,
377
+ )
378
+ self._upgraded = True
379
+ self._payload_parser = HttpPayloadParser(
380
+ payload,
381
+ method=msg.method,
382
+ compression=msg.compression,
383
+ readall=True,
384
+ auto_decompress=self._auto_decompress,
385
+ )
386
+ else:
387
+ if (
388
+ getattr(msg, "code", 100) >= 199
389
+ and length is None
390
+ and self.read_until_eof
391
+ ):
392
+ payload = StreamReader(
393
+ self.protocol,
394
+ timer=self.timer,
395
+ loop=loop,
396
+ limit=self._limit,
397
+ )
398
+ payload_parser = HttpPayloadParser(
399
+ payload,
400
+ length=length,
401
+ chunked=msg.chunked,
402
+ method=method,
403
+ compression=msg.compression,
404
+ code=self.code,
405
+ readall=True,
406
+ response_with_body=self.response_with_body,
407
+ auto_decompress=self._auto_decompress,
408
+ )
409
+ if not payload_parser.done:
410
+ self._payload_parser = payload_parser
411
+ else:
412
+ payload = EMPTY_PAYLOAD
413
+
414
+ messages.append((msg, payload))
415
+ else:
416
+ self._tail = data[start_pos:]
417
+ data = EMPTY
418
+ break
419
+
420
+ # no parser, just store
421
+ elif self._payload_parser is None and self._upgraded:
422
+ assert not self._lines
423
+ break
424
+
425
+ # feed payload
426
+ elif data and start_pos < data_len:
427
+ assert not self._lines
428
+ assert self._payload_parser is not None
429
+ try:
430
+ eof, data = self._payload_parser.feed_data(data[start_pos:])
431
+ except BaseException as exc:
432
+ if self.payload_exception is not None:
433
+ self._payload_parser.payload.set_exception(
434
+ self.payload_exception(str(exc))
435
+ )
436
+ else:
437
+ self._payload_parser.payload.set_exception(exc)
438
+
439
+ eof = True
440
+ data = b""
441
+
442
+ if eof:
443
+ start_pos = 0
444
+ data_len = len(data)
445
+ self._payload_parser = None
446
+ continue
447
+ else:
448
+ break
449
+
450
+ if data and start_pos < data_len:
451
+ data = data[start_pos:]
452
+ else:
453
+ data = EMPTY
454
+
455
+ return messages, self._upgraded, data
456
+
457
+ def parse_headers(
458
+ self, lines: List[bytes]
459
+ ) -> Tuple[
460
+ "CIMultiDictProxy[str]", RawHeaders, Optional[bool], Optional[str], bool, bool
461
+ ]:
462
+ """Parses RFC 5322 headers from a stream.
463
+
464
+ Line continuations are supported. Returns list of header name
465
+ and value pairs. Header name is in upper case.
466
+ """
467
+ headers, raw_headers = self._headers_parser.parse_headers(lines)
468
+ close_conn = None
469
+ encoding = None
470
+ upgrade = False
471
+ chunked = False
472
+
473
+ # keep-alive
474
+ conn = headers.get(hdrs.CONNECTION)
475
+ if conn:
476
+ v = conn.lower()
477
+ if v == "close":
478
+ close_conn = True
479
+ elif v == "keep-alive":
480
+ close_conn = False
481
+ elif v == "upgrade":
482
+ upgrade = True
483
+
484
+ # encoding
485
+ enc = headers.get(hdrs.CONTENT_ENCODING)
486
+ if enc:
487
+ enc = enc.lower()
488
+ if enc in ("gzip", "deflate", "br"):
489
+ encoding = enc
490
+
491
+ # chunking
492
+ te = headers.get(hdrs.TRANSFER_ENCODING)
493
+ if te is not None:
494
+ if "chunked" == te.lower():
495
+ chunked = True
496
+ else:
497
+ raise BadHttpMessage("Request has invalid `Transfer-Encoding`")
498
+
499
+ if hdrs.CONTENT_LENGTH in headers:
500
+ raise BadHttpMessage(
501
+ "Content-Length can't be present with Transfer-Encoding",
502
+ )
503
+
504
+ return (headers, raw_headers, close_conn, encoding, upgrade, chunked)
505
+
506
+ def set_upgraded(self, val: bool) -> None:
507
+ """Set connection upgraded (to websocket) mode.
508
+
509
+ :param bool val: new state.
510
+ """
511
+ self._upgraded = val
512
+
513
+
514
+ class HttpRequestParser(HttpParser[RawRequestMessage]):
515
+ """Read request status line.
516
+
517
+ Exception .http_exceptions.BadStatusLine
518
+ could be raised in case of any errors in status line.
519
+ Returns RawRequestMessage.
520
+ """
521
+
522
+ def parse_message(self, lines: List[bytes]) -> RawRequestMessage:
523
+ # request line
524
+ line = lines[0].decode("utf-8", "surrogateescape")
525
+ try:
526
+ method, path, version = line.split(None, 2)
527
+ except ValueError:
528
+ raise BadStatusLine(line) from None
529
+
530
+ if len(path) > self.max_line_size:
531
+ raise LineTooLong(
532
+ "Status line is too long", str(self.max_line_size), str(len(path))
533
+ )
534
+
535
+ # method
536
+ if not METHRE.match(method):
537
+ raise BadStatusLine(method)
538
+
539
+ # version
540
+ try:
541
+ if version.startswith("HTTP/"):
542
+ n1, n2 = version[5:].split(".", 1)
543
+ version_o = HttpVersion(int(n1), int(n2))
544
+ else:
545
+ raise BadStatusLine(version)
546
+ except Exception:
547
+ raise BadStatusLine(version)
548
+
549
+ if method == "CONNECT":
550
+ # authority-form,
551
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
552
+ url = URL.build(authority=path, encoded=True)
553
+ elif path.startswith("/"):
554
+ # origin-form,
555
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
556
+ path_part, _hash_separator, url_fragment = path.partition("#")
557
+ path_part, _question_mark_separator, qs_part = path_part.partition("?")
558
+
559
+ # NOTE: `yarl.URL.build()` is used to mimic what the Cython-based
560
+ # NOTE: parser does, otherwise it results into the same
561
+ # NOTE: HTTP Request-Line input producing different
562
+ # NOTE: `yarl.URL()` objects
563
+ url = URL.build(
564
+ path=path_part,
565
+ query_string=qs_part,
566
+ fragment=url_fragment,
567
+ encoded=True,
568
+ )
569
+ else:
570
+ # absolute-form for proxy maybe,
571
+ # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
572
+ url = URL(path, encoded=True)
573
+
574
+ # read headers
575
+ (
576
+ headers,
577
+ raw_headers,
578
+ close,
579
+ compression,
580
+ upgrade,
581
+ chunked,
582
+ ) = self.parse_headers(lines)
583
+
584
+ if close is None: # then the headers weren't set in the request
585
+ if version_o <= HttpVersion10: # HTTP 1.0 must asks to not close
586
+ close = True
587
+ else: # HTTP 1.1 must ask to close.
588
+ close = False
589
+
590
+ return RawRequestMessage(
591
+ method,
592
+ path,
593
+ version_o,
594
+ headers,
595
+ raw_headers,
596
+ close,
597
+ compression,
598
+ upgrade,
599
+ chunked,
600
+ url,
601
+ )
602
+
603
+
604
+ class HttpResponseParser(HttpParser[RawResponseMessage]):
605
+ """Read response status line and headers.
606
+
607
+ BadStatusLine could be raised in case of any errors in status line.
608
+ Returns RawResponseMessage.
609
+ """
610
+
611
+ def parse_message(self, lines: List[bytes]) -> RawResponseMessage:
612
+ line = lines[0].decode("utf-8", "surrogateescape")
613
+ try:
614
+ version, status = line.split(None, 1)
615
+ except ValueError:
616
+ raise BadStatusLine(line) from None
617
+
618
+ try:
619
+ status, reason = status.split(None, 1)
620
+ except ValueError:
621
+ reason = ""
622
+
623
+ if len(reason) > self.max_line_size:
624
+ raise LineTooLong(
625
+ "Status line is too long", str(self.max_line_size), str(len(reason))
626
+ )
627
+
628
+ # version
629
+ match = VERSRE.match(version)
630
+ if match is None:
631
+ raise BadStatusLine(line)
632
+ version_o = HttpVersion(int(match.group(1)), int(match.group(2)))
633
+
634
+ # The status code is a three-digit number
635
+ try:
636
+ status_i = int(status)
637
+ except ValueError:
638
+ raise BadStatusLine(line) from None
639
+
640
+ if status_i > 999:
641
+ raise BadStatusLine(line)
642
+
643
+ # read headers
644
+ (
645
+ headers,
646
+ raw_headers,
647
+ close,
648
+ compression,
649
+ upgrade,
650
+ chunked,
651
+ ) = self.parse_headers(lines)
652
+
653
+ if close is None:
654
+ close = version_o <= HttpVersion10
655
+
656
+ return RawResponseMessage(
657
+ version_o,
658
+ status_i,
659
+ reason.strip(),
660
+ headers,
661
+ raw_headers,
662
+ close,
663
+ compression,
664
+ upgrade,
665
+ chunked,
666
+ )
667
+
668
+
669
+ class HttpPayloadParser:
670
+ def __init__(
671
+ self,
672
+ payload: StreamReader,
673
+ length: Optional[int] = None,
674
+ chunked: bool = False,
675
+ compression: Optional[str] = None,
676
+ code: Optional[int] = None,
677
+ method: Optional[str] = None,
678
+ readall: bool = False,
679
+ response_with_body: bool = True,
680
+ auto_decompress: bool = True,
681
+ ) -> None:
682
+ self._length = 0
683
+ self._type = ParseState.PARSE_NONE
684
+ self._chunk = ChunkState.PARSE_CHUNKED_SIZE
685
+ self._chunk_size = 0
686
+ self._chunk_tail = b""
687
+ self._auto_decompress = auto_decompress
688
+ self.done = False
689
+
690
+ # payload decompression wrapper
691
+ if response_with_body and compression and self._auto_decompress:
692
+ real_payload: Union[StreamReader, DeflateBuffer] = DeflateBuffer(
693
+ payload, compression
694
+ )
695
+ else:
696
+ real_payload = payload
697
+
698
+ # payload parser
699
+ if not response_with_body:
700
+ # don't parse payload if it's not expected to be received
701
+ self._type = ParseState.PARSE_NONE
702
+ real_payload.feed_eof()
703
+ self.done = True
704
+
705
+ elif chunked:
706
+ self._type = ParseState.PARSE_CHUNKED
707
+ elif length is not None:
708
+ self._type = ParseState.PARSE_LENGTH
709
+ self._length = length
710
+ if self._length == 0:
711
+ real_payload.feed_eof()
712
+ self.done = True
713
+ else:
714
+ if readall and code != 204:
715
+ self._type = ParseState.PARSE_UNTIL_EOF
716
+ elif method in ("PUT", "POST"):
717
+ internal_logger.warning( # pragma: no cover
718
+ "Content-Length or Transfer-Encoding header is required"
719
+ )
720
+ self._type = ParseState.PARSE_NONE
721
+ real_payload.feed_eof()
722
+ self.done = True
723
+
724
+ self.payload = real_payload
725
+
726
+ def feed_eof(self) -> None:
727
+ if self._type == ParseState.PARSE_UNTIL_EOF:
728
+ self.payload.feed_eof()
729
+ elif self._type == ParseState.PARSE_LENGTH:
730
+ raise ContentLengthError(
731
+ "Not enough data for satisfy content length header."
732
+ )
733
+ elif self._type == ParseState.PARSE_CHUNKED:
734
+ raise TransferEncodingError(
735
+ "Not enough data for satisfy transfer length header."
736
+ )
737
+
738
+ def feed_data(
739
+ self, chunk: bytes, SEP: bytes = b"\r\n", CHUNK_EXT: bytes = b";"
740
+ ) -> Tuple[bool, bytes]:
741
+ # Read specified amount of bytes
742
+ if self._type == ParseState.PARSE_LENGTH:
743
+ required = self._length
744
+ chunk_len = len(chunk)
745
+
746
+ if required >= chunk_len:
747
+ self._length = required - chunk_len
748
+ self.payload.feed_data(chunk, chunk_len)
749
+ if self._length == 0:
750
+ self.payload.feed_eof()
751
+ return True, b""
752
+ else:
753
+ self._length = 0
754
+ self.payload.feed_data(chunk[:required], required)
755
+ self.payload.feed_eof()
756
+ return True, chunk[required:]
757
+
758
+ # Chunked transfer encoding parser
759
+ elif self._type == ParseState.PARSE_CHUNKED:
760
+ if self._chunk_tail:
761
+ chunk = self._chunk_tail + chunk
762
+ self._chunk_tail = b""
763
+
764
+ while chunk:
765
+
766
+ # read next chunk size
767
+ if self._chunk == ChunkState.PARSE_CHUNKED_SIZE:
768
+ pos = chunk.find(SEP)
769
+ if pos >= 0:
770
+ i = chunk.find(CHUNK_EXT, 0, pos)
771
+ if i >= 0:
772
+ size_b = chunk[:i] # strip chunk-extensions
773
+ else:
774
+ size_b = chunk[:pos]
775
+
776
+ try:
777
+ size = int(bytes(size_b), 16)
778
+ except ValueError:
779
+ exc = TransferEncodingError(
780
+ chunk[:pos].decode("ascii", "surrogateescape")
781
+ )
782
+ self.payload.set_exception(exc)
783
+ raise exc from None
784
+
785
+ chunk = chunk[pos + 2 :]
786
+ if size == 0: # eof marker
787
+ self._chunk = ChunkState.PARSE_MAYBE_TRAILERS
788
+ else:
789
+ self._chunk = ChunkState.PARSE_CHUNKED_CHUNK
790
+ self._chunk_size = size
791
+ self.payload.begin_http_chunk_receiving()
792
+ else:
793
+ self._chunk_tail = chunk
794
+ return False, b""
795
+
796
+ # read chunk and feed buffer
797
+ if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK:
798
+ required = self._chunk_size
799
+ chunk_len = len(chunk)
800
+
801
+ if required > chunk_len:
802
+ self._chunk_size = required - chunk_len
803
+ self.payload.feed_data(chunk, chunk_len)
804
+ return False, b""
805
+ else:
806
+ self._chunk_size = 0
807
+ self.payload.feed_data(chunk[:required], required)
808
+ chunk = chunk[required:]
809
+ self._chunk = ChunkState.PARSE_CHUNKED_CHUNK_EOF
810
+ self.payload.end_http_chunk_receiving()
811
+
812
+ # toss the CRLF at the end of the chunk
813
+ if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK_EOF:
814
+ if chunk[:2] == SEP:
815
+ chunk = chunk[2:]
816
+ self._chunk = ChunkState.PARSE_CHUNKED_SIZE
817
+ else:
818
+ self._chunk_tail = chunk
819
+ return False, b""
820
+
821
+ # if stream does not contain trailer, after 0\r\n
822
+ # we should get another \r\n otherwise
823
+ # trailers needs to be skiped until \r\n\r\n
824
+ if self._chunk == ChunkState.PARSE_MAYBE_TRAILERS:
825
+ head = chunk[:2]
826
+ if head == SEP:
827
+ # end of stream
828
+ self.payload.feed_eof()
829
+ return True, chunk[2:]
830
+ # Both CR and LF, or only LF may not be received yet. It is
831
+ # expected that CRLF or LF will be shown at the very first
832
+ # byte next time, otherwise trailers should come. The last
833
+ # CRLF which marks the end of response might not be
834
+ # contained in the same TCP segment which delivered the
835
+ # size indicator.
836
+ if not head:
837
+ return False, b""
838
+ if head == SEP[:1]:
839
+ self._chunk_tail = head
840
+ return False, b""
841
+ self._chunk = ChunkState.PARSE_TRAILERS
842
+
843
+ # read and discard trailer up to the CRLF terminator
844
+ if self._chunk == ChunkState.PARSE_TRAILERS:
845
+ pos = chunk.find(SEP)
846
+ if pos >= 0:
847
+ chunk = chunk[pos + 2 :]
848
+ self._chunk = ChunkState.PARSE_MAYBE_TRAILERS
849
+ else:
850
+ self._chunk_tail = chunk
851
+ return False, b""
852
+
853
+ # Read all bytes until eof
854
+ elif self._type == ParseState.PARSE_UNTIL_EOF:
855
+ self.payload.feed_data(chunk, len(chunk))
856
+
857
+ return False, b""
858
+
859
+
860
+ class DeflateBuffer:
861
+ """DeflateStream decompress stream and feed data into specified stream."""
862
+
863
+ decompressor: Any
864
+
865
+ def __init__(self, out: StreamReader, encoding: Optional[str]) -> None:
866
+ self.out = out
867
+ self.size = 0
868
+ self.encoding = encoding
869
+ self._started_decoding = False
870
+
871
+ if encoding == "br":
872
+ if not HAS_BROTLI: # pragma: no cover
873
+ raise ContentEncodingError(
874
+ "Can not decode content-encoding: brotli (br). "
875
+ "Please install `Brotli`"
876
+ )
877
+
878
+ class BrotliDecoder:
879
+ # Supports both 'brotlipy' and 'Brotli' packages
880
+ # since they share an import name. The top branches
881
+ # are for 'brotlipy' and bottom branches for 'Brotli'
882
+ def __init__(self) -> None:
883
+ self._obj = brotli.Decompressor()
884
+
885
+ def decompress(self, data: bytes) -> bytes:
886
+ if hasattr(self._obj, "decompress"):
887
+ return cast(bytes, self._obj.decompress(data))
888
+ return cast(bytes, self._obj.process(data))
889
+
890
+ def flush(self) -> bytes:
891
+ if hasattr(self._obj, "flush"):
892
+ return cast(bytes, self._obj.flush())
893
+ return b""
894
+
895
+ self.decompressor = BrotliDecoder()
896
+ else:
897
+ zlib_mode = 16 + zlib.MAX_WBITS if encoding == "gzip" else zlib.MAX_WBITS
898
+ self.decompressor = zlib.decompressobj(wbits=zlib_mode)
899
+
900
+ def set_exception(self, exc: BaseException) -> None:
901
+ self.out.set_exception(exc)
902
+
903
+ def feed_data(self, chunk: bytes, size: int) -> None:
904
+ if not size:
905
+ return
906
+
907
+ self.size += size
908
+
909
+ # RFC1950
910
+ # bits 0..3 = CM = 0b1000 = 8 = "deflate"
911
+ # bits 4..7 = CINFO = 1..7 = windows size.
912
+ if (
913
+ not self._started_decoding
914
+ and self.encoding == "deflate"
915
+ and chunk[0] & 0xF != 8
916
+ ):
917
+ # Change the decoder to decompress incorrectly compressed data
918
+ # Actually we should issue a warning about non-RFC-compliant data.
919
+ self.decompressor = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
920
+
921
+ try:
922
+ chunk = self.decompressor.decompress(chunk)
923
+ except Exception:
924
+ raise ContentEncodingError(
925
+ "Can not decode content-encoding: %s" % self.encoding
926
+ )
927
+
928
+ self._started_decoding = True
929
+
930
+ if chunk:
931
+ self.out.feed_data(chunk, len(chunk))
932
+
933
+ def feed_eof(self) -> None:
934
+ chunk = self.decompressor.flush()
935
+
936
+ if chunk or self.size > 0:
937
+ self.out.feed_data(chunk, len(chunk))
938
+ if self.encoding == "deflate" and not self.decompressor.eof:
939
+ raise ContentEncodingError("deflate")
940
+
941
+ self.out.feed_eof()
942
+
943
+ def begin_http_chunk_receiving(self) -> None:
944
+ self.out.begin_http_chunk_receiving()
945
+
946
+ def end_http_chunk_receiving(self) -> None:
947
+ self.out.end_http_chunk_receiving()
948
+
949
+
950
+ HttpRequestParserPy = HttpRequestParser
951
+ HttpResponseParserPy = HttpResponseParser
952
+ RawRequestMessagePy = RawRequestMessage
953
+ RawResponseMessagePy = RawResponseMessage
954
+
955
+ try:
956
+ if not NO_EXTENSIONS:
957
+ from ._http_parser import ( # type: ignore[import,no-redef]
958
+ HttpRequestParser,
959
+ HttpResponseParser,
960
+ RawRequestMessage,
961
+ RawResponseMessage,
962
+ )
963
+
964
+ HttpRequestParserC = HttpRequestParser
965
+ HttpResponseParserC = HttpResponseParser
966
+ RawRequestMessageC = RawRequestMessage
967
+ RawResponseMessageC = RawResponseMessage
968
+ except ImportError: # pragma: no cover
969
+ pass
runtime/Lib/site-packages/aiohttp/http_websocket.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebSocket protocol versions 13 and 8."""
2
+
3
+ import asyncio
4
+ import collections
5
+ import json
6
+ import random
7
+ import re
8
+ import sys
9
+ import zlib
10
+ from enum import IntEnum
11
+ from struct import Struct
12
+ from typing import Any, Callable, List, Optional, Pattern, Set, Tuple, Union, cast
13
+
14
+ from .base_protocol import BaseProtocol
15
+ from .helpers import NO_EXTENSIONS
16
+ from .streams import DataQueue
17
+ from .typedefs import Final
18
+
19
+ __all__ = (
20
+ "WS_CLOSED_MESSAGE",
21
+ "WS_CLOSING_MESSAGE",
22
+ "WS_KEY",
23
+ "WebSocketReader",
24
+ "WebSocketWriter",
25
+ "WSMessage",
26
+ "WebSocketError",
27
+ "WSMsgType",
28
+ "WSCloseCode",
29
+ )
30
+
31
+
32
+ class WSCloseCode(IntEnum):
33
+ OK = 1000
34
+ GOING_AWAY = 1001
35
+ PROTOCOL_ERROR = 1002
36
+ UNSUPPORTED_DATA = 1003
37
+ ABNORMAL_CLOSURE = 1006
38
+ INVALID_TEXT = 1007
39
+ POLICY_VIOLATION = 1008
40
+ MESSAGE_TOO_BIG = 1009
41
+ MANDATORY_EXTENSION = 1010
42
+ INTERNAL_ERROR = 1011
43
+ SERVICE_RESTART = 1012
44
+ TRY_AGAIN_LATER = 1013
45
+ BAD_GATEWAY = 1014
46
+
47
+
48
+ ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode}
49
+
50
+
51
+ class WSMsgType(IntEnum):
52
+ # websocket spec types
53
+ CONTINUATION = 0x0
54
+ TEXT = 0x1
55
+ BINARY = 0x2
56
+ PING = 0x9
57
+ PONG = 0xA
58
+ CLOSE = 0x8
59
+
60
+ # aiohttp specific types
61
+ CLOSING = 0x100
62
+ CLOSED = 0x101
63
+ ERROR = 0x102
64
+
65
+ text = TEXT
66
+ binary = BINARY
67
+ ping = PING
68
+ pong = PONG
69
+ close = CLOSE
70
+ closing = CLOSING
71
+ closed = CLOSED
72
+ error = ERROR
73
+
74
+
75
+ WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
76
+
77
+
78
+ UNPACK_LEN2 = Struct("!H").unpack_from
79
+ UNPACK_LEN3 = Struct("!Q").unpack_from
80
+ UNPACK_CLOSE_CODE = Struct("!H").unpack
81
+ PACK_LEN1 = Struct("!BB").pack
82
+ PACK_LEN2 = Struct("!BBH").pack
83
+ PACK_LEN3 = Struct("!BBQ").pack
84
+ PACK_CLOSE_CODE = Struct("!H").pack
85
+ MSG_SIZE: Final[int] = 2**14
86
+ DEFAULT_LIMIT: Final[int] = 2**16
87
+
88
+
89
+ _WSMessageBase = collections.namedtuple("_WSMessageBase", ["type", "data", "extra"])
90
+
91
+
92
+ class WSMessage(_WSMessageBase):
93
+ def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any:
94
+ """Return parsed JSON data.
95
+
96
+ .. versionadded:: 0.22
97
+ """
98
+ return loads(self.data)
99
+
100
+
101
+ WS_CLOSED_MESSAGE = WSMessage(WSMsgType.CLOSED, None, None)
102
+ WS_CLOSING_MESSAGE = WSMessage(WSMsgType.CLOSING, None, None)
103
+
104
+
105
+ class WebSocketError(Exception):
106
+ """WebSocket protocol parser error."""
107
+
108
+ def __init__(self, code: int, message: str) -> None:
109
+ self.code = code
110
+ super().__init__(code, message)
111
+
112
+ def __str__(self) -> str:
113
+ return cast(str, self.args[1])
114
+
115
+
116
+ class WSHandshakeError(Exception):
117
+ """WebSocket protocol handshake error."""
118
+
119
+
120
+ native_byteorder: Final[str] = sys.byteorder
121
+
122
+
123
+ # Used by _websocket_mask_python
124
+ _XOR_TABLE: Final[List[bytes]] = [bytes(a ^ b for a in range(256)) for b in range(256)]
125
+
126
+
127
+ def _websocket_mask_python(mask: bytes, data: bytearray) -> None:
128
+ """Websocket masking function.
129
+
130
+ `mask` is a `bytes` object of length 4; `data` is a `bytearray`
131
+ object of any length. The contents of `data` are masked with `mask`,
132
+ as specified in section 5.3 of RFC 6455.
133
+
134
+ Note that this function mutates the `data` argument.
135
+
136
+ This pure-python implementation may be replaced by an optimized
137
+ version when available.
138
+
139
+ """
140
+ assert isinstance(data, bytearray), data
141
+ assert len(mask) == 4, mask
142
+
143
+ if data:
144
+ a, b, c, d = (_XOR_TABLE[n] for n in mask)
145
+ data[::4] = data[::4].translate(a)
146
+ data[1::4] = data[1::4].translate(b)
147
+ data[2::4] = data[2::4].translate(c)
148
+ data[3::4] = data[3::4].translate(d)
149
+
150
+
151
+ if NO_EXTENSIONS: # pragma: no cover
152
+ _websocket_mask = _websocket_mask_python
153
+ else:
154
+ try:
155
+ from ._websocket import _websocket_mask_cython # type: ignore[import]
156
+
157
+ _websocket_mask = _websocket_mask_cython
158
+ except ImportError: # pragma: no cover
159
+ _websocket_mask = _websocket_mask_python
160
+
161
+ _WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF])
162
+
163
+
164
+ _WS_EXT_RE: Final[Pattern[str]] = re.compile(
165
+ r"^(?:;\s*(?:"
166
+ r"(server_no_context_takeover)|"
167
+ r"(client_no_context_takeover)|"
168
+ r"(server_max_window_bits(?:=(\d+))?)|"
169
+ r"(client_max_window_bits(?:=(\d+))?)))*$"
170
+ )
171
+
172
+ _WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?")
173
+
174
+
175
+ def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]:
176
+ if not extstr:
177
+ return 0, False
178
+
179
+ compress = 0
180
+ notakeover = False
181
+ for ext in _WS_EXT_RE_SPLIT.finditer(extstr):
182
+ defext = ext.group(1)
183
+ # Return compress = 15 when get `permessage-deflate`
184
+ if not defext:
185
+ compress = 15
186
+ break
187
+ match = _WS_EXT_RE.match(defext)
188
+ if match:
189
+ compress = 15
190
+ if isserver:
191
+ # Server never fail to detect compress handshake.
192
+ # Server does not need to send max wbit to client
193
+ if match.group(4):
194
+ compress = int(match.group(4))
195
+ # Group3 must match if group4 matches
196
+ # Compress wbit 8 does not support in zlib
197
+ # If compress level not support,
198
+ # CONTINUE to next extension
199
+ if compress > 15 or compress < 9:
200
+ compress = 0
201
+ continue
202
+ if match.group(1):
203
+ notakeover = True
204
+ # Ignore regex group 5 & 6 for client_max_window_bits
205
+ break
206
+ else:
207
+ if match.group(6):
208
+ compress = int(match.group(6))
209
+ # Group5 must match if group6 matches
210
+ # Compress wbit 8 does not support in zlib
211
+ # If compress level not support,
212
+ # FAIL the parse progress
213
+ if compress > 15 or compress < 9:
214
+ raise WSHandshakeError("Invalid window size")
215
+ if match.group(2):
216
+ notakeover = True
217
+ # Ignore regex group 5 & 6 for client_max_window_bits
218
+ break
219
+ # Return Fail if client side and not match
220
+ elif not isserver:
221
+ raise WSHandshakeError("Extension for deflate not supported" + ext.group(1))
222
+
223
+ return compress, notakeover
224
+
225
+
226
+ def ws_ext_gen(
227
+ compress: int = 15, isserver: bool = False, server_notakeover: bool = False
228
+ ) -> str:
229
+ # client_notakeover=False not used for server
230
+ # compress wbit 8 does not support in zlib
231
+ if compress < 9 or compress > 15:
232
+ raise ValueError(
233
+ "Compress wbits must between 9 and 15, " "zlib does not support wbits=8"
234
+ )
235
+ enabledext = ["permessage-deflate"]
236
+ if not isserver:
237
+ enabledext.append("client_max_window_bits")
238
+
239
+ if compress < 15:
240
+ enabledext.append("server_max_window_bits=" + str(compress))
241
+ if server_notakeover:
242
+ enabledext.append("server_no_context_takeover")
243
+ # if client_notakeover:
244
+ # enabledext.append('client_no_context_takeover')
245
+ return "; ".join(enabledext)
246
+
247
+
248
+ class WSParserState(IntEnum):
249
+ READ_HEADER = 1
250
+ READ_PAYLOAD_LENGTH = 2
251
+ READ_PAYLOAD_MASK = 3
252
+ READ_PAYLOAD = 4
253
+
254
+
255
+ class WebSocketReader:
256
+ def __init__(
257
+ self, queue: DataQueue[WSMessage], max_msg_size: int, compress: bool = True
258
+ ) -> None:
259
+ self.queue = queue
260
+ self._max_msg_size = max_msg_size
261
+
262
+ self._exc: Optional[BaseException] = None
263
+ self._partial = bytearray()
264
+ self._state = WSParserState.READ_HEADER
265
+
266
+ self._opcode: Optional[int] = None
267
+ self._frame_fin = False
268
+ self._frame_opcode: Optional[int] = None
269
+ self._frame_payload = bytearray()
270
+
271
+ self._tail = b""
272
+ self._has_mask = False
273
+ self._frame_mask: Optional[bytes] = None
274
+ self._payload_length = 0
275
+ self._payload_length_flag = 0
276
+ self._compressed: Optional[bool] = None
277
+ self._decompressobj: Any = None # zlib.decompressobj actually
278
+ self._compress = compress
279
+
280
+ def feed_eof(self) -> None:
281
+ self.queue.feed_eof()
282
+
283
+ def feed_data(self, data: bytes) -> Tuple[bool, bytes]:
284
+ if self._exc:
285
+ return True, data
286
+
287
+ try:
288
+ return self._feed_data(data)
289
+ except Exception as exc:
290
+ self._exc = exc
291
+ self.queue.set_exception(exc)
292
+ return True, b""
293
+
294
+ def _feed_data(self, data: bytes) -> Tuple[bool, bytes]:
295
+ for fin, opcode, payload, compressed in self.parse_frame(data):
296
+ if compressed and not self._decompressobj:
297
+ self._decompressobj = zlib.decompressobj(wbits=-zlib.MAX_WBITS)
298
+ if opcode == WSMsgType.CLOSE:
299
+ if len(payload) >= 2:
300
+ close_code = UNPACK_CLOSE_CODE(payload[:2])[0]
301
+ if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES:
302
+ raise WebSocketError(
303
+ WSCloseCode.PROTOCOL_ERROR,
304
+ f"Invalid close code: {close_code}",
305
+ )
306
+ try:
307
+ close_message = payload[2:].decode("utf-8")
308
+ except UnicodeDecodeError as exc:
309
+ raise WebSocketError(
310
+ WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message"
311
+ ) from exc
312
+ msg = WSMessage(WSMsgType.CLOSE, close_code, close_message)
313
+ elif payload:
314
+ raise WebSocketError(
315
+ WSCloseCode.PROTOCOL_ERROR,
316
+ f"Invalid close frame: {fin} {opcode} {payload!r}",
317
+ )
318
+ else:
319
+ msg = WSMessage(WSMsgType.CLOSE, 0, "")
320
+
321
+ self.queue.feed_data(msg, 0)
322
+
323
+ elif opcode == WSMsgType.PING:
324
+ self.queue.feed_data(
325
+ WSMessage(WSMsgType.PING, payload, ""), len(payload)
326
+ )
327
+
328
+ elif opcode == WSMsgType.PONG:
329
+ self.queue.feed_data(
330
+ WSMessage(WSMsgType.PONG, payload, ""), len(payload)
331
+ )
332
+
333
+ elif (
334
+ opcode not in (WSMsgType.TEXT, WSMsgType.BINARY)
335
+ and self._opcode is None
336
+ ):
337
+ raise WebSocketError(
338
+ WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}"
339
+ )
340
+ else:
341
+ # load text/binary
342
+ if not fin:
343
+ # got partial frame payload
344
+ if opcode != WSMsgType.CONTINUATION:
345
+ self._opcode = opcode
346
+ self._partial.extend(payload)
347
+ if self._max_msg_size and len(self._partial) >= self._max_msg_size:
348
+ raise WebSocketError(
349
+ WSCloseCode.MESSAGE_TOO_BIG,
350
+ "Message size {} exceeds limit {}".format(
351
+ len(self._partial), self._max_msg_size
352
+ ),
353
+ )
354
+ else:
355
+ # previous frame was non finished
356
+ # we should get continuation opcode
357
+ if self._partial:
358
+ if opcode != WSMsgType.CONTINUATION:
359
+ raise WebSocketError(
360
+ WSCloseCode.PROTOCOL_ERROR,
361
+ "The opcode in non-fin frame is expected "
362
+ "to be zero, got {!r}".format(opcode),
363
+ )
364
+
365
+ if opcode == WSMsgType.CONTINUATION:
366
+ assert self._opcode is not None
367
+ opcode = self._opcode
368
+ self._opcode = None
369
+
370
+ self._partial.extend(payload)
371
+ if self._max_msg_size and len(self._partial) >= self._max_msg_size:
372
+ raise WebSocketError(
373
+ WSCloseCode.MESSAGE_TOO_BIG,
374
+ "Message size {} exceeds limit {}".format(
375
+ len(self._partial), self._max_msg_size
376
+ ),
377
+ )
378
+
379
+ # Decompress process must to be done after all packets
380
+ # received.
381
+ if compressed:
382
+ self._partial.extend(_WS_DEFLATE_TRAILING)
383
+ payload_merged = self._decompressobj.decompress(
384
+ self._partial, self._max_msg_size
385
+ )
386
+ if self._decompressobj.unconsumed_tail:
387
+ left = len(self._decompressobj.unconsumed_tail)
388
+ raise WebSocketError(
389
+ WSCloseCode.MESSAGE_TOO_BIG,
390
+ "Decompressed message size {} exceeds limit {}".format(
391
+ self._max_msg_size + left, self._max_msg_size
392
+ ),
393
+ )
394
+ else:
395
+ payload_merged = bytes(self._partial)
396
+
397
+ self._partial.clear()
398
+
399
+ if opcode == WSMsgType.TEXT:
400
+ try:
401
+ text = payload_merged.decode("utf-8")
402
+ self.queue.feed_data(
403
+ WSMessage(WSMsgType.TEXT, text, ""), len(text)
404
+ )
405
+ except UnicodeDecodeError as exc:
406
+ raise WebSocketError(
407
+ WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message"
408
+ ) from exc
409
+ else:
410
+ self.queue.feed_data(
411
+ WSMessage(WSMsgType.BINARY, payload_merged, ""),
412
+ len(payload_merged),
413
+ )
414
+
415
+ return False, b""
416
+
417
+ def parse_frame(
418
+ self, buf: bytes
419
+ ) -> List[Tuple[bool, Optional[int], bytearray, Optional[bool]]]:
420
+ """Return the next frame from the socket."""
421
+ frames = []
422
+ if self._tail:
423
+ buf, self._tail = self._tail + buf, b""
424
+
425
+ start_pos = 0
426
+ buf_length = len(buf)
427
+
428
+ while True:
429
+ # read header
430
+ if self._state == WSParserState.READ_HEADER:
431
+ if buf_length - start_pos >= 2:
432
+ data = buf[start_pos : start_pos + 2]
433
+ start_pos += 2
434
+ first_byte, second_byte = data
435
+
436
+ fin = (first_byte >> 7) & 1
437
+ rsv1 = (first_byte >> 6) & 1
438
+ rsv2 = (first_byte >> 5) & 1
439
+ rsv3 = (first_byte >> 4) & 1
440
+ opcode = first_byte & 0xF
441
+
442
+ # frame-fin = %x0 ; more frames of this message follow
443
+ # / %x1 ; final frame of this message
444
+ # frame-rsv1 = %x0 ;
445
+ # 1 bit, MUST be 0 unless negotiated otherwise
446
+ # frame-rsv2 = %x0 ;
447
+ # 1 bit, MUST be 0 unless negotiated otherwise
448
+ # frame-rsv3 = %x0 ;
449
+ # 1 bit, MUST be 0 unless negotiated otherwise
450
+ #
451
+ # Remove rsv1 from this test for deflate development
452
+ if rsv2 or rsv3 or (rsv1 and not self._compress):
453
+ raise WebSocketError(
454
+ WSCloseCode.PROTOCOL_ERROR,
455
+ "Received frame with non-zero reserved bits",
456
+ )
457
+
458
+ if opcode > 0x7 and fin == 0:
459
+ raise WebSocketError(
460
+ WSCloseCode.PROTOCOL_ERROR,
461
+ "Received fragmented control frame",
462
+ )
463
+
464
+ has_mask = (second_byte >> 7) & 1
465
+ length = second_byte & 0x7F
466
+
467
+ # Control frames MUST have a payload
468
+ # length of 125 bytes or less
469
+ if opcode > 0x7 and length > 125:
470
+ raise WebSocketError(
471
+ WSCloseCode.PROTOCOL_ERROR,
472
+ "Control frame payload cannot be " "larger than 125 bytes",
473
+ )
474
+
475
+ # Set compress status if last package is FIN
476
+ # OR set compress status if this is first fragment
477
+ # Raise error if not first fragment with rsv1 = 0x1
478
+ if self._frame_fin or self._compressed is None:
479
+ self._compressed = True if rsv1 else False
480
+ elif rsv1:
481
+ raise WebSocketError(
482
+ WSCloseCode.PROTOCOL_ERROR,
483
+ "Received frame with non-zero reserved bits",
484
+ )
485
+
486
+ self._frame_fin = bool(fin)
487
+ self._frame_opcode = opcode
488
+ self._has_mask = bool(has_mask)
489
+ self._payload_length_flag = length
490
+ self._state = WSParserState.READ_PAYLOAD_LENGTH
491
+ else:
492
+ break
493
+
494
+ # read payload length
495
+ if self._state == WSParserState.READ_PAYLOAD_LENGTH:
496
+ length = self._payload_length_flag
497
+ if length == 126:
498
+ if buf_length - start_pos >= 2:
499
+ data = buf[start_pos : start_pos + 2]
500
+ start_pos += 2
501
+ length = UNPACK_LEN2(data)[0]
502
+ self._payload_length = length
503
+ self._state = (
504
+ WSParserState.READ_PAYLOAD_MASK
505
+ if self._has_mask
506
+ else WSParserState.READ_PAYLOAD
507
+ )
508
+ else:
509
+ break
510
+ elif length > 126:
511
+ if buf_length - start_pos >= 8:
512
+ data = buf[start_pos : start_pos + 8]
513
+ start_pos += 8
514
+ length = UNPACK_LEN3(data)[0]
515
+ self._payload_length = length
516
+ self._state = (
517
+ WSParserState.READ_PAYLOAD_MASK
518
+ if self._has_mask
519
+ else WSParserState.READ_PAYLOAD
520
+ )
521
+ else:
522
+ break
523
+ else:
524
+ self._payload_length = length
525
+ self._state = (
526
+ WSParserState.READ_PAYLOAD_MASK
527
+ if self._has_mask
528
+ else WSParserState.READ_PAYLOAD
529
+ )
530
+
531
+ # read payload mask
532
+ if self._state == WSParserState.READ_PAYLOAD_MASK:
533
+ if buf_length - start_pos >= 4:
534
+ self._frame_mask = buf[start_pos : start_pos + 4]
535
+ start_pos += 4
536
+ self._state = WSParserState.READ_PAYLOAD
537
+ else:
538
+ break
539
+
540
+ if self._state == WSParserState.READ_PAYLOAD:
541
+ length = self._payload_length
542
+ payload = self._frame_payload
543
+
544
+ chunk_len = buf_length - start_pos
545
+ if length >= chunk_len:
546
+ self._payload_length = length - chunk_len
547
+ payload.extend(buf[start_pos:])
548
+ start_pos = buf_length
549
+ else:
550
+ self._payload_length = 0
551
+ payload.extend(buf[start_pos : start_pos + length])
552
+ start_pos = start_pos + length
553
+
554
+ if self._payload_length == 0:
555
+ if self._has_mask:
556
+ assert self._frame_mask is not None
557
+ _websocket_mask(self._frame_mask, payload)
558
+
559
+ frames.append(
560
+ (self._frame_fin, self._frame_opcode, payload, self._compressed)
561
+ )
562
+
563
+ self._frame_payload = bytearray()
564
+ self._state = WSParserState.READ_HEADER
565
+ else:
566
+ break
567
+
568
+ self._tail = buf[start_pos:]
569
+
570
+ return frames
571
+
572
+
573
+ class WebSocketWriter:
574
+ def __init__(
575
+ self,
576
+ protocol: BaseProtocol,
577
+ transport: asyncio.Transport,
578
+ *,
579
+ use_mask: bool = False,
580
+ limit: int = DEFAULT_LIMIT,
581
+ random: Any = random.Random(),
582
+ compress: int = 0,
583
+ notakeover: bool = False,
584
+ ) -> None:
585
+ self.protocol = protocol
586
+ self.transport = transport
587
+ self.use_mask = use_mask
588
+ self.randrange = random.randrange
589
+ self.compress = compress
590
+ self.notakeover = notakeover
591
+ self._closing = False
592
+ self._limit = limit
593
+ self._output_size = 0
594
+ self._compressobj: Any = None # actually compressobj
595
+
596
+ async def _send_frame(
597
+ self, message: bytes, opcode: int, compress: Optional[int] = None
598
+ ) -> None:
599
+ """Send a frame over the websocket with message as its payload."""
600
+ if self._closing and not (opcode & WSMsgType.CLOSE):
601
+ raise ConnectionResetError("Cannot write to closing transport")
602
+
603
+ rsv = 0
604
+
605
+ # Only compress larger packets (disabled)
606
+ # Does small packet needs to be compressed?
607
+ # if self.compress and opcode < 8 and len(message) > 124:
608
+ if (compress or self.compress) and opcode < 8:
609
+ if compress:
610
+ # Do not set self._compress if compressing is for this frame
611
+ compressobj = zlib.compressobj(level=zlib.Z_BEST_SPEED, wbits=-compress)
612
+ else: # self.compress
613
+ if not self._compressobj:
614
+ self._compressobj = zlib.compressobj(
615
+ level=zlib.Z_BEST_SPEED, wbits=-self.compress
616
+ )
617
+ compressobj = self._compressobj
618
+
619
+ message = compressobj.compress(message)
620
+ message = message + compressobj.flush(
621
+ zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH
622
+ )
623
+ if message.endswith(_WS_DEFLATE_TRAILING):
624
+ message = message[:-4]
625
+ rsv = rsv | 0x40
626
+
627
+ msg_length = len(message)
628
+
629
+ use_mask = self.use_mask
630
+ if use_mask:
631
+ mask_bit = 0x80
632
+ else:
633
+ mask_bit = 0
634
+
635
+ if msg_length < 126:
636
+ header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit)
637
+ elif msg_length < (1 << 16):
638
+ header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length)
639
+ else:
640
+ header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length)
641
+ if use_mask:
642
+ mask = self.randrange(0, 0xFFFFFFFF)
643
+ mask = mask.to_bytes(4, "big")
644
+ message = bytearray(message)
645
+ _websocket_mask(mask, message)
646
+ self._write(header + mask + message)
647
+ self._output_size += len(header) + len(mask) + len(message)
648
+ else:
649
+ if len(message) > MSG_SIZE:
650
+ self._write(header)
651
+ self._write(message)
652
+ else:
653
+ self._write(header + message)
654
+
655
+ self._output_size += len(header) + len(message)
656
+
657
+ if self._output_size > self._limit:
658
+ self._output_size = 0
659
+ await self.protocol._drain_helper()
660
+
661
+ def _write(self, data: bytes) -> None:
662
+ if self.transport is None or self.transport.is_closing():
663
+ raise ConnectionResetError("Cannot write to closing transport")
664
+ self.transport.write(data)
665
+
666
+ async def pong(self, message: bytes = b"") -> None:
667
+ """Send pong message."""
668
+ if isinstance(message, str):
669
+ message = message.encode("utf-8")
670
+ await self._send_frame(message, WSMsgType.PONG)
671
+
672
+ async def ping(self, message: bytes = b"") -> None:
673
+ """Send ping message."""
674
+ if isinstance(message, str):
675
+ message = message.encode("utf-8")
676
+ await self._send_frame(message, WSMsgType.PING)
677
+
678
+ async def send(
679
+ self,
680
+ message: Union[str, bytes],
681
+ binary: bool = False,
682
+ compress: Optional[int] = None,
683
+ ) -> None:
684
+ """Send a frame over the websocket with message as its payload."""
685
+ if isinstance(message, str):
686
+ message = message.encode("utf-8")
687
+ if binary:
688
+ await self._send_frame(message, WSMsgType.BINARY, compress)
689
+ else:
690
+ await self._send_frame(message, WSMsgType.TEXT, compress)
691
+
692
+ async def close(self, code: int = 1000, message: bytes = b"") -> None:
693
+ """Close the websocket, sending the specified code and message."""
694
+ if isinstance(message, str):
695
+ message = message.encode("utf-8")
696
+ try:
697
+ await self._send_frame(
698
+ PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE
699
+ )
700
+ finally:
701
+ self._closing = True
runtime/Lib/site-packages/aiohttp/http_writer.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Http related parsers and protocol."""
2
+
3
+ import asyncio
4
+ import zlib
5
+ from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa
6
+
7
+ from multidict import CIMultiDict
8
+
9
+ from .abc import AbstractStreamWriter
10
+ from .base_protocol import BaseProtocol
11
+ from .helpers import NO_EXTENSIONS
12
+
13
+ __all__ = ("StreamWriter", "HttpVersion", "HttpVersion10", "HttpVersion11")
14
+
15
+
16
+ class HttpVersion(NamedTuple):
17
+ major: int
18
+ minor: int
19
+
20
+
21
+ HttpVersion10 = HttpVersion(1, 0)
22
+ HttpVersion11 = HttpVersion(1, 1)
23
+
24
+
25
+ _T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]]
26
+ _T_OnHeadersSent = Optional[Callable[["CIMultiDict[str]"], Awaitable[None]]]
27
+
28
+
29
+ class StreamWriter(AbstractStreamWriter):
30
+ def __init__(
31
+ self,
32
+ protocol: BaseProtocol,
33
+ loop: asyncio.AbstractEventLoop,
34
+ on_chunk_sent: _T_OnChunkSent = None,
35
+ on_headers_sent: _T_OnHeadersSent = None,
36
+ ) -> None:
37
+ self._protocol = protocol
38
+ self._transport = protocol.transport
39
+
40
+ self.loop = loop
41
+ self.length = None
42
+ self.chunked = False
43
+ self.buffer_size = 0
44
+ self.output_size = 0
45
+
46
+ self._eof = False
47
+ self._compress: Any = None
48
+ self._drain_waiter = None
49
+
50
+ self._on_chunk_sent: _T_OnChunkSent = on_chunk_sent
51
+ self._on_headers_sent: _T_OnHeadersSent = on_headers_sent
52
+
53
+ @property
54
+ def transport(self) -> Optional[asyncio.Transport]:
55
+ return self._transport
56
+
57
+ @property
58
+ def protocol(self) -> BaseProtocol:
59
+ return self._protocol
60
+
61
+ def enable_chunking(self) -> None:
62
+ self.chunked = True
63
+
64
+ def enable_compression(
65
+ self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY
66
+ ) -> None:
67
+ zlib_mode = 16 + zlib.MAX_WBITS if encoding == "gzip" else zlib.MAX_WBITS
68
+ self._compress = zlib.compressobj(wbits=zlib_mode, strategy=strategy)
69
+
70
+ def _write(self, chunk: bytes) -> None:
71
+ size = len(chunk)
72
+ self.buffer_size += size
73
+ self.output_size += size
74
+
75
+ if self._transport is None or self._transport.is_closing():
76
+ raise ConnectionResetError("Cannot write to closing transport")
77
+ self._transport.write(chunk)
78
+
79
+ async def write(
80
+ self, chunk: bytes, *, drain: bool = True, LIMIT: int = 0x10000
81
+ ) -> None:
82
+ """Writes chunk of data to a stream.
83
+
84
+ write_eof() indicates end of stream.
85
+ writer can't be used after write_eof() method being called.
86
+ write() return drain future.
87
+ """
88
+ if self._on_chunk_sent is not None:
89
+ await self._on_chunk_sent(chunk)
90
+
91
+ if isinstance(chunk, memoryview):
92
+ if chunk.nbytes != len(chunk):
93
+ # just reshape it
94
+ chunk = chunk.cast("c")
95
+
96
+ if self._compress is not None:
97
+ chunk = self._compress.compress(chunk)
98
+ if not chunk:
99
+ return
100
+
101
+ if self.length is not None:
102
+ chunk_len = len(chunk)
103
+ if self.length >= chunk_len:
104
+ self.length = self.length - chunk_len
105
+ else:
106
+ chunk = chunk[: self.length]
107
+ self.length = 0
108
+ if not chunk:
109
+ return
110
+
111
+ if chunk:
112
+ if self.chunked:
113
+ chunk_len_pre = ("%x\r\n" % len(chunk)).encode("ascii")
114
+ chunk = chunk_len_pre + chunk + b"\r\n"
115
+
116
+ self._write(chunk)
117
+
118
+ if self.buffer_size > LIMIT and drain:
119
+ self.buffer_size = 0
120
+ await self.drain()
121
+
122
+ async def write_headers(
123
+ self, status_line: str, headers: "CIMultiDict[str]"
124
+ ) -> None:
125
+ """Write request/response status and headers."""
126
+ if self._on_headers_sent is not None:
127
+ await self._on_headers_sent(headers)
128
+
129
+ # status + headers
130
+ buf = _serialize_headers(status_line, headers)
131
+ self._write(buf)
132
+
133
+ async def write_eof(self, chunk: bytes = b"") -> None:
134
+ if self._eof:
135
+ return
136
+
137
+ if chunk and self._on_chunk_sent is not None:
138
+ await self._on_chunk_sent(chunk)
139
+
140
+ if self._compress:
141
+ if chunk:
142
+ chunk = self._compress.compress(chunk)
143
+
144
+ chunk = chunk + self._compress.flush()
145
+ if chunk and self.chunked:
146
+ chunk_len = ("%x\r\n" % len(chunk)).encode("ascii")
147
+ chunk = chunk_len + chunk + b"\r\n0\r\n\r\n"
148
+ else:
149
+ if self.chunked:
150
+ if chunk:
151
+ chunk_len = ("%x\r\n" % len(chunk)).encode("ascii")
152
+ chunk = chunk_len + chunk + b"\r\n0\r\n\r\n"
153
+ else:
154
+ chunk = b"0\r\n\r\n"
155
+
156
+ if chunk:
157
+ self._write(chunk)
158
+
159
+ await self.drain()
160
+
161
+ self._eof = True
162
+ self._transport = None
163
+
164
+ async def drain(self) -> None:
165
+ """Flush the write buffer.
166
+
167
+ The intended use is to write
168
+
169
+ await w.write(data)
170
+ await w.drain()
171
+ """
172
+ if self._protocol.transport is not None:
173
+ await self._protocol._drain_helper()
174
+
175
+
176
+ def _safe_header(string: str) -> str:
177
+ if "\r" in string or "\n" in string:
178
+ raise ValueError(
179
+ "Newline or carriage return detected in headers. "
180
+ "Potential header injection attack."
181
+ )
182
+ return string
183
+
184
+
185
+ def _py_serialize_headers(status_line: str, headers: "CIMultiDict[str]") -> bytes:
186
+ headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items())
187
+ line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n"
188
+ return line.encode("utf-8")
189
+
190
+
191
+ _serialize_headers = _py_serialize_headers
192
+
193
+ try:
194
+ import aiohttp._http_writer as _http_writer # type: ignore[import]
195
+
196
+ _c_serialize_headers = _http_writer._serialize_headers
197
+ if not NO_EXTENSIONS:
198
+ _serialize_headers = _c_serialize_headers
199
+ except ImportError:
200
+ pass