_connection.py 26 KB

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