http1connection.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. #
  2. # Copyright 2014 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """Client and server implementations of HTTP/1.x.
  16. .. versionadded:: 4.0
  17. """
  18. import asyncio
  19. import logging
  20. import re
  21. import types
  22. from tornado.concurrent import (
  23. Future,
  24. future_add_done_callback,
  25. future_set_result_unless_cancelled,
  26. )
  27. from tornado.escape import native_str, utf8
  28. from tornado import gen
  29. from tornado import httputil
  30. from tornado import iostream
  31. from tornado.log import gen_log, app_log
  32. from tornado.util import GzipDecompressor
  33. from typing import cast, Optional, Type, Awaitable, Callable, Union, Tuple
  34. class _QuietException(Exception):
  35. def __init__(self) -> None:
  36. pass
  37. class _ExceptionLoggingContext(object):
  38. """Used with the ``with`` statement when calling delegate methods to
  39. log any exceptions with the given logger. Any exceptions caught are
  40. converted to _QuietException
  41. """
  42. def __init__(self, logger: logging.Logger) -> None:
  43. self.logger = logger
  44. def __enter__(self) -> None:
  45. pass
  46. def __exit__(
  47. self,
  48. typ: "Optional[Type[BaseException]]",
  49. value: Optional[BaseException],
  50. tb: types.TracebackType,
  51. ) -> None:
  52. if value is not None:
  53. assert typ is not None
  54. self.logger.error("Uncaught exception", exc_info=(typ, value, tb))
  55. raise _QuietException
  56. class HTTP1ConnectionParameters(object):
  57. """Parameters for `.HTTP1Connection` and `.HTTP1ServerConnection`.
  58. """
  59. def __init__(
  60. self,
  61. no_keep_alive: bool = False,
  62. chunk_size: int = None,
  63. max_header_size: int = None,
  64. header_timeout: float = None,
  65. max_body_size: int = None,
  66. body_timeout: float = None,
  67. decompress: bool = False,
  68. ) -> None:
  69. """
  70. :arg bool no_keep_alive: If true, always close the connection after
  71. one request.
  72. :arg int chunk_size: how much data to read into memory at once
  73. :arg int max_header_size: maximum amount of data for HTTP headers
  74. :arg float header_timeout: how long to wait for all headers (seconds)
  75. :arg int max_body_size: maximum amount of data for body
  76. :arg float body_timeout: how long to wait while reading body (seconds)
  77. :arg bool decompress: if true, decode incoming
  78. ``Content-Encoding: gzip``
  79. """
  80. self.no_keep_alive = no_keep_alive
  81. self.chunk_size = chunk_size or 65536
  82. self.max_header_size = max_header_size or 65536
  83. self.header_timeout = header_timeout
  84. self.max_body_size = max_body_size
  85. self.body_timeout = body_timeout
  86. self.decompress = decompress
  87. class HTTP1Connection(httputil.HTTPConnection):
  88. """Implements the HTTP/1.x protocol.
  89. This class can be on its own for clients, or via `HTTP1ServerConnection`
  90. for servers.
  91. """
  92. def __init__(
  93. self,
  94. stream: iostream.IOStream,
  95. is_client: bool,
  96. params: HTTP1ConnectionParameters = None,
  97. context: object = None,
  98. ) -> None:
  99. """
  100. :arg stream: an `.IOStream`
  101. :arg bool is_client: client or server
  102. :arg params: a `.HTTP1ConnectionParameters` instance or ``None``
  103. :arg context: an opaque application-defined object that can be accessed
  104. as ``connection.context``.
  105. """
  106. self.is_client = is_client
  107. self.stream = stream
  108. if params is None:
  109. params = HTTP1ConnectionParameters()
  110. self.params = params
  111. self.context = context
  112. self.no_keep_alive = params.no_keep_alive
  113. # The body limits can be altered by the delegate, so save them
  114. # here instead of just referencing self.params later.
  115. self._max_body_size = self.params.max_body_size or self.stream.max_buffer_size
  116. self._body_timeout = self.params.body_timeout
  117. # _write_finished is set to True when finish() has been called,
  118. # i.e. there will be no more data sent. Data may still be in the
  119. # stream's write buffer.
  120. self._write_finished = False
  121. # True when we have read the entire incoming body.
  122. self._read_finished = False
  123. # _finish_future resolves when all data has been written and flushed
  124. # to the IOStream.
  125. self._finish_future = Future() # type: Future[None]
  126. # If true, the connection should be closed after this request
  127. # (after the response has been written in the server side,
  128. # and after it has been read in the client)
  129. self._disconnect_on_finish = False
  130. self._clear_callbacks()
  131. # Save the start lines after we read or write them; they
  132. # affect later processing (e.g. 304 responses and HEAD methods
  133. # have content-length but no bodies)
  134. self._request_start_line = None # type: Optional[httputil.RequestStartLine]
  135. self._response_start_line = None # type: Optional[httputil.ResponseStartLine]
  136. self._request_headers = None # type: Optional[httputil.HTTPHeaders]
  137. # True if we are writing output with chunked encoding.
  138. self._chunking_output = False
  139. # While reading a body with a content-length, this is the
  140. # amount left to read.
  141. self._expected_content_remaining = None # type: Optional[int]
  142. # A Future for our outgoing writes, returned by IOStream.write.
  143. self._pending_write = None # type: Optional[Future[None]]
  144. def read_response(self, delegate: httputil.HTTPMessageDelegate) -> Awaitable[bool]:
  145. """Read a single HTTP response.
  146. Typical client-mode usage is to write a request using `write_headers`,
  147. `write`, and `finish`, and then call ``read_response``.
  148. :arg delegate: a `.HTTPMessageDelegate`
  149. Returns a `.Future` that resolves to a bool after the full response has
  150. been read. The result is true if the stream is still open.
  151. """
  152. if self.params.decompress:
  153. delegate = _GzipMessageDelegate(delegate, self.params.chunk_size)
  154. return self._read_message(delegate)
  155. async def _read_message(self, delegate: httputil.HTTPMessageDelegate) -> bool:
  156. need_delegate_close = False
  157. try:
  158. header_future = self.stream.read_until_regex(
  159. b"\r?\n\r?\n", max_bytes=self.params.max_header_size
  160. )
  161. if self.params.header_timeout is None:
  162. header_data = await header_future
  163. else:
  164. try:
  165. header_data = await gen.with_timeout(
  166. self.stream.io_loop.time() + self.params.header_timeout,
  167. header_future,
  168. quiet_exceptions=iostream.StreamClosedError,
  169. )
  170. except gen.TimeoutError:
  171. self.close()
  172. return False
  173. start_line_str, headers = self._parse_headers(header_data)
  174. if self.is_client:
  175. resp_start_line = httputil.parse_response_start_line(start_line_str)
  176. self._response_start_line = resp_start_line
  177. start_line = (
  178. resp_start_line
  179. ) # type: Union[httputil.RequestStartLine, httputil.ResponseStartLine]
  180. # TODO: this will need to change to support client-side keepalive
  181. self._disconnect_on_finish = False
  182. else:
  183. req_start_line = httputil.parse_request_start_line(start_line_str)
  184. self._request_start_line = req_start_line
  185. self._request_headers = headers
  186. start_line = req_start_line
  187. self._disconnect_on_finish = not self._can_keep_alive(
  188. req_start_line, headers
  189. )
  190. need_delegate_close = True
  191. with _ExceptionLoggingContext(app_log):
  192. header_recv_future = delegate.headers_received(start_line, headers)
  193. if header_recv_future is not None:
  194. await header_recv_future
  195. if self.stream is None:
  196. # We've been detached.
  197. need_delegate_close = False
  198. return False
  199. skip_body = False
  200. if self.is_client:
  201. assert isinstance(start_line, httputil.ResponseStartLine)
  202. if (
  203. self._request_start_line is not None
  204. and self._request_start_line.method == "HEAD"
  205. ):
  206. skip_body = True
  207. code = start_line.code
  208. if code == 304:
  209. # 304 responses may include the content-length header
  210. # but do not actually have a body.
  211. # http://tools.ietf.org/html/rfc7230#section-3.3
  212. skip_body = True
  213. if code >= 100 and code < 200:
  214. # 1xx responses should never indicate the presence of
  215. # a body.
  216. if "Content-Length" in headers or "Transfer-Encoding" in headers:
  217. raise httputil.HTTPInputError(
  218. "Response code %d cannot have body" % code
  219. )
  220. # TODO: client delegates will get headers_received twice
  221. # in the case of a 100-continue. Document or change?
  222. await self._read_message(delegate)
  223. else:
  224. if headers.get("Expect") == "100-continue" and not self._write_finished:
  225. self.stream.write(b"HTTP/1.1 100 (Continue)\r\n\r\n")
  226. if not skip_body:
  227. body_future = self._read_body(
  228. resp_start_line.code if self.is_client else 0, headers, delegate
  229. )
  230. if body_future is not None:
  231. if self._body_timeout is None:
  232. await body_future
  233. else:
  234. try:
  235. await gen.with_timeout(
  236. self.stream.io_loop.time() + self._body_timeout,
  237. body_future,
  238. quiet_exceptions=iostream.StreamClosedError,
  239. )
  240. except gen.TimeoutError:
  241. gen_log.info("Timeout reading body from %s", self.context)
  242. self.stream.close()
  243. return False
  244. self._read_finished = True
  245. if not self._write_finished or self.is_client:
  246. need_delegate_close = False
  247. with _ExceptionLoggingContext(app_log):
  248. delegate.finish()
  249. # If we're waiting for the application to produce an asynchronous
  250. # response, and we're not detached, register a close callback
  251. # on the stream (we didn't need one while we were reading)
  252. if (
  253. not self._finish_future.done()
  254. and self.stream is not None
  255. and not self.stream.closed()
  256. ):
  257. self.stream.set_close_callback(self._on_connection_close)
  258. await self._finish_future
  259. if self.is_client and self._disconnect_on_finish:
  260. self.close()
  261. if self.stream is None:
  262. return False
  263. except httputil.HTTPInputError as e:
  264. gen_log.info("Malformed HTTP message from %s: %s", self.context, e)
  265. if not self.is_client:
  266. await self.stream.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
  267. self.close()
  268. return False
  269. finally:
  270. if need_delegate_close:
  271. with _ExceptionLoggingContext(app_log):
  272. delegate.on_connection_close()
  273. header_future = None # type: ignore
  274. self._clear_callbacks()
  275. return True
  276. def _clear_callbacks(self) -> None:
  277. """Clears the callback attributes.
  278. This allows the request handler to be garbage collected more
  279. quickly in CPython by breaking up reference cycles.
  280. """
  281. self._write_callback = None
  282. self._write_future = None # type: Optional[Future[None]]
  283. self._close_callback = None # type: Optional[Callable[[], None]]
  284. if self.stream is not None:
  285. self.stream.set_close_callback(None)
  286. def set_close_callback(self, callback: Optional[Callable[[], None]]) -> None:
  287. """Sets a callback that will be run when the connection is closed.
  288. Note that this callback is slightly different from
  289. `.HTTPMessageDelegate.on_connection_close`: The
  290. `.HTTPMessageDelegate` method is called when the connection is
  291. closed while recieving a message. This callback is used when
  292. there is not an active delegate (for example, on the server
  293. side this callback is used if the client closes the connection
  294. after sending its request but before receiving all the
  295. response.
  296. """
  297. self._close_callback = callback
  298. def _on_connection_close(self) -> None:
  299. # Note that this callback is only registered on the IOStream
  300. # when we have finished reading the request and are waiting for
  301. # the application to produce its response.
  302. if self._close_callback is not None:
  303. callback = self._close_callback
  304. self._close_callback = None
  305. callback()
  306. if not self._finish_future.done():
  307. future_set_result_unless_cancelled(self._finish_future, None)
  308. self._clear_callbacks()
  309. def close(self) -> None:
  310. if self.stream is not None:
  311. self.stream.close()
  312. self._clear_callbacks()
  313. if not self._finish_future.done():
  314. future_set_result_unless_cancelled(self._finish_future, None)
  315. def detach(self) -> iostream.IOStream:
  316. """Take control of the underlying stream.
  317. Returns the underlying `.IOStream` object and stops all further
  318. HTTP processing. May only be called during
  319. `.HTTPMessageDelegate.headers_received`. Intended for implementing
  320. protocols like websockets that tunnel over an HTTP handshake.
  321. """
  322. self._clear_callbacks()
  323. stream = self.stream
  324. self.stream = None # type: ignore
  325. if not self._finish_future.done():
  326. future_set_result_unless_cancelled(self._finish_future, None)
  327. return stream
  328. def set_body_timeout(self, timeout: float) -> None:
  329. """Sets the body timeout for a single request.
  330. Overrides the value from `.HTTP1ConnectionParameters`.
  331. """
  332. self._body_timeout = timeout
  333. def set_max_body_size(self, max_body_size: int) -> None:
  334. """Sets the body size limit for a single request.
  335. Overrides the value from `.HTTP1ConnectionParameters`.
  336. """
  337. self._max_body_size = max_body_size
  338. def write_headers(
  339. self,
  340. start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
  341. headers: httputil.HTTPHeaders,
  342. chunk: bytes = None,
  343. ) -> "Future[None]":
  344. """Implements `.HTTPConnection.write_headers`."""
  345. lines = []
  346. if self.is_client:
  347. assert isinstance(start_line, httputil.RequestStartLine)
  348. self._request_start_line = start_line
  349. lines.append(utf8("%s %s HTTP/1.1" % (start_line[0], start_line[1])))
  350. # Client requests with a non-empty body must have either a
  351. # Content-Length or a Transfer-Encoding.
  352. self._chunking_output = (
  353. start_line.method in ("POST", "PUT", "PATCH")
  354. and "Content-Length" not in headers
  355. and (
  356. "Transfer-Encoding" not in headers
  357. or headers["Transfer-Encoding"] == "chunked"
  358. )
  359. )
  360. else:
  361. assert isinstance(start_line, httputil.ResponseStartLine)
  362. assert self._request_start_line is not None
  363. assert self._request_headers is not None
  364. self._response_start_line = start_line
  365. lines.append(utf8("HTTP/1.1 %d %s" % (start_line[1], start_line[2])))
  366. self._chunking_output = (
  367. # TODO: should this use
  368. # self._request_start_line.version or
  369. # start_line.version?
  370. self._request_start_line.version == "HTTP/1.1"
  371. # 1xx, 204 and 304 responses have no body (not even a zero-length
  372. # body), and so should not have either Content-Length or
  373. # Transfer-Encoding headers.
  374. and start_line.code not in (204, 304)
  375. and (start_line.code < 100 or start_line.code >= 200)
  376. # No need to chunk the output if a Content-Length is specified.
  377. and "Content-Length" not in headers
  378. # Applications are discouraged from touching Transfer-Encoding,
  379. # but if they do, leave it alone.
  380. and "Transfer-Encoding" not in headers
  381. )
  382. # If connection to a 1.1 client will be closed, inform client
  383. if (
  384. self._request_start_line.version == "HTTP/1.1"
  385. and self._disconnect_on_finish
  386. ):
  387. headers["Connection"] = "close"
  388. # If a 1.0 client asked for keep-alive, add the header.
  389. if (
  390. self._request_start_line.version == "HTTP/1.0"
  391. and self._request_headers.get("Connection", "").lower() == "keep-alive"
  392. ):
  393. headers["Connection"] = "Keep-Alive"
  394. if self._chunking_output:
  395. headers["Transfer-Encoding"] = "chunked"
  396. if not self.is_client and (
  397. self._request_start_line.method == "HEAD"
  398. or cast(httputil.ResponseStartLine, start_line).code == 304
  399. ):
  400. self._expected_content_remaining = 0
  401. elif "Content-Length" in headers:
  402. self._expected_content_remaining = int(headers["Content-Length"])
  403. else:
  404. self._expected_content_remaining = None
  405. # TODO: headers are supposed to be of type str, but we still have some
  406. # cases that let bytes slip through. Remove these native_str calls when those
  407. # are fixed.
  408. header_lines = (
  409. native_str(n) + ": " + native_str(v) for n, v in headers.get_all()
  410. )
  411. lines.extend(l.encode("latin1") for l in header_lines)
  412. for line in lines:
  413. if b"\n" in line:
  414. raise ValueError("Newline in header: " + repr(line))
  415. future = None
  416. if self.stream.closed():
  417. future = self._write_future = Future()
  418. future.set_exception(iostream.StreamClosedError())
  419. future.exception()
  420. else:
  421. future = self._write_future = Future()
  422. data = b"\r\n".join(lines) + b"\r\n\r\n"
  423. if chunk:
  424. data += self._format_chunk(chunk)
  425. self._pending_write = self.stream.write(data)
  426. future_add_done_callback(self._pending_write, self._on_write_complete)
  427. return future
  428. def _format_chunk(self, chunk: bytes) -> bytes:
  429. if self._expected_content_remaining is not None:
  430. self._expected_content_remaining -= len(chunk)
  431. if self._expected_content_remaining < 0:
  432. # Close the stream now to stop further framing errors.
  433. self.stream.close()
  434. raise httputil.HTTPOutputError(
  435. "Tried to write more data than Content-Length"
  436. )
  437. if self._chunking_output and chunk:
  438. # Don't write out empty chunks because that means END-OF-STREAM
  439. # with chunked encoding
  440. return utf8("%x" % len(chunk)) + b"\r\n" + chunk + b"\r\n"
  441. else:
  442. return chunk
  443. def write(self, chunk: bytes) -> "Future[None]":
  444. """Implements `.HTTPConnection.write`.
  445. For backwards compatibility it is allowed but deprecated to
  446. skip `write_headers` and instead call `write()` with a
  447. pre-encoded header block.
  448. """
  449. future = None
  450. if self.stream.closed():
  451. future = self._write_future = Future()
  452. self._write_future.set_exception(iostream.StreamClosedError())
  453. self._write_future.exception()
  454. else:
  455. future = self._write_future = Future()
  456. self._pending_write = self.stream.write(self._format_chunk(chunk))
  457. future_add_done_callback(self._pending_write, self._on_write_complete)
  458. return future
  459. def finish(self) -> None:
  460. """Implements `.HTTPConnection.finish`."""
  461. if (
  462. self._expected_content_remaining is not None
  463. and self._expected_content_remaining != 0
  464. and not self.stream.closed()
  465. ):
  466. self.stream.close()
  467. raise httputil.HTTPOutputError(
  468. "Tried to write %d bytes less than Content-Length"
  469. % self._expected_content_remaining
  470. )
  471. if self._chunking_output:
  472. if not self.stream.closed():
  473. self._pending_write = self.stream.write(b"0\r\n\r\n")
  474. self._pending_write.add_done_callback(self._on_write_complete)
  475. self._write_finished = True
  476. # If the app finished the request while we're still reading,
  477. # divert any remaining data away from the delegate and
  478. # close the connection when we're done sending our response.
  479. # Closing the connection is the only way to avoid reading the
  480. # whole input body.
  481. if not self._read_finished:
  482. self._disconnect_on_finish = True
  483. # No more data is coming, so instruct TCP to send any remaining
  484. # data immediately instead of waiting for a full packet or ack.
  485. self.stream.set_nodelay(True)
  486. if self._pending_write is None:
  487. self._finish_request(None)
  488. else:
  489. future_add_done_callback(self._pending_write, self._finish_request)
  490. def _on_write_complete(self, future: "Future[None]") -> None:
  491. exc = future.exception()
  492. if exc is not None and not isinstance(exc, iostream.StreamClosedError):
  493. future.result()
  494. if self._write_callback is not None:
  495. callback = self._write_callback
  496. self._write_callback = None
  497. self.stream.io_loop.add_callback(callback)
  498. if self._write_future is not None:
  499. future = self._write_future
  500. self._write_future = None
  501. future_set_result_unless_cancelled(future, None)
  502. def _can_keep_alive(
  503. self, start_line: httputil.RequestStartLine, headers: httputil.HTTPHeaders
  504. ) -> bool:
  505. if self.params.no_keep_alive:
  506. return False
  507. connection_header = headers.get("Connection")
  508. if connection_header is not None:
  509. connection_header = connection_header.lower()
  510. if start_line.version == "HTTP/1.1":
  511. return connection_header != "close"
  512. elif (
  513. "Content-Length" in headers
  514. or headers.get("Transfer-Encoding", "").lower() == "chunked"
  515. or getattr(start_line, "method", None) in ("HEAD", "GET")
  516. ):
  517. # start_line may be a request or response start line; only
  518. # the former has a method attribute.
  519. return connection_header == "keep-alive"
  520. return False
  521. def _finish_request(self, future: "Optional[Future[None]]") -> None:
  522. self._clear_callbacks()
  523. if not self.is_client and self._disconnect_on_finish:
  524. self.close()
  525. return
  526. # Turn Nagle's algorithm back on, leaving the stream in its
  527. # default state for the next request.
  528. self.stream.set_nodelay(False)
  529. if not self._finish_future.done():
  530. future_set_result_unless_cancelled(self._finish_future, None)
  531. def _parse_headers(self, data: bytes) -> Tuple[str, httputil.HTTPHeaders]:
  532. # The lstrip removes newlines that some implementations sometimes
  533. # insert between messages of a reused connection. Per RFC 7230,
  534. # we SHOULD ignore at least one empty line before the request.
  535. # http://tools.ietf.org/html/rfc7230#section-3.5
  536. data_str = native_str(data.decode("latin1")).lstrip("\r\n")
  537. # RFC 7230 section allows for both CRLF and bare LF.
  538. eol = data_str.find("\n")
  539. start_line = data_str[:eol].rstrip("\r")
  540. headers = httputil.HTTPHeaders.parse(data_str[eol:])
  541. return start_line, headers
  542. def _read_body(
  543. self,
  544. code: int,
  545. headers: httputil.HTTPHeaders,
  546. delegate: httputil.HTTPMessageDelegate,
  547. ) -> Optional[Awaitable[None]]:
  548. if "Content-Length" in headers:
  549. if "Transfer-Encoding" in headers:
  550. # Response cannot contain both Content-Length and
  551. # Transfer-Encoding headers.
  552. # http://tools.ietf.org/html/rfc7230#section-3.3.3
  553. raise httputil.HTTPInputError(
  554. "Response with both Transfer-Encoding and Content-Length"
  555. )
  556. if "," in headers["Content-Length"]:
  557. # Proxies sometimes cause Content-Length headers to get
  558. # duplicated. If all the values are identical then we can
  559. # use them but if they differ it's an error.
  560. pieces = re.split(r",\s*", headers["Content-Length"])
  561. if any(i != pieces[0] for i in pieces):
  562. raise httputil.HTTPInputError(
  563. "Multiple unequal Content-Lengths: %r"
  564. % headers["Content-Length"]
  565. )
  566. headers["Content-Length"] = pieces[0]
  567. try:
  568. content_length = int(headers["Content-Length"]) # type: Optional[int]
  569. except ValueError:
  570. # Handles non-integer Content-Length value.
  571. raise httputil.HTTPInputError(
  572. "Only integer Content-Length is allowed: %s"
  573. % headers["Content-Length"]
  574. )
  575. if cast(int, content_length) > self._max_body_size:
  576. raise httputil.HTTPInputError("Content-Length too long")
  577. else:
  578. content_length = None
  579. if code == 204:
  580. # This response code is not allowed to have a non-empty body,
  581. # and has an implicit length of zero instead of read-until-close.
  582. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
  583. if "Transfer-Encoding" in headers or content_length not in (None, 0):
  584. raise httputil.HTTPInputError(
  585. "Response with code %d should not have body" % code
  586. )
  587. content_length = 0
  588. if content_length is not None:
  589. return self._read_fixed_body(content_length, delegate)
  590. if headers.get("Transfer-Encoding", "").lower() == "chunked":
  591. return self._read_chunked_body(delegate)
  592. if self.is_client:
  593. return self._read_body_until_close(delegate)
  594. return None
  595. async def _read_fixed_body(
  596. self, content_length: int, delegate: httputil.HTTPMessageDelegate
  597. ) -> None:
  598. while content_length > 0:
  599. body = await self.stream.read_bytes(
  600. min(self.params.chunk_size, content_length), partial=True
  601. )
  602. content_length -= len(body)
  603. if not self._write_finished or self.is_client:
  604. with _ExceptionLoggingContext(app_log):
  605. ret = delegate.data_received(body)
  606. if ret is not None:
  607. await ret
  608. async def _read_chunked_body(self, delegate: httputil.HTTPMessageDelegate) -> None:
  609. # TODO: "chunk extensions" http://tools.ietf.org/html/rfc2616#section-3.6.1
  610. total_size = 0
  611. while True:
  612. chunk_len_str = await self.stream.read_until(b"\r\n", max_bytes=64)
  613. chunk_len = int(chunk_len_str.strip(), 16)
  614. if chunk_len == 0:
  615. crlf = await self.stream.read_bytes(2)
  616. if crlf != b"\r\n":
  617. raise httputil.HTTPInputError(
  618. "improperly terminated chunked request"
  619. )
  620. return
  621. total_size += chunk_len
  622. if total_size > self._max_body_size:
  623. raise httputil.HTTPInputError("chunked body too large")
  624. bytes_to_read = chunk_len
  625. while bytes_to_read:
  626. chunk = await self.stream.read_bytes(
  627. min(bytes_to_read, self.params.chunk_size), partial=True
  628. )
  629. bytes_to_read -= len(chunk)
  630. if not self._write_finished or self.is_client:
  631. with _ExceptionLoggingContext(app_log):
  632. ret = delegate.data_received(chunk)
  633. if ret is not None:
  634. await ret
  635. # chunk ends with \r\n
  636. crlf = await self.stream.read_bytes(2)
  637. assert crlf == b"\r\n"
  638. async def _read_body_until_close(
  639. self, delegate: httputil.HTTPMessageDelegate
  640. ) -> None:
  641. body = await self.stream.read_until_close()
  642. if not self._write_finished or self.is_client:
  643. with _ExceptionLoggingContext(app_log):
  644. ret = delegate.data_received(body)
  645. if ret is not None:
  646. await ret
  647. class _GzipMessageDelegate(httputil.HTTPMessageDelegate):
  648. """Wraps an `HTTPMessageDelegate` to decode ``Content-Encoding: gzip``.
  649. """
  650. def __init__(self, delegate: httputil.HTTPMessageDelegate, chunk_size: int) -> None:
  651. self._delegate = delegate
  652. self._chunk_size = chunk_size
  653. self._decompressor = None # type: Optional[GzipDecompressor]
  654. def headers_received(
  655. self,
  656. start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
  657. headers: httputil.HTTPHeaders,
  658. ) -> Optional[Awaitable[None]]:
  659. if headers.get("Content-Encoding") == "gzip":
  660. self._decompressor = GzipDecompressor()
  661. # Downstream delegates will only see uncompressed data,
  662. # so rename the content-encoding header.
  663. # (but note that curl_httpclient doesn't do this).
  664. headers.add("X-Consumed-Content-Encoding", headers["Content-Encoding"])
  665. del headers["Content-Encoding"]
  666. return self._delegate.headers_received(start_line, headers)
  667. async def data_received(self, chunk: bytes) -> None:
  668. if self._decompressor:
  669. compressed_data = chunk
  670. while compressed_data:
  671. decompressed = self._decompressor.decompress(
  672. compressed_data, self._chunk_size
  673. )
  674. if decompressed:
  675. ret = self._delegate.data_received(decompressed)
  676. if ret is not None:
  677. await ret
  678. compressed_data = self._decompressor.unconsumed_tail
  679. else:
  680. ret = self._delegate.data_received(chunk)
  681. if ret is not None:
  682. await ret
  683. def finish(self) -> None:
  684. if self._decompressor is not None:
  685. tail = self._decompressor.flush()
  686. if tail:
  687. # The tail should always be empty: decompress returned
  688. # all that it can in data_received and the only
  689. # purpose of the flush call is to detect errors such
  690. # as truncated input. If we did legitimately get a new
  691. # chunk at this point we'd need to change the
  692. # interface to make finish() a coroutine.
  693. raise ValueError(
  694. "decompressor.flush returned data; possile truncated input"
  695. )
  696. return self._delegate.finish()
  697. def on_connection_close(self) -> None:
  698. return self._delegate.on_connection_close()
  699. class HTTP1ServerConnection(object):
  700. """An HTTP/1.x server."""
  701. def __init__(
  702. self,
  703. stream: iostream.IOStream,
  704. params: HTTP1ConnectionParameters = None,
  705. context: object = None,
  706. ) -> None:
  707. """
  708. :arg stream: an `.IOStream`
  709. :arg params: a `.HTTP1ConnectionParameters` or None
  710. :arg context: an opaque application-defined object that is accessible
  711. as ``connection.context``
  712. """
  713. self.stream = stream
  714. if params is None:
  715. params = HTTP1ConnectionParameters()
  716. self.params = params
  717. self.context = context
  718. self._serving_future = None # type: Optional[Future[None]]
  719. async def close(self) -> None:
  720. """Closes the connection.
  721. Returns a `.Future` that resolves after the serving loop has exited.
  722. """
  723. self.stream.close()
  724. # Block until the serving loop is done, but ignore any exceptions
  725. # (start_serving is already responsible for logging them).
  726. assert self._serving_future is not None
  727. try:
  728. await self._serving_future
  729. except Exception:
  730. pass
  731. def start_serving(self, delegate: httputil.HTTPServerConnectionDelegate) -> None:
  732. """Starts serving requests on this connection.
  733. :arg delegate: a `.HTTPServerConnectionDelegate`
  734. """
  735. assert isinstance(delegate, httputil.HTTPServerConnectionDelegate)
  736. fut = gen.convert_yielded(self._server_request_loop(delegate))
  737. self._serving_future = fut
  738. # Register the future on the IOLoop so its errors get logged.
  739. self.stream.io_loop.add_future(fut, lambda f: f.result())
  740. async def _server_request_loop(
  741. self, delegate: httputil.HTTPServerConnectionDelegate
  742. ) -> None:
  743. try:
  744. while True:
  745. conn = HTTP1Connection(self.stream, False, self.params, self.context)
  746. request_delegate = delegate.start_request(self, conn)
  747. try:
  748. ret = await conn.read_response(request_delegate)
  749. except (
  750. iostream.StreamClosedError,
  751. iostream.UnsatisfiableReadError,
  752. asyncio.CancelledError,
  753. ):
  754. return
  755. except _QuietException:
  756. # This exception was already logged.
  757. conn.close()
  758. return
  759. except Exception:
  760. gen_log.error("Uncaught exception", exc_info=True)
  761. conn.close()
  762. return
  763. if not ret:
  764. return
  765. await asyncio.sleep(0)
  766. finally:
  767. delegate.on_close(self)