server.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import json
  2. import logging
  3. from io import BytesIO
  4. from six import text_type
  5. import attr
  6. from zope.interface import implementer
  7. from twisted.internet import address, threads, udp
  8. from twisted.internet._resolver import SimpleResolverComplexifier
  9. from twisted.internet.defer import Deferred, fail, succeed
  10. from twisted.internet.error import DNSLookupError
  11. from twisted.internet.interfaces import IReactorPluggableNameResolver, IResolverSimple
  12. from twisted.python.failure import Failure
  13. from twisted.test.proto_helpers import MemoryReactorClock
  14. from twisted.web.http import unquote
  15. from twisted.web.http_headers import Headers
  16. from synapse.http.site import SynapseRequest
  17. from synapse.util import Clock
  18. from tests.utils import setup_test_homeserver as _sth
  19. logger = logging.getLogger(__name__)
  20. class TimedOutException(Exception):
  21. """
  22. A web query timed out.
  23. """
  24. @attr.s
  25. class FakeChannel(object):
  26. """
  27. A fake Twisted Web Channel (the part that interfaces with the
  28. wire).
  29. """
  30. _reactor = attr.ib()
  31. result = attr.ib(default=attr.Factory(dict))
  32. _producer = None
  33. @property
  34. def json_body(self):
  35. if not self.result:
  36. raise Exception("No result yet.")
  37. return json.loads(self.result["body"].decode("utf8"))
  38. @property
  39. def code(self):
  40. if not self.result:
  41. raise Exception("No result yet.")
  42. return int(self.result["code"])
  43. @property
  44. def headers(self):
  45. if not self.result:
  46. raise Exception("No result yet.")
  47. h = Headers()
  48. for i in self.result["headers"]:
  49. h.addRawHeader(*i)
  50. return h
  51. def writeHeaders(self, version, code, reason, headers):
  52. self.result["version"] = version
  53. self.result["code"] = code
  54. self.result["reason"] = reason
  55. self.result["headers"] = headers
  56. def write(self, content):
  57. assert isinstance(content, bytes), "Should be bytes! " + repr(content)
  58. if "body" not in self.result:
  59. self.result["body"] = b""
  60. self.result["body"] += content
  61. def registerProducer(self, producer, streaming):
  62. self._producer = producer
  63. self.producerStreaming = streaming
  64. def _produce():
  65. if self._producer:
  66. self._producer.resumeProducing()
  67. self._reactor.callLater(0.1, _produce)
  68. if not streaming:
  69. self._reactor.callLater(0.0, _produce)
  70. def unregisterProducer(self):
  71. if self._producer is None:
  72. return
  73. self._producer = None
  74. def requestDone(self, _self):
  75. self.result["done"] = True
  76. def getPeer(self):
  77. # We give an address so that getClientIP returns a non null entry,
  78. # causing us to record the MAU
  79. return address.IPv4Address("TCP", "127.0.0.1", 3423)
  80. def getHost(self):
  81. return None
  82. @property
  83. def transport(self):
  84. return self
  85. class FakeSite:
  86. """
  87. A fake Twisted Web Site, with mocks of the extra things that
  88. Synapse adds.
  89. """
  90. server_version_string = b"1"
  91. site_tag = "test"
  92. access_logger = logging.getLogger("synapse.access.http.fake")
  93. def make_request(
  94. reactor,
  95. method,
  96. path,
  97. content=b"",
  98. access_token=None,
  99. request=SynapseRequest,
  100. shorthand=True,
  101. federation_auth_origin=None,
  102. ):
  103. """
  104. Make a web request using the given method and path, feed it the
  105. content, and return the Request and the Channel underneath.
  106. Args:
  107. method (bytes/unicode): The HTTP request method ("verb").
  108. path (bytes/unicode): The HTTP path, suitably URL encoded (e.g.
  109. escaped UTF-8 & spaces and such).
  110. content (bytes or dict): The body of the request. JSON-encoded, if
  111. a dict.
  112. shorthand: Whether to try and be helpful and prefix the given URL
  113. with the usual REST API path, if it doesn't contain it.
  114. federation_auth_origin (bytes|None): if set to not-None, we will add a fake
  115. Authorization header pretenting to be the given server name.
  116. Returns:
  117. Tuple[synapse.http.site.SynapseRequest, channel]
  118. """
  119. if not isinstance(method, bytes):
  120. method = method.encode("ascii")
  121. if not isinstance(path, bytes):
  122. path = path.encode("ascii")
  123. # Decorate it to be the full path, if we're using shorthand
  124. if shorthand and not path.startswith(b"/_matrix"):
  125. path = b"/_matrix/client/r0/" + path
  126. path = path.replace(b"//", b"/")
  127. if not path.startswith(b"/"):
  128. path = b"/" + path
  129. if isinstance(content, text_type):
  130. content = content.encode("utf8")
  131. site = FakeSite()
  132. channel = FakeChannel(reactor)
  133. req = request(site, channel)
  134. req.process = lambda: b""
  135. req.content = BytesIO(content)
  136. req.postpath = list(map(unquote, path[1:].split(b"/")))
  137. if access_token:
  138. req.requestHeaders.addRawHeader(
  139. b"Authorization", b"Bearer " + access_token.encode("ascii")
  140. )
  141. if federation_auth_origin is not None:
  142. req.requestHeaders.addRawHeader(
  143. b"Authorization",
  144. b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,),
  145. )
  146. if content:
  147. req.requestHeaders.addRawHeader(b"Content-Type", b"application/json")
  148. req.requestReceived(method, path, b"1.1")
  149. return req, channel
  150. def wait_until_result(clock, request, timeout=100):
  151. """
  152. Wait until the request is finished.
  153. """
  154. clock.run()
  155. x = 0
  156. while not request.finished:
  157. # If there's a producer, tell it to resume producing so we get content
  158. if request._channel._producer:
  159. request._channel._producer.resumeProducing()
  160. x += 1
  161. if x > timeout:
  162. raise TimedOutException("Timed out waiting for request to finish.")
  163. clock.advance(0.1)
  164. def render(request, resource, clock):
  165. request.render(resource)
  166. wait_until_result(clock, request)
  167. @implementer(IReactorPluggableNameResolver)
  168. class ThreadedMemoryReactorClock(MemoryReactorClock):
  169. """
  170. A MemoryReactorClock that supports callFromThread.
  171. """
  172. def __init__(self):
  173. self.threadpool = ThreadPool(self)
  174. self._udp = []
  175. lookups = self.lookups = {}
  176. @implementer(IResolverSimple)
  177. class FakeResolver(object):
  178. def getHostByName(self, name, timeout=None):
  179. if name not in lookups:
  180. return fail(DNSLookupError("OH NO: unknown %s" % (name,)))
  181. return succeed(lookups[name])
  182. self.nameResolver = SimpleResolverComplexifier(FakeResolver())
  183. super(ThreadedMemoryReactorClock, self).__init__()
  184. def listenUDP(self, port, protocol, interface="", maxPacketSize=8196):
  185. p = udp.Port(port, protocol, interface, maxPacketSize, self)
  186. p.startListening()
  187. self._udp.append(p)
  188. return p
  189. def callFromThread(self, callback, *args, **kwargs):
  190. """
  191. Make the callback fire in the next reactor iteration.
  192. """
  193. d = Deferred()
  194. d.addCallback(lambda x: callback(*args, **kwargs))
  195. self.callLater(0, d.callback, True)
  196. return d
  197. def getThreadPool(self):
  198. return self.threadpool
  199. class ThreadPool:
  200. """
  201. Threadless thread pool.
  202. """
  203. def __init__(self, reactor):
  204. self._reactor = reactor
  205. def start(self):
  206. pass
  207. def stop(self):
  208. pass
  209. def callInThreadWithCallback(self, onResult, function, *args, **kwargs):
  210. def _(res):
  211. if isinstance(res, Failure):
  212. onResult(False, res)
  213. else:
  214. onResult(True, res)
  215. d = Deferred()
  216. d.addCallback(lambda x: function(*args, **kwargs))
  217. d.addBoth(_)
  218. self._reactor.callLater(0, d.callback, True)
  219. return d
  220. def setup_test_homeserver(cleanup_func, *args, **kwargs):
  221. """
  222. Set up a synchronous test server, driven by the reactor used by
  223. the homeserver.
  224. """
  225. d = _sth(cleanup_func, *args, **kwargs).result
  226. if isinstance(d, Failure):
  227. d.raiseException()
  228. # Make the thread pool synchronous.
  229. clock = d.get_clock()
  230. pool = d.get_db_pool()
  231. def runWithConnection(func, *args, **kwargs):
  232. return threads.deferToThreadPool(
  233. pool._reactor,
  234. pool.threadpool,
  235. pool._runWithConnection,
  236. func,
  237. *args,
  238. **kwargs
  239. )
  240. def runInteraction(interaction, *args, **kwargs):
  241. return threads.deferToThreadPool(
  242. pool._reactor,
  243. pool.threadpool,
  244. pool._runInteraction,
  245. interaction,
  246. *args,
  247. **kwargs
  248. )
  249. if pool:
  250. pool.runWithConnection = runWithConnection
  251. pool.runInteraction = runInteraction
  252. pool.threadpool = ThreadPool(clock._reactor)
  253. pool.running = True
  254. return d
  255. def get_clock():
  256. clock = ThreadedMemoryReactorClock()
  257. hs_clock = Clock(clock)
  258. return (clock, hs_clock)
  259. @attr.s(cmp=False)
  260. class FakeTransport(object):
  261. """
  262. A twisted.internet.interfaces.ITransport implementation which sends all its data
  263. straight into an IProtocol object: it exists to connect two IProtocols together.
  264. To use it, instantiate it with the receiving IProtocol, and then pass it to the
  265. sending IProtocol's makeConnection method:
  266. server = HTTPChannel()
  267. client.makeConnection(FakeTransport(server, self.reactor))
  268. If you want bidirectional communication, you'll need two instances.
  269. """
  270. other = attr.ib()
  271. """The Protocol object which will receive any data written to this transport.
  272. :type: twisted.internet.interfaces.IProtocol
  273. """
  274. _reactor = attr.ib()
  275. """Test reactor
  276. :type: twisted.internet.interfaces.IReactorTime
  277. """
  278. _protocol = attr.ib(default=None)
  279. """The Protocol which is producing data for this transport. Optional, but if set
  280. will get called back for connectionLost() notifications etc.
  281. """
  282. disconnecting = False
  283. disconnected = False
  284. buffer = attr.ib(default=b"")
  285. producer = attr.ib(default=None)
  286. autoflush = attr.ib(default=True)
  287. def getPeer(self):
  288. return None
  289. def getHost(self):
  290. return None
  291. def loseConnection(self, reason=None):
  292. if not self.disconnecting:
  293. logger.info("FakeTransport: loseConnection(%s)", reason)
  294. self.disconnecting = True
  295. if self._protocol:
  296. self._protocol.connectionLost(reason)
  297. self.disconnected = True
  298. def abortConnection(self):
  299. logger.info("FakeTransport: abortConnection()")
  300. self.loseConnection()
  301. def pauseProducing(self):
  302. if not self.producer:
  303. return
  304. self.producer.pauseProducing()
  305. def resumeProducing(self):
  306. if not self.producer:
  307. return
  308. self.producer.resumeProducing()
  309. def unregisterProducer(self):
  310. if not self.producer:
  311. return
  312. self.producer = None
  313. def registerProducer(self, producer, streaming):
  314. self.producer = producer
  315. self.producerStreaming = streaming
  316. def _produce():
  317. d = self.producer.resumeProducing()
  318. d.addCallback(lambda x: self._reactor.callLater(0.1, _produce))
  319. if not streaming:
  320. self._reactor.callLater(0.0, _produce)
  321. def write(self, byt):
  322. self.buffer = self.buffer + byt
  323. # always actually do the write asynchronously. Some protocols (notably the
  324. # TLSMemoryBIOProtocol) get very confused if a read comes back while they are
  325. # still doing a write. Doing a callLater here breaks the cycle.
  326. if self.autoflush:
  327. self._reactor.callLater(0.0, self.flush)
  328. def writeSequence(self, seq):
  329. for x in seq:
  330. self.write(x)
  331. def flush(self, maxbytes=None):
  332. if not self.buffer:
  333. # nothing to do. Don't write empty buffers: it upsets the
  334. # TLSMemoryBIOProtocol
  335. return
  336. if self.disconnected:
  337. return
  338. if getattr(self.other, "transport") is None:
  339. # the other has no transport yet; reschedule
  340. if self.autoflush:
  341. self._reactor.callLater(0.0, self.flush)
  342. return
  343. if maxbytes is not None:
  344. to_write = self.buffer[:maxbytes]
  345. else:
  346. to_write = self.buffer
  347. logger.info("%s->%s: %s", self._protocol, self.other, to_write)
  348. try:
  349. self.other.dataReceived(to_write)
  350. except Exception as e:
  351. logger.warning("Exception writing to protocol: %s", e)
  352. return
  353. self.buffer = self.buffer[len(to_write) :]
  354. if self.buffer and self.autoflush:
  355. self._reactor.callLater(0.0, self.flush)