server.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. from six.moves import http_client
  18. from synapse.api.errors import (
  19. cs_exception, SynapseError, CodeMessageException, UnrecognizedRequestError, Codes
  20. )
  21. from synapse.http.request_metrics import (
  22. requests_counter,
  23. )
  24. from synapse.util.logcontext import LoggingContext, PreserveLoggingContext
  25. from synapse.util.caches import intern_dict
  26. from synapse.util.metrics import Measure
  27. import synapse.metrics
  28. import synapse.events
  29. from canonicaljson import (
  30. encode_canonical_json, encode_pretty_printed_json
  31. )
  32. from twisted.internet import defer
  33. from twisted.python import failure
  34. from twisted.web import server, resource
  35. from twisted.web.server import NOT_DONE_YET
  36. from twisted.web.util import redirectTo
  37. import collections
  38. import logging
  39. import urllib
  40. import simplejson
  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 adds logging as per wrap_request_handler_with_logging.
  56. The handler method must have a signature of "handle_foo(self, request)",
  57. where "self" must have a "clock" attribute (and "request" must be a
  58. SynapseRequest).
  59. The handler must return a deferred. If the deferred succeeds we assume that
  60. a response has been sent. If the deferred fails with a SynapseError we use
  61. it to send a JSON response with the appropriate HTTP reponse code. If the
  62. deferred fails with any other type of error we send a 500 reponse.
  63. """
  64. @defer.inlineCallbacks
  65. def wrapped_request_handler(self, request):
  66. try:
  67. yield h(self, request)
  68. except CodeMessageException as e:
  69. code = e.code
  70. if isinstance(e, SynapseError):
  71. logger.info(
  72. "%s SynapseError: %s - %s", request, code, e.msg
  73. )
  74. else:
  75. logger.exception(e)
  76. respond_with_json(
  77. request, code, cs_exception(e), send_cors=True,
  78. pretty_print=_request_user_agent_is_curl(request),
  79. )
  80. except Exception:
  81. # failure.Failure() fishes the original Failure out
  82. # of our stack, and thus gives us a sensible stack
  83. # trace.
  84. f = failure.Failure()
  85. logger.error(
  86. "Failed handle request via %r: %r: %s",
  87. h,
  88. request,
  89. f.getTraceback().rstrip(),
  90. )
  91. respond_with_json(
  92. request,
  93. 500,
  94. {
  95. "error": "Internal server error",
  96. "errcode": Codes.UNKNOWN,
  97. },
  98. send_cors=True,
  99. pretty_print=_request_user_agent_is_curl(request),
  100. )
  101. return wrap_request_handler_with_logging(wrapped_request_handler)
  102. def wrap_html_request_handler(h):
  103. """Wraps a request handler method with exception handling.
  104. Also adds logging as per wrap_request_handler_with_logging.
  105. The handler method must have a signature of "handle_foo(self, request)",
  106. where "self" must have a "clock" attribute (and "request" must be a
  107. SynapseRequest).
  108. """
  109. def wrapped_request_handler(self, request):
  110. d = defer.maybeDeferred(h, self, request)
  111. d.addErrback(_return_html_error, request)
  112. return d
  113. return wrap_request_handler_with_logging(wrapped_request_handler)
  114. def _return_html_error(f, request):
  115. """Sends an HTML error page corresponding to the given failure
  116. Args:
  117. f (twisted.python.failure.Failure):
  118. request (twisted.web.iweb.IRequest):
  119. """
  120. if f.check(CodeMessageException):
  121. cme = f.value
  122. code = cme.code
  123. msg = cme.msg
  124. if isinstance(cme, SynapseError):
  125. logger.info(
  126. "%s SynapseError: %s - %s", request, code, msg
  127. )
  128. else:
  129. logger.error(
  130. "Failed handle request %r: %s",
  131. request,
  132. f.getTraceback().rstrip(),
  133. )
  134. else:
  135. code = http_client.INTERNAL_SERVER_ERROR
  136. msg = "Internal server error"
  137. logger.error(
  138. "Failed handle request %r: %s",
  139. request,
  140. f.getTraceback().rstrip(),
  141. )
  142. body = HTML_ERROR_TEMPLATE.format(
  143. code=code, msg=cgi.escape(msg),
  144. ).encode("utf-8")
  145. request.setResponseCode(code)
  146. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  147. request.setHeader(b"Content-Length", b"%i" % (len(body),))
  148. request.write(body)
  149. finish_request(request)
  150. def wrap_request_handler_with_logging(h):
  151. """Wraps a request handler to provide logging and metrics
  152. The handler method must have a signature of "handle_foo(self, request)",
  153. where "self" must have a "clock" attribute (and "request" must be a
  154. SynapseRequest).
  155. As well as calling `request.processing` (which will log the response and
  156. duration for this request), the wrapped request handler will insert the
  157. request id into the logging context.
  158. """
  159. @defer.inlineCallbacks
  160. def wrapped_request_handler(self, request):
  161. """
  162. Args:
  163. self:
  164. request (synapse.http.site.SynapseRequest):
  165. """
  166. request_id = request.get_request_id()
  167. with LoggingContext(request_id) as request_context:
  168. request_context.request = request_id
  169. with Measure(self.clock, "wrapped_request_handler"):
  170. # we start the request metrics timer here with an initial stab
  171. # at the servlet name. For most requests that name will be
  172. # JsonResource (or a subclass), and JsonResource._async_render
  173. # will update it once it picks a servlet.
  174. servlet_name = self.__class__.__name__
  175. with request.processing(servlet_name):
  176. with PreserveLoggingContext(request_context):
  177. d = defer.maybeDeferred(h, self, request)
  178. # record the arrival of the request *after*
  179. # dispatching to the handler, so that the handler
  180. # can update the servlet name in the request
  181. # metrics
  182. requests_counter.labels(request.method,
  183. request.request_metrics.name).inc()
  184. yield d
  185. return wrapped_request_handler
  186. class HttpServer(object):
  187. """ Interface for registering callbacks on a HTTP server
  188. """
  189. def register_paths(self, method, path_patterns, callback):
  190. """ Register a callback that gets fired if we receive a http request
  191. with the given method for a path that matches the given regex.
  192. If the regex contains groups these gets passed to the calback via
  193. an unpacked tuple.
  194. Args:
  195. method (str): The method to listen to.
  196. path_patterns (list<SRE_Pattern>): The regex used to match requests.
  197. callback (function): The function to fire if we receive a matched
  198. request. The first argument will be the request object and
  199. subsequent arguments will be any matched groups from the regex.
  200. This should return a tuple of (code, response).
  201. """
  202. pass
  203. class JsonResource(HttpServer, resource.Resource):
  204. """ This implements the HttpServer interface and provides JSON support for
  205. Resources.
  206. Register callbacks via register_paths()
  207. Callbacks can return a tuple of status code and a dict in which case the
  208. the dict will automatically be sent to the client as a JSON object.
  209. The JsonResource is primarily intended for returning JSON, but callbacks
  210. may send something other than JSON, they may do so by using the methods
  211. on the request object and instead returning None.
  212. """
  213. isLeaf = True
  214. _PathEntry = collections.namedtuple("_PathEntry", ["pattern", "callback"])
  215. def __init__(self, hs, canonical_json=True):
  216. resource.Resource.__init__(self)
  217. self.canonical_json = canonical_json
  218. self.clock = hs.get_clock()
  219. self.path_regexs = {}
  220. self.hs = hs
  221. def register_paths(self, method, path_patterns, callback):
  222. for path_pattern in path_patterns:
  223. logger.debug("Registering for %s %s", method, path_pattern.pattern)
  224. self.path_regexs.setdefault(method, []).append(
  225. self._PathEntry(path_pattern, callback)
  226. )
  227. def render(self, request):
  228. """ This gets called by twisted every time someone sends us a request.
  229. """
  230. self._async_render(request)
  231. return server.NOT_DONE_YET
  232. @wrap_json_request_handler
  233. @defer.inlineCallbacks
  234. def _async_render(self, request):
  235. """ This gets called from render() every time someone sends us a request.
  236. This checks if anyone has registered a callback for that method and
  237. path.
  238. """
  239. callback, group_dict = self._get_handler_for_request(request)
  240. servlet_instance = getattr(callback, "__self__", None)
  241. if servlet_instance is not None:
  242. servlet_classname = servlet_instance.__class__.__name__
  243. else:
  244. servlet_classname = "%r" % callback
  245. request.request_metrics.name = servlet_classname
  246. # Now trigger the callback. If it returns a response, we send it
  247. # here. If it throws an exception, that is handled by the wrapper
  248. # installed by @request_handler.
  249. kwargs = intern_dict({
  250. name: urllib.unquote(value).decode("UTF-8") if value else value
  251. for name, value in group_dict.items()
  252. })
  253. callback_return = yield callback(request, **kwargs)
  254. if callback_return is not None:
  255. code, response = callback_return
  256. self._send_response(request, code, response)
  257. def _get_handler_for_request(self, request):
  258. """Finds a callback method to handle the given request
  259. Args:
  260. request (twisted.web.http.Request):
  261. Returns:
  262. Tuple[Callable, dict[str, str]]: callback method, and the dict
  263. mapping keys to path components as specified in the handler's
  264. path match regexp.
  265. The callback will normally be a method registered via
  266. register_paths, so will return (possibly via Deferred) either
  267. None, or a tuple of (http code, response body).
  268. """
  269. if request.method == b"OPTIONS":
  270. return _options_handler, {}
  271. # Loop through all the registered callbacks to check if the method
  272. # and path regex match
  273. for path_entry in self.path_regexs.get(request.method, []):
  274. m = path_entry.pattern.match(request.path)
  275. if m:
  276. # We found a match!
  277. return path_entry.callback, m.groupdict()
  278. # Huh. No one wanted to handle that? Fiiiiiine. Send 400.
  279. return _unrecognised_request_handler, {}
  280. def _send_response(self, request, code, response_json_object,
  281. response_code_message=None):
  282. # TODO: Only enable CORS for the requests that need it.
  283. respond_with_json(
  284. request, code, response_json_object,
  285. send_cors=True,
  286. response_code_message=response_code_message,
  287. pretty_print=_request_user_agent_is_curl(request),
  288. canonical_json=self.canonical_json,
  289. )
  290. def _options_handler(request):
  291. """Request handler for OPTIONS requests
  292. This is a request handler suitable for return from
  293. _get_handler_for_request. It returns a 200 and an empty body.
  294. Args:
  295. request (twisted.web.http.Request):
  296. Returns:
  297. Tuple[int, dict]: http code, response body.
  298. """
  299. return 200, {}
  300. def _unrecognised_request_handler(request):
  301. """Request handler for unrecognised requests
  302. This is a request handler suitable for return from
  303. _get_handler_for_request. It actually just raises an
  304. UnrecognizedRequestError.
  305. Args:
  306. request (twisted.web.http.Request):
  307. """
  308. raise UnrecognizedRequestError()
  309. class RootRedirect(resource.Resource):
  310. """Redirects the root '/' path to another path."""
  311. def __init__(self, path):
  312. resource.Resource.__init__(self)
  313. self.url = path
  314. def render_GET(self, request):
  315. return redirectTo(self.url, request)
  316. def getChild(self, name, request):
  317. if len(name) == 0:
  318. return self # select ourselves as the child to render
  319. return resource.Resource.getChild(self, name, request)
  320. def respond_with_json(request, code, json_object, send_cors=False,
  321. response_code_message=None, pretty_print=False,
  322. canonical_json=True):
  323. # could alternatively use request.notifyFinish() and flip a flag when
  324. # the Deferred fires, but since the flag is RIGHT THERE it seems like
  325. # a waste.
  326. if request._disconnected:
  327. logger.warn(
  328. "Not sending response to request %s, already disconnected.",
  329. request)
  330. return
  331. if pretty_print:
  332. json_bytes = encode_pretty_printed_json(json_object) + "\n"
  333. else:
  334. if canonical_json or synapse.events.USE_FROZEN_DICTS:
  335. json_bytes = encode_canonical_json(json_object)
  336. else:
  337. json_bytes = simplejson.dumps(json_object)
  338. return respond_with_json_bytes(
  339. request, code, json_bytes,
  340. send_cors=send_cors,
  341. response_code_message=response_code_message,
  342. )
  343. def respond_with_json_bytes(request, code, json_bytes, send_cors=False,
  344. response_code_message=None):
  345. """Sends encoded JSON in response to the given request.
  346. Args:
  347. request (twisted.web.http.Request): The http request to respond to.
  348. code (int): The HTTP response code.
  349. json_bytes (bytes): The json bytes to use as the response body.
  350. send_cors (bool): Whether to send Cross-Origin Resource Sharing headers
  351. http://www.w3.org/TR/cors/
  352. Returns:
  353. twisted.web.server.NOT_DONE_YET"""
  354. request.setResponseCode(code, message=response_code_message)
  355. request.setHeader(b"Content-Type", b"application/json")
  356. request.setHeader(b"Content-Length", b"%d" % (len(json_bytes),))
  357. request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate")
  358. if send_cors:
  359. set_cors_headers(request)
  360. request.write(json_bytes)
  361. finish_request(request)
  362. return NOT_DONE_YET
  363. def set_cors_headers(request):
  364. """Set the CORs headers so that javascript running in a web browsers can
  365. use this API
  366. Args:
  367. request (twisted.web.http.Request): The http request to add CORs to.
  368. """
  369. request.setHeader("Access-Control-Allow-Origin", "*")
  370. request.setHeader(
  371. "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"
  372. )
  373. request.setHeader(
  374. "Access-Control-Allow-Headers",
  375. "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  376. )
  377. def finish_request(request):
  378. """ Finish writing the response to the request.
  379. Twisted throws a RuntimeException if the connection closed before the
  380. response was written but doesn't provide a convenient or reliable way to
  381. determine if the connection was closed. So we catch and log the RuntimeException
  382. You might think that ``request.notifyFinish`` could be used to tell if the
  383. request was finished. However the deferred it returns won't fire if the
  384. connection was already closed, meaning we'd have to have called the method
  385. right at the start of the request. By the time we want to write the response
  386. it will already be too late.
  387. """
  388. try:
  389. request.finish()
  390. except RuntimeError as e:
  391. logger.info("Connection disconnected before response was written: %r", e)
  392. def _request_user_agent_is_curl(request):
  393. user_agents = request.requestHeaders.getRawHeaders(
  394. b"User-Agent", default=[]
  395. )
  396. for user_agent in user_agents:
  397. if b"curl" in user_agent:
  398. return True
  399. return False