server.py 19 KB

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