federation_client.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import copy
  16. import itertools
  17. import logging
  18. import random
  19. from twisted.internet import defer
  20. from synapse.api.constants import Membership
  21. from synapse.api.errors import (
  22. CodeMessageException, HttpResponseException, SynapseError, FederationDeniedError
  23. )
  24. from synapse.events import builder
  25. from synapse.federation.federation_base import (
  26. FederationBase,
  27. event_from_pdu_json,
  28. )
  29. import synapse.metrics
  30. from synapse.util import logcontext, unwrapFirstError
  31. from synapse.util.caches.expiringcache import ExpiringCache
  32. from synapse.util.logcontext import make_deferred_yieldable, run_in_background
  33. from synapse.util.logutils import log_function
  34. from synapse.util.retryutils import NotRetryingDestination
  35. logger = logging.getLogger(__name__)
  36. # synapse.federation.federation_client is a silly name
  37. metrics = synapse.metrics.get_metrics_for("synapse.federation.client")
  38. sent_queries_counter = metrics.register_counter("sent_queries", labels=["type"])
  39. PDU_RETRY_TIME_MS = 1 * 60 * 1000
  40. class FederationClient(FederationBase):
  41. def __init__(self, hs):
  42. super(FederationClient, self).__init__(hs)
  43. self.pdu_destination_tried = {}
  44. self._clock.looping_call(
  45. self._clear_tried_cache, 60 * 1000,
  46. )
  47. self.state = hs.get_state_handler()
  48. self.transport_layer = hs.get_federation_transport_client()
  49. def _clear_tried_cache(self):
  50. """Clear pdu_destination_tried cache"""
  51. now = self._clock.time_msec()
  52. old_dict = self.pdu_destination_tried
  53. self.pdu_destination_tried = {}
  54. for event_id, destination_dict in old_dict.items():
  55. destination_dict = {
  56. dest: time
  57. for dest, time in destination_dict.items()
  58. if time + PDU_RETRY_TIME_MS > now
  59. }
  60. if destination_dict:
  61. self.pdu_destination_tried[event_id] = destination_dict
  62. def start_get_pdu_cache(self):
  63. self._get_pdu_cache = ExpiringCache(
  64. cache_name="get_pdu_cache",
  65. clock=self._clock,
  66. max_len=1000,
  67. expiry_ms=120 * 1000,
  68. reset_expiry_on_get=False,
  69. )
  70. self._get_pdu_cache.start()
  71. @log_function
  72. def make_query(self, destination, query_type, args,
  73. retry_on_dns_fail=False, ignore_backoff=False):
  74. """Sends a federation Query to a remote homeserver of the given type
  75. and arguments.
  76. Args:
  77. destination (str): Domain name of the remote homeserver
  78. query_type (str): Category of the query type; should match the
  79. handler name used in register_query_handler().
  80. args (dict): Mapping of strings to strings containing the details
  81. of the query request.
  82. ignore_backoff (bool): true to ignore the historical backoff data
  83. and try the request anyway.
  84. Returns:
  85. a Deferred which will eventually yield a JSON object from the
  86. response
  87. """
  88. sent_queries_counter.inc(query_type)
  89. return self.transport_layer.make_query(
  90. destination, query_type, args, retry_on_dns_fail=retry_on_dns_fail,
  91. ignore_backoff=ignore_backoff,
  92. )
  93. @log_function
  94. def query_client_keys(self, destination, content, timeout):
  95. """Query device keys for a device hosted on a remote server.
  96. Args:
  97. destination (str): Domain name of the remote homeserver
  98. content (dict): The query content.
  99. Returns:
  100. a Deferred which will eventually yield a JSON object from the
  101. response
  102. """
  103. sent_queries_counter.inc("client_device_keys")
  104. return self.transport_layer.query_client_keys(
  105. destination, content, timeout
  106. )
  107. @log_function
  108. def query_user_devices(self, destination, user_id, timeout=30000):
  109. """Query the device keys for a list of user ids hosted on a remote
  110. server.
  111. """
  112. sent_queries_counter.inc("user_devices")
  113. return self.transport_layer.query_user_devices(
  114. destination, user_id, timeout
  115. )
  116. @log_function
  117. def claim_client_keys(self, destination, content, timeout):
  118. """Claims one-time keys for a device hosted on a remote server.
  119. Args:
  120. destination (str): Domain name of the remote homeserver
  121. content (dict): The query content.
  122. Returns:
  123. a Deferred which will eventually yield a JSON object from the
  124. response
  125. """
  126. sent_queries_counter.inc("client_one_time_keys")
  127. return self.transport_layer.claim_client_keys(
  128. destination, content, timeout
  129. )
  130. @defer.inlineCallbacks
  131. @log_function
  132. def backfill(self, dest, context, limit, extremities):
  133. """Requests some more historic PDUs for the given context from the
  134. given destination server.
  135. Args:
  136. dest (str): The remote home server to ask.
  137. context (str): The context to backfill.
  138. limit (int): The maximum number of PDUs to return.
  139. extremities (list): List of PDU id and origins of the first pdus
  140. we have seen from the context
  141. Returns:
  142. Deferred: Results in the received PDUs.
  143. """
  144. logger.debug("backfill extrem=%s", extremities)
  145. # If there are no extremeties then we've (probably) reached the start.
  146. if not extremities:
  147. return
  148. transaction_data = yield self.transport_layer.backfill(
  149. dest, context, extremities, limit)
  150. logger.debug("backfill transaction_data=%s", repr(transaction_data))
  151. pdus = [
  152. event_from_pdu_json(p, outlier=False)
  153. for p in transaction_data["pdus"]
  154. ]
  155. # FIXME: We should handle signature failures more gracefully.
  156. pdus[:] = yield logcontext.make_deferred_yieldable(defer.gatherResults(
  157. self._check_sigs_and_hashes(pdus),
  158. consumeErrors=True,
  159. ).addErrback(unwrapFirstError))
  160. defer.returnValue(pdus)
  161. @defer.inlineCallbacks
  162. @log_function
  163. def get_pdu(self, destinations, event_id, outlier=False, timeout=None):
  164. """Requests the PDU with given origin and ID from the remote home
  165. servers.
  166. Will attempt to get the PDU from each destination in the list until
  167. one succeeds.
  168. This will persist the PDU locally upon receipt.
  169. Args:
  170. destinations (list): Which home servers to query
  171. event_id (str): event to fetch
  172. outlier (bool): Indicates whether the PDU is an `outlier`, i.e. if
  173. it's from an arbitary point in the context as opposed to part
  174. of the current block of PDUs. Defaults to `False`
  175. timeout (int): How long to try (in ms) each destination for before
  176. moving to the next destination. None indicates no timeout.
  177. Returns:
  178. Deferred: Results in the requested PDU.
  179. """
  180. # TODO: Rate limit the number of times we try and get the same event.
  181. if self._get_pdu_cache:
  182. ev = self._get_pdu_cache.get(event_id)
  183. if ev:
  184. defer.returnValue(ev)
  185. pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {})
  186. signed_pdu = None
  187. for destination in destinations:
  188. now = self._clock.time_msec()
  189. last_attempt = pdu_attempts.get(destination, 0)
  190. if last_attempt + PDU_RETRY_TIME_MS > now:
  191. continue
  192. try:
  193. transaction_data = yield self.transport_layer.get_event(
  194. destination, event_id, timeout=timeout,
  195. )
  196. logger.debug("transaction_data %r", transaction_data)
  197. pdu_list = [
  198. event_from_pdu_json(p, outlier=outlier)
  199. for p in transaction_data["pdus"]
  200. ]
  201. if pdu_list and pdu_list[0]:
  202. pdu = pdu_list[0]
  203. # Check signatures are correct.
  204. signed_pdu = yield self._check_sigs_and_hash(pdu)
  205. break
  206. pdu_attempts[destination] = now
  207. except SynapseError as e:
  208. logger.info(
  209. "Failed to get PDU %s from %s because %s",
  210. event_id, destination, e,
  211. )
  212. except NotRetryingDestination as e:
  213. logger.info(e.message)
  214. continue
  215. except FederationDeniedError as e:
  216. logger.info(e.message)
  217. continue
  218. except Exception as e:
  219. pdu_attempts[destination] = now
  220. logger.info(
  221. "Failed to get PDU %s from %s because %s",
  222. event_id, destination, e,
  223. )
  224. continue
  225. if self._get_pdu_cache is not None and signed_pdu:
  226. self._get_pdu_cache[event_id] = signed_pdu
  227. defer.returnValue(signed_pdu)
  228. @defer.inlineCallbacks
  229. @log_function
  230. def get_state_for_room(self, destination, room_id, event_id):
  231. """Requests all of the `current` state PDUs for a given room from
  232. a remote home server.
  233. Args:
  234. destination (str): The remote homeserver to query for the state.
  235. room_id (str): The id of the room we're interested in.
  236. event_id (str): The id of the event we want the state at.
  237. Returns:
  238. Deferred: Results in a list of PDUs.
  239. """
  240. try:
  241. # First we try and ask for just the IDs, as thats far quicker if
  242. # we have most of the state and auth_chain already.
  243. # However, this may 404 if the other side has an old synapse.
  244. result = yield self.transport_layer.get_room_state_ids(
  245. destination, room_id, event_id=event_id,
  246. )
  247. state_event_ids = result["pdu_ids"]
  248. auth_event_ids = result.get("auth_chain_ids", [])
  249. fetched_events, failed_to_fetch = yield self.get_events(
  250. [destination], room_id, set(state_event_ids + auth_event_ids)
  251. )
  252. if failed_to_fetch:
  253. logger.warn("Failed to get %r", failed_to_fetch)
  254. event_map = {
  255. ev.event_id: ev for ev in fetched_events
  256. }
  257. pdus = [event_map[e_id] for e_id in state_event_ids if e_id in event_map]
  258. auth_chain = [
  259. event_map[e_id] for e_id in auth_event_ids if e_id in event_map
  260. ]
  261. auth_chain.sort(key=lambda e: e.depth)
  262. defer.returnValue((pdus, auth_chain))
  263. except HttpResponseException as e:
  264. if e.code == 400 or e.code == 404:
  265. logger.info("Failed to use get_room_state_ids API, falling back")
  266. else:
  267. raise e
  268. result = yield self.transport_layer.get_room_state(
  269. destination, room_id, event_id=event_id,
  270. )
  271. pdus = [
  272. event_from_pdu_json(p, outlier=True) for p in result["pdus"]
  273. ]
  274. auth_chain = [
  275. event_from_pdu_json(p, outlier=True)
  276. for p in result.get("auth_chain", [])
  277. ]
  278. seen_events = yield self.store.get_events([
  279. ev.event_id for ev in itertools.chain(pdus, auth_chain)
  280. ])
  281. signed_pdus = yield self._check_sigs_and_hash_and_fetch(
  282. destination,
  283. [p for p in pdus if p.event_id not in seen_events],
  284. outlier=True
  285. )
  286. signed_pdus.extend(
  287. seen_events[p.event_id] for p in pdus if p.event_id in seen_events
  288. )
  289. signed_auth = yield self._check_sigs_and_hash_and_fetch(
  290. destination,
  291. [p for p in auth_chain if p.event_id not in seen_events],
  292. outlier=True
  293. )
  294. signed_auth.extend(
  295. seen_events[p.event_id] for p in auth_chain if p.event_id in seen_events
  296. )
  297. signed_auth.sort(key=lambda e: e.depth)
  298. defer.returnValue((signed_pdus, signed_auth))
  299. @defer.inlineCallbacks
  300. def get_events(self, destinations, room_id, event_ids, return_local=True):
  301. """Fetch events from some remote destinations, checking if we already
  302. have them.
  303. Args:
  304. destinations (list)
  305. room_id (str)
  306. event_ids (list)
  307. return_local (bool): Whether to include events we already have in
  308. the DB in the returned list of events
  309. Returns:
  310. Deferred: A deferred resolving to a 2-tuple where the first is a list of
  311. events and the second is a list of event ids that we failed to fetch.
  312. """
  313. if return_local:
  314. seen_events = yield self.store.get_events(event_ids, allow_rejected=True)
  315. signed_events = seen_events.values()
  316. else:
  317. seen_events = yield self.store.have_seen_events(event_ids)
  318. signed_events = []
  319. failed_to_fetch = set()
  320. missing_events = set(event_ids)
  321. for k in seen_events:
  322. missing_events.discard(k)
  323. if not missing_events:
  324. defer.returnValue((signed_events, failed_to_fetch))
  325. def random_server_list():
  326. srvs = list(destinations)
  327. random.shuffle(srvs)
  328. return srvs
  329. batch_size = 20
  330. missing_events = list(missing_events)
  331. for i in xrange(0, len(missing_events), batch_size):
  332. batch = set(missing_events[i:i + batch_size])
  333. deferreds = [
  334. run_in_background(
  335. self.get_pdu,
  336. destinations=random_server_list(),
  337. event_id=e_id,
  338. )
  339. for e_id in batch
  340. ]
  341. res = yield make_deferred_yieldable(
  342. defer.DeferredList(deferreds, consumeErrors=True)
  343. )
  344. for success, result in res:
  345. if success and result:
  346. signed_events.append(result)
  347. batch.discard(result.event_id)
  348. # We removed all events we successfully fetched from `batch`
  349. failed_to_fetch.update(batch)
  350. defer.returnValue((signed_events, failed_to_fetch))
  351. @defer.inlineCallbacks
  352. @log_function
  353. def get_event_auth(self, destination, room_id, event_id):
  354. res = yield self.transport_layer.get_event_auth(
  355. destination, room_id, event_id,
  356. )
  357. auth_chain = [
  358. event_from_pdu_json(p, outlier=True)
  359. for p in res["auth_chain"]
  360. ]
  361. signed_auth = yield self._check_sigs_and_hash_and_fetch(
  362. destination, auth_chain, outlier=True
  363. )
  364. signed_auth.sort(key=lambda e: e.depth)
  365. defer.returnValue(signed_auth)
  366. @defer.inlineCallbacks
  367. def make_membership_event(self, destinations, room_id, user_id, membership,
  368. content={},):
  369. """
  370. Creates an m.room.member event, with context, without participating in the room.
  371. Does so by asking one of the already participating servers to create an
  372. event with proper context.
  373. Note that this does not append any events to any graphs.
  374. Args:
  375. destinations (str): Candidate homeservers which are probably
  376. participating in the room.
  377. room_id (str): The room in which the event will happen.
  378. user_id (str): The user whose membership is being evented.
  379. membership (str): The "membership" property of the event. Must be
  380. one of "join" or "leave".
  381. content (object): Any additional data to put into the content field
  382. of the event.
  383. Return:
  384. Deferred: resolves to a tuple of (origin (str), event (object))
  385. where origin is the remote homeserver which generated the event.
  386. Fails with a ``CodeMessageException`` if the chosen remote server
  387. returns a 300/400 code.
  388. Fails with a ``RuntimeError`` if no servers were reachable.
  389. """
  390. valid_memberships = {Membership.JOIN, Membership.LEAVE}
  391. if membership not in valid_memberships:
  392. raise RuntimeError(
  393. "make_membership_event called with membership='%s', must be one of %s" %
  394. (membership, ",".join(valid_memberships))
  395. )
  396. for destination in destinations:
  397. if destination == self.server_name:
  398. continue
  399. try:
  400. ret = yield self.transport_layer.make_membership_event(
  401. destination, room_id, user_id, membership
  402. )
  403. pdu_dict = ret["event"]
  404. logger.debug("Got response to make_%s: %s", membership, pdu_dict)
  405. pdu_dict["content"].update(content)
  406. # The protoevent received over the JSON wire may not have all
  407. # the required fields. Lets just gloss over that because
  408. # there's some we never care about
  409. if "prev_state" not in pdu_dict:
  410. pdu_dict["prev_state"] = []
  411. ev = builder.EventBuilder(pdu_dict)
  412. defer.returnValue(
  413. (destination, ev)
  414. )
  415. break
  416. except CodeMessageException as e:
  417. if not 500 <= e.code < 600:
  418. raise
  419. else:
  420. logger.warn(
  421. "Failed to make_%s via %s: %s",
  422. membership, destination, e.message
  423. )
  424. except Exception as e:
  425. logger.warn(
  426. "Failed to make_%s via %s: %s",
  427. membership, destination, e.message
  428. )
  429. raise RuntimeError("Failed to send to any server.")
  430. @defer.inlineCallbacks
  431. def send_join(self, destinations, pdu):
  432. """Sends a join event to one of a list of homeservers.
  433. Doing so will cause the remote server to add the event to the graph,
  434. and send the event out to the rest of the federation.
  435. Args:
  436. destinations (str): Candidate homeservers which are probably
  437. participating in the room.
  438. pdu (BaseEvent): event to be sent
  439. Return:
  440. Deferred: resolves to a dict with members ``origin`` (a string
  441. giving the serer the event was sent to, ``state`` (?) and
  442. ``auth_chain``.
  443. Fails with a ``CodeMessageException`` if the chosen remote server
  444. returns a 300/400 code.
  445. Fails with a ``RuntimeError`` if no servers were reachable.
  446. """
  447. for destination in destinations:
  448. if destination == self.server_name:
  449. continue
  450. try:
  451. time_now = self._clock.time_msec()
  452. _, content = yield self.transport_layer.send_join(
  453. destination=destination,
  454. room_id=pdu.room_id,
  455. event_id=pdu.event_id,
  456. content=pdu.get_pdu_json(time_now),
  457. )
  458. logger.debug("Got content: %s", content)
  459. state = [
  460. event_from_pdu_json(p, outlier=True)
  461. for p in content.get("state", [])
  462. ]
  463. auth_chain = [
  464. event_from_pdu_json(p, outlier=True)
  465. for p in content.get("auth_chain", [])
  466. ]
  467. pdus = {
  468. p.event_id: p
  469. for p in itertools.chain(state, auth_chain)
  470. }
  471. valid_pdus = yield self._check_sigs_and_hash_and_fetch(
  472. destination, pdus.values(),
  473. outlier=True,
  474. )
  475. valid_pdus_map = {
  476. p.event_id: p
  477. for p in valid_pdus
  478. }
  479. # NB: We *need* to copy to ensure that we don't have multiple
  480. # references being passed on, as that causes... issues.
  481. signed_state = [
  482. copy.copy(valid_pdus_map[p.event_id])
  483. for p in state
  484. if p.event_id in valid_pdus_map
  485. ]
  486. signed_auth = [
  487. valid_pdus_map[p.event_id]
  488. for p in auth_chain
  489. if p.event_id in valid_pdus_map
  490. ]
  491. # NB: We *need* to copy to ensure that we don't have multiple
  492. # references being passed on, as that causes... issues.
  493. for s in signed_state:
  494. s.internal_metadata = copy.deepcopy(s.internal_metadata)
  495. auth_chain.sort(key=lambda e: e.depth)
  496. defer.returnValue({
  497. "state": signed_state,
  498. "auth_chain": signed_auth,
  499. "origin": destination,
  500. })
  501. except CodeMessageException as e:
  502. if not 500 <= e.code < 600:
  503. raise
  504. else:
  505. logger.exception(
  506. "Failed to send_join via %s: %s",
  507. destination, e.message
  508. )
  509. except Exception as e:
  510. logger.exception(
  511. "Failed to send_join via %s: %s",
  512. destination, e.message
  513. )
  514. raise RuntimeError("Failed to send to any server.")
  515. @defer.inlineCallbacks
  516. def send_invite(self, destination, room_id, event_id, pdu):
  517. time_now = self._clock.time_msec()
  518. code, content = yield self.transport_layer.send_invite(
  519. destination=destination,
  520. room_id=room_id,
  521. event_id=event_id,
  522. content=pdu.get_pdu_json(time_now),
  523. )
  524. pdu_dict = content["event"]
  525. logger.debug("Got response to send_invite: %s", pdu_dict)
  526. pdu = event_from_pdu_json(pdu_dict)
  527. # Check signatures are correct.
  528. pdu = yield self._check_sigs_and_hash(pdu)
  529. # FIXME: We should handle signature failures more gracefully.
  530. defer.returnValue(pdu)
  531. @defer.inlineCallbacks
  532. def send_leave(self, destinations, pdu):
  533. """Sends a leave event to one of a list of homeservers.
  534. Doing so will cause the remote server to add the event to the graph,
  535. and send the event out to the rest of the federation.
  536. This is mostly useful to reject received invites.
  537. Args:
  538. destinations (str): Candidate homeservers which are probably
  539. participating in the room.
  540. pdu (BaseEvent): event to be sent
  541. Return:
  542. Deferred: resolves to None.
  543. Fails with a ``CodeMessageException`` if the chosen remote server
  544. returns a non-200 code.
  545. Fails with a ``RuntimeError`` if no servers were reachable.
  546. """
  547. for destination in destinations:
  548. if destination == self.server_name:
  549. continue
  550. try:
  551. time_now = self._clock.time_msec()
  552. _, content = yield self.transport_layer.send_leave(
  553. destination=destination,
  554. room_id=pdu.room_id,
  555. event_id=pdu.event_id,
  556. content=pdu.get_pdu_json(time_now),
  557. )
  558. logger.debug("Got content: %s", content)
  559. defer.returnValue(None)
  560. except CodeMessageException:
  561. raise
  562. except Exception as e:
  563. logger.exception(
  564. "Failed to send_leave via %s: %s",
  565. destination, e.message
  566. )
  567. raise RuntimeError("Failed to send to any server.")
  568. def get_public_rooms(self, destination, limit=None, since_token=None,
  569. search_filter=None, include_all_networks=False,
  570. third_party_instance_id=None):
  571. if destination == self.server_name:
  572. return
  573. return self.transport_layer.get_public_rooms(
  574. destination, limit, since_token, search_filter,
  575. include_all_networks=include_all_networks,
  576. third_party_instance_id=third_party_instance_id,
  577. )
  578. @defer.inlineCallbacks
  579. def query_auth(self, destination, room_id, event_id, local_auth):
  580. """
  581. Params:
  582. destination (str)
  583. event_it (str)
  584. local_auth (list)
  585. """
  586. time_now = self._clock.time_msec()
  587. send_content = {
  588. "auth_chain": [e.get_pdu_json(time_now) for e in local_auth],
  589. }
  590. code, content = yield self.transport_layer.send_query_auth(
  591. destination=destination,
  592. room_id=room_id,
  593. event_id=event_id,
  594. content=send_content,
  595. )
  596. auth_chain = [
  597. event_from_pdu_json(e)
  598. for e in content["auth_chain"]
  599. ]
  600. signed_auth = yield self._check_sigs_and_hash_and_fetch(
  601. destination, auth_chain, outlier=True
  602. )
  603. signed_auth.sort(key=lambda e: e.depth)
  604. ret = {
  605. "auth_chain": signed_auth,
  606. "rejects": content.get("rejects", []),
  607. "missing": content.get("missing", []),
  608. }
  609. defer.returnValue(ret)
  610. @defer.inlineCallbacks
  611. def get_missing_events(self, destination, room_id, earliest_events_ids,
  612. latest_events, limit, min_depth, timeout):
  613. """Tries to fetch events we are missing. This is called when we receive
  614. an event without having received all of its ancestors.
  615. Args:
  616. destination (str)
  617. room_id (str)
  618. earliest_events_ids (list): List of event ids. Effectively the
  619. events we expected to receive, but haven't. `get_missing_events`
  620. should only return events that didn't happen before these.
  621. latest_events (list): List of events we have received that we don't
  622. have all previous events for.
  623. limit (int): Maximum number of events to return.
  624. min_depth (int): Minimum depth of events tor return.
  625. timeout (int): Max time to wait in ms
  626. """
  627. try:
  628. content = yield self.transport_layer.get_missing_events(
  629. destination=destination,
  630. room_id=room_id,
  631. earliest_events=earliest_events_ids,
  632. latest_events=[e.event_id for e in latest_events],
  633. limit=limit,
  634. min_depth=min_depth,
  635. timeout=timeout,
  636. )
  637. events = [
  638. event_from_pdu_json(e)
  639. for e in content.get("events", [])
  640. ]
  641. signed_events = yield self._check_sigs_and_hash_and_fetch(
  642. destination, events, outlier=False
  643. )
  644. except HttpResponseException as e:
  645. if not e.code == 400:
  646. raise
  647. # We are probably hitting an old server that doesn't support
  648. # get_missing_events
  649. signed_events = []
  650. defer.returnValue(signed_events)
  651. @defer.inlineCallbacks
  652. def forward_third_party_invite(self, destinations, room_id, event_dict):
  653. for destination in destinations:
  654. if destination == self.server_name:
  655. continue
  656. try:
  657. yield self.transport_layer.exchange_third_party_invite(
  658. destination=destination,
  659. room_id=room_id,
  660. event_dict=event_dict,
  661. )
  662. defer.returnValue(None)
  663. except CodeMessageException:
  664. raise
  665. except Exception as e:
  666. logger.exception(
  667. "Failed to send_third_party_invite via %s: %s",
  668. destination, e.message
  669. )
  670. raise RuntimeError("Failed to send to any server.")