server.py 13 KB

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