devices.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2016 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2015-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. '''API for various types of devices.
  22. Main concept is that some domain main
  23. expose (potentially multiple) devices, which can be attached to other domains.
  24. Devices can be of different buses (like 'pci', 'usb', etc). Each device
  25. bus is implemented by an extension.
  26. Devices are identified by pair of (backend domain, `ident`), where `ident` is
  27. :py:class:`str` and can contain only characters from `[a-zA-Z0-9._-]` set.
  28. Such extension should provide:
  29. - `qubes.devices` endpoint - a class descendant from
  30. :py:class:`qubes.devices.DeviceInfo`, designed to hold device description (
  31. including bus-specific properties)
  32. - handle `device-attach:bus` and `device-detach:bus` events for
  33. performing the attach/detach action; events are fired even when domain isn't
  34. running and extension should be prepared for this; handlers for those events
  35. can be coroutines
  36. - handle `device-list:bus` event - list devices exposed by particular
  37. domain; it should return list of appropriate DeviceInfo objects
  38. - handle `device-get:bus` event - get one device object exposed by this
  39. domain of given identifier
  40. - handle `device-list-attached:class` event - list currently attached
  41. devices to this domain
  42. - fire `device-list-change:class` event when device list change is detected
  43. (new/removed device)
  44. Note that device-listing event handlers can not be asynchronous. This for
  45. example means you can not call qrexec service there. This is intentional to
  46. keep device listing operation cheap. You need to design the extension to take
  47. this into account (for example by using QubesDB).
  48. Extension may use QubesDB watch API (QubesVM.watch_qdb_path(path), then handle
  49. `domain-qdb-change:path`) to detect changes and fire
  50. `device-list-change:class` event.
  51. '''
  52. import asyncio
  53. import qubes.utils
  54. class DeviceNotAttached(qubes.exc.QubesException, KeyError):
  55. '''Trying to detach not attached device'''
  56. pass
  57. class DeviceAlreadyAttached(qubes.exc.QubesException, KeyError):
  58. '''Trying to attach already attached device'''
  59. pass
  60. class DeviceInfo:
  61. ''' Holds all information about a device '''
  62. # pylint: disable=too-few-public-methods
  63. def __init__(self, backend_domain, ident, description=None,
  64. frontend_domain=None):
  65. #: domain providing this device
  66. self.backend_domain = backend_domain
  67. #: device identifier (unique for given domain and device type)
  68. self.ident = ident
  69. # allow redefining those as dynamic properties in subclasses
  70. try:
  71. #: human readable description/name of the device
  72. self.description = description
  73. except AttributeError:
  74. pass
  75. try:
  76. #: (running) domain to which device is currently attached
  77. self.frontend_domain = frontend_domain
  78. except AttributeError:
  79. pass
  80. if hasattr(self, 'regex'):
  81. # pylint: disable=no-member
  82. dev_match = self.regex.match(ident)
  83. if not dev_match:
  84. raise ValueError('Invalid device identifier: {!r}'.format(
  85. ident))
  86. for group in self.regex.groupindex:
  87. setattr(self, group, dev_match.group(group))
  88. def __hash__(self):
  89. return hash((self.backend_domain, self.ident))
  90. def __eq__(self, other):
  91. return (
  92. self.backend_domain == other.backend_domain and
  93. self.ident == other.ident
  94. )
  95. def __lt__(self, other):
  96. if isinstance(other, DeviceInfo):
  97. return (self.backend_domain, self.ident) < \
  98. (other.backend_domain, other.ident)
  99. return NotImplemented
  100. def __str__(self):
  101. return '{!s}:{!s}'.format(self.backend_domain, self.ident)
  102. class DeviceAssignment: # pylint: disable=too-few-public-methods
  103. ''' Maps a device to a frontend_domain. '''
  104. def __init__(self, backend_domain, ident, options=None, persistent=False,
  105. bus=None):
  106. self.backend_domain = backend_domain
  107. self.ident = ident
  108. self.options = options or {}
  109. self.persistent = persistent
  110. self.bus = bus
  111. def __repr__(self):
  112. return "[%s]:%s" % (self.backend_domain, self.ident)
  113. def __hash__(self):
  114. # it's important to use the same hash as DeviceInfo
  115. return hash((self.backend_domain, self.ident))
  116. def __eq__(self, other):
  117. if not isinstance(self, other.__class__):
  118. return NotImplemented
  119. return self.backend_domain == other.backend_domain \
  120. and self.ident == other.ident
  121. def clone(self):
  122. '''Clone object instance'''
  123. return self.__class__(
  124. self.backend_domain,
  125. self.ident,
  126. self.options,
  127. self.persistent,
  128. self.bus,
  129. )
  130. @property
  131. def device(self):
  132. '''Get DeviceInfo object corresponding to this DeviceAssignment'''
  133. return self.backend_domain.devices[self.bus][self.ident]
  134. class DeviceCollection:
  135. '''Bag for devices.
  136. Used as default value for :py:meth:`DeviceManager.__missing__` factory.
  137. :param vm: VM for which we manage devices
  138. :param bus: device bus
  139. This class emits following events on VM object:
  140. .. event:: device-attach:<class> (device)
  141. Fired when device is attached to a VM.
  142. Handler for this event can be asynchronous (a coroutine).
  143. :param device: :py:class:`DeviceInfo` object to be attached
  144. .. event:: device-pre-attach:<class> (device)
  145. Fired before device is attached to a VM
  146. Handler for this event can be asynchronous (a coroutine).
  147. :param device: :py:class:`DeviceInfo` object to be attached
  148. .. event:: device-detach:<class> (device)
  149. Fired when device is detached from a VM.
  150. Handler for this event can be asynchronous (a coroutine).
  151. :param device: :py:class:`DeviceInfo` object to be attached
  152. .. event:: device-pre-detach:<class> (device)
  153. Fired before device is detached from a VM
  154. Handler for this event can be asynchronous (a coroutine).
  155. :param device: :py:class:`DeviceInfo` object to be attached
  156. .. event:: device-list:<class>
  157. Fired to get list of devices exposed by a VM. Handlers of this
  158. event should return a list of py:class:`DeviceInfo` objects (or
  159. appropriate class specific descendant)
  160. .. event:: device-get:<class> (ident)
  161. Fired to get a single device, given by the `ident` parameter.
  162. Handlers of this event should either return appropriate object of
  163. :py:class:`DeviceInfo`, or :py:obj:`None`. Especially should not
  164. raise :py:class:`exceptions.KeyError`.
  165. .. event:: device-list-attached:<class> (persistent)
  166. Fired to get list of currently attached devices to a VM. Handlers
  167. of this event should return list of devices actually attached to
  168. a domain, regardless of its settings.
  169. '''
  170. def __init__(self, vm, bus):
  171. self._vm = vm
  172. self._bus = bus
  173. self._set = PersistentCollection()
  174. self.devclass = qubes.utils.get_entry_point_one(
  175. 'qubes.devices', self._bus)
  176. @asyncio.coroutine
  177. def attach(self, device_assignment: DeviceAssignment):
  178. '''Attach (add) device to domain.
  179. :param DeviceInfo device: device object
  180. '''
  181. if device_assignment.bus is None:
  182. device_assignment.bus = self._bus
  183. else:
  184. assert device_assignment.bus == self._bus, \
  185. "Trying to attach DeviceAssignment of a different device class"
  186. if not device_assignment.persistent and self._vm.is_halted():
  187. raise qubes.exc.QubesVMNotRunningError(self._vm,
  188. "VM not running, can only attach device with persistent flag")
  189. device = device_assignment.device
  190. if device in self.assignments():
  191. raise DeviceAlreadyAttached(
  192. 'device {!s} of class {} already attached to {!s}'.format(
  193. device, self._bus, self._vm))
  194. yield from self._vm.fire_event_async('device-pre-attach:' + self._bus,
  195. pre_event=True,
  196. device=device, options=device_assignment.options)
  197. if device_assignment.persistent:
  198. self._set.add(device_assignment)
  199. yield from self._vm.fire_event_async('device-attach:' + self._bus,
  200. device=device, options=device_assignment.options)
  201. def load_persistent(self, device_assignment: DeviceAssignment):
  202. '''Load DeviceAssignment retrieved from qubes.xml
  203. This can be used only for loading qubes.xml, when VM events are not
  204. enabled yet.
  205. '''
  206. assert not self._vm.events_enabled
  207. assert device_assignment.persistent
  208. device_assignment.bus = self._bus
  209. self._set.add(device_assignment)
  210. def update_persistent(self, device: DeviceInfo, persistent: bool):
  211. '''Update `persistent` flag of already attached device.
  212. '''
  213. if self._vm.is_halted():
  214. raise qubes.exc.QubesVMNotStartedError(self._vm,
  215. 'VM must be running to modify device persistence flag')
  216. assignments = [a for a in self.assignments() if a.device == device]
  217. if not assignments:
  218. raise qubes.exc.QubesValueError('Device not assigned')
  219. assert len(assignments) == 1
  220. assignment = assignments[0]
  221. # be careful to use already present assignment, not the provided one
  222. # - to not change options as a side effect
  223. if persistent and device not in self._set:
  224. assignment.persistent = True
  225. self._set.add(assignment)
  226. elif not persistent and device in self._set:
  227. self._set.discard(assignment)
  228. @asyncio.coroutine
  229. def detach(self, device_assignment: DeviceAssignment):
  230. '''Detach (remove) device from domain.
  231. :param DeviceInfo device: device object
  232. '''
  233. if device_assignment.bus is None:
  234. device_assignment.bus = self._bus
  235. else:
  236. assert device_assignment.bus == self._bus, \
  237. "Trying to attach DeviceAssignment of a different device class"
  238. if device_assignment in self._set and not self._vm.is_halted():
  239. raise qubes.exc.QubesVMNotHaltedError(self._vm,
  240. "Can not remove a persistent attachment from a non halted vm")
  241. if device_assignment not in self.assignments():
  242. raise DeviceNotAttached(
  243. 'device {!s} of class {} not attached to {!s}'.format(
  244. device_assignment.ident, self._bus, self._vm))
  245. device = device_assignment.device
  246. yield from self._vm.fire_event_async('device-pre-detach:' + self._bus,
  247. pre_event=True, device=device)
  248. if device in self._set:
  249. device_assignment.persistent = True
  250. self._set.discard(device_assignment)
  251. yield from self._vm.fire_event_async('device-detach:' + self._bus,
  252. device=device)
  253. def attached(self):
  254. '''List devices which are (or may be) attached to this vm '''
  255. attached = self._vm.fire_event('device-list-attached:' + self._bus,
  256. persistent=None)
  257. if attached:
  258. return [dev for dev, _ in attached]
  259. return []
  260. def persistent(self):
  261. ''' Devices persistently attached and safe to access before libvirt
  262. bootstrap.
  263. '''
  264. return [a.device for a in self._set]
  265. def assignments(self, persistent=None):
  266. '''List assignments for devices which are (or may be) attached to the
  267. vm.
  268. Devices may be attached persistently (so they are included in
  269. :file:`qubes.xml`) or not. Device can also be in :file:`qubes.xml`,
  270. but be temporarily detached.
  271. :param bool persistent: only include devices which are or are not
  272. attached persistently.
  273. '''
  274. try:
  275. devices = self._vm.fire_event('device-list-attached:' + self._bus,
  276. persistent=persistent)
  277. except Exception: # pylint: disable=broad-except
  278. self._vm.log.exception('Failed to list {} devices'.format(
  279. self._bus))
  280. if persistent is True:
  281. # don't break app.save()
  282. return self._set
  283. raise
  284. result = set()
  285. for dev, options in devices:
  286. if dev in self._set and not persistent:
  287. continue
  288. elif dev in self._set:
  289. result.add(self._set.get(dev))
  290. elif dev not in self._set and persistent:
  291. continue
  292. else:
  293. result.add(
  294. DeviceAssignment(
  295. backend_domain=dev.backend_domain,
  296. ident=dev.ident, options=options,
  297. bus=self._bus))
  298. if persistent is not False:
  299. result.update(self._set)
  300. return result
  301. def available(self):
  302. '''List devices exposed by this vm'''
  303. devices = self._vm.fire_event('device-list:' + self._bus)
  304. return devices
  305. def __iter__(self):
  306. return iter(self.available())
  307. def __getitem__(self, ident):
  308. '''Get device object with given ident.
  309. :returns: py:class:`DeviceInfo`
  310. If domain isn't running, it is impossible to check device validity,
  311. so return UnknownDevice object. Also do the same for non-existing
  312. devices - otherwise it will be impossible to detach already
  313. disconnected device.
  314. :raises AssertionError: when multiple devices with the same ident are
  315. found
  316. '''
  317. dev = self._vm.fire_event('device-get:' + self._bus, ident=ident)
  318. if dev:
  319. assert len(dev) == 1
  320. return dev[0]
  321. return UnknownDevice(self._vm, ident)
  322. class DeviceManager(dict):
  323. '''Device manager that hold all devices by their classess.
  324. :param vm: VM for which we manage devices
  325. '''
  326. def __init__(self, vm):
  327. super(DeviceManager, self).__init__()
  328. self._vm = vm
  329. def __missing__(self, key):
  330. self[key] = DeviceCollection(self._vm, key)
  331. return self[key]
  332. class UnknownDevice(DeviceInfo):
  333. # pylint: disable=too-few-public-methods
  334. '''Unknown device - for example exposed by domain not running currently'''
  335. def __init__(self, backend_domain, ident, description=None,
  336. frontend_domain=None):
  337. if description is None:
  338. description = "Unknown device"
  339. super(UnknownDevice, self).__init__(backend_domain, ident, description,
  340. frontend_domain)
  341. class PersistentCollection:
  342. ''' Helper object managing persistent `DeviceAssignment`s.
  343. '''
  344. def __init__(self):
  345. self._dict = {}
  346. def add(self, assignment: DeviceAssignment):
  347. ''' Add assignment to collection '''
  348. assert assignment.persistent
  349. vm = assignment.backend_domain
  350. ident = assignment.ident
  351. key = (vm, ident)
  352. assert key not in self._dict
  353. self._dict[key] = assignment
  354. def discard(self, assignment):
  355. ''' Discard assignment from collection '''
  356. assert assignment.persistent
  357. vm = assignment.backend_domain
  358. ident = assignment.ident
  359. key = (vm, ident)
  360. if key not in self._dict:
  361. raise KeyError
  362. del self._dict[key]
  363. def __contains__(self, device) -> bool:
  364. return (device.backend_domain, device.ident) in self._dict
  365. def get(self, device: DeviceInfo) -> DeviceAssignment:
  366. ''' Returns the corresponding `qubes.devices.DeviceAssignment` for the
  367. device. '''
  368. return self._dict[(device.backend_domain, device.ident)]
  369. def __iter__(self):
  370. return self._dict.values().__iter__()
  371. def __len__(self) -> int:
  372. return len(self._dict.keys())