federation_server.py 33 KB

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