Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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