devices.py 16 KB

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