2015-01-26 05:45:24 -05:00
|
|
|
#
|
2023-11-21 15:29:58 -05:00
|
|
|
# This file is licensed under the Affero General Public License (AGPL) version 3.
|
|
|
|
#
|
2024-01-23 06:26:48 -05:00
|
|
|
# Copyright 2019-2021 Matrix.org Federation C.I.C
|
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2023-11-21 15:29:58 -05:00
|
|
|
# Copyright (C) 2023 New Vector, Ltd
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as
|
|
|
|
# published by the Free Software Foundation, either version 3 of the
|
|
|
|
# License, or (at your option) any later version.
|
|
|
|
#
|
|
|
|
# See the GNU Affero General Public License for more details:
|
|
|
|
# <https://www.gnu.org/licenses/agpl-3.0.html>.
|
|
|
|
#
|
|
|
|
# Originally licensed under the Apache License, Version 2.0:
|
|
|
|
# <http://www.apache.org/licenses/LICENSE-2.0>.
|
|
|
|
#
|
|
|
|
# [This file includes modifications made by New Vector Limited]
|
2015-01-26 05:45:24 -05:00
|
|
|
#
|
|
|
|
#
|
2017-12-30 13:40:19 -05:00
|
|
|
import logging
|
2021-01-07 13:07:28 -05:00
|
|
|
import random
|
2020-07-16 10:12:54 -04:00
|
|
|
from typing import (
|
|
|
|
TYPE_CHECKING,
|
|
|
|
Any,
|
|
|
|
Awaitable,
|
|
|
|
Callable,
|
2022-02-12 05:44:16 -05:00
|
|
|
Collection,
|
2020-07-16 10:12:54 -04:00
|
|
|
Dict,
|
|
|
|
List,
|
2023-02-10 18:29:00 -05:00
|
|
|
Mapping,
|
2020-07-16 10:12:54 -04:00
|
|
|
Optional,
|
|
|
|
Tuple,
|
|
|
|
Union,
|
|
|
|
)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-10-01 06:09:12 -04:00
|
|
|
from prometheus_client import Counter, Gauge, Histogram
|
2018-07-09 02:09:20 -04:00
|
|
|
|
2018-07-23 17:13:19 -04:00
|
|
|
from twisted.python import failure
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2023-02-01 16:35:24 -05:00
|
|
|
from synapse.api.constants import (
|
|
|
|
Direction,
|
|
|
|
EduTypes,
|
|
|
|
EventContentFields,
|
|
|
|
EventTypes,
|
|
|
|
Membership,
|
|
|
|
)
|
2018-07-25 17:25:41 -04:00
|
|
|
from synapse.api.errors import (
|
|
|
|
AuthError,
|
2019-02-23 09:31:08 -05:00
|
|
|
Codes,
|
2018-07-25 17:25:41 -04:00
|
|
|
FederationError,
|
|
|
|
IncompatibleRoomVersionError,
|
|
|
|
NotFoundError,
|
2023-02-10 18:31:05 -05:00
|
|
|
PartialStateConflictError,
|
2018-07-25 17:25:41 -04:00
|
|
|
SynapseError,
|
2019-05-21 08:47:25 -04:00
|
|
|
UnsupportedRoomVersionError,
|
2018-07-25 17:25:41 -04:00
|
|
|
)
|
2021-06-29 14:55:22 -04:00
|
|
|
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
|
2021-07-26 12:17:00 -04:00
|
|
|
from synapse.crypto.event_signing import compute_event_signature
|
2020-04-07 15:03:23 -04:00
|
|
|
from synapse.events import EventBase
|
2021-06-24 10:30:49 -04:00
|
|
|
from synapse.events.snapshot import EventContext
|
2022-05-31 18:32:56 -04:00
|
|
|
from synapse.federation.federation_base import (
|
|
|
|
FederationBase,
|
|
|
|
InvalidEventSignatureError,
|
|
|
|
event_from_pdu_json,
|
|
|
|
)
|
2018-03-12 10:07:39 -04:00
|
|
|
from synapse.federation.persistence import TransactionActions
|
2017-12-30 13:40:19 -05:00
|
|
|
from synapse.federation.units import Edu, Transaction
|
2023-08-16 10:19:54 -04:00
|
|
|
from synapse.handlers.worker_lock import NEW_EVENT_DURING_PURGE_LOCK_NAME
|
2020-11-19 05:05:33 -05:00
|
|
|
from synapse.http.servlet import assert_params_in_dict
|
2020-01-14 09:08:35 -05:00
|
|
|
from synapse.logging.context import (
|
|
|
|
make_deferred_yieldable,
|
|
|
|
nested_logging_context,
|
|
|
|
run_in_background,
|
|
|
|
)
|
2022-08-15 14:41:23 -04:00
|
|
|
from synapse.logging.opentracing import (
|
2023-01-31 07:43:20 -05:00
|
|
|
SynapseTags,
|
2022-08-15 14:41:23 -04:00
|
|
|
log_kv,
|
2023-01-31 07:43:20 -05:00
|
|
|
set_tag,
|
2022-08-15 14:41:23 -04:00
|
|
|
start_active_span_from_edu,
|
|
|
|
tag_args,
|
|
|
|
trace,
|
|
|
|
)
|
2021-06-29 14:55:22 -04:00
|
|
|
from synapse.metrics.background_process_metrics import wrap_as_background_process
|
2018-07-26 06:44:22 -04:00
|
|
|
from synapse.replication.http.federation import (
|
|
|
|
ReplicationFederationSendEduRestServlet,
|
|
|
|
ReplicationGetQueryRestServlet,
|
|
|
|
)
|
2021-06-29 14:55:22 -04:00
|
|
|
from synapse.storage.databases.main.lock import Lock
|
2022-11-15 12:35:19 -05:00
|
|
|
from synapse.storage.databases.main.roommember import extract_heroes_from_room_summary
|
|
|
|
from synapse.storage.roommember import MemberSummary
|
2023-10-31 10:32:35 -04:00
|
|
|
from synapse.types import JsonDict, StateMap, UserID, get_domain_from_id
|
2023-03-28 14:26:27 -04:00
|
|
|
from synapse.util import unwrapFirstError
|
2021-12-14 12:35:28 -05:00
|
|
|
from synapse.util.async_helpers import Linearizer, concurrently_execute, gather_results
|
2017-12-30 13:40:19 -05:00
|
|
|
from synapse.util.caches.response_cache import ResponseCache
|
2021-01-20 08:15:14 -05:00
|
|
|
from synapse.util.stringutils import parse_server_name
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from synapse.server import HomeServer
|
|
|
|
|
2017-10-06 11:07:20 -04:00
|
|
|
# when processing incoming transactions, we try to handle multiple rooms in
|
|
|
|
# parallel, up to this limit.
|
|
|
|
TRANSACTION_CONCURRENCY_LIMIT = 10
|
2015-01-26 05:45:24 -05:00
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
received_pdus_counter = Counter("synapse_federation_server_received_pdus", "")
|
2015-03-10 11:29:22 -04:00
|
|
|
|
2018-05-21 20:47:37 -04:00
|
|
|
received_edus_counter = Counter("synapse_federation_server_received_edus", "")
|
2015-03-10 11:29:22 -04:00
|
|
|
|
2018-05-22 17:54:22 -04:00
|
|
|
received_queries_counter = Counter(
|
|
|
|
"synapse_federation_server_received_queries", "", ["type"]
|
|
|
|
)
|
2015-02-24 13:10:44 -05:00
|
|
|
|
2020-06-30 11:58:06 -04:00
|
|
|
pdu_process_time = Histogram(
|
|
|
|
"synapse_federation_server_pdu_process_time",
|
|
|
|
"Time taken to process an event",
|
|
|
|
)
|
|
|
|
|
2021-03-04 11:40:18 -05:00
|
|
|
last_pdu_ts_metric = Gauge(
|
|
|
|
"synapse_federation_last_received_pdu_time",
|
|
|
|
"The timestamp of the last PDU which was successfully received from the given domain",
|
2020-10-01 06:09:12 -04:00
|
|
|
labelnames=("server_name",),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-06-29 14:55:22 -04:00
|
|
|
# The name of the lock to use when process events in a room received over
|
|
|
|
# federation.
|
|
|
|
_INBOUND_EVENT_HANDLING_LOCK_NAME = "federation_inbound_pdu"
|
|
|
|
|
|
|
|
|
2015-02-03 09:58:30 -05:00
|
|
|
class FederationServer(FederationBase):
|
2021-03-08 14:00:07 -05:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
2020-09-18 09:56:44 -04:00
|
|
|
super().__init__(hs)
|
2016-06-15 10:12:59 -04:00
|
|
|
|
2023-05-05 10:06:22 -04:00
|
|
|
self.server_name = hs.hostname
|
2020-10-09 07:24:34 -04:00
|
|
|
self.handler = hs.get_federation_handler()
|
2023-04-17 20:57:40 -04:00
|
|
|
self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
|
2021-08-26 16:41:44 -04:00
|
|
|
self._federation_event_handler = hs.get_federation_event_handler()
|
2019-11-27 16:54:07 -05:00
|
|
|
self.state = hs.get_state_handler()
|
2021-07-01 14:25:37 -04:00
|
|
|
self._event_auth_handler = hs.get_event_auth_handler()
|
2022-07-19 07:45:17 -04:00
|
|
|
self._room_member_handler = hs.get_room_member_handler()
|
2023-03-28 14:26:27 -04:00
|
|
|
self._e2e_keys_handler = hs.get_e2e_keys_handler()
|
2023-07-31 05:58:03 -04:00
|
|
|
self._worker_lock_handler = hs.get_worker_locks_handler()
|
2016-07-21 05:30:12 -04:00
|
|
|
|
2022-06-01 11:02:53 -04:00
|
|
|
self._state_storage_controller = hs.get_storage_controllers().state
|
|
|
|
|
2020-02-07 10:45:39 -05:00
|
|
|
self.device_handler = hs.get_device_handler()
|
2020-10-09 07:24:34 -04:00
|
|
|
|
|
|
|
# Ensure the following handlers are loaded since they register callbacks
|
|
|
|
# with FederationHandlerRegistry.
|
|
|
|
hs.get_directory_handler()
|
|
|
|
|
2018-08-10 09:50:21 -04:00
|
|
|
self._server_linearizer = Linearizer("fed_server")
|
2021-03-12 10:14:55 -05:00
|
|
|
|
|
|
|
# origins that we are currently processing a transaction from.
|
|
|
|
# a dict from origin to txn id.
|
2021-07-15 06:02:43 -04:00
|
|
|
self._active_transactions: Dict[str, str] = {}
|
2016-06-15 10:12:59 -04:00
|
|
|
|
2020-09-18 05:49:29 -04:00
|
|
|
# We cache results for transaction with the same ID
|
2021-07-15 06:02:43 -04:00
|
|
|
self._transaction_resp_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
|
2021-03-08 14:00:07 -05:00
|
|
|
hs.get_clock(), "fed_txn_handler", timeout_ms=30000
|
2021-07-15 06:02:43 -04:00
|
|
|
)
|
2020-09-18 05:49:29 -04:00
|
|
|
|
2018-03-12 10:07:39 -04:00
|
|
|
self.transaction_actions = TransactionActions(self.store)
|
|
|
|
|
2018-03-12 12:17:08 -04:00
|
|
|
self.registry = hs.get_federation_registry()
|
|
|
|
|
2016-07-21 05:30:12 -04:00
|
|
|
# We cache responses to state queries, as they take a while and often
|
|
|
|
# come in waves.
|
2021-07-15 06:02:43 -04:00
|
|
|
self._state_resp_cache: ResponseCache[
|
|
|
|
Tuple[str, Optional[str]]
|
|
|
|
] = ResponseCache(hs.get_clock(), "state_resp", timeout_ms=30000)
|
|
|
|
self._state_ids_resp_cache: ResponseCache[Tuple[str, str]] = ResponseCache(
|
2021-03-08 14:00:07 -05:00
|
|
|
hs.get_clock(), "state_ids_resp", timeout_ms=30000
|
2021-07-15 06:02:43 -04:00
|
|
|
)
|
2016-07-21 05:30:12 -04:00
|
|
|
|
2020-10-01 06:09:12 -04:00
|
|
|
self._federation_metrics_domains = (
|
2021-04-14 14:09:08 -04:00
|
|
|
hs.config.federation.federation_metrics_domains
|
2020-10-01 06:09:12 -04:00
|
|
|
)
|
|
|
|
|
2021-06-09 14:39:51 -04:00
|
|
|
self._room_prejoin_state_types = hs.config.api.room_prejoin_state
|
|
|
|
|
2021-07-06 08:02:37 -04:00
|
|
|
# Whether we have started handling old events in the staging area.
|
|
|
|
self._started_handling_of_staged_events = False
|
|
|
|
|
|
|
|
@wrap_as_background_process("_handle_old_staged_events")
|
|
|
|
async def _handle_old_staged_events(self) -> None:
|
|
|
|
"""Handle old staged events by fetching all rooms that have staged
|
|
|
|
events and start the processing of each of those rooms.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Get all the rooms IDs with staged events.
|
|
|
|
room_ids = await self.store.get_all_rooms_with_staged_incoming_events()
|
|
|
|
|
|
|
|
# We then shuffle them so that if there are multiple instances doing
|
|
|
|
# this work they're less likely to collide.
|
|
|
|
random.shuffle(room_ids)
|
|
|
|
|
|
|
|
for room_id in room_ids:
|
|
|
|
room_version = await self.store.get_room_version(room_id)
|
|
|
|
|
|
|
|
# Try and acquire the processing lock for the room, if we get it start a
|
|
|
|
# background process for handling the events in the room.
|
|
|
|
lock = await self.store.try_acquire_lock(
|
|
|
|
_INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
|
|
|
|
)
|
|
|
|
if lock:
|
|
|
|
logger.info("Handling old staged inbound events in %s", room_id)
|
|
|
|
self._process_incoming_pdus_in_room_inner(
|
|
|
|
room_id,
|
|
|
|
room_version,
|
|
|
|
lock,
|
|
|
|
)
|
|
|
|
|
|
|
|
# We pause a bit so that we don't start handling all rooms at once.
|
|
|
|
await self._clock.sleep(random.uniform(0, 0.1))
|
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_backfill_request(
|
|
|
|
self, origin: str, room_id: str, versions: List[str], limit: int
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._server_linearizer.queue((origin, room_id)):
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2019-10-29 10:05:32 -04:00
|
|
|
pdus = await self.handler.on_backfill_request(
|
2016-06-17 11:43:45 -04:00
|
|
|
origin, room_id, versions, limit
|
|
|
|
)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
res = self._transaction_dict_from_pdus(pdus)
|
2016-06-17 11:43:45 -04:00
|
|
|
|
2019-08-30 11:28:26 -04:00
|
|
|
return 200, res
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2021-12-02 02:02:20 -05:00
|
|
|
async def on_timestamp_to_event_request(
|
2023-02-01 16:35:24 -05:00
|
|
|
self, origin: str, room_id: str, timestamp: int, direction: Direction
|
2021-12-02 02:02:20 -05:00
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
|
|
|
"""When we receive a federated `/timestamp_to_event` request,
|
|
|
|
handle all of the logic for validating and fetching the event.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
origin: The server we received the event from
|
|
|
|
room_id: Room to fetch the event from
|
|
|
|
timestamp: The point in time (inclusive) we should navigate from in
|
|
|
|
the given direction to find the closest event.
|
2023-02-01 16:35:24 -05:00
|
|
|
direction: indicates whether we should navigate forward
|
2021-12-02 02:02:20 -05:00
|
|
|
or backward from the given timestamp to find the closest event.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Tuple indicating the response status code and dictionary response
|
|
|
|
body including `event_id`.
|
|
|
|
"""
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._server_linearizer.queue((origin, room_id)):
|
2021-12-02 02:02:20 -05:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
|
|
|
|
|
|
|
# We only try to fetch data from the local database
|
|
|
|
event_id = await self.store.get_event_id_for_timestamp(
|
|
|
|
room_id, timestamp, direction
|
|
|
|
)
|
|
|
|
if event_id:
|
|
|
|
event = await self.store.get_event(
|
|
|
|
event_id, allow_none=False, allow_rejected=False
|
|
|
|
)
|
|
|
|
|
|
|
|
return 200, {
|
|
|
|
"event_id": event_id,
|
|
|
|
"origin_server_ts": event.origin_server_ts,
|
|
|
|
}
|
|
|
|
|
|
|
|
raise SynapseError(
|
|
|
|
404,
|
|
|
|
"Unable to find event from %s in direction %s" % (timestamp, direction),
|
|
|
|
errcode=Codes.NOT_FOUND,
|
|
|
|
)
|
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_incoming_transaction(
|
2021-08-06 09:39:59 -04:00
|
|
|
self,
|
|
|
|
origin: str,
|
|
|
|
transaction_id: str,
|
|
|
|
destination: str,
|
|
|
|
transaction_data: JsonDict,
|
|
|
|
) -> Tuple[int, JsonDict]:
|
2021-07-06 08:02:37 -04:00
|
|
|
# If we receive a transaction we should make sure that kick off handling
|
|
|
|
# any old events in the staging area.
|
|
|
|
if not self._started_handling_of_staged_events:
|
|
|
|
self._started_handling_of_staged_events = True
|
|
|
|
self._handle_old_staged_events()
|
|
|
|
|
2021-11-08 04:54:47 -05:00
|
|
|
# Start a periodic check for old staged events. This is to handle
|
|
|
|
# the case where locks time out, e.g. if another process gets killed
|
|
|
|
# without dropping its locks.
|
|
|
|
self._clock.looping_call(self._handle_old_staged_events, 60 * 1000)
|
|
|
|
|
2017-10-06 10:18:58 -04:00
|
|
|
# keep this as early as possible to make the calculated origin ts as
|
|
|
|
# accurate as possible.
|
2017-10-06 10:31:58 -04:00
|
|
|
request_time = self._clock.time_msec()
|
2015-03-10 11:29:22 -04:00
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
transaction = Transaction(
|
|
|
|
transaction_id=transaction_id,
|
|
|
|
destination=destination,
|
|
|
|
origin=origin,
|
2022-04-27 09:03:44 -04:00
|
|
|
origin_server_ts=transaction_data.get("origin_server_ts"), # type: ignore[arg-type]
|
|
|
|
pdus=transaction_data.get("pdus"),
|
2021-08-06 09:39:59 -04:00
|
|
|
edus=transaction_data.get("edus"),
|
|
|
|
)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-09-18 05:49:29 -04:00
|
|
|
if not transaction_id:
|
2017-10-06 10:31:58 -04:00
|
|
|
raise Exception("Transaction missing transaction_id")
|
|
|
|
|
2020-09-18 05:49:29 -04:00
|
|
|
logger.debug("[%s] Got transaction", transaction_id)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2021-03-12 10:14:55 -05:00
|
|
|
# Reject malformed transactions early: reject if too many PDUs/EDUs
|
2021-08-06 09:39:59 -04:00
|
|
|
if len(transaction.pdus) > 50 or len(transaction.edus) > 100:
|
2021-03-12 10:14:55 -05:00
|
|
|
logger.info("Transaction PDU or EDU count too large. Returning 400")
|
|
|
|
return 400, {}
|
|
|
|
|
|
|
|
# we only process one transaction from each origin at a time. We need to do
|
|
|
|
# this check here, rather than in _on_incoming_transaction_inner so that we
|
|
|
|
# don't cache the rejection in _transaction_resp_cache (so that if the txn
|
|
|
|
# arrives again later, we can process it).
|
|
|
|
current_transaction = self._active_transactions.get(origin)
|
|
|
|
if current_transaction and current_transaction != transaction_id:
|
|
|
|
logger.warning(
|
|
|
|
"Received another txn %s from %s while still processing %s",
|
|
|
|
transaction_id,
|
|
|
|
origin,
|
|
|
|
current_transaction,
|
|
|
|
)
|
|
|
|
return 429, {
|
|
|
|
"errcode": Codes.UNKNOWN,
|
|
|
|
"error": "Too many concurrent transactions",
|
|
|
|
}
|
|
|
|
|
|
|
|
# CRITICAL SECTION: we must now not await until we populate _active_transactions
|
|
|
|
# in _on_incoming_transaction_inner.
|
|
|
|
|
2020-09-18 05:49:29 -04:00
|
|
|
# We wrap in a ResponseCache so that we de-duplicate retried
|
|
|
|
# transactions.
|
|
|
|
return await self._transaction_resp_cache.wrap(
|
|
|
|
(origin, transaction_id),
|
|
|
|
self._on_incoming_transaction_inner,
|
|
|
|
origin,
|
|
|
|
transaction,
|
|
|
|
request_time,
|
|
|
|
)
|
|
|
|
|
|
|
|
async def _on_incoming_transaction_inner(
|
|
|
|
self, origin: str, transaction: Transaction, request_time: int
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
2021-03-12 10:14:55 -05:00
|
|
|
# CRITICAL SECTION: the first thing we must do (before awaiting) is
|
|
|
|
# add an entry to _active_transactions.
|
|
|
|
assert origin not in self._active_transactions
|
2021-08-06 09:39:59 -04:00
|
|
|
self._active_transactions[origin] = transaction.transaction_id
|
2021-03-12 10:14:55 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
result = await self._handle_incoming_transaction(
|
|
|
|
origin, transaction, request_time
|
|
|
|
)
|
|
|
|
return result
|
|
|
|
finally:
|
|
|
|
del self._active_transactions[origin]
|
2017-10-06 10:31:58 -04:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def _handle_incoming_transaction(
|
|
|
|
self, origin: str, transaction: Transaction, request_time: int
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
2017-10-06 10:31:58 -04:00
|
|
|
"""Process an incoming transaction and return the HTTP response
|
|
|
|
|
|
|
|
Args:
|
2020-04-07 15:03:23 -04:00
|
|
|
origin: the server making the request
|
|
|
|
transaction: incoming transaction
|
|
|
|
request_time: timestamp that the HTTP request arrived at
|
2017-10-06 10:31:58 -04:00
|
|
|
|
|
|
|
Returns:
|
2020-04-07 15:03:23 -04:00
|
|
|
HTTP response code and body
|
2017-10-06 10:31:58 -04:00
|
|
|
"""
|
2021-10-27 12:27:23 -04:00
|
|
|
existing_response = await self.transaction_actions.have_responded(
|
|
|
|
origin, transaction
|
|
|
|
)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2021-10-27 12:27:23 -04:00
|
|
|
if existing_response:
|
2015-01-26 09:33:11 -05:00
|
|
|
logger.debug(
|
2017-01-06 21:13:06 -05:00
|
|
|
"[%s] We've already responded to this request",
|
2021-08-06 09:39:59 -04:00
|
|
|
transaction.transaction_id,
|
2015-01-26 09:33:11 -05:00
|
|
|
)
|
2021-10-27 12:27:23 -04:00
|
|
|
return existing_response
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
logger.debug("[%s] Transaction is new", transaction.transaction_id)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-01-14 09:08:35 -05:00
|
|
|
# We process PDUs and EDUs in parallel. This is important as we don't
|
|
|
|
# want to block things like to device messages from reaching clients
|
|
|
|
# behind the potentially expensive handling of PDUs.
|
|
|
|
pdu_results, _ = await make_deferred_yieldable(
|
2021-12-14 12:35:28 -05:00
|
|
|
gather_results(
|
|
|
|
(
|
2020-01-14 09:08:35 -05:00
|
|
|
run_in_background(
|
|
|
|
self._handle_pdus_in_txn, origin, transaction, request_time
|
|
|
|
),
|
|
|
|
run_in_background(self._handle_edus_in_txn, origin, transaction),
|
2021-12-14 12:35:28 -05:00
|
|
|
),
|
2020-01-14 09:08:35 -05:00
|
|
|
consumeErrors=True,
|
|
|
|
).addErrback(unwrapFirstError)
|
|
|
|
)
|
|
|
|
|
|
|
|
response = {"pdus": pdu_results}
|
|
|
|
|
|
|
|
logger.debug("Returning: %s", str(response))
|
|
|
|
|
|
|
|
await self.transaction_actions.set_response(origin, transaction, 200, response)
|
|
|
|
return 200, response
|
|
|
|
|
|
|
|
async def _handle_pdus_in_txn(
|
|
|
|
self, origin: str, transaction: Transaction, request_time: int
|
|
|
|
) -> Dict[str, dict]:
|
|
|
|
"""Process the PDUs in a received transaction.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
origin: the server making the request
|
|
|
|
transaction: incoming transaction
|
|
|
|
request_time: timestamp that the HTTP request arrived at
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A map from event ID of a processed PDU to any errors we should
|
|
|
|
report back to the sending server.
|
|
|
|
"""
|
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
received_pdus_counter.inc(len(transaction.pdus))
|
2017-10-06 10:18:58 -04:00
|
|
|
|
2018-09-03 20:23:18 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2021-07-15 06:02:43 -04:00
|
|
|
pdus_by_room: Dict[str, List[EventBase]] = {}
|
2017-10-06 10:18:58 -04:00
|
|
|
|
2020-10-01 06:09:12 -04:00
|
|
|
newest_pdu_ts = 0
|
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
for p in transaction.pdus:
|
2020-10-01 06:09:12 -04:00
|
|
|
# FIXME (richardv): I don't think this works:
|
|
|
|
# https://github.com/matrix-org/synapse/issues/8429
|
2017-10-06 10:18:58 -04:00
|
|
|
if "unsigned" in p:
|
|
|
|
unsigned = p["unsigned"]
|
|
|
|
if "age" in unsigned:
|
|
|
|
p["age"] = unsigned["age"]
|
|
|
|
if "age" in p:
|
|
|
|
p["age_ts"] = request_time - int(p["age"])
|
|
|
|
del p["age"]
|
|
|
|
|
2018-11-09 06:28:22 -05:00
|
|
|
# We try and pull out an event ID so that if later checks fail we
|
2018-11-08 07:11:20 -05:00
|
|
|
# can log something sensible. We don't mandate an event ID here in
|
|
|
|
# case future event formats get rid of the key.
|
|
|
|
possible_event_id = p.get("event_id", "<Unknown>")
|
|
|
|
|
|
|
|
# Now we get the room ID so that we can check that we know the
|
|
|
|
# version of the room.
|
|
|
|
room_id = p.get("room_id")
|
|
|
|
if not room_id:
|
|
|
|
logger.info(
|
|
|
|
"Ignoring PDU as does not have a room_id. Event ID: %s",
|
|
|
|
possible_event_id,
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
|
|
|
|
try:
|
2020-01-31 11:50:13 -05:00
|
|
|
room_version = await self.store.get_room_version(room_id)
|
2018-11-08 07:11:20 -05:00
|
|
|
except NotFoundError:
|
2018-11-09 06:28:25 -05:00
|
|
|
logger.info("Ignoring PDU for unknown room_id: %s", room_id)
|
2018-11-08 07:11:20 -05:00
|
|
|
continue
|
2020-01-31 11:50:13 -05:00
|
|
|
except UnsupportedRoomVersionError as e:
|
2019-05-21 08:47:25 -04:00
|
|
|
# this can happen if support for a given room version is withdrawn,
|
|
|
|
# so that we still get events for said room.
|
2020-01-31 11:50:13 -05:00
|
|
|
logger.info("Ignoring PDU: %s", e)
|
2019-05-21 08:47:25 -04:00
|
|
|
continue
|
|
|
|
|
2020-01-31 11:50:13 -05:00
|
|
|
event = event_from_pdu_json(p, room_version)
|
2017-10-06 11:07:20 -04:00
|
|
|
pdus_by_room.setdefault(room_id, []).append(event)
|
2017-10-06 10:18:58 -04:00
|
|
|
|
2020-10-01 06:09:12 -04:00
|
|
|
if event.origin_server_ts > newest_pdu_ts:
|
|
|
|
newest_pdu_ts = event.origin_server_ts
|
|
|
|
|
2017-10-06 10:18:58 -04:00
|
|
|
pdu_results = {}
|
2015-05-08 11:32:18 -04:00
|
|
|
|
2017-10-06 11:07:20 -04:00
|
|
|
# we can process different rooms in parallel (which is useful if they
|
|
|
|
# require callouts to other servers to fetch missing events), but
|
|
|
|
# impose a limit to avoid going too crazy with ram/cpu.
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2021-12-02 11:18:10 -05:00
|
|
|
async def process_pdus_for_room(room_id: str) -> None:
|
2021-03-12 10:08:03 -05:00
|
|
|
with nested_logging_context(room_id):
|
|
|
|
logger.debug("Processing PDUs for %s", room_id)
|
|
|
|
|
|
|
|
try:
|
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
|
|
|
except AuthError as e:
|
|
|
|
logger.warning(
|
|
|
|
"Ignoring PDUs for room %s from banned server", room_id
|
|
|
|
)
|
|
|
|
for pdu in pdus_by_room[room_id]:
|
|
|
|
event_id = pdu.event_id
|
2022-07-27 08:44:40 -04:00
|
|
|
pdu_results[event_id] = e.error_dict(self.hs.config)
|
2021-03-12 10:08:03 -05:00
|
|
|
return
|
|
|
|
|
2018-07-04 10:31:00 -04:00
|
|
|
for pdu in pdus_by_room[room_id]:
|
2021-03-12 10:08:03 -05:00
|
|
|
pdu_results[pdu.event_id] = await process_pdu(pdu)
|
|
|
|
|
|
|
|
async def process_pdu(pdu: EventBase) -> JsonDict:
|
2022-10-19 16:39:43 -04:00
|
|
|
"""
|
|
|
|
Processes a pushed PDU sent to us via a `/send` transaction
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
JsonDict representing a "PDU Processing Result" that will be bundled up
|
|
|
|
with the other processed PDU's in the `/send` transaction and sent back
|
|
|
|
to remote homeserver.
|
|
|
|
"""
|
2021-03-12 10:08:03 -05:00
|
|
|
event_id = pdu.event_id
|
2021-06-30 07:07:16 -04:00
|
|
|
with nested_logging_context(event_id):
|
|
|
|
try:
|
|
|
|
await self._handle_received_pdu(origin, pdu)
|
|
|
|
return {}
|
|
|
|
except FederationError as e:
|
|
|
|
logger.warning("Error handling PDU %s: %s", event_id, e)
|
|
|
|
return {"error": str(e)}
|
|
|
|
except Exception as e:
|
|
|
|
f = failure.Failure()
|
|
|
|
logger.error(
|
|
|
|
"Failed to handle PDU %s",
|
|
|
|
event_id,
|
2023-05-31 07:18:29 -04:00
|
|
|
exc_info=(f.type, f.value, f.getTracebackObject()),
|
2021-06-30 07:07:16 -04:00
|
|
|
)
|
|
|
|
return {"error": str(e)}
|
2017-10-06 11:07:20 -04:00
|
|
|
|
2019-10-29 10:05:32 -04:00
|
|
|
await concurrently_execute(
|
2017-10-06 11:07:20 -04:00
|
|
|
process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT
|
|
|
|
)
|
2015-05-08 11:32:18 -04:00
|
|
|
|
2020-10-01 06:09:12 -04:00
|
|
|
if newest_pdu_ts and origin in self._federation_metrics_domains:
|
2021-03-04 11:40:18 -05:00
|
|
|
last_pdu_ts_metric.labels(server_name=origin).set(newest_pdu_ts / 1000)
|
2020-10-01 06:09:12 -04:00
|
|
|
|
2020-01-14 09:08:35 -05:00
|
|
|
return pdu_results
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
async def _handle_edus_in_txn(self, origin: str, transaction: Transaction) -> None:
|
2020-01-14 09:08:35 -05:00
|
|
|
"""Process the EDUs in a received transaction."""
|
2015-02-17 08:24:13 -05:00
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
async def _process_edu(edu_dict: JsonDict) -> None:
|
2020-01-14 09:08:35 -05:00
|
|
|
received_edus_counter.inc()
|
2017-10-06 10:18:58 -04:00
|
|
|
|
2020-02-07 08:56:38 -05:00
|
|
|
edu = Edu(
|
|
|
|
origin=origin,
|
|
|
|
destination=self.server_name,
|
|
|
|
edu_type=edu_dict["edu_type"],
|
|
|
|
content=edu_dict["content"],
|
|
|
|
)
|
2020-01-14 09:08:35 -05:00
|
|
|
await self.registry.on_edu(edu.edu_type, origin, edu.content)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-01-14 09:08:35 -05:00
|
|
|
await concurrently_execute(
|
|
|
|
_process_edu,
|
2021-08-06 09:39:59 -04:00
|
|
|
transaction.edus,
|
2020-01-14 09:08:35 -05:00
|
|
|
TRANSACTION_CONCURRENCY_LIMIT,
|
|
|
|
)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-11-19 05:05:33 -05:00
|
|
|
async def on_room_state_request(
|
2022-04-19 07:17:29 -04:00
|
|
|
self, origin: str, room_id: str, event_id: str
|
2021-10-22 13:15:41 -04:00
|
|
|
) -> Tuple[int, JsonDict]:
|
2022-09-23 06:47:16 -04:00
|
|
|
await self._event_auth_handler.assert_host_in_room(room_id, origin)
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2018-04-20 06:10:04 -04:00
|
|
|
# we grab the linearizer to protect ourselves from servers which hammer
|
|
|
|
# us. In theory we might already have the response to this query
|
|
|
|
# in the cache so we could return it without waiting for the linearizer
|
|
|
|
# - but that's non-trivial to get right, and anyway somewhat defeats
|
|
|
|
# the point of the linearizer.
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._server_linearizer.queue((origin, room_id)):
|
2022-04-19 07:17:29 -04:00
|
|
|
resp = await self._state_resp_cache.wrap(
|
|
|
|
(room_id, event_id),
|
|
|
|
self._on_context_state_request_compute,
|
|
|
|
room_id,
|
|
|
|
event_id,
|
2018-04-20 06:10:04 -04:00
|
|
|
)
|
2016-07-21 05:30:12 -04:00
|
|
|
|
2019-08-30 11:28:26 -04:00
|
|
|
return 200, resp
|
2015-02-10 10:46:24 -05:00
|
|
|
|
2022-08-15 14:41:23 -04:00
|
|
|
@trace
|
|
|
|
@tag_args
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_state_ids_request(
|
|
|
|
self, origin: str, room_id: str, event_id: str
|
2021-12-02 11:18:10 -05:00
|
|
|
) -> Tuple[int, JsonDict]:
|
2016-08-03 09:47:37 -04:00
|
|
|
if not event_id:
|
|
|
|
raise NotImplementedError("Specify an event")
|
|
|
|
|
2022-09-23 06:47:16 -04:00
|
|
|
await self._event_auth_handler.assert_host_in_room(room_id, origin)
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2020-07-23 13:38:19 -04:00
|
|
|
resp = await self._state_ids_resp_cache.wrap(
|
|
|
|
(room_id, event_id),
|
|
|
|
self._on_state_ids_request_compute,
|
|
|
|
room_id,
|
|
|
|
event_id,
|
|
|
|
)
|
|
|
|
|
|
|
|
return 200, resp
|
|
|
|
|
2022-08-15 14:41:23 -04:00
|
|
|
@trace
|
|
|
|
@tag_args
|
2021-12-02 11:18:10 -05:00
|
|
|
async def _on_state_ids_request_compute(
|
|
|
|
self, room_id: str, event_id: str
|
|
|
|
) -> JsonDict:
|
2019-10-29 10:05:32 -04:00
|
|
|
state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
|
2021-03-10 09:57:59 -05:00
|
|
|
auth_chain_ids = await self.store.get_auth_chain_ids(room_id, state_ids)
|
2022-02-12 05:44:16 -05:00
|
|
|
return {"pdu_ids": state_ids, "auth_chain_ids": list(auth_chain_ids)}
|
2016-08-03 09:47:37 -04:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def _on_context_state_request_compute(
|
2022-04-19 07:17:29 -04:00
|
|
|
self, room_id: str, event_id: str
|
2020-04-07 15:03:23 -04:00
|
|
|
) -> Dict[str, list]:
|
2022-03-21 07:23:32 -04:00
|
|
|
pdus: Collection[EventBase]
|
2022-04-19 07:17:29 -04:00
|
|
|
event_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
|
|
|
|
pdus = await self.store.get_events_as_list(event_ids)
|
2019-11-27 16:54:07 -05:00
|
|
|
|
2021-03-10 09:57:59 -05:00
|
|
|
auth_chain = await self.store.get_auth_chain(
|
|
|
|
room_id, [pdu.event_id for pdu in pdus]
|
|
|
|
)
|
2016-07-21 05:30:12 -04:00
|
|
|
|
2019-07-23 09:00:55 -04:00
|
|
|
return {
|
|
|
|
"pdus": [pdu.get_pdu_json() for pdu in pdus],
|
|
|
|
"auth_chain": [pdu.get_pdu_json() for pdu in auth_chain],
|
|
|
|
}
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_pdu_request(
|
|
|
|
self, origin: str, event_id: str
|
|
|
|
) -> Tuple[int, Union[JsonDict, str]]:
|
2019-10-29 10:05:32 -04:00
|
|
|
pdu = await self.handler.get_persisted_pdu(origin, event_id)
|
2015-01-26 05:45:24 -05:00
|
|
|
|
|
|
|
if pdu:
|
2021-08-06 09:39:59 -04:00
|
|
|
return 200, self._transaction_dict_from_pdus([pdu])
|
2015-01-26 05:45:24 -05:00
|
|
|
else:
|
2019-08-30 11:28:26 -04:00
|
|
|
return 404, ""
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_query_request(
|
|
|
|
self, query_type: str, args: Dict[str, str]
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
2018-05-21 20:47:37 -04:00
|
|
|
received_queries_counter.labels(query_type).inc()
|
2019-10-29 10:05:32 -04:00
|
|
|
resp = await self.registry.on_query(query_type, args)
|
2019-08-30 11:28:26 -04:00
|
|
|
return 200, resp
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_make_join_request(
|
|
|
|
self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
|
|
|
|
) -> Dict[str, Any]:
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
2018-07-25 17:25:41 -04:00
|
|
|
|
2020-01-31 05:06:21 -05:00
|
|
|
room_version = await self.store.get_room_version_id(room_id)
|
2018-07-25 17:25:41 -04:00
|
|
|
if room_version not in supported_versions:
|
2019-10-31 06:23:24 -04:00
|
|
|
logger.warning(
|
|
|
|
"Room version %s not in %s", room_version, supported_versions
|
|
|
|
)
|
2018-07-25 17:25:41 -04:00
|
|
|
raise IncompatibleRoomVersionError(room_version=room_version)
|
|
|
|
|
2022-07-19 07:45:17 -04:00
|
|
|
# Refuse the request if that room has seen too many joins recently.
|
|
|
|
# This is in addition to the HS-level rate limiting applied by
|
|
|
|
# BaseFederationServlet.
|
|
|
|
# type-ignore: mypy doesn't seem able to deduce the type of the limiter(!?)
|
|
|
|
await self._room_member_handler._join_rate_per_room_limiter.ratelimit( # type: ignore[has-type]
|
|
|
|
requester=None,
|
|
|
|
key=room_id,
|
|
|
|
update=False,
|
|
|
|
)
|
2019-10-29 10:05:32 -04:00
|
|
|
pdu = await self.handler.on_make_join_request(origin, room_id, user_id)
|
2021-07-16 10:36:38 -04:00
|
|
|
return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-02-03 08:15:24 -05:00
|
|
|
async def on_invite_request(
|
|
|
|
self, origin: str, content: JsonDict, room_version_id: str
|
2020-04-07 15:03:23 -04:00
|
|
|
) -> Dict[str, Any]:
|
2020-02-03 08:15:24 -05:00
|
|
|
room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
|
|
|
|
if not room_version:
|
2019-02-23 09:31:08 -05:00
|
|
|
raise SynapseError(
|
|
|
|
400,
|
|
|
|
"Homeserver does not support this room version",
|
|
|
|
Codes.UNSUPPORTED_ROOM_VERSION,
|
|
|
|
)
|
|
|
|
|
2020-01-31 11:50:13 -05:00
|
|
|
pdu = event_from_pdu_json(content, room_version)
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, pdu.room_id)
|
2022-05-31 18:32:56 -04:00
|
|
|
try:
|
|
|
|
pdu = await self._check_sigs_and_hash(room_version, pdu)
|
|
|
|
except InvalidEventSignatureError as e:
|
|
|
|
errmsg = f"event id {pdu.event_id}: {e}"
|
|
|
|
logger.warning("%s", errmsg)
|
|
|
|
raise SynapseError(403, errmsg, Codes.FORBIDDEN)
|
2020-01-30 17:13:02 -05:00
|
|
|
ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version)
|
2015-01-26 05:45:24 -05:00
|
|
|
time_now = self._clock.time_msec()
|
2019-07-23 09:00:55 -04:00
|
|
|
return {"event": ret_pdu.get_pdu_json(time_now)}
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_send_join_request(
|
2022-02-12 05:44:16 -05:00
|
|
|
self,
|
|
|
|
origin: str,
|
|
|
|
content: JsonDict,
|
|
|
|
room_id: str,
|
|
|
|
caller_supports_partial_state: bool = False,
|
2020-04-07 15:03:23 -04:00
|
|
|
) -> Dict[str, Any]:
|
2023-01-31 07:43:20 -05:00
|
|
|
set_tag(
|
|
|
|
SynapseTags.SEND_JOIN_RESPONSE_IS_PARTIAL_STATE,
|
|
|
|
caller_supports_partial_state,
|
|
|
|
)
|
2022-07-19 07:45:17 -04:00
|
|
|
await self._room_member_handler._join_rate_per_room_limiter.ratelimit( # type: ignore[has-type]
|
|
|
|
requester=None,
|
|
|
|
key=room_id,
|
|
|
|
update=False,
|
|
|
|
)
|
|
|
|
|
2021-07-26 12:17:00 -04:00
|
|
|
event, context = await self._on_send_membership_event(
|
2021-06-24 10:30:49 -04:00
|
|
|
origin, content, Membership.JOIN, room_id
|
|
|
|
)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
prev_state_ids = await context.get_prev_state_ids()
|
2019-10-28 08:43:23 -04:00
|
|
|
|
2022-02-12 05:44:16 -05:00
|
|
|
state_event_ids: Collection[str]
|
|
|
|
servers_in_room: Optional[Collection[str]]
|
|
|
|
if caller_supports_partial_state:
|
2022-11-15 12:35:19 -05:00
|
|
|
summary = await self.store.get_room_summary(room_id)
|
2022-02-12 05:44:16 -05:00
|
|
|
state_event_ids = _get_event_ids_for_partial_state_join(
|
2022-11-15 12:35:19 -05:00
|
|
|
event, prev_state_ids, summary
|
2022-02-12 05:44:16 -05:00
|
|
|
)
|
|
|
|
servers_in_room = await self.state.get_hosts_in_room_at_events(
|
|
|
|
room_id, event_ids=event.prev_event_ids()
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
state_event_ids = prev_state_ids.values()
|
|
|
|
servers_in_room = None
|
|
|
|
|
|
|
|
auth_chain_event_ids = await self.store.get_auth_chain_ids(
|
|
|
|
room_id, state_event_ids
|
|
|
|
)
|
|
|
|
|
|
|
|
# if the caller has opted in, we can omit any auth_chain events which are
|
|
|
|
# already in state_event_ids
|
|
|
|
if caller_supports_partial_state:
|
|
|
|
auth_chain_event_ids.difference_update(state_event_ids)
|
|
|
|
|
|
|
|
auth_chain_events = await self.store.get_events_as_list(auth_chain_event_ids)
|
|
|
|
state_events = await self.store.get_events_as_list(state_event_ids)
|
|
|
|
|
|
|
|
# we try to do all the async stuff before this point, so that time_now is as
|
|
|
|
# accurate as possible.
|
2015-01-26 05:45:24 -05:00
|
|
|
time_now = self._clock.time_msec()
|
2022-02-12 05:44:16 -05:00
|
|
|
event_json = event.get_pdu_json(time_now)
|
|
|
|
resp = {
|
2021-11-29 10:43:20 -05:00
|
|
|
"event": event_json,
|
2022-02-12 05:44:16 -05:00
|
|
|
"state": [p.get_pdu_json(time_now) for p in state_events],
|
|
|
|
"auth_chain": [p.get_pdu_json(time_now) for p in auth_chain_events],
|
2023-01-13 12:58:53 -05:00
|
|
|
"members_omitted": caller_supports_partial_state,
|
2019-11-11 11:40:45 -05:00
|
|
|
}
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2022-02-12 05:44:16 -05:00
|
|
|
if servers_in_room is not None:
|
2023-01-13 12:58:53 -05:00
|
|
|
resp["servers_in_room"] = list(servers_in_room)
|
2022-02-12 05:44:16 -05:00
|
|
|
|
|
|
|
return resp
|
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_make_leave_request(
|
|
|
|
self, origin: str, room_id: str, user_id: str
|
|
|
|
) -> Dict[str, Any]:
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
|
|
|
pdu = await self.handler.on_make_leave_request(origin, room_id, user_id)
|
2019-01-23 11:50:06 -05:00
|
|
|
|
2020-01-31 05:06:21 -05:00
|
|
|
room_version = await self.store.get_room_version_id(room_id)
|
2019-01-23 11:50:06 -05:00
|
|
|
|
2021-07-16 10:36:38 -04:00
|
|
|
return {"event": pdu.get_templated_pdu_json(), "room_version": room_version}
|
2015-10-20 06:58:58 -04:00
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
async def on_send_leave_request(
|
|
|
|
self, origin: str, content: JsonDict, room_id: str
|
|
|
|
) -> dict:
|
2015-10-20 06:58:58 -04:00
|
|
|
logger.debug("on_send_leave_request: content: %s", content)
|
2021-06-24 10:30:49 -04:00
|
|
|
await self._on_send_membership_event(origin, content, Membership.LEAVE, room_id)
|
2019-11-11 11:40:45 -05:00
|
|
|
return {}
|
2015-10-20 06:58:58 -04:00
|
|
|
|
2021-06-09 14:39:51 -04:00
|
|
|
async def on_make_knock_request(
|
|
|
|
self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
|
2021-10-27 12:27:23 -04:00
|
|
|
) -> JsonDict:
|
2021-06-09 14:39:51 -04:00
|
|
|
"""We've received a /make_knock/ request, so we create a partial knock
|
|
|
|
event for the room and hand that back, along with the room version, to the knocking
|
|
|
|
homeserver. We do *not* persist or process this event until the other server has
|
|
|
|
signed it and sent it back.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
origin: The (verified) server name of the requesting server.
|
|
|
|
room_id: The room to create the knock event in.
|
|
|
|
user_id: The user to create the knock for.
|
|
|
|
supported_versions: The room versions supported by the requesting server.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The partial knock event.
|
|
|
|
"""
|
|
|
|
origin_host, _ = parse_server_name(origin)
|
2022-08-24 05:09:59 -04:00
|
|
|
|
|
|
|
if await self.store.is_partial_state_room(room_id):
|
|
|
|
# Before we do anything: check if the room is partial-stated.
|
|
|
|
# Note that at the time this check was added, `on_make_knock_request` would
|
|
|
|
# block due to https://github.com/matrix-org/synapse/issues/12997.
|
|
|
|
raise SynapseError(
|
|
|
|
404,
|
|
|
|
"Unable to handle /make_knock right now; this server is not fully joined.",
|
|
|
|
errcode=Codes.NOT_FOUND,
|
|
|
|
)
|
|
|
|
|
2021-06-09 14:39:51 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
|
|
|
|
|
|
|
room_version = await self.store.get_room_version(room_id)
|
|
|
|
|
|
|
|
# Check that this room version is supported by the remote homeserver
|
|
|
|
if room_version.identifier not in supported_versions:
|
|
|
|
logger.warning(
|
|
|
|
"Room version %s not in %s", room_version.identifier, supported_versions
|
|
|
|
)
|
|
|
|
raise IncompatibleRoomVersionError(room_version=room_version.identifier)
|
|
|
|
|
|
|
|
# Check that this room supports knocking as defined by its room version
|
2023-07-18 08:44:59 -04:00
|
|
|
if not room_version.knock_join_rule:
|
2021-06-09 14:39:51 -04:00
|
|
|
raise SynapseError(
|
|
|
|
403,
|
|
|
|
"This room version does not support knocking",
|
|
|
|
errcode=Codes.FORBIDDEN,
|
|
|
|
)
|
|
|
|
|
|
|
|
pdu = await self.handler.on_make_knock_request(origin, room_id, user_id)
|
|
|
|
return {
|
2021-07-16 10:36:38 -04:00
|
|
|
"event": pdu.get_templated_pdu_json(),
|
2021-06-09 14:39:51 -04:00
|
|
|
"room_version": room_version.identifier,
|
|
|
|
}
|
|
|
|
|
|
|
|
async def on_send_knock_request(
|
|
|
|
self,
|
|
|
|
origin: str,
|
|
|
|
content: JsonDict,
|
|
|
|
room_id: str,
|
|
|
|
) -> Dict[str, List[JsonDict]]:
|
|
|
|
"""
|
|
|
|
We have received a knock event for a room. Verify and send the event into the room
|
|
|
|
on the knocking homeserver's behalf. Then reply with some stripped state from the
|
|
|
|
room for the knockee.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
origin: The remote homeserver of the knocking user.
|
|
|
|
content: The content of the request.
|
|
|
|
room_id: The ID of the room to knock on.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The stripped room state.
|
|
|
|
"""
|
2021-07-26 12:17:00 -04:00
|
|
|
_, context = await self._on_send_membership_event(
|
2021-06-24 10:30:49 -04:00
|
|
|
origin, content, Membership.KNOCK, room_id
|
|
|
|
)
|
|
|
|
|
|
|
|
# Retrieve stripped state events from the room and send them back to the remote
|
|
|
|
# server. This will allow the remote server's clients to display information
|
|
|
|
# related to the room while the knock request is pending.
|
|
|
|
stripped_room_state = (
|
|
|
|
await self.store.get_stripped_room_state_from_event_context(
|
2021-07-26 12:17:00 -04:00
|
|
|
context, self._room_prejoin_state_types
|
2021-06-24 10:30:49 -04:00
|
|
|
)
|
|
|
|
)
|
2023-10-06 07:27:35 -04:00
|
|
|
return {"knock_room_state": stripped_room_state}
|
2021-06-24 10:30:49 -04:00
|
|
|
|
|
|
|
async def _on_send_membership_event(
|
|
|
|
self, origin: str, content: JsonDict, membership_type: str, room_id: str
|
2021-07-26 12:17:00 -04:00
|
|
|
) -> Tuple[EventBase, EventContext]:
|
2021-06-24 10:30:49 -04:00
|
|
|
"""Handle an on_send_{join,leave,knock} request
|
|
|
|
|
|
|
|
Does some preliminary validation before passing the request on to the
|
|
|
|
federation handler.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
origin: The (authenticated) requesting server
|
|
|
|
content: The body of the send_* request - a complete membership event
|
|
|
|
membership_type: The expected membership type (join or leave, depending
|
|
|
|
on the endpoint)
|
|
|
|
room_id: The room_id from the request, to be validated against the room_id
|
|
|
|
in the event
|
|
|
|
|
|
|
|
Returns:
|
2021-07-26 12:17:00 -04:00
|
|
|
The event and context of the event after inserting it into the room graph.
|
2021-06-24 10:30:49 -04:00
|
|
|
|
|
|
|
Raises:
|
|
|
|
SynapseError if there is a problem with the request, including things like
|
|
|
|
the room_id not matching or the event not being authorized.
|
|
|
|
"""
|
|
|
|
assert_params_in_dict(content, ["room_id"])
|
|
|
|
if content["room_id"] != room_id:
|
|
|
|
raise SynapseError(
|
|
|
|
400,
|
|
|
|
"Room ID in body does not match that in request path",
|
|
|
|
Codes.BAD_JSON,
|
|
|
|
)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2022-08-04 11:27:04 -04:00
|
|
|
# Note that get_room_version throws if the room does not exist here.
|
2021-06-09 14:39:51 -04:00
|
|
|
room_version = await self.store.get_room_version(room_id)
|
|
|
|
|
2022-08-04 11:27:04 -04:00
|
|
|
if await self.store.is_partial_state_room(room_id):
|
|
|
|
# If our server is still only partially joined, we can't give a complete
|
|
|
|
# response to /send_join, /send_knock or /send_leave.
|
|
|
|
# This is because we will not be able to provide the server list (for partial
|
|
|
|
# joins) or the full state (for full joins).
|
|
|
|
# Return a 404 as we would if we weren't in the room at all.
|
|
|
|
logger.info(
|
|
|
|
f"Rejecting /send_{membership_type} to %s because it's a partial state room",
|
|
|
|
room_id,
|
|
|
|
)
|
|
|
|
raise SynapseError(
|
|
|
|
404,
|
|
|
|
f"Unable to handle /send_{membership_type} right now; this server is not fully joined.",
|
|
|
|
errcode=Codes.NOT_FOUND,
|
|
|
|
)
|
|
|
|
|
2023-07-18 08:44:59 -04:00
|
|
|
if membership_type == Membership.KNOCK and not room_version.knock_join_rule:
|
2021-06-09 14:39:51 -04:00
|
|
|
raise SynapseError(
|
|
|
|
403,
|
|
|
|
"This room version does not support knocking",
|
|
|
|
errcode=Codes.FORBIDDEN,
|
|
|
|
)
|
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
event = event_from_pdu_json(content, room_version)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
if event.type != EventTypes.Member or not event.is_state():
|
|
|
|
raise SynapseError(400, "Not an m.room.member event", Codes.BAD_JSON)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
if event.content.get("membership") != membership_type:
|
|
|
|
raise SynapseError(400, "Not a %s event" % membership_type, Codes.BAD_JSON)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
|
|
|
await self.check_server_matches_acl(origin_host, event.room_id)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2021-06-24 10:30:49 -04:00
|
|
|
logger.debug("_on_send_membership_event: pdu sigs: %s", event.signatures)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2021-07-26 12:17:00 -04:00
|
|
|
# Sign the event since we're vouching on behalf of the remote server that
|
|
|
|
# the event is valid to be sent into the room. Currently this is only done
|
|
|
|
# if the user is being joined via restricted join rules.
|
|
|
|
if (
|
2023-07-18 08:44:59 -04:00
|
|
|
room_version.restricted_join_rule
|
2021-07-26 12:17:00 -04:00
|
|
|
and event.membership == Membership.JOIN
|
2021-09-30 11:13:59 -04:00
|
|
|
and EventContentFields.AUTHORISING_USER in event.content
|
2021-07-26 12:17:00 -04:00
|
|
|
):
|
|
|
|
# We can only authorise our own users.
|
|
|
|
authorising_server = get_domain_from_id(
|
2021-09-30 11:13:59 -04:00
|
|
|
event.content[EventContentFields.AUTHORISING_USER]
|
2021-07-26 12:17:00 -04:00
|
|
|
)
|
2023-05-05 10:06:22 -04:00
|
|
|
if not self._is_mine_server_name(authorising_server):
|
2021-07-26 12:17:00 -04:00
|
|
|
raise SynapseError(
|
|
|
|
400,
|
2023-06-06 17:26:12 -04:00
|
|
|
f"Cannot authorise membership event for {authorising_server}. We can only authorise requests from our own homeserver",
|
2021-07-26 12:17:00 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
event.signatures.update(
|
|
|
|
compute_event_signature(
|
|
|
|
room_version,
|
|
|
|
event.get_pdu_json(),
|
|
|
|
self.hs.hostname,
|
|
|
|
self.hs.signing_key,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2022-05-31 18:32:56 -04:00
|
|
|
try:
|
|
|
|
event = await self._check_sigs_and_hash(room_version, event)
|
|
|
|
except InvalidEventSignatureError as e:
|
|
|
|
errmsg = f"event id {event.event_id}: {e}"
|
|
|
|
logger.warning("%s", errmsg)
|
|
|
|
raise SynapseError(403, errmsg, Codes.FORBIDDEN)
|
2021-06-24 10:30:49 -04:00
|
|
|
|
Handle race between persisting an event and un-partial stating a room (#13100)
Whenever we want to persist an event, we first compute an event context,
which includes the state at the event and a flag indicating whether the
state is partial. After a lot of processing, we finally try to store the
event in the database, which can fail for partial state events when the
containing room has been un-partial stated in the meantime.
We detect the race as a foreign key constraint failure in the data store
layer and turn it into a special `PartialStateConflictError` exception,
which makes its way up to the method in which we computed the event
context.
To make things difficult, the exception needs to cross a replication
request: `/fed_send_events` for events coming over federation and
`/send_event` for events from clients. We transport the
`PartialStateConflictError` as a `409 Conflict` over replication and
turn `409`s back into `PartialStateConflictError`s on the worker making
the request.
All client events go through
`EventCreationHandler.handle_new_client_event`, which is called in
*a lot* of places. Instead of trying to update all the code which
creates client events, we turn the `PartialStateConflictError` into a
`429 Too Many Requests` in
`EventCreationHandler.handle_new_client_event` and hope that clients
take it as a hint to retry their request.
On the federation event side, there are 7 places which compute event
contexts. 4 of them use outlier event contexts:
`FederationEventHandler._auth_and_persist_outliers_inner`,
`FederationHandler.do_knock`, `FederationHandler.on_invite_request` and
`FederationHandler.do_remotely_reject_invite`. These events won't have
the partial state flag, so we do not need to do anything for then.
The remaining 3 paths which create events are
`FederationEventHandler.process_remote_join`,
`FederationEventHandler.on_send_membership_event` and
`FederationEventHandler._process_received_pdu`.
We can't experience the race in `process_remote_join`, unless we're
handling an additional join into a partial state room, which currently
blocks, so we make no attempt to handle it correctly.
`on_send_membership_event` is only called by
`FederationServer._on_send_membership_event`, so we catch the
`PartialStateConflictError` there and retry just once.
`_process_received_pdu` is called by `on_receive_pdu` for incoming
events and `_process_pulled_event` for backfill. The latter should never
try to persist partial state events, so we ignore it. We catch the
`PartialStateConflictError` in `on_receive_pdu` and retry just once.
Refering to the graph of code paths in
https://github.com/matrix-org/synapse/issues/12988#issuecomment-1156857648
may make the above make more sense.
Signed-off-by: Sean Quah <seanq@matrix.org>
2022-07-05 11:12:52 -04:00
|
|
|
try:
|
|
|
|
return await self._federation_event_handler.on_send_membership_event(
|
|
|
|
origin, event
|
|
|
|
)
|
|
|
|
except PartialStateConflictError:
|
|
|
|
# The room was un-partial stated while we were persisting the event.
|
|
|
|
# Try once more, with full state this time.
|
|
|
|
logger.info(
|
|
|
|
"Room %s was un-partial stated during `on_send_membership_event`, trying again.",
|
|
|
|
room_id,
|
|
|
|
)
|
|
|
|
return await self._federation_event_handler.on_send_membership_event(
|
|
|
|
origin, event
|
|
|
|
)
|
2021-06-09 14:39:51 -04:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_event_auth(
|
|
|
|
self, origin: str, room_id: str, event_id: str
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._server_linearizer.queue((origin, room_id)):
|
2022-09-23 06:47:16 -04:00
|
|
|
await self._event_auth_handler.assert_host_in_room(room_id, origin)
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2016-06-17 11:43:45 -04:00
|
|
|
time_now = self._clock.time_msec()
|
2019-10-29 10:05:32 -04:00
|
|
|
auth_pdus = await self.handler.on_event_auth(event_id)
|
2016-06-17 11:43:45 -04:00
|
|
|
res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]}
|
2019-08-30 11:28:26 -04:00
|
|
|
return 200, res
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_query_client_keys(
|
|
|
|
self, origin: str, content: Dict[str, str]
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
|
|
|
return await self.on_query_request("client_keys", content)
|
|
|
|
|
|
|
|
async def on_query_user_devices(
|
|
|
|
self, origin: str, user_id: str
|
|
|
|
) -> Tuple[int, Dict[str, Any]]:
|
2020-02-07 10:45:39 -05:00
|
|
|
keys = await self.device_handler.on_federation_query_user_devices(user_id)
|
|
|
|
return 200, keys
|
2017-01-26 11:06:54 -05:00
|
|
|
|
2019-08-22 06:28:12 -04:00
|
|
|
@trace
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_claim_client_keys(
|
2023-04-27 12:57:46 -04:00
|
|
|
self, query: List[Tuple[str, str, str, int]], always_include_fallback_keys: bool
|
2020-04-07 15:03:23 -04:00
|
|
|
) -> Dict[str, Any]:
|
2023-10-31 09:58:30 -04:00
|
|
|
if any(
|
|
|
|
not self.hs.is_mine(UserID.from_string(user_id))
|
|
|
|
for user_id, _, _, _ in query
|
|
|
|
):
|
|
|
|
raise SynapseError(400, "User is not hosted on this homeserver")
|
|
|
|
|
2019-08-22 06:28:12 -04:00
|
|
|
log_kv({"message": "Claiming one time keys.", "user, device pairs": query})
|
2023-04-25 13:30:41 -04:00
|
|
|
results = await self._e2e_keys_handler.claim_local_one_time_keys(
|
|
|
|
query, always_include_fallback_keys=always_include_fallback_keys
|
|
|
|
)
|
2023-03-28 14:26:27 -04:00
|
|
|
|
|
|
|
json_result: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
|
|
|
|
for result in results:
|
|
|
|
for user_id, device_keys in result.items():
|
|
|
|
for device_id, keys in device_keys.items():
|
|
|
|
for key_id, key in keys.items():
|
2023-06-13 13:51:47 -04:00
|
|
|
json_result.setdefault(user_id, {}).setdefault(device_id, {})[
|
|
|
|
key_id
|
|
|
|
] = key
|
2015-08-13 12:27:46 -04:00
|
|
|
|
2017-05-09 14:01:39 -04:00
|
|
|
logger.info(
|
|
|
|
"Claimed one-time-keys: %s",
|
|
|
|
",".join(
|
2019-06-20 05:32:02 -04:00
|
|
|
(
|
2017-05-09 14:01:39 -04:00
|
|
|
"%s for %s:%s" % (key_id, user_id, device_id)
|
2020-06-15 07:03:36 -04:00
|
|
|
for user_id, user_keys in json_result.items()
|
|
|
|
for device_id, device_keys in user_keys.items()
|
|
|
|
for key_id, _ in device_keys.items()
|
2019-06-20 05:32:02 -04:00
|
|
|
)
|
2017-05-09 14:01:39 -04:00
|
|
|
),
|
|
|
|
)
|
|
|
|
|
2019-07-23 09:00:55 -04:00
|
|
|
return {"one_time_keys": json_result}
|
2015-07-23 11:03:38 -04:00
|
|
|
|
2019-10-29 10:05:32 -04:00
|
|
|
async def on_get_missing_events(
|
2020-04-07 15:03:23 -04:00
|
|
|
self,
|
|
|
|
origin: str,
|
|
|
|
room_id: str,
|
|
|
|
earliest_events: List[str],
|
|
|
|
latest_events: List[str],
|
|
|
|
limit: int,
|
|
|
|
) -> Dict[str, list]:
|
2022-04-05 10:43:52 -04:00
|
|
|
async with self._server_linearizer.queue((origin, room_id)):
|
2018-07-04 10:31:00 -04:00
|
|
|
origin_host, _ = parse_server_name(origin)
|
2019-10-29 10:05:32 -04:00
|
|
|
await self.check_server_matches_acl(origin_host, room_id)
|
2018-07-04 10:31:00 -04:00
|
|
|
|
2020-02-06 08:31:05 -05:00
|
|
|
logger.debug(
|
2016-06-17 11:43:45 -04:00
|
|
|
"on_get_missing_events: earliest_events: %r, latest_events: %r,"
|
2018-10-16 15:37:16 -04:00
|
|
|
" limit: %d",
|
|
|
|
earliest_events,
|
|
|
|
latest_events,
|
|
|
|
limit,
|
2016-06-17 11:43:45 -04:00
|
|
|
)
|
2016-12-31 10:21:37 -05:00
|
|
|
|
2019-10-29 10:05:32 -04:00
|
|
|
missing_events = await self.handler.on_get_missing_events(
|
2018-10-16 15:37:16 -04:00
|
|
|
origin, room_id, earliest_events, latest_events, limit
|
2016-06-17 11:43:45 -04:00
|
|
|
)
|
2015-02-19 12:24:14 -05:00
|
|
|
|
2016-06-17 11:43:45 -04:00
|
|
|
if len(missing_events) < 5:
|
2020-02-06 08:31:05 -05:00
|
|
|
logger.debug(
|
2016-06-17 11:43:45 -04:00
|
|
|
"Returning %d events: %r", len(missing_events), missing_events
|
|
|
|
)
|
|
|
|
else:
|
2020-02-06 08:31:05 -05:00
|
|
|
logger.debug("Returning %d events", len(missing_events))
|
2016-06-08 06:55:31 -04:00
|
|
|
|
2016-06-17 11:43:45 -04:00
|
|
|
time_now = self._clock.time_msec()
|
2015-02-19 12:24:14 -05:00
|
|
|
|
2019-07-23 09:00:55 -04:00
|
|
|
return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]}
|
2015-02-19 12:24:14 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def on_openid_userinfo(self, token: str) -> Optional[str]:
|
2016-05-05 08:42:44 -04:00
|
|
|
ts_now_ms = self._clock.time_msec()
|
2020-04-07 15:03:23 -04:00
|
|
|
return await self.store.get_user_id_for_open_id_token(token, ts_now_ms)
|
2016-05-05 08:42:44 -04:00
|
|
|
|
2021-08-06 09:39:59 -04:00
|
|
|
def _transaction_dict_from_pdus(self, pdu_list: List[EventBase]) -> JsonDict:
|
2015-01-26 05:45:24 -05:00
|
|
|
"""Returns a new Transaction containing the given PDUs suitable for
|
|
|
|
transmission.
|
|
|
|
"""
|
|
|
|
time_now = self._clock.time_msec()
|
|
|
|
pdus = [p.get_pdu_json(time_now) for p in pdu_list]
|
|
|
|
return Transaction(
|
2021-08-06 09:39:59 -04:00
|
|
|
# Just need a dummy transaction ID and destination since it won't be used.
|
|
|
|
transaction_id="",
|
2015-01-26 05:45:24 -05:00
|
|
|
origin=self.server_name,
|
|
|
|
pdus=pdus,
|
|
|
|
origin_server_ts=int(time_now),
|
2021-08-06 09:39:59 -04:00
|
|
|
destination="",
|
|
|
|
).get_dict()
|
2015-01-26 05:45:24 -05:00
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None:
|
2017-03-09 08:15:27 -05:00
|
|
|
"""Process a PDU received in a federation /send/ transaction.
|
|
|
|
|
2018-04-17 18:41:36 -04:00
|
|
|
If the event is invalid, then this method throws a FederationError.
|
|
|
|
(The error will then be logged and sent back to the sender (which
|
|
|
|
probably won't do anything with it), and other events in the
|
|
|
|
transaction will be processed as normal).
|
|
|
|
|
|
|
|
It is likely that we'll then receive other events which refer to
|
|
|
|
this rejected_event in their prev_events, etc. When that happens,
|
|
|
|
we'll attempt to fetch the rejected event again, which will presumably
|
|
|
|
fail, so those second-generation events will also get rejected.
|
|
|
|
|
|
|
|
Eventually, we get to the point where there are more than 10 events
|
|
|
|
between any new events and the original rejected event. Since we
|
|
|
|
only try to backfill 10 events deep on received pdu, we then accept the
|
|
|
|
new event, possibly introducing a discontinuity in the DAG, with new
|
|
|
|
forward extremities, so normal service is approximately returned,
|
|
|
|
until we try to backfill across the discontinuity.
|
|
|
|
|
2017-03-09 08:15:27 -05:00
|
|
|
Args:
|
2020-04-07 15:03:23 -04:00
|
|
|
origin: server which sent the pdu
|
|
|
|
pdu: received pdu
|
2018-04-17 18:41:36 -04:00
|
|
|
|
|
|
|
Raises: FederationError if the signatures / hash do not match, or
|
|
|
|
if the event was unacceptable for any other reason (eg, too large,
|
|
|
|
too many prev_events, couldn't find the prev_events)
|
|
|
|
"""
|
2017-10-06 09:24:06 -04:00
|
|
|
|
2019-01-29 12:21:48 -05:00
|
|
|
# We've already checked that we know the room version by this point
|
2020-03-19 08:22:56 -04:00
|
|
|
room_version = await self.store.get_room_version(pdu.room_id)
|
2019-01-29 12:21:48 -05:00
|
|
|
|
2017-03-09 08:15:27 -05:00
|
|
|
# Check signature.
|
|
|
|
try:
|
2019-10-29 10:05:32 -04:00
|
|
|
pdu = await self._check_sigs_and_hash(room_version, pdu)
|
2022-05-31 18:32:56 -04:00
|
|
|
except InvalidEventSignatureError as e:
|
|
|
|
logger.warning("event id %s: %s", pdu.event_id, e)
|
|
|
|
raise FederationError("ERROR", 403, str(e), affected=pdu.event_id)
|
2017-03-09 08:15:27 -05:00
|
|
|
|
2023-04-17 20:57:40 -04:00
|
|
|
if await self._spam_checker_module_callbacks.should_drop_federated_event(pdu):
|
2022-05-23 12:36:21 -04:00
|
|
|
logger.warning(
|
|
|
|
"Unstaged federated event contains spam, dropping %s", pdu.event_id
|
|
|
|
)
|
|
|
|
return
|
|
|
|
|
2021-06-29 14:55:22 -04:00
|
|
|
# Add the event to our staging area
|
|
|
|
await self.store.insert_received_event_to_staging(origin, pdu)
|
|
|
|
|
|
|
|
# Try and acquire the processing lock for the room, if we get it start a
|
|
|
|
# background process for handling the events in the room.
|
|
|
|
lock = await self.store.try_acquire_lock(
|
|
|
|
_INBOUND_EVENT_HANDLING_LOCK_NAME, pdu.room_id
|
|
|
|
)
|
|
|
|
if lock:
|
|
|
|
self._process_incoming_pdus_in_room_inner(
|
|
|
|
pdu.room_id, room_version, lock, origin, pdu
|
|
|
|
)
|
|
|
|
|
2022-05-23 12:36:21 -04:00
|
|
|
async def _get_next_nonspam_staged_event_for_room(
|
|
|
|
self, room_id: str, room_version: RoomVersion
|
|
|
|
) -> Optional[Tuple[str, EventBase]]:
|
|
|
|
"""Fetch the first non-spam event from staging queue.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
room_id: the room to fetch the first non-spam event in.
|
|
|
|
room_version: the version of the room.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The first non-spam event in that room.
|
|
|
|
"""
|
|
|
|
|
|
|
|
while True:
|
|
|
|
# We need to do this check outside the lock to avoid a race between
|
|
|
|
# a new event being inserted by another instance and it attempting
|
|
|
|
# to acquire the lock.
|
|
|
|
next = await self.store.get_next_staged_event_for_room(
|
|
|
|
room_id, room_version
|
|
|
|
)
|
|
|
|
|
|
|
|
if next is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
origin, event = next
|
|
|
|
|
2023-04-17 20:57:40 -04:00
|
|
|
if await self._spam_checker_module_callbacks.should_drop_federated_event(
|
|
|
|
event
|
|
|
|
):
|
2022-05-23 12:36:21 -04:00
|
|
|
logger.warning(
|
|
|
|
"Staged federated event contains spam, dropping %s",
|
|
|
|
event.event_id,
|
|
|
|
)
|
|
|
|
continue
|
|
|
|
|
|
|
|
return next
|
|
|
|
|
2021-06-29 14:55:22 -04:00
|
|
|
@wrap_as_background_process("_process_incoming_pdus_in_room_inner")
|
|
|
|
async def _process_incoming_pdus_in_room_inner(
|
|
|
|
self,
|
|
|
|
room_id: str,
|
|
|
|
room_version: RoomVersion,
|
|
|
|
lock: Lock,
|
2021-07-06 08:02:37 -04:00
|
|
|
latest_origin: Optional[str] = None,
|
|
|
|
latest_event: Optional[EventBase] = None,
|
2021-06-29 14:55:22 -04:00
|
|
|
) -> None:
|
|
|
|
"""Process events in the staging area for the given room.
|
|
|
|
|
|
|
|
The latest_origin and latest_event args are the latest origin and event
|
2021-07-06 08:02:37 -04:00
|
|
|
received (or None to simply pull the next event from the database).
|
2021-06-29 14:55:22 -04:00
|
|
|
"""
|
|
|
|
|
|
|
|
# The common path is for the event we just received be the only event in
|
|
|
|
# the room, so instead of pulling the event out of the DB and parsing
|
|
|
|
# the event we just pull out the next event ID and check if that matches.
|
2021-07-06 08:02:37 -04:00
|
|
|
if latest_event is not None and latest_origin is not None:
|
2021-08-13 07:49:06 -04:00
|
|
|
result = await self.store.get_next_staged_event_id_for_room(room_id)
|
|
|
|
if result is None:
|
2021-07-06 08:02:37 -04:00
|
|
|
latest_origin = None
|
|
|
|
latest_event = None
|
2021-08-13 07:49:06 -04:00
|
|
|
else:
|
|
|
|
next_origin, next_event_id = result
|
|
|
|
if (
|
|
|
|
next_origin != latest_origin
|
|
|
|
or next_event_id != latest_event.event_id
|
|
|
|
):
|
|
|
|
latest_origin = None
|
|
|
|
latest_event = None
|
2021-07-06 08:02:37 -04:00
|
|
|
|
|
|
|
if latest_origin is None or latest_event is None:
|
2021-06-29 14:55:22 -04:00
|
|
|
next = await self.store.get_next_staged_event_for_room(
|
|
|
|
room_id, room_version
|
|
|
|
)
|
|
|
|
if not next:
|
2021-07-09 05:16:54 -04:00
|
|
|
await lock.release()
|
2021-06-29 14:55:22 -04:00
|
|
|
return
|
|
|
|
|
|
|
|
origin, event = next
|
2021-07-06 08:02:37 -04:00
|
|
|
else:
|
|
|
|
origin = latest_origin
|
|
|
|
event = latest_event
|
2021-06-29 14:55:22 -04:00
|
|
|
|
|
|
|
# We loop round until there are no more events in the room in the
|
|
|
|
# staging area, or we fail to get the lock (which means another process
|
|
|
|
# has started processing).
|
|
|
|
while True:
|
|
|
|
async with lock:
|
2022-03-25 10:44:57 -04:00
|
|
|
logger.info("handling received PDU in room %s: %s", room_id, event)
|
2021-06-29 14:55:22 -04:00
|
|
|
try:
|
2021-09-29 06:59:43 -04:00
|
|
|
with nested_logging_context(event.event_id):
|
2023-07-31 05:58:03 -04:00
|
|
|
# We're taking out a lock within a lock, which could
|
|
|
|
# lead to deadlocks if we're not careful. However, it is
|
|
|
|
# safe on this occasion as we only ever take a write
|
|
|
|
# lock when deleting a room, which we would never do
|
|
|
|
# while holding the `_INBOUND_EVENT_HANDLING_LOCK_NAME`
|
|
|
|
# lock.
|
|
|
|
async with self._worker_lock_handler.acquire_read_write_lock(
|
2023-08-16 10:19:54 -04:00
|
|
|
NEW_EVENT_DURING_PURGE_LOCK_NAME, room_id, write=False
|
2023-07-31 05:58:03 -04:00
|
|
|
):
|
|
|
|
await self._federation_event_handler.on_receive_pdu(
|
|
|
|
origin, event
|
|
|
|
)
|
2021-06-29 14:55:22 -04:00
|
|
|
except FederationError as e:
|
|
|
|
# XXX: Ideally we'd inform the remote we failed to process
|
|
|
|
# the event, but we can't return an error in the transaction
|
|
|
|
# response (as we've already responded).
|
|
|
|
logger.warning("Error handling PDU %s: %s", event.event_id, e)
|
|
|
|
except Exception:
|
|
|
|
f = failure.Failure()
|
|
|
|
logger.error(
|
|
|
|
"Failed to handle PDU %s",
|
|
|
|
event.event_id,
|
2023-05-31 07:18:29 -04:00
|
|
|
exc_info=(f.type, f.value, f.getTracebackObject()),
|
2021-06-29 14:55:22 -04:00
|
|
|
)
|
|
|
|
|
2021-06-30 07:07:16 -04:00
|
|
|
received_ts = await self.store.remove_received_event_from_staging(
|
2021-06-29 14:55:22 -04:00
|
|
|
origin, event.event_id
|
|
|
|
)
|
2021-06-30 07:07:16 -04:00
|
|
|
if received_ts is not None:
|
|
|
|
pdu_process_time.observe(
|
|
|
|
(self._clock.time_msec() - received_ts) / 1000
|
|
|
|
)
|
2021-06-29 14:55:22 -04:00
|
|
|
|
2022-05-23 12:36:21 -04:00
|
|
|
next = await self._get_next_nonspam_staged_event_for_room(
|
2021-06-29 14:55:22 -04:00
|
|
|
room_id, room_version
|
|
|
|
)
|
2022-05-23 12:36:21 -04:00
|
|
|
|
2021-06-29 14:55:22 -04:00
|
|
|
if not next:
|
|
|
|
break
|
|
|
|
|
|
|
|
origin, event = next
|
|
|
|
|
2021-08-02 09:37:25 -04:00
|
|
|
# Prune the event queue if it's getting large.
|
|
|
|
#
|
|
|
|
# We do this *after* handling the first event as the common case is
|
|
|
|
# that the queue is empty (/has the single event in), and so there's
|
|
|
|
# no need to do this check.
|
|
|
|
pruned = await self.store.prune_staged_events_in_room(room_id, room_version)
|
|
|
|
if pruned:
|
|
|
|
# If we have pruned the queue check we need to refetch the next
|
|
|
|
# event to handle.
|
|
|
|
next = await self.store.get_next_staged_event_for_room(
|
|
|
|
room_id, room_version
|
|
|
|
)
|
|
|
|
if not next:
|
|
|
|
break
|
|
|
|
|
|
|
|
origin, event = next
|
|
|
|
|
2021-10-22 13:15:41 -04:00
|
|
|
new_lock = await self.store.try_acquire_lock(
|
2021-06-29 14:55:22 -04:00
|
|
|
_INBOUND_EVENT_HANDLING_LOCK_NAME, room_id
|
|
|
|
)
|
2021-10-22 13:15:41 -04:00
|
|
|
if not new_lock:
|
2021-06-29 14:55:22 -04:00
|
|
|
return
|
2021-10-22 13:15:41 -04:00
|
|
|
lock = new_lock
|
2017-03-09 07:20:46 -05:00
|
|
|
|
2019-10-29 10:05:32 -04:00
|
|
|
async def exchange_third_party_invite(
|
2020-04-07 15:03:23 -04:00
|
|
|
self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict
|
2021-04-06 07:21:57 -04:00
|
|
|
) -> None:
|
|
|
|
await self.handler.exchange_third_party_invite(
|
2016-02-23 10:11:25 -05:00
|
|
|
sender_user_id, target_user_id, room_id, signed
|
|
|
|
)
|
2015-11-05 11:43:19 -05:00
|
|
|
|
2021-04-06 07:21:57 -04:00
|
|
|
async def on_exchange_third_party_invite_request(self, event_dict: Dict) -> None:
|
|
|
|
await self.handler.on_exchange_third_party_invite_request(event_dict)
|
2018-03-12 12:17:08 -04:00
|
|
|
|
2021-04-06 07:21:57 -04:00
|
|
|
async def check_server_matches_acl(self, server_name: str, room_id: str) -> None:
|
2018-07-04 10:31:00 -04:00
|
|
|
"""Check if the given server is allowed by the server ACLs in the room
|
|
|
|
|
|
|
|
Args:
|
2020-04-07 15:03:23 -04:00
|
|
|
server_name: name of server, *without any port part*
|
|
|
|
room_id: ID of the room to check
|
2018-07-04 10:31:00 -04:00
|
|
|
|
|
|
|
Raises:
|
|
|
|
AuthError if the server does not match the ACL
|
|
|
|
"""
|
2023-09-26 11:57:50 -04:00
|
|
|
server_acl_evaluator = (
|
|
|
|
await self._storage_controllers.state.get_server_acl_for_room(room_id)
|
2022-06-06 04:24:12 -04:00
|
|
|
)
|
2023-09-26 11:57:50 -04:00
|
|
|
if server_acl_evaluator and not server_acl_evaluator.server_matches_acl_event(
|
|
|
|
server_name
|
|
|
|
):
|
|
|
|
raise AuthError(code=403, msg="Server is banned from room")
|
2018-07-04 10:31:00 -04:00
|
|
|
|
|
|
|
|
2020-09-04 06:54:56 -04:00
|
|
|
class FederationHandlerRegistry:
|
2018-03-12 12:17:08 -04:00
|
|
|
"""Allows classes to register themselves as handlers for a given EDU or
|
|
|
|
query type for incoming federation traffic.
|
|
|
|
"""
|
2019-06-20 05:32:02 -04:00
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
def __init__(self, hs: "HomeServer"):
|
|
|
|
self.config = hs.config
|
|
|
|
self.clock = hs.get_clock()
|
|
|
|
self._instance_name = hs.get_instance_name()
|
2018-03-12 12:17:08 -04:00
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
# These are safe to load in monolith mode, but will explode if we try
|
|
|
|
# and use them. However we have guards before we use them to ensure that
|
|
|
|
# we don't route to ourselves, and in monolith mode that will always be
|
|
|
|
# the case.
|
|
|
|
self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
|
|
|
|
self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
|
|
|
|
|
2021-07-15 06:02:43 -04:00
|
|
|
self.edu_handlers: Dict[str, Callable[[str, dict], Awaitable[None]]] = {}
|
|
|
|
self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
|
2020-07-16 10:12:54 -04:00
|
|
|
|
2021-01-07 13:07:28 -05:00
|
|
|
# Map from type to instance names that we should route EDU handling to.
|
|
|
|
# We randomly choose one instance from the list to route to for each new
|
|
|
|
# EDU received.
|
2021-07-15 06:02:43 -04:00
|
|
|
self._edu_type_to_instance: Dict[str, List[str]] = {}
|
2020-07-16 10:12:54 -04:00
|
|
|
|
|
|
|
def register_edu_handler(
|
2020-10-09 07:20:51 -04:00
|
|
|
self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
|
2021-04-06 07:21:57 -04:00
|
|
|
) -> None:
|
2018-03-12 12:17:08 -04:00
|
|
|
"""Sets the handler callable that will be used to handle an incoming
|
|
|
|
federation EDU of the given type.
|
|
|
|
|
|
|
|
Args:
|
2020-04-07 15:03:23 -04:00
|
|
|
edu_type: The type of the incoming EDU to register handler for
|
|
|
|
handler: A callable invoked on incoming EDU
|
2018-03-12 12:17:08 -04:00
|
|
|
of the given type. The arguments are the origin server name and
|
|
|
|
the EDU contents.
|
|
|
|
"""
|
|
|
|
if edu_type in self.edu_handlers:
|
|
|
|
raise KeyError("Already have an EDU handler for %s" % (edu_type,))
|
|
|
|
|
2018-07-26 06:44:22 -04:00
|
|
|
logger.info("Registering federation EDU handler for %r", edu_type)
|
|
|
|
|
2018-03-12 12:17:08 -04:00
|
|
|
self.edu_handlers[edu_type] = handler
|
|
|
|
|
2020-04-07 15:03:23 -04:00
|
|
|
def register_query_handler(
|
2021-03-12 11:37:57 -05:00
|
|
|
self, query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
|
2021-04-06 07:21:57 -04:00
|
|
|
) -> None:
|
2018-03-12 12:17:08 -04:00
|
|
|
"""Sets the handler callable that will be used to handle an incoming
|
|
|
|
federation query of the given type.
|
|
|
|
|
|
|
|
Args:
|
2020-04-07 15:03:23 -04:00
|
|
|
query_type: Category name of the query, which should match
|
2018-03-12 12:17:08 -04:00
|
|
|
the string used by make_query.
|
2020-04-07 15:03:23 -04:00
|
|
|
handler: Invoked to handle
|
2018-03-12 12:17:08 -04:00
|
|
|
incoming queries of this type. The return will be yielded
|
|
|
|
on and the result used as the response to the query request.
|
|
|
|
"""
|
|
|
|
if query_type in self.query_handlers:
|
|
|
|
raise KeyError("Already have a Query handler for %s" % (query_type,))
|
|
|
|
|
2018-07-26 06:44:22 -04:00
|
|
|
logger.info("Registering federation query handler for %r", query_type)
|
|
|
|
|
2018-03-12 12:17:08 -04:00
|
|
|
self.query_handlers[query_type] = handler
|
|
|
|
|
2021-04-06 07:21:57 -04:00
|
|
|
def register_instances_for_edu(
|
|
|
|
self, edu_type: str, instance_names: List[str]
|
|
|
|
) -> None:
|
2021-01-07 13:07:28 -05:00
|
|
|
"""Register that the EDU handler is on multiple instances."""
|
|
|
|
self._edu_type_to_instance[edu_type] = instance_names
|
2020-07-16 10:12:54 -04:00
|
|
|
|
2021-04-06 07:21:57 -04:00
|
|
|
async def on_edu(self, edu_type: str, origin: str, content: dict) -> None:
|
2023-10-26 15:11:24 -04:00
|
|
|
if not self.config.server.track_presence and edu_type == EduTypes.PRESENCE:
|
2021-02-19 13:20:34 -05:00
|
|
|
return
|
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
# Check if we have a handler on this instance
|
2018-03-12 12:17:08 -04:00
|
|
|
handler = self.edu_handlers.get(edu_type)
|
2020-07-16 10:12:54 -04:00
|
|
|
if handler:
|
|
|
|
with start_active_span_from_edu(content, "handle_edu"):
|
|
|
|
try:
|
|
|
|
await handler(origin, content)
|
|
|
|
except SynapseError as e:
|
|
|
|
logger.info("Failed to handle edu %r: %r", edu_type, e)
|
|
|
|
except Exception:
|
|
|
|
logger.exception("Failed to handle edu %r", edu_type)
|
2020-04-07 15:03:23 -04:00
|
|
|
return
|
2018-03-12 12:17:08 -04:00
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
# Check if we can route it somewhere else that isn't us
|
2021-01-07 13:07:28 -05:00
|
|
|
instances = self._edu_type_to_instance.get(edu_type, ["master"])
|
|
|
|
if self._instance_name not in instances:
|
|
|
|
# Pick an instance randomly so that we don't overload one.
|
|
|
|
route_to = random.choice(instances)
|
|
|
|
|
2019-08-22 13:21:10 -04:00
|
|
|
try:
|
2020-07-16 10:12:54 -04:00
|
|
|
await self._send_edu(
|
|
|
|
instance_name=route_to,
|
|
|
|
edu_type=edu_type,
|
|
|
|
origin=origin,
|
|
|
|
content=content,
|
|
|
|
)
|
2019-08-22 13:21:10 -04:00
|
|
|
except SynapseError as e:
|
|
|
|
logger.info("Failed to handle edu %r: %r", edu_type, e)
|
|
|
|
except Exception:
|
|
|
|
logger.exception("Failed to handle edu %r", edu_type)
|
2019-02-27 08:53:46 -05:00
|
|
|
return
|
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
# Oh well, let's just log and move on.
|
|
|
|
logger.warning("No handler registered for EDU type %s", edu_type)
|
2018-07-26 06:44:22 -04:00
|
|
|
|
2021-03-12 11:37:57 -05:00
|
|
|
async def on_query(self, query_type: str, args: dict) -> JsonDict:
|
2018-07-26 06:44:22 -04:00
|
|
|
handler = self.query_handlers.get(query_type)
|
|
|
|
if handler:
|
2019-10-29 12:36:46 -04:00
|
|
|
return await handler(args)
|
2018-07-26 06:44:22 -04:00
|
|
|
|
2020-07-16 10:12:54 -04:00
|
|
|
# Check if we can route it somewhere else that isn't us
|
|
|
|
if self._instance_name == "master":
|
|
|
|
return await self._get_query_client(query_type=query_type, args=args)
|
|
|
|
|
|
|
|
# Uh oh, no handler! Let's raise an exception so the request returns an
|
|
|
|
# error.
|
|
|
|
logger.warning("No handler registered for query type %s", query_type)
|
|
|
|
raise NotFoundError("No handler for Query type '%s'" % (query_type,))
|
2022-02-12 05:44:16 -05:00
|
|
|
|
|
|
|
|
|
|
|
def _get_event_ids_for_partial_state_join(
|
|
|
|
join_event: EventBase,
|
|
|
|
prev_state_ids: StateMap[str],
|
2023-02-10 18:29:00 -05:00
|
|
|
summary: Mapping[str, MemberSummary],
|
2022-02-12 05:44:16 -05:00
|
|
|
) -> Collection[str]:
|
2023-01-16 07:40:25 -05:00
|
|
|
"""Calculate state to be returned in a partial_state send_join
|
2022-02-12 05:44:16 -05:00
|
|
|
|
|
|
|
Args:
|
|
|
|
join_event: the join event being send_joined
|
|
|
|
prev_state_ids: the event ids of the state before the join
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
the event ids to be returned
|
|
|
|
"""
|
|
|
|
|
|
|
|
# return all non-member events
|
|
|
|
state_event_ids = {
|
|
|
|
event_id
|
|
|
|
for (event_type, state_key), event_id in prev_state_ids.items()
|
|
|
|
if event_type != EventTypes.Member
|
|
|
|
}
|
|
|
|
|
|
|
|
# we also need the current state of the current user (it's going to
|
|
|
|
# be an auth event for the new join, so we may as well return it)
|
|
|
|
current_membership_event_id = prev_state_ids.get(
|
|
|
|
(EventTypes.Member, join_event.state_key)
|
|
|
|
)
|
|
|
|
if current_membership_event_id is not None:
|
|
|
|
state_event_ids.add(current_membership_event_id)
|
|
|
|
|
2022-11-15 12:35:19 -05:00
|
|
|
name_id = prev_state_ids.get((EventTypes.Name, ""))
|
|
|
|
canonical_alias_id = prev_state_ids.get((EventTypes.CanonicalAlias, ""))
|
|
|
|
if not name_id and not canonical_alias_id:
|
|
|
|
# Also include the hero members of the room (for DM rooms without a title).
|
|
|
|
# To do this properly, we should select the correct subset of membership events
|
|
|
|
# from `prev_state_ids`. Instead, we are lazier and use the (cached)
|
|
|
|
# `get_room_summary` function, which is based on the current state of the room.
|
|
|
|
# This introduces races; we choose to ignore them because a) they should be rare
|
|
|
|
# and b) even if it's wrong, joining servers will get the full state eventually.
|
|
|
|
heroes = extract_heroes_from_room_summary(summary, join_event.state_key)
|
|
|
|
for hero in heroes:
|
|
|
|
membership_event_id = prev_state_ids.get((EventTypes.Member, hero))
|
|
|
|
if membership_event_id:
|
|
|
|
state_event_ids.add(membership_event_id)
|
2022-02-12 05:44:16 -05:00
|
|
|
|
|
|
|
return state_event_ids
|