server.py 14 KB

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