You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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