device.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. # -*- coding: utf-8 -*-
  2. # Copyright 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 six import iteritems, itervalues
  17. from twisted.internet import defer
  18. from synapse.api import errors
  19. from synapse.api.constants import EventTypes
  20. from synapse.api.errors import FederationDeniedError
  21. from synapse.types import RoomStreamToken, get_domain_from_id
  22. from synapse.util import stringutils
  23. from synapse.util.async_helpers import Linearizer
  24. from synapse.util.caches.expiringcache import ExpiringCache
  25. from synapse.util.metrics import measure_func
  26. from synapse.util.retryutils import NotRetryingDestination
  27. from ._base import BaseHandler
  28. logger = logging.getLogger(__name__)
  29. class DeviceHandler(BaseHandler):
  30. def __init__(self, hs):
  31. super(DeviceHandler, self).__init__(hs)
  32. self.hs = hs
  33. self.state = hs.get_state_handler()
  34. self._auth_handler = hs.get_auth_handler()
  35. self.federation_sender = hs.get_federation_sender()
  36. self._edu_updater = DeviceListEduUpdater(hs, self)
  37. federation_registry = hs.get_federation_registry()
  38. federation_registry.register_edu_handler(
  39. "m.device_list_update", self._edu_updater.incoming_device_list_update,
  40. )
  41. federation_registry.register_query_handler(
  42. "user_devices", self.on_federation_query_user_devices,
  43. )
  44. hs.get_distributor().observe("user_left_room", self.user_left_room)
  45. @defer.inlineCallbacks
  46. def check_device_registered(self, user_id, device_id,
  47. initial_device_display_name=None):
  48. """
  49. If the given device has not been registered, register it with the
  50. supplied display name.
  51. If no device_id is supplied, we make one up.
  52. Args:
  53. user_id (str): @user:id
  54. device_id (str | None): device id supplied by client
  55. initial_device_display_name (str | None): device display name from
  56. client
  57. Returns:
  58. str: device id (generated if none was supplied)
  59. """
  60. if device_id is not None:
  61. new_device = yield self.store.store_device(
  62. user_id=user_id,
  63. device_id=device_id,
  64. initial_device_display_name=initial_device_display_name,
  65. )
  66. if new_device:
  67. yield self.notify_device_update(user_id, [device_id])
  68. defer.returnValue(device_id)
  69. # if the device id is not specified, we'll autogen one, but loop a few
  70. # times in case of a clash.
  71. attempts = 0
  72. while attempts < 5:
  73. device_id = stringutils.random_string(10).upper()
  74. new_device = yield self.store.store_device(
  75. user_id=user_id,
  76. device_id=device_id,
  77. initial_device_display_name=initial_device_display_name,
  78. )
  79. if new_device:
  80. yield self.notify_device_update(user_id, [device_id])
  81. defer.returnValue(device_id)
  82. attempts += 1
  83. raise errors.StoreError(500, "Couldn't generate a device ID.")
  84. @defer.inlineCallbacks
  85. def get_devices_by_user(self, user_id):
  86. """
  87. Retrieve the given user's devices
  88. Args:
  89. user_id (str):
  90. Returns:
  91. defer.Deferred: list[dict[str, X]]: info on each device
  92. """
  93. device_map = yield self.store.get_devices_by_user(user_id)
  94. ips = yield self.store.get_last_client_ip_by_device(
  95. user_id, device_id=None
  96. )
  97. devices = list(device_map.values())
  98. for device in devices:
  99. _update_device_from_client_ips(device, ips)
  100. defer.returnValue(devices)
  101. @defer.inlineCallbacks
  102. def get_device(self, user_id, device_id):
  103. """ Retrieve the given device
  104. Args:
  105. user_id (str):
  106. device_id (str):
  107. Returns:
  108. defer.Deferred: dict[str, X]: info on the device
  109. Raises:
  110. errors.NotFoundError: if the device was not found
  111. """
  112. try:
  113. device = yield self.store.get_device(user_id, device_id)
  114. except errors.StoreError:
  115. raise errors.NotFoundError
  116. ips = yield self.store.get_last_client_ip_by_device(
  117. user_id, device_id,
  118. )
  119. _update_device_from_client_ips(device, ips)
  120. defer.returnValue(device)
  121. @defer.inlineCallbacks
  122. def delete_device(self, user_id, device_id):
  123. """ Delete the given device
  124. Args:
  125. user_id (str):
  126. device_id (str):
  127. Returns:
  128. defer.Deferred:
  129. """
  130. try:
  131. yield self.store.delete_device(user_id, device_id)
  132. except errors.StoreError as e:
  133. if e.code == 404:
  134. # no match
  135. pass
  136. else:
  137. raise
  138. yield self._auth_handler.delete_access_tokens_for_user(
  139. user_id, device_id=device_id,
  140. )
  141. yield self.store.delete_e2e_keys_by_device(
  142. user_id=user_id, device_id=device_id
  143. )
  144. yield self.notify_device_update(user_id, [device_id])
  145. @defer.inlineCallbacks
  146. def delete_all_devices_for_user(self, user_id, except_device_id=None):
  147. """Delete all of the user's devices
  148. Args:
  149. user_id (str):
  150. except_device_id (str|None): optional device id which should not
  151. be deleted
  152. Returns:
  153. defer.Deferred:
  154. """
  155. device_map = yield self.store.get_devices_by_user(user_id)
  156. device_ids = list(device_map)
  157. if except_device_id is not None:
  158. device_ids = [d for d in device_ids if d != except_device_id]
  159. yield self.delete_devices(user_id, device_ids)
  160. @defer.inlineCallbacks
  161. def delete_devices(self, user_id, device_ids):
  162. """ Delete several devices
  163. Args:
  164. user_id (str):
  165. device_ids (List[str]): The list of device IDs to delete
  166. Returns:
  167. defer.Deferred:
  168. """
  169. try:
  170. yield self.store.delete_devices(user_id, device_ids)
  171. except errors.StoreError as e:
  172. if e.code == 404:
  173. # no match
  174. pass
  175. else:
  176. raise
  177. # Delete access tokens and e2e keys for each device. Not optimised as it is not
  178. # considered as part of a critical path.
  179. for device_id in device_ids:
  180. yield self._auth_handler.delete_access_tokens_for_user(
  181. user_id, device_id=device_id,
  182. )
  183. yield self.store.delete_e2e_keys_by_device(
  184. user_id=user_id, device_id=device_id
  185. )
  186. yield self.notify_device_update(user_id, device_ids)
  187. @defer.inlineCallbacks
  188. def update_device(self, user_id, device_id, content):
  189. """ Update the given device
  190. Args:
  191. user_id (str):
  192. device_id (str):
  193. content (dict): body of update request
  194. Returns:
  195. defer.Deferred:
  196. """
  197. try:
  198. yield self.store.update_device(
  199. user_id,
  200. device_id,
  201. new_display_name=content.get("display_name")
  202. )
  203. yield self.notify_device_update(user_id, [device_id])
  204. except errors.StoreError as e:
  205. if e.code == 404:
  206. raise errors.NotFoundError()
  207. else:
  208. raise
  209. @measure_func("notify_device_update")
  210. @defer.inlineCallbacks
  211. def notify_device_update(self, user_id, device_ids):
  212. """Notify that a user's device(s) has changed. Pokes the notifier, and
  213. remote servers if the user is local.
  214. """
  215. users_who_share_room = yield self.store.get_users_who_share_room_with_user(
  216. user_id
  217. )
  218. hosts = set()
  219. if self.hs.is_mine_id(user_id):
  220. hosts.update(get_domain_from_id(u) for u in users_who_share_room)
  221. hosts.discard(self.server_name)
  222. position = yield self.store.add_device_change_to_streams(
  223. user_id, device_ids, list(hosts)
  224. )
  225. room_ids = yield self.store.get_rooms_for_user(user_id)
  226. yield self.notifier.on_new_event(
  227. "device_list_key", position, rooms=room_ids,
  228. )
  229. if hosts:
  230. logger.info("Sending device list update notif to: %r", hosts)
  231. for host in hosts:
  232. self.federation_sender.send_device_messages(host)
  233. @measure_func("device.get_user_ids_changed")
  234. @defer.inlineCallbacks
  235. def get_user_ids_changed(self, user_id, from_token):
  236. """Get list of users that have had the devices updated, or have newly
  237. joined a room, that `user_id` may be interested in.
  238. Args:
  239. user_id (str)
  240. from_token (StreamToken)
  241. """
  242. now_token = yield self.hs.get_event_sources().get_current_token()
  243. room_ids = yield self.store.get_rooms_for_user(user_id)
  244. # First we check if any devices have changed
  245. changed = yield self.store.get_user_whose_devices_changed(
  246. from_token.device_list_key
  247. )
  248. # Then work out if any users have since joined
  249. rooms_changed = self.store.get_rooms_that_changed(room_ids, from_token.room_key)
  250. member_events = yield self.store.get_membership_changes_for_user(
  251. user_id, from_token.room_key, now_token.room_key
  252. )
  253. rooms_changed.update(event.room_id for event in member_events)
  254. stream_ordering = RoomStreamToken.parse_stream_token(
  255. from_token.room_key
  256. ).stream
  257. possibly_changed = set(changed)
  258. possibly_left = set()
  259. for room_id in rooms_changed:
  260. current_state_ids = yield self.store.get_current_state_ids(room_id)
  261. # The user may have left the room
  262. # TODO: Check if they actually did or if we were just invited.
  263. if room_id not in room_ids:
  264. for key, event_id in iteritems(current_state_ids):
  265. etype, state_key = key
  266. if etype != EventTypes.Member:
  267. continue
  268. possibly_left.add(state_key)
  269. continue
  270. # Fetch the current state at the time.
  271. try:
  272. event_ids = yield self.store.get_forward_extremeties_for_room(
  273. room_id, stream_ordering=stream_ordering
  274. )
  275. except errors.StoreError:
  276. # we have purged the stream_ordering index since the stream
  277. # ordering: treat it the same as a new room
  278. event_ids = []
  279. # special-case for an empty prev state: include all members
  280. # in the changed list
  281. if not event_ids:
  282. for key, event_id in iteritems(current_state_ids):
  283. etype, state_key = key
  284. if etype != EventTypes.Member:
  285. continue
  286. possibly_changed.add(state_key)
  287. continue
  288. current_member_id = current_state_ids.get((EventTypes.Member, user_id))
  289. if not current_member_id:
  290. continue
  291. # mapping from event_id -> state_dict
  292. prev_state_ids = yield self.store.get_state_ids_for_events(event_ids)
  293. # Check if we've joined the room? If so we just blindly add all the users to
  294. # the "possibly changed" users.
  295. for state_dict in itervalues(prev_state_ids):
  296. member_event = state_dict.get((EventTypes.Member, user_id), None)
  297. if not member_event or member_event != current_member_id:
  298. for key, event_id in iteritems(current_state_ids):
  299. etype, state_key = key
  300. if etype != EventTypes.Member:
  301. continue
  302. possibly_changed.add(state_key)
  303. break
  304. # If there has been any change in membership, include them in the
  305. # possibly changed list. We'll check if they are joined below,
  306. # and we're not toooo worried about spuriously adding users.
  307. for key, event_id in iteritems(current_state_ids):
  308. etype, state_key = key
  309. if etype != EventTypes.Member:
  310. continue
  311. # check if this member has changed since any of the extremities
  312. # at the stream_ordering, and add them to the list if so.
  313. for state_dict in itervalues(prev_state_ids):
  314. prev_event_id = state_dict.get(key, None)
  315. if not prev_event_id or prev_event_id != event_id:
  316. if state_key != user_id:
  317. possibly_changed.add(state_key)
  318. break
  319. if possibly_changed or possibly_left:
  320. users_who_share_room = yield self.store.get_users_who_share_room_with_user(
  321. user_id
  322. )
  323. # Take the intersection of the users whose devices may have changed
  324. # and those that actually still share a room with the user
  325. possibly_joined = possibly_changed & users_who_share_room
  326. possibly_left = (possibly_changed | possibly_left) - users_who_share_room
  327. else:
  328. possibly_joined = []
  329. possibly_left = []
  330. defer.returnValue({
  331. "changed": list(possibly_joined),
  332. "left": list(possibly_left),
  333. })
  334. @defer.inlineCallbacks
  335. def on_federation_query_user_devices(self, user_id):
  336. stream_id, devices = yield self.store.get_devices_with_keys_by_user(user_id)
  337. defer.returnValue({
  338. "user_id": user_id,
  339. "stream_id": stream_id,
  340. "devices": devices,
  341. })
  342. @defer.inlineCallbacks
  343. def user_left_room(self, user, room_id):
  344. user_id = user.to_string()
  345. room_ids = yield self.store.get_rooms_for_user(user_id)
  346. if not room_ids:
  347. # We no longer share rooms with this user, so we'll no longer
  348. # receive device updates. Mark this in DB.
  349. yield self.store.mark_remote_user_device_list_as_unsubscribed(user_id)
  350. def _update_device_from_client_ips(device, client_ips):
  351. ip = client_ips.get((device["user_id"], device["device_id"]), {})
  352. device.update({
  353. "last_seen_ts": ip.get("last_seen"),
  354. "last_seen_ip": ip.get("ip"),
  355. })
  356. class DeviceListEduUpdater(object):
  357. "Handles incoming device list updates from federation and updates the DB"
  358. def __init__(self, hs, device_handler):
  359. self.store = hs.get_datastore()
  360. self.federation = hs.get_federation_client()
  361. self.clock = hs.get_clock()
  362. self.device_handler = device_handler
  363. self._remote_edu_linearizer = Linearizer(name="remote_device_list")
  364. # user_id -> list of updates waiting to be handled.
  365. self._pending_updates = {}
  366. # Recently seen stream ids. We don't bother keeping these in the DB,
  367. # but they're useful to have them about to reduce the number of spurious
  368. # resyncs.
  369. self._seen_updates = ExpiringCache(
  370. cache_name="device_update_edu",
  371. clock=self.clock,
  372. max_len=10000,
  373. expiry_ms=30 * 60 * 1000,
  374. iterable=True,
  375. )
  376. @defer.inlineCallbacks
  377. def incoming_device_list_update(self, origin, edu_content):
  378. """Called on incoming device list update from federation. Responsible
  379. for parsing the EDU and adding to pending updates list.
  380. """
  381. user_id = edu_content.pop("user_id")
  382. device_id = edu_content.pop("device_id")
  383. stream_id = str(edu_content.pop("stream_id")) # They may come as ints
  384. prev_ids = edu_content.pop("prev_id", [])
  385. prev_ids = [str(p) for p in prev_ids] # They may come as ints
  386. if get_domain_from_id(user_id) != origin:
  387. # TODO: Raise?
  388. logger.warning("Got device list update edu for %r from %r", user_id, origin)
  389. return
  390. room_ids = yield self.store.get_rooms_for_user(user_id)
  391. if not room_ids:
  392. # We don't share any rooms with this user. Ignore update, as we
  393. # probably won't get any further updates.
  394. return
  395. self._pending_updates.setdefault(user_id, []).append(
  396. (device_id, stream_id, prev_ids, edu_content)
  397. )
  398. yield self._handle_device_updates(user_id)
  399. @measure_func("_incoming_device_list_update")
  400. @defer.inlineCallbacks
  401. def _handle_device_updates(self, user_id):
  402. "Actually handle pending updates."
  403. with (yield self._remote_edu_linearizer.queue(user_id)):
  404. pending_updates = self._pending_updates.pop(user_id, [])
  405. if not pending_updates:
  406. # This can happen since we batch updates
  407. return
  408. # Given a list of updates we check if we need to resync. This
  409. # happens if we've missed updates.
  410. resync = yield self._need_to_do_resync(user_id, pending_updates)
  411. if resync:
  412. # Fetch all devices for the user.
  413. origin = get_domain_from_id(user_id)
  414. try:
  415. result = yield self.federation.query_user_devices(origin, user_id)
  416. except NotRetryingDestination:
  417. # TODO: Remember that we are now out of sync and try again
  418. # later
  419. logger.warn(
  420. "Failed to handle device list update for %s,"
  421. " we're not retrying the remote",
  422. user_id,
  423. )
  424. # We abort on exceptions rather than accepting the update
  425. # as otherwise synapse will 'forget' that its device list
  426. # is out of date. If we bail then we will retry the resync
  427. # next time we get a device list update for this user_id.
  428. # This makes it more likely that the device lists will
  429. # eventually become consistent.
  430. return
  431. except FederationDeniedError as e:
  432. logger.info(e)
  433. return
  434. except Exception:
  435. # TODO: Remember that we are now out of sync and try again
  436. # later
  437. logger.exception(
  438. "Failed to handle device list update for %s", user_id
  439. )
  440. return
  441. stream_id = result["stream_id"]
  442. devices = result["devices"]
  443. # If the remote server has more than ~1000 devices for this user
  444. # we assume that something is going horribly wrong (e.g. a bot
  445. # that logs in and creates a new device every time it tries to
  446. # send a message). Maintaining lots of devices per user in the
  447. # cache can cause serious performance issues as if this request
  448. # takes more than 60s to complete, internal replication from the
  449. # inbound federation worker to the synapse master may time out
  450. # causing the inbound federation to fail and causing the remote
  451. # server to retry, causing a DoS. So in this scenario we give
  452. # up on storing the total list of devices and only handle the
  453. # delta instead.
  454. if len(devices) > 1000:
  455. logger.warn(
  456. "Ignoring device list snapshot for %s as it has >1K devs (%d)",
  457. user_id, len(devices)
  458. )
  459. devices = []
  460. yield self.store.update_remote_device_list_cache(
  461. user_id, devices, stream_id,
  462. )
  463. device_ids = [device["device_id"] for device in devices]
  464. yield self.device_handler.notify_device_update(user_id, device_ids)
  465. else:
  466. # Simply update the single device, since we know that is the only
  467. # change (because of the single prev_id matching the current cache)
  468. for device_id, stream_id, prev_ids, content in pending_updates:
  469. yield self.store.update_remote_device_list_cache_entry(
  470. user_id, device_id, content, stream_id,
  471. )
  472. yield self.device_handler.notify_device_update(
  473. user_id, [device_id for device_id, _, _, _ in pending_updates]
  474. )
  475. self._seen_updates.setdefault(user_id, set()).update(
  476. stream_id for _, stream_id, _, _ in pending_updates
  477. )
  478. @defer.inlineCallbacks
  479. def _need_to_do_resync(self, user_id, updates):
  480. """Given a list of updates for a user figure out if we need to do a full
  481. resync, or whether we have enough data that we can just apply the delta.
  482. """
  483. seen_updates = self._seen_updates.get(user_id, set())
  484. extremity = yield self.store.get_device_list_last_stream_id_for_remote(
  485. user_id
  486. )
  487. stream_id_in_updates = set() # stream_ids in updates list
  488. for _, stream_id, prev_ids, _ in updates:
  489. if not prev_ids:
  490. # We always do a resync if there are no previous IDs
  491. defer.returnValue(True)
  492. for prev_id in prev_ids:
  493. if prev_id == extremity:
  494. continue
  495. elif prev_id in seen_updates:
  496. continue
  497. elif prev_id in stream_id_in_updates:
  498. continue
  499. else:
  500. defer.returnValue(True)
  501. stream_id_in_updates.add(stream_id)
  502. defer.returnValue(False)