federation_server.py 32 KB

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