Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

1903 righe
69 KiB

  1. # Copyright 2015-2022 The Matrix.org Foundation C.I.C.
  2. # Copyright 2020 Sorunome
  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. TYPE_CHECKING,
  20. Awaitable,
  21. Callable,
  22. Collection,
  23. Container,
  24. Dict,
  25. Iterable,
  26. List,
  27. Mapping,
  28. Optional,
  29. Sequence,
  30. Tuple,
  31. TypeVar,
  32. Union,
  33. )
  34. import attr
  35. from prometheus_client import Counter
  36. from synapse.api.constants import EventContentFields, EventTypes, Membership
  37. from synapse.api.errors import (
  38. CodeMessageException,
  39. Codes,
  40. FederationDeniedError,
  41. HttpResponseException,
  42. RequestSendFailed,
  43. SynapseError,
  44. UnsupportedRoomVersionError,
  45. )
  46. from synapse.api.room_versions import (
  47. KNOWN_ROOM_VERSIONS,
  48. EventFormatVersions,
  49. RoomVersion,
  50. RoomVersions,
  51. )
  52. from synapse.events import EventBase, builder, make_event_from_dict
  53. from synapse.federation.federation_base import (
  54. FederationBase,
  55. InvalidEventSignatureError,
  56. event_from_pdu_json,
  57. )
  58. from synapse.federation.transport.client import SendJoinResponse
  59. from synapse.http.types import QueryParams
  60. from synapse.logging.opentracing import SynapseTags, log_kv, set_tag, tag_args, trace
  61. from synapse.types import JsonDict, UserID, get_domain_from_id
  62. from synapse.util.async_helpers import concurrently_execute
  63. from synapse.util.caches.expiringcache import ExpiringCache
  64. from synapse.util.retryutils import NotRetryingDestination
  65. if TYPE_CHECKING:
  66. from synapse.server import HomeServer
  67. logger = logging.getLogger(__name__)
  68. sent_queries_counter = Counter("synapse_federation_client_sent_queries", "", ["type"])
  69. PDU_RETRY_TIME_MS = 1 * 60 * 1000
  70. T = TypeVar("T")
  71. @attr.s(frozen=True, slots=True, auto_attribs=True)
  72. class PulledPduInfo:
  73. """
  74. A result object that stores the PDU and info about it like which homeserver we
  75. pulled it from (`pull_origin`)
  76. """
  77. pdu: EventBase
  78. # Which homeserver we pulled the PDU from
  79. pull_origin: str
  80. class InvalidResponseError(RuntimeError):
  81. """Helper for _try_destination_list: indicates that the server returned a response
  82. we couldn't parse
  83. """
  84. @attr.s(slots=True, frozen=True, auto_attribs=True)
  85. class SendJoinResult:
  86. # The event to persist.
  87. event: EventBase
  88. # A string giving the server the event was sent to.
  89. origin: str
  90. state: List[EventBase]
  91. auth_chain: List[EventBase]
  92. # True if 'state' elides non-critical membership events
  93. partial_state: bool
  94. # if 'partial_state' is set, a list of the servers in the room (otherwise empty)
  95. servers_in_room: List[str]
  96. class FederationClient(FederationBase):
  97. def __init__(self, hs: "HomeServer"):
  98. super().__init__(hs)
  99. self.pdu_destination_tried: Dict[str, Dict[str, int]] = {}
  100. self._clock.looping_call(self._clear_tried_cache, 60 * 1000)
  101. self.state = hs.get_state_handler()
  102. self.transport_layer = hs.get_federation_transport_client()
  103. self.hostname = hs.hostname
  104. self.signing_key = hs.signing_key
  105. # Cache mapping `event_id` to a tuple of the event itself and the `pull_origin`
  106. # (which server we pulled the event from)
  107. self._get_pdu_cache: ExpiringCache[str, Tuple[EventBase, str]] = ExpiringCache(
  108. cache_name="get_pdu_cache",
  109. clock=self._clock,
  110. max_len=1000,
  111. expiry_ms=120 * 1000,
  112. reset_expiry_on_get=False,
  113. )
  114. # A cache for fetching the room hierarchy over federation.
  115. #
  116. # Some stale data over federation is OK, but must be refreshed
  117. # periodically since the local server is in the room.
  118. #
  119. # It is a map of (room ID, suggested-only) -> the response of
  120. # get_room_hierarchy.
  121. self._get_room_hierarchy_cache: ExpiringCache[
  122. Tuple[str, bool],
  123. Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]],
  124. ] = ExpiringCache(
  125. cache_name="get_room_hierarchy_cache",
  126. clock=self._clock,
  127. max_len=1000,
  128. expiry_ms=5 * 60 * 1000,
  129. reset_expiry_on_get=False,
  130. )
  131. def _clear_tried_cache(self) -> None:
  132. """Clear pdu_destination_tried cache"""
  133. now = self._clock.time_msec()
  134. old_dict = self.pdu_destination_tried
  135. self.pdu_destination_tried = {}
  136. for event_id, destination_dict in old_dict.items():
  137. destination_dict = {
  138. dest: time
  139. for dest, time in destination_dict.items()
  140. if time + PDU_RETRY_TIME_MS > now
  141. }
  142. if destination_dict:
  143. self.pdu_destination_tried[event_id] = destination_dict
  144. async def make_query(
  145. self,
  146. destination: str,
  147. query_type: str,
  148. args: QueryParams,
  149. retry_on_dns_fail: bool = False,
  150. ignore_backoff: bool = False,
  151. ) -> JsonDict:
  152. """Sends a federation Query to a remote homeserver of the given type
  153. and arguments.
  154. Args:
  155. destination: Domain name of the remote homeserver
  156. query_type: Category of the query type; should match the
  157. handler name used in register_query_handler().
  158. args: Mapping of strings to strings containing the details
  159. of the query request.
  160. ignore_backoff: true to ignore the historical backoff data
  161. and try the request anyway.
  162. Returns:
  163. The JSON object from the response
  164. """
  165. sent_queries_counter.labels(query_type).inc()
  166. return await self.transport_layer.make_query(
  167. destination,
  168. query_type,
  169. args,
  170. retry_on_dns_fail=retry_on_dns_fail,
  171. ignore_backoff=ignore_backoff,
  172. )
  173. async def query_client_keys(
  174. self, destination: str, content: JsonDict, timeout: int
  175. ) -> JsonDict:
  176. """Query device keys for a device hosted on a remote server.
  177. Args:
  178. destination: Domain name of the remote homeserver
  179. content: The query content.
  180. Returns:
  181. The JSON object from the response
  182. """
  183. sent_queries_counter.labels("client_device_keys").inc()
  184. return await self.transport_layer.query_client_keys(
  185. destination, content, timeout
  186. )
  187. async def query_user_devices(
  188. self, destination: str, user_id: str, timeout: int = 30000
  189. ) -> JsonDict:
  190. """Query the device keys for a list of user ids hosted on a remote
  191. server.
  192. """
  193. sent_queries_counter.labels("user_devices").inc()
  194. return await self.transport_layer.query_user_devices(
  195. destination, user_id, timeout
  196. )
  197. async def claim_client_keys(
  198. self, destination: str, content: JsonDict, timeout: Optional[int]
  199. ) -> JsonDict:
  200. """Claims one-time keys for a device hosted on a remote server.
  201. Args:
  202. destination: Domain name of the remote homeserver
  203. content: The query content.
  204. Returns:
  205. The JSON object from the response
  206. """
  207. sent_queries_counter.labels("client_one_time_keys").inc()
  208. return await self.transport_layer.claim_client_keys(
  209. destination, content, timeout
  210. )
  211. @trace
  212. @tag_args
  213. async def backfill(
  214. self, dest: str, room_id: str, limit: int, extremities: Collection[str]
  215. ) -> Optional[List[EventBase]]:
  216. """Requests some more historic PDUs for the given room from the
  217. given destination server.
  218. Args:
  219. dest: The remote homeserver to ask.
  220. room_id: The room_id to backfill.
  221. limit: The maximum number of events to return.
  222. extremities: our current backwards extremities, to backfill from
  223. Must be a Collection that is falsy when empty.
  224. (Iterable is not enough here!)
  225. """
  226. logger.debug("backfill extrem=%s", extremities)
  227. # If there are no extremities then we've (probably) reached the start.
  228. if not extremities:
  229. return None
  230. transaction_data = await self.transport_layer.backfill(
  231. dest, room_id, extremities, limit
  232. )
  233. logger.debug("backfill transaction_data=%r", transaction_data)
  234. if not isinstance(transaction_data, dict):
  235. # TODO we probably want an exception type specific to federation
  236. # client validation.
  237. raise TypeError("Backfill transaction_data is not a dict.")
  238. transaction_data_pdus = transaction_data.get("pdus")
  239. if not isinstance(transaction_data_pdus, list):
  240. # TODO we probably want an exception type specific to federation
  241. # client validation.
  242. raise TypeError("transaction_data.pdus is not a list.")
  243. room_version = await self.store.get_room_version(room_id)
  244. pdus = [event_from_pdu_json(p, room_version) for p in transaction_data_pdus]
  245. # Check signatures and hash of pdus, removing any from the list that fail checks
  246. pdus[:] = await self._check_sigs_and_hash_for_pulled_events_and_fetch(
  247. dest, pdus, room_version=room_version
  248. )
  249. return pdus
  250. async def get_pdu_from_destination_raw(
  251. self,
  252. destination: str,
  253. event_id: str,
  254. room_version: RoomVersion,
  255. timeout: Optional[int] = None,
  256. ) -> Optional[EventBase]:
  257. """Requests the PDU with given origin and ID from the remote home
  258. server. Does not have any caching or rate limiting!
  259. Args:
  260. destination: Which homeserver to query
  261. event_id: event to fetch
  262. room_version: version of the room
  263. timeout: How long to try (in ms) each destination for before
  264. moving to the next destination. None indicates no timeout.
  265. Returns:
  266. A copy of the requested PDU that is safe to modify, or None if we
  267. were unable to find it.
  268. Raises:
  269. SynapseError, NotRetryingDestination, FederationDeniedError
  270. """
  271. transaction_data = await self.transport_layer.get_event(
  272. destination, event_id, timeout=timeout
  273. )
  274. logger.debug(
  275. "get_pdu_from_destination_raw: retrieved event id %s from %s: %r",
  276. event_id,
  277. destination,
  278. transaction_data,
  279. )
  280. pdu_list: List[EventBase] = [
  281. event_from_pdu_json(p, room_version) for p in transaction_data["pdus"]
  282. ]
  283. if pdu_list and pdu_list[0]:
  284. pdu = pdu_list[0]
  285. # Check signatures are correct.
  286. try:
  287. async def _record_failure_callback(
  288. event: EventBase, cause: str
  289. ) -> None:
  290. await self.store.record_event_failed_pull_attempt(
  291. event.room_id, event.event_id, cause
  292. )
  293. signed_pdu = await self._check_sigs_and_hash(
  294. room_version, pdu, _record_failure_callback
  295. )
  296. except InvalidEventSignatureError as e:
  297. errmsg = f"event id {pdu.event_id}: {e}"
  298. logger.warning("%s", errmsg)
  299. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  300. return signed_pdu
  301. return None
  302. @trace
  303. @tag_args
  304. async def get_pdu(
  305. self,
  306. destinations: Collection[str],
  307. event_id: str,
  308. room_version: RoomVersion,
  309. timeout: Optional[int] = None,
  310. ) -> Optional[PulledPduInfo]:
  311. """Requests the PDU with given origin and ID from the remote home
  312. servers.
  313. Will attempt to get the PDU from each destination in the list until
  314. one succeeds.
  315. Args:
  316. destinations: Which homeservers to query
  317. event_id: event to fetch
  318. room_version: version of the room
  319. timeout: How long to try (in ms) each destination for before
  320. moving to the next destination. None indicates no timeout.
  321. Returns:
  322. The requested PDU wrapped in `PulledPduInfo`, or None if we were unable to find it.
  323. """
  324. logger.debug(
  325. "get_pdu(event_id=%s): from destinations=%s", event_id, destinations
  326. )
  327. # TODO: Rate limit the number of times we try and get the same event.
  328. # We might need the same event multiple times in quick succession (before
  329. # it gets persisted to the database), so we cache the results of the lookup.
  330. # Note that this is separate to the regular get_event cache which caches
  331. # events once they have been persisted.
  332. get_pdu_cache_entry = self._get_pdu_cache.get(event_id)
  333. event = None
  334. pull_origin = None
  335. if get_pdu_cache_entry:
  336. event, pull_origin = get_pdu_cache_entry
  337. # If we don't see the event in the cache, go try to fetch it from the
  338. # provided remote federated destinations
  339. else:
  340. pdu_attempts = self.pdu_destination_tried.setdefault(event_id, {})
  341. # TODO: We can probably refactor this to use `_try_destination_list`
  342. for destination in destinations:
  343. now = self._clock.time_msec()
  344. last_attempt = pdu_attempts.get(destination, 0)
  345. if last_attempt + PDU_RETRY_TIME_MS > now:
  346. logger.debug(
  347. "get_pdu(event_id=%s): skipping destination=%s because we tried it recently last_attempt=%s and we only check every %s (now=%s)",
  348. event_id,
  349. destination,
  350. last_attempt,
  351. PDU_RETRY_TIME_MS,
  352. now,
  353. )
  354. continue
  355. try:
  356. event = await self.get_pdu_from_destination_raw(
  357. destination=destination,
  358. event_id=event_id,
  359. room_version=room_version,
  360. timeout=timeout,
  361. )
  362. pull_origin = destination
  363. pdu_attempts[destination] = now
  364. if event:
  365. # Prime the cache
  366. self._get_pdu_cache[event.event_id] = (event, pull_origin)
  367. # Now that we have an event, we can break out of this
  368. # loop and stop asking other destinations.
  369. break
  370. except NotRetryingDestination as e:
  371. logger.info("get_pdu(event_id=%s): %s", event_id, e)
  372. continue
  373. except FederationDeniedError:
  374. logger.info(
  375. "get_pdu(event_id=%s): Not attempting to fetch PDU from %s because the homeserver is not on our federation whitelist",
  376. event_id,
  377. destination,
  378. )
  379. continue
  380. except SynapseError as e:
  381. logger.info(
  382. "get_pdu(event_id=%s): Failed to get PDU from %s because %s",
  383. event_id,
  384. destination,
  385. e,
  386. )
  387. continue
  388. except Exception as e:
  389. pdu_attempts[destination] = now
  390. logger.info(
  391. "get_pdu(event_id=%s): Failed to get PDU from %s because %s",
  392. event_id,
  393. destination,
  394. e,
  395. )
  396. continue
  397. if not event or not pull_origin:
  398. return None
  399. # `event` now refers to an object stored in `get_pdu_cache`. Our
  400. # callers may need to modify the returned object (eg to set
  401. # `event.internal_metadata.outlier = true`), so we return a copy
  402. # rather than the original object.
  403. event_copy = make_event_from_dict(
  404. event.get_pdu_json(),
  405. event.room_version,
  406. )
  407. return PulledPduInfo(event_copy, pull_origin)
  408. @trace
  409. @tag_args
  410. async def get_room_state_ids(
  411. self, destination: str, room_id: str, event_id: str
  412. ) -> Tuple[List[str], List[str]]:
  413. """Calls the /state_ids endpoint to fetch the state at a particular point
  414. in the room, and the auth events for the given event
  415. Returns:
  416. a tuple of (state event_ids, auth event_ids)
  417. Raises:
  418. InvalidResponseError: if fields in the response have the wrong type.
  419. """
  420. result = await self.transport_layer.get_room_state_ids(
  421. destination, room_id, event_id=event_id
  422. )
  423. state_event_ids = result["pdu_ids"]
  424. auth_event_ids = result.get("auth_chain_ids", [])
  425. set_tag(
  426. SynapseTags.RESULT_PREFIX + "state_event_ids",
  427. str(state_event_ids),
  428. )
  429. set_tag(
  430. SynapseTags.RESULT_PREFIX + "state_event_ids.length",
  431. str(len(state_event_ids)),
  432. )
  433. set_tag(
  434. SynapseTags.RESULT_PREFIX + "auth_event_ids",
  435. str(auth_event_ids),
  436. )
  437. set_tag(
  438. SynapseTags.RESULT_PREFIX + "auth_event_ids.length",
  439. str(len(auth_event_ids)),
  440. )
  441. if not isinstance(state_event_ids, list) or not isinstance(
  442. auth_event_ids, list
  443. ):
  444. raise InvalidResponseError("invalid response from /state_ids")
  445. return state_event_ids, auth_event_ids
  446. @trace
  447. @tag_args
  448. async def get_room_state(
  449. self,
  450. destination: str,
  451. room_id: str,
  452. event_id: str,
  453. room_version: RoomVersion,
  454. ) -> Tuple[List[EventBase], List[EventBase]]:
  455. """Calls the /state endpoint to fetch the state at a particular point
  456. in the room.
  457. Any invalid events (those with incorrect or unverifiable signatures or hashes)
  458. are filtered out from the response, and any duplicate events are removed.
  459. (Size limits and other event-format checks are *not* performed.)
  460. Note that the result is not ordered, so callers must be careful to process
  461. the events in an order that handles dependencies.
  462. Returns:
  463. a tuple of (state events, auth events)
  464. """
  465. result = await self.transport_layer.get_room_state(
  466. room_version,
  467. destination,
  468. room_id,
  469. event_id,
  470. )
  471. state_events = result.state
  472. auth_events = result.auth_events
  473. # we may as well filter out any duplicates from the response, to save
  474. # processing them multiple times. (In particular, events may be present in
  475. # `auth_events` as well as `state`, which is redundant).
  476. #
  477. # We don't rely on the sort order of the events, so we can just stick them
  478. # in a dict.
  479. state_event_map = {event.event_id: event for event in state_events}
  480. auth_event_map = {
  481. event.event_id: event
  482. for event in auth_events
  483. if event.event_id not in state_event_map
  484. }
  485. logger.info(
  486. "Processing from /state: %d state events, %d auth events",
  487. len(state_event_map),
  488. len(auth_event_map),
  489. )
  490. valid_auth_events = await self._check_sigs_and_hash_for_pulled_events_and_fetch(
  491. destination, auth_event_map.values(), room_version
  492. )
  493. valid_state_events = (
  494. await self._check_sigs_and_hash_for_pulled_events_and_fetch(
  495. destination, state_event_map.values(), room_version
  496. )
  497. )
  498. return valid_state_events, valid_auth_events
  499. @trace
  500. async def _check_sigs_and_hash_for_pulled_events_and_fetch(
  501. self,
  502. origin: str,
  503. pdus: Collection[EventBase],
  504. room_version: RoomVersion,
  505. ) -> List[EventBase]:
  506. """
  507. Checks the signatures and hashes of a list of pulled events we got from
  508. federation and records any signature failures as failed pull attempts.
  509. If a PDU fails its signature check then we check if we have it in
  510. the database, and if not then request it from the sender's server (if that
  511. is different from `origin`). If that still fails, the event is omitted from
  512. the returned list.
  513. If a PDU fails its content hash check then it is redacted.
  514. Also runs each event through the spam checker; if it fails, redacts the event
  515. and flags it as soft-failed.
  516. The given list of PDUs are not modified; instead the function returns
  517. a new list.
  518. Args:
  519. origin: The server that sent us these events
  520. pdus: The events to be checked
  521. room_version: the version of the room these events are in
  522. Returns:
  523. A list of PDUs that have valid signatures and hashes.
  524. """
  525. set_tag(
  526. SynapseTags.RESULT_PREFIX + "pdus.length",
  527. str(len(pdus)),
  528. )
  529. # We limit how many PDUs we check at once, as if we try to do hundreds
  530. # of thousands of PDUs at once we see large memory spikes.
  531. valid_pdus: List[EventBase] = []
  532. async def _record_failure_callback(event: EventBase, cause: str) -> None:
  533. await self.store.record_event_failed_pull_attempt(
  534. event.room_id, event.event_id, cause
  535. )
  536. async def _execute(pdu: EventBase) -> None:
  537. valid_pdu = await self._check_sigs_and_hash_and_fetch_one(
  538. pdu=pdu,
  539. origin=origin,
  540. room_version=room_version,
  541. record_failure_callback=_record_failure_callback,
  542. )
  543. if valid_pdu:
  544. valid_pdus.append(valid_pdu)
  545. await concurrently_execute(_execute, pdus, 10000)
  546. return valid_pdus
  547. @trace
  548. @tag_args
  549. async def _check_sigs_and_hash_and_fetch_one(
  550. self,
  551. pdu: EventBase,
  552. origin: str,
  553. room_version: RoomVersion,
  554. record_failure_callback: Optional[
  555. Callable[[EventBase, str], Awaitable[None]]
  556. ] = None,
  557. ) -> Optional[EventBase]:
  558. """Takes a PDU and checks its signatures and hashes.
  559. If the PDU fails its signature check then we check if we have it in the
  560. database; if not, we then request it from sender's server (if that is not the
  561. same as `origin`). If that still fails, we return None.
  562. If the PDU fails its content hash check, it is redacted.
  563. Also runs the event through the spam checker; if it fails, redacts the event
  564. and flags it as soft-failed.
  565. Args:
  566. origin
  567. pdu
  568. room_version
  569. record_failure_callback: A callback to run whenever the given event
  570. fails signature or hash checks. This includes exceptions
  571. that would be normally be thrown/raised but also things like
  572. checking for event tampering where we just return the redacted
  573. event.
  574. Returns:
  575. The PDU (possibly redacted) if it has valid signatures and hashes.
  576. None if no valid copy could be found.
  577. """
  578. try:
  579. return await self._check_sigs_and_hash(
  580. room_version, pdu, record_failure_callback
  581. )
  582. except InvalidEventSignatureError as e:
  583. logger.warning(
  584. "Signature on retrieved event %s was invalid (%s). "
  585. "Checking local store/origin server",
  586. pdu.event_id,
  587. e,
  588. )
  589. log_kv(
  590. {
  591. "message": "Signature on retrieved event was invalid. "
  592. "Checking local store/origin server",
  593. "event_id": pdu.event_id,
  594. "InvalidEventSignatureError": e,
  595. }
  596. )
  597. # Check local db.
  598. res = await self.store.get_event(
  599. pdu.event_id, allow_rejected=True, allow_none=True
  600. )
  601. # If the PDU fails its signature check and we don't have it in our
  602. # database, we then request it from sender's server (if that is not the
  603. # same as `origin`).
  604. pdu_origin = get_domain_from_id(pdu.sender)
  605. if not res and pdu_origin != origin:
  606. try:
  607. pulled_pdu_info = await self.get_pdu(
  608. destinations=[pdu_origin],
  609. event_id=pdu.event_id,
  610. room_version=room_version,
  611. timeout=10000,
  612. )
  613. if pulled_pdu_info is not None:
  614. res = pulled_pdu_info.pdu
  615. except SynapseError:
  616. pass
  617. if not res:
  618. logger.warning(
  619. "Failed to find copy of %s with valid signature", pdu.event_id
  620. )
  621. return res
  622. async def get_event_auth(
  623. self, destination: str, room_id: str, event_id: str
  624. ) -> List[EventBase]:
  625. res = await self.transport_layer.get_event_auth(destination, room_id, event_id)
  626. room_version = await self.store.get_room_version(room_id)
  627. auth_chain = [event_from_pdu_json(p, room_version) for p in res["auth_chain"]]
  628. signed_auth = await self._check_sigs_and_hash_for_pulled_events_and_fetch(
  629. destination, auth_chain, room_version=room_version
  630. )
  631. return signed_auth
  632. def _is_unknown_endpoint(
  633. self, e: HttpResponseException, synapse_error: Optional[SynapseError] = None
  634. ) -> bool:
  635. """
  636. Returns true if the response was due to an endpoint being unimplemented.
  637. Args:
  638. e: The error response received from the remote server.
  639. synapse_error: The above error converted to a SynapseError. This is
  640. automatically generated if not provided.
  641. """
  642. if synapse_error is None:
  643. synapse_error = e.to_synapse_error()
  644. # MSC3743 specifies that servers should return a 404 or 405 with an errcode
  645. # of M_UNRECOGNIZED when they receive a request to an unknown endpoint or
  646. # to an unknown method, respectively.
  647. #
  648. # Older versions of servers don't properly handle this. This needs to be
  649. # rather specific as some endpoints truly do return 404 errors.
  650. return (
  651. # 404 is an unknown endpoint, 405 is a known endpoint, but unknown method.
  652. (e.code == 404 or e.code == 405)
  653. and (
  654. # Older Dendrites returned a text or empty body.
  655. # Older Conduit returned an empty body.
  656. not e.response
  657. or e.response == b"404 page not found"
  658. # The proper response JSON with M_UNRECOGNIZED errcode.
  659. or synapse_error.errcode == Codes.UNRECOGNIZED
  660. )
  661. ) or (
  662. # Older Synapses returned a 400 error.
  663. e.code == 400
  664. and synapse_error.errcode == Codes.UNRECOGNIZED
  665. )
  666. async def _try_destination_list(
  667. self,
  668. description: str,
  669. destinations: Iterable[str],
  670. callback: Callable[[str], Awaitable[T]],
  671. failover_errcodes: Optional[Container[str]] = None,
  672. failover_on_unknown_endpoint: bool = False,
  673. ) -> T:
  674. """Try an operation on a series of servers, until it succeeds
  675. Args:
  676. description: description of the operation we're doing, for logging
  677. destinations: list of server_names to try
  678. callback: Function to run for each server. Passed a single
  679. argument: the server_name to try.
  680. If the callback raises a CodeMessageException with a 300/400 code or
  681. an UnsupportedRoomVersionError, attempts to perform the operation
  682. stop immediately and the exception is reraised.
  683. Otherwise, if the callback raises an Exception the error is logged and the
  684. next server tried. Normally the stacktrace is logged but this is
  685. suppressed if the exception is an InvalidResponseError.
  686. failover_errcodes: Error codes (specific to this endpoint) which should
  687. cause a failover when received as part of an HTTP 400 error.
  688. failover_on_unknown_endpoint: if True, we will try other servers if it looks
  689. like a server doesn't support the endpoint. This is typically useful
  690. if the endpoint in question is new or experimental.
  691. Returns:
  692. The result of callback, if it succeeds
  693. Raises:
  694. SynapseError if the chosen remote server returns a 300/400 code, or
  695. no servers were reachable.
  696. """
  697. if failover_errcodes is None:
  698. failover_errcodes = ()
  699. if not destinations:
  700. # Give a bit of a clearer message if no servers were specified at all.
  701. raise SynapseError(
  702. 502, f"Failed to {description} via any server: No servers specified."
  703. )
  704. for destination in destinations:
  705. # We don't want to ask our own server for information we don't have
  706. if destination == self.server_name:
  707. continue
  708. try:
  709. return await callback(destination)
  710. except (
  711. RequestSendFailed,
  712. InvalidResponseError,
  713. ) as e:
  714. logger.warning("Failed to %s via %s: %s", description, destination, e)
  715. # Skip to the next homeserver in the list to try.
  716. continue
  717. except NotRetryingDestination as e:
  718. logger.info("%s: %s", description, e)
  719. continue
  720. except FederationDeniedError:
  721. logger.info(
  722. "%s: Not attempting to %s from %s because the homeserver is not on our federation whitelist",
  723. description,
  724. description,
  725. destination,
  726. )
  727. continue
  728. except UnsupportedRoomVersionError:
  729. raise
  730. except HttpResponseException as e:
  731. synapse_error = e.to_synapse_error()
  732. failover = False
  733. # Failover should occur:
  734. #
  735. # * On internal server errors.
  736. # * If the destination responds that it cannot complete the request.
  737. # * If the destination doesn't implemented the endpoint for some reason.
  738. if 500 <= e.code < 600:
  739. failover = True
  740. elif e.code == 400 and synapse_error.errcode in failover_errcodes:
  741. failover = True
  742. elif failover_on_unknown_endpoint and self._is_unknown_endpoint(
  743. e, synapse_error
  744. ):
  745. failover = True
  746. if not failover:
  747. raise synapse_error from e
  748. logger.warning(
  749. "Failed to %s via %s: %i %s",
  750. description,
  751. destination,
  752. e.code,
  753. e.args[0],
  754. )
  755. except Exception:
  756. logger.warning(
  757. "Failed to %s via %s", description, destination, exc_info=True
  758. )
  759. raise SynapseError(502, f"Failed to {description} via any server")
  760. async def make_membership_event(
  761. self,
  762. destinations: Iterable[str],
  763. room_id: str,
  764. user_id: str,
  765. membership: str,
  766. content: dict,
  767. params: Optional[Mapping[str, Union[str, Iterable[str]]]],
  768. ) -> Tuple[str, EventBase, RoomVersion]:
  769. """
  770. Creates an m.room.member event, with context, without participating in the room.
  771. Does so by asking one of the already participating servers to create an
  772. event with proper context.
  773. Returns a fully signed and hashed event.
  774. Note that this does not append any events to any graphs.
  775. Args:
  776. destinations: Candidate homeservers which are probably
  777. participating in the room.
  778. room_id: The room in which the event will happen.
  779. user_id: The user whose membership is being evented.
  780. membership: The "membership" property of the event. Must be one of
  781. "join" or "leave".
  782. content: Any additional data to put into the content field of the
  783. event.
  784. params: Query parameters to include in the request.
  785. Returns:
  786. `(origin, event, room_version)` where origin is the remote
  787. homeserver which generated the event, and room_version is the
  788. version of the room.
  789. Raises:
  790. UnsupportedRoomVersionError: if remote responds with
  791. a room version we don't understand.
  792. SynapseError: if the chosen remote server returns a 300/400 code, or
  793. no servers successfully handle the request.
  794. """
  795. valid_memberships = {Membership.JOIN, Membership.LEAVE, Membership.KNOCK}
  796. if membership not in valid_memberships:
  797. raise RuntimeError(
  798. "make_membership_event called with membership='%s', must be one of %s"
  799. % (membership, ",".join(valid_memberships))
  800. )
  801. async def send_request(destination: str) -> Tuple[str, EventBase, RoomVersion]:
  802. ret = await self.transport_layer.make_membership_event(
  803. destination, room_id, user_id, membership, params
  804. )
  805. # Note: If not supplied, the room version may be either v1 or v2,
  806. # however either way the event format version will be v1.
  807. room_version_id = ret.get("room_version", RoomVersions.V1.identifier)
  808. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  809. if not room_version:
  810. raise UnsupportedRoomVersionError()
  811. if not room_version.msc2403_knocking and membership == Membership.KNOCK:
  812. raise SynapseError(
  813. 400,
  814. "This room version does not support knocking",
  815. errcode=Codes.FORBIDDEN,
  816. )
  817. pdu_dict = ret.get("event", None)
  818. if not isinstance(pdu_dict, dict):
  819. raise InvalidResponseError("Bad 'event' field in response")
  820. logger.debug("Got response to make_%s: %s", membership, pdu_dict)
  821. pdu_dict["content"].update(content)
  822. # The protoevent received over the JSON wire may not have all
  823. # the required fields. Lets just gloss over that because
  824. # there's some we never care about
  825. ev = builder.create_local_event_from_event_dict(
  826. self._clock,
  827. self.hostname,
  828. self.signing_key,
  829. room_version=room_version,
  830. event_dict=pdu_dict,
  831. )
  832. return destination, ev, room_version
  833. # MSC3083 defines additional error codes for room joins. Unfortunately
  834. # we do not yet know the room version, assume these will only be returned
  835. # by valid room versions.
  836. failover_errcodes = (
  837. (Codes.UNABLE_AUTHORISE_JOIN, Codes.UNABLE_TO_GRANT_JOIN)
  838. if membership == Membership.JOIN
  839. else None
  840. )
  841. return await self._try_destination_list(
  842. "make_" + membership,
  843. destinations,
  844. send_request,
  845. failover_errcodes=failover_errcodes,
  846. )
  847. async def send_join(
  848. self,
  849. destinations: Iterable[str],
  850. pdu: EventBase,
  851. room_version: RoomVersion,
  852. partial_state: bool = True,
  853. ) -> SendJoinResult:
  854. """Sends a join event to one of a list of homeservers.
  855. Doing so will cause the remote server to add the event to the graph,
  856. and send the event out to the rest of the federation.
  857. Args:
  858. destinations: Candidate homeservers which are probably
  859. participating in the room.
  860. pdu: event to be sent
  861. room_version: the version of the room (according to the server that
  862. did the make_join)
  863. partial_state: whether to ask the remote server to omit membership state
  864. events from the response. If the remote server complies,
  865. `partial_state` in the send join result will be set. Defaults to
  866. `True`.
  867. Returns:
  868. The result of the send join request.
  869. Raises:
  870. SynapseError: if the chosen remote server returns a 300/400 code, or
  871. no servers successfully handle the request.
  872. """
  873. async def send_request(destination: str) -> SendJoinResult:
  874. response = await self._do_send_join(
  875. room_version, destination, pdu, omit_members=partial_state
  876. )
  877. # If an event was returned (and expected to be returned):
  878. #
  879. # * Ensure it has the same event ID (note that the event ID is a hash
  880. # of the event fields for versions which support MSC3083).
  881. # * Ensure the signatures are good.
  882. #
  883. # Otherwise, fallback to the provided event.
  884. if room_version.msc3083_join_rules and response.event:
  885. event = response.event
  886. valid_pdu = await self._check_sigs_and_hash_and_fetch_one(
  887. pdu=event,
  888. origin=destination,
  889. room_version=room_version,
  890. )
  891. if valid_pdu is None or event.event_id != pdu.event_id:
  892. raise InvalidResponseError("Returned an invalid join event")
  893. else:
  894. event = pdu
  895. state = response.state
  896. auth_chain = response.auth_events
  897. create_event = None
  898. for e in state:
  899. if (e.type, e.state_key) == (EventTypes.Create, ""):
  900. create_event = e
  901. break
  902. if create_event is None:
  903. # If the state doesn't have a create event then the room is
  904. # invalid, and it would fail auth checks anyway.
  905. raise InvalidResponseError("No create event in state")
  906. # the room version should be sane.
  907. create_room_version = create_event.content.get(
  908. "room_version", RoomVersions.V1.identifier
  909. )
  910. if create_room_version != room_version.identifier:
  911. # either the server that fulfilled the make_join, or the server that is
  912. # handling the send_join, is lying.
  913. raise InvalidResponseError(
  914. "Unexpected room version %s in create event"
  915. % (create_room_version,)
  916. )
  917. logger.info(
  918. "Processing from send_join %d events", len(state) + len(auth_chain)
  919. )
  920. # We now go and check the signatures and hashes for the event. Note
  921. # that we limit how many events we process at a time to keep the
  922. # memory overhead from exploding.
  923. valid_pdus_map: Dict[str, EventBase] = {}
  924. async def _execute(pdu: EventBase) -> None:
  925. valid_pdu = await self._check_sigs_and_hash_and_fetch_one(
  926. pdu=pdu,
  927. origin=destination,
  928. room_version=room_version,
  929. )
  930. if valid_pdu:
  931. valid_pdus_map[valid_pdu.event_id] = valid_pdu
  932. await concurrently_execute(
  933. _execute, itertools.chain(state, auth_chain), 10000
  934. )
  935. # NB: We *need* to copy to ensure that we don't have multiple
  936. # references being passed on, as that causes... issues.
  937. signed_state = [
  938. copy.copy(valid_pdus_map[p.event_id])
  939. for p in state
  940. if p.event_id in valid_pdus_map
  941. ]
  942. signed_auth = [
  943. valid_pdus_map[p.event_id]
  944. for p in auth_chain
  945. if p.event_id in valid_pdus_map
  946. ]
  947. # NB: We *need* to copy to ensure that we don't have multiple
  948. # references being passed on, as that causes... issues.
  949. for s in signed_state:
  950. s.internal_metadata = copy.deepcopy(s.internal_metadata)
  951. # double-check that the auth chain doesn't include a different create event
  952. auth_chain_create_events = [
  953. e.event_id
  954. for e in signed_auth
  955. if (e.type, e.state_key) == (EventTypes.Create, "")
  956. ]
  957. if auth_chain_create_events and auth_chain_create_events != [
  958. create_event.event_id
  959. ]:
  960. raise InvalidResponseError(
  961. "Unexpected create event(s) in auth chain: %s"
  962. % (auth_chain_create_events,)
  963. )
  964. if response.members_omitted and not response.servers_in_room:
  965. raise InvalidResponseError(
  966. "members_omitted was set, but no servers were listed in the room"
  967. )
  968. if response.members_omitted and not partial_state:
  969. raise InvalidResponseError(
  970. "members_omitted was set, but we asked for full state"
  971. )
  972. return SendJoinResult(
  973. event=event,
  974. state=signed_state,
  975. auth_chain=signed_auth,
  976. origin=destination,
  977. partial_state=response.members_omitted,
  978. servers_in_room=response.servers_in_room or [],
  979. )
  980. # MSC3083 defines additional error codes for room joins.
  981. failover_errcodes = None
  982. if room_version.msc3083_join_rules:
  983. failover_errcodes = (
  984. Codes.UNABLE_AUTHORISE_JOIN,
  985. Codes.UNABLE_TO_GRANT_JOIN,
  986. )
  987. # If the join is being authorised via allow rules, we need to send
  988. # the /send_join back to the same server that was originally used
  989. # with /make_join.
  990. if EventContentFields.AUTHORISING_USER in pdu.content:
  991. destinations = [
  992. get_domain_from_id(pdu.content[EventContentFields.AUTHORISING_USER])
  993. ]
  994. return await self._try_destination_list(
  995. "send_join", destinations, send_request, failover_errcodes=failover_errcodes
  996. )
  997. async def _do_send_join(
  998. self,
  999. room_version: RoomVersion,
  1000. destination: str,
  1001. pdu: EventBase,
  1002. omit_members: bool,
  1003. ) -> SendJoinResponse:
  1004. time_now = self._clock.time_msec()
  1005. try:
  1006. return await self.transport_layer.send_join_v2(
  1007. room_version=room_version,
  1008. destination=destination,
  1009. room_id=pdu.room_id,
  1010. event_id=pdu.event_id,
  1011. content=pdu.get_pdu_json(time_now),
  1012. omit_members=omit_members,
  1013. )
  1014. except HttpResponseException as e:
  1015. # If an error is received that is due to an unrecognised endpoint,
  1016. # fallback to the v1 endpoint. Otherwise, consider it a legitimate error
  1017. # and raise.
  1018. if not self._is_unknown_endpoint(e):
  1019. raise
  1020. logger.debug("Couldn't send_join with the v2 API, falling back to the v1 API")
  1021. return await self.transport_layer.send_join_v1(
  1022. room_version=room_version,
  1023. destination=destination,
  1024. room_id=pdu.room_id,
  1025. event_id=pdu.event_id,
  1026. content=pdu.get_pdu_json(time_now),
  1027. )
  1028. async def send_invite(
  1029. self,
  1030. destination: str,
  1031. room_id: str,
  1032. event_id: str,
  1033. pdu: EventBase,
  1034. ) -> EventBase:
  1035. room_version = await self.store.get_room_version(room_id)
  1036. content = await self._do_send_invite(destination, pdu, room_version)
  1037. pdu_dict = content["event"]
  1038. logger.debug("Got response to send_invite: %s", pdu_dict)
  1039. pdu = event_from_pdu_json(pdu_dict, room_version)
  1040. # Check signatures are correct.
  1041. try:
  1042. pdu = await self._check_sigs_and_hash(room_version, pdu)
  1043. except InvalidEventSignatureError as e:
  1044. errmsg = f"event id {pdu.event_id}: {e}"
  1045. logger.warning("%s", errmsg)
  1046. raise SynapseError(403, errmsg, Codes.FORBIDDEN)
  1047. # FIXME: We should handle signature failures more gracefully.
  1048. return pdu
  1049. async def _do_send_invite(
  1050. self, destination: str, pdu: EventBase, room_version: RoomVersion
  1051. ) -> JsonDict:
  1052. """Actually sends the invite, first trying v2 API and falling back to
  1053. v1 API if necessary.
  1054. Returns:
  1055. The event as a dict as returned by the remote server
  1056. Raises:
  1057. SynapseError: if the remote server returns an error or if the server
  1058. only supports the v1 endpoint and a room version other than "1"
  1059. or "2" is requested.
  1060. """
  1061. time_now = self._clock.time_msec()
  1062. try:
  1063. return await self.transport_layer.send_invite_v2(
  1064. destination=destination,
  1065. room_id=pdu.room_id,
  1066. event_id=pdu.event_id,
  1067. content={
  1068. "event": pdu.get_pdu_json(time_now),
  1069. "room_version": room_version.identifier,
  1070. "invite_room_state": pdu.unsigned.get("invite_room_state", []),
  1071. },
  1072. )
  1073. except HttpResponseException as e:
  1074. # If an error is received that is due to an unrecognised endpoint,
  1075. # fallback to the v1 endpoint if the room uses old-style event IDs.
  1076. # Otherwise, consider it a legitimate error and raise.
  1077. err = e.to_synapse_error()
  1078. if self._is_unknown_endpoint(e, err):
  1079. if room_version.event_format != EventFormatVersions.ROOM_V1_V2:
  1080. raise SynapseError(
  1081. 400,
  1082. "User's homeserver does not support this room version",
  1083. Codes.UNSUPPORTED_ROOM_VERSION,
  1084. )
  1085. else:
  1086. raise err
  1087. # Didn't work, try v1 API.
  1088. # Note the v1 API returns a tuple of `(200, content)`
  1089. _, content = await self.transport_layer.send_invite_v1(
  1090. destination=destination,
  1091. room_id=pdu.room_id,
  1092. event_id=pdu.event_id,
  1093. content=pdu.get_pdu_json(time_now),
  1094. )
  1095. return content
  1096. async def send_leave(self, destinations: Iterable[str], pdu: EventBase) -> None:
  1097. """Sends a leave event to one of a list of homeservers.
  1098. Doing so will cause the remote server to add the event to the graph,
  1099. and send the event out to the rest of the federation.
  1100. This is mostly useful to reject received invites.
  1101. Args:
  1102. destinations: Candidate homeservers which are probably
  1103. participating in the room.
  1104. pdu: event to be sent
  1105. Raises:
  1106. SynapseError: if the chosen remote server returns a 300/400 code, or
  1107. no servers successfully handle the request.
  1108. """
  1109. async def send_request(destination: str) -> None:
  1110. content = await self._do_send_leave(destination, pdu)
  1111. logger.debug("Got content: %s", content)
  1112. return await self._try_destination_list(
  1113. "send_leave", destinations, send_request
  1114. )
  1115. async def _do_send_leave(self, destination: str, pdu: EventBase) -> JsonDict:
  1116. time_now = self._clock.time_msec()
  1117. try:
  1118. return await self.transport_layer.send_leave_v2(
  1119. destination=destination,
  1120. room_id=pdu.room_id,
  1121. event_id=pdu.event_id,
  1122. content=pdu.get_pdu_json(time_now),
  1123. )
  1124. except HttpResponseException as e:
  1125. # If an error is received that is due to an unrecognised endpoint,
  1126. # fallback to the v1 endpoint. Otherwise, consider it a legitimate error
  1127. # and raise.
  1128. if not self._is_unknown_endpoint(e):
  1129. raise
  1130. logger.debug("Couldn't send_leave with the v2 API, falling back to the v1 API")
  1131. resp = await self.transport_layer.send_leave_v1(
  1132. destination=destination,
  1133. room_id=pdu.room_id,
  1134. event_id=pdu.event_id,
  1135. content=pdu.get_pdu_json(time_now),
  1136. )
  1137. # We expect the v1 API to respond with [200, content], so we only return the
  1138. # content.
  1139. return resp[1]
  1140. async def send_knock(self, destinations: List[str], pdu: EventBase) -> JsonDict:
  1141. """Attempts to send a knock event to a given list of servers. Iterates
  1142. through the list until one attempt succeeds.
  1143. Doing so will cause the remote server to add the event to the graph,
  1144. and send the event out to the rest of the federation.
  1145. Args:
  1146. destinations: A list of candidate homeservers which are likely to be
  1147. participating in the room.
  1148. pdu: The event to be sent.
  1149. Returns:
  1150. The remote homeserver return some state from the room. The response
  1151. dictionary is in the form:
  1152. {"knock_state_events": [<state event dict>, ...]}
  1153. The list of state events may be empty.
  1154. Raises:
  1155. SynapseError: If the chosen remote server returns a 3xx/4xx code.
  1156. RuntimeError: If no servers were reachable.
  1157. """
  1158. async def send_request(destination: str) -> JsonDict:
  1159. return await self._do_send_knock(destination, pdu)
  1160. return await self._try_destination_list(
  1161. "send_knock", destinations, send_request
  1162. )
  1163. async def _do_send_knock(self, destination: str, pdu: EventBase) -> JsonDict:
  1164. """Send a knock event to a remote homeserver.
  1165. Args:
  1166. destination: The homeserver to send to.
  1167. pdu: The event to send.
  1168. Returns:
  1169. The remote homeserver can optionally return some state from the room. The response
  1170. dictionary is in the form:
  1171. {"knock_state_events": [<state event dict>, ...]}
  1172. The list of state events may be empty.
  1173. """
  1174. time_now = self._clock.time_msec()
  1175. return await self.transport_layer.send_knock_v1(
  1176. destination=destination,
  1177. room_id=pdu.room_id,
  1178. event_id=pdu.event_id,
  1179. content=pdu.get_pdu_json(time_now),
  1180. )
  1181. async def get_public_rooms(
  1182. self,
  1183. remote_server: str,
  1184. limit: Optional[int] = None,
  1185. since_token: Optional[str] = None,
  1186. search_filter: Optional[Dict] = None,
  1187. include_all_networks: bool = False,
  1188. third_party_instance_id: Optional[str] = None,
  1189. ) -> JsonDict:
  1190. """Get the list of public rooms from a remote homeserver
  1191. Args:
  1192. remote_server: The name of the remote server
  1193. limit: Maximum amount of rooms to return
  1194. since_token: Used for result pagination
  1195. search_filter: A filter dictionary to send the remote homeserver
  1196. and filter the result set
  1197. include_all_networks: Whether to include results from all third party instances
  1198. third_party_instance_id: Whether to only include results from a specific third
  1199. party instance
  1200. Returns:
  1201. The response from the remote server.
  1202. Raises:
  1203. HttpResponseException / RequestSendFailed: There was an exception
  1204. returned from the remote server
  1205. SynapseException: M_FORBIDDEN when the remote server has disallowed publicRoom
  1206. requests over federation
  1207. """
  1208. return await self.transport_layer.get_public_rooms(
  1209. remote_server,
  1210. limit,
  1211. since_token,
  1212. search_filter,
  1213. include_all_networks=include_all_networks,
  1214. third_party_instance_id=third_party_instance_id,
  1215. )
  1216. async def get_missing_events(
  1217. self,
  1218. destination: str,
  1219. room_id: str,
  1220. earliest_events_ids: Iterable[str],
  1221. latest_events: Iterable[EventBase],
  1222. limit: int,
  1223. min_depth: int,
  1224. timeout: int,
  1225. ) -> List[EventBase]:
  1226. """Tries to fetch events we are missing. This is called when we receive
  1227. an event without having received all of its ancestors.
  1228. Args:
  1229. destination
  1230. room_id
  1231. earliest_events_ids: List of event ids. Effectively the
  1232. events we expected to receive, but haven't. `get_missing_events`
  1233. should only return events that didn't happen before these.
  1234. latest_events: List of events we have received that we don't
  1235. have all previous events for.
  1236. limit: Maximum number of events to return.
  1237. min_depth: Minimum depth of events to return.
  1238. timeout: Max time to wait in ms
  1239. """
  1240. try:
  1241. content = await self.transport_layer.get_missing_events(
  1242. destination=destination,
  1243. room_id=room_id,
  1244. earliest_events=earliest_events_ids,
  1245. latest_events=[e.event_id for e in latest_events],
  1246. limit=limit,
  1247. min_depth=min_depth,
  1248. timeout=timeout,
  1249. )
  1250. room_version = await self.store.get_room_version(room_id)
  1251. events = [
  1252. event_from_pdu_json(e, room_version) for e in content.get("events", [])
  1253. ]
  1254. signed_events = await self._check_sigs_and_hash_for_pulled_events_and_fetch(
  1255. destination, events, room_version=room_version
  1256. )
  1257. except HttpResponseException as e:
  1258. if not e.code == 400:
  1259. raise
  1260. # We are probably hitting an old server that doesn't support
  1261. # get_missing_events
  1262. signed_events = []
  1263. return signed_events
  1264. async def forward_third_party_invite(
  1265. self, destinations: Iterable[str], room_id: str, event_dict: JsonDict
  1266. ) -> None:
  1267. for destination in destinations:
  1268. if destination == self.server_name:
  1269. continue
  1270. try:
  1271. await self.transport_layer.exchange_third_party_invite(
  1272. destination=destination, room_id=room_id, event_dict=event_dict
  1273. )
  1274. return
  1275. except CodeMessageException:
  1276. raise
  1277. except Exception as e:
  1278. logger.exception(
  1279. "Failed to send_third_party_invite via %s: %s", destination, str(e)
  1280. )
  1281. raise RuntimeError("Failed to send to any server.")
  1282. async def get_room_complexity(
  1283. self, destination: str, room_id: str
  1284. ) -> Optional[JsonDict]:
  1285. """
  1286. Fetch the complexity of a remote room from another server.
  1287. Args:
  1288. destination: The remote server
  1289. room_id: The room ID to ask about.
  1290. Returns:
  1291. Dict contains the complexity metric versions, while None means we
  1292. could not fetch the complexity.
  1293. """
  1294. try:
  1295. return await self.transport_layer.get_room_complexity(
  1296. destination=destination, room_id=room_id
  1297. )
  1298. except CodeMessageException as e:
  1299. # We didn't manage to get it -- probably a 404. We are okay if other
  1300. # servers don't give it to us.
  1301. logger.debug(
  1302. "Failed to fetch room complexity via %s for %s, got a %d",
  1303. destination,
  1304. room_id,
  1305. e.code,
  1306. )
  1307. except Exception:
  1308. logger.exception(
  1309. "Failed to fetch room complexity via %s for %s", destination, room_id
  1310. )
  1311. # If we don't manage to find it, return None. It's not an error if a
  1312. # server doesn't give it to us.
  1313. return None
  1314. async def get_room_hierarchy(
  1315. self,
  1316. destinations: Iterable[str],
  1317. room_id: str,
  1318. suggested_only: bool,
  1319. ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]:
  1320. """
  1321. Call other servers to get a hierarchy of the given room.
  1322. Performs simple data validates and parsing of the response.
  1323. Args:
  1324. destinations: The remote servers. We will try them in turn, omitting any
  1325. that have been blacklisted.
  1326. room_id: ID of the space to be queried
  1327. suggested_only: If true, ask the remote server to only return children
  1328. with the "suggested" flag set
  1329. Returns:
  1330. A tuple of:
  1331. The room as a JSON dictionary, without a "children_state" key.
  1332. A list of `m.space.child` state events.
  1333. A list of children rooms, as JSON dictionaries.
  1334. A list of inaccessible children room IDs.
  1335. Raises:
  1336. SynapseError if we were unable to get a valid summary from any of the
  1337. remote servers
  1338. """
  1339. cached_result = self._get_room_hierarchy_cache.get((room_id, suggested_only))
  1340. if cached_result:
  1341. return cached_result
  1342. async def send_request(
  1343. destination: str,
  1344. ) -> Tuple[JsonDict, Sequence[JsonDict], Sequence[JsonDict], Sequence[str]]:
  1345. try:
  1346. res = await self.transport_layer.get_room_hierarchy(
  1347. destination=destination,
  1348. room_id=room_id,
  1349. suggested_only=suggested_only,
  1350. )
  1351. except HttpResponseException as e:
  1352. # If an error is received that is due to an unrecognised endpoint,
  1353. # fallback to the unstable endpoint. Otherwise, consider it a
  1354. # legitimate error and raise.
  1355. if not self._is_unknown_endpoint(e):
  1356. raise
  1357. logger.debug(
  1358. "Couldn't fetch room hierarchy with the v1 API, falling back to the unstable API"
  1359. )
  1360. res = await self.transport_layer.get_room_hierarchy_unstable(
  1361. destination=destination,
  1362. room_id=room_id,
  1363. suggested_only=suggested_only,
  1364. )
  1365. room = res.get("room")
  1366. if not isinstance(room, dict):
  1367. raise InvalidResponseError("'room' must be a dict")
  1368. if room.get("room_id") != room_id:
  1369. raise InvalidResponseError("wrong room returned in hierarchy response")
  1370. # Validate children_state of the room.
  1371. children_state = room.pop("children_state", [])
  1372. if not isinstance(children_state, list):
  1373. raise InvalidResponseError("'room.children_state' must be a list")
  1374. if any(not isinstance(e, dict) for e in children_state):
  1375. raise InvalidResponseError("Invalid event in 'children_state' list")
  1376. try:
  1377. for child_state in children_state:
  1378. _validate_hierarchy_event(child_state)
  1379. except ValueError as e:
  1380. raise InvalidResponseError(str(e))
  1381. # Validate the children rooms.
  1382. children = res.get("children", [])
  1383. if not isinstance(children, list):
  1384. raise InvalidResponseError("'children' must be a list")
  1385. if any(not isinstance(r, dict) for r in children):
  1386. raise InvalidResponseError("Invalid room in 'children' list")
  1387. # Validate the inaccessible children.
  1388. inaccessible_children = res.get("inaccessible_children", [])
  1389. if not isinstance(inaccessible_children, list):
  1390. raise InvalidResponseError("'inaccessible_children' must be a list")
  1391. if any(not isinstance(r, str) for r in inaccessible_children):
  1392. raise InvalidResponseError(
  1393. "Invalid room ID in 'inaccessible_children' list"
  1394. )
  1395. return room, children_state, children, inaccessible_children
  1396. result = await self._try_destination_list(
  1397. "fetch room hierarchy",
  1398. destinations,
  1399. send_request,
  1400. failover_on_unknown_endpoint=True,
  1401. )
  1402. # Cache the result to avoid fetching data over federation every time.
  1403. self._get_room_hierarchy_cache[(room_id, suggested_only)] = result
  1404. return result
  1405. async def timestamp_to_event(
  1406. self, *, destinations: List[str], room_id: str, timestamp: int, direction: str
  1407. ) -> Optional["TimestampToEventResponse"]:
  1408. """
  1409. Calls each remote federating server from `destinations` asking for their closest
  1410. event to the given timestamp in the given direction until we get a response.
  1411. Also validates the response to always return the expected keys or raises an
  1412. error.
  1413. Args:
  1414. destinations: The domains of homeservers to try fetching from
  1415. room_id: Room to fetch the event from
  1416. timestamp: The point in time (inclusive) we should navigate from in
  1417. the given direction to find the closest event.
  1418. direction: ["f"|"b"] to indicate whether we should navigate forward
  1419. or backward from the given timestamp to find the closest event.
  1420. Returns:
  1421. A parsed TimestampToEventResponse including the closest event_id
  1422. and origin_server_ts or None if no destination has a response.
  1423. """
  1424. async def _timestamp_to_event_from_destination(
  1425. destination: str,
  1426. ) -> TimestampToEventResponse:
  1427. return await self._timestamp_to_event_from_destination(
  1428. destination, room_id, timestamp, direction
  1429. )
  1430. try:
  1431. # Loop through each homeserver candidate until we get a succesful response
  1432. timestamp_to_event_response = await self._try_destination_list(
  1433. "timestamp_to_event",
  1434. destinations,
  1435. # TODO: The requested timestamp may lie in a part of the
  1436. # event graph that the remote server *also* didn't have,
  1437. # in which case they will have returned another event
  1438. # which may be nowhere near the requested timestamp. In
  1439. # the future, we may need to reconcile that gap and ask
  1440. # other homeservers, and/or extend `/timestamp_to_event`
  1441. # to return events on *both* sides of the timestamp to
  1442. # help reconcile the gap faster.
  1443. _timestamp_to_event_from_destination,
  1444. # Since this endpoint is new, we should try other servers before giving up.
  1445. # We can safely remove this in a year (remove after 2023-11-16).
  1446. failover_on_unknown_endpoint=True,
  1447. )
  1448. return timestamp_to_event_response
  1449. except SynapseError as e:
  1450. logger.warn(
  1451. "timestamp_to_event(room_id=%s, timestamp=%s, direction=%s): encountered error when trying to fetch from destinations: %s",
  1452. room_id,
  1453. timestamp,
  1454. direction,
  1455. e,
  1456. )
  1457. return None
  1458. async def _timestamp_to_event_from_destination(
  1459. self, destination: str, room_id: str, timestamp: int, direction: str
  1460. ) -> "TimestampToEventResponse":
  1461. """
  1462. Calls a remote federating server at `destination` asking for their
  1463. closest event to the given timestamp in the given direction. Also
  1464. validates the response to always return the expected keys or raises an
  1465. error.
  1466. Args:
  1467. destination: Domain name of the remote homeserver
  1468. room_id: Room to fetch the event from
  1469. timestamp: The point in time (inclusive) we should navigate from in
  1470. the given direction to find the closest event.
  1471. direction: ["f"|"b"] to indicate whether we should navigate forward
  1472. or backward from the given timestamp to find the closest event.
  1473. Returns:
  1474. A parsed TimestampToEventResponse including the closest event_id
  1475. and origin_server_ts
  1476. Raises:
  1477. Various exceptions when the request fails
  1478. InvalidResponseError when the response does not have the correct
  1479. keys or wrong types
  1480. """
  1481. remote_response = await self.transport_layer.timestamp_to_event(
  1482. destination, room_id, timestamp, direction
  1483. )
  1484. if not isinstance(remote_response, dict):
  1485. raise InvalidResponseError(
  1486. "Response must be a JSON dictionary but received %r" % remote_response
  1487. )
  1488. try:
  1489. return TimestampToEventResponse.from_json_dict(remote_response)
  1490. except ValueError as e:
  1491. raise InvalidResponseError(str(e))
  1492. async def get_account_status(
  1493. self, destination: str, user_ids: List[str]
  1494. ) -> Tuple[JsonDict, List[str]]:
  1495. """Retrieves account statuses for a given list of users on a given remote
  1496. homeserver.
  1497. If the request fails for any reason, all user IDs for this destination are marked
  1498. as failed.
  1499. Args:
  1500. destination: the destination to contact
  1501. user_ids: the user ID(s) for which to request account status(es)
  1502. Returns:
  1503. The account statuses, as well as the list of user IDs for which it was not
  1504. possible to retrieve a status.
  1505. """
  1506. try:
  1507. res = await self.transport_layer.get_account_status(destination, user_ids)
  1508. except Exception:
  1509. # If the query failed for any reason, mark all the users as failed.
  1510. return {}, user_ids
  1511. statuses = res.get("account_statuses", {})
  1512. failures = res.get("failures", [])
  1513. if not isinstance(statuses, dict) or not isinstance(failures, list):
  1514. # Make sure we're not feeding back malformed data back to the caller.
  1515. logger.warning(
  1516. "Destination %s responded with malformed data to account_status query",
  1517. destination,
  1518. )
  1519. return {}, user_ids
  1520. for user_id in user_ids:
  1521. # Any account whose status is missing is a user we failed to receive the
  1522. # status of.
  1523. if user_id not in statuses and user_id not in failures:
  1524. failures.append(user_id)
  1525. # Filter out any user ID that doesn't belong to the remote server that sent its
  1526. # status (or failure).
  1527. def filter_user_id(user_id: str) -> bool:
  1528. try:
  1529. return UserID.from_string(user_id).domain == destination
  1530. except SynapseError:
  1531. # If the user ID doesn't parse, ignore it.
  1532. return False
  1533. filtered_statuses = dict(
  1534. # item is a (key, value) tuple, so item[0] is the user ID.
  1535. filter(lambda item: filter_user_id(item[0]), statuses.items())
  1536. )
  1537. filtered_failures = list(filter(filter_user_id, failures))
  1538. return filtered_statuses, filtered_failures
  1539. @attr.s(frozen=True, slots=True, auto_attribs=True)
  1540. class TimestampToEventResponse:
  1541. """Typed response dictionary for the federation /timestamp_to_event endpoint"""
  1542. event_id: str
  1543. origin_server_ts: int
  1544. # the raw data, including the above keys
  1545. data: JsonDict
  1546. @classmethod
  1547. def from_json_dict(cls, d: JsonDict) -> "TimestampToEventResponse":
  1548. """Parsed response from the federation /timestamp_to_event endpoint
  1549. Args:
  1550. d: JSON object response to be parsed
  1551. Raises:
  1552. ValueError if d does not the correct keys or they are the wrong types
  1553. """
  1554. event_id = d.get("event_id")
  1555. if not isinstance(event_id, str):
  1556. raise ValueError(
  1557. "Invalid response: 'event_id' must be a str but received %r" % event_id
  1558. )
  1559. origin_server_ts = d.get("origin_server_ts")
  1560. if not isinstance(origin_server_ts, int):
  1561. raise ValueError(
  1562. "Invalid response: 'origin_server_ts' must be a int but received %r"
  1563. % origin_server_ts
  1564. )
  1565. return cls(event_id, origin_server_ts, d)
  1566. def _validate_hierarchy_event(d: JsonDict) -> None:
  1567. """Validate an event within the result of a /hierarchy request
  1568. Args:
  1569. d: json object to be parsed
  1570. Raises:
  1571. ValueError if d is not a valid event
  1572. """
  1573. event_type = d.get("type")
  1574. if not isinstance(event_type, str):
  1575. raise ValueError("Invalid event: 'event_type' must be a str")
  1576. state_key = d.get("state_key")
  1577. if not isinstance(state_key, str):
  1578. raise ValueError("Invalid event: 'state_key' must be a str")
  1579. content = d.get("content")
  1580. if not isinstance(content, dict):
  1581. raise ValueError("Invalid event: 'content' must be a dict")
  1582. via = content.get("via")
  1583. if not isinstance(via, list):
  1584. raise ValueError("Invalid event: 'via' must be a list")
  1585. if any(not isinstance(v, str) for v in via):
  1586. raise ValueError("Invalid event: 'via' must be a list of strings")