federation_client.py 28 KB

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