server.py 16 KB

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