message.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. # Copyright 2017 - 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. from six import iteritems, itervalues, string_types
  18. from canonicaljson import encode_canonical_json, json
  19. from twisted.internet import defer
  20. from twisted.internet.defer import succeed
  21. from synapse.api.constants import MAX_DEPTH, EventTypes, Membership
  22. from synapse.api.errors import (
  23. AuthError,
  24. Codes,
  25. ConsentNotGivenError,
  26. NotFoundError,
  27. SynapseError,
  28. )
  29. from synapse.api.urls import ConsentURIBuilder
  30. from synapse.crypto.event_signing import add_hashes_and_signatures
  31. from synapse.events.utils import serialize_event
  32. from synapse.events.validator import EventValidator
  33. from synapse.replication.http.send_event import ReplicationSendEventRestServlet
  34. from synapse.storage.state import StateFilter
  35. from synapse.types import RoomAlias, UserID
  36. from synapse.util.async_helpers import Linearizer
  37. from synapse.util.frozenutils import frozendict_json_encoder
  38. from synapse.util.logcontext import run_in_background
  39. from synapse.util.metrics import measure_func
  40. from synapse.visibility import filter_events_for_client
  41. from ._base import BaseHandler
  42. logger = logging.getLogger(__name__)
  43. class MessageHandler(object):
  44. """Contains some read only APIs to get state about a room
  45. """
  46. def __init__(self, hs):
  47. self.auth = hs.get_auth()
  48. self.clock = hs.get_clock()
  49. self.state = hs.get_state_handler()
  50. self.store = hs.get_datastore()
  51. @defer.inlineCallbacks
  52. def get_room_data(self, user_id=None, room_id=None,
  53. event_type=None, state_key="", is_guest=False):
  54. """ Get data from a room.
  55. Args:
  56. event : The room path event
  57. Returns:
  58. The path data content.
  59. Raises:
  60. SynapseError if something went wrong.
  61. """
  62. membership, membership_event_id = yield self.auth.check_in_room_or_world_readable(
  63. room_id, user_id
  64. )
  65. if membership == Membership.JOIN:
  66. data = yield self.state.get_current_state(
  67. room_id, event_type, state_key
  68. )
  69. elif membership == Membership.LEAVE:
  70. key = (event_type, state_key)
  71. room_state = yield self.store.get_state_for_events(
  72. [membership_event_id], StateFilter.from_types([key])
  73. )
  74. data = room_state[membership_event_id].get(key)
  75. defer.returnValue(data)
  76. @defer.inlineCallbacks
  77. def get_state_events(
  78. self, user_id, room_id, state_filter=StateFilter.all(),
  79. at_token=None, is_guest=False,
  80. ):
  81. """Retrieve all state events for a given room. If the user is
  82. joined to the room then return the current state. If the user has
  83. left the room return the state events from when they left. If an explicit
  84. 'at' parameter is passed, return the state events as of that event, if
  85. visible.
  86. Args:
  87. user_id(str): The user requesting state events.
  88. room_id(str): The room ID to get all state events from.
  89. state_filter (StateFilter): The state filter used to fetch state
  90. from the database.
  91. at_token(StreamToken|None): the stream token of the at which we are requesting
  92. the stats. If the user is not allowed to view the state as of that
  93. stream token, we raise a 403 SynapseError. If None, returns the current
  94. state based on the current_state_events table.
  95. is_guest(bool): whether this user is a guest
  96. Returns:
  97. A list of dicts representing state events. [{}, {}, {}]
  98. Raises:
  99. NotFoundError (404) if the at token does not yield an event
  100. AuthError (403) if the user doesn't have permission to view
  101. members of this room.
  102. """
  103. if at_token:
  104. # FIXME this claims to get the state at a stream position, but
  105. # get_recent_events_for_room operates by topo ordering. This therefore
  106. # does not reliably give you the state at the given stream position.
  107. # (https://github.com/matrix-org/synapse/issues/3305)
  108. last_events, _ = yield self.store.get_recent_events_for_room(
  109. room_id, end_token=at_token.room_key, limit=1,
  110. )
  111. if not last_events:
  112. raise NotFoundError("Can't find event for token %s" % (at_token, ))
  113. visible_events = yield filter_events_for_client(
  114. self.store, user_id, last_events,
  115. )
  116. event = last_events[0]
  117. if visible_events:
  118. room_state = yield self.store.get_state_for_events(
  119. [event.event_id], state_filter=state_filter,
  120. )
  121. room_state = room_state[event.event_id]
  122. else:
  123. raise AuthError(
  124. 403,
  125. "User %s not allowed to view events in room %s at token %s" % (
  126. user_id, room_id, at_token,
  127. )
  128. )
  129. else:
  130. membership, membership_event_id = (
  131. yield self.auth.check_in_room_or_world_readable(
  132. room_id, user_id,
  133. )
  134. )
  135. if membership == Membership.JOIN:
  136. state_ids = yield self.store.get_filtered_current_state_ids(
  137. room_id, state_filter=state_filter,
  138. )
  139. room_state = yield self.store.get_events(state_ids.values())
  140. elif membership == Membership.LEAVE:
  141. room_state = yield self.store.get_state_for_events(
  142. [membership_event_id], state_filter=state_filter,
  143. )
  144. room_state = room_state[membership_event_id]
  145. now = self.clock.time_msec()
  146. defer.returnValue(
  147. [serialize_event(c, now) for c in room_state.values()]
  148. )
  149. @defer.inlineCallbacks
  150. def get_joined_members(self, requester, room_id):
  151. """Get all the joined members in the room and their profile information.
  152. If the user has left the room return the state events from when they left.
  153. Args:
  154. requester(Requester): The user requesting state events.
  155. room_id(str): The room ID to get all state events from.
  156. Returns:
  157. A dict of user_id to profile info
  158. """
  159. user_id = requester.user.to_string()
  160. if not requester.app_service:
  161. # We check AS auth after fetching the room membership, as it
  162. # requires us to pull out all joined members anyway.
  163. membership, _ = yield self.auth.check_in_room_or_world_readable(
  164. room_id, user_id
  165. )
  166. if membership != Membership.JOIN:
  167. raise NotImplementedError(
  168. "Getting joined members after leaving is not implemented"
  169. )
  170. users_with_profile = yield self.state.get_current_user_in_room(room_id)
  171. # If this is an AS, double check that they are allowed to see the members.
  172. # This can either be because the AS user is in the room or because there
  173. # is a user in the room that the AS is "interested in"
  174. if requester.app_service and user_id not in users_with_profile:
  175. for uid in users_with_profile:
  176. if requester.app_service.is_interested_in_user(uid):
  177. break
  178. else:
  179. # Loop fell through, AS has no interested users in room
  180. raise AuthError(403, "Appservice not in room")
  181. defer.returnValue({
  182. user_id: {
  183. "avatar_url": profile.avatar_url,
  184. "display_name": profile.display_name,
  185. }
  186. for user_id, profile in iteritems(users_with_profile)
  187. })
  188. class EventCreationHandler(object):
  189. def __init__(self, hs):
  190. self.hs = hs
  191. self.auth = hs.get_auth()
  192. self.store = hs.get_datastore()
  193. self.state = hs.get_state_handler()
  194. self.clock = hs.get_clock()
  195. self.validator = EventValidator()
  196. self.profile_handler = hs.get_profile_handler()
  197. self.event_builder_factory = hs.get_event_builder_factory()
  198. self.server_name = hs.hostname
  199. self.ratelimiter = hs.get_ratelimiter()
  200. self.notifier = hs.get_notifier()
  201. self.config = hs.config
  202. self.send_event_to_master = ReplicationSendEventRestServlet.make_client(hs)
  203. # This is only used to get at ratelimit function, and maybe_kick_guest_users
  204. self.base_handler = BaseHandler(hs)
  205. self.pusher_pool = hs.get_pusherpool()
  206. # We arbitrarily limit concurrent event creation for a room to 5.
  207. # This is to stop us from diverging history *too* much.
  208. self.limiter = Linearizer(max_count=5, name="room_event_creation_limit")
  209. self.action_generator = hs.get_action_generator()
  210. self.spam_checker = hs.get_spam_checker()
  211. if self.config.block_events_without_consent_error is not None:
  212. self._consent_uri_builder = ConsentURIBuilder(self.config)
  213. @defer.inlineCallbacks
  214. def create_event(self, requester, event_dict, token_id=None, txn_id=None,
  215. prev_events_and_hashes=None):
  216. """
  217. Given a dict from a client, create a new event.
  218. Creates an FrozenEvent object, filling out auth_events, prev_events,
  219. etc.
  220. Adds display names to Join membership events.
  221. Args:
  222. requester
  223. event_dict (dict): An entire event
  224. token_id (str)
  225. txn_id (str)
  226. prev_events_and_hashes (list[(str, dict[str, str], int)]|None):
  227. the forward extremities to use as the prev_events for the
  228. new event. For each event, a tuple of (event_id, hashes, depth)
  229. where *hashes* is a map from algorithm to hash.
  230. If None, they will be requested from the database.
  231. Raises:
  232. ResourceLimitError if server is blocked to some resource being
  233. exceeded
  234. Returns:
  235. Tuple of created event (FrozenEvent), Context
  236. """
  237. yield self.auth.check_auth_blocking(requester.user.to_string())
  238. builder = self.event_builder_factory.new(event_dict)
  239. self.validator.validate_new(builder)
  240. if builder.type == EventTypes.Member:
  241. membership = builder.content.get("membership", None)
  242. target = UserID.from_string(builder.state_key)
  243. if membership in {Membership.JOIN, Membership.INVITE}:
  244. # If event doesn't include a display name, add one.
  245. profile = self.profile_handler
  246. content = builder.content
  247. try:
  248. if "displayname" not in content:
  249. content["displayname"] = yield profile.get_displayname(target)
  250. if "avatar_url" not in content:
  251. content["avatar_url"] = yield profile.get_avatar_url(target)
  252. except Exception as e:
  253. logger.info(
  254. "Failed to get profile information for %r: %s",
  255. target, e
  256. )
  257. is_exempt = yield self._is_exempt_from_privacy_policy(builder, requester)
  258. if not is_exempt:
  259. yield self.assert_accepted_privacy_policy(requester)
  260. if token_id is not None:
  261. builder.internal_metadata.token_id = token_id
  262. if txn_id is not None:
  263. builder.internal_metadata.txn_id = txn_id
  264. event, context = yield self.create_new_client_event(
  265. builder=builder,
  266. requester=requester,
  267. prev_events_and_hashes=prev_events_and_hashes,
  268. )
  269. defer.returnValue((event, context))
  270. def _is_exempt_from_privacy_policy(self, builder, requester):
  271. """"Determine if an event to be sent is exempt from having to consent
  272. to the privacy policy
  273. Args:
  274. builder (synapse.events.builder.EventBuilder): event being created
  275. requester (Requster): user requesting this event
  276. Returns:
  277. Deferred[bool]: true if the event can be sent without the user
  278. consenting
  279. """
  280. # the only thing the user can do is join the server notices room.
  281. if builder.type == EventTypes.Member:
  282. membership = builder.content.get("membership", None)
  283. if membership == Membership.JOIN:
  284. return self._is_server_notices_room(builder.room_id)
  285. elif membership == Membership.LEAVE:
  286. # the user is always allowed to leave (but not kick people)
  287. return builder.state_key == requester.user.to_string()
  288. return succeed(False)
  289. @defer.inlineCallbacks
  290. def _is_server_notices_room(self, room_id):
  291. if self.config.server_notices_mxid is None:
  292. defer.returnValue(False)
  293. user_ids = yield self.store.get_users_in_room(room_id)
  294. defer.returnValue(self.config.server_notices_mxid in user_ids)
  295. @defer.inlineCallbacks
  296. def assert_accepted_privacy_policy(self, requester):
  297. """Check if a user has accepted the privacy policy
  298. Called when the given user is about to do something that requires
  299. privacy consent. We see if the user is exempt and otherwise check that
  300. they have given consent. If they have not, a ConsentNotGiven error is
  301. raised.
  302. Args:
  303. requester (synapse.types.Requester):
  304. The user making the request
  305. Returns:
  306. Deferred[None]: returns normally if the user has consented or is
  307. exempt
  308. Raises:
  309. ConsentNotGivenError: if the user has not given consent yet
  310. """
  311. if self.config.block_events_without_consent_error is None:
  312. return
  313. # exempt AS users from needing consent
  314. if requester.app_service is not None:
  315. return
  316. user_id = requester.user.to_string()
  317. # exempt the system notices user
  318. if (
  319. self.config.server_notices_mxid is not None and
  320. user_id == self.config.server_notices_mxid
  321. ):
  322. return
  323. u = yield self.store.get_user_by_id(user_id)
  324. assert u is not None
  325. if u["appservice_id"] is not None:
  326. # users registered by an appservice are exempt
  327. return
  328. if u["consent_version"] == self.config.user_consent_version:
  329. return
  330. consent_uri = self._consent_uri_builder.build_user_consent_uri(
  331. requester.user.localpart,
  332. )
  333. msg = self.config.block_events_without_consent_error % {
  334. 'consent_uri': consent_uri,
  335. }
  336. raise ConsentNotGivenError(
  337. msg=msg,
  338. consent_uri=consent_uri,
  339. )
  340. @defer.inlineCallbacks
  341. def send_nonmember_event(self, requester, event, context, ratelimit=True):
  342. """
  343. Persists and notifies local clients and federation of an event.
  344. Args:
  345. event (FrozenEvent) the event to send.
  346. context (Context) the context of the event.
  347. ratelimit (bool): Whether to rate limit this send.
  348. is_guest (bool): Whether the sender is a guest.
  349. """
  350. if event.type == EventTypes.Member:
  351. raise SynapseError(
  352. 500,
  353. "Tried to send member event through non-member codepath"
  354. )
  355. user = UserID.from_string(event.sender)
  356. assert self.hs.is_mine(user), "User must be our own: %s" % (user,)
  357. if event.is_state():
  358. prev_state = yield self.deduplicate_state_event(event, context)
  359. logger.info(
  360. "Not bothering to persist duplicate state event %s", event.event_id,
  361. )
  362. if prev_state is not None:
  363. defer.returnValue(prev_state)
  364. yield self.handle_new_client_event(
  365. requester=requester,
  366. event=event,
  367. context=context,
  368. ratelimit=ratelimit,
  369. )
  370. @defer.inlineCallbacks
  371. def deduplicate_state_event(self, event, context):
  372. """
  373. Checks whether event is in the latest resolved state in context.
  374. If so, returns the version of the event in context.
  375. Otherwise, returns None.
  376. """
  377. prev_state_ids = yield context.get_prev_state_ids(self.store)
  378. prev_event_id = prev_state_ids.get((event.type, event.state_key))
  379. prev_event = yield self.store.get_event(prev_event_id, allow_none=True)
  380. if not prev_event:
  381. return
  382. if prev_event and event.user_id == prev_event.user_id:
  383. prev_content = encode_canonical_json(prev_event.content)
  384. next_content = encode_canonical_json(event.content)
  385. if prev_content == next_content:
  386. defer.returnValue(prev_event)
  387. return
  388. @defer.inlineCallbacks
  389. def create_and_send_nonmember_event(
  390. self,
  391. requester,
  392. event_dict,
  393. ratelimit=True,
  394. txn_id=None
  395. ):
  396. """
  397. Creates an event, then sends it.
  398. See self.create_event and self.send_nonmember_event.
  399. """
  400. # We limit the number of concurrent event sends in a room so that we
  401. # don't fork the DAG too much. If we don't limit then we can end up in
  402. # a situation where event persistence can't keep up, causing
  403. # extremities to pile up, which in turn leads to state resolution
  404. # taking longer.
  405. with (yield self.limiter.queue(event_dict["room_id"])):
  406. event, context = yield self.create_event(
  407. requester,
  408. event_dict,
  409. token_id=requester.access_token_id,
  410. txn_id=txn_id
  411. )
  412. spam_error = self.spam_checker.check_event_for_spam(event)
  413. if spam_error:
  414. if not isinstance(spam_error, string_types):
  415. spam_error = "Spam is not permitted here"
  416. raise SynapseError(
  417. 403, spam_error, Codes.FORBIDDEN
  418. )
  419. yield self.send_nonmember_event(
  420. requester,
  421. event,
  422. context,
  423. ratelimit=ratelimit,
  424. )
  425. defer.returnValue(event)
  426. @measure_func("create_new_client_event")
  427. @defer.inlineCallbacks
  428. def create_new_client_event(self, builder, requester=None,
  429. prev_events_and_hashes=None):
  430. """Create a new event for a local client
  431. Args:
  432. builder (EventBuilder):
  433. requester (synapse.types.Requester|None):
  434. prev_events_and_hashes (list[(str, dict[str, str], int)]|None):
  435. the forward extremities to use as the prev_events for the
  436. new event. For each event, a tuple of (event_id, hashes, depth)
  437. where *hashes* is a map from algorithm to hash.
  438. If None, they will be requested from the database.
  439. Returns:
  440. Deferred[(synapse.events.EventBase, synapse.events.snapshot.EventContext)]
  441. """
  442. if prev_events_and_hashes is not None:
  443. assert len(prev_events_and_hashes) <= 10, \
  444. "Attempting to create an event with %i prev_events" % (
  445. len(prev_events_and_hashes),
  446. )
  447. else:
  448. prev_events_and_hashes = \
  449. yield self.store.get_prev_events_for_room(builder.room_id)
  450. if prev_events_and_hashes:
  451. depth = max([d for _, _, d in prev_events_and_hashes]) + 1
  452. # we cap depth of generated events, to ensure that they are not
  453. # rejected by other servers (and so that they can be persisted in
  454. # the db)
  455. depth = min(depth, MAX_DEPTH)
  456. else:
  457. depth = 1
  458. prev_events = [
  459. (event_id, prev_hashes)
  460. for event_id, prev_hashes, _ in prev_events_and_hashes
  461. ]
  462. builder.prev_events = prev_events
  463. builder.depth = depth
  464. context = yield self.state.compute_event_context(builder)
  465. if requester:
  466. context.app_service = requester.app_service
  467. if builder.is_state():
  468. builder.prev_state = yield self.store.add_event_hashes(
  469. context.prev_state_events
  470. )
  471. yield self.auth.add_auth_events(builder, context)
  472. signing_key = self.hs.config.signing_key[0]
  473. add_hashes_and_signatures(
  474. builder, self.server_name, signing_key
  475. )
  476. event = builder.build()
  477. logger.debug(
  478. "Created event %s",
  479. event.event_id,
  480. )
  481. defer.returnValue(
  482. (event, context,)
  483. )
  484. @measure_func("handle_new_client_event")
  485. @defer.inlineCallbacks
  486. def handle_new_client_event(
  487. self,
  488. requester,
  489. event,
  490. context,
  491. ratelimit=True,
  492. extra_users=[],
  493. ):
  494. """Processes a new event. This includes checking auth, persisting it,
  495. notifying users, sending to remote servers, etc.
  496. If called from a worker will hit out to the master process for final
  497. processing.
  498. Args:
  499. requester (Requester)
  500. event (FrozenEvent)
  501. context (EventContext)
  502. ratelimit (bool)
  503. extra_users (list(UserID)): Any extra users to notify about event
  504. """
  505. try:
  506. yield self.auth.check_from_context(event, context)
  507. except AuthError as err:
  508. logger.warn("Denying new event %r because %s", event, err)
  509. raise err
  510. # Ensure that we can round trip before trying to persist in db
  511. try:
  512. dump = frozendict_json_encoder.encode(event.content)
  513. json.loads(dump)
  514. except Exception:
  515. logger.exception("Failed to encode content: %r", event.content)
  516. raise
  517. yield self.action_generator.handle_push_actions_for_event(
  518. event, context
  519. )
  520. # reraise does not allow inlineCallbacks to preserve the stacktrace, so we
  521. # hack around with a try/finally instead.
  522. success = False
  523. try:
  524. # If we're a worker we need to hit out to the master.
  525. if self.config.worker_app:
  526. yield self.send_event_to_master(
  527. event_id=event.event_id,
  528. store=self.store,
  529. requester=requester,
  530. event=event,
  531. context=context,
  532. ratelimit=ratelimit,
  533. extra_users=extra_users,
  534. )
  535. success = True
  536. return
  537. yield self.persist_and_notify_client_event(
  538. requester,
  539. event,
  540. context,
  541. ratelimit=ratelimit,
  542. extra_users=extra_users,
  543. )
  544. success = True
  545. finally:
  546. if not success:
  547. # Ensure that we actually remove the entries in the push actions
  548. # staging area, if we calculated them.
  549. run_in_background(
  550. self.store.remove_push_actions_from_staging,
  551. event.event_id,
  552. )
  553. @defer.inlineCallbacks
  554. def persist_and_notify_client_event(
  555. self,
  556. requester,
  557. event,
  558. context,
  559. ratelimit=True,
  560. extra_users=[],
  561. ):
  562. """Called when we have fully built the event, have already
  563. calculated the push actions for the event, and checked auth.
  564. This should only be run on master.
  565. """
  566. assert not self.config.worker_app
  567. if ratelimit:
  568. yield self.base_handler.ratelimit(requester)
  569. yield self.base_handler.maybe_kick_guest_users(event, context)
  570. if event.type == EventTypes.CanonicalAlias:
  571. # Check the alias is acually valid (at this time at least)
  572. room_alias_str = event.content.get("alias", None)
  573. if room_alias_str:
  574. room_alias = RoomAlias.from_string(room_alias_str)
  575. directory_handler = self.hs.get_handlers().directory_handler
  576. mapping = yield directory_handler.get_association(room_alias)
  577. if mapping["room_id"] != event.room_id:
  578. raise SynapseError(
  579. 400,
  580. "Room alias %s does not point to the room" % (
  581. room_alias_str,
  582. )
  583. )
  584. federation_handler = self.hs.get_handlers().federation_handler
  585. if event.type == EventTypes.Member:
  586. if event.content["membership"] == Membership.INVITE:
  587. def is_inviter_member_event(e):
  588. return (
  589. e.type == EventTypes.Member and
  590. e.sender == event.sender
  591. )
  592. current_state_ids = yield context.get_current_state_ids(self.store)
  593. state_to_include_ids = [
  594. e_id
  595. for k, e_id in iteritems(current_state_ids)
  596. if k[0] in self.hs.config.room_invite_state_types
  597. or k == (EventTypes.Member, event.sender)
  598. ]
  599. state_to_include = yield self.store.get_events(state_to_include_ids)
  600. event.unsigned["invite_room_state"] = [
  601. {
  602. "type": e.type,
  603. "state_key": e.state_key,
  604. "content": e.content,
  605. "sender": e.sender,
  606. }
  607. for e in itervalues(state_to_include)
  608. ]
  609. invitee = UserID.from_string(event.state_key)
  610. if not self.hs.is_mine(invitee):
  611. # TODO: Can we add signature from remote server in a nicer
  612. # way? If we have been invited by a remote server, we need
  613. # to get them to sign the event.
  614. returned_invite = yield federation_handler.send_invite(
  615. invitee.domain,
  616. event,
  617. )
  618. event.unsigned.pop("room_state", None)
  619. # TODO: Make sure the signatures actually are correct.
  620. event.signatures.update(
  621. returned_invite.signatures
  622. )
  623. if event.type == EventTypes.Redaction:
  624. prev_state_ids = yield context.get_prev_state_ids(self.store)
  625. auth_events_ids = yield self.auth.compute_auth_events(
  626. event, prev_state_ids, for_verification=True,
  627. )
  628. auth_events = yield self.store.get_events(auth_events_ids)
  629. auth_events = {
  630. (e.type, e.state_key): e for e in auth_events.values()
  631. }
  632. if self.auth.check_redaction(event, auth_events=auth_events):
  633. original_event = yield self.store.get_event(
  634. event.redacts,
  635. check_redacted=False,
  636. get_prev_content=False,
  637. allow_rejected=False,
  638. allow_none=False
  639. )
  640. if event.user_id != original_event.user_id:
  641. raise AuthError(
  642. 403,
  643. "You don't have permission to redact events"
  644. )
  645. if event.type == EventTypes.Create:
  646. prev_state_ids = yield context.get_prev_state_ids(self.store)
  647. if prev_state_ids:
  648. raise AuthError(
  649. 403,
  650. "Changing the room create event is forbidden",
  651. )
  652. (event_stream_id, max_stream_id) = yield self.store.persist_event(
  653. event, context=context
  654. )
  655. yield self.pusher_pool.on_new_notifications(
  656. event_stream_id, max_stream_id,
  657. )
  658. def _notify():
  659. try:
  660. self.notifier.on_new_room_event(
  661. event, event_stream_id, max_stream_id,
  662. extra_users=extra_users
  663. )
  664. except Exception:
  665. logger.exception("Error notifying about new room event")
  666. run_in_background(_notify)
  667. if event.type == EventTypes.Message:
  668. # We don't want to block sending messages on any presence code. This
  669. # matters as sometimes presence code can take a while.
  670. run_in_background(self._bump_active_time, requester.user)
  671. @defer.inlineCallbacks
  672. def _bump_active_time(self, user):
  673. try:
  674. presence = self.hs.get_presence_handler()
  675. yield presence.bump_presence_active_time(user)
  676. except Exception:
  677. logger.exception("Error bumping presence active time")