server.py 30 KB

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