25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

660 satır
26 KiB

  1. # This contains the main Connection class. Everything in h11 revolves around
  2. # this.
  3. from typing import (
  4. Any,
  5. Callable,
  6. cast,
  7. Dict,
  8. List,
  9. Optional,
  10. overload,
  11. Tuple,
  12. Type,
  13. Union,
  14. )
  15. from ._events import (
  16. ConnectionClosed,
  17. Data,
  18. EndOfMessage,
  19. Event,
  20. InformationalResponse,
  21. Request,
  22. Response,
  23. )
  24. from ._headers import get_comma_header, has_expect_100_continue, set_comma_header
  25. from ._readers import READERS, ReadersType
  26. from ._receivebuffer import ReceiveBuffer
  27. from ._state import (
  28. _SWITCH_CONNECT,
  29. _SWITCH_UPGRADE,
  30. CLIENT,
  31. ConnectionState,
  32. DONE,
  33. ERROR,
  34. MIGHT_SWITCH_PROTOCOL,
  35. SEND_BODY,
  36. SERVER,
  37. SWITCHED_PROTOCOL,
  38. )
  39. from ._util import ( # Import the internal things we need
  40. LocalProtocolError,
  41. RemoteProtocolError,
  42. Sentinel,
  43. )
  44. from ._writers import WRITERS, WritersType
  45. # Everything in __all__ gets re-exported as part of the h11 public API.
  46. __all__ = ["Connection", "NEED_DATA", "PAUSED"]
  47. class NEED_DATA(Sentinel, metaclass=Sentinel):
  48. pass
  49. class PAUSED(Sentinel, metaclass=Sentinel):
  50. pass
  51. # If we ever have this much buffered without it making a complete parseable
  52. # event, we error out. The only time we really buffer is when reading the
  53. # request/response line + headers together, so this is effectively the limit on
  54. # the size of that.
  55. #
  56. # Some precedents for defaults:
  57. # - node.js: 80 * 1024
  58. # - tomcat: 8 * 1024
  59. # - IIS: 16 * 1024
  60. # - Apache: <8 KiB per line>
  61. DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024
  62. # RFC 7230's rules for connection lifecycles:
  63. # - If either side says they want to close the connection, then the connection
  64. # must close.
  65. # - HTTP/1.1 defaults to keep-alive unless someone says Connection: close
  66. # - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive
  67. # (and even this is a mess -- e.g. if you're implementing a proxy then
  68. # sending Connection: keep-alive is forbidden).
  69. #
  70. # We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So
  71. # our rule is:
  72. # - If someone says Connection: close, we will close
  73. # - If someone uses HTTP/1.0, we will close.
  74. def _keep_alive(event: Union[Request, Response]) -> bool:
  75. connection = get_comma_header(event.headers, b"connection")
  76. if b"close" in connection:
  77. return False
  78. if getattr(event, "http_version", b"1.1") < b"1.1":
  79. return False
  80. return True
  81. def _body_framing(
  82. request_method: bytes, event: Union[Request, Response]
  83. ) -> Tuple[str, Union[Tuple[()], Tuple[int]]]:
  84. # Called when we enter SEND_BODY to figure out framing information for
  85. # this body.
  86. #
  87. # These are the only two events that can trigger a SEND_BODY state:
  88. assert type(event) in (Request, Response)
  89. # Returns one of:
  90. #
  91. # ("content-length", count)
  92. # ("chunked", ())
  93. # ("http/1.0", ())
  94. #
  95. # which are (lookup key, *args) for constructing body reader/writer
  96. # objects.
  97. #
  98. # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3
  99. #
  100. # Step 1: some responses always have an empty body, regardless of what the
  101. # headers say.
  102. if type(event) is Response:
  103. if (
  104. event.status_code in (204, 304)
  105. or request_method == b"HEAD"
  106. or (request_method == b"CONNECT" and 200 <= event.status_code < 300)
  107. ):
  108. return ("content-length", (0,))
  109. # Section 3.3.3 also lists another case -- responses with status_code
  110. # < 200. For us these are InformationalResponses, not Responses, so
  111. # they can't get into this function in the first place.
  112. assert event.status_code >= 200
  113. # Step 2: check for Transfer-Encoding (T-E beats C-L):
  114. transfer_encodings = get_comma_header(event.headers, b"transfer-encoding")
  115. if transfer_encodings:
  116. assert transfer_encodings == [b"chunked"]
  117. return ("chunked", ())
  118. # Step 3: check for Content-Length
  119. content_lengths = get_comma_header(event.headers, b"content-length")
  120. if content_lengths:
  121. return ("content-length", (int(content_lengths[0]),))
  122. # Step 4: no applicable headers; fallback/default depends on type
  123. if type(event) is Request:
  124. return ("content-length", (0,))
  125. else:
  126. return ("http/1.0", ())
  127. ################################################################
  128. #
  129. # The main Connection class
  130. #
  131. ################################################################
  132. class Connection:
  133. """An object encapsulating the state of an HTTP connection.
  134. Args:
  135. our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If
  136. you're implementing a server, pass :data:`h11.SERVER`.
  137. max_incomplete_event_size (int):
  138. The maximum number of bytes we're willing to buffer of an
  139. incomplete event. In practice this mostly sets a limit on the
  140. maximum size of the request/response line + headers. If this is
  141. exceeded, then :meth:`next_event` will raise
  142. :exc:`RemoteProtocolError`.
  143. """
  144. def __init__(
  145. self,
  146. our_role: Type[Sentinel],
  147. max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE,
  148. ) -> None:
  149. self._max_incomplete_event_size = max_incomplete_event_size
  150. # State and role tracking
  151. if our_role not in (CLIENT, SERVER):
  152. raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}")
  153. self.our_role = our_role
  154. self.their_role: Type[Sentinel]
  155. if our_role is CLIENT:
  156. self.their_role = SERVER
  157. else:
  158. self.their_role = CLIENT
  159. self._cstate = ConnectionState()
  160. # Callables for converting data->events or vice-versa given the
  161. # current state
  162. self._writer = self._get_io_object(self.our_role, None, WRITERS)
  163. self._reader = self._get_io_object(self.their_role, None, READERS)
  164. # Holds any unprocessed received data
  165. self._receive_buffer = ReceiveBuffer()
  166. # If this is true, then it indicates that the incoming connection was
  167. # closed *after* the end of whatever's in self._receive_buffer:
  168. self._receive_buffer_closed = False
  169. # Extra bits of state that don't fit into the state machine.
  170. #
  171. # These two are only used to interpret framing headers for figuring
  172. # out how to read/write response bodies. their_http_version is also
  173. # made available as a convenient public API.
  174. self.their_http_version: Optional[bytes] = None
  175. self._request_method: Optional[bytes] = None
  176. # This is pure flow-control and doesn't at all affect the set of legal
  177. # transitions, so no need to bother ConnectionState with it:
  178. self.client_is_waiting_for_100_continue = False
  179. @property
  180. def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]:
  181. """A dictionary like::
  182. {CLIENT: <client state>, SERVER: <server state>}
  183. See :ref:`state-machine` for details.
  184. """
  185. return dict(self._cstate.states)
  186. @property
  187. def our_state(self) -> Type[Sentinel]:
  188. """The current state of whichever role we are playing. See
  189. :ref:`state-machine` for details.
  190. """
  191. return self._cstate.states[self.our_role]
  192. @property
  193. def their_state(self) -> Type[Sentinel]:
  194. """The current state of whichever role we are NOT playing. See
  195. :ref:`state-machine` for details.
  196. """
  197. return self._cstate.states[self.their_role]
  198. @property
  199. def they_are_waiting_for_100_continue(self) -> bool:
  200. return self.their_role is CLIENT and self.client_is_waiting_for_100_continue
  201. def start_next_cycle(self) -> None:
  202. """Attempt to reset our connection state for a new request/response
  203. cycle.
  204. If both client and server are in :data:`DONE` state, then resets them
  205. both to :data:`IDLE` state in preparation for a new request/response
  206. cycle on this same connection. Otherwise, raises a
  207. :exc:`LocalProtocolError`.
  208. See :ref:`keepalive-and-pipelining`.
  209. """
  210. old_states = dict(self._cstate.states)
  211. self._cstate.start_next_cycle()
  212. self._request_method = None
  213. # self.their_http_version gets left alone, since it presumably lasts
  214. # beyond a single request/response cycle
  215. assert not self.client_is_waiting_for_100_continue
  216. self._respond_to_state_changes(old_states)
  217. def _process_error(self, role: Type[Sentinel]) -> None:
  218. old_states = dict(self._cstate.states)
  219. self._cstate.process_error(role)
  220. self._respond_to_state_changes(old_states)
  221. def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]:
  222. if type(event) is InformationalResponse and event.status_code == 101:
  223. return _SWITCH_UPGRADE
  224. if type(event) is Response:
  225. if (
  226. _SWITCH_CONNECT in self._cstate.pending_switch_proposals
  227. and 200 <= event.status_code < 300
  228. ):
  229. return _SWITCH_CONNECT
  230. return None
  231. # All events go through here
  232. def _process_event(self, role: Type[Sentinel], event: Event) -> None:
  233. # First, pass the event through the state machine to make sure it
  234. # succeeds.
  235. old_states = dict(self._cstate.states)
  236. if role is CLIENT and type(event) is Request:
  237. if event.method == b"CONNECT":
  238. self._cstate.process_client_switch_proposal(_SWITCH_CONNECT)
  239. if get_comma_header(event.headers, b"upgrade"):
  240. self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE)
  241. server_switch_event = None
  242. if role is SERVER:
  243. server_switch_event = self._server_switch_event(event)
  244. self._cstate.process_event(role, type(event), server_switch_event)
  245. # Then perform the updates triggered by it.
  246. if type(event) is Request:
  247. self._request_method = event.method
  248. if role is self.their_role and type(event) in (
  249. Request,
  250. Response,
  251. InformationalResponse,
  252. ):
  253. event = cast(Union[Request, Response, InformationalResponse], event)
  254. self.their_http_version = event.http_version
  255. # Keep alive handling
  256. #
  257. # RFC 7230 doesn't really say what one should do if Connection: close
  258. # shows up on a 1xx InformationalResponse. I think the idea is that
  259. # this is not supposed to happen. In any case, if it does happen, we
  260. # ignore it.
  261. if type(event) in (Request, Response) and not _keep_alive(
  262. cast(Union[Request, Response], event)
  263. ):
  264. self._cstate.process_keep_alive_disabled()
  265. # 100-continue
  266. if type(event) is Request and has_expect_100_continue(event):
  267. self.client_is_waiting_for_100_continue = True
  268. if type(event) in (InformationalResponse, Response):
  269. self.client_is_waiting_for_100_continue = False
  270. if role is CLIENT and type(event) in (Data, EndOfMessage):
  271. self.client_is_waiting_for_100_continue = False
  272. self._respond_to_state_changes(old_states, event)
  273. def _get_io_object(
  274. self,
  275. role: Type[Sentinel],
  276. event: Optional[Event],
  277. io_dict: Union[ReadersType, WritersType],
  278. ) -> Optional[Callable[..., Any]]:
  279. # event may be None; it's only used when entering SEND_BODY
  280. state = self._cstate.states[role]
  281. if state is SEND_BODY:
  282. # Special case: the io_dict has a dict of reader/writer factories
  283. # that depend on the request/response framing.
  284. framing_type, args = _body_framing(
  285. cast(bytes, self._request_method), cast(Union[Request, Response], event)
  286. )
  287. return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index]
  288. else:
  289. # General case: the io_dict just has the appropriate reader/writer
  290. # for this state
  291. return io_dict.get((role, state)) # type: ignore[return-value]
  292. # This must be called after any action that might have caused
  293. # self._cstate.states to change.
  294. def _respond_to_state_changes(
  295. self,
  296. old_states: Dict[Type[Sentinel], Type[Sentinel]],
  297. event: Optional[Event] = None,
  298. ) -> None:
  299. # Update reader/writer
  300. if self.our_state != old_states[self.our_role]:
  301. self._writer = self._get_io_object(self.our_role, event, WRITERS)
  302. if self.their_state != old_states[self.their_role]:
  303. self._reader = self._get_io_object(self.their_role, event, READERS)
  304. @property
  305. def trailing_data(self) -> Tuple[bytes, bool]:
  306. """Data that has been received, but not yet processed, represented as
  307. a tuple with two elements, where the first is a byte-string containing
  308. the unprocessed data itself, and the second is a bool that is True if
  309. the receive connection was closed.
  310. See :ref:`switching-protocols` for discussion of why you'd want this.
  311. """
  312. return (bytes(self._receive_buffer), self._receive_buffer_closed)
  313. def receive_data(self, data: bytes) -> None:
  314. """Add data to our internal receive buffer.
  315. This does not actually do any processing on the data, just stores
  316. it. To trigger processing, you have to call :meth:`next_event`.
  317. Args:
  318. data (:term:`bytes-like object`):
  319. The new data that was just received.
  320. Special case: If *data* is an empty byte-string like ``b""``,
  321. then this indicates that the remote side has closed the
  322. connection (end of file). Normally this is convenient, because
  323. standard Python APIs like :meth:`file.read` or
  324. :meth:`socket.recv` use ``b""`` to indicate end-of-file, while
  325. other failures to read are indicated using other mechanisms
  326. like raising :exc:`TimeoutError`. When using such an API you
  327. can just blindly pass through whatever you get from ``read``
  328. to :meth:`receive_data`, and everything will work.
  329. But, if you have an API where reading an empty string is a
  330. valid non-EOF condition, then you need to be aware of this and
  331. make sure to check for such strings and avoid passing them to
  332. :meth:`receive_data`.
  333. Returns:
  334. Nothing, but after calling this you should call :meth:`next_event`
  335. to parse the newly received data.
  336. Raises:
  337. RuntimeError:
  338. Raised if you pass an empty *data*, indicating EOF, and then
  339. pass a non-empty *data*, indicating more data that somehow
  340. arrived after the EOF.
  341. (Calling ``receive_data(b"")`` multiple times is fine,
  342. and equivalent to calling it once.)
  343. """
  344. if data:
  345. if self._receive_buffer_closed:
  346. raise RuntimeError("received close, then received more data?")
  347. self._receive_buffer += data
  348. else:
  349. self._receive_buffer_closed = True
  350. def _extract_next_receive_event(
  351. self,
  352. ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
  353. state = self.their_state
  354. # We don't pause immediately when they enter DONE, because even in
  355. # DONE state we can still process a ConnectionClosed() event. But
  356. # if we have data in our buffer, then we definitely aren't getting
  357. # a ConnectionClosed() immediately and we need to pause.
  358. if state is DONE and self._receive_buffer:
  359. return PAUSED
  360. if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL:
  361. return PAUSED
  362. assert self._reader is not None
  363. event = self._reader(self._receive_buffer)
  364. if event is None:
  365. if not self._receive_buffer and self._receive_buffer_closed:
  366. # In some unusual cases (basically just HTTP/1.0 bodies), EOF
  367. # triggers an actual protocol event; in that case, we want to
  368. # return that event, and then the state will change and we'll
  369. # get called again to generate the actual ConnectionClosed().
  370. if hasattr(self._reader, "read_eof"):
  371. event = self._reader.read_eof()
  372. else:
  373. event = ConnectionClosed()
  374. if event is None:
  375. event = NEED_DATA
  376. return event # type: ignore[no-any-return]
  377. def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
  378. """Parse the next event out of our receive buffer, update our internal
  379. state, and return it.
  380. This is a mutating operation -- think of it like calling :func:`next`
  381. on an iterator.
  382. Returns:
  383. : One of three things:
  384. 1) An event object -- see :ref:`events`.
  385. 2) The special constant :data:`NEED_DATA`, which indicates that
  386. you need to read more data from your socket and pass it to
  387. :meth:`receive_data` before this method will be able to return
  388. any more events.
  389. 3) The special constant :data:`PAUSED`, which indicates that we
  390. are not in a state where we can process incoming data (usually
  391. because the peer has finished their part of the current
  392. request/response cycle, and you have not yet called
  393. :meth:`start_next_cycle`). See :ref:`flow-control` for details.
  394. Raises:
  395. RemoteProtocolError:
  396. The peer has misbehaved. You should close the connection
  397. (possibly after sending some kind of 4xx response).
  398. Once this method returns :class:`ConnectionClosed` once, then all
  399. subsequent calls will also return :class:`ConnectionClosed`.
  400. If this method raises any exception besides :exc:`RemoteProtocolError`
  401. then that's a bug -- if it happens please file a bug report!
  402. If this method raises any exception then it also sets
  403. :attr:`Connection.their_state` to :data:`ERROR` -- see
  404. :ref:`error-handling` for discussion.
  405. """
  406. if self.their_state is ERROR:
  407. raise RemoteProtocolError("Can't receive data when peer state is ERROR")
  408. try:
  409. event = self._extract_next_receive_event()
  410. if event not in [NEED_DATA, PAUSED]:
  411. self._process_event(self.their_role, cast(Event, event))
  412. if event is NEED_DATA:
  413. if len(self._receive_buffer) > self._max_incomplete_event_size:
  414. # 431 is "Request header fields too large" which is pretty
  415. # much the only situation where we can get here
  416. raise RemoteProtocolError(
  417. "Receive buffer too long", error_status_hint=431
  418. )
  419. if self._receive_buffer_closed:
  420. # We're still trying to complete some event, but that's
  421. # never going to happen because no more data is coming
  422. raise RemoteProtocolError("peer unexpectedly closed connection")
  423. return event
  424. except BaseException as exc:
  425. self._process_error(self.their_role)
  426. if isinstance(exc, LocalProtocolError):
  427. exc._reraise_as_remote_protocol_error()
  428. else:
  429. raise
  430. @overload
  431. def send(self, event: ConnectionClosed) -> None:
  432. ...
  433. @overload
  434. def send(
  435. self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage]
  436. ) -> bytes:
  437. ...
  438. @overload
  439. def send(self, event: Event) -> Optional[bytes]:
  440. ...
  441. def send(self, event: Event) -> Optional[bytes]:
  442. """Convert a high-level event into bytes that can be sent to the peer,
  443. while updating our internal state machine.
  444. Args:
  445. event: The :ref:`event <events>` to send.
  446. Returns:
  447. If ``type(event) is ConnectionClosed``, then returns
  448. ``None``. Otherwise, returns a :term:`bytes-like object`.
  449. Raises:
  450. LocalProtocolError:
  451. Sending this event at this time would violate our
  452. understanding of the HTTP/1.1 protocol.
  453. If this method raises any exception then it also sets
  454. :attr:`Connection.our_state` to :data:`ERROR` -- see
  455. :ref:`error-handling` for discussion.
  456. """
  457. data_list = self.send_with_data_passthrough(event)
  458. if data_list is None:
  459. return None
  460. else:
  461. return b"".join(data_list)
  462. def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]:
  463. """Identical to :meth:`send`, except that in situations where
  464. :meth:`send` returns a single :term:`bytes-like object`, this instead
  465. returns a list of them -- and when sending a :class:`Data` event, this
  466. list is guaranteed to contain the exact object you passed in as
  467. :attr:`Data.data`. See :ref:`sendfile` for discussion.
  468. """
  469. if self.our_state is ERROR:
  470. raise LocalProtocolError("Can't send data when our state is ERROR")
  471. try:
  472. if type(event) is Response:
  473. event = self._clean_up_response_headers_for_sending(event)
  474. # We want to call _process_event before calling the writer,
  475. # because if someone tries to do something invalid then this will
  476. # give a sensible error message, while our writers all just assume
  477. # they will only receive valid events. But, _process_event might
  478. # change self._writer. So we have to do a little dance:
  479. writer = self._writer
  480. self._process_event(self.our_role, event)
  481. if type(event) is ConnectionClosed:
  482. return None
  483. else:
  484. # In any situation where writer is None, process_event should
  485. # have raised ProtocolError
  486. assert writer is not None
  487. data_list: List[bytes] = []
  488. writer(event, data_list.append)
  489. return data_list
  490. except:
  491. self._process_error(self.our_role)
  492. raise
  493. def send_failed(self) -> None:
  494. """Notify the state machine that we failed to send the data it gave
  495. us.
  496. This causes :attr:`Connection.our_state` to immediately become
  497. :data:`ERROR` -- see :ref:`error-handling` for discussion.
  498. """
  499. self._process_error(self.our_role)
  500. # When sending a Response, we take responsibility for a few things:
  501. #
  502. # - Sometimes you MUST set Connection: close. We take care of those
  503. # times. (You can also set it yourself if you want, and if you do then
  504. # we'll respect that and close the connection at the right time. But you
  505. # don't have to worry about that unless you want to.)
  506. #
  507. # - The user has to set Content-Length if they want it. Otherwise, for
  508. # responses that have bodies (e.g. not HEAD), then we will automatically
  509. # select the right mechanism for streaming a body of unknown length,
  510. # which depends on depending on the peer's HTTP version.
  511. #
  512. # This function's *only* responsibility is making sure headers are set up
  513. # right -- everything downstream just looks at the headers. There are no
  514. # side channels.
  515. def _clean_up_response_headers_for_sending(self, response: Response) -> Response:
  516. assert type(response) is Response
  517. headers = response.headers
  518. need_close = False
  519. # HEAD requests need some special handling: they always act like they
  520. # have Content-Length: 0, and that's how _body_framing treats
  521. # them. But their headers are supposed to match what we would send if
  522. # the request was a GET. (Technically there is one deviation allowed:
  523. # we're allowed to leave out the framing headers -- see
  524. # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as
  525. # easy to get them right.)
  526. method_for_choosing_headers = cast(bytes, self._request_method)
  527. if method_for_choosing_headers == b"HEAD":
  528. method_for_choosing_headers = b"GET"
  529. framing_type, _ = _body_framing(method_for_choosing_headers, response)
  530. if framing_type in ("chunked", "http/1.0"):
  531. # This response has a body of unknown length.
  532. # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked
  533. # If our peer is HTTP/1.0, we use no framing headers, and close the
  534. # connection afterwards.
  535. #
  536. # Make sure to clear Content-Length (in principle user could have
  537. # set both and then we ignored Content-Length b/c
  538. # Transfer-Encoding overwrote it -- this would be naughty of them,
  539. # but the HTTP spec says that if our peer does this then we have
  540. # to fix it instead of erroring out, so we'll accord the user the
  541. # same respect).
  542. headers = set_comma_header(headers, b"content-length", [])
  543. if self.their_http_version is None or self.their_http_version < b"1.1":
  544. # Either we never got a valid request and are sending back an
  545. # error (their_http_version is None), so we assume the worst;
  546. # or else we did get a valid HTTP/1.0 request, so we know that
  547. # they don't understand chunked encoding.
  548. headers = set_comma_header(headers, b"transfer-encoding", [])
  549. # This is actually redundant ATM, since currently we
  550. # unconditionally disable keep-alive when talking to HTTP/1.0
  551. # peers. But let's be defensive just in case we add
  552. # Connection: keep-alive support later:
  553. if self._request_method != b"HEAD":
  554. need_close = True
  555. else:
  556. headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"])
  557. if not self._cstate.keep_alive or need_close:
  558. # Make sure Connection: close is set
  559. connection = set(get_comma_header(headers, b"connection"))
  560. connection.discard(b"keep-alive")
  561. connection.add(b"close")
  562. headers = set_comma_header(headers, b"connection", sorted(connection))
  563. return Response(
  564. headers=headers,
  565. status_code=response.status_code,
  566. http_version=response.http_version,
  567. reason=response.reason,
  568. )