devices.py 15 KB

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