federation_server.py 33 KB

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