2016-04-19 06:31:43 -04:00
|
|
|
# Copyright 2014-2016 OpenMarket Ltd
|
2021-01-15 10:57:37 -05:00
|
|
|
# Copyright 2019-2021 The Matrix.org Foundation C.I.C.
|
2016-04-19 06:31:43 -04:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2018-07-09 02:09:20 -04:00
|
|
|
import logging
|
|
|
|
import os
|
2020-06-16 08:51:47 -04:00
|
|
|
import urllib
|
Use mypy 1.0 (#15052)
* Update mypy and mypy-zope
* Remove unused ignores
These used to suppress
```
synapse/storage/engines/__init__.py:28: error: "__new__" must return a
class instance (got "NoReturn") [misc]
```
and
```
synapse/http/matrixfederationclient.py:1270: error: "BaseException" has no attribute "reasons" [attr-defined]
```
(note that we check `hasattr(e, "reasons")` above)
* Avoid empty body warnings, sometimes by marking methods as abstract
E.g.
```
tests/handlers/test_register.py:58: error: Missing return statement [empty-body]
tests/handlers/test_register.py:108: error: Missing return statement [empty-body]
```
* Suppress false positive about `JaegerConfig`
Complaint was
```
synapse/logging/opentracing.py:450: error: Function "Type[Config]" could always be true in boolean context [truthy-function]
```
* Fix not calling `is_state()`
Oops!
```
tests/rest/client/test_third_party_rules.py:428: error: Function "Callable[[], bool]" could always be true in boolean context [truthy-function]
```
* Suppress false positives from ParamSpecs
````
synapse/logging/opentracing.py:971: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
synapse/logging/opentracing.py:1017: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
````
* Drive-by improvement to `wrapping_logic` annotation
* Workaround false "unreachable" positives
See https://github.com/Shoobx/mypy-zope/issues/91
```
tests/http/test_proxyagent.py:626: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:762: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:826: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:838: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:845: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:151: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:452: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:60: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:93: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:127: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:152: error: Statement is unreachable [unreachable]
```
* Changelog
* Tweak DBAPI2 Protocol to be accepted by mypy 1.0
Some extra context in:
- https://github.com/matrix-org/python-canonicaljson/pull/57
- https://github.com/python/mypy/issues/6002
- https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
* Pull in updated canonicaljson lib
so the protocol check just works
* Improve comments in opentracing
I tried to workaround the ignores but found it too much trouble.
I think the corresponding issue is
https://github.com/python/mypy/issues/12909. The mypy repo has a PR
claiming to fix this (https://github.com/python/mypy/pull/14677) which
might mean this gets resolved soon?
* Better annotation for INTERACTIVE_AUTH_CHECKERS
* Drive-by AUTH_TYPE annotation, to remove an ignore
2023-02-16 11:09:11 -05:00
|
|
|
from abc import ABC, abstractmethod
|
2021-09-15 08:45:32 -04:00
|
|
|
from types import TracebackType
|
|
|
|
from typing import Awaitable, Dict, Generator, List, Optional, Tuple, Type
|
2016-04-19 06:31:43 -04:00
|
|
|
|
2021-09-14 07:09:38 -04:00
|
|
|
import attr
|
|
|
|
|
2020-07-27 14:40:11 -04:00
|
|
|
from twisted.internet.interfaces import IConsumer
|
2016-04-19 06:31:43 -04:00
|
|
|
from twisted.protocols.basic import FileSender
|
2021-03-01 12:23:46 -05:00
|
|
|
from twisted.web.server import Request
|
2016-04-19 06:31:43 -04:00
|
|
|
|
2018-07-09 02:09:20 -04:00
|
|
|
from synapse.api.errors import Codes, SynapseError, cs_error
|
|
|
|
from synapse.http.server import finish_request, respond_with_json
|
2021-09-24 06:01:25 -04:00
|
|
|
from synapse.http.site import SynapseRequest
|
2019-07-03 10:07:04 -04:00
|
|
|
from synapse.logging.context import make_deferred_yieldable
|
2021-11-19 08:39:15 -05:00
|
|
|
from synapse.util.stringutils import is_ascii, parse_and_validate_server_name
|
2016-04-19 06:31:43 -04:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-03-17 09:29:09 -04:00
|
|
|
# list all text content types that will have the charset default to UTF-8 when
|
|
|
|
# none is given
|
|
|
|
TEXT_CONTENT_TYPES = [
|
|
|
|
"text/css",
|
|
|
|
"text/csv",
|
|
|
|
"text/html",
|
|
|
|
"text/calendar",
|
|
|
|
"text/plain",
|
|
|
|
"text/javascript",
|
|
|
|
"application/json",
|
|
|
|
"application/ld+json",
|
|
|
|
"application/rtf",
|
|
|
|
"image/svg+xml",
|
|
|
|
"text/xml",
|
|
|
|
]
|
|
|
|
|
2016-04-19 06:31:43 -04:00
|
|
|
|
2021-01-15 10:57:37 -05:00
|
|
|
def parse_media_id(request: Request) -> Tuple[str, str, Optional[str]]:
|
2021-11-19 08:39:15 -05:00
|
|
|
"""Parses the server name, media ID and optional file name from the request URI
|
|
|
|
|
|
|
|
Also performs some rough validation on the server name.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
request: The `Request`.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A tuple containing the parsed server name, media ID and optional file name.
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
SynapseError(404): if parsing or validation fail for any reason
|
|
|
|
"""
|
2016-04-19 06:31:43 -04:00
|
|
|
try:
|
2021-03-01 12:23:46 -05:00
|
|
|
# The type on postpath seems incorrect in Twisted 21.2.0.
|
2021-07-16 13:22:36 -04:00
|
|
|
postpath: List[bytes] = request.postpath # type: ignore
|
2021-03-01 12:23:46 -05:00
|
|
|
assert postpath
|
|
|
|
|
2016-04-19 06:31:43 -04:00
|
|
|
# This allows users to append e.g. /test.png to the URL. Useful for
|
|
|
|
# clients that parse the URL to see content type.
|
2021-03-01 12:23:46 -05:00
|
|
|
server_name_bytes, media_id_bytes = postpath[:2]
|
|
|
|
server_name = server_name_bytes.decode("utf-8")
|
|
|
|
media_id = media_id_bytes.decode("utf8")
|
2018-09-12 06:41:31 -04:00
|
|
|
|
2021-11-19 08:39:15 -05:00
|
|
|
# Validate the server name, raising if invalid
|
|
|
|
parse_and_validate_server_name(server_name)
|
|
|
|
|
2016-04-19 06:31:43 -04:00
|
|
|
file_name = None
|
2021-03-01 12:23:46 -05:00
|
|
|
if len(postpath) > 2:
|
2016-04-19 06:31:43 -04:00
|
|
|
try:
|
2021-03-01 12:23:46 -05:00
|
|
|
file_name = urllib.parse.unquote(postpath[-1].decode("utf-8"))
|
2016-04-19 06:31:43 -04:00
|
|
|
except UnicodeDecodeError:
|
|
|
|
pass
|
|
|
|
return server_name, media_id, file_name
|
2017-10-23 10:52:32 -04:00
|
|
|
except Exception:
|
2016-04-19 06:31:43 -04:00
|
|
|
raise SynapseError(
|
2018-11-15 16:55:58 -05:00
|
|
|
404, "Invalid media id token %r" % (request.postpath,), Codes.UNKNOWN
|
2016-04-19 06:31:43 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-09-24 06:01:25 -04:00
|
|
|
def respond_404(request: SynapseRequest) -> None:
|
2016-04-19 06:31:43 -04:00
|
|
|
respond_with_json(
|
2018-11-15 16:55:58 -05:00
|
|
|
request,
|
|
|
|
404,
|
|
|
|
cs_error("Not found %r" % (request.postpath,), code=Codes.NOT_FOUND),
|
|
|
|
send_cors=True,
|
2016-04-19 06:31:43 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-07-24 09:39:02 -04:00
|
|
|
async def respond_with_file(
|
2021-09-24 06:01:25 -04:00
|
|
|
request: SynapseRequest,
|
2021-01-15 10:57:37 -05:00
|
|
|
media_type: str,
|
|
|
|
file_path: str,
|
|
|
|
file_size: Optional[int] = None,
|
|
|
|
upload_name: Optional[str] = None,
|
|
|
|
) -> None:
|
2016-04-19 06:31:43 -04:00
|
|
|
logger.debug("Responding with %r", file_path)
|
|
|
|
|
|
|
|
if os.path.isfile(file_path):
|
|
|
|
if file_size is None:
|
|
|
|
stat = os.stat(file_path)
|
|
|
|
file_size = stat.st_size
|
|
|
|
|
2018-01-05 10:09:43 -05:00
|
|
|
add_file_headers(request, media_type, file_size, upload_name)
|
2016-04-19 06:31:43 -04:00
|
|
|
|
|
|
|
with open(file_path, "rb") as f:
|
2020-07-24 09:39:02 -04:00
|
|
|
await make_deferred_yieldable(FileSender().beginFileTransfer(f, request))
|
2016-04-19 06:31:43 -04:00
|
|
|
|
|
|
|
finish_request(request)
|
|
|
|
else:
|
|
|
|
respond_404(request)
|
2018-01-05 10:09:43 -05:00
|
|
|
|
|
|
|
|
2021-01-15 10:57:37 -05:00
|
|
|
def add_file_headers(
|
|
|
|
request: Request,
|
|
|
|
media_type: str,
|
|
|
|
file_size: Optional[int],
|
|
|
|
upload_name: Optional[str],
|
|
|
|
) -> None:
|
2018-01-05 10:09:43 -05:00
|
|
|
"""Adds the correct response headers in preparation for responding with the
|
|
|
|
media.
|
|
|
|
|
|
|
|
Args:
|
2021-01-15 10:57:37 -05:00
|
|
|
request
|
|
|
|
media_type: The media/content type.
|
|
|
|
file_size: Size in bytes of the media, if known.
|
|
|
|
upload_name: The name of the requested file, if any.
|
2018-01-05 10:09:43 -05:00
|
|
|
"""
|
2018-11-15 16:55:58 -05:00
|
|
|
|
2021-09-15 08:45:32 -04:00
|
|
|
def _quote(x: str) -> str:
|
2018-09-12 06:41:31 -04:00
|
|
|
return urllib.parse.quote(x.encode("utf-8"))
|
|
|
|
|
2020-03-17 09:29:09 -04:00
|
|
|
# Default to a UTF-8 charset for text content types.
|
|
|
|
# ex, uses UTF-8 for 'text/css' but not 'text/css; charset=UTF-16'
|
|
|
|
if media_type.lower() in TEXT_CONTENT_TYPES:
|
|
|
|
content_type = media_type + "; charset=UTF-8"
|
|
|
|
else:
|
|
|
|
content_type = media_type
|
|
|
|
|
|
|
|
request.setHeader(b"Content-Type", content_type.encode("UTF-8"))
|
2018-01-05 10:09:43 -05:00
|
|
|
if upload_name:
|
2019-03-11 05:53:45 -04:00
|
|
|
# RFC6266 section 4.1 [1] defines both `filename` and `filename*`.
|
|
|
|
#
|
|
|
|
# `filename` is defined to be a `value`, which is defined by RFC2616
|
|
|
|
# section 3.6 [2] to be a `token` or a `quoted-string`, where a `token`
|
|
|
|
# is (essentially) a single US-ASCII word, and a `quoted-string` is a
|
|
|
|
# US-ASCII string surrounded by double-quotes, using backslash as an
|
2021-02-12 11:01:48 -05:00
|
|
|
# escape character. Note that %-encoding is *not* permitted.
|
2019-03-11 05:53:45 -04:00
|
|
|
#
|
|
|
|
# `filename*` is defined to be an `ext-value`, which is defined in
|
|
|
|
# RFC5987 section 3.2.1 [3] to be `charset "'" [ language ] "'" value-chars`,
|
|
|
|
# where `value-chars` is essentially a %-encoded string in the given charset.
|
|
|
|
#
|
|
|
|
# [1]: https://tools.ietf.org/html/rfc6266#section-4.1
|
|
|
|
# [2]: https://tools.ietf.org/html/rfc2616#section-3.6
|
|
|
|
# [3]: https://tools.ietf.org/html/rfc5987#section-3.2.1
|
|
|
|
|
|
|
|
# We avoid the quoted-string version of `filename`, because (a) synapse didn't
|
|
|
|
# correctly interpret those as of 0.99.2 and (b) they are a bit of a pain and we
|
|
|
|
# may as well just do the filename* version.
|
|
|
|
if _can_encode_filename_as_token(upload_name):
|
2019-06-20 05:32:02 -04:00
|
|
|
disposition = "inline; filename=%s" % (upload_name,)
|
2018-01-05 10:09:43 -05:00
|
|
|
else:
|
2019-06-20 05:32:02 -04:00
|
|
|
disposition = "inline; filename*=utf-8''%s" % (_quote(upload_name),)
|
2018-09-12 06:41:31 -04:00
|
|
|
|
2019-06-20 05:32:02 -04:00
|
|
|
request.setHeader(b"Content-Disposition", disposition.encode("ascii"))
|
2018-01-05 10:09:43 -05:00
|
|
|
|
|
|
|
# cache for at least a day.
|
|
|
|
# XXX: we might want to turn this off for data we don't want to
|
|
|
|
# recommend caching as it's sensitive or private - or at least
|
|
|
|
# select private. don't bother setting Expires as all our
|
|
|
|
# clients are smart enough to be happy with Cache-Control
|
2018-11-15 16:55:58 -05:00
|
|
|
request.setHeader(b"Cache-Control", b"public,max-age=86400,s-maxage=86400")
|
2021-01-15 10:57:37 -05:00
|
|
|
if file_size is not None:
|
|
|
|
request.setHeader(b"Content-Length", b"%d" % (file_size,))
|
2018-01-08 11:58:09 -05:00
|
|
|
|
2020-12-08 17:51:03 -05:00
|
|
|
# Tell web crawlers to not index, archive, or follow links in media. This
|
|
|
|
# should help to prevent things in the media repo from showing up in web
|
|
|
|
# search results.
|
|
|
|
request.setHeader(b"X-Robots-Tag", "noindex, nofollow, noarchive, noimageindex")
|
|
|
|
|
2018-01-08 11:58:09 -05:00
|
|
|
|
2019-03-11 05:53:45 -04:00
|
|
|
# separators as defined in RFC2616. SP and HT are handled separately.
|
|
|
|
# see _can_encode_filename_as_token.
|
2020-02-21 07:15:07 -05:00
|
|
|
_FILENAME_SEPARATOR_CHARS = {
|
|
|
|
"(",
|
|
|
|
")",
|
|
|
|
"<",
|
|
|
|
">",
|
|
|
|
"@",
|
|
|
|
",",
|
|
|
|
";",
|
|
|
|
":",
|
|
|
|
"\\",
|
|
|
|
'"',
|
|
|
|
"/",
|
|
|
|
"[",
|
|
|
|
"]",
|
|
|
|
"?",
|
|
|
|
"=",
|
|
|
|
"{",
|
|
|
|
"}",
|
|
|
|
}
|
2019-03-11 05:53:45 -04:00
|
|
|
|
|
|
|
|
2021-01-15 10:57:37 -05:00
|
|
|
def _can_encode_filename_as_token(x: str) -> bool:
|
2019-03-11 05:53:45 -04:00
|
|
|
for c in x:
|
|
|
|
# from RFC2616:
|
|
|
|
#
|
|
|
|
# token = 1*<any CHAR except CTLs or separators>
|
|
|
|
#
|
|
|
|
# separators = "(" | ")" | "<" | ">" | "@"
|
|
|
|
# | "," | ";" | ":" | "\" | <">
|
|
|
|
# | "/" | "[" | "]" | "?" | "="
|
|
|
|
# | "{" | "}" | SP | HT
|
|
|
|
#
|
|
|
|
# CHAR = <any US-ASCII character (octets 0 - 127)>
|
|
|
|
#
|
|
|
|
# CTL = <any US-ASCII control character
|
|
|
|
# (octets 0 - 31) and DEL (127)>
|
|
|
|
#
|
|
|
|
if ord(c) >= 127 or ord(c) <= 32 or c in _FILENAME_SEPARATOR_CHARS:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2020-07-24 09:39:02 -04:00
|
|
|
async def respond_with_responder(
|
2021-09-24 06:01:25 -04:00
|
|
|
request: SynapseRequest,
|
2021-01-15 10:57:37 -05:00
|
|
|
responder: "Optional[Responder]",
|
|
|
|
media_type: str,
|
|
|
|
file_size: Optional[int],
|
|
|
|
upload_name: Optional[str] = None,
|
|
|
|
) -> None:
|
2018-01-08 11:58:09 -05:00
|
|
|
"""Responds to the request with given responder. If responder is None then
|
|
|
|
returns 404.
|
|
|
|
|
|
|
|
Args:
|
2021-01-15 10:57:37 -05:00
|
|
|
request
|
|
|
|
responder
|
|
|
|
media_type: The media/content type.
|
|
|
|
file_size: Size in bytes of the media. If not known it should be None
|
|
|
|
upload_name: The name of the requested file, if any.
|
2018-01-08 11:58:09 -05:00
|
|
|
"""
|
|
|
|
if not responder:
|
|
|
|
respond_404(request)
|
|
|
|
return
|
|
|
|
|
2022-08-30 07:17:48 -04:00
|
|
|
# If we have a responder we *must* use it as a context manager.
|
|
|
|
with responder:
|
|
|
|
if request._disconnected:
|
|
|
|
logger.warning(
|
|
|
|
"Not sending response to request %s, already disconnected.", request
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
|
|
|
logger.debug("Responding to media request with responder %s", responder)
|
|
|
|
add_file_headers(request, media_type, file_size, upload_name)
|
|
|
|
try:
|
|
|
|
|
2020-07-24 09:39:02 -04:00
|
|
|
await responder.write_to_consumer(request)
|
2022-08-30 07:17:48 -04:00
|
|
|
except Exception as e:
|
|
|
|
# The majority of the time this will be due to the client having gone
|
|
|
|
# away. Unfortunately, Twisted simply throws a generic exception at us
|
|
|
|
# in that case.
|
|
|
|
logger.warning("Failed to write to consumer: %s %s", type(e), e)
|
|
|
|
|
|
|
|
# Unregister the producer, if it has one, so Twisted doesn't complain
|
|
|
|
if request.producer:
|
|
|
|
request.unregisterProducer()
|
2019-04-24 12:37:33 -04:00
|
|
|
|
2018-01-08 11:58:09 -05:00
|
|
|
finish_request(request)
|
|
|
|
|
|
|
|
|
Use mypy 1.0 (#15052)
* Update mypy and mypy-zope
* Remove unused ignores
These used to suppress
```
synapse/storage/engines/__init__.py:28: error: "__new__" must return a
class instance (got "NoReturn") [misc]
```
and
```
synapse/http/matrixfederationclient.py:1270: error: "BaseException" has no attribute "reasons" [attr-defined]
```
(note that we check `hasattr(e, "reasons")` above)
* Avoid empty body warnings, sometimes by marking methods as abstract
E.g.
```
tests/handlers/test_register.py:58: error: Missing return statement [empty-body]
tests/handlers/test_register.py:108: error: Missing return statement [empty-body]
```
* Suppress false positive about `JaegerConfig`
Complaint was
```
synapse/logging/opentracing.py:450: error: Function "Type[Config]" could always be true in boolean context [truthy-function]
```
* Fix not calling `is_state()`
Oops!
```
tests/rest/client/test_third_party_rules.py:428: error: Function "Callable[[], bool]" could always be true in boolean context [truthy-function]
```
* Suppress false positives from ParamSpecs
````
synapse/logging/opentracing.py:971: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
synapse/logging/opentracing.py:1017: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
````
* Drive-by improvement to `wrapping_logic` annotation
* Workaround false "unreachable" positives
See https://github.com/Shoobx/mypy-zope/issues/91
```
tests/http/test_proxyagent.py:626: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:762: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:826: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:838: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:845: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:151: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:452: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:60: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:93: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:127: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:152: error: Statement is unreachable [unreachable]
```
* Changelog
* Tweak DBAPI2 Protocol to be accepted by mypy 1.0
Some extra context in:
- https://github.com/matrix-org/python-canonicaljson/pull/57
- https://github.com/python/mypy/issues/6002
- https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
* Pull in updated canonicaljson lib
so the protocol check just works
* Improve comments in opentracing
I tried to workaround the ignores but found it too much trouble.
I think the corresponding issue is
https://github.com/python/mypy/issues/12909. The mypy repo has a PR
claiming to fix this (https://github.com/python/mypy/pull/14677) which
might mean this gets resolved soon?
* Better annotation for INTERACTIVE_AUTH_CHECKERS
* Drive-by AUTH_TYPE annotation, to remove an ignore
2023-02-16 11:09:11 -05:00
|
|
|
class Responder(ABC):
|
2018-01-08 11:58:09 -05:00
|
|
|
"""Represents a response that can be streamed to the requester.
|
|
|
|
|
2018-01-12 08:32:03 -05:00
|
|
|
Responder is a context manager which *must* be used, so that any resources
|
|
|
|
held can be cleaned up.
|
2018-01-08 11:58:09 -05:00
|
|
|
"""
|
2018-11-15 16:55:58 -05:00
|
|
|
|
Use mypy 1.0 (#15052)
* Update mypy and mypy-zope
* Remove unused ignores
These used to suppress
```
synapse/storage/engines/__init__.py:28: error: "__new__" must return a
class instance (got "NoReturn") [misc]
```
and
```
synapse/http/matrixfederationclient.py:1270: error: "BaseException" has no attribute "reasons" [attr-defined]
```
(note that we check `hasattr(e, "reasons")` above)
* Avoid empty body warnings, sometimes by marking methods as abstract
E.g.
```
tests/handlers/test_register.py:58: error: Missing return statement [empty-body]
tests/handlers/test_register.py:108: error: Missing return statement [empty-body]
```
* Suppress false positive about `JaegerConfig`
Complaint was
```
synapse/logging/opentracing.py:450: error: Function "Type[Config]" could always be true in boolean context [truthy-function]
```
* Fix not calling `is_state()`
Oops!
```
tests/rest/client/test_third_party_rules.py:428: error: Function "Callable[[], bool]" could always be true in boolean context [truthy-function]
```
* Suppress false positives from ParamSpecs
````
synapse/logging/opentracing.py:971: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
synapse/logging/opentracing.py:1017: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
````
* Drive-by improvement to `wrapping_logic` annotation
* Workaround false "unreachable" positives
See https://github.com/Shoobx/mypy-zope/issues/91
```
tests/http/test_proxyagent.py:626: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:762: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:826: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:838: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:845: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:151: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:452: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:60: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:93: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:127: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:152: error: Statement is unreachable [unreachable]
```
* Changelog
* Tweak DBAPI2 Protocol to be accepted by mypy 1.0
Some extra context in:
- https://github.com/matrix-org/python-canonicaljson/pull/57
- https://github.com/python/mypy/issues/6002
- https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
* Pull in updated canonicaljson lib
so the protocol check just works
* Improve comments in opentracing
I tried to workaround the ignores but found it too much trouble.
I think the corresponding issue is
https://github.com/python/mypy/issues/12909. The mypy repo has a PR
claiming to fix this (https://github.com/python/mypy/pull/14677) which
might mean this gets resolved soon?
* Better annotation for INTERACTIVE_AUTH_CHECKERS
* Drive-by AUTH_TYPE annotation, to remove an ignore
2023-02-16 11:09:11 -05:00
|
|
|
@abstractmethod
|
2020-07-27 14:40:11 -04:00
|
|
|
def write_to_consumer(self, consumer: IConsumer) -> Awaitable:
|
2018-01-08 11:58:09 -05:00
|
|
|
"""Stream response into consumer
|
|
|
|
|
|
|
|
Args:
|
2020-07-27 14:40:11 -04:00
|
|
|
consumer: The consumer to stream into.
|
2018-01-08 11:58:09 -05:00
|
|
|
|
|
|
|
Returns:
|
2020-07-27 14:40:11 -04:00
|
|
|
Resolves once the response has finished being written
|
2018-01-08 11:58:09 -05:00
|
|
|
"""
|
Use mypy 1.0 (#15052)
* Update mypy and mypy-zope
* Remove unused ignores
These used to suppress
```
synapse/storage/engines/__init__.py:28: error: "__new__" must return a
class instance (got "NoReturn") [misc]
```
and
```
synapse/http/matrixfederationclient.py:1270: error: "BaseException" has no attribute "reasons" [attr-defined]
```
(note that we check `hasattr(e, "reasons")` above)
* Avoid empty body warnings, sometimes by marking methods as abstract
E.g.
```
tests/handlers/test_register.py:58: error: Missing return statement [empty-body]
tests/handlers/test_register.py:108: error: Missing return statement [empty-body]
```
* Suppress false positive about `JaegerConfig`
Complaint was
```
synapse/logging/opentracing.py:450: error: Function "Type[Config]" could always be true in boolean context [truthy-function]
```
* Fix not calling `is_state()`
Oops!
```
tests/rest/client/test_third_party_rules.py:428: error: Function "Callable[[], bool]" could always be true in boolean context [truthy-function]
```
* Suppress false positives from ParamSpecs
````
synapse/logging/opentracing.py:971: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
synapse/logging/opentracing.py:1017: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
````
* Drive-by improvement to `wrapping_logic` annotation
* Workaround false "unreachable" positives
See https://github.com/Shoobx/mypy-zope/issues/91
```
tests/http/test_proxyagent.py:626: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:762: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:826: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:838: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:845: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:151: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:452: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:60: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:93: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:127: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:152: error: Statement is unreachable [unreachable]
```
* Changelog
* Tweak DBAPI2 Protocol to be accepted by mypy 1.0
Some extra context in:
- https://github.com/matrix-org/python-canonicaljson/pull/57
- https://github.com/python/mypy/issues/6002
- https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
* Pull in updated canonicaljson lib
so the protocol check just works
* Improve comments in opentracing
I tried to workaround the ignores but found it too much trouble.
I think the corresponding issue is
https://github.com/python/mypy/issues/12909. The mypy repo has a PR
claiming to fix this (https://github.com/python/mypy/pull/14677) which
might mean this gets resolved soon?
* Better annotation for INTERACTIVE_AUTH_CHECKERS
* Drive-by AUTH_TYPE annotation, to remove an ignore
2023-02-16 11:09:11 -05:00
|
|
|
raise NotImplementedError()
|
2018-01-08 11:58:09 -05:00
|
|
|
|
Use mypy 1.0 (#15052)
* Update mypy and mypy-zope
* Remove unused ignores
These used to suppress
```
synapse/storage/engines/__init__.py:28: error: "__new__" must return a
class instance (got "NoReturn") [misc]
```
and
```
synapse/http/matrixfederationclient.py:1270: error: "BaseException" has no attribute "reasons" [attr-defined]
```
(note that we check `hasattr(e, "reasons")` above)
* Avoid empty body warnings, sometimes by marking methods as abstract
E.g.
```
tests/handlers/test_register.py:58: error: Missing return statement [empty-body]
tests/handlers/test_register.py:108: error: Missing return statement [empty-body]
```
* Suppress false positive about `JaegerConfig`
Complaint was
```
synapse/logging/opentracing.py:450: error: Function "Type[Config]" could always be true in boolean context [truthy-function]
```
* Fix not calling `is_state()`
Oops!
```
tests/rest/client/test_third_party_rules.py:428: error: Function "Callable[[], bool]" could always be true in boolean context [truthy-function]
```
* Suppress false positives from ParamSpecs
````
synapse/logging/opentracing.py:971: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
synapse/logging/opentracing.py:1017: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
````
* Drive-by improvement to `wrapping_logic` annotation
* Workaround false "unreachable" positives
See https://github.com/Shoobx/mypy-zope/issues/91
```
tests/http/test_proxyagent.py:626: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:762: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:826: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:838: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:845: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:151: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:452: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:60: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:93: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:127: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:152: error: Statement is unreachable [unreachable]
```
* Changelog
* Tweak DBAPI2 Protocol to be accepted by mypy 1.0
Some extra context in:
- https://github.com/matrix-org/python-canonicaljson/pull/57
- https://github.com/python/mypy/issues/6002
- https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
* Pull in updated canonicaljson lib
so the protocol check just works
* Improve comments in opentracing
I tried to workaround the ignores but found it too much trouble.
I think the corresponding issue is
https://github.com/python/mypy/issues/12909. The mypy repo has a PR
claiming to fix this (https://github.com/python/mypy/pull/14677) which
might mean this gets resolved soon?
* Better annotation for INTERACTIVE_AUTH_CHECKERS
* Drive-by AUTH_TYPE annotation, to remove an ignore
2023-02-16 11:09:11 -05:00
|
|
|
def __enter__(self) -> None: # noqa: B027
|
2018-01-12 08:32:03 -05:00
|
|
|
pass
|
|
|
|
|
Use mypy 1.0 (#15052)
* Update mypy and mypy-zope
* Remove unused ignores
These used to suppress
```
synapse/storage/engines/__init__.py:28: error: "__new__" must return a
class instance (got "NoReturn") [misc]
```
and
```
synapse/http/matrixfederationclient.py:1270: error: "BaseException" has no attribute "reasons" [attr-defined]
```
(note that we check `hasattr(e, "reasons")` above)
* Avoid empty body warnings, sometimes by marking methods as abstract
E.g.
```
tests/handlers/test_register.py:58: error: Missing return statement [empty-body]
tests/handlers/test_register.py:108: error: Missing return statement [empty-body]
```
* Suppress false positive about `JaegerConfig`
Complaint was
```
synapse/logging/opentracing.py:450: error: Function "Type[Config]" could always be true in boolean context [truthy-function]
```
* Fix not calling `is_state()`
Oops!
```
tests/rest/client/test_third_party_rules.py:428: error: Function "Callable[[], bool]" could always be true in boolean context [truthy-function]
```
* Suppress false positives from ParamSpecs
````
synapse/logging/opentracing.py:971: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
synapse/logging/opentracing.py:1017: error: Argument 2 to "_custom_sync_async_decorator" has incompatible type "Callable[[Arg(Callable[P, R], 'func'), **P], _GeneratorContextManager[None]]"; expected "Callable[[Callable[P, R], **P], _GeneratorContextManager[None]]" [arg-type]
````
* Drive-by improvement to `wrapping_logic` annotation
* Workaround false "unreachable" positives
See https://github.com/Shoobx/mypy-zope/issues/91
```
tests/http/test_proxyagent.py:626: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:762: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:826: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:838: error: Statement is unreachable [unreachable]
tests/http/test_proxyagent.py:845: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:151: error: Statement is unreachable [unreachable]
tests/http/federation/test_matrix_federation_agent.py:452: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:60: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:93: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:127: error: Statement is unreachable [unreachable]
tests/logging/test_remote_handler.py:152: error: Statement is unreachable [unreachable]
```
* Changelog
* Tweak DBAPI2 Protocol to be accepted by mypy 1.0
Some extra context in:
- https://github.com/matrix-org/python-canonicaljson/pull/57
- https://github.com/python/mypy/issues/6002
- https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
* Pull in updated canonicaljson lib
so the protocol check just works
* Improve comments in opentracing
I tried to workaround the ignores but found it too much trouble.
I think the corresponding issue is
https://github.com/python/mypy/issues/12909. The mypy repo has a PR
claiming to fix this (https://github.com/python/mypy/pull/14677) which
might mean this gets resolved soon?
* Better annotation for INTERACTIVE_AUTH_CHECKERS
* Drive-by AUTH_TYPE annotation, to remove an ignore
2023-02-16 11:09:11 -05:00
|
|
|
def __exit__( # noqa: B027
|
2021-09-15 08:45:32 -04:00
|
|
|
self,
|
|
|
|
exc_type: Optional[Type[BaseException]],
|
|
|
|
exc_val: Optional[BaseException],
|
|
|
|
exc_tb: Optional[TracebackType],
|
|
|
|
) -> None:
|
2018-01-08 11:58:09 -05:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-09-14 07:09:38 -04:00
|
|
|
@attr.s(slots=True, frozen=True, auto_attribs=True)
|
|
|
|
class ThumbnailInfo:
|
|
|
|
"""Details about a generated thumbnail."""
|
2018-11-15 16:55:58 -05:00
|
|
|
|
2021-09-14 07:09:38 -04:00
|
|
|
width: int
|
|
|
|
height: int
|
|
|
|
method: str
|
|
|
|
# Content type of thumbnail, e.g. image/png
|
|
|
|
type: str
|
|
|
|
# The size of the media file, in bytes.
|
|
|
|
length: Optional[int] = None
|
|
|
|
|
|
|
|
|
|
|
|
@attr.s(slots=True, frozen=True, auto_attribs=True)
|
|
|
|
class FileInfo:
|
|
|
|
"""Details about a requested/uploaded file."""
|
|
|
|
|
|
|
|
# The server name where the media originated from, or None if local.
|
|
|
|
server_name: Optional[str]
|
|
|
|
# The local ID of the file. For local files this is the same as the media_id
|
|
|
|
file_id: str
|
|
|
|
# If the file is for the url preview cache
|
|
|
|
url_cache: bool = False
|
|
|
|
# Whether the file is a thumbnail or not.
|
|
|
|
thumbnail: Optional[ThumbnailInfo] = None
|
|
|
|
|
|
|
|
# The below properties exist to maintain compatibility with third-party modules.
|
|
|
|
@property
|
2021-09-15 08:45:32 -04:00
|
|
|
def thumbnail_width(self) -> Optional[int]:
|
2021-09-14 07:09:38 -04:00
|
|
|
if not self.thumbnail:
|
|
|
|
return None
|
|
|
|
return self.thumbnail.width
|
|
|
|
|
|
|
|
@property
|
2021-09-15 08:45:32 -04:00
|
|
|
def thumbnail_height(self) -> Optional[int]:
|
2021-09-14 07:09:38 -04:00
|
|
|
if not self.thumbnail:
|
|
|
|
return None
|
|
|
|
return self.thumbnail.height
|
|
|
|
|
|
|
|
@property
|
2021-09-15 08:45:32 -04:00
|
|
|
def thumbnail_method(self) -> Optional[str]:
|
2021-09-14 07:09:38 -04:00
|
|
|
if not self.thumbnail:
|
|
|
|
return None
|
|
|
|
return self.thumbnail.method
|
|
|
|
|
|
|
|
@property
|
2021-09-15 08:45:32 -04:00
|
|
|
def thumbnail_type(self) -> Optional[str]:
|
2021-09-14 07:09:38 -04:00
|
|
|
if not self.thumbnail:
|
|
|
|
return None
|
|
|
|
return self.thumbnail.type
|
|
|
|
|
|
|
|
@property
|
2021-09-15 08:45:32 -04:00
|
|
|
def thumbnail_length(self) -> Optional[int]:
|
2021-09-14 07:09:38 -04:00
|
|
|
if not self.thumbnail:
|
|
|
|
return None
|
|
|
|
return self.thumbnail.length
|
2018-11-15 16:55:58 -05:00
|
|
|
|
|
|
|
|
2021-01-15 10:57:37 -05:00
|
|
|
def get_filename_from_headers(headers: Dict[bytes, List[bytes]]) -> Optional[str]:
|
2018-11-15 16:55:58 -05:00
|
|
|
"""
|
|
|
|
Get the filename of the downloaded file by inspecting the
|
|
|
|
Content-Disposition HTTP header.
|
|
|
|
|
|
|
|
Args:
|
2021-01-15 10:57:37 -05:00
|
|
|
headers: The HTTP request headers.
|
2018-11-15 16:55:58 -05:00
|
|
|
|
|
|
|
Returns:
|
2021-01-15 10:57:37 -05:00
|
|
|
The filename, or None.
|
2018-11-15 16:55:58 -05:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
content_disposition = headers.get(b"Content-Disposition", [b""])
|
2018-11-15 16:55:58 -05:00
|
|
|
|
|
|
|
# No header, bail out.
|
|
|
|
if not content_disposition[0]:
|
2021-01-15 10:57:37 -05:00
|
|
|
return None
|
2018-11-15 16:55:58 -05:00
|
|
|
|
2019-02-27 17:29:10 -05:00
|
|
|
_, params = _parse_header(content_disposition[0])
|
2018-11-15 16:55:58 -05:00
|
|
|
|
|
|
|
upload_name = None
|
|
|
|
|
|
|
|
# First check if there is a valid UTF-8 filename
|
2019-02-27 17:29:10 -05:00
|
|
|
upload_name_utf8 = params.get(b"filename*", None)
|
2018-11-15 16:55:58 -05:00
|
|
|
if upload_name_utf8:
|
|
|
|
if upload_name_utf8.lower().startswith(b"utf-8''"):
|
|
|
|
upload_name_utf8 = upload_name_utf8[7:]
|
|
|
|
# We have a filename*= section. This MUST be ASCII, and any UTF-8
|
|
|
|
# bytes are %-quoted.
|
2020-05-15 14:17:06 -04:00
|
|
|
try:
|
|
|
|
# Once it is decoded, we can then unquote the %-encoded
|
|
|
|
# parts strictly into a unicode string.
|
|
|
|
upload_name = urllib.parse.unquote(
|
|
|
|
upload_name_utf8.decode("ascii"), errors="strict"
|
|
|
|
)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
# Incorrect UTF-8.
|
|
|
|
pass
|
2018-11-15 16:55:58 -05:00
|
|
|
|
|
|
|
# If there isn't check for an ascii name.
|
|
|
|
if not upload_name:
|
2019-02-27 17:29:10 -05:00
|
|
|
upload_name_ascii = params.get(b"filename", None)
|
2018-11-15 16:55:58 -05:00
|
|
|
if upload_name_ascii and is_ascii(upload_name_ascii):
|
2019-06-20 05:32:02 -04:00
|
|
|
upload_name = upload_name_ascii.decode("ascii")
|
2018-11-15 16:55:58 -05:00
|
|
|
|
|
|
|
# This may be None here, indicating we did not find a matching name.
|
|
|
|
return upload_name
|
2019-02-27 17:29:10 -05:00
|
|
|
|
|
|
|
|
2021-01-15 10:57:37 -05:00
|
|
|
def _parse_header(line: bytes) -> Tuple[bytes, Dict[bytes, bytes]]:
|
2019-02-27 17:29:10 -05:00
|
|
|
"""Parse a Content-type like header.
|
|
|
|
|
|
|
|
Cargo-culted from `cgi`, but works on bytes rather than strings.
|
|
|
|
|
|
|
|
Args:
|
2021-01-15 10:57:37 -05:00
|
|
|
line: header to be parsed
|
2019-02-27 17:29:10 -05:00
|
|
|
|
|
|
|
Returns:
|
2021-01-15 10:57:37 -05:00
|
|
|
The main content-type, followed by the parameter dictionary
|
2019-02-27 17:29:10 -05:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
parts = _parseparam(b";" + line)
|
2019-02-27 17:29:10 -05:00
|
|
|
key = next(parts)
|
|
|
|
pdict = {}
|
|
|
|
for p in parts:
|
2019-06-20 05:32:02 -04:00
|
|
|
i = p.find(b"=")
|
2019-02-27 17:29:10 -05:00
|
|
|
if i >= 0:
|
|
|
|
name = p[:i].strip().lower()
|
2019-06-20 05:32:02 -04:00
|
|
|
value = p[i + 1 :].strip()
|
2019-02-27 17:29:10 -05:00
|
|
|
|
|
|
|
# strip double-quotes
|
|
|
|
if len(value) >= 2 and value[0:1] == value[-1:] == b'"':
|
|
|
|
value = value[1:-1]
|
2019-06-20 05:32:02 -04:00
|
|
|
value = value.replace(b"\\\\", b"\\").replace(b'\\"', b'"')
|
2019-02-27 17:29:10 -05:00
|
|
|
pdict[name] = value
|
|
|
|
|
|
|
|
return key, pdict
|
|
|
|
|
|
|
|
|
2021-01-15 10:57:37 -05:00
|
|
|
def _parseparam(s: bytes) -> Generator[bytes, None, None]:
|
2019-02-27 17:29:10 -05:00
|
|
|
"""Generator which splits the input on ;, respecting double-quoted sequences
|
|
|
|
|
|
|
|
Cargo-culted from `cgi`, but works on bytes rather than strings.
|
|
|
|
|
|
|
|
Args:
|
2021-01-15 10:57:37 -05:00
|
|
|
s: header to be parsed
|
2019-02-27 17:29:10 -05:00
|
|
|
|
|
|
|
Returns:
|
2021-01-15 10:57:37 -05:00
|
|
|
The split input
|
2019-02-27 17:29:10 -05:00
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
while s[:1] == b";":
|
2019-02-27 17:29:10 -05:00
|
|
|
s = s[1:]
|
|
|
|
|
|
|
|
# look for the next ;
|
2019-06-20 05:32:02 -04:00
|
|
|
end = s.find(b";")
|
2019-02-27 17:29:10 -05:00
|
|
|
|
|
|
|
# if there is an odd number of " marks between here and the next ;, skip to the
|
|
|
|
# next ; instead
|
|
|
|
while end > 0 and (s.count(b'"', 0, end) - s.count(b'\\"', 0, end)) % 2:
|
2019-06-20 05:32:02 -04:00
|
|
|
end = s.find(b";", end + 1)
|
2019-02-27 17:29:10 -05:00
|
|
|
|
|
|
|
if end < 0:
|
|
|
|
end = len(s)
|
|
|
|
f = s[:end]
|
|
|
|
yield f.strip()
|
|
|
|
s = s[end:]
|