__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. @builtins.property
  89. def icon_path(self):
  90. '''Icon path
  91. .. deprecated:: 2.0
  92. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  93. '''
  94. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  95. self.icon) + ".png"
  96. @builtins.property
  97. def icon_path_dispvm(self):
  98. '''Icon path
  99. .. deprecated:: 2.0
  100. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  101. '''
  102. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  103. self.icon_dispvm) + ".png"
  104. class property(object): # pylint: disable=redefined-builtin,invalid-name
  105. '''Qubes property.
  106. This class holds one property that can be saved to and loaded from
  107. :file:`qubes.xml`. It is used for both global and per-VM properties.
  108. Property can be unset by ordinary ``del`` statement or assigning
  109. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  110. assignment/load) attempting to read a property will get its default value
  111. or, when no default, py:class:`exceptions.AttributeError`.
  112. :param str name: name of the property
  113. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  114. initialise value; first parameter to the function is holder instance \
  115. and the second is value; this is called before ``type``
  116. :param collections.Callable saver: function to coerce value to something \
  117. readable by setter
  118. :param type type: if not :py:obj:`None`, value is coerced to this type
  119. :param object default: default value; if callable, will be called with \
  120. holder as first argument
  121. :param int load_stage: stage when property should be loaded (see \
  122. :py:class:`Qubes` for description of stages)
  123. :param int order: order of evaluation (bigger order values are later)
  124. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  125. include this property by default if :py:obj:`False`
  126. :param str doc: docstring; this should be one paragraph of plain RST, no \
  127. sphinx-specific features
  128. Setters and savers have following signatures:
  129. .. :py:function:: setter(self, prop, value)
  130. :noindex:
  131. :param self: instance of object that is holding property
  132. :param prop: property object
  133. :param value: value being assigned
  134. .. :py:function:: saver(self, prop, value)
  135. :noindex:
  136. :param self: instance of object that is holding property
  137. :param prop: property object
  138. :param value: value being saved
  139. :rtype: str
  140. :raises property.DontSave: when property should not be saved at all
  141. '''
  142. #: Assigning this value to property means setting it to its default value.
  143. #: If property has no default value, this will unset it.
  144. DEFAULT = object()
  145. # internal use only
  146. _NO_DEFAULT = object()
  147. def __init__(self, name, setter=None, saver=None, type=None,
  148. default=_NO_DEFAULT, write_once=False, load_stage=2, order=0,
  149. save_via_ref=False, clone=True,
  150. doc=None):
  151. # pylint: disable=redefined-builtin
  152. self.__name__ = name
  153. self._setter = setter
  154. self._saver = saver if saver is not None else (
  155. lambda self, prop, value: str(value))
  156. self.type = type
  157. self._default = default
  158. self._write_once = write_once
  159. self.order = order
  160. self.load_stage = load_stage
  161. self.save_via_ref = save_via_ref
  162. self.clone = clone
  163. self.__doc__ = doc
  164. self._attr_name = '_qubesprop_' + name
  165. def __get__(self, instance, owner):
  166. if instance is None:
  167. return self
  168. # XXX this violates duck typing, shall we keep it?
  169. if not isinstance(instance, PropertyHolder):
  170. raise AttributeError('qubes.property should be used on '
  171. 'qubes.PropertyHolder instances only')
  172. try:
  173. return getattr(instance, self._attr_name)
  174. except AttributeError:
  175. if self._default is self._NO_DEFAULT:
  176. raise AttributeError(
  177. 'property {!r} not set'.format(self.__name__))
  178. elif isinstance(self._default, collections.Callable):
  179. return self._default(instance)
  180. else:
  181. return self._default
  182. def __set__(self, instance, value):
  183. self._enforce_write_once(instance)
  184. if value is self.__class__.DEFAULT:
  185. self.__delete__(instance)
  186. return
  187. try:
  188. oldvalue = getattr(instance, self.__name__)
  189. has_oldvalue = True
  190. except AttributeError:
  191. has_oldvalue = False
  192. if self._setter is not None:
  193. value = self._setter(instance, self, value)
  194. if self.type not in (None, type(value)):
  195. value = self.type(value)
  196. if has_oldvalue:
  197. instance.fire_event_pre('property-pre-set:' + self.__name__,
  198. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  199. else:
  200. instance.fire_event_pre('property-pre-set:' + self.__name__,
  201. name=self.__name__, newvalue=value)
  202. instance._property_init(self, value) # pylint: disable=protected-access
  203. if has_oldvalue:
  204. instance.fire_event('property-set:' + self.__name__,
  205. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  206. else:
  207. instance.fire_event('property-set:' + self.__name__,
  208. name=self.__name__, newvalue=value)
  209. def __delete__(self, instance):
  210. self._enforce_write_once(instance)
  211. try:
  212. oldvalue = getattr(instance, self._attr_name)
  213. has_oldvalue = True
  214. except AttributeError:
  215. has_oldvalue = False
  216. if has_oldvalue:
  217. instance.fire_event_pre('property-pre-del:' + self.__name__,
  218. name=self.__name__, oldvalue=oldvalue)
  219. delattr(instance, self._attr_name)
  220. instance.fire_event('property-del:' + self.__name__,
  221. name=self.__name__, oldvalue=oldvalue)
  222. else:
  223. instance.fire_event_pre('property-pre-del:' + self.__name__,
  224. name=self.__name__)
  225. instance.fire_event('property-del:' + self.__name__,
  226. name=self.__name__)
  227. def __repr__(self):
  228. default = ' default={!r}'.format(self._default) \
  229. if self._default is not self._NO_DEFAULT \
  230. else ''
  231. return '<{} object at {:#x} name={!r}{}>'.format(
  232. self.__class__.__name__, id(self), self.__name__, default) \
  233. def __hash__(self):
  234. return hash(self.__name__)
  235. def __lt__(self, other):
  236. if isinstance(other, property):
  237. return (self.load_stage, self.order, self.__name__) <\
  238. (other.load_stage, other.order, other.__name__)
  239. return NotImplemented
  240. def __eq__(self, other):
  241. if isinstance(other, str):
  242. return self.__name__ == other
  243. return isinstance(other, property) and self.__name__ == other.__name__
  244. def _enforce_write_once(self, instance):
  245. if self._write_once and not instance.property_is_default(self):
  246. raise AttributeError(
  247. 'property {!r} is write-once and already set'.format(
  248. self.__name__))
  249. def sanitize(self, *, untrusted_newvalue):
  250. '''Coarse sanitization of value to be set, before sending it to a
  251. setter. Can raise QubesValueError if the value is invalid.
  252. :param untrusted_newvalue: value to be validated
  253. :return sanitized value
  254. :raises qubes.exc.QubesValueError
  255. '''
  256. # do not treat type='str' as sufficient validation
  257. if self.type is not None and self.type is not str:
  258. # assume specific type will preform enough validation
  259. if self.type is bool:
  260. try:
  261. untrusted_newvalue = untrusted_newvalue.decode('ascii')
  262. except UnicodeDecodeError:
  263. raise qubes.exc.QubesValueError
  264. return self.bool(None, None, untrusted_newvalue)
  265. else:
  266. try:
  267. return self.type(untrusted_newvalue)
  268. except ValueError:
  269. raise qubes.exc.QubesValueError
  270. else:
  271. # 'str' or not specified type
  272. try:
  273. untrusted_newvalue = untrusted_newvalue.decode('ascii',
  274. errors='strict')
  275. except UnicodeDecodeError:
  276. raise qubes.exc.QubesValueError
  277. allowed_set = string.printable
  278. if not all(x in allowed_set for x in untrusted_newvalue):
  279. raise qubes.exc.QubesValueError(
  280. 'Invalid characters in property value')
  281. return untrusted_newvalue
  282. #
  283. # exceptions
  284. #
  285. class DontSave(Exception):
  286. '''This exception may be raised from saver to sign that property should
  287. not be saved.
  288. '''
  289. pass
  290. @staticmethod
  291. def dontsave(self, prop, value):
  292. '''Dummy saver that never saves anything.'''
  293. # pylint: disable=bad-staticmethod-argument,unused-argument
  294. raise property.DontSave()
  295. #
  296. # some setters provided
  297. #
  298. @staticmethod
  299. def forbidden(self, prop, value):
  300. '''Property setter that forbids loading a property.
  301. This is used to effectively disable property in classes which inherit
  302. unwanted property. When someone attempts to load such a property, it
  303. :throws AttributeError: always
  304. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  305. raise AttributeError(
  306. 'setting {} property on {} instance is forbidden'.format(
  307. prop.__name__, self.__class__.__name__))
  308. @staticmethod
  309. def bool(self, prop, value):
  310. '''Property setter for boolean properties.
  311. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  312. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  313. :py:obj:`True`.
  314. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  315. if isinstance(value, str):
  316. lcvalue = value.lower()
  317. if lcvalue in ('0', 'no', 'false', 'off'):
  318. return False
  319. if lcvalue in ('1', 'yes', 'true', 'on'):
  320. return True
  321. raise qubes.exc.QubesValueError(
  322. 'Invalid literal for boolean property: {!r}'.format(value))
  323. return bool(value)
  324. class PropertyHolder(qubes.events.Emitter):
  325. '''Abstract class for holding :py:class:`qubes.property`
  326. Events fired by instances of this class:
  327. .. event:: property-load (subject, event)
  328. Fired once after all properties are loaded from XML. Individual
  329. ``property-set`` events are not fired.
  330. .. event:: property-set:<propname> \
  331. (subject, event, name, newvalue[, oldvalue])
  332. Fired when property changes state. Signature is variable,
  333. *oldvalue* is present only if there was an old value.
  334. :param name: Property name
  335. :param newvalue: New value of the property
  336. :param oldvalue: Old value of the property
  337. .. event:: property-pre-set:<propname> \
  338. (subject, event, name, newvalue[, oldvalue])
  339. Fired before property changes state. Signature is variable,
  340. *oldvalue* is present only if there was an old value.
  341. :param name: Property name
  342. :param newvalue: New value of the property
  343. :param oldvalue: Old value of the property
  344. .. event:: property-del:<propname> \
  345. (subject, event, name[, oldvalue])
  346. Fired when property gets deleted (is set to default). Signature is
  347. variable, *oldvalue* is present only if there was an old value.
  348. :param name: Property name
  349. :param oldvalue: Old value of the property
  350. .. event:: property-pre-del:<propname> \
  351. (subject, event, name[, oldvalue])
  352. Fired before property gets deleted (is set to default). Signature
  353. is variable, *oldvalue* is present only if there was an old value.
  354. :param name: Property name
  355. :param oldvalue: Old value of the property
  356. .. event:: clone-properties (subject, event, src, proplist)
  357. :param src: object, from which we are cloning
  358. :param proplist: list of properties
  359. Members:
  360. '''
  361. def __init__(self, xml, **kwargs):
  362. self.xml = xml
  363. propvalues = {}
  364. all_names = set(prop.__name__ for prop in self.property_list())
  365. for key in list(kwargs):
  366. if not key in all_names:
  367. continue
  368. propvalues[key] = kwargs.pop(key)
  369. super(PropertyHolder, self).__init__(**kwargs)
  370. for key, value in propvalues.items():
  371. setattr(self, key, value)
  372. if self.xml is not None:
  373. # check if properties are appropriate
  374. all_names = set(prop.__name__ for prop in self.property_list())
  375. for node in self.xml.xpath('./properties/property'):
  376. name = node.get('name')
  377. if name not in all_names:
  378. raise TypeError(
  379. 'property {!r} not applicable to {!r}'.format(
  380. name, self.__class__.__name__))
  381. @classmethod
  382. def property_list(cls, load_stage=None):
  383. '''List all properties attached to this VM's class
  384. :param load_stage: Filter by load stage
  385. :type load_stage: :py:func:`int` or :py:obj:`None`
  386. '''
  387. props = set()
  388. for class_ in cls.__mro__:
  389. props.update(prop for prop in class_.__dict__.values()
  390. if isinstance(prop, property))
  391. if load_stage is not None:
  392. props = set(prop for prop in props
  393. if prop.load_stage == load_stage)
  394. return sorted(props)
  395. def _property_init(self, prop, value):
  396. '''Initialise property to a given value, without side effects.
  397. :param qubes.property prop: property object of particular interest
  398. :param value: value
  399. '''
  400. # pylint: disable=protected-access
  401. setattr(self, self.property_get_def(prop)._attr_name, value)
  402. def property_is_default(self, prop):
  403. '''Check whether property is in it's default value.
  404. Properties when unset may return some default value, so
  405. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  406. method allows for checking if the value returned is in fact it's
  407. default value.
  408. :param qubes.property prop: property object of particular interest
  409. :rtype: bool
  410. ''' # pylint: disable=protected-access
  411. # both property_get_def() and ._attr_name may throw AttributeError,
  412. # which we don't want to catch
  413. attrname = self.property_get_def(prop)._attr_name
  414. return not hasattr(self, attrname)
  415. @classmethod
  416. def property_get_def(cls, prop):
  417. '''Return property definition object.
  418. If prop is already :py:class:`qubes.property` instance, return the same
  419. object.
  420. :param prop: property object or name
  421. :type prop: qubes.property or str
  422. :rtype: qubes.property
  423. '''
  424. if isinstance(prop, qubes.property):
  425. return prop
  426. for p in cls.property_list():
  427. if p.__name__ == prop:
  428. return p
  429. raise AttributeError('No property {!r} found in {!r}'.format(
  430. prop, cls))
  431. def load_properties(self, load_stage=None):
  432. '''Load properties from immediate children of XML node.
  433. ``property-set`` events are not fired for each individual property.
  434. :param int load_stage: Stage of loading.
  435. '''
  436. if self.xml is None:
  437. return
  438. all_names = set(
  439. prop.__name__ for prop in self.property_list(load_stage))
  440. for node in self.xml.xpath('./properties/property'):
  441. name = node.get('name')
  442. value = node.get('ref') or node.text
  443. if not name in all_names:
  444. continue
  445. setattr(self, name, value)
  446. def xml_properties(self, with_defaults=False):
  447. '''Iterator that yields XML nodes representing set properties.
  448. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  449. properties which were not set explicite, but have default values \
  450. filled.
  451. '''
  452. properties = lxml.etree.Element('properties')
  453. for prop in self.property_list():
  454. # pylint: disable=protected-access
  455. try:
  456. value = getattr(
  457. self, (prop.__name__ if with_defaults else prop._attr_name))
  458. except AttributeError:
  459. continue
  460. try:
  461. value = prop._saver(self, prop, value)
  462. except property.DontSave:
  463. continue
  464. element = lxml.etree.Element('property', name=prop.__name__)
  465. if prop.save_via_ref:
  466. element.set('ref', value)
  467. else:
  468. element.text = value
  469. properties.append(element)
  470. return properties
  471. # this was clone_attrs
  472. def clone_properties(self, src, proplist=None):
  473. '''Clone properties from other object.
  474. :param PropertyHolder src: source object
  475. :param list proplist: list of properties \
  476. (:py:obj:`None` or omit for all properties except those with \
  477. :py:attr:`property.clone` set to :py:obj:`False`)
  478. '''
  479. if proplist is None:
  480. proplist = [prop for prop in self.property_list()
  481. if prop.clone]
  482. else:
  483. proplist = [prop for prop in self.property_list()
  484. if prop.__name__ in proplist or prop in proplist]
  485. for prop in proplist:
  486. try:
  487. # pylint: disable=protected-access
  488. self._property_init(prop, getattr(src, prop._attr_name))
  489. except AttributeError:
  490. continue
  491. self.fire_event('clone-properties', src=src, proplist=proplist)
  492. def property_require(self, prop, allow_none=False, hard=False):
  493. '''Complain badly when property is not set.
  494. :param prop: property name or object
  495. :type prop: qubes.property or str
  496. :param bool allow_none: if :py:obj:`True`, don't complain if \
  497. :py:obj:`None` is found
  498. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  499. if :py:obj:`False`, log warning instead
  500. '''
  501. if isinstance(prop, qubes.property):
  502. prop = prop.__name__
  503. try:
  504. value = getattr(self, prop)
  505. if value is None and not allow_none:
  506. raise AttributeError()
  507. except AttributeError:
  508. # pylint: disable=no-member
  509. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  510. if hard:
  511. raise AssertionError(msg)
  512. else:
  513. # pylint: disable=no-member
  514. self.log.fatal(msg)
  515. # pylint: disable=wrong-import-position
  516. from qubes.vm import VMProperty
  517. from qubes.app import Qubes
  518. __all__ = [
  519. 'Label',
  520. 'PropertyHolder',
  521. 'Qubes',
  522. 'VMProperty',
  523. 'property',
  524. ]