federation_client.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. from typing import Dict, Iterable
  19. from prometheus_client import Counter
  20. from twisted.internet import defer
  21. from synapse.api.constants import EventTypes, Membership
  22. from synapse.api.errors import (
  23. CodeMessageException,
  24. Codes,
  25. FederationDeniedError,
  26. HttpResponseException,
  27. SynapseError,
  28. UnsupportedRoomVersionError,
  29. )
  30. from synapse.api.room_versions import (
  31. KNOWN_ROOM_VERSIONS,
  32. EventFormatVersions,
  33. RoomVersions,
  34. )
  35. from synapse.events import builder, room_version_to_event_format
  36. from synapse.federation.federation_base import FederationBase, event_from_pdu_json
  37. from synapse.logging.context import make_deferred_yieldable
  38. from synapse.logging.utils import log_function
  39. from synapse.util import unwrapFirstError
  40. from synapse.util.caches.expiringcache import ExpiringCache
  41. from synapse.util.retryutils import NotRetryingDestination
  42. logger = logging.getLogger(__name__)
  43. sent_queries_counter = Counter("synapse_federation_client_sent_queries", "", ["type"])
  44. PDU_RETRY_TIME_MS = 1 * 60 * 1000
  45. class InvalidResponseError(RuntimeError):
  46. """Helper for _try_destination_list: indicates that the server returned a response
  47. we couldn't parse
  48. """
  49. pass
  50. class FederationClient(FederationBase):
  51. def __init__(self, hs):
  52. super(FederationClient, self).__init__(hs)
  53. self.pdu_destination_tried = {}
  54. self._clock.looping_call(self._clear_tried_cache, 60 * 1000)
  55. self.state = hs.get_state_handler()
  56. self.transport_layer = hs.get_federation_transport_client()
  57. self.hostname = hs.hostname
  58. self.signing_key = hs.config.signing_key[0]
  59. self._get_pdu_cache = ExpiringCache(
  60. cache_name="get_pdu_cache",
  61. clock=self._clock,
  62. max_len=1000,
  63. expiry_ms=120 * 1000,
  64. reset_expiry_on_get=False,
  65. )
  66. def _clear_tried_cache(self):
  67. """Clear pdu_destination_tried cache"""
  68. now = self._clock.time_msec()
  69. old_dict = self.pdu_destination_tried
  70. self.pdu_destination_tried = {}
  71. for event_id, destination_dict in old_dict.items():
  72. destination_dict = {
  73. dest: time
  74. for dest, time in destination_dict.items()
  75. if time + PDU_RETRY_TIME_MS > now
  76. }
  77. if destination_dict:
  78. self.pdu_destination_tried[event_id] = destination_dict
  79. @log_function
  80. def make_query(
  81. self,
  82. destination,
  83. query_type,
  84. args,
  85. retry_on_dns_fail=False,
  86. ignore_backoff=False,
  87. ):
  88. """Sends a federation Query to a remote homeserver of the given type
  89. and arguments.
  90. Args:
  91. destination (str): Domain name of the remote homeserver
  92. query_type (str): Category of the query type; should match the
  93. handler name used in register_query_handler().
  94. args (dict): Mapping of strings to strings containing the details
  95. of the query request.
  96. ignore_backoff (bool): true to ignore the historical backoff data
  97. and try the request anyway.
  98. Returns:
  99. a Deferred which will eventually yield a JSON object from the
  100. response
  101. """
  102. sent_queries_counter.labels(query_type).inc()
  103. return self.transport_layer.make_query(
  104. destination,
  105. query_type,
  106. args,
  107. retry_on_dns_fail=retry_on_dns_fail,
  108. ignore_backoff=ignore_backoff,
  109. )
  110. @log_function
  111. def query_client_keys(self, destination, content, timeout):
  112. """Query device keys for a device hosted on a remote server.
  113. Args:
  114. destination (str): Domain name of the remote homeserver
  115. content (dict): The query content.
  116. Returns:
  117. a Deferred which will eventually yield a JSON object from the
  118. response
  119. """
  120. sent_queries_counter.labels("client_device_keys").inc()
  121. return self.transport_layer.query_client_keys(destination, content, timeout)
  122. @log_function
  123. def query_user_devices(self, destination, user_id, timeout=30000):
  124. """Query the device keys for a list of user ids hosted on a remote
  125. server.
  126. """
  127. sent_queries_counter.labels("user_devices").inc()
  128. return self.transport_layer.query_user_devices(destination, user_id, timeout)
  129. @log_function
  130. def claim_client_keys(self, destination, content, timeout):
  131. """Claims one-time keys for a device hosted on a remote server.
  132. Args:
  133. destination (str): Domain name of the remote homeserver
  134. content (dict): The query content.
  135. Returns:
  136. a Deferred which will eventually yield a JSON object from the
  137. response
  138. """
  139. sent_queries_counter.labels("client_one_time_keys").inc()
  140. return self.transport_layer.claim_client_keys(destination, content, timeout)
  141. @defer.inlineCallbacks
  142. @log_function
  143. def backfill(self, dest, room_id, limit, extremities):
  144. """Requests some more historic PDUs for the given context from the
  145. given destination server.
  146. Args:
  147. dest (str): The remote homeserver to ask.
  148. room_id (str): The room_id to backfill.
  149. limit (int): The maximum number of PDUs to return.
  150. extremities (list): List of PDU id and origins of the first pdus
  151. we have seen from the context
  152. Returns:
  153. Deferred: Results in the received PDUs.
  154. """
  155. logger.debug("backfill extrem=%s", extremities)
  156. # If there are no extremeties then we've (probably) reached the start.
  157. if not extremities:
  158. return
  159. transaction_data = yield self.transport_layer.backfill(
  160. dest, room_id, extremities, limit
  161. )
  162. logger.debug("backfill transaction_data=%r", transaction_data)
  163. room_version = yield self.store.get_room_version_id(room_id)
  164. format_ver = room_version_to_event_format(room_version)
  165. pdus = [
  166. event_from_pdu_json(p, format_ver, outlier=False)
  167. for p in transaction_data["pdus"]
  168. ]
  169. # FIXME: We should handle signature failures more gracefully.
  170. pdus[:] = yield make_deferred_yieldable(
  171. defer.gatherResults(
  172. self._check_sigs_and_hashes(room_version, pdus), consumeErrors=True
  173. ).addErrback(unwrapFirstError)
  174. )
  175. return pdus
  176. @defer.inlineCallbacks
  177. @log_function
  178. def get_pdu(
  179. self, destinations, event_id, room_version, outlier=False, timeout=None
  180. ):
  181. """Requests the PDU with given origin and ID from the remote home
  182. servers.
  183. Will attempt to get the PDU from each destination in the list until
  184. one succeeds.
  185. Args:
  186. destinations (list): Which homeservers to query
  187. event_id (str): event to fetch
  188. room_version (str): version of the room
  189. outlier (bool): Indicates whether the PDU is an `outlier`, i.e. if
  190. it's from an arbitary point in the context as opposed to part
  191. of the current block of PDUs. Defaults to `False`
  192. timeout (int): How long to try (in ms) each destination for before
  193. moving to the next destination. None indicates no timeout.
  194. Returns:
  195. Deferred: Results in the requested PDU, or None if we were unable to find
  196. it.
  197. """
  198. # TODO: Rate limit the number of times we try and get the same event.
  199. ev = self._get_pdu_cache.get(event_id)
  200. if ev:
  201. return ev
  202. pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {})
  203. format_ver = room_version_to_event_format(room_version)
  204. signed_pdu = None
  205. for destination in destinations:
  206. now = self._clock.time_msec()
  207. last_attempt = pdu_attempts.get(destination, 0)
  208. if last_attempt + PDU_RETRY_TIME_MS > now:
  209. continue
  210. try:
  211. transaction_data = yield self.transport_layer.get_event(
  212. destination, event_id, timeout=timeout
  213. )
  214. logger.debug(
  215. "retrieved event id %s from %s: %r",
  216. event_id,
  217. destination,
  218. transaction_data,
  219. )
  220. pdu_list = [
  221. event_from_pdu_json(p, format_ver, outlier=outlier)
  222. for p in transaction_data["pdus"]
  223. ]
  224. if pdu_list and pdu_list[0]:
  225. pdu = pdu_list[0]
  226. # Check signatures are correct.
  227. signed_pdu = yield self._check_sigs_and_hash(room_version, pdu)
  228. break
  229. pdu_attempts[destination] = now
  230. except SynapseError as e:
  231. logger.info(
  232. "Failed to get PDU %s from %s because %s", event_id, destination, e
  233. )
  234. continue
  235. except NotRetryingDestination as e:
  236. logger.info(str(e))
  237. continue
  238. except FederationDeniedError as e:
  239. logger.info(str(e))
  240. continue
  241. except Exception as e:
  242. pdu_attempts[destination] = now
  243. logger.info(
  244. "Failed to get PDU %s from %s because %s", event_id, destination, e
  245. )
  246. continue
  247. if signed_pdu:
  248. self._get_pdu_cache[event_id] = signed_pdu
  249. return signed_pdu
  250. @defer.inlineCallbacks
  251. def get_room_state_ids(self, destination: str, room_id: str, event_id: str):
  252. """Calls the /state_ids endpoint to fetch the state at a particular point
  253. in the room, and the auth events for the given event
  254. Returns:
  255. Tuple[List[str], List[str]]: a tuple of (state event_ids, auth event_ids)
  256. """
  257. result = yield self.transport_layer.get_room_state_ids(
  258. destination, room_id, event_id=event_id
  259. )
  260. state_event_ids = result["pdu_ids"]
  261. auth_event_ids = result.get("auth_chain_ids", [])
  262. if not isinstance(state_event_ids, list) or not isinstance(
  263. auth_event_ids, list
  264. ):
  265. raise Exception("invalid response from /state_ids")
  266. return state_event_ids, auth_event_ids
  267. @defer.inlineCallbacks
  268. @log_function
  269. def get_event_auth(self, destination, room_id, event_id):
  270. res = yield self.transport_layer.get_event_auth(destination, room_id, event_id)
  271. room_version = yield self.store.get_room_version_id(room_id)
  272. format_ver = room_version_to_event_format(room_version)
  273. auth_chain = [
  274. event_from_pdu_json(p, format_ver, outlier=True) for p in res["auth_chain"]
  275. ]
  276. signed_auth = yield self._check_sigs_and_hash_and_fetch(
  277. destination, auth_chain, outlier=True, room_version=room_version
  278. )
  279. signed_auth.sort(key=lambda e: e.depth)
  280. return signed_auth
  281. @defer.inlineCallbacks
  282. def _try_destination_list(self, description, destinations, callback):
  283. """Try an operation on a series of servers, until it succeeds
  284. Args:
  285. description (unicode): description of the operation we're doing, for logging
  286. destinations (Iterable[unicode]): list of server_names to try
  287. callback (callable): Function to run for each server. Passed a single
  288. argument: the server_name to try. May return a deferred.
  289. If the callback raises a CodeMessageException with a 300/400 code,
  290. attempts to perform the operation stop immediately and the exception is
  291. reraised.
  292. Otherwise, if the callback raises an Exception the error is logged and the
  293. next server tried. Normally the stacktrace is logged but this is
  294. suppressed if the exception is an InvalidResponseError.
  295. Returns:
  296. The [Deferred] result of callback, if it succeeds
  297. Raises:
  298. SynapseError if the chosen remote server returns a 300/400 code, or
  299. no servers were reachable.
  300. """
  301. for destination in destinations:
  302. if destination == self.server_name:
  303. continue
  304. try:
  305. res = yield callback(destination)
  306. return res
  307. except InvalidResponseError as e:
  308. logger.warning("Failed to %s via %s: %s", description, destination, e)
  309. except UnsupportedRoomVersionError:
  310. raise
  311. except HttpResponseException as e:
  312. if not 500 <= e.code < 600:
  313. raise e.to_synapse_error()
  314. else:
  315. logger.warning(
  316. "Failed to %s via %s: %i %s",
  317. description,
  318. destination,
  319. e.code,
  320. e.args[0],
  321. )
  322. except Exception:
  323. logger.warning(
  324. "Failed to %s via %s", description, destination, exc_info=1
  325. )
  326. raise SynapseError(502, "Failed to %s via any server" % (description,))
  327. def make_membership_event(
  328. self,
  329. destinations: Iterable[str],
  330. room_id: str,
  331. user_id: str,
  332. membership: str,
  333. content: dict,
  334. params: Dict[str, str],
  335. ):
  336. """
  337. Creates an m.room.member event, with context, without participating in the room.
  338. Does so by asking one of the already participating servers to create an
  339. event with proper context.
  340. Returns a fully signed and hashed event.
  341. Note that this does not append any events to any graphs.
  342. Args:
  343. destinations: Candidate homeservers which are probably
  344. participating in the room.
  345. room_id: The room in which the event will happen.
  346. user_id: The user whose membership is being evented.
  347. membership: The "membership" property of the event. Must be one of
  348. "join" or "leave".
  349. content: Any additional data to put into the content field of the
  350. event.
  351. params: Query parameters to include in the request.
  352. Return:
  353. Deferred[Tuple[str, FrozenEvent, RoomVersion]]: resolves to a tuple of
  354. `(origin, event, room_version)` where origin is the remote
  355. homeserver which generated the event, and room_version is the
  356. version of the room.
  357. Fails with a `UnsupportedRoomVersionError` if remote responds with
  358. a room version we don't understand.
  359. Fails with a ``SynapseError`` if the chosen remote server
  360. returns a 300/400 code.
  361. Fails with a ``RuntimeError`` if no servers were reachable.
  362. """
  363. valid_memberships = {Membership.JOIN, Membership.LEAVE}
  364. if membership not in valid_memberships:
  365. raise RuntimeError(
  366. "make_membership_event called with membership='%s', must be one of %s"
  367. % (membership, ",".join(valid_memberships))
  368. )
  369. @defer.inlineCallbacks
  370. def send_request(destination):
  371. ret = yield self.transport_layer.make_membership_event(
  372. destination, room_id, user_id, membership, params
  373. )
  374. # Note: If not supplied, the room version may be either v1 or v2,
  375. # however either way the event format version will be v1.
  376. room_version_id = ret.get("room_version", RoomVersions.V1.identifier)
  377. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  378. if not room_version:
  379. raise UnsupportedRoomVersionError()
  380. event_format = room_version_to_event_format(room_version_id)
  381. pdu_dict = ret.get("event", None)
  382. if not isinstance(pdu_dict, dict):
  383. raise InvalidResponseError("Bad 'event' field in response")
  384. logger.debug("Got response to make_%s: %s", membership, pdu_dict)
  385. pdu_dict["content"].update(content)
  386. # The protoevent received over the JSON wire may not have all
  387. # the required fields. Lets just gloss over that because
  388. # there's some we never care about
  389. if "prev_state" not in pdu_dict:
  390. pdu_dict["prev_state"] = []
  391. ev = builder.create_local_event_from_event_dict(
  392. self._clock,
  393. self.hostname,
  394. self.signing_key,
  395. format_version=event_format,
  396. event_dict=pdu_dict,
  397. )
  398. return (destination, ev, room_version)
  399. return self._try_destination_list(
  400. "make_" + membership, destinations, send_request
  401. )
  402. def send_join(self, destinations, pdu, event_format_version):
  403. """Sends a join event to one of a list of homeservers.
  404. Doing so will cause the remote server to add the event to the graph,
  405. and send the event out to the rest of the federation.
  406. Args:
  407. destinations (str): Candidate homeservers which are probably
  408. participating in the room.
  409. pdu (BaseEvent): event to be sent
  410. event_format_version (int): The event format version
  411. Return:
  412. Deferred: resolves to a dict with members ``origin`` (a string
  413. giving the serer the event was sent to, ``state`` (?) and
  414. ``auth_chain``.
  415. Fails with a ``SynapseError`` if the chosen remote server
  416. returns a 300/400 code.
  417. Fails with a ``RuntimeError`` if no servers were reachable.
  418. """
  419. def check_authchain_validity(signed_auth_chain):
  420. for e in signed_auth_chain:
  421. if e.type == EventTypes.Create:
  422. create_event = e
  423. break
  424. else:
  425. raise InvalidResponseError("no %s in auth chain" % (EventTypes.Create,))
  426. # the room version should be sane.
  427. room_version = create_event.content.get("room_version", "1")
  428. if room_version not in KNOWN_ROOM_VERSIONS:
  429. # This shouldn't be possible, because the remote server should have
  430. # rejected the join attempt during make_join.
  431. raise InvalidResponseError(
  432. "room appears to have unsupported version %s" % (room_version,)
  433. )
  434. @defer.inlineCallbacks
  435. def send_request(destination):
  436. content = yield self._do_send_join(destination, pdu)
  437. logger.debug("Got content: %s", content)
  438. state = [
  439. event_from_pdu_json(p, event_format_version, outlier=True)
  440. for p in content.get("state", [])
  441. ]
  442. auth_chain = [
  443. event_from_pdu_json(p, event_format_version, outlier=True)
  444. for p in content.get("auth_chain", [])
  445. ]
  446. pdus = {p.event_id: p for p in itertools.chain(state, auth_chain)}
  447. room_version = None
  448. for e in state:
  449. if (e.type, e.state_key) == (EventTypes.Create, ""):
  450. room_version = e.content.get(
  451. "room_version", RoomVersions.V1.identifier
  452. )
  453. break
  454. if room_version is None:
  455. # If the state doesn't have a create event then the room is
  456. # invalid, and it would fail auth checks anyway.
  457. raise SynapseError(400, "No create event in state")
  458. valid_pdus = yield self._check_sigs_and_hash_and_fetch(
  459. destination,
  460. list(pdus.values()),
  461. outlier=True,
  462. room_version=room_version,
  463. )
  464. valid_pdus_map = {p.event_id: p for p in valid_pdus}
  465. # NB: We *need* to copy to ensure that we don't have multiple
  466. # references being passed on, as that causes... issues.
  467. signed_state = [
  468. copy.copy(valid_pdus_map[p.event_id])
  469. for p in state
  470. if p.event_id in valid_pdus_map
  471. ]
  472. signed_auth = [
  473. valid_pdus_map[p.event_id]
  474. for p in auth_chain
  475. if p.event_id in valid_pdus_map
  476. ]
  477. # NB: We *need* to copy to ensure that we don't have multiple
  478. # references being passed on, as that causes... issues.
  479. for s in signed_state:
  480. s.internal_metadata = copy.deepcopy(s.internal_metadata)
  481. check_authchain_validity(signed_auth)
  482. return {
  483. "state": signed_state,
  484. "auth_chain": signed_auth,
  485. "origin": destination,
  486. }
  487. return self._try_destination_list("send_join", destinations, send_request)
  488. @defer.inlineCallbacks
  489. def _do_send_join(self, destination, pdu):
  490. time_now = self._clock.time_msec()
  491. try:
  492. content = yield self.transport_layer.send_join_v2(
  493. destination=destination,
  494. room_id=pdu.room_id,
  495. event_id=pdu.event_id,
  496. content=pdu.get_pdu_json(time_now),
  497. )
  498. return content
  499. except HttpResponseException as e:
  500. if e.code in [400, 404]:
  501. err = e.to_synapse_error()
  502. # If we receive an error response that isn't a generic error, or an
  503. # unrecognised endpoint error, we assume that the remote understands
  504. # the v2 invite API and this is a legitimate error.
  505. if err.errcode not in [Codes.UNKNOWN, Codes.UNRECOGNIZED]:
  506. raise err
  507. else:
  508. raise e.to_synapse_error()
  509. logger.debug("Couldn't send_join with the v2 API, falling back to the v1 API")
  510. resp = yield self.transport_layer.send_join_v1(
  511. destination=destination,
  512. room_id=pdu.room_id,
  513. event_id=pdu.event_id,
  514. content=pdu.get_pdu_json(time_now),
  515. )
  516. # We expect the v1 API to respond with [200, content], so we only return the
  517. # content.
  518. return resp[1]
  519. @defer.inlineCallbacks
  520. def send_invite(self, destination, room_id, event_id, pdu):
  521. room_version = yield self.store.get_room_version_id(room_id)
  522. content = yield self._do_send_invite(destination, pdu, room_version)
  523. pdu_dict = content["event"]
  524. logger.debug("Got response to send_invite: %s", pdu_dict)
  525. room_version = yield self.store.get_room_version_id(room_id)
  526. format_ver = room_version_to_event_format(room_version)
  527. pdu = event_from_pdu_json(pdu_dict, format_ver)
  528. # Check signatures are correct.
  529. pdu = yield self._check_sigs_and_hash(room_version, pdu)
  530. # FIXME: We should handle signature failures more gracefully.
  531. return pdu
  532. @defer.inlineCallbacks
  533. def _do_send_invite(self, destination, pdu, room_version):
  534. """Actually sends the invite, first trying v2 API and falling back to
  535. v1 API if necessary.
  536. Args:
  537. destination (str): Target server
  538. pdu (FrozenEvent)
  539. room_version (str)
  540. Returns:
  541. dict: The event as a dict as returned by the remote server
  542. """
  543. time_now = self._clock.time_msec()
  544. try:
  545. content = yield self.transport_layer.send_invite_v2(
  546. destination=destination,
  547. room_id=pdu.room_id,
  548. event_id=pdu.event_id,
  549. content={
  550. "event": pdu.get_pdu_json(time_now),
  551. "room_version": room_version,
  552. "invite_room_state": pdu.unsigned.get("invite_room_state", []),
  553. },
  554. )
  555. return content
  556. except HttpResponseException as e:
  557. if e.code in [400, 404]:
  558. err = e.to_synapse_error()
  559. # If we receive an error response that isn't a generic error, we
  560. # assume that the remote understands the v2 invite API and this
  561. # is a legitimate error.
  562. if err.errcode != Codes.UNKNOWN:
  563. raise err
  564. # Otherwise, we assume that the remote server doesn't understand
  565. # the v2 invite API. That's ok provided the room uses old-style event
  566. # IDs.
  567. v = KNOWN_ROOM_VERSIONS.get(room_version)
  568. if v.event_format != EventFormatVersions.V1:
  569. raise SynapseError(
  570. 400,
  571. "User's homeserver does not support this room version",
  572. Codes.UNSUPPORTED_ROOM_VERSION,
  573. )
  574. elif e.code == 403:
  575. raise e.to_synapse_error()
  576. else:
  577. raise
  578. # Didn't work, try v1 API.
  579. # Note the v1 API returns a tuple of `(200, content)`
  580. _, content = yield self.transport_layer.send_invite_v1(
  581. destination=destination,
  582. room_id=pdu.room_id,
  583. event_id=pdu.event_id,
  584. content=pdu.get_pdu_json(time_now),
  585. )
  586. return content
  587. def send_leave(self, destinations, pdu):
  588. """Sends a leave event to one of a list of homeservers.
  589. Doing so will cause the remote server to add the event to the graph,
  590. and send the event out to the rest of the federation.
  591. This is mostly useful to reject received invites.
  592. Args:
  593. destinations (str): Candidate homeservers which are probably
  594. participating in the room.
  595. pdu (BaseEvent): event to be sent
  596. Return:
  597. Deferred: resolves to None.
  598. Fails with a ``SynapseError`` if the chosen remote server
  599. returns a 300/400 code.
  600. Fails with a ``RuntimeError`` if no servers were reachable.
  601. """
  602. @defer.inlineCallbacks
  603. def send_request(destination):
  604. content = yield self._do_send_leave(destination, pdu)
  605. logger.debug("Got content: %s", content)
  606. return None
  607. return self._try_destination_list("send_leave", destinations, send_request)
  608. @defer.inlineCallbacks
  609. def _do_send_leave(self, destination, pdu):
  610. time_now = self._clock.time_msec()
  611. try:
  612. content = yield self.transport_layer.send_leave_v2(
  613. destination=destination,
  614. room_id=pdu.room_id,
  615. event_id=pdu.event_id,
  616. content=pdu.get_pdu_json(time_now),
  617. )
  618. return content
  619. except HttpResponseException as e:
  620. if e.code in [400, 404]:
  621. err = e.to_synapse_error()
  622. # If we receive an error response that isn't a generic error, or an
  623. # unrecognised endpoint error, we assume that the remote understands
  624. # the v2 invite API and this is a legitimate error.
  625. if err.errcode not in [Codes.UNKNOWN, Codes.UNRECOGNIZED]:
  626. raise err
  627. else:
  628. raise e.to_synapse_error()
  629. logger.debug("Couldn't send_leave with the v2 API, falling back to the v1 API")
  630. resp = yield self.transport_layer.send_leave_v1(
  631. destination=destination,
  632. room_id=pdu.room_id,
  633. event_id=pdu.event_id,
  634. content=pdu.get_pdu_json(time_now),
  635. )
  636. # We expect the v1 API to respond with [200, content], so we only return the
  637. # content.
  638. return resp[1]
  639. def get_public_rooms(
  640. self,
  641. destination,
  642. limit=None,
  643. since_token=None,
  644. search_filter=None,
  645. include_all_networks=False,
  646. third_party_instance_id=None,
  647. ):
  648. if destination == self.server_name:
  649. return
  650. return self.transport_layer.get_public_rooms(
  651. destination,
  652. limit,
  653. since_token,
  654. search_filter,
  655. include_all_networks=include_all_networks,
  656. third_party_instance_id=third_party_instance_id,
  657. )
  658. @defer.inlineCallbacks
  659. def get_missing_events(
  660. self,
  661. destination,
  662. room_id,
  663. earliest_events_ids,
  664. latest_events,
  665. limit,
  666. min_depth,
  667. timeout,
  668. ):
  669. """Tries to fetch events we are missing. This is called when we receive
  670. an event without having received all of its ancestors.
  671. Args:
  672. destination (str)
  673. room_id (str)
  674. earliest_events_ids (list): List of event ids. Effectively the
  675. events we expected to receive, but haven't. `get_missing_events`
  676. should only return events that didn't happen before these.
  677. latest_events (list): List of events we have received that we don't
  678. have all previous events for.
  679. limit (int): Maximum number of events to return.
  680. min_depth (int): Minimum depth of events tor return.
  681. timeout (int): Max time to wait in ms
  682. """
  683. try:
  684. content = yield self.transport_layer.get_missing_events(
  685. destination=destination,
  686. room_id=room_id,
  687. earliest_events=earliest_events_ids,
  688. latest_events=[e.event_id for e in latest_events],
  689. limit=limit,
  690. min_depth=min_depth,
  691. timeout=timeout,
  692. )
  693. room_version = yield self.store.get_room_version_id(room_id)
  694. format_ver = room_version_to_event_format(room_version)
  695. events = [
  696. event_from_pdu_json(e, format_ver) for e in content.get("events", [])
  697. ]
  698. signed_events = yield self._check_sigs_and_hash_and_fetch(
  699. destination, events, outlier=False, room_version=room_version
  700. )
  701. except HttpResponseException as e:
  702. if not e.code == 400:
  703. raise
  704. # We are probably hitting an old server that doesn't support
  705. # get_missing_events
  706. signed_events = []
  707. return signed_events
  708. @defer.inlineCallbacks
  709. def forward_third_party_invite(self, destinations, room_id, event_dict):
  710. for destination in destinations:
  711. if destination == self.server_name:
  712. continue
  713. try:
  714. yield self.transport_layer.exchange_third_party_invite(
  715. destination=destination, room_id=room_id, event_dict=event_dict
  716. )
  717. return None
  718. except CodeMessageException:
  719. raise
  720. except Exception as e:
  721. logger.exception(
  722. "Failed to send_third_party_invite via %s: %s", destination, str(e)
  723. )
  724. raise RuntimeError("Failed to send to any server.")
  725. @defer.inlineCallbacks
  726. def get_room_complexity(self, destination, room_id):
  727. """
  728. Fetch the complexity of a remote room from another server.
  729. Args:
  730. destination (str): The remote server
  731. room_id (str): The room ID to ask about.
  732. Returns:
  733. Deferred[dict] or Deferred[None]: Dict contains the complexity
  734. metric versions, while None means we could not fetch the complexity.
  735. """
  736. try:
  737. complexity = yield self.transport_layer.get_room_complexity(
  738. destination=destination, room_id=room_id
  739. )
  740. defer.returnValue(complexity)
  741. except CodeMessageException as e:
  742. # We didn't manage to get it -- probably a 404. We are okay if other
  743. # servers don't give it to us.
  744. logger.debug(
  745. "Failed to fetch room complexity via %s for %s, got a %d",
  746. destination,
  747. room_id,
  748. e.code,
  749. )
  750. except Exception:
  751. logger.exception(
  752. "Failed to fetch room complexity via %s for %s", destination, room_id
  753. )
  754. # If we don't manage to find it, return None. It's not an error if a
  755. # server doesn't give it to us.
  756. defer.returnValue(None)