federation_server.py 34 KB

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