_base.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from twisted.internet import defer
  17. import synapse.types
  18. from synapse.api.constants import EventTypes, Membership
  19. from synapse.api.errors import LimitExceededError
  20. from synapse.types import UserID
  21. logger = logging.getLogger(__name__)
  22. class BaseHandler(object):
  23. """
  24. Common base class for the event handlers.
  25. Attributes:
  26. store (synapse.storage.DataStore):
  27. state_handler (synapse.state.StateHandler):
  28. """
  29. def __init__(self, hs):
  30. """
  31. Args:
  32. hs (synapse.server.HomeServer):
  33. """
  34. self.store = hs.get_datastore()
  35. self.auth = hs.get_auth()
  36. self.notifier = hs.get_notifier()
  37. self.state_handler = hs.get_state_handler()
  38. self.distributor = hs.get_distributor()
  39. self.ratelimiter = hs.get_ratelimiter()
  40. self.clock = hs.get_clock()
  41. self.hs = hs
  42. self.server_name = hs.hostname
  43. self.event_builder_factory = hs.get_event_builder_factory()
  44. @defer.inlineCallbacks
  45. def ratelimit(self, requester, update=True):
  46. """Ratelimits requests.
  47. Args:
  48. requester (Requester)
  49. update (bool): Whether to record that a request is being processed.
  50. Set to False when doing multiple checks for one request (e.g.
  51. to check up front if we would reject the request), and set to
  52. True for the last call for a given request.
  53. Raises:
  54. LimitExceededError if the request should be ratelimited
  55. """
  56. time_now = self.clock.time()
  57. user_id = requester.user.to_string()
  58. # The AS user itself is never rate limited.
  59. app_service = self.store.get_app_service_by_user_id(user_id)
  60. if app_service is not None:
  61. return # do not ratelimit app service senders
  62. # Disable rate limiting of users belonging to any AS that is configured
  63. # not to be rate limited in its registration file (rate_limited: true|false).
  64. if requester.app_service and not requester.app_service.is_rate_limited():
  65. return
  66. # Check if there is a per user override in the DB.
  67. override = yield self.store.get_ratelimit_for_user(user_id)
  68. if override:
  69. # If overriden with a null Hz then ratelimiting has been entirely
  70. # disabled for the user
  71. if not override.messages_per_second:
  72. return
  73. messages_per_second = override.messages_per_second
  74. burst_count = override.burst_count
  75. else:
  76. messages_per_second = self.hs.config.rc_messages_per_second
  77. burst_count = self.hs.config.rc_message_burst_count
  78. allowed, time_allowed = self.ratelimiter.send_message(
  79. user_id, time_now,
  80. msg_rate_hz=messages_per_second,
  81. burst_count=burst_count,
  82. update=update,
  83. )
  84. if not allowed:
  85. raise LimitExceededError(
  86. retry_after_ms=int(1000 * (time_allowed - time_now)),
  87. )
  88. @defer.inlineCallbacks
  89. def maybe_kick_guest_users(self, event, context=None):
  90. # Technically this function invalidates current_state by changing it.
  91. # Hopefully this isn't that important to the caller.
  92. if event.type == EventTypes.GuestAccess:
  93. guest_access = event.content.get("guest_access", "forbidden")
  94. if guest_access != "can_join":
  95. if context:
  96. current_state = yield self.store.get_events(
  97. list(context.current_state_ids.values())
  98. )
  99. else:
  100. current_state = yield self.state_handler.get_current_state(
  101. event.room_id
  102. )
  103. current_state = list(current_state.values())
  104. logger.info("maybe_kick_guest_users %r", current_state)
  105. yield self.kick_guest_users(current_state)
  106. @defer.inlineCallbacks
  107. def kick_guest_users(self, current_state):
  108. for member_event in current_state:
  109. try:
  110. if member_event.type != EventTypes.Member:
  111. continue
  112. target_user = UserID.from_string(member_event.state_key)
  113. if not self.hs.is_mine(target_user):
  114. continue
  115. if member_event.content["membership"] not in {
  116. Membership.JOIN,
  117. Membership.INVITE
  118. }:
  119. continue
  120. if (
  121. "kind" not in member_event.content
  122. or member_event.content["kind"] != "guest"
  123. ):
  124. continue
  125. # We make the user choose to leave, rather than have the
  126. # event-sender kick them. This is partially because we don't
  127. # need to worry about power levels, and partially because guest
  128. # users are a concept which doesn't hugely work over federation,
  129. # and having homeservers have their own users leave keeps more
  130. # of that decision-making and control local to the guest-having
  131. # homeserver.
  132. requester = synapse.types.create_requester(
  133. target_user, is_guest=True)
  134. handler = self.hs.get_room_member_handler()
  135. yield handler.update_membership(
  136. requester,
  137. target_user,
  138. member_event.room_id,
  139. "leave",
  140. ratelimit=False,
  141. )
  142. except Exception as e:
  143. logger.warn("Error kicking guest user: %s" % (e,))