devices.py 16 KB

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