server.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import collections
  17. import html
  18. import logging
  19. import types
  20. import urllib
  21. from http import HTTPStatus
  22. from io import BytesIO
  23. from typing import Awaitable, Callable, TypeVar, Union
  24. import jinja2
  25. from canonicaljson import encode_canonical_json, encode_pretty_printed_json, json
  26. from twisted.internet import defer
  27. from twisted.python import failure
  28. from twisted.web import resource
  29. from twisted.web.server import NOT_DONE_YET, Request
  30. from twisted.web.static import NoRangeStaticProducer
  31. from twisted.web.util import redirectTo
  32. import synapse.events
  33. import synapse.metrics
  34. from synapse.api.errors import (
  35. CodeMessageException,
  36. Codes,
  37. RedirectException,
  38. SynapseError,
  39. UnrecognizedRequestError,
  40. )
  41. from synapse.http.site import SynapseRequest
  42. from synapse.logging.context import preserve_fn
  43. from synapse.logging.opentracing import trace_servlet
  44. from synapse.util.caches import intern_dict
  45. logger = logging.getLogger(__name__)
  46. HTML_ERROR_TEMPLATE = """<!DOCTYPE html>
  47. <html lang=en>
  48. <head>
  49. <meta charset="utf-8">
  50. <title>Error {code}</title>
  51. </head>
  52. <body>
  53. <p>{msg}</p>
  54. </body>
  55. </html>
  56. """
  57. def wrap_json_request_handler(h):
  58. """Wraps a request handler method with exception handling.
  59. Also does the wrapping with request.processing as per wrap_async_request_handler.
  60. The handler method must have a signature of "handle_foo(self, request)",
  61. where "request" must be a SynapseRequest.
  62. The handler must return a deferred or a coroutine. If the deferred succeeds
  63. we assume that a response has been sent. If the deferred fails with a SynapseError we use
  64. it to send a JSON response with the appropriate HTTP reponse code. If the
  65. deferred fails with any other type of error we send a 500 reponse.
  66. """
  67. async def wrapped_request_handler(self, request):
  68. try:
  69. await h(self, request)
  70. except SynapseError as e:
  71. code = e.code
  72. logger.info("%s SynapseError: %s - %s", request, code, e.msg)
  73. # Only respond with an error response if we haven't already started
  74. # writing, otherwise lets just kill the connection
  75. if request.startedWriting:
  76. if request.transport:
  77. try:
  78. request.transport.abortConnection()
  79. except Exception:
  80. # abortConnection throws if the connection is already closed
  81. pass
  82. else:
  83. respond_with_json(
  84. request,
  85. code,
  86. e.error_dict(),
  87. send_cors=True,
  88. pretty_print=_request_user_agent_is_curl(request),
  89. )
  90. except Exception:
  91. # failure.Failure() fishes the original Failure out
  92. # of our stack, and thus gives us a sensible stack
  93. # trace.
  94. f = failure.Failure()
  95. logger.error(
  96. "Failed handle request via %r: %r",
  97. request.request_metrics.name,
  98. request,
  99. exc_info=(f.type, f.value, f.getTracebackObject()),
  100. )
  101. # Only respond with an error response if we haven't already started
  102. # writing, otherwise lets just kill the connection
  103. if request.startedWriting:
  104. if request.transport:
  105. try:
  106. request.transport.abortConnection()
  107. except Exception:
  108. # abortConnection throws if the connection is already closed
  109. pass
  110. else:
  111. respond_with_json(
  112. request,
  113. 500,
  114. {"error": "Internal server error", "errcode": Codes.UNKNOWN},
  115. send_cors=True,
  116. pretty_print=_request_user_agent_is_curl(request),
  117. )
  118. return wrap_async_request_handler(wrapped_request_handler)
  119. TV = TypeVar("TV")
  120. def wrap_html_request_handler(
  121. h: Callable[[TV, SynapseRequest], Awaitable]
  122. ) -> Callable[[TV, SynapseRequest], Awaitable[None]]:
  123. """Wraps a request handler method with exception handling.
  124. Also does the wrapping with request.processing as per wrap_async_request_handler.
  125. The handler method must have a signature of "handle_foo(self, request)",
  126. where "request" must be a SynapseRequest.
  127. """
  128. async def wrapped_request_handler(self, request):
  129. try:
  130. await h(self, request)
  131. except Exception:
  132. f = failure.Failure()
  133. return_html_error(f, request, HTML_ERROR_TEMPLATE)
  134. return wrap_async_request_handler(wrapped_request_handler)
  135. def return_html_error(
  136. f: failure.Failure, request: Request, error_template: Union[str, jinja2.Template],
  137. ) -> None:
  138. """Sends an HTML error page corresponding to the given failure.
  139. Handles RedirectException and other CodeMessageExceptions (such as SynapseError)
  140. Args:
  141. f: the error to report
  142. request: the failing request
  143. error_template: the HTML template. Can be either a string (with `{code}`,
  144. `{msg}` placeholders), or a jinja2 template
  145. """
  146. if f.check(CodeMessageException):
  147. cme = f.value
  148. code = cme.code
  149. msg = cme.msg
  150. if isinstance(cme, RedirectException):
  151. logger.info("%s redirect to %s", request, cme.location)
  152. request.setHeader(b"location", cme.location)
  153. request.cookies.extend(cme.cookies)
  154. elif isinstance(cme, SynapseError):
  155. logger.info("%s SynapseError: %s - %s", request, code, msg)
  156. else:
  157. logger.error(
  158. "Failed handle request %r",
  159. request,
  160. exc_info=(f.type, f.value, f.getTracebackObject()),
  161. )
  162. else:
  163. code = HTTPStatus.INTERNAL_SERVER_ERROR
  164. msg = "Internal server error"
  165. logger.error(
  166. "Failed handle request %r",
  167. request,
  168. exc_info=(f.type, f.value, f.getTracebackObject()),
  169. )
  170. if isinstance(error_template, str):
  171. body = error_template.format(code=code, msg=html.escape(msg))
  172. else:
  173. body = error_template.render(code=code, msg=msg)
  174. body_bytes = body.encode("utf-8")
  175. request.setResponseCode(code)
  176. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  177. request.setHeader(b"Content-Length", b"%i" % (len(body_bytes),))
  178. request.write(body_bytes)
  179. finish_request(request)
  180. def wrap_async_request_handler(h):
  181. """Wraps an async request handler so that it calls request.processing.
  182. This helps ensure that work done by the request handler after the request is completed
  183. is correctly recorded against the request metrics/logs.
  184. The handler method must have a signature of "handle_foo(self, request)",
  185. where "request" must be a SynapseRequest.
  186. The handler may return a deferred, in which case the completion of the request isn't
  187. logged until the deferred completes.
  188. """
  189. async def wrapped_async_request_handler(self, request):
  190. with request.processing():
  191. await h(self, request)
  192. # we need to preserve_fn here, because the synchronous render method won't yield for
  193. # us (obviously)
  194. return preserve_fn(wrapped_async_request_handler)
  195. class HttpServer(object):
  196. """ Interface for registering callbacks on a HTTP server
  197. """
  198. def register_paths(self, method, path_patterns, callback):
  199. """ Register a callback that gets fired if we receive a http request
  200. with the given method for a path that matches the given regex.
  201. If the regex contains groups these gets passed to the calback via
  202. an unpacked tuple.
  203. Args:
  204. method (str): The method to listen to.
  205. path_patterns (list<SRE_Pattern>): The regex used to match requests.
  206. callback (function): The function to fire if we receive a matched
  207. request. The first argument will be the request object and
  208. subsequent arguments will be any matched groups from the regex.
  209. This should return a tuple of (code, response).
  210. """
  211. pass
  212. class JsonResource(HttpServer, resource.Resource):
  213. """ This implements the HttpServer interface and provides JSON support for
  214. Resources.
  215. Register callbacks via register_paths()
  216. Callbacks can return a tuple of status code and a dict in which case the
  217. the dict will automatically be sent to the client as a JSON object.
  218. The JsonResource is primarily intended for returning JSON, but callbacks
  219. may send something other than JSON, they may do so by using the methods
  220. on the request object and instead returning None.
  221. """
  222. isLeaf = True
  223. _PathEntry = collections.namedtuple(
  224. "_PathEntry", ["pattern", "callback", "servlet_classname"]
  225. )
  226. def __init__(self, hs, canonical_json=True):
  227. resource.Resource.__init__(self)
  228. self.canonical_json = canonical_json
  229. self.clock = hs.get_clock()
  230. self.path_regexs = {}
  231. self.hs = hs
  232. def register_paths(
  233. self, method, path_patterns, callback, servlet_classname, trace=True
  234. ):
  235. """
  236. Registers a request handler against a regular expression. Later request URLs are
  237. checked against these regular expressions in order to identify an appropriate
  238. handler for that request.
  239. Args:
  240. method (str): GET, POST etc
  241. path_patterns (Iterable[str]): A list of regular expressions to which
  242. the request URLs are compared.
  243. callback (function): The handler for the request. Usually a Servlet
  244. servlet_classname (str): The name of the handler to be used in prometheus
  245. and opentracing logs.
  246. trace (bool): Whether we should start a span to trace the servlet.
  247. """
  248. method = method.encode("utf-8") # method is bytes on py3
  249. if trace:
  250. # We don't extract the context from the servlet because we can't
  251. # trust the sender
  252. callback = trace_servlet(servlet_classname)(callback)
  253. for path_pattern in path_patterns:
  254. logger.debug("Registering for %s %s", method, path_pattern.pattern)
  255. self.path_regexs.setdefault(method, []).append(
  256. self._PathEntry(path_pattern, callback, servlet_classname)
  257. )
  258. def render(self, request):
  259. """ This gets called by twisted every time someone sends us a request.
  260. """
  261. defer.ensureDeferred(self._async_render(request))
  262. return NOT_DONE_YET
  263. @wrap_json_request_handler
  264. async def _async_render(self, request):
  265. """ This gets called from render() every time someone sends us a request.
  266. This checks if anyone has registered a callback for that method and
  267. path.
  268. """
  269. callback, servlet_classname, group_dict = self._get_handler_for_request(request)
  270. # Make sure we have a name for this handler in prometheus.
  271. request.request_metrics.name = servlet_classname
  272. # Now trigger the callback. If it returns a response, we send it
  273. # here. If it throws an exception, that is handled by the wrapper
  274. # installed by @request_handler.
  275. kwargs = intern_dict(
  276. {
  277. name: urllib.parse.unquote(value) if value else value
  278. for name, value in group_dict.items()
  279. }
  280. )
  281. callback_return = callback(request, **kwargs)
  282. # Is it synchronous? We'll allow this for now.
  283. if isinstance(callback_return, (defer.Deferred, types.CoroutineType)):
  284. callback_return = await callback_return
  285. if callback_return is not None:
  286. code, response = callback_return
  287. self._send_response(request, code, response)
  288. def _get_handler_for_request(self, request):
  289. """Finds a callback method to handle the given request
  290. Args:
  291. request (twisted.web.http.Request):
  292. Returns:
  293. Tuple[Callable, str, dict[unicode, unicode]]: callback method, the
  294. label to use for that method in prometheus metrics, and the
  295. dict mapping keys to path components as specified in the
  296. handler's path match regexp.
  297. The callback will normally be a method registered via
  298. register_paths, so will return (possibly via Deferred) either
  299. None, or a tuple of (http code, response body).
  300. """
  301. request_path = request.path.decode("ascii")
  302. # Loop through all the registered callbacks to check if the method
  303. # and path regex match
  304. for path_entry in self.path_regexs.get(request.method, []):
  305. m = path_entry.pattern.match(request_path)
  306. if m:
  307. # We found a match!
  308. return path_entry.callback, path_entry.servlet_classname, m.groupdict()
  309. # Huh. No one wanted to handle that? Fiiiiiine. Send 400.
  310. return _unrecognised_request_handler, "unrecognised_request_handler", {}
  311. def _send_response(
  312. self, request, code, response_json_object, response_code_message=None
  313. ):
  314. # TODO: Only enable CORS for the requests that need it.
  315. respond_with_json(
  316. request,
  317. code,
  318. response_json_object,
  319. send_cors=True,
  320. response_code_message=response_code_message,
  321. pretty_print=_request_user_agent_is_curl(request),
  322. canonical_json=self.canonical_json,
  323. )
  324. class DirectServeResource(resource.Resource):
  325. def render(self, request):
  326. """
  327. Render the request, using an asynchronous render handler if it exists.
  328. """
  329. async_render_callback_name = "_async_render_" + request.method.decode("ascii")
  330. # Try and get the async renderer
  331. callback = getattr(self, async_render_callback_name, None)
  332. # No async renderer for this request method.
  333. if not callback:
  334. return super().render(request)
  335. resp = trace_servlet(self.__class__.__name__)(callback)(request)
  336. # If it's a coroutine, turn it into a Deferred
  337. if isinstance(resp, types.CoroutineType):
  338. defer.ensureDeferred(resp)
  339. return NOT_DONE_YET
  340. def _options_handler(request):
  341. """Request handler for OPTIONS requests
  342. This is a request handler suitable for return from
  343. _get_handler_for_request. It returns a 200 and an empty body.
  344. Args:
  345. request (twisted.web.http.Request):
  346. Returns:
  347. Tuple[int, dict]: http code, response body.
  348. """
  349. return 200, {}
  350. def _unrecognised_request_handler(request):
  351. """Request handler for unrecognised requests
  352. This is a request handler suitable for return from
  353. _get_handler_for_request. It actually just raises an
  354. UnrecognizedRequestError.
  355. Args:
  356. request (twisted.web.http.Request):
  357. """
  358. raise UnrecognizedRequestError()
  359. class RootRedirect(resource.Resource):
  360. """Redirects the root '/' path to another path."""
  361. def __init__(self, path):
  362. resource.Resource.__init__(self)
  363. self.url = path
  364. def render_GET(self, request):
  365. return redirectTo(self.url.encode("ascii"), request)
  366. def getChild(self, name, request):
  367. if len(name) == 0:
  368. return self # select ourselves as the child to render
  369. return resource.Resource.getChild(self, name, request)
  370. class OptionsResource(resource.Resource):
  371. """Responds to OPTION requests for itself and all children."""
  372. def render_OPTIONS(self, request):
  373. code, response_json_object = _options_handler(request)
  374. return respond_with_json(
  375. request, code, response_json_object, send_cors=True, canonical_json=False,
  376. )
  377. def getChildWithDefault(self, path, request):
  378. if request.method == b"OPTIONS":
  379. return self # select ourselves as the child to render
  380. return resource.Resource.getChildWithDefault(self, path, request)
  381. class RootOptionsRedirectResource(OptionsResource, RootRedirect):
  382. pass
  383. def respond_with_json(
  384. request,
  385. code,
  386. json_object,
  387. send_cors=False,
  388. response_code_message=None,
  389. pretty_print=False,
  390. canonical_json=True,
  391. ):
  392. # could alternatively use request.notifyFinish() and flip a flag when
  393. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  394. # a waste.
  395. if request._disconnected:
  396. logger.warning(
  397. "Not sending response to request %s, already disconnected.", request
  398. )
  399. return
  400. if pretty_print:
  401. json_bytes = encode_pretty_printed_json(json_object) + b"\n"
  402. else:
  403. if canonical_json or synapse.events.USE_FROZEN_DICTS:
  404. # canonicaljson already encodes to bytes
  405. json_bytes = encode_canonical_json(json_object)
  406. else:
  407. json_bytes = json.dumps(json_object).encode("utf-8")
  408. return respond_with_json_bytes(
  409. request,
  410. code,
  411. json_bytes,
  412. send_cors=send_cors,
  413. response_code_message=response_code_message,
  414. )
  415. def respond_with_json_bytes(
  416. request, code, json_bytes, send_cors=False, response_code_message=None
  417. ):
  418. """Sends encoded JSON in response to the given request.
  419. Args:
  420. request (twisted.web.http.Request): The http request to respond to.
  421. code (int): The HTTP response code.
  422. json_bytes (bytes): The json bytes to use as the response body.
  423. send_cors (bool): Whether to send Cross-Origin Resource Sharing headers
  424. http://www.w3.org/TR/cors/
  425. Returns:
  426. twisted.web.server.NOT_DONE_YET"""
  427. request.setResponseCode(code, message=response_code_message)
  428. request.setHeader(b"Content-Type", b"application/json")
  429. request.setHeader(b"Content-Length", b"%d" % (len(json_bytes),))
  430. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  431. if send_cors:
  432. set_cors_headers(request)
  433. # todo: we can almost certainly avoid this copy and encode the json straight into
  434. # the bytesIO, but it would involve faffing around with string->bytes wrappers.
  435. bytes_io = BytesIO(json_bytes)
  436. producer = NoRangeStaticProducer(request, bytes_io)
  437. producer.start()
  438. return NOT_DONE_YET
  439. def set_cors_headers(request):
  440. """Set the CORs headers so that javascript running in a web browsers can
  441. use this API
  442. Args:
  443. request (twisted.web.http.Request): The http request to add CORs to.
  444. """
  445. request.setHeader(b"Access-Control-Allow-Origin", b"*")
  446. request.setHeader(
  447. b"Access-Control-Allow-Methods", b"GET, POST, PUT, DELETE, OPTIONS"
  448. )
  449. request.setHeader(
  450. b"Access-Control-Allow-Headers",
  451. b"Origin, X-Requested-With, Content-Type, Accept, Authorization",
  452. )
  453. def finish_request(request):
  454. """ Finish writing the response to the request.
  455. Twisted throws a RuntimeException if the connection closed before the
  456. response was written but doesn't provide a convenient or reliable way to
  457. determine if the connection was closed. So we catch and log the RuntimeException
  458. You might think that ``request.notifyFinish`` could be used to tell if the
  459. request was finished. However the deferred it returns won't fire if the
  460. connection was already closed, meaning we'd have to have called the method
  461. right at the start of the request. By the time we want to write the response
  462. it will already be too late.
  463. """
  464. try:
  465. request.finish()
  466. except RuntimeError as e:
  467. logger.info("Connection disconnected before response was written: %r", e)
  468. def _request_user_agent_is_curl(request):
  469. user_agents = request.requestHeaders.getRawHeaders(b"User-Agent", default=[])
  470. for user_agent in user_agents:
  471. if b"curl" in user_agent:
  472. return True
  473. return False