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.
 
 
 
 
 
 

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