__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''
  24. Qubes OS
  25. :copyright: © 2010-2015 Invisible Things Lab
  26. '''
  27. import builtins
  28. import collections
  29. import os
  30. import os.path
  31. import string
  32. import lxml.etree
  33. import qubes.config
  34. import qubes.events
  35. import qubes.exc
  36. __author__ = 'Invisible Things Lab'
  37. __license__ = 'GPLv2 or later'
  38. __version__ = 'R3'
  39. class Label(object):
  40. '''Label definition for virtual machines
  41. Label specifies colour of the padlock displayed next to VM's name.
  42. When this is a :py:class:`qubes.vm.dispvm.DispVM`, padlock is overlayed
  43. with recycling pictogram.
  44. :param int index: numeric identificator of label
  45. :param str color: colour specification as in HTML (``#abcdef``)
  46. :param str name: label's name like "red" or "green"
  47. '''
  48. def __init__(self, index, color, name):
  49. #: numeric identificator of label
  50. self.index = index
  51. #: colour specification as in HTML (``#abcdef``)
  52. self.color = color
  53. #: label's name like "red" or "green"
  54. self.name = name
  55. #: freedesktop icon name, suitable for use in
  56. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  57. self.icon = 'appvm-' + name
  58. #: freedesktop icon name, suitable for use in
  59. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme` on DispVMs
  60. self.icon_dispvm = 'dispvm-' + name
  61. @classmethod
  62. def fromxml(cls, xml):
  63. '''Create label definition from XML node
  64. :param lxml.etree._Element xml: XML node reference
  65. :rtype: :py:class:`qubes.Label`
  66. '''
  67. index = int(xml.get('id').split('-', 1)[1])
  68. color = xml.get('color')
  69. name = xml.text
  70. return cls(index, color, name)
  71. def __xml__(self):
  72. element = lxml.etree.Element(
  73. 'label', id='label-{}'.format(self.index), color=self.color)
  74. element.text = self.name
  75. return element
  76. def __str__(self):
  77. return self.name
  78. def __repr__(self):
  79. return '{}({!r}, {!r}, {!r})'.format(
  80. self.__class__.__name__,
  81. self.index,
  82. self.color,
  83. self.name)
  84. def __eq__(self, other):
  85. if isinstance(other, Label):
  86. return self.name == other.name
  87. return NotImplemented
  88. def __hash__(self):
  89. return hash(self.name)
  90. @builtins.property
  91. def icon_path(self):
  92. '''Icon path
  93. .. deprecated:: 2.0
  94. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  95. '''
  96. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  97. self.icon) + ".png"
  98. @builtins.property
  99. def icon_path_dispvm(self):
  100. '''Icon path
  101. .. deprecated:: 2.0
  102. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  103. '''
  104. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  105. self.icon_dispvm) + ".png"
  106. class property(object): # pylint: disable=redefined-builtin,invalid-name
  107. '''Qubes property.
  108. This class holds one property that can be saved to and loaded from
  109. :file:`qubes.xml`. It is used for both global and per-VM properties.
  110. Property can be unset by ordinary ``del`` statement or assigning
  111. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  112. assignment/load) attempting to read a property will get its default value
  113. or, when no default, py:class:`exceptions.AttributeError`.
  114. :param str name: name of the property
  115. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  116. initialise value; first parameter to the function is holder instance \
  117. and the second is value; this is called before ``type``
  118. :param collections.Callable saver: function to coerce value to something \
  119. readable by setter
  120. :param type type: if not :py:obj:`None`, value is coerced to this type
  121. :param object default: default value; if callable, will be called with \
  122. holder as first argument
  123. :param int load_stage: stage when property should be loaded (see \
  124. :py:class:`Qubes` for description of stages)
  125. :param int order: order of evaluation (bigger order values are later)
  126. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  127. include this property by default if :py:obj:`False`
  128. :param str doc: docstring; this should be one paragraph of plain RST, no \
  129. sphinx-specific features
  130. Setters and savers have following signatures:
  131. .. :py:function:: setter(self, prop, value)
  132. :noindex:
  133. :param self: instance of object that is holding property
  134. :param prop: property object
  135. :param value: value being assigned
  136. .. :py:function:: saver(self, prop, value)
  137. :noindex:
  138. :param self: instance of object that is holding property
  139. :param prop: property object
  140. :param value: value being saved
  141. :rtype: str
  142. :raises property.DontSave: when property should not be saved at all
  143. '''
  144. #: Assigning this value to property means setting it to its default value.
  145. #: If property has no default value, this will unset it.
  146. DEFAULT = object()
  147. # internal use only
  148. _NO_DEFAULT = object()
  149. def __init__(self, name, setter=None, saver=None, type=None,
  150. default=_NO_DEFAULT, write_once=False, load_stage=2, order=0,
  151. save_via_ref=False, clone=True,
  152. doc=None):
  153. # pylint: disable=redefined-builtin
  154. self.__name__ = name
  155. self._setter = setter
  156. self._saver = saver if saver is not None else (
  157. lambda self, prop, value: str(value))
  158. self.type = type
  159. self._default = default
  160. self._write_once = write_once
  161. self.order = order
  162. self.load_stage = load_stage
  163. self.save_via_ref = save_via_ref
  164. self.clone = clone
  165. self.__doc__ = doc
  166. self._attr_name = '_qubesprop_' + name
  167. def __get__(self, instance, owner):
  168. if instance is None:
  169. return self
  170. # XXX this violates duck typing, shall we keep it?
  171. if not isinstance(instance, PropertyHolder):
  172. raise AttributeError('qubes.property should be used on '
  173. 'qubes.PropertyHolder instances only')
  174. try:
  175. return getattr(instance, self._attr_name)
  176. except AttributeError:
  177. if self._default is self._NO_DEFAULT:
  178. raise AttributeError(
  179. 'property {!r} not set'.format(self.__name__))
  180. elif isinstance(self._default, collections.Callable):
  181. return self._default(instance)
  182. else:
  183. return self._default
  184. def __set__(self, instance, value):
  185. self._enforce_write_once(instance)
  186. if value is self.__class__.DEFAULT:
  187. self.__delete__(instance)
  188. return
  189. try:
  190. oldvalue = getattr(instance, self.__name__)
  191. has_oldvalue = True
  192. except AttributeError:
  193. has_oldvalue = False
  194. if self._setter is not None:
  195. value = self._setter(instance, self, value)
  196. if self.type not in (None, type(value)):
  197. value = self.type(value)
  198. if has_oldvalue:
  199. instance.fire_event_pre('property-pre-set:' + self.__name__,
  200. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  201. else:
  202. instance.fire_event_pre('property-pre-set:' + self.__name__,
  203. name=self.__name__, newvalue=value)
  204. instance._property_init(self, value) # pylint: disable=protected-access
  205. if has_oldvalue:
  206. instance.fire_event('property-set:' + self.__name__,
  207. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  208. else:
  209. instance.fire_event('property-set:' + self.__name__,
  210. name=self.__name__, newvalue=value)
  211. def __delete__(self, instance):
  212. self._enforce_write_once(instance)
  213. try:
  214. oldvalue = getattr(instance, self._attr_name)
  215. has_oldvalue = True
  216. except AttributeError:
  217. has_oldvalue = False
  218. if has_oldvalue:
  219. instance.fire_event_pre('property-pre-del:' + self.__name__,
  220. name=self.__name__, oldvalue=oldvalue)
  221. delattr(instance, self._attr_name)
  222. instance.fire_event('property-del:' + self.__name__,
  223. name=self.__name__, oldvalue=oldvalue)
  224. else:
  225. instance.fire_event_pre('property-pre-del:' + self.__name__,
  226. name=self.__name__)
  227. instance.fire_event('property-del:' + self.__name__,
  228. name=self.__name__)
  229. def __repr__(self):
  230. default = ' default={!r}'.format(self._default) \
  231. if self._default is not self._NO_DEFAULT \
  232. else ''
  233. return '<{} object at {:#x} name={!r}{}>'.format(
  234. self.__class__.__name__, id(self), self.__name__, default)
  235. def __str__(self):
  236. return self.__name__
  237. def __hash__(self):
  238. return hash(self.__name__)
  239. def __lt__(self, other):
  240. if isinstance(other, property):
  241. return (self.load_stage, self.order, self.__name__) <\
  242. (other.load_stage, other.order, other.__name__)
  243. return NotImplemented
  244. def __eq__(self, other):
  245. if isinstance(other, str):
  246. return self.__name__ == other
  247. return isinstance(other, property) and self.__name__ == other.__name__
  248. def _enforce_write_once(self, instance):
  249. if self._write_once and not instance.property_is_default(self):
  250. raise AttributeError(
  251. 'property {!r} is write-once and already set'.format(
  252. self.__name__))
  253. def sanitize(self, *, untrusted_newvalue):
  254. '''Coarse sanitization of value to be set, before sending it to a
  255. setter. Can raise QubesValueError if the value is invalid.
  256. :param untrusted_newvalue: value to be validated
  257. :return sanitized value
  258. :raises qubes.exc.QubesValueError
  259. '''
  260. # do not treat type='str' as sufficient validation
  261. if self.type is not None and self.type is not str:
  262. # assume specific type will preform enough validation
  263. if self.type is bool:
  264. try:
  265. untrusted_newvalue = untrusted_newvalue.decode('ascii')
  266. except UnicodeDecodeError:
  267. raise qubes.exc.QubesValueError
  268. return self.bool(None, None, untrusted_newvalue)
  269. else:
  270. try:
  271. return self.type(untrusted_newvalue)
  272. except ValueError:
  273. raise qubes.exc.QubesValueError
  274. else:
  275. # 'str' or not specified type
  276. try:
  277. untrusted_newvalue = untrusted_newvalue.decode('ascii',
  278. errors='strict')
  279. except UnicodeDecodeError:
  280. raise qubes.exc.QubesValueError
  281. allowed_set = string.printable
  282. if not all(x in allowed_set for x in untrusted_newvalue):
  283. raise qubes.exc.QubesValueError(
  284. 'Invalid characters in property value')
  285. return untrusted_newvalue
  286. #
  287. # exceptions
  288. #
  289. class DontSave(Exception):
  290. '''This exception may be raised from saver to sign that property should
  291. not be saved.
  292. '''
  293. pass
  294. @staticmethod
  295. def dontsave(self, prop, value):
  296. '''Dummy saver that never saves anything.'''
  297. # pylint: disable=bad-staticmethod-argument,unused-argument
  298. raise property.DontSave()
  299. #
  300. # some setters provided
  301. #
  302. @staticmethod
  303. def forbidden(self, prop, value):
  304. '''Property setter that forbids loading a property.
  305. This is used to effectively disable property in classes which inherit
  306. unwanted property. When someone attempts to load such a property, it
  307. :throws AttributeError: always
  308. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  309. raise AttributeError(
  310. 'setting {} property on {} instance is forbidden'.format(
  311. prop.__name__, self.__class__.__name__))
  312. @staticmethod
  313. def bool(self, prop, value):
  314. '''Property setter for boolean properties.
  315. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  316. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  317. :py:obj:`True`.
  318. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  319. if isinstance(value, str):
  320. lcvalue = value.lower()
  321. if lcvalue in ('0', 'no', 'false', 'off'):
  322. return False
  323. if lcvalue in ('1', 'yes', 'true', 'on'):
  324. return True
  325. raise qubes.exc.QubesValueError(
  326. 'Invalid literal for boolean property: {!r}'.format(value))
  327. return bool(value)
  328. def stateless_property(func):
  329. '''Decorator similar to :py:class:`builtins.property`, but for properties
  330. exposed through management API (including qvm-prefs etc)'''
  331. return property(func.__name__,
  332. setter=property.forbidden,
  333. saver=property.DontSave,
  334. default=func,
  335. doc=func.__doc__)
  336. class PropertyHolder(qubes.events.Emitter):
  337. '''Abstract class for holding :py:class:`qubes.property`
  338. Events fired by instances of this class:
  339. .. event:: property-load (subject, event)
  340. Fired once after all properties are loaded from XML. Individual
  341. ``property-set`` events are not fired.
  342. .. event:: property-set:<propname> \
  343. (subject, event, name, newvalue[, oldvalue])
  344. Fired when property changes state. Signature is variable,
  345. *oldvalue* is present only if there was an old value.
  346. :param name: Property name
  347. :param newvalue: New value of the property
  348. :param oldvalue: Old value of the property
  349. .. event:: property-pre-set:<propname> \
  350. (subject, event, name, newvalue[, oldvalue])
  351. Fired before property changes state. Signature is variable,
  352. *oldvalue* is present only if there was an old value.
  353. :param name: Property name
  354. :param newvalue: New value of the property
  355. :param oldvalue: Old value of the property
  356. .. event:: property-del:<propname> \
  357. (subject, event, name[, oldvalue])
  358. Fired when property gets deleted (is set to default). Signature is
  359. variable, *oldvalue* is present only if there was an old value.
  360. :param name: Property name
  361. :param oldvalue: Old value of the property
  362. .. event:: property-pre-del:<propname> \
  363. (subject, event, name[, oldvalue])
  364. Fired before property gets deleted (is set to default). Signature
  365. is variable, *oldvalue* is present only if there was an old value.
  366. :param name: Property name
  367. :param oldvalue: Old value of the property
  368. .. event:: clone-properties (subject, event, src, proplist)
  369. :param src: object, from which we are cloning
  370. :param proplist: list of properties
  371. Members:
  372. '''
  373. def __init__(self, xml, **kwargs):
  374. self.xml = xml
  375. propvalues = {}
  376. all_names = set(prop.__name__ for prop in self.property_list())
  377. for key in list(kwargs):
  378. if not key in all_names:
  379. continue
  380. propvalues[key] = kwargs.pop(key)
  381. super(PropertyHolder, self).__init__(**kwargs)
  382. for key, value in propvalues.items():
  383. setattr(self, key, value)
  384. if self.xml is not None:
  385. # check if properties are appropriate
  386. all_names = set(prop.__name__ for prop in self.property_list())
  387. for node in self.xml.xpath('./properties/property'):
  388. name = node.get('name')
  389. if name not in all_names:
  390. raise TypeError(
  391. 'property {!r} not applicable to {!r}'.format(
  392. name, self.__class__.__name__))
  393. @classmethod
  394. def property_list(cls, load_stage=None):
  395. '''List all properties attached to this VM's class
  396. :param load_stage: Filter by load stage
  397. :type load_stage: :py:func:`int` or :py:obj:`None`
  398. '''
  399. props = set()
  400. for class_ in cls.__mro__:
  401. props.update(prop for prop in class_.__dict__.values()
  402. if isinstance(prop, property))
  403. if load_stage is not None:
  404. props = set(prop for prop in props
  405. if prop.load_stage == load_stage)
  406. return sorted(props)
  407. def _property_init(self, prop, value):
  408. '''Initialise property to a given value, without side effects.
  409. :param qubes.property prop: property object of particular interest
  410. :param value: value
  411. '''
  412. # pylint: disable=protected-access
  413. setattr(self, self.property_get_def(prop)._attr_name, value)
  414. def property_is_default(self, prop):
  415. '''Check whether property is in it's default value.
  416. Properties when unset may return some default value, so
  417. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  418. method allows for checking if the value returned is in fact it's
  419. default value.
  420. :param qubes.property prop: property object of particular interest
  421. :rtype: bool
  422. ''' # pylint: disable=protected-access
  423. # both property_get_def() and ._attr_name may throw AttributeError,
  424. # which we don't want to catch
  425. attrname = self.property_get_def(prop)._attr_name
  426. return not hasattr(self, attrname)
  427. @classmethod
  428. def property_get_def(cls, prop):
  429. '''Return property definition object.
  430. If prop is already :py:class:`qubes.property` instance, return the same
  431. object.
  432. :param prop: property object or name
  433. :type prop: qubes.property or str
  434. :rtype: qubes.property
  435. '''
  436. if isinstance(prop, qubes.property):
  437. return prop
  438. for p in cls.property_list():
  439. if p.__name__ == prop:
  440. return p
  441. raise AttributeError('No property {!r} found in {!r}'.format(
  442. prop, cls))
  443. def load_properties(self, load_stage=None):
  444. '''Load properties from immediate children of XML node.
  445. ``property-set`` events are not fired for each individual property.
  446. :param int load_stage: Stage of loading.
  447. '''
  448. if self.xml is None:
  449. return
  450. all_names = set(
  451. prop.__name__ for prop in self.property_list(load_stage))
  452. for node in self.xml.xpath('./properties/property'):
  453. name = node.get('name')
  454. value = node.get('ref') or node.text
  455. if not name in all_names:
  456. continue
  457. setattr(self, name, value)
  458. def xml_properties(self, with_defaults=False):
  459. '''Iterator that yields XML nodes representing set properties.
  460. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  461. properties which were not set explicite, but have default values \
  462. filled.
  463. '''
  464. properties = lxml.etree.Element('properties')
  465. for prop in self.property_list():
  466. # pylint: disable=protected-access
  467. try:
  468. value = getattr(
  469. self, (prop.__name__ if with_defaults else prop._attr_name))
  470. except AttributeError:
  471. continue
  472. try:
  473. value = prop._saver(self, prop, value)
  474. except property.DontSave:
  475. continue
  476. element = lxml.etree.Element('property', name=prop.__name__)
  477. if prop.save_via_ref:
  478. element.set('ref', value)
  479. else:
  480. element.text = value
  481. properties.append(element)
  482. return properties
  483. # this was clone_attrs
  484. def clone_properties(self, src, proplist=None):
  485. '''Clone properties from other object.
  486. :param PropertyHolder src: source object
  487. :param list proplist: list of properties \
  488. (:py:obj:`None` or omit for all properties except those with \
  489. :py:attr:`property.clone` set to :py:obj:`False`)
  490. '''
  491. if proplist is None:
  492. proplist = [prop for prop in self.property_list()
  493. if prop.clone]
  494. else:
  495. proplist = [prop for prop in self.property_list()
  496. if prop.__name__ in proplist or prop in proplist]
  497. for prop in proplist:
  498. try:
  499. # pylint: disable=protected-access
  500. self._property_init(prop, getattr(src, prop._attr_name))
  501. except AttributeError:
  502. continue
  503. self.fire_event('clone-properties', src=src, proplist=proplist)
  504. def property_require(self, prop, allow_none=False, hard=False):
  505. '''Complain badly when property is not set.
  506. :param prop: property name or object
  507. :type prop: qubes.property or str
  508. :param bool allow_none: if :py:obj:`True`, don't complain if \
  509. :py:obj:`None` is found
  510. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  511. if :py:obj:`False`, log warning instead
  512. '''
  513. if isinstance(prop, qubes.property):
  514. prop = prop.__name__
  515. try:
  516. value = getattr(self, prop)
  517. if value is None and not allow_none:
  518. raise AttributeError()
  519. except AttributeError:
  520. # pylint: disable=no-member
  521. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  522. if hard:
  523. raise AssertionError(msg)
  524. else:
  525. # pylint: disable=no-member
  526. self.log.fatal(msg)
  527. # pylint: disable=wrong-import-position
  528. from qubes.vm import VMProperty
  529. from qubes.app import Qubes
  530. __all__ = [
  531. 'Label',
  532. 'PropertyHolder',
  533. 'Qubes',
  534. 'VMProperty',
  535. 'property',
  536. ]