devices.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. class DeviceAlreadyAttached(qubes.exc.QubesException, KeyError):
  57. '''Trying to attach already attached device'''
  58. class DeviceInfo:
  59. ''' Holds all information about a device '''
  60. # pylint: disable=too-few-public-methods
  61. def __init__(self, backend_domain, ident, description=None,
  62. frontend_domain=None):
  63. #: domain providing this device
  64. self.backend_domain = backend_domain
  65. #: device identifier (unique for given domain and device type)
  66. self.ident = ident
  67. # allow redefining those as dynamic properties in subclasses
  68. try:
  69. #: human readable description/name of the device
  70. self.description = description
  71. except AttributeError:
  72. pass
  73. try:
  74. #: (running) domain to which device is currently attached
  75. self.frontend_domain = frontend_domain
  76. except AttributeError:
  77. pass
  78. if hasattr(self, 'regex'):
  79. # pylint: disable=no-member
  80. dev_match = self.regex.match(ident)
  81. if not dev_match:
  82. raise ValueError('Invalid device identifier: {!r}'.format(
  83. ident))
  84. for group in self.regex.groupindex:
  85. setattr(self, group, dev_match.group(group))
  86. def __hash__(self):
  87. return hash((self.backend_domain, self.ident))
  88. def __eq__(self, other):
  89. return (
  90. self.backend_domain == other.backend_domain and
  91. self.ident == other.ident
  92. )
  93. def __lt__(self, other):
  94. if isinstance(other, DeviceInfo):
  95. return (self.backend_domain, self.ident) < \
  96. (other.backend_domain, other.ident)
  97. return NotImplemented
  98. def __str__(self):
  99. return '{!s}:{!s}'.format(self.backend_domain, self.ident)
  100. class DeviceAssignment: # pylint: disable=too-few-public-methods
  101. ''' Maps a device to a frontend_domain. '''
  102. def __init__(self, backend_domain, ident, options=None, persistent=False,
  103. bus=None):
  104. self.backend_domain = backend_domain
  105. self.ident = ident
  106. self.options = options or {}
  107. self.persistent = persistent
  108. self.bus = bus
  109. def __repr__(self):
  110. return "[%s]:%s" % (self.backend_domain, self.ident)
  111. def __hash__(self):
  112. # it's important to use the same hash as DeviceInfo
  113. return hash((self.backend_domain, self.ident))
  114. def __eq__(self, other):
  115. if not isinstance(self, other.__class__):
  116. return NotImplemented
  117. return self.backend_domain == other.backend_domain \
  118. and self.ident == other.ident
  119. def clone(self):
  120. '''Clone object instance'''
  121. return self.__class__(
  122. self.backend_domain,
  123. self.ident,
  124. self.options,
  125. self.persistent,
  126. self.bus,
  127. )
  128. @property
  129. def device(self):
  130. '''Get DeviceInfo object corresponding to this DeviceAssignment'''
  131. return self.backend_domain.devices[self.bus][self.ident]
  132. class DeviceCollection:
  133. '''Bag for devices.
  134. Used as default value for :py:meth:`DeviceManager.__missing__` factory.
  135. :param vm: VM for which we manage devices
  136. :param bus: device bus
  137. This class emits following events on VM object:
  138. .. event:: device-attach:<class> (device, options)
  139. Fired when device is attached to a VM.
  140. Handler for this event can be asynchronous (a coroutine).
  141. :param device: :py:class:`DeviceInfo` object to be attached
  142. :param options: :py:class:`dict` of attachment options
  143. .. event:: device-pre-attach:<class> (device)
  144. Fired before device is attached to a VM
  145. Handler for this event can be asynchronous (a coroutine).
  146. :param device: :py:class:`DeviceInfo` object to be attached
  147. .. event:: device-detach:<class> (device)
  148. Fired when device is detached from a VM.
  149. Handler for this event can be asynchronous (a coroutine).
  150. :param device: :py:class:`DeviceInfo` object to be attached
  151. .. event:: device-pre-detach:<class> (device)
  152. Fired before device is detached from a VM
  153. Handler for this event can be asynchronous (a coroutine).
  154. :param device: :py:class:`DeviceInfo` object to be attached
  155. .. event:: device-list:<class>
  156. Fired to get list of devices exposed by a VM. Handlers of this
  157. event should return a list of py:class:`DeviceInfo` objects (or
  158. appropriate class specific descendant)
  159. .. event:: device-get:<class> (ident)
  160. Fired to get a single device, given by the `ident` parameter.
  161. Handlers of this event should either return appropriate object of
  162. :py:class:`DeviceInfo`, or :py:obj:`None`. Especially should not
  163. raise :py:class:`exceptions.KeyError`.
  164. .. event:: device-list-attached:<class> (persistent)
  165. Fired to get list of currently attached devices to a VM. Handlers
  166. of this event should return list of devices actually attached to
  167. a domain, regardless of its settings.
  168. '''
  169. def __init__(self, vm, bus):
  170. self._vm = vm
  171. self._bus = bus
  172. self._set = PersistentCollection()
  173. self.devclass = qubes.utils.get_entry_point_one(
  174. 'qubes.devices', self._bus)
  175. @asyncio.coroutine
  176. def attach(self, device_assignment: DeviceAssignment):
  177. '''Attach (add) device to domain.
  178. :param DeviceInfo device: device object
  179. '''
  180. if device_assignment.bus is None:
  181. device_assignment.bus = self._bus
  182. elif device_assignment.bus != self._bus:
  183. raise ValueError(
  184. 'Trying to attach DeviceAssignment of a different device class')
  185. if not device_assignment.persistent and self._vm.is_halted():
  186. raise qubes.exc.QubesVMNotRunningError(self._vm,
  187. "VM not running, can only attach device with persistent flag")
  188. device = device_assignment.device
  189. if device in self.assignments():
  190. raise DeviceAlreadyAttached(
  191. 'device {!s} of class {} already attached to {!s}'.format(
  192. device, self._bus, self._vm))
  193. yield from self._vm.fire_event_async('device-pre-attach:' + self._bus,
  194. pre_event=True,
  195. device=device, options=device_assignment.options)
  196. if device_assignment.persistent:
  197. self._set.add(device_assignment)
  198. yield from self._vm.fire_event_async('device-attach:' + self._bus,
  199. device=device, options=device_assignment.options)
  200. def load_persistent(self, device_assignment: DeviceAssignment):
  201. '''Load DeviceAssignment retrieved from qubes.xml
  202. This can be used only for loading qubes.xml, when VM events are not
  203. enabled yet.
  204. '''
  205. assert not self._vm.events_enabled
  206. assert device_assignment.persistent
  207. device_assignment.bus = self._bus
  208. self._set.add(device_assignment)
  209. def update_persistent(self, device: DeviceInfo, persistent: bool):
  210. '''Update `persistent` flag of already attached device.
  211. '''
  212. if self._vm.is_halted():
  213. raise qubes.exc.QubesVMNotStartedError(self._vm,
  214. 'VM must be running to modify device persistence flag')
  215. assignments = [a for a in self.assignments() if a.device == device]
  216. if not assignments:
  217. raise qubes.exc.QubesValueError('Device not assigned')
  218. assert len(assignments) == 1
  219. assignment = assignments[0]
  220. # be careful to use already present assignment, not the provided one
  221. # - to not change options as a side effect
  222. if persistent and device not in self._set:
  223. assignment.persistent = True
  224. self._set.add(assignment)
  225. elif not persistent and device in self._set:
  226. self._set.discard(assignment)
  227. @asyncio.coroutine
  228. def detach(self, device_assignment: DeviceAssignment):
  229. '''Detach (remove) device from domain.
  230. :param DeviceInfo device: device object
  231. '''
  232. if device_assignment.bus is None:
  233. device_assignment.bus = self._bus
  234. else:
  235. assert device_assignment.bus == self._bus, \
  236. "Trying to attach DeviceAssignment of a different device class"
  237. if device_assignment in self._set and not self._vm.is_halted():
  238. raise qubes.exc.QubesVMNotHaltedError(self._vm,
  239. "Can not remove a persistent attachment from a non halted vm")
  240. if device_assignment not in self.assignments():
  241. raise DeviceNotAttached(
  242. 'device {!s} of class {} not attached to {!s}'.format(
  243. device_assignment.ident, self._bus, self._vm))
  244. device = device_assignment.device
  245. yield from self._vm.fire_event_async('device-pre-detach:' + self._bus,
  246. pre_event=True, device=device)
  247. if device in self._set:
  248. device_assignment.persistent = True
  249. self._set.discard(device_assignment)
  250. yield from self._vm.fire_event_async('device-detach:' + self._bus,
  251. device=device)
  252. def attached(self):
  253. '''List devices which are (or may be) attached to this vm '''
  254. attached = self._vm.fire_event('device-list-attached:' + self._bus,
  255. persistent=None)
  256. if attached:
  257. return [dev for dev, _ in attached]
  258. return []
  259. def persistent(self):
  260. ''' Devices persistently attached and safe to access before libvirt
  261. bootstrap.
  262. '''
  263. return [a.device for a in self._set]
  264. def assignments(self, persistent=None):
  265. '''List assignments for devices which are (or may be) attached to the
  266. vm.
  267. Devices may be attached persistently (so they are included in
  268. :file:`qubes.xml`) or not. Device can also be in :file:`qubes.xml`,
  269. but be temporarily detached.
  270. :param bool persistent: only include devices which are or are not
  271. attached persistently.
  272. '''
  273. try:
  274. devices = self._vm.fire_event('device-list-attached:' + self._bus,
  275. persistent=persistent)
  276. except Exception: # pylint: disable=broad-except
  277. self._vm.log.exception('Failed to list {} devices'.format(
  278. self._bus))
  279. if persistent is True:
  280. # don't break app.save()
  281. return self._set
  282. raise
  283. result = set()
  284. for dev, options in devices:
  285. if dev in self._set and not persistent:
  286. continue
  287. if dev in self._set:
  288. result.add(self._set.get(dev))
  289. elif dev not in self._set and persistent:
  290. continue
  291. else:
  292. result.add(
  293. DeviceAssignment(
  294. backend_domain=dev.backend_domain,
  295. ident=dev.ident, options=options,
  296. bus=self._bus))
  297. if persistent is not False:
  298. result.update(self._set)
  299. return result
  300. def available(self):
  301. '''List devices exposed by this vm'''
  302. devices = self._vm.fire_event('device-list:' + self._bus)
  303. return devices
  304. def __iter__(self):
  305. return iter(self.available())
  306. def __getitem__(self, ident):
  307. '''Get device object with given ident.
  308. :returns: py:class:`DeviceInfo`
  309. If domain isn't running, it is impossible to check device validity,
  310. so return UnknownDevice object. Also do the same for non-existing
  311. devices - otherwise it will be impossible to detach already
  312. disconnected device.
  313. :raises AssertionError: when multiple devices with the same ident are
  314. found
  315. '''
  316. dev = self._vm.fire_event('device-get:' + self._bus, ident=ident)
  317. if dev:
  318. assert len(dev) == 1
  319. return dev[0]
  320. return UnknownDevice(self._vm, ident)
  321. class DeviceManager(dict):
  322. '''Device manager that hold all devices by their classess.
  323. :param vm: VM for which we manage devices
  324. '''
  325. def __init__(self, vm):
  326. super().__init__()
  327. self._vm = vm
  328. def __missing__(self, key):
  329. self[key] = DeviceCollection(self._vm, key)
  330. return self[key]
  331. class UnknownDevice(DeviceInfo):
  332. # pylint: disable=too-few-public-methods
  333. '''Unknown device - for example exposed by domain not running currently'''
  334. def __init__(self, backend_domain, ident, description=None,
  335. frontend_domain=None):
  336. if description is None:
  337. description = "Unknown device"
  338. super().__init__(backend_domain, ident, description,
  339. frontend_domain)
  340. class PersistentCollection:
  341. ''' Helper object managing persistent `DeviceAssignment`s.
  342. '''
  343. def __init__(self):
  344. self._dict = {}
  345. def add(self, assignment: DeviceAssignment):
  346. ''' Add assignment to collection '''
  347. assert assignment.persistent
  348. vm = assignment.backend_domain
  349. ident = assignment.ident
  350. key = (vm, ident)
  351. assert key not in self._dict
  352. self._dict[key] = assignment
  353. def discard(self, assignment):
  354. ''' Discard assignment from collection '''
  355. assert assignment.persistent
  356. vm = assignment.backend_domain
  357. ident = assignment.ident
  358. key = (vm, ident)
  359. if key not in self._dict:
  360. raise KeyError
  361. del self._dict[key]
  362. def __contains__(self, device) -> bool:
  363. return (device.backend_domain, device.ident) in self._dict
  364. def get(self, device: DeviceInfo) -> DeviceAssignment:
  365. ''' Returns the corresponding `qubes.devices.DeviceAssignment` for the
  366. device. '''
  367. return self._dict[(device.backend_domain, device.ident)]
  368. def __iter__(self):
  369. return self._dict.values().__iter__()
  370. def __len__(self) -> int:
  371. return len(self._dict.keys())