device.py 18 KB

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