federation_server.py 28 KB

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