federation_client.py 36 KB

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