You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

969 lines
33 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain 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,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import abc
  16. import html
  17. import logging
  18. import types
  19. import urllib
  20. from http import HTTPStatus
  21. from inspect import isawaitable
  22. from typing import (
  23. TYPE_CHECKING,
  24. Any,
  25. Awaitable,
  26. Callable,
  27. Dict,
  28. Iterable,
  29. Iterator,
  30. List,
  31. NoReturn,
  32. Optional,
  33. Pattern,
  34. Tuple,
  35. Union,
  36. )
  37. import attr
  38. import jinja2
  39. from canonicaljson import encode_canonical_json
  40. from typing_extensions import Protocol
  41. from zope.interface import implementer
  42. from twisted.internet import defer, interfaces
  43. from twisted.internet.defer import CancelledError
  44. from twisted.python import failure
  45. from twisted.web import resource
  46. from twisted.web.server import NOT_DONE_YET, Request
  47. from twisted.web.static import File
  48. from twisted.web.util import redirectTo
  49. from synapse.api.errors import (
  50. CodeMessageException,
  51. Codes,
  52. RedirectException,
  53. SynapseError,
  54. UnrecognizedRequestError,
  55. )
  56. from synapse.config.homeserver import HomeServerConfig
  57. from synapse.http.site import SynapseRequest
  58. from synapse.logging.context import defer_to_thread, preserve_fn, run_in_background
  59. from synapse.logging.opentracing import active_span, start_active_span, trace_servlet
  60. from synapse.util import json_encoder
  61. from synapse.util.caches import intern_dict
  62. from synapse.util.cancellation import is_function_cancellable
  63. from synapse.util.iterutils import chunk_seq
  64. if TYPE_CHECKING:
  65. import opentracing
  66. from synapse.server import HomeServer
  67. logger = logging.getLogger(__name__)
  68. HTML_ERROR_TEMPLATE = """<!DOCTYPE html>
  69. <html lang=en>
  70. <head>
  71. <meta charset="utf-8">
  72. <title>Error {code}</title>
  73. </head>
  74. <body>
  75. <p>{msg}</p>
  76. </body>
  77. </html>
  78. """
  79. # A fictional HTTP status code for requests where the client has disconnected and we
  80. # successfully cancelled the request. Used only for logging purposes. Clients will never
  81. # observe this code unless cancellations leak across requests or we raise a
  82. # `CancelledError` ourselves.
  83. # Analogous to nginx's 499 status code:
  84. # https://github.com/nginx/nginx/blob/release-1.21.6/src/http/ngx_http_request.h#L128-L134
  85. HTTP_STATUS_REQUEST_CANCELLED = 499
  86. def return_json_error(
  87. f: failure.Failure, request: SynapseRequest, config: Optional[HomeServerConfig]
  88. ) -> None:
  89. """Sends a JSON error response to clients."""
  90. if f.check(SynapseError):
  91. # mypy doesn't understand that f.check asserts the type.
  92. exc: SynapseError = f.value # type: ignore
  93. error_code = exc.code
  94. error_dict = exc.error_dict(config)
  95. logger.info("%s SynapseError: %s - %s", request, error_code, exc.msg)
  96. elif f.check(CancelledError):
  97. error_code = HTTP_STATUS_REQUEST_CANCELLED
  98. error_dict = {"error": "Request cancelled", "errcode": Codes.UNKNOWN}
  99. if not request._disconnected:
  100. logger.error(
  101. "Got cancellation before client disconnection from %r: %r",
  102. request.request_metrics.name,
  103. request,
  104. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
  105. )
  106. else:
  107. error_code = 500
  108. error_dict = {"error": "Internal server error", "errcode": Codes.UNKNOWN}
  109. logger.error(
  110. "Failed handle request via %r: %r",
  111. request.request_metrics.name,
  112. request,
  113. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
  114. )
  115. # Only respond with an error response if we haven't already started writing,
  116. # otherwise lets just kill the connection
  117. if request.startedWriting:
  118. if request.transport:
  119. try:
  120. request.transport.abortConnection()
  121. except Exception:
  122. # abortConnection throws if the connection is already closed
  123. pass
  124. else:
  125. respond_with_json(
  126. request,
  127. error_code,
  128. error_dict,
  129. send_cors=True,
  130. )
  131. def return_html_error(
  132. f: failure.Failure,
  133. request: Request,
  134. error_template: Union[str, jinja2.Template],
  135. ) -> None:
  136. """Sends an HTML error page corresponding to the given failure.
  137. Handles RedirectException and other CodeMessageExceptions (such as SynapseError)
  138. Args:
  139. f: the error to report
  140. request: the failing request
  141. error_template: the HTML template. Can be either a string (with `{code}`,
  142. `{msg}` placeholders), or a jinja2 template
  143. """
  144. if f.check(CodeMessageException):
  145. # mypy doesn't understand that f.check asserts the type.
  146. cme: CodeMessageException = f.value # type: ignore
  147. code = cme.code
  148. msg = cme.msg
  149. if isinstance(cme, RedirectException):
  150. logger.info("%s redirect to %s", request, cme.location)
  151. request.setHeader(b"location", cme.location)
  152. request.cookies.extend(cme.cookies)
  153. elif isinstance(cme, SynapseError):
  154. logger.info("%s SynapseError: %s - %s", request, code, msg)
  155. else:
  156. logger.error(
  157. "Failed handle request %r",
  158. request,
  159. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
  160. )
  161. elif f.check(CancelledError):
  162. code = HTTP_STATUS_REQUEST_CANCELLED
  163. msg = "Request cancelled"
  164. if not request._disconnected:
  165. logger.error(
  166. "Got cancellation before client disconnection when handling request %r",
  167. request,
  168. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
  169. )
  170. else:
  171. code = HTTPStatus.INTERNAL_SERVER_ERROR
  172. msg = "Internal server error"
  173. logger.error(
  174. "Failed handle request %r",
  175. request,
  176. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore[arg-type]
  177. )
  178. if isinstance(error_template, str):
  179. body = error_template.format(code=code, msg=html.escape(msg))
  180. else:
  181. body = error_template.render(code=code, msg=msg)
  182. respond_with_html(request, code, body)
  183. def wrap_async_request_handler(
  184. h: Callable[["_AsyncResource", SynapseRequest], Awaitable[None]]
  185. ) -> Callable[["_AsyncResource", SynapseRequest], "defer.Deferred[None]"]:
  186. """Wraps an async request handler so that it calls request.processing.
  187. This helps ensure that work done by the request handler after the request is completed
  188. is correctly recorded against the request metrics/logs.
  189. The handler method must have a signature of "handle_foo(self, request)",
  190. where "request" must be a SynapseRequest.
  191. The handler may return a deferred, in which case the completion of the request isn't
  192. logged until the deferred completes.
  193. """
  194. async def wrapped_async_request_handler(
  195. self: "_AsyncResource", request: SynapseRequest
  196. ) -> None:
  197. with request.processing():
  198. await h(self, request)
  199. # we need to preserve_fn here, because the synchronous render method won't yield for
  200. # us (obviously)
  201. return preserve_fn(wrapped_async_request_handler)
  202. # Type of a callback method for processing requests
  203. # it is actually called with a SynapseRequest and a kwargs dict for the params,
  204. # but I can't figure out how to represent that.
  205. ServletCallback = Callable[
  206. ..., Union[None, Awaitable[None], Tuple[int, Any], Awaitable[Tuple[int, Any]]]
  207. ]
  208. class HttpServer(Protocol):
  209. """Interface for registering callbacks on a HTTP server"""
  210. def register_paths(
  211. self,
  212. method: str,
  213. path_patterns: Iterable[Pattern],
  214. callback: ServletCallback,
  215. servlet_classname: str,
  216. ) -> None:
  217. """Register a callback that gets fired if we receive a http request
  218. with the given method for a path that matches the given regex.
  219. If the regex contains groups these gets passed to the callback via
  220. an unpacked tuple.
  221. The callback may be marked with the `@cancellable` decorator, which will
  222. cause request processing to be cancelled when clients disconnect early.
  223. Args:
  224. method: The HTTP method to listen to.
  225. path_patterns: The regex used to match requests.
  226. callback: The function to fire if we receive a matched
  227. request. The first argument will be the request object and
  228. subsequent arguments will be any matched groups from the regex.
  229. This should return either tuple of (code, response), or None.
  230. servlet_classname (str): The name of the handler to be used in prometheus
  231. and opentracing logs.
  232. """
  233. class _AsyncResource(resource.Resource, metaclass=abc.ABCMeta):
  234. """Base class for resources that have async handlers.
  235. Sub classes can either implement `_async_render_<METHOD>` to handle
  236. requests by method, or override `_async_render` to handle all requests.
  237. Args:
  238. extract_context: Whether to attempt to extract the opentracing
  239. context from the request the servlet is handling.
  240. """
  241. def __init__(self, extract_context: bool = False):
  242. super().__init__()
  243. self._extract_context = extract_context
  244. def render(self, request: SynapseRequest) -> int:
  245. """This gets called by twisted every time someone sends us a request."""
  246. request.render_deferred = defer.ensureDeferred(
  247. self._async_render_wrapper(request)
  248. )
  249. return NOT_DONE_YET
  250. @wrap_async_request_handler
  251. async def _async_render_wrapper(self, request: SynapseRequest) -> None:
  252. """This is a wrapper that delegates to `_async_render` and handles
  253. exceptions, return values, metrics, etc.
  254. """
  255. try:
  256. request.request_metrics.name = self.__class__.__name__
  257. with trace_servlet(request, self._extract_context):
  258. callback_return = await self._async_render(request)
  259. if callback_return is not None:
  260. code, response = callback_return
  261. self._send_response(request, code, response)
  262. except Exception:
  263. # failure.Failure() fishes the original Failure out
  264. # of our stack, and thus gives us a sensible stack
  265. # trace.
  266. f = failure.Failure()
  267. self._send_error_response(f, request)
  268. async def _async_render(self, request: SynapseRequest) -> Optional[Tuple[int, Any]]:
  269. """Delegates to `_async_render_<METHOD>` methods, or returns a 400 if
  270. no appropriate method exists. Can be overridden in sub classes for
  271. different routing.
  272. """
  273. # Treat HEAD requests as GET requests.
  274. request_method = request.method.decode("ascii")
  275. if request_method == "HEAD":
  276. request_method = "GET"
  277. method_handler = getattr(self, "_async_render_%s" % (request_method,), None)
  278. if method_handler:
  279. request.is_render_cancellable = is_function_cancellable(method_handler)
  280. raw_callback_return = method_handler(request)
  281. # Is it synchronous? We'll allow this for now.
  282. if isawaitable(raw_callback_return):
  283. callback_return = await raw_callback_return
  284. else:
  285. callback_return = raw_callback_return
  286. return callback_return
  287. _unrecognised_request_handler(request)
  288. @abc.abstractmethod
  289. def _send_response(
  290. self,
  291. request: SynapseRequest,
  292. code: int,
  293. response_object: Any,
  294. ) -> None:
  295. raise NotImplementedError()
  296. @abc.abstractmethod
  297. def _send_error_response(
  298. self,
  299. f: failure.Failure,
  300. request: SynapseRequest,
  301. ) -> None:
  302. raise NotImplementedError()
  303. class DirectServeJsonResource(_AsyncResource):
  304. """A resource that will call `self._async_on_<METHOD>` on new requests,
  305. formatting responses and errors as JSON.
  306. """
  307. def __init__(self, canonical_json: bool = False, extract_context: bool = False):
  308. super().__init__(extract_context)
  309. self.canonical_json = canonical_json
  310. def _send_response(
  311. self,
  312. request: SynapseRequest,
  313. code: int,
  314. response_object: Any,
  315. ) -> None:
  316. """Implements _AsyncResource._send_response"""
  317. # TODO: Only enable CORS for the requests that need it.
  318. respond_with_json(
  319. request,
  320. code,
  321. response_object,
  322. send_cors=True,
  323. canonical_json=self.canonical_json,
  324. )
  325. def _send_error_response(
  326. self,
  327. f: failure.Failure,
  328. request: SynapseRequest,
  329. ) -> None:
  330. """Implements _AsyncResource._send_error_response"""
  331. return_json_error(f, request, None)
  332. @attr.s(slots=True, frozen=True, auto_attribs=True)
  333. class _PathEntry:
  334. pattern: Pattern
  335. callback: ServletCallback
  336. servlet_classname: str
  337. class JsonResource(DirectServeJsonResource):
  338. """This implements the HttpServer interface and provides JSON support for
  339. Resources.
  340. Register callbacks via register_paths()
  341. Callbacks can return a tuple of status code and a dict in which case the
  342. the dict will automatically be sent to the client as a JSON object.
  343. The JsonResource is primarily intended for returning JSON, but callbacks
  344. may send something other than JSON, they may do so by using the methods
  345. on the request object and instead returning None.
  346. """
  347. isLeaf = True
  348. def __init__(
  349. self,
  350. hs: "HomeServer",
  351. canonical_json: bool = True,
  352. extract_context: bool = False,
  353. ):
  354. super().__init__(canonical_json, extract_context)
  355. self.clock = hs.get_clock()
  356. self.path_regexs: Dict[bytes, List[_PathEntry]] = {}
  357. self.hs = hs
  358. def register_paths(
  359. self,
  360. method: str,
  361. path_patterns: Iterable[Pattern],
  362. callback: ServletCallback,
  363. servlet_classname: str,
  364. ) -> None:
  365. """
  366. Registers a request handler against a regular expression. Later request URLs are
  367. checked against these regular expressions in order to identify an appropriate
  368. handler for that request.
  369. Args:
  370. method: GET, POST etc
  371. path_patterns: A list of regular expressions to which the request
  372. URLs are compared.
  373. callback: The handler for the request. Usually a Servlet
  374. servlet_classname: The name of the handler to be used in prometheus
  375. and opentracing logs.
  376. """
  377. method_bytes = method.encode("utf-8")
  378. for path_pattern in path_patterns:
  379. logger.debug("Registering for %s %s", method, path_pattern.pattern)
  380. self.path_regexs.setdefault(method_bytes, []).append(
  381. _PathEntry(path_pattern, callback, servlet_classname)
  382. )
  383. def _get_handler_for_request(
  384. self, request: SynapseRequest
  385. ) -> Tuple[ServletCallback, str, Dict[str, str]]:
  386. """Finds a callback method to handle the given request.
  387. Returns:
  388. A tuple of the callback to use, the name of the servlet, and the
  389. key word arguments to pass to the callback
  390. """
  391. # At this point the path must be bytes.
  392. request_path_bytes: bytes = request.path # type: ignore
  393. request_path = request_path_bytes.decode("ascii")
  394. # Treat HEAD requests as GET requests.
  395. request_method = request.method
  396. if request_method == b"HEAD":
  397. request_method = b"GET"
  398. # Loop through all the registered callbacks to check if the method
  399. # and path regex match
  400. for path_entry in self.path_regexs.get(request_method, []):
  401. m = path_entry.pattern.match(request_path)
  402. if m:
  403. # We found a match!
  404. return path_entry.callback, path_entry.servlet_classname, m.groupdict()
  405. # Huh. No one wanted to handle that? Fiiiiiine. Send 400.
  406. return _unrecognised_request_handler, "unrecognised_request_handler", {}
  407. async def _async_render(self, request: SynapseRequest) -> Tuple[int, Any]:
  408. callback, servlet_classname, group_dict = self._get_handler_for_request(request)
  409. request.is_render_cancellable = is_function_cancellable(callback)
  410. # Make sure we have an appropriate name for this handler in prometheus
  411. # (rather than the default of JsonResource).
  412. request.request_metrics.name = servlet_classname
  413. # Now trigger the callback. If it returns a response, we send it
  414. # here. If it throws an exception, that is handled by the wrapper
  415. # installed by @request_handler.
  416. kwargs = intern_dict(
  417. {
  418. name: urllib.parse.unquote(value) if value else value
  419. for name, value in group_dict.items()
  420. }
  421. )
  422. raw_callback_return = callback(request, **kwargs)
  423. # Is it synchronous? We'll allow this for now.
  424. if isinstance(raw_callback_return, (defer.Deferred, types.CoroutineType)):
  425. callback_return = await raw_callback_return
  426. else:
  427. callback_return = raw_callback_return
  428. return callback_return
  429. def _send_error_response(
  430. self,
  431. f: failure.Failure,
  432. request: SynapseRequest,
  433. ) -> None:
  434. """Implements _AsyncResource._send_error_response"""
  435. return_json_error(f, request, self.hs.config)
  436. class DirectServeHtmlResource(_AsyncResource):
  437. """A resource that will call `self._async_on_<METHOD>` on new requests,
  438. formatting responses and errors as HTML.
  439. """
  440. # The error template to use for this resource
  441. ERROR_TEMPLATE = HTML_ERROR_TEMPLATE
  442. def _send_response(
  443. self,
  444. request: SynapseRequest,
  445. code: int,
  446. response_object: Any,
  447. ) -> None:
  448. """Implements _AsyncResource._send_response"""
  449. # We expect to get bytes for us to write
  450. assert isinstance(response_object, bytes)
  451. html_bytes = response_object
  452. respond_with_html_bytes(request, 200, html_bytes)
  453. def _send_error_response(
  454. self,
  455. f: failure.Failure,
  456. request: SynapseRequest,
  457. ) -> None:
  458. """Implements _AsyncResource._send_error_response"""
  459. return_html_error(f, request, self.ERROR_TEMPLATE)
  460. class StaticResource(File):
  461. """
  462. A resource that represents a plain non-interpreted file or directory.
  463. Differs from the File resource by adding clickjacking protection.
  464. """
  465. def render_GET(self, request: Request) -> bytes:
  466. set_clickjacking_protection_headers(request)
  467. return super().render_GET(request)
  468. def _unrecognised_request_handler(request: Request) -> NoReturn:
  469. """Request handler for unrecognised requests
  470. This is a request handler suitable for return from
  471. _get_handler_for_request. It actually just raises an
  472. UnrecognizedRequestError.
  473. Args:
  474. request: Unused, but passed in to match the signature of ServletCallback.
  475. """
  476. raise UnrecognizedRequestError()
  477. class RootRedirect(resource.Resource):
  478. """Redirects the root '/' path to another path."""
  479. def __init__(self, path: str):
  480. super().__init__()
  481. self.url = path
  482. def render_GET(self, request: Request) -> bytes:
  483. return redirectTo(self.url.encode("ascii"), request)
  484. def getChild(self, name: str, request: Request) -> resource.Resource:
  485. if len(name) == 0:
  486. return self # select ourselves as the child to render
  487. return super().getChild(name, request)
  488. class OptionsResource(resource.Resource):
  489. """Responds to OPTION requests for itself and all children."""
  490. def render_OPTIONS(self, request: Request) -> bytes:
  491. request.setResponseCode(204)
  492. request.setHeader(b"Content-Length", b"0")
  493. set_cors_headers(request)
  494. return b""
  495. def getChildWithDefault(self, path: str, request: Request) -> resource.Resource:
  496. if request.method == b"OPTIONS":
  497. return self # select ourselves as the child to render
  498. return super().getChildWithDefault(path, request)
  499. class RootOptionsRedirectResource(OptionsResource, RootRedirect):
  500. pass
  501. @implementer(interfaces.IPushProducer)
  502. class _ByteProducer:
  503. """
  504. Iteratively write bytes to the request.
  505. """
  506. # The minimum number of bytes for each chunk. Note that the last chunk will
  507. # usually be smaller than this.
  508. min_chunk_size = 1024
  509. def __init__(
  510. self,
  511. request: Request,
  512. iterator: Iterator[bytes],
  513. ):
  514. self._request: Optional[Request] = request
  515. self._iterator = iterator
  516. self._paused = False
  517. try:
  518. self._request.registerProducer(self, True)
  519. except AttributeError as e:
  520. # Calling self._request.registerProducer might raise an AttributeError since
  521. # the underlying Twisted code calls self._request.channel.registerProducer,
  522. # however self._request.channel will be None if the connection was lost.
  523. logger.info("Connection disconnected before response was written: %r", e)
  524. # We drop our references to data we'll not use.
  525. self._request = None
  526. self._iterator = iter(())
  527. else:
  528. # Start producing if `registerProducer` was successful
  529. self.resumeProducing()
  530. def _send_data(self, data: List[bytes]) -> None:
  531. """
  532. Send a list of bytes as a chunk of a response.
  533. """
  534. if not data or not self._request:
  535. return
  536. self._request.write(b"".join(data))
  537. def pauseProducing(self) -> None:
  538. self._paused = True
  539. def resumeProducing(self) -> None:
  540. # We've stopped producing in the meantime (note that this might be
  541. # re-entrant after calling write).
  542. if not self._request:
  543. return
  544. self._paused = False
  545. # Write until there's backpressure telling us to stop.
  546. while not self._paused:
  547. # Get the next chunk and write it to the request.
  548. #
  549. # The output of the JSON encoder is buffered and coalesced until
  550. # min_chunk_size is reached. This is because JSON encoders produce
  551. # very small output per iteration and the Request object converts
  552. # each call to write() to a separate chunk. Without this there would
  553. # be an explosion in bytes written (e.g. b"{" becoming "1\r\n{\r\n").
  554. #
  555. # Note that buffer stores a list of bytes (instead of appending to
  556. # bytes) to hopefully avoid many allocations.
  557. buffer = []
  558. buffered_bytes = 0
  559. while buffered_bytes < self.min_chunk_size:
  560. try:
  561. data = next(self._iterator)
  562. buffer.append(data)
  563. buffered_bytes += len(data)
  564. except StopIteration:
  565. # The entire JSON object has been serialized, write any
  566. # remaining data, finalize the producer and the request, and
  567. # clean-up any references.
  568. self._send_data(buffer)
  569. self._request.unregisterProducer()
  570. self._request.finish()
  571. self.stopProducing()
  572. return
  573. self._send_data(buffer)
  574. def stopProducing(self) -> None:
  575. # Clear a circular reference.
  576. self._request = None
  577. def _encode_json_bytes(json_object: object) -> bytes:
  578. """
  579. Encode an object into JSON. Returns an iterator of bytes.
  580. """
  581. return json_encoder.encode(json_object).encode("utf-8")
  582. def respond_with_json(
  583. request: SynapseRequest,
  584. code: int,
  585. json_object: Any,
  586. send_cors: bool = False,
  587. canonical_json: bool = True,
  588. ) -> Optional[int]:
  589. """Sends encoded JSON in response to the given request.
  590. Args:
  591. request: The http request to respond to.
  592. code: The HTTP response code.
  593. json_object: The object to serialize to JSON.
  594. send_cors: Whether to send Cross-Origin Resource Sharing headers
  595. https://fetch.spec.whatwg.org/#http-cors-protocol
  596. canonical_json: Whether to use the canonicaljson algorithm when encoding
  597. the JSON bytes.
  598. Returns:
  599. twisted.web.server.NOT_DONE_YET if the request is still active.
  600. """
  601. # The response code must always be set, for logging purposes.
  602. request.setResponseCode(code)
  603. # could alternatively use request.notifyFinish() and flip a flag when
  604. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  605. # a waste.
  606. if request._disconnected:
  607. logger.warning(
  608. "Not sending response to request %s, already disconnected.", request
  609. )
  610. return None
  611. if canonical_json:
  612. encoder: Callable[[object], bytes] = encode_canonical_json
  613. else:
  614. encoder = _encode_json_bytes
  615. request.setHeader(b"Content-Type", b"application/json")
  616. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  617. if send_cors:
  618. set_cors_headers(request)
  619. run_in_background(
  620. _async_write_json_to_request_in_thread, request, encoder, json_object
  621. )
  622. return NOT_DONE_YET
  623. def respond_with_json_bytes(
  624. request: Request,
  625. code: int,
  626. json_bytes: bytes,
  627. send_cors: bool = False,
  628. ) -> Optional[int]:
  629. """Sends encoded JSON in response to the given request.
  630. Args:
  631. request: The http request to respond to.
  632. code: The HTTP response code.
  633. json_bytes: The json bytes to use as the response body.
  634. send_cors: Whether to send Cross-Origin Resource Sharing headers
  635. https://fetch.spec.whatwg.org/#http-cors-protocol
  636. Returns:
  637. twisted.web.server.NOT_DONE_YET if the request is still active.
  638. """
  639. # The response code must always be set, for logging purposes.
  640. request.setResponseCode(code)
  641. if request._disconnected:
  642. logger.warning(
  643. "Not sending response to request %s, already disconnected.", request
  644. )
  645. return None
  646. request.setHeader(b"Content-Type", b"application/json")
  647. request.setHeader(b"Content-Length", b"%d" % (len(json_bytes),))
  648. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  649. if send_cors:
  650. set_cors_headers(request)
  651. _write_bytes_to_request(request, json_bytes)
  652. return NOT_DONE_YET
  653. async def _async_write_json_to_request_in_thread(
  654. request: SynapseRequest,
  655. json_encoder: Callable[[Any], bytes],
  656. json_object: Any,
  657. ) -> None:
  658. """Encodes the given JSON object on a thread and then writes it to the
  659. request.
  660. This is done so that encoding large JSON objects doesn't block the reactor
  661. thread.
  662. Note: We don't use JsonEncoder.iterencode here as that falls back to the
  663. Python implementation (rather than the C backend), which is *much* more
  664. expensive.
  665. """
  666. def encode(opentracing_span: "Optional[opentracing.Span]") -> bytes:
  667. # it might take a while for the threadpool to schedule us, so we write
  668. # opentracing logs once we actually get scheduled, so that we can see how
  669. # much that contributed.
  670. if opentracing_span:
  671. opentracing_span.log_kv({"event": "scheduled"})
  672. res = json_encoder(json_object)
  673. if opentracing_span:
  674. opentracing_span.log_kv({"event": "encoded"})
  675. return res
  676. with start_active_span("encode_json_response"):
  677. span = active_span()
  678. json_str = await defer_to_thread(request.reactor, encode, span)
  679. _write_bytes_to_request(request, json_str)
  680. def _write_bytes_to_request(request: Request, bytes_to_write: bytes) -> None:
  681. """Writes the bytes to the request using an appropriate producer.
  682. Note: This should be used instead of `Request.write` to correctly handle
  683. large response bodies.
  684. """
  685. # The problem with dumping all of the response into the `Request` object at
  686. # once (via `Request.write`) is that doing so starts the timeout for the
  687. # next request to be received: so if it takes longer than 60s to stream back
  688. # the response to the client, the client never gets it.
  689. #
  690. # The correct solution is to use a Producer; then the timeout is only
  691. # started once all of the content is sent over the TCP connection.
  692. # To make sure we don't write all of the bytes at once we split it up into
  693. # chunks.
  694. chunk_size = 4096
  695. bytes_generator = chunk_seq(bytes_to_write, chunk_size)
  696. # We use a `_ByteProducer` here rather than `NoRangeStaticProducer` as the
  697. # unit tests can't cope with being given a pull producer.
  698. _ByteProducer(request, bytes_generator)
  699. def set_cors_headers(request: Request) -> None:
  700. """Set the CORS headers so that javascript running in a web browsers can
  701. use this API
  702. Args:
  703. request: The http request to add CORS to.
  704. """
  705. request.setHeader(b"Access-Control-Allow-Origin", b"*")
  706. request.setHeader(
  707. b"Access-Control-Allow-Methods", b"GET, HEAD, POST, PUT, DELETE, OPTIONS"
  708. )
  709. request.setHeader(
  710. b"Access-Control-Allow-Headers",
  711. b"X-Requested-With, Content-Type, Authorization, Date",
  712. )
  713. def set_corp_headers(request: Request) -> None:
  714. """Set the CORP headers so that javascript running in a web browsers can
  715. embed the resource returned from this request when their client requires
  716. the `Cross-Origin-Embedder-Policy: require-corp` header.
  717. Args:
  718. request: The http request to add the CORP header to.
  719. """
  720. request.setHeader(b"Cross-Origin-Resource-Policy", b"cross-origin")
  721. def respond_with_html(request: Request, code: int, html: str) -> None:
  722. """
  723. Wraps `respond_with_html_bytes` by first encoding HTML from a str to UTF-8 bytes.
  724. """
  725. respond_with_html_bytes(request, code, html.encode("utf-8"))
  726. def respond_with_html_bytes(request: Request, code: int, html_bytes: bytes) -> None:
  727. """
  728. Sends HTML (encoded as UTF-8 bytes) as the response to the given request.
  729. Note that this adds clickjacking protection headers and finishes the request.
  730. Args:
  731. request: The http request to respond to.
  732. code: The HTTP response code.
  733. html_bytes: The HTML bytes to use as the response body.
  734. """
  735. # The response code must always be set, for logging purposes.
  736. request.setResponseCode(code)
  737. # could alternatively use request.notifyFinish() and flip a flag when
  738. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  739. # a waste.
  740. if request._disconnected:
  741. logger.warning(
  742. "Not sending response to request %s, already disconnected.", request
  743. )
  744. return None
  745. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  746. request.setHeader(b"Content-Length", b"%d" % (len(html_bytes),))
  747. # Ensure this content cannot be embedded.
  748. set_clickjacking_protection_headers(request)
  749. request.write(html_bytes)
  750. finish_request(request)
  751. def set_clickjacking_protection_headers(request: Request) -> None:
  752. """
  753. Set headers to guard against clickjacking of embedded content.
  754. This sets the X-Frame-Options and Content-Security-Policy headers which instructs
  755. browsers to not allow the HTML of the response to be embedded onto another
  756. page.
  757. Args:
  758. request: The http request to add the headers to.
  759. """
  760. request.setHeader(b"X-Frame-Options", b"DENY")
  761. request.setHeader(b"Content-Security-Policy", b"frame-ancestors 'none';")
  762. def respond_with_redirect(request: Request, url: bytes) -> None:
  763. """Write a 302 response to the request, if it is still alive."""
  764. logger.debug("Redirect to %s", url.decode("utf-8"))
  765. request.redirect(url)
  766. finish_request(request)
  767. def finish_request(request: Request) -> None:
  768. """Finish writing the response to the request.
  769. Twisted throws a RuntimeException if the connection closed before the
  770. response was written but doesn't provide a convenient or reliable way to
  771. determine if the connection was closed. So we catch and log the RuntimeException
  772. You might think that ``request.notifyFinish`` could be used to tell if the
  773. request was finished. However the deferred it returns won't fire if the
  774. connection was already closed, meaning we'd have to have called the method
  775. right at the start of the request. By the time we want to write the response
  776. it will already be too late.
  777. """
  778. try:
  779. request.finish()
  780. except RuntimeError as e:
  781. logger.info("Connection disconnected before response was written: %r", e)