devices.py 17 KB

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