http1connection.py 30 KB

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