Debian Codegraph @

third_party/python/aiohttp/aiohttp/http_parser.py

raw
1 import abc
2 import asyncio
3 import re
4 import string
5 from contextlib import suppress
6 from enum import IntEnum
7 from typing import (
8 Any,
9 ClassVar,
10 Final,
11 Generic,
12 List,
13 Literal,
14 NamedTuple,
15 Optional,
16 Pattern,
17 Set,
18 Tuple,
19 Type,
20 TypeVar,
21 Union,
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 .compression_utils import HAS_BROTLI, BrotliDecompressor, ZLibDecompressor
30 from .helpers import (
31 _EXC_SENTINEL,
32 DEBUG,
33 NO_EXTENSIONS,
34 BaseTimerContext,
35 method_must_be_empty_body,
36 set_exception,
37 status_code_must_be_empty_body,
38 )
39 from .http_exceptions import (
40 BadHttpMessage,
41 BadStatusLine,
42 ContentEncodingError,
43 ContentLengthError,
44 InvalidHeader,
45 InvalidURLError,
46 LineTooLong,
47 TransferEncodingError,
48 )
49 from .http_writer import HttpVersion, HttpVersion10
50 from .streams import EMPTY_PAYLOAD, StreamReader
51 from .typedefs import RawHeaders
52
53 __all__ = (
54 "HeadersParser",
55 "HttpParser",
56 "HttpRequestParser",
57 "HttpResponseParser",
58 "RawRequestMessage",
59 "RawResponseMessage",
60 )
61
62 _SEP = Literal[b"\r\n", b"\n"]
63
64 ASCIISET: Final[Set[str]] = set(string.printable)
65
66 # See https://www.rfc-editor.org/rfc/rfc9110.html#name-overview
67 # and https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens
68 #
69 # method = token
70 # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
71 # "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
72 # token = 1*tchar
73 _TCHAR_SPECIALS: Final[str] = re.escape("!#$%&'*+-.^_`|~")
74 TOKENRE: Final[Pattern[str]] = re.compile(f"[0-9A-Za-z{_TCHAR_SPECIALS}]+")
75 VERSRE: Final[Pattern[str]] = re.compile(r"HTTP/(\d)\.(\d)", re.ASCII)
76 DIGITS: Final[Pattern[str]] = re.compile(r"\d+", re.ASCII)
77 HEXDIGITS: Final[Pattern[bytes]] = re.compile(rb"[0-9a-fA-F]+")
78
79
80 class RawRequestMessage(NamedTuple):
81 method: str
82 path: str
83 version: HttpVersion
84 headers: "CIMultiDictProxy[str]"
85 raw_headers: RawHeaders
86 should_close: bool
87 compression: Optional[str]
88 upgrade: bool
89 chunked: bool
90 url: URL
91
92
93 class RawResponseMessage(NamedTuple):
94 version: HttpVersion
95 code: int
96 reason: str
97 headers: CIMultiDictProxy[str]
98 raw_headers: RawHeaders
99 should_close: bool
100 compression: Optional[str]
101 upgrade: bool
102 chunked: bool
103
104
105 _MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage)
106
107
108 class ParseState(IntEnum):
109
110 PARSE_NONE = 0
111 PARSE_LENGTH = 1
112 PARSE_CHUNKED = 2
113 PARSE_UNTIL_EOF = 3
114
115
116 class ChunkState(IntEnum):
117 PARSE_CHUNKED_SIZE = 0
118 PARSE_CHUNKED_CHUNK = 1
119 PARSE_CHUNKED_CHUNK_EOF = 2
120 PARSE_MAYBE_TRAILERS = 3
121 PARSE_TRAILERS = 4
122
123
124 class HeadersParser:
125 def __init__(
126 self,
127 max_line_size: int = 8190,
128 max_headers: int = 32768,
129 max_field_size: int = 8190,
130 lax: bool = False,
131 ) -> None:
132 self.max_line_size = max_line_size
133 self.max_headers = max_headers
134 self.max_field_size = max_field_size
135 self._lax = lax
136
137 def parse_headers(
138 self, lines: List[bytes]
139 ) -> Tuple["CIMultiDictProxy[str]", RawHeaders]:
140 headers: CIMultiDict[str] = CIMultiDict()
141 # note: "raw" does not mean inclusion of OWS before/after the field value
142 raw_headers = []
143
144 lines_idx = 1
145 line = lines[1]
146 line_count = len(lines)
147
148 while line:
149 # Parse initial header name : value pair.
150 try:
151 bname, bvalue = line.split(b":", 1)
152 except ValueError:
153 raise InvalidHeader(line) from None
154
155 if len(bname) == 0:
156 raise InvalidHeader(bname)
157
158 # https://www.rfc-editor.org/rfc/rfc9112.html#section-5.1-2
159 if {bname[0], bname[-1]} & {32, 9}: # {" ", "\t"}
160 raise InvalidHeader(line)
161
162 bvalue = bvalue.lstrip(b" \t")
163 if len(bname) > self.max_field_size:
164 raise LineTooLong(
165 "request header name {}".format(
166 bname.decode("utf8", "backslashreplace")
167 ),
168 str(self.max_field_size),
169 str(len(bname)),
170 )
171 name = bname.decode("utf-8", "surrogateescape")
172 if not TOKENRE.fullmatch(name):
173 raise InvalidHeader(bname)
174
175 header_length = len(bvalue)
176
177 # next line
178 lines_idx += 1
179 line = lines[lines_idx]
180
181 # consume continuation lines
182 continuation = self._lax and line and line[0] in (32, 9) # (' ', '\t')
183
184 # Deprecated: https://www.rfc-editor.org/rfc/rfc9112.html#name-obsolete-line-folding
185 if continuation:
186 bvalue_lst = [bvalue]
187 while continuation:
188 header_length += len(line)
189 if header_length > self.max_field_size:
190 raise LineTooLong(
191 "request header field {}".format(
192 bname.decode("utf8", "backslashreplace")
193 ),
194 str(self.max_field_size),
195 str(header_length),
196 )
197 bvalue_lst.append(line)
198
199 # next line
200 lines_idx += 1
201 if lines_idx < line_count:
202 line = lines[lines_idx]
203 if line:
204 continuation = line[0] in (32, 9) # (' ', '\t')
205 else:
206 line = b""
207 break
208 bvalue = b"".join(bvalue_lst)
209 else:
210 if header_length > self.max_field_size:
211 raise LineTooLong(
212 "request header field {}".format(
213 bname.decode("utf8", "backslashreplace")
214 ),
215 str(self.max_field_size),
216 str(header_length),
217 )
218
219 bvalue = bvalue.strip(b" \t")
220 value = bvalue.decode("utf-8", "surrogateescape")
221
222 # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-5
223 if "\n" in value or "\r" in value or "\x00" in value:
224 raise InvalidHeader(bvalue)
225
226 headers.add(name, value)
227 raw_headers.append((bname, bvalue))
228
229 return (CIMultiDictProxy(headers), tuple(raw_headers))
230
231
232 def _is_supported_upgrade(headers: CIMultiDictProxy[str]) -> bool:
233 """Check if the upgrade header is supported."""
234 return headers.get(hdrs.UPGRADE, "").lower() in {"tcp", "websocket"}
235
236
237 class HttpParser(abc.ABC, Generic[_MsgT]):
238 lax: ClassVar[bool] = False
239
240 def __init__(
241 self,
242 protocol: Optional[BaseProtocol] = None,
243 loop: Optional[asyncio.AbstractEventLoop] = None,
244 limit: int = 2**16,
245 max_line_size: int = 8190,
246 max_headers: int = 32768,
247 max_field_size: int = 8190,
248 timer: Optional[BaseTimerContext] = None,
249 code: Optional[int] = None,
250 method: Optional[str] = None,
251 payload_exception: Optional[Type[BaseException]] = None,
252 response_with_body: bool = True,
253 read_until_eof: bool = False,
254 auto_decompress: bool = True,
255 ) -> None:
256 self.protocol = protocol
257 self.loop = loop
258 self.max_line_size = max_line_size
259 self.max_headers = max_headers
260 self.max_field_size = max_field_size
261 self.timer = timer
262 self.code = code
263 self.method = method
264 self.payload_exception = payload_exception
265 self.response_with_body = response_with_body
266 self.read_until_eof = read_until_eof
267
268 self._lines: List[bytes] = []
269 self._tail = b""
270 self._upgraded = False
271 self._payload = None
272 self._payload_parser: Optional[HttpPayloadParser] = None
273 self._auto_decompress = auto_decompress
274 self._limit = limit
275 self._headers_parser = HeadersParser(
276 max_line_size, max_headers, max_field_size, self.lax
277 )
278
279 @abc.abstractmethod
280 def parse_message(self, lines: List[bytes]) -> _MsgT: ...
281
282 @abc.abstractmethod
283 def _is_chunked_te(self, te: str) -> bool: ...
284
285 def feed_eof(self) -> Optional[_MsgT]:
286 if self._payload_parser is not None:
287 self._payload_parser.feed_eof()
288 self._payload_parser = None
289 else:
290 # try to extract partial message
291 if self._tail:
292 self._lines.append(self._tail)
293
294 if self._lines:
295 if self._lines[-1] != "\r\n":
296 self._lines.append(b"")
297 with suppress(Exception):
298 return self.parse_message(self._lines)
299 return None
300
301 def feed_data(
302 self,
303 data: bytes,
304 SEP: _SEP = b"\r\n",
305 EMPTY: bytes = b"",
306 CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH,
307 METH_CONNECT: str = hdrs.METH_CONNECT,
308 SEC_WEBSOCKET_KEY1: istr = hdrs.SEC_WEBSOCKET_KEY1,
309 ) -> Tuple[List[Tuple[_MsgT, StreamReader]], bool, bytes]:
310
311 messages = []
312
313 if self._tail:
314 data, self._tail = self._tail + data, b""
315
316 data_len = len(data)
317 start_pos = 0
318 loop = self.loop
319
320 should_close = False
321 while start_pos < data_len:
322
323 # read HTTP message (request/response line + headers), \r\n\r\n
324 # and split by lines
325 if self._payload_parser is None and not self._upgraded:
326 pos = data.find(SEP, start_pos)
327 # consume \r\n
328 if pos == start_pos and not self._lines:
329 start_pos = pos + len(SEP)
330 continue
331
332 if pos >= start_pos:
333 if should_close:
334 raise BadHttpMessage("Data after `Connection: close`")
335
336 # line found
337 line = data[start_pos:pos]
338 if SEP == b"\n": # For lax response parsing
339 line = line.rstrip(b"\r")
340 self._lines.append(line)
341 start_pos = pos + len(SEP)
342
343 # \r\n\r\n found
344 if self._lines[-1] == EMPTY:
345 try:
346 msg: _MsgT = self.parse_message(self._lines)
347 finally:
348 self._lines.clear()
349
350 def get_content_length() -> Optional[int]:
351 # payload length
352 length_hdr = msg.headers.get(CONTENT_LENGTH)
353 if length_hdr is None:
354 return None
355
356 # Shouldn't allow +/- or other number formats.
357 # https://www.rfc-editor.org/rfc/rfc9110#section-8.6-2
358 # msg.headers is already stripped of leading/trailing wsp
359 if not DIGITS.fullmatch(length_hdr):
360 raise InvalidHeader(CONTENT_LENGTH)
361
362 return int(length_hdr)
363
364 length = get_content_length()
365 # do not support old websocket spec
366 if SEC_WEBSOCKET_KEY1 in msg.headers:
367 raise InvalidHeader(SEC_WEBSOCKET_KEY1)
368
369 self._upgraded = msg.upgrade and _is_supported_upgrade(
370 msg.headers
371 )
372
373 method = getattr(msg, "method", self.method)
374 # code is only present on responses
375 code = getattr(msg, "code", 0)
376
377 assert self.protocol is not None
378 # calculate payload
379 empty_body = status_code_must_be_empty_body(code) or bool(
380 method and method_must_be_empty_body(method)
381 )
382 if not empty_body and (
383 ((length is not None and length > 0) or msg.chunked)
384 and not self._upgraded
385 ):
386 payload = StreamReader(
387 self.protocol,
388 timer=self.timer,
389 loop=loop,
390 limit=self._limit,
391 )
392 payload_parser = HttpPayloadParser(
393 payload,
394 length=length,
395 chunked=msg.chunked,
396 method=method,
397 compression=msg.compression,
398 code=self.code,
399 response_with_body=self.response_with_body,
400 auto_decompress=self._auto_decompress,
401 lax=self.lax,
402 )
403 if not payload_parser.done:
404 self._payload_parser = payload_parser
405 elif method == METH_CONNECT:
406 assert isinstance(msg, RawRequestMessage)
407 payload = StreamReader(
408 self.protocol,
409 timer=self.timer,
410 loop=loop,
411 limit=self._limit,
412 )
413 self._upgraded = True
414 self._payload_parser = HttpPayloadParser(
415 payload,
416 method=msg.method,
417 compression=msg.compression,
418 auto_decompress=self._auto_decompress,
419 lax=self.lax,
420 )
421 elif not empty_body and length is None and self.read_until_eof:
422 payload = StreamReader(
423 self.protocol,
424 timer=self.timer,
425 loop=loop,
426 limit=self._limit,
427 )
428 payload_parser = HttpPayloadParser(
429 payload,
430 length=length,
431 chunked=msg.chunked,
432 method=method,
433 compression=msg.compression,
434 code=self.code,
435 response_with_body=self.response_with_body,
436 auto_decompress=self._auto_decompress,
437 lax=self.lax,
438 )
439 if not payload_parser.done:
440 self._payload_parser = payload_parser
441 else:
442 payload = EMPTY_PAYLOAD
443
444 messages.append((msg, payload))
445 should_close = msg.should_close
446 else:
447 self._tail = data[start_pos:]
448 data = EMPTY
449 break
450
451 # no parser, just store
452 elif self._payload_parser is None and self._upgraded:
453 assert not self._lines
454 break
455
456 # feed payload
457 elif data and start_pos < data_len:
458 assert not self._lines
459 assert self._payload_parser is not None
460 try:
461 eof, data = self._payload_parser.feed_data(data[start_pos:], SEP)
462 except BaseException as underlying_exc:
463 reraised_exc = underlying_exc
464 if self.payload_exception is not None:
465 reraised_exc = self.payload_exception(str(underlying_exc))
466
467 set_exception(
468 self._payload_parser.payload,
469 reraised_exc,
470 underlying_exc,
471 )
472
473 eof = True
474 data = b""
475
476 if eof:
477 start_pos = 0
478 data_len = len(data)
479 self._payload_parser = None
480 continue
481 else:
482 break
483
484 if data and start_pos < data_len:
485 data = data[start_pos:]
486 else:
487 data = EMPTY
488
489 return messages, self._upgraded, data
490
491 def parse_headers(
492 self, lines: List[bytes]
493 ) -> Tuple[
494 "CIMultiDictProxy[str]", RawHeaders, Optional[bool], Optional[str], bool, bool
495 ]:
496 """Parses RFC 5322 headers from a stream.
497
498 Line continuations are supported. Returns list of header name
499 and value pairs. Header name is in upper case.
500 """
501 headers, raw_headers = self._headers_parser.parse_headers(lines)
502 close_conn = None
503 encoding = None
504 upgrade = False
505 chunked = False
506
507 # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-6
508 # https://www.rfc-editor.org/rfc/rfc9110.html#name-collected-abnf
509 singletons = (
510 hdrs.CONTENT_LENGTH,
511 hdrs.CONTENT_LOCATION,
512 hdrs.CONTENT_RANGE,
513 hdrs.CONTENT_TYPE,
514 hdrs.ETAG,
515 hdrs.HOST,
516 hdrs.MAX_FORWARDS,
517 hdrs.SERVER,
518 hdrs.TRANSFER_ENCODING,
519 hdrs.USER_AGENT,
520 )
521 bad_hdr = next((h for h in singletons if len(headers.getall(h, ())) > 1), None)
522 if bad_hdr is not None:
523 raise BadHttpMessage(f"Duplicate '{bad_hdr}' header found.")
524
525 # keep-alive
526 conn = headers.get(hdrs.CONNECTION)
527 if conn:
528 v = conn.lower()
529 if v == "close":
530 close_conn = True
531 elif v == "keep-alive":
532 close_conn = False
533 # https://www.rfc-editor.org/rfc/rfc9110.html#name-101-switching-protocols
534 elif v == "upgrade" and headers.get(hdrs.UPGRADE):
535 upgrade = True
536
537 # encoding
538 enc = headers.get(hdrs.CONTENT_ENCODING)
539 if enc:
540 enc = enc.lower()
541 if enc in ("gzip", "deflate", "br"):
542 encoding = enc
543
544 # chunking
545 te = headers.get(hdrs.TRANSFER_ENCODING)
546 if te is not None:
547 if self._is_chunked_te(te):
548 chunked = True
549
550 if hdrs.CONTENT_LENGTH in headers:
551 raise BadHttpMessage(
552 "Transfer-Encoding can't be present with Content-Length",
553 )
554
555 return (headers, raw_headers, close_conn, encoding, upgrade, chunked)
556
557 def set_upgraded(self, val: bool) -> None:
558 """Set connection upgraded (to websocket) mode.
559
560 :param bool val: new state.
561 """
562 self._upgraded = val
563
564
565 class HttpRequestParser(HttpParser[RawRequestMessage]):
566 """Read request status line.
567
568 Exception .http_exceptions.BadStatusLine
569 could be raised in case of any errors in status line.
570 Returns RawRequestMessage.
571 """
572
573 def parse_message(self, lines: List[bytes]) -> RawRequestMessage:
574 # request line
575 line = lines[0].decode("utf-8", "surrogateescape")
576 try:
577 method, path, version = line.split(" ", maxsplit=2)
578 except ValueError:
579 raise BadStatusLine(line) from None
580
581 if len(path) > self.max_line_size:
582 raise LineTooLong(
583 "Status line is too long", str(self.max_line_size), str(len(path))
584 )
585
586 # method
587 if not TOKENRE.fullmatch(method):
588 raise BadStatusLine(method)
589
590 # version
591 match = VERSRE.fullmatch(version)
592 if match is None:
593 raise BadStatusLine(line)
594 version_o = HttpVersion(int(match.group(1)), int(match.group(2)))
595
596 if method == "CONNECT":
597 # authority-form,
598 # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3
599 url = URL.build(authority=path, encoded=True)
600 elif path.startswith("/"):
601 # origin-form,
602 # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1
603 path_part, _hash_separator, url_fragment = path.partition("#")
604 path_part, _question_mark_separator, qs_part = path_part.partition("?")
605
606 # NOTE: `yarl.URL.build()` is used to mimic what the Cython-based
607 # NOTE: parser does, otherwise it results into the same
608 # NOTE: HTTP Request-Line input producing different
609 # NOTE: `yarl.URL()` objects
610 url = URL.build(
611 path=path_part,
612 query_string=qs_part,
613 fragment=url_fragment,
614 encoded=True,
615 )
616 elif path == "*" and method == "OPTIONS":
617 # asterisk-form,
618 url = URL(path, encoded=True)
619 else:
620 # absolute-form for proxy maybe,
621 # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2
622 url = URL(path, encoded=True)
623 if url.scheme == "":
624 # not absolute-form
625 raise InvalidURLError(
626 path.encode(errors="surrogateescape").decode("latin1")
627 )
628
629 # read headers
630 (
631 headers,
632 raw_headers,
633 close,
634 compression,
635 upgrade,
636 chunked,
637 ) = self.parse_headers(lines)
638
639 if close is None: # then the headers weren't set in the request
640 if version_o <= HttpVersion10: # HTTP 1.0 must asks to not close
641 close = True
642 else: # HTTP 1.1 must ask to close.
643 close = False
644
645 return RawRequestMessage(
646 method,
647 path,
648 version_o,
649 headers,
650 raw_headers,
651 close,
652 compression,
653 upgrade,
654 chunked,
655 url,
656 )
657
658 def _is_chunked_te(self, te: str) -> bool:
659 if te.rsplit(",", maxsplit=1)[-1].strip(" \t").lower() == "chunked":
660 return True
661 # https://www.rfc-editor.org/rfc/rfc9112#section-6.3-2.4.3
662 raise BadHttpMessage("Request has invalid `Transfer-Encoding`")
663
664
665 class HttpResponseParser(HttpParser[RawResponseMessage]):
666 """Read response status line and headers.
667
668 BadStatusLine could be raised in case of any errors in status line.
669 Returns RawResponseMessage.
670 """
671
672 # Lax mode should only be enabled on response parser.
673 lax = not DEBUG
674
675 def feed_data(
676 self,
677 data: bytes,
678 SEP: Optional[_SEP] = None,
679 *args: Any,
680 **kwargs: Any,
681 ) -> Tuple[List[Tuple[RawResponseMessage, StreamReader]], bool, bytes]:
682 if SEP is None:
683 SEP = b"\r\n" if DEBUG else b"\n"
684 return super().feed_data(data, SEP, *args, **kwargs)
685
686 def parse_message(self, lines: List[bytes]) -> RawResponseMessage:
687 line = lines[0].decode("utf-8", "surrogateescape")
688 try:
689 version, status = line.split(maxsplit=1)
690 except ValueError:
691 raise BadStatusLine(line) from None
692
693 try:
694 status, reason = status.split(maxsplit=1)
695 except ValueError:
696 status = status.strip()
697 reason = ""
698
699 if len(reason) > self.max_line_size:
700 raise LineTooLong(
701 "Status line is too long", str(self.max_line_size), str(len(reason))
702 )
703
704 # version
705 match = VERSRE.fullmatch(version)
706 if match is None:
707 raise BadStatusLine(line)
708 version_o = HttpVersion(int(match.group(1)), int(match.group(2)))
709
710 # The status code is a three-digit ASCII number, no padding
711 if len(status) != 3 or not DIGITS.fullmatch(status):
712 raise BadStatusLine(line)
713 status_i = int(status)
714
715 # read headers
716 (
717 headers,
718 raw_headers,
719 close,
720 compression,
721 upgrade,
722 chunked,
723 ) = self.parse_headers(lines)
724
725 if close is None:
726 if version_o <= HttpVersion10:
727 close = True
728 # https://www.rfc-editor.org/rfc/rfc9112.html#name-message-body-length
729 elif 100 <= status_i < 200 or status_i in {204, 304}:
730 close = False
731 elif hdrs.CONTENT_LENGTH in headers or hdrs.TRANSFER_ENCODING in headers:
732 close = False
733 else:
734 # https://www.rfc-editor.org/rfc/rfc9112.html#section-6.3-2.8
735 close = True
736
737 return RawResponseMessage(
738 version_o,
739 status_i,
740 reason.strip(),
741 headers,
742 raw_headers,
743 close,
744 compression,
745 upgrade,
746 chunked,
747 )
748
749 def _is_chunked_te(self, te: str) -> bool:
750 # https://www.rfc-editor.org/rfc/rfc9112#section-6.3-2.4.2
751 return te.rsplit(",", maxsplit=1)[-1].strip(" \t").lower() == "chunked"
752
753
754 class HttpPayloadParser:
755 def __init__(
756 self,
757 payload: StreamReader,
758 length: Optional[int] = None,
759 chunked: bool = False,
760 compression: Optional[str] = None,
761 code: Optional[int] = None,
762 method: Optional[str] = None,
763 response_with_body: bool = True,
764 auto_decompress: bool = True,
765 lax: bool = False,
766 ) -> None:
767 self._length = 0
768 self._type = ParseState.PARSE_UNTIL_EOF
769 self._chunk = ChunkState.PARSE_CHUNKED_SIZE
770 self._chunk_size = 0
771 self._chunk_tail = b""
772 self._auto_decompress = auto_decompress
773 self._lax = lax
774 self.done = False
775
776 # payload decompression wrapper
777 if response_with_body and compression and self._auto_decompress:
778 real_payload: Union[StreamReader, DeflateBuffer] = DeflateBuffer(
779 payload, compression
780 )
781 else:
782 real_payload = payload
783
784 # payload parser
785 if not response_with_body:
786 # don't parse payload if it's not expected to be received
787 self._type = ParseState.PARSE_NONE
788 real_payload.feed_eof()
789 self.done = True
790 elif chunked:
791 self._type = ParseState.PARSE_CHUNKED
792 elif length is not None:
793 self._type = ParseState.PARSE_LENGTH
794 self._length = length
795 if self._length == 0:
796 real_payload.feed_eof()
797 self.done = True
798
799 self.payload = real_payload
800
801 def feed_eof(self) -> None:
802 if self._type == ParseState.PARSE_UNTIL_EOF:
803 self.payload.feed_eof()
804 elif self._type == ParseState.PARSE_LENGTH:
805 raise ContentLengthError(
806 "Not enough data for satisfy content length header."
807 )
808 elif self._type == ParseState.PARSE_CHUNKED:
809 raise TransferEncodingError(
810 "Not enough data for satisfy transfer length header."
811 )
812
813 def feed_data(
814 self, chunk: bytes, SEP: _SEP = b"\r\n", CHUNK_EXT: bytes = b";"
815 ) -> Tuple[bool, bytes]:
816 # Read specified amount of bytes
817 if self._type == ParseState.PARSE_LENGTH:
818 required = self._length
819 chunk_len = len(chunk)
820
821 if required >= chunk_len:
822 self._length = required - chunk_len
823 self.payload.feed_data(chunk, chunk_len)
824 if self._length == 0:
825 self.payload.feed_eof()
826 return True, b""
827 else:
828 self._length = 0
829 self.payload.feed_data(chunk[:required], required)
830 self.payload.feed_eof()
831 return True, chunk[required:]
832
833 # Chunked transfer encoding parser
834 elif self._type == ParseState.PARSE_CHUNKED:
835 if self._chunk_tail:
836 chunk = self._chunk_tail + chunk
837 self._chunk_tail = b""
838
839 while chunk:
840
841 # read next chunk size
842 if self._chunk == ChunkState.PARSE_CHUNKED_SIZE:
843 pos = chunk.find(SEP)
844 if pos >= 0:
845 i = chunk.find(CHUNK_EXT, 0, pos)
846 if i >= 0:
847 size_b = chunk[:i] # strip chunk-extensions
848 # Verify no LF in the chunk-extension
849 if b"\n" in (ext := chunk[i:pos]):
850 exc = BadHttpMessage(
851 f"Unexpected LF in chunk-extension: {ext!r}"
852 )
853 set_exception(self.payload, exc)
854 raise exc
855 else:
856 size_b = chunk[:pos]
857
858 if self._lax: # Allow whitespace in lax mode.
859 size_b = size_b.strip()
860
861 if not re.fullmatch(HEXDIGITS, size_b):
862 exc = TransferEncodingError(
863 chunk[:pos].decode("ascii", "surrogateescape")
864 )
865 set_exception(self.payload, exc)
866 raise exc
867 size = int(bytes(size_b), 16)
868
869 chunk = chunk[pos + len(SEP) :]
870 if size == 0: # eof marker
871 self._chunk = ChunkState.PARSE_MAYBE_TRAILERS
872 if self._lax and chunk.startswith(b"\r"):
873 chunk = chunk[1:]
874 else:
875 self._chunk = ChunkState.PARSE_CHUNKED_CHUNK
876 self._chunk_size = size
877 self.payload.begin_http_chunk_receiving()
878 else:
879 self._chunk_tail = chunk
880 return False, b""
881
882 # read chunk and feed buffer
883 if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK:
884 required = self._chunk_size
885 chunk_len = len(chunk)
886
887 if required > chunk_len:
888 self._chunk_size = required - chunk_len
889 self.payload.feed_data(chunk, chunk_len)
890 return False, b""
891 else:
892 self._chunk_size = 0
893 self.payload.feed_data(chunk[:required], required)
894 chunk = chunk[required:]
895 self._chunk = ChunkState.PARSE_CHUNKED_CHUNK_EOF
896 self.payload.end_http_chunk_receiving()
897
898 # toss the CRLF at the end of the chunk
899 if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK_EOF:
900 if self._lax and chunk.startswith(b"\r"):
901 chunk = chunk[1:]
902 if chunk[: len(SEP)] == SEP:
903 chunk = chunk[len(SEP) :]
904 self._chunk = ChunkState.PARSE_CHUNKED_SIZE
905 else:
906 self._chunk_tail = chunk
907 return False, b""
908
909 # if stream does not contain trailer, after 0\r\n
910 # we should get another \r\n otherwise
911 # trailers needs to be skipped until \r\n\r\n
912 if self._chunk == ChunkState.PARSE_MAYBE_TRAILERS:
913 head = chunk[: len(SEP)]
914 if head == SEP:
915 # end of stream
916 self.payload.feed_eof()
917 return True, chunk[len(SEP) :]
918 # Both CR and LF, or only LF may not be received yet. It is
919 # expected that CRLF or LF will be shown at the very first
920 # byte next time, otherwise trailers should come. The last
921 # CRLF which marks the end of response might not be
922 # contained in the same TCP segment which delivered the
923 # size indicator.
924 if not head:
925 return False, b""
926 if head == SEP[:1]:
927 self._chunk_tail = head
928 return False, b""
929 self._chunk = ChunkState.PARSE_TRAILERS
930
931 # read and discard trailer up to the CRLF terminator
932 if self._chunk == ChunkState.PARSE_TRAILERS:
933 pos = chunk.find(SEP)
934 if pos >= 0:
935 chunk = chunk[pos + len(SEP) :]
936 self._chunk = ChunkState.PARSE_MAYBE_TRAILERS
937 else:
938 self._chunk_tail = chunk
939 return False, b""
940
941 # Read all bytes until eof
942 elif self._type == ParseState.PARSE_UNTIL_EOF:
943 self.payload.feed_data(chunk, len(chunk))
944
945 return False, b""
946
947
948 class DeflateBuffer:
949 """DeflateStream decompress stream and feed data into specified stream."""
950
951 decompressor: Any
952
953 def __init__(self, out: StreamReader, encoding: Optional[str]) -> None:
954 self.out = out
955 self.size = 0
956 self.encoding = encoding
957 self._started_decoding = False
958
959 self.decompressor: Union[BrotliDecompressor, ZLibDecompressor]
960 if encoding == "br":
961 if not HAS_BROTLI: # pragma: no cover
962 raise ContentEncodingError(
963 "Can not decode content-encoding: brotli (br). "
964 "Please install `Brotli`"
965 )
966 self.decompressor = BrotliDecompressor()
967 else:
968 self.decompressor = ZLibDecompressor(encoding=encoding)
969
970 def set_exception(
971 self,
972 exc: BaseException,
973 exc_cause: BaseException = _EXC_SENTINEL,
974 ) -> None:
975 set_exception(self.out, exc, exc_cause)
976
977 def feed_data(self, chunk: bytes, size: int) -> None:
978 if not size:
979 return
980
981 self.size += size
982
983 # RFC1950
984 # bits 0..3 = CM = 0b1000 = 8 = "deflate"
985 # bits 4..7 = CINFO = 1..7 = windows size.
986 if (
987 not self._started_decoding
988 and self.encoding == "deflate"
989 and chunk[0] & 0xF != 8
990 ):
991 # Change the decoder to decompress incorrectly compressed data
992 # Actually we should issue a warning about non-RFC-compliant data.
993 self.decompressor = ZLibDecompressor(
994 encoding=self.encoding, suppress_deflate_header=True
995 )
996
997 try:
998 chunk = self.decompressor.decompress_sync(chunk)
999 except Exception:
1000 raise ContentEncodingError(
1001 "Can not decode content-encoding: %s" % self.encoding
1002 )
1003
1004 self._started_decoding = True
1005
1006 if chunk:
1007 self.out.feed_data(chunk, len(chunk))
1008
1009 def feed_eof(self) -> None:
1010 chunk = self.decompressor.flush()
1011
1012 if chunk or self.size > 0:
1013 self.out.feed_data(chunk, len(chunk))
1014 if self.encoding == "deflate" and not self.decompressor.eof:
1015 raise ContentEncodingError("deflate")
1016
1017 self.out.feed_eof()
1018
1019 def begin_http_chunk_receiving(self) -> None:
1020 self.out.begin_http_chunk_receiving()
1021
1022 def end_http_chunk_receiving(self) -> None:
1023 self.out.end_http_chunk_receiving()
1024
1025
1026 HttpRequestParserPy = HttpRequestParser
1027 HttpResponseParserPy = HttpResponseParser
1028 RawRequestMessagePy = RawRequestMessage
1029 RawResponseMessagePy = RawResponseMessage
1030
1031 try:
1032 if not NO_EXTENSIONS:
1033 from ._http_parser import ( # type: ignore[import-not-found,no-redef]
1034 HttpRequestParser,
1035 HttpResponseParser,
1036 RawRequestMessage,
1037 RawResponseMessage,
1038 )
1039
1040 HttpRequestParserC = HttpRequestParser
1041 HttpResponseParserC = HttpResponseParser
1042 RawRequestMessageC = RawRequestMessage
1043 RawResponseMessageC = RawResponseMessage
1044 except ImportError: # pragma: no cover
1045 pass