federation_server.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. # Copyright 2019 Matrix.org Federation C.I.C
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. from typing import Any, Callable, Dict, List, Match, Optional, Tuple, Union
  19. from canonicaljson import json
  20. from prometheus_client import Counter
  21. from twisted.internet import defer
  22. from twisted.internet.abstract import isIPAddress
  23. from twisted.python import failure
  24. from synapse.api.constants import EventTypes, Membership
  25. from synapse.api.errors import (
  26. AuthError,
  27. Codes,
  28. FederationError,
  29. IncompatibleRoomVersionError,
  30. NotFoundError,
  31. SynapseError,
  32. UnsupportedRoomVersionError,
  33. )
  34. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
  35. from synapse.events import EventBase
  36. from synapse.federation.federation_base import FederationBase, event_from_pdu_json
  37. from synapse.federation.persistence import TransactionActions
  38. from synapse.federation.units import Edu, Transaction
  39. from synapse.http.endpoint import parse_server_name
  40. from synapse.logging.context import (
  41. make_deferred_yieldable,
  42. nested_logging_context,
  43. run_in_background,
  44. )
  45. from synapse.logging.opentracing import log_kv, start_active_span_from_edu, trace
  46. from synapse.logging.utils import log_function
  47. from synapse.replication.http.federation import (
  48. ReplicationFederationSendEduRestServlet,
  49. ReplicationGetQueryRestServlet,
  50. )
  51. from synapse.types import JsonDict, get_domain_from_id
  52. from synapse.util import glob_to_regex, unwrapFirstError
  53. from synapse.util.async_helpers import Linearizer, concurrently_execute
  54. from synapse.util.caches.response_cache import ResponseCache
  55. # when processing incoming transactions, we try to handle multiple rooms in
  56. # parallel, up to this limit.
  57. TRANSACTION_CONCURRENCY_LIMIT = 10
  58. logger = logging.getLogger(__name__)
  59. received_pdus_counter = Counter("synapse_federation_server_received_pdus", "")
  60. received_edus_counter = Counter("synapse_federation_server_received_edus", "")
  61. received_queries_counter = Counter(
  62. "synapse_federation_server_received_queries", "", ["type"]
  63. )
  64. class FederationServer(FederationBase):
  65. def __init__(self, hs):
  66. super(FederationServer, self).__init__(hs)
  67. self.auth = hs.get_auth()
  68. self.handler = hs.get_handlers().federation_handler
  69. self.state = hs.get_state_handler()
  70. self.device_handler = hs.get_device_handler()
  71. self._server_linearizer = Linearizer("fed_server")
  72. self._transaction_linearizer = Linearizer("fed_txn_handler")
  73. self.transaction_actions = TransactionActions(self.store)
  74. self.registry = hs.get_federation_registry()
  75. # We cache responses to state queries, as they take a while and often
  76. # come in waves.
  77. self._state_resp_cache = ResponseCache(hs, "state_resp", timeout_ms=30000)
  78. async def on_backfill_request(
  79. self, origin: str, room_id: str, versions: List[str], limit: int
  80. ) -> Tuple[int, Dict[str, Any]]:
  81. with (await self._server_linearizer.queue((origin, room_id))):
  82. origin_host, _ = parse_server_name(origin)
  83. await self.check_server_matches_acl(origin_host, room_id)
  84. pdus = await self.handler.on_backfill_request(
  85. origin, room_id, versions, limit
  86. )
  87. res = self._transaction_from_pdus(pdus).get_dict()
  88. return 200, res
  89. async def on_incoming_transaction(
  90. self, origin: str, transaction_data: JsonDict
  91. ) -> Tuple[int, Dict[str, Any]]:
  92. # keep this as early as possible to make the calculated origin ts as
  93. # accurate as possible.
  94. request_time = self._clock.time_msec()
  95. transaction = Transaction(**transaction_data)
  96. if not transaction.transaction_id: # type: ignore
  97. raise Exception("Transaction missing transaction_id")
  98. logger.debug("[%s] Got transaction", transaction.transaction_id) # type: ignore
  99. # use a linearizer to ensure that we don't process the same transaction
  100. # multiple times in parallel.
  101. with (
  102. await self._transaction_linearizer.queue(
  103. (origin, transaction.transaction_id) # type: ignore
  104. )
  105. ):
  106. result = await self._handle_incoming_transaction(
  107. origin, transaction, request_time
  108. )
  109. return result
  110. async def _handle_incoming_transaction(
  111. self, origin: str, transaction: Transaction, request_time: int
  112. ) -> Tuple[int, Dict[str, Any]]:
  113. """ Process an incoming transaction and return the HTTP response
  114. Args:
  115. origin: the server making the request
  116. transaction: incoming transaction
  117. request_time: timestamp that the HTTP request arrived at
  118. Returns:
  119. HTTP response code and body
  120. """
  121. response = await self.transaction_actions.have_responded(origin, transaction)
  122. if response:
  123. logger.debug(
  124. "[%s] We've already responded to this request",
  125. transaction.transaction_id, # type: ignore
  126. )
  127. return response
  128. logger.debug("[%s] Transaction is new", transaction.transaction_id) # type: ignore
  129. # Reject if PDU count > 50 or EDU count > 100
  130. if len(transaction.pdus) > 50 or ( # type: ignore
  131. hasattr(transaction, "edus") and len(transaction.edus) > 100 # type: ignore
  132. ):
  133. logger.info("Transaction PDU or EDU count too large. Returning 400")
  134. response = {}
  135. await self.transaction_actions.set_response(
  136. origin, transaction, 400, response
  137. )
  138. return 400, response
  139. # We process PDUs and EDUs in parallel. This is important as we don't
  140. # want to block things like to device messages from reaching clients
  141. # behind the potentially expensive handling of PDUs.
  142. pdu_results, _ = await make_deferred_yieldable(
  143. defer.gatherResults(
  144. [
  145. run_in_background(
  146. self._handle_pdus_in_txn, origin, transaction, request_time
  147. ),
  148. run_in_background(self._handle_edus_in_txn, origin, transaction),
  149. ],
  150. consumeErrors=True,
  151. ).addErrback(unwrapFirstError)
  152. )
  153. response = {"pdus": pdu_results}
  154. logger.debug("Returning: %s", str(response))
  155. await self.transaction_actions.set_response(origin, transaction, 200, response)
  156. return 200, response
  157. async def _handle_pdus_in_txn(
  158. self, origin: str, transaction: Transaction, request_time: int
  159. ) -> Dict[str, dict]:
  160. """Process the PDUs in a received transaction.
  161. Args:
  162. origin: the server making the request
  163. transaction: incoming transaction
  164. request_time: timestamp that the HTTP request arrived at
  165. Returns:
  166. A map from event ID of a processed PDU to any errors we should
  167. report back to the sending server.
  168. """
  169. received_pdus_counter.inc(len(transaction.pdus)) # type: ignore
  170. origin_host, _ = parse_server_name(origin)
  171. pdus_by_room = {} # type: Dict[str, List[EventBase]]
  172. for p in transaction.pdus: # type: ignore
  173. if "unsigned" in p:
  174. unsigned = p["unsigned"]
  175. if "age" in unsigned:
  176. p["age"] = unsigned["age"]
  177. if "age" in p:
  178. p["age_ts"] = request_time - int(p["age"])
  179. del p["age"]
  180. # We try and pull out an event ID so that if later checks fail we
  181. # can log something sensible. We don't mandate an event ID here in
  182. # case future event formats get rid of the key.
  183. possible_event_id = p.get("event_id", "<Unknown>")
  184. # Now we get the room ID so that we can check that we know the
  185. # version of the room.
  186. room_id = p.get("room_id")
  187. if not room_id:
  188. logger.info(
  189. "Ignoring PDU as does not have a room_id. Event ID: %s",
  190. possible_event_id,
  191. )
  192. continue
  193. try:
  194. room_version = await self.store.get_room_version(room_id)
  195. except NotFoundError:
  196. logger.info("Ignoring PDU for unknown room_id: %s", room_id)
  197. continue
  198. except UnsupportedRoomVersionError as e:
  199. # this can happen if support for a given room version is withdrawn,
  200. # so that we still get events for said room.
  201. logger.info("Ignoring PDU: %s", e)
  202. continue
  203. event = event_from_pdu_json(p, room_version)
  204. pdus_by_room.setdefault(room_id, []).append(event)
  205. pdu_results = {}
  206. # we can process different rooms in parallel (which is useful if they
  207. # require callouts to other servers to fetch missing events), but
  208. # impose a limit to avoid going too crazy with ram/cpu.
  209. async def process_pdus_for_room(room_id: str):
  210. logger.debug("Processing PDUs for %s", room_id)
  211. try:
  212. await self.check_server_matches_acl(origin_host, room_id)
  213. except AuthError as e:
  214. logger.warning("Ignoring PDUs for room %s from banned server", room_id)
  215. for pdu in pdus_by_room[room_id]:
  216. event_id = pdu.event_id
  217. pdu_results[event_id] = e.error_dict()
  218. return
  219. for pdu in pdus_by_room[room_id]:
  220. event_id = pdu.event_id
  221. with nested_logging_context(event_id):
  222. try:
  223. await self._handle_received_pdu(origin, pdu)
  224. pdu_results[event_id] = {}
  225. except FederationError as e:
  226. logger.warning("Error handling PDU %s: %s", event_id, e)
  227. pdu_results[event_id] = {"error": str(e)}
  228. except Exception as e:
  229. f = failure.Failure()
  230. pdu_results[event_id] = {"error": str(e)}
  231. logger.error(
  232. "Failed to handle PDU %s",
  233. event_id,
  234. exc_info=(f.type, f.value, f.getTracebackObject()),
  235. )
  236. await concurrently_execute(
  237. process_pdus_for_room, pdus_by_room.keys(), TRANSACTION_CONCURRENCY_LIMIT
  238. )
  239. return pdu_results
  240. async def _handle_edus_in_txn(self, origin: str, transaction: Transaction):
  241. """Process the EDUs in a received transaction.
  242. """
  243. async def _process_edu(edu_dict):
  244. received_edus_counter.inc()
  245. edu = Edu(
  246. origin=origin,
  247. destination=self.server_name,
  248. edu_type=edu_dict["edu_type"],
  249. content=edu_dict["content"],
  250. )
  251. await self.registry.on_edu(edu.edu_type, origin, edu.content)
  252. await concurrently_execute(
  253. _process_edu,
  254. getattr(transaction, "edus", []),
  255. TRANSACTION_CONCURRENCY_LIMIT,
  256. )
  257. async def on_context_state_request(
  258. self, origin: str, room_id: str, event_id: str
  259. ) -> Tuple[int, Dict[str, Any]]:
  260. origin_host, _ = parse_server_name(origin)
  261. await self.check_server_matches_acl(origin_host, room_id)
  262. in_room = await self.auth.check_host_in_room(room_id, origin)
  263. if not in_room:
  264. raise AuthError(403, "Host not in room.")
  265. # we grab the linearizer to protect ourselves from servers which hammer
  266. # us. In theory we might already have the response to this query
  267. # in the cache so we could return it without waiting for the linearizer
  268. # - but that's non-trivial to get right, and anyway somewhat defeats
  269. # the point of the linearizer.
  270. with (await self._server_linearizer.queue((origin, room_id))):
  271. resp = dict(
  272. await self._state_resp_cache.wrap(
  273. (room_id, event_id),
  274. self._on_context_state_request_compute,
  275. room_id,
  276. event_id,
  277. )
  278. )
  279. room_version = await self.store.get_room_version_id(room_id)
  280. resp["room_version"] = room_version
  281. return 200, resp
  282. async def on_state_ids_request(
  283. self, origin: str, room_id: str, event_id: str
  284. ) -> Tuple[int, Dict[str, Any]]:
  285. if not event_id:
  286. raise NotImplementedError("Specify an event")
  287. origin_host, _ = parse_server_name(origin)
  288. await self.check_server_matches_acl(origin_host, room_id)
  289. in_room = await self.auth.check_host_in_room(room_id, origin)
  290. if not in_room:
  291. raise AuthError(403, "Host not in room.")
  292. state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
  293. auth_chain_ids = await self.store.get_auth_chain_ids(state_ids)
  294. return 200, {"pdu_ids": state_ids, "auth_chain_ids": auth_chain_ids}
  295. async def _on_context_state_request_compute(
  296. self, room_id: str, event_id: str
  297. ) -> Dict[str, list]:
  298. if event_id:
  299. pdus = await self.handler.get_state_for_pdu(room_id, event_id)
  300. else:
  301. pdus = (await self.state.get_current_state(room_id)).values()
  302. auth_chain = await self.store.get_auth_chain([pdu.event_id for pdu in pdus])
  303. return {
  304. "pdus": [pdu.get_pdu_json() for pdu in pdus],
  305. "auth_chain": [pdu.get_pdu_json() for pdu in auth_chain],
  306. }
  307. async def on_pdu_request(
  308. self, origin: str, event_id: str
  309. ) -> Tuple[int, Union[JsonDict, str]]:
  310. pdu = await self.handler.get_persisted_pdu(origin, event_id)
  311. if pdu:
  312. return 200, self._transaction_from_pdus([pdu]).get_dict()
  313. else:
  314. return 404, ""
  315. async def on_query_request(
  316. self, query_type: str, args: Dict[str, str]
  317. ) -> Tuple[int, Dict[str, Any]]:
  318. received_queries_counter.labels(query_type).inc()
  319. resp = await self.registry.on_query(query_type, args)
  320. return 200, resp
  321. async def on_make_join_request(
  322. self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
  323. ) -> Dict[str, Any]:
  324. origin_host, _ = parse_server_name(origin)
  325. await self.check_server_matches_acl(origin_host, room_id)
  326. room_version = await self.store.get_room_version_id(room_id)
  327. if room_version not in supported_versions:
  328. logger.warning(
  329. "Room version %s not in %s", room_version, supported_versions
  330. )
  331. raise IncompatibleRoomVersionError(room_version=room_version)
  332. pdu = await self.handler.on_make_join_request(origin, room_id, user_id)
  333. time_now = self._clock.time_msec()
  334. return {"event": pdu.get_pdu_json(time_now), "room_version": room_version}
  335. async def on_invite_request(
  336. self, origin: str, content: JsonDict, room_version_id: str
  337. ) -> Dict[str, Any]:
  338. room_version = KNOWN_ROOM_VERSIONS.get(room_version_id)
  339. if not room_version:
  340. raise SynapseError(
  341. 400,
  342. "Homeserver does not support this room version",
  343. Codes.UNSUPPORTED_ROOM_VERSION,
  344. )
  345. pdu = event_from_pdu_json(content, room_version)
  346. origin_host, _ = parse_server_name(origin)
  347. await self.check_server_matches_acl(origin_host, pdu.room_id)
  348. pdu = await self._check_sigs_and_hash(room_version, pdu)
  349. ret_pdu = await self.handler.on_invite_request(origin, pdu, room_version)
  350. time_now = self._clock.time_msec()
  351. return {"event": ret_pdu.get_pdu_json(time_now)}
  352. async def on_send_join_request(
  353. self, origin: str, content: JsonDict, room_id: str
  354. ) -> Dict[str, Any]:
  355. logger.debug("on_send_join_request: content: %s", content)
  356. room_version = await self.store.get_room_version(room_id)
  357. pdu = event_from_pdu_json(content, room_version)
  358. origin_host, _ = parse_server_name(origin)
  359. await self.check_server_matches_acl(origin_host, pdu.room_id)
  360. logger.debug("on_send_join_request: pdu sigs: %s", pdu.signatures)
  361. pdu = await self._check_sigs_and_hash(room_version, pdu)
  362. res_pdus = await self.handler.on_send_join_request(origin, pdu)
  363. time_now = self._clock.time_msec()
  364. return {
  365. "state": [p.get_pdu_json(time_now) for p in res_pdus["state"]],
  366. "auth_chain": [p.get_pdu_json(time_now) for p in res_pdus["auth_chain"]],
  367. }
  368. async def on_make_leave_request(
  369. self, origin: str, room_id: str, user_id: str
  370. ) -> Dict[str, Any]:
  371. origin_host, _ = parse_server_name(origin)
  372. await self.check_server_matches_acl(origin_host, room_id)
  373. pdu = await self.handler.on_make_leave_request(origin, room_id, user_id)
  374. room_version = await self.store.get_room_version_id(room_id)
  375. time_now = self._clock.time_msec()
  376. return {"event": pdu.get_pdu_json(time_now), "room_version": room_version}
  377. async def on_send_leave_request(
  378. self, origin: str, content: JsonDict, room_id: str
  379. ) -> dict:
  380. logger.debug("on_send_leave_request: content: %s", content)
  381. room_version = await self.store.get_room_version(room_id)
  382. pdu = event_from_pdu_json(content, room_version)
  383. origin_host, _ = parse_server_name(origin)
  384. await self.check_server_matches_acl(origin_host, pdu.room_id)
  385. logger.debug("on_send_leave_request: pdu sigs: %s", pdu.signatures)
  386. pdu = await self._check_sigs_and_hash(room_version, pdu)
  387. await self.handler.on_send_leave_request(origin, pdu)
  388. return {}
  389. async def on_event_auth(
  390. self, origin: str, room_id: str, event_id: str
  391. ) -> Tuple[int, Dict[str, Any]]:
  392. with (await self._server_linearizer.queue((origin, room_id))):
  393. origin_host, _ = parse_server_name(origin)
  394. await self.check_server_matches_acl(origin_host, room_id)
  395. time_now = self._clock.time_msec()
  396. auth_pdus = await self.handler.on_event_auth(event_id)
  397. res = {"auth_chain": [a.get_pdu_json(time_now) for a in auth_pdus]}
  398. return 200, res
  399. @log_function
  400. async def on_query_client_keys(
  401. self, origin: str, content: Dict[str, str]
  402. ) -> Tuple[int, Dict[str, Any]]:
  403. return await self.on_query_request("client_keys", content)
  404. async def on_query_user_devices(
  405. self, origin: str, user_id: str
  406. ) -> Tuple[int, Dict[str, Any]]:
  407. keys = await self.device_handler.on_federation_query_user_devices(user_id)
  408. return 200, keys
  409. @trace
  410. async def on_claim_client_keys(
  411. self, origin: str, content: JsonDict
  412. ) -> Dict[str, Any]:
  413. query = []
  414. for user_id, device_keys in content.get("one_time_keys", {}).items():
  415. for device_id, algorithm in device_keys.items():
  416. query.append((user_id, device_id, algorithm))
  417. log_kv({"message": "Claiming one time keys.", "user, device pairs": query})
  418. results = await self.store.claim_e2e_one_time_keys(query)
  419. json_result = {} # type: Dict[str, Dict[str, dict]]
  420. for user_id, device_keys in results.items():
  421. for device_id, keys in device_keys.items():
  422. for key_id, json_bytes in keys.items():
  423. json_result.setdefault(user_id, {})[device_id] = {
  424. key_id: json.loads(json_bytes)
  425. }
  426. logger.info(
  427. "Claimed one-time-keys: %s",
  428. ",".join(
  429. (
  430. "%s for %s:%s" % (key_id, user_id, device_id)
  431. for user_id, user_keys in json_result.items()
  432. for device_id, device_keys in user_keys.items()
  433. for key_id, _ in device_keys.items()
  434. )
  435. ),
  436. )
  437. return {"one_time_keys": json_result}
  438. async def on_get_missing_events(
  439. self,
  440. origin: str,
  441. room_id: str,
  442. earliest_events: List[str],
  443. latest_events: List[str],
  444. limit: int,
  445. ) -> Dict[str, list]:
  446. with (await self._server_linearizer.queue((origin, room_id))):
  447. origin_host, _ = parse_server_name(origin)
  448. await self.check_server_matches_acl(origin_host, room_id)
  449. logger.debug(
  450. "on_get_missing_events: earliest_events: %r, latest_events: %r,"
  451. " limit: %d",
  452. earliest_events,
  453. latest_events,
  454. limit,
  455. )
  456. missing_events = await self.handler.on_get_missing_events(
  457. origin, room_id, earliest_events, latest_events, limit
  458. )
  459. if len(missing_events) < 5:
  460. logger.debug(
  461. "Returning %d events: %r", len(missing_events), missing_events
  462. )
  463. else:
  464. logger.debug("Returning %d events", len(missing_events))
  465. time_now = self._clock.time_msec()
  466. return {"events": [ev.get_pdu_json(time_now) for ev in missing_events]}
  467. @log_function
  468. async def on_openid_userinfo(self, token: str) -> Optional[str]:
  469. ts_now_ms = self._clock.time_msec()
  470. return await self.store.get_user_id_for_open_id_token(token, ts_now_ms)
  471. def _transaction_from_pdus(self, pdu_list: List[EventBase]) -> Transaction:
  472. """Returns a new Transaction containing the given PDUs suitable for
  473. transmission.
  474. """
  475. time_now = self._clock.time_msec()
  476. pdus = [p.get_pdu_json(time_now) for p in pdu_list]
  477. return Transaction(
  478. origin=self.server_name,
  479. pdus=pdus,
  480. origin_server_ts=int(time_now),
  481. destination=None,
  482. )
  483. async def _handle_received_pdu(self, origin: str, pdu: EventBase) -> None:
  484. """ Process a PDU received in a federation /send/ transaction.
  485. If the event is invalid, then this method throws a FederationError.
  486. (The error will then be logged and sent back to the sender (which
  487. probably won't do anything with it), and other events in the
  488. transaction will be processed as normal).
  489. It is likely that we'll then receive other events which refer to
  490. this rejected_event in their prev_events, etc. When that happens,
  491. we'll attempt to fetch the rejected event again, which will presumably
  492. fail, so those second-generation events will also get rejected.
  493. Eventually, we get to the point where there are more than 10 events
  494. between any new events and the original rejected event. Since we
  495. only try to backfill 10 events deep on received pdu, we then accept the
  496. new event, possibly introducing a discontinuity in the DAG, with new
  497. forward extremities, so normal service is approximately returned,
  498. until we try to backfill across the discontinuity.
  499. Args:
  500. origin: server which sent the pdu
  501. pdu: received pdu
  502. Raises: FederationError if the signatures / hash do not match, or
  503. if the event was unacceptable for any other reason (eg, too large,
  504. too many prev_events, couldn't find the prev_events)
  505. """
  506. # check that it's actually being sent from a valid destination to
  507. # workaround bug #1753 in 0.18.5 and 0.18.6
  508. if origin != get_domain_from_id(pdu.sender):
  509. # We continue to accept join events from any server; this is
  510. # necessary for the federation join dance to work correctly.
  511. # (When we join over federation, the "helper" server is
  512. # responsible for sending out the join event, rather than the
  513. # origin. See bug #1893. This is also true for some third party
  514. # invites).
  515. if not (
  516. pdu.type == "m.room.member"
  517. and pdu.content
  518. and pdu.content.get("membership", None)
  519. in (Membership.JOIN, Membership.INVITE)
  520. ):
  521. logger.info(
  522. "Discarding PDU %s from invalid origin %s", pdu.event_id, origin
  523. )
  524. return
  525. else:
  526. logger.info("Accepting join PDU %s from %s", pdu.event_id, origin)
  527. # We've already checked that we know the room version by this point
  528. room_version = await self.store.get_room_version(pdu.room_id)
  529. # Check signature.
  530. try:
  531. pdu = await self._check_sigs_and_hash(room_version, pdu)
  532. except SynapseError as e:
  533. raise FederationError("ERROR", e.code, e.msg, affected=pdu.event_id)
  534. await self.handler.on_receive_pdu(origin, pdu, sent_to_us_directly=True)
  535. def __str__(self):
  536. return "<ReplicationLayer(%s)>" % self.server_name
  537. async def exchange_third_party_invite(
  538. self, sender_user_id: str, target_user_id: str, room_id: str, signed: Dict
  539. ):
  540. ret = await self.handler.exchange_third_party_invite(
  541. sender_user_id, target_user_id, room_id, signed
  542. )
  543. return ret
  544. async def on_exchange_third_party_invite_request(
  545. self, room_id: str, event_dict: Dict
  546. ):
  547. ret = await self.handler.on_exchange_third_party_invite_request(
  548. room_id, event_dict
  549. )
  550. return ret
  551. async def check_server_matches_acl(self, server_name: str, room_id: str):
  552. """Check if the given server is allowed by the server ACLs in the room
  553. Args:
  554. server_name: name of server, *without any port part*
  555. room_id: ID of the room to check
  556. Raises:
  557. AuthError if the server does not match the ACL
  558. """
  559. state_ids = await self.store.get_current_state_ids(room_id)
  560. acl_event_id = state_ids.get((EventTypes.ServerACL, ""))
  561. if not acl_event_id:
  562. return
  563. acl_event = await self.store.get_event(acl_event_id)
  564. if server_matches_acl_event(server_name, acl_event):
  565. return
  566. raise AuthError(code=403, msg="Server is banned from room")
  567. def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool:
  568. """Check if the given server is allowed by the ACL event
  569. Args:
  570. server_name: name of server, without any port part
  571. acl_event: m.room.server_acl event
  572. Returns:
  573. True if this server is allowed by the ACLs
  574. """
  575. logger.debug("Checking %s against acl %s", server_name, acl_event.content)
  576. # first of all, check if literal IPs are blocked, and if so, whether the
  577. # server name is a literal IP
  578. allow_ip_literals = acl_event.content.get("allow_ip_literals", True)
  579. if not isinstance(allow_ip_literals, bool):
  580. logger.warning("Ignorning non-bool allow_ip_literals flag")
  581. allow_ip_literals = True
  582. if not allow_ip_literals:
  583. # check for ipv6 literals. These start with '['.
  584. if server_name[0] == "[":
  585. return False
  586. # check for ipv4 literals. We can just lift the routine from twisted.
  587. if isIPAddress(server_name):
  588. return False
  589. # next, check the deny list
  590. deny = acl_event.content.get("deny", [])
  591. if not isinstance(deny, (list, tuple)):
  592. logger.warning("Ignorning non-list deny ACL %s", deny)
  593. deny = []
  594. for e in deny:
  595. if _acl_entry_matches(server_name, e):
  596. # logger.info("%s matched deny rule %s", server_name, e)
  597. return False
  598. # then the allow list.
  599. allow = acl_event.content.get("allow", [])
  600. if not isinstance(allow, (list, tuple)):
  601. logger.warning("Ignorning non-list allow ACL %s", allow)
  602. allow = []
  603. for e in allow:
  604. if _acl_entry_matches(server_name, e):
  605. # logger.info("%s matched allow rule %s", server_name, e)
  606. return True
  607. # everything else should be rejected.
  608. # logger.info("%s fell through", server_name)
  609. return False
  610. def _acl_entry_matches(server_name: str, acl_entry: str) -> Match:
  611. if not isinstance(acl_entry, str):
  612. logger.warning(
  613. "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry)
  614. )
  615. return False
  616. regex = glob_to_regex(acl_entry)
  617. return regex.match(server_name)
  618. class FederationHandlerRegistry(object):
  619. """Allows classes to register themselves as handlers for a given EDU or
  620. query type for incoming federation traffic.
  621. """
  622. def __init__(self):
  623. self.edu_handlers = {}
  624. self.query_handlers = {}
  625. def register_edu_handler(self, edu_type: str, handler: Callable[[str, dict], None]):
  626. """Sets the handler callable that will be used to handle an incoming
  627. federation EDU of the given type.
  628. Args:
  629. edu_type: The type of the incoming EDU to register handler for
  630. handler: A callable invoked on incoming EDU
  631. of the given type. The arguments are the origin server name and
  632. the EDU contents.
  633. """
  634. if edu_type in self.edu_handlers:
  635. raise KeyError("Already have an EDU handler for %s" % (edu_type,))
  636. logger.info("Registering federation EDU handler for %r", edu_type)
  637. self.edu_handlers[edu_type] = handler
  638. def register_query_handler(
  639. self, query_type: str, handler: Callable[[dict], defer.Deferred]
  640. ):
  641. """Sets the handler callable that will be used to handle an incoming
  642. federation query of the given type.
  643. Args:
  644. query_type: Category name of the query, which should match
  645. the string used by make_query.
  646. handler: Invoked to handle
  647. incoming queries of this type. The return will be yielded
  648. on and the result used as the response to the query request.
  649. """
  650. if query_type in self.query_handlers:
  651. raise KeyError("Already have a Query handler for %s" % (query_type,))
  652. logger.info("Registering federation query handler for %r", query_type)
  653. self.query_handlers[query_type] = handler
  654. async def on_edu(self, edu_type: str, origin: str, content: dict):
  655. handler = self.edu_handlers.get(edu_type)
  656. if not handler:
  657. logger.warning("No handler registered for EDU type %s", edu_type)
  658. return
  659. with start_active_span_from_edu(content, "handle_edu"):
  660. try:
  661. await handler(origin, content)
  662. except SynapseError as e:
  663. logger.info("Failed to handle edu %r: %r", edu_type, e)
  664. except Exception:
  665. logger.exception("Failed to handle edu %r", edu_type)
  666. def on_query(self, query_type: str, args: dict) -> defer.Deferred:
  667. handler = self.query_handlers.get(query_type)
  668. if not handler:
  669. logger.warning("No handler registered for query type %s", query_type)
  670. raise NotFoundError("No handler for Query type '%s'" % (query_type,))
  671. return handler(args)
  672. class ReplicationFederationHandlerRegistry(FederationHandlerRegistry):
  673. """A FederationHandlerRegistry for worker processes.
  674. When receiving EDU or queries it will check if an appropriate handler has
  675. been registered on the worker, if there isn't one then it calls off to the
  676. master process.
  677. """
  678. def __init__(self, hs):
  679. self.config = hs.config
  680. self.http_client = hs.get_simple_http_client()
  681. self.clock = hs.get_clock()
  682. self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
  683. self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)
  684. super(ReplicationFederationHandlerRegistry, self).__init__()
  685. async def on_edu(self, edu_type: str, origin: str, content: dict):
  686. """Overrides FederationHandlerRegistry
  687. """
  688. if not self.config.use_presence and edu_type == "m.presence":
  689. return
  690. handler = self.edu_handlers.get(edu_type)
  691. if handler:
  692. return await super(ReplicationFederationHandlerRegistry, self).on_edu(
  693. edu_type, origin, content
  694. )
  695. return await self._send_edu(edu_type=edu_type, origin=origin, content=content)
  696. async def on_query(self, query_type: str, args: dict):
  697. """Overrides FederationHandlerRegistry
  698. """
  699. handler = self.query_handlers.get(query_type)
  700. if handler:
  701. return await handler(args)
  702. return await self._get_query_client(query_type=query_type, args=args)