devices.py 14 KB

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