__init__.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. '''
  26. Qubes OS
  27. :copyright: © 2010-2015 Invisible Things Lab
  28. '''
  29. from __future__ import absolute_import
  30. __author__ = 'Invisible Things Lab'
  31. __license__ = 'GPLv2 or later'
  32. __version__ = 'R3'
  33. import ast
  34. import atexit
  35. import collections
  36. import errno
  37. import grp
  38. import logging
  39. import os
  40. import os.path
  41. import sys
  42. import tempfile
  43. import time
  44. import warnings
  45. import __builtin__
  46. import docutils.core
  47. import docutils.io
  48. import lxml.etree
  49. import qubes.config
  50. import qubes.ext
  51. if os.name == 'posix':
  52. import fcntl
  53. elif os.name == 'nt':
  54. # pylint: disable=import-error
  55. import win32con
  56. import win32file
  57. import pywintypes
  58. else:
  59. raise RuntimeError("Qubes works only on POSIX or WinNT systems")
  60. import libvirt
  61. try:
  62. import xen.lowlevel.xs
  63. import xen.lowlevel.xc
  64. except ImportError:
  65. pass
  66. class QubesException(Exception):
  67. '''Exception that can be shown to the user'''
  68. pass
  69. import qubes.events
  70. class VMMConnection(object):
  71. '''Connection to Virtual Machine Manager (libvirt)'''
  72. def __init__(self):
  73. self._libvirt_conn = None
  74. self._xs = None
  75. self._xc = None
  76. self._offline_mode = False
  77. @__builtin__.property
  78. def offline_mode(self):
  79. '''Check or enable offline mode (do not actually connect to vmm)'''
  80. return self._offline_mode
  81. @offline_mode.setter
  82. def offline_mode(self, value):
  83. if value and self._libvirt_conn is not None:
  84. raise QubesException(
  85. "Cannot change offline mode while already connected")
  86. self._offline_mode = value
  87. def _libvirt_error_handler(self, ctx, error):
  88. pass
  89. def init_vmm_connection(self):
  90. '''Initialise connection
  91. This method is automatically called when getting'''
  92. if self._libvirt_conn is not None:
  93. # Already initialized
  94. return
  95. if self._offline_mode:
  96. # Do not initialize in offline mode
  97. raise QubesException("VMM operations disabled in offline mode")
  98. if 'xen.lowlevel.xs' in sys.modules:
  99. self._xs = xen.lowlevel.xs.xs()
  100. if 'xen.lowlevel.cs' in sys.modules:
  101. self._xc = xen.lowlevel.xc.xc()
  102. self._libvirt_conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  103. if self._libvirt_conn is None:
  104. raise QubesException("Failed connect to libvirt driver")
  105. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  106. atexit.register(self._libvirt_conn.close)
  107. @__builtin__.property
  108. def libvirt_conn(self):
  109. '''Connection to libvirt'''
  110. self.init_vmm_connection()
  111. return self._libvirt_conn
  112. @__builtin__.property
  113. def xs(self):
  114. '''Connection to Xen Store
  115. This property in available only when running on Xen.
  116. '''
  117. # XXX what about the case when we run under KVM,
  118. # but xen modules are importable?
  119. if 'xen.lowlevel.xs' not in sys.modules:
  120. raise AttributeError(
  121. 'xs object is available under Xen hypervisor only')
  122. self.init_vmm_connection()
  123. return self._xs
  124. @__builtin__.property
  125. def xc(self):
  126. '''Connection to Xen
  127. This property in available only when running on Xen.
  128. '''
  129. # XXX what about the case when we run under KVM,
  130. # but xen modules are importable?
  131. if 'xen.lowlevel.xc' not in sys.modules:
  132. raise AttributeError(
  133. 'xc object is available under Xen hypervisor only')
  134. self.init_vmm_connection()
  135. return self._xs
  136. class QubesHost(object):
  137. '''Basic information about host machine
  138. :param qubes.Qubes app: Qubes application context (must have \
  139. :py:attr:`Qubes.vmm` attribute defined)
  140. '''
  141. def __init__(self, app):
  142. self.app = app
  143. self._no_cpus = None
  144. self._total_mem = None
  145. self._physinfo = None
  146. def _fetch(self):
  147. if self._no_cpus is not None:
  148. return
  149. # pylint: disable=unused-variable
  150. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  151. self.app.vmm.libvirt_conn.getInfo()
  152. self._total_mem = long(memory) * 1024
  153. self._no_cpus = cpus
  154. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  155. self.no_cpus, self.memory_total))
  156. try:
  157. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  158. self.get_free_xen_memory()))
  159. except NotImplementedError:
  160. pass
  161. @__builtin__.property
  162. def memory_total(self):
  163. '''Total memory, in bytes'''
  164. self._fetch()
  165. return self._total_mem
  166. @__builtin__.property
  167. def no_cpus(self):
  168. '''Number of CPUs'''
  169. self._fetch()
  170. return self._no_cpus
  171. def get_free_xen_memory(self):
  172. '''Get free memory from Xen's physinfo.
  173. :raises NotImplementedError: when not under Xen
  174. '''
  175. try:
  176. self._physinfo = self.app.xc.physinfo()
  177. except AttributeError:
  178. raise NotImplementedError('This function requires Xen hypervisor')
  179. return long(self._physinfo['free_memory'])
  180. def measure_cpu_usage(self, previous_time=None, previous=None,
  181. wait_time=1):
  182. '''Measure cpu usage for all domains at once.
  183. This function requires Xen hypervisor.
  184. .. versionchanged:: 3.0
  185. argument order to match return tuple
  186. :raises NotImplementedError: when not under Xen
  187. '''
  188. if previous is None:
  189. previous_time = time.time()
  190. previous = {}
  191. try:
  192. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  193. except AttributeError:
  194. raise NotImplementedError(
  195. 'This function requires Xen hypervisor')
  196. for vm in info:
  197. previous[vm['domid']] = {}
  198. previous[vm['domid']]['cpu_time'] = (
  199. vm['cpu_time'] / vm['online_vcpus'])
  200. previous[vm['domid']]['cpu_usage'] = 0
  201. time.sleep(wait_time)
  202. current_time = time.time()
  203. current = {}
  204. try:
  205. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  206. except AttributeError:
  207. raise NotImplementedError(
  208. 'This function requires Xen hypervisor')
  209. for vm in info:
  210. current[vm['domid']] = {}
  211. current[vm['domid']]['cpu_time'] = (
  212. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  213. if vm['domid'] in previous.keys():
  214. current[vm['domid']]['cpu_usage'] = (
  215. float(current[vm['domid']]['cpu_time'] -
  216. previous[vm['domid']]['cpu_time']) /
  217. long(1000 ** 3) / (current_time - previous_time) * 100)
  218. if current[vm['domid']]['cpu_usage'] < 0:
  219. # VM has been rebooted
  220. current[vm['domid']]['cpu_usage'] = 0
  221. else:
  222. current[vm['domid']]['cpu_usage'] = 0
  223. return (current_time, current)
  224. class Label(object):
  225. '''Label definition for virtual machines
  226. Label specifies colour of the padlock displayed next to VM's name.
  227. When this is a :py:class:`qubes.vm.dispvm.DispVM`, padlock is overlayed
  228. with recycling pictogram.
  229. :param int index: numeric identificator of label
  230. :param str color: colour specification as in HTML (``#abcdef``)
  231. :param str name: label's name like "red" or "green"
  232. '''
  233. def __init__(self, index, color, name):
  234. #: numeric identificator of label
  235. self.index = index
  236. #: colour specification as in HTML (``#abcdef``)
  237. self.color = color
  238. #: label's name like "red" or "green"
  239. self.name = name
  240. #: freedesktop icon name, suitable for use in
  241. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  242. self.icon = 'appvm-' + name
  243. #: freedesktop icon name, suitable for use in
  244. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme` on DispVMs
  245. self.icon_dispvm = 'dispvm-' + name
  246. @classmethod
  247. def fromxml(cls, xml):
  248. '''Create label definition from XML node
  249. :param lxml.etree._Element xml: XML node reference
  250. :rtype: :py:class:`qubes.Label`
  251. '''
  252. index = int(xml.get('id').split('-', 1)[1])
  253. color = xml.get('color')
  254. name = xml.text
  255. return cls(index, color, name)
  256. def __xml__(self):
  257. element = lxml.etree.Element(
  258. 'label', id='label-{}'.format(self.index), color=self.color)
  259. element.text = self.name
  260. return element
  261. def __repr__(self):
  262. return '{}({!r}, {!r}, {!r})'.format(
  263. self.__class__.__name__,
  264. self.index,
  265. self.color,
  266. self.name)
  267. @__builtin__.property
  268. def icon_path(self):
  269. '''Icon path
  270. .. deprecated:: 2.0
  271. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  272. '''
  273. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  274. self.icon) + ".png"
  275. @__builtin__.property
  276. def icon_path_dispvm(self):
  277. '''Icon path
  278. .. deprecated:: 2.0
  279. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  280. '''
  281. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  282. self.icon_dispvm) + ".png"
  283. class VMCollection(object):
  284. '''A collection of Qubes VMs
  285. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  286. and whole VM object's presence.
  287. Iterating over VMCollection will yield machine objects.
  288. '''
  289. def __init__(self, app):
  290. self.app = app
  291. self._dict = dict()
  292. def __repr__(self):
  293. return '<{} {!r}>'.format(
  294. self.__class__.__name__, list(sorted(self.keys())))
  295. def items(self):
  296. '''Iterate over ``(qid, vm)`` pairs'''
  297. for qid in self.qids():
  298. yield (qid, self[qid])
  299. def qids(self):
  300. '''Iterate over all qids
  301. qids are sorted by numerical order.
  302. '''
  303. return iter(sorted(self._dict.keys()))
  304. keys = qids
  305. def names(self):
  306. '''Iterate over all names
  307. names are sorted by lexical order.
  308. '''
  309. return iter(sorted(vm.name for vm in self._dict.values()))
  310. def vms(self):
  311. '''Iterate over all machines
  312. vms are sorted by qid.
  313. '''
  314. return iter(sorted(self._dict.values()))
  315. __iter__ = vms
  316. values = vms
  317. def add(self, value):
  318. '''Add VM to collection
  319. :param qubes.vm.BaseVM value: VM to add
  320. :raises TypeError: when value is of wrong type
  321. :raises ValueError: when there is already VM which has equal ``qid``
  322. '''
  323. # this violates duck typing, but is needed
  324. # for VMProperty to function correctly
  325. if not isinstance(value, qubes.vm.BaseVM):
  326. raise TypeError('{} holds only BaseVM instances'.format(
  327. self.__class__.__name__))
  328. if not hasattr(value, 'qid'):
  329. value.qid = self.get_new_unused_qid()
  330. if value.qid in self:
  331. raise ValueError('This collection already holds VM that has '
  332. 'qid={!r} ({!r})'.format(value.qid, self[value.qid]))
  333. if value.name in self:
  334. raise ValueError('This collection already holds VM that has '
  335. 'name={!r} ({!r})'.format(value.name, self[value.name]))
  336. self._dict[value.qid] = value
  337. value.events_enabled = True
  338. self.app.fire_event('domain-added', value)
  339. def __getitem__(self, key):
  340. if isinstance(key, int):
  341. return self._dict[key]
  342. if isinstance(key, basestring):
  343. for vm in self:
  344. if vm.name == key:
  345. return vm
  346. raise KeyError(key)
  347. if isinstance(key, qubes.vm.BaseVM):
  348. if key in self:
  349. return key
  350. raise KeyError(key)
  351. raise KeyError(key)
  352. def __delitem__(self, key):
  353. vm = self[key]
  354. del self._dict[vm.qid]
  355. self.app.fire_event('domain-deleted', vm)
  356. def __contains__(self, key):
  357. return any((key == vm or key == vm.qid or key == vm.name)
  358. for vm in self)
  359. def __len__(self):
  360. return len(self._dict)
  361. def get_vms_based_on(self, template):
  362. template = self[template]
  363. return set(vm for vm in self if vm.template == template)
  364. def get_vms_connected_to(self, netvm):
  365. new_vms = set([self[netvm]])
  366. dependent_vms = set()
  367. # Dependency resolving only makes sense on NetVM (or derivative)
  368. # if not self[netvm_qid].is_netvm():
  369. # return set([])
  370. while len(new_vms) > 0:
  371. cur_vm = new_vms.pop()
  372. for vm in cur_vm.connected_vms.values():
  373. if vm in dependent_vms:
  374. continue
  375. dependent_vms.add(vm.qid)
  376. # if vm.is_netvm():
  377. new_vms.add(vm.qid)
  378. return dependent_vms
  379. # XXX with Qubes Admin Api this will probably lead to race condition
  380. # whole process of creating and adding should be synchronised
  381. def get_new_unused_qid(self):
  382. used_ids = set(self.qids())
  383. for i in range(1, qubes.config.max_qid):
  384. if i not in used_ids:
  385. return i
  386. raise LookupError("Cannot find unused qid!")
  387. def get_new_unused_netid(self):
  388. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  389. for i in range(1, qubes.config.max_netid):
  390. if i not in used_ids:
  391. return i
  392. raise LookupError("Cannot find unused netid!")
  393. class property(object): # pylint: disable=redefined-builtin,invalid-name
  394. '''Qubes property.
  395. This class holds one property that can be saved to and loaded from
  396. :file:`qubes.xml`. It is used for both global and per-VM properties.
  397. Property can be unset by ordinary ``del`` statement or assigning
  398. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  399. assignment/load) attempting to read a property will get its default value
  400. or, when no default, py:class:`exceptions.AttributeError`.
  401. :param str name: name of the property
  402. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  403. initialise value; first parameter to the function is holder instance \
  404. and the second is value; this is called before ``type``
  405. :param collections.Callable saver: function to coerce value to something \
  406. readable by setter
  407. :param type type: if not :py:obj:`None`, value is coerced to this type
  408. :param object default: default value; if callable, will be called with \
  409. holder as first argument
  410. :param int load_stage: stage when property should be loaded (see \
  411. :py:class:`Qubes` for description of stages)
  412. :param int order: order of evaluation (bigger order values are later)
  413. :param str ls_head: column head for :program:`qvm-ls`
  414. :param int ls_width: column width in :program:`qvm-ls`
  415. :param str doc: docstring; this should be one paragraph of plain RST, no \
  416. sphinx-specific features
  417. Setters and savers have following signatures:
  418. .. :py:function:: setter(self, prop, value)
  419. :noindex:
  420. :param self: instance of object that is holding property
  421. :param prop: property object
  422. :param value: value being assigned
  423. .. :py:function:: saver(self, prop, value)
  424. :noindex:
  425. :param self: instance of object that is holding property
  426. :param prop: property object
  427. :param value: value being saved
  428. :rtype: str
  429. :raises property.DontSave: when property should not be saved at all
  430. '''
  431. #: Assigning this value to property means setting it to its default value.
  432. #: If property has no default value, this will unset it.
  433. DEFAULT = object()
  434. # internal use only
  435. _NO_DEFAULT = object()
  436. def __init__(self, name, setter=None, saver=None, type=None,
  437. default=_NO_DEFAULT, load_stage=2, order=0, save_via_ref=False,
  438. ls_head=None, ls_width=None, doc=None):
  439. # pylint: disable=redefined-builtin
  440. self.__name__ = name
  441. self._setter = setter
  442. self._saver = saver if saver is not None else (
  443. lambda self, prop, value: str(value))
  444. self._type = type
  445. self._default = default
  446. self.order = order
  447. self.load_stage = load_stage
  448. self.save_via_ref = save_via_ref
  449. self.__doc__ = doc
  450. self._attr_name = '_qubesprop_' + name
  451. if ls_head is not None or ls_width is not None:
  452. self.ls_head = ls_head or self.__name__.replace('_', '-').upper()
  453. self.ls_width = max(ls_width or 0, len(self.ls_head) + 1)
  454. def __get__(self, instance, owner):
  455. if instance is None:
  456. return self
  457. # XXX this violates duck typing, shall we keep it?
  458. if not isinstance(instance, PropertyHolder):
  459. raise AttributeError('qubes.property should be used on '
  460. 'qubes.PropertyHolder instances only')
  461. try:
  462. return getattr(instance, self._attr_name)
  463. except AttributeError:
  464. if self._default is self._NO_DEFAULT:
  465. raise AttributeError(
  466. 'property {!r} not set'.format(self.__name__))
  467. elif isinstance(self._default, collections.Callable):
  468. return self._default(instance)
  469. else:
  470. return self._default
  471. def __set__(self, instance, value):
  472. if value is self.__class__.DEFAULT:
  473. self.__delete__(instance)
  474. return
  475. try:
  476. oldvalue = getattr(instance, self.__name__)
  477. has_oldvalue = True
  478. except AttributeError:
  479. has_oldvalue = False
  480. if self._setter is not None:
  481. value = self._setter(instance, self, value)
  482. if self._type is not None:
  483. value = self._type(value)
  484. if has_oldvalue:
  485. instance.fire_event_pre('property-pre-set:' + self.__name__,
  486. self.__name__, value, oldvalue)
  487. else:
  488. instance.fire_event_pre('property-pre-set:' + self.__name__,
  489. self.__name__, value)
  490. instance._property_init(self, value) # pylint: disable=protected-access
  491. if has_oldvalue:
  492. instance.fire_event('property-set:' + self.__name__, self.__name__,
  493. value, oldvalue)
  494. else:
  495. instance.fire_event('property-set:' + self.__name__, self.__name__,
  496. value)
  497. def __delete__(self, instance):
  498. try:
  499. oldvalue = getattr(instance, self.__name__)
  500. has_oldvalue = True
  501. except AttributeError:
  502. has_oldvalue = False
  503. if has_oldvalue:
  504. instance.fire_event_pre('property-pre-deleted:' + self.__name__,
  505. self.__name__, oldvalue)
  506. else:
  507. instance.fire_event_pre('property-pre-deleted:' + self.__name__,
  508. self.__name__)
  509. delattr(instance, self._attr_name)
  510. if has_oldvalue:
  511. instance.fire_event('property-deleted:' + self.__name__,
  512. self.__name__, oldvalue)
  513. else:
  514. instance.fire_event('property-deleted:' + self.__name__,
  515. self.__name__)
  516. def __repr__(self):
  517. return '<{} object at {:#x} name={!r} default={!r}>'.format(
  518. self.__class__.__name__, id(self), self.__name__, self._default)
  519. def __hash__(self):
  520. return hash(self.__name__)
  521. def __eq__(self, other):
  522. return self.__name__ == other.__name__
  523. #
  524. # exceptions
  525. #
  526. class DontSave(Exception):
  527. '''This exception may be raised from saver to sing that property should
  528. not be saved.
  529. '''
  530. pass
  531. @staticmethod
  532. def dontsave(self, prop, value):
  533. '''Dummy saver that never saves anything.'''
  534. # pylint: disable=bad-staticmethod-argument,unused-argument
  535. raise property.DontSave()
  536. #
  537. # some setters provided
  538. #
  539. @staticmethod
  540. def forbidden(self, prop, value):
  541. '''Property setter that forbids loading a property.
  542. This is used to effectively disable property in classes which inherit
  543. unwanted property. When someone attempts to load such a property, it
  544. :throws AttributeError: always
  545. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  546. raise AttributeError(
  547. 'setting {} property on {} instance is forbidden'.format(
  548. prop.__name__, self.__class__.__name__))
  549. @staticmethod
  550. def bool(self, prop, value):
  551. '''Property setter for boolean properties.
  552. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  553. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  554. :py:obj:`True`.
  555. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  556. lcvalue = value.lower()
  557. if lcvalue in ('0', 'no', 'false'):
  558. return False
  559. if lcvalue in ('1', 'yes', 'true'):
  560. return True
  561. raise ValueError(
  562. 'Invalid literal for boolean property: {!r}'.format(value))
  563. class PropertyHolder(qubes.events.Emitter):
  564. '''Abstract class for holding :py:class:`qubes.property`
  565. Events fired by instances of this class:
  566. .. event:: property-load (subject, event)
  567. Fired once after all properties are loaded from XML. Individual
  568. ``property-set`` events are not fired.
  569. .. event:: property-set:<propname> \
  570. (subject, event, name, newvalue[, oldvalue])
  571. Fired when property changes state. Signature is variable,
  572. *oldvalue* is present only if there was an old value.
  573. :param name: Property name
  574. :param newvalue: New value of the property
  575. :param oldvalue: Old value of the property
  576. .. event:: property-pre-set:<propname> \
  577. (subject, event, name, newvalue[, oldvalue])
  578. Fired before property changes state. Signature is variable,
  579. *oldvalue* is present only if there was an old value.
  580. :param name: Property name
  581. :param newvalue: New value of the property
  582. :param oldvalue: Old value of the property
  583. .. event:: property-del:<propname> \
  584. (subject, event, name[, oldvalue])
  585. Fired when property gets deleted (is set to default). Signature is
  586. variable, *oldvalue* is present only if there was an old value.
  587. :param name: Property name
  588. :param oldvalue: Old value of the property
  589. .. event:: property-pre-del:<propname> \
  590. (subject, event, name[, oldvalue])
  591. Fired before property gets deleted (is set to default). Signature
  592. is variable, *oldvalue* is present only if there was an old value.
  593. :param name: Property name
  594. :param oldvalue: Old value of the property
  595. Members:
  596. '''
  597. def __init__(self, xml, **kwargs):
  598. super(PropertyHolder, self).__init__()
  599. self.xml = xml
  600. for key, value in kwargs.items():
  601. setattr(self, key, value)
  602. all_names = set(prop.__name__ for prop in self.property_list())
  603. for key in list(kwargs.keys()):
  604. if not key in all_names:
  605. continue
  606. setattr(self, key, kwargs.pop(key))
  607. @classmethod
  608. def property_list(cls, load_stage=None):
  609. '''List all properties attached to this VM's class
  610. :param load_stage: Filter by load stage
  611. :type load_stage: :py:func:`int` or :py:obj:`None`
  612. '''
  613. props = set()
  614. for class_ in cls.__mro__:
  615. props.update(prop for prop in class_.__dict__.values()
  616. if isinstance(prop, property))
  617. if load_stage is not None:
  618. props = set(prop for prop in props
  619. if prop.load_stage == load_stage)
  620. return sorted(props,
  621. key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  622. def _property_init(self, prop, value):
  623. '''Initialise property to a given value, without side effects.
  624. :param qubes.property prop: property object of particular interest
  625. :param value: value
  626. '''
  627. # pylint: disable=protected-access
  628. setattr(self, self.property_get_def(prop)._attr_name, value)
  629. def property_is_default(self, prop):
  630. '''Check whether property is in it's default value.
  631. Properties when unset may return some default value, so
  632. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  633. method allows for checking if the value returned is in fact it's
  634. default value.
  635. :param qubes.property prop: property object of particular interest
  636. :rtype: bool
  637. '''
  638. # pylint: disable=protected-access
  639. return hasattr(self, self.property_get_def(prop)._attr_name)
  640. @classmethod
  641. def property_get_def(cls, prop):
  642. '''Return property definition object.
  643. If prop is already :py:class:`qubes.property` instance, return the same
  644. object.
  645. :param prop: property object or name
  646. :type prop: qubes.property or str
  647. :rtype: qubes.property
  648. '''
  649. if isinstance(prop, qubes.property):
  650. return prop
  651. for p in cls.property_list():
  652. if p.__name__ == prop:
  653. return p
  654. raise AttributeError('No property {!r} found in {!r}'.format(
  655. prop, cls))
  656. def load_properties(self, load_stage=None):
  657. '''Load properties from immediate children of XML node.
  658. ``property-set`` events are not fired for each individual property.
  659. :param int load_stage: Stage of loading.
  660. '''
  661. all_names = set(
  662. prop.__name__ for prop in self.property_list(load_stage))
  663. for node in self.xml.xpath('./properties/property'):
  664. name = node.get('name')
  665. value = node.get('ref') or node.text
  666. if not name in all_names:
  667. continue
  668. setattr(self, name, value)
  669. def xml_properties(self, with_defaults=False):
  670. '''Iterator that yields XML nodes representing set properties.
  671. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  672. properties which were not set explicite, but have default values \
  673. filled.
  674. '''
  675. properties = lxml.etree.Element('properties')
  676. for prop in self.property_list():
  677. # pylint: disable=protected-access
  678. try:
  679. value = getattr(
  680. self, (prop.__name__ if with_defaults else prop._attr_name))
  681. except AttributeError:
  682. continue
  683. try:
  684. value = prop._saver(self, prop, value)
  685. except property.DontSave:
  686. continue
  687. element = lxml.etree.Element('property', name=prop.__name__)
  688. if prop.save_via_ref:
  689. element.set('ref', value)
  690. else:
  691. element.text = value
  692. properties.append(element)
  693. return properties
  694. # this was clone_attrs
  695. def clone_properties(self, src, proplist=None):
  696. '''Clone properties from other object.
  697. :param PropertyHolder src: source object
  698. :param list proplist: list of properties \
  699. (:py:obj:`None` for all properties)
  700. '''
  701. if proplist is None:
  702. proplist = self.property_list()
  703. else:
  704. proplist = [prop for prop in self.property_list()
  705. if prop.__name__ in proplist or prop in proplist]
  706. for prop in self.property_list():
  707. try:
  708. # pylint: disable=protected-access
  709. self._property_init(prop, getattr(src, prop._attr_name))
  710. except AttributeError:
  711. continue
  712. self.fire_event('cloned-properties', src, proplist)
  713. def property_require(self, prop, allow_none=False, hard=False):
  714. '''Complain badly when property is not set.
  715. :param prop: property name or object
  716. :type prop: qubes.property or str
  717. :param bool allow_none: if :py:obj:`True`, don't complain if \
  718. :py:obj:`None` is found
  719. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  720. if :py:obj:`False`, log warning instead
  721. '''
  722. if isinstance(prop, qubes.property):
  723. prop = prop.__name__
  724. try:
  725. value = getattr(self, prop)
  726. if value is None and not allow_none:
  727. raise AttributeError()
  728. except AttributeError:
  729. # pylint: disable=no-member
  730. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  731. if hard:
  732. raise AssertionError(msg)
  733. else:
  734. # pylint: disable=no-member
  735. self.log.fatal(msg)
  736. import qubes.vm
  737. class VMProperty(property):
  738. '''Property that is referring to a VM
  739. :param type vmclass: class that returned VM is supposed to be instance of
  740. and all supported by :py:class:`property` with the exception of ``type`` \
  741. and ``setter``
  742. '''
  743. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False,
  744. **kwargs):
  745. if 'type' in kwargs:
  746. raise TypeError(
  747. "'type' keyword parameter is unsupported in {}".format(
  748. self.__class__.__name__))
  749. if 'setter' in kwargs:
  750. raise TypeError(
  751. "'setter' keyword parameter is unsupported in {}".format(
  752. self.__class__.__name__))
  753. if not issubclass(vmclass, qubes.vm.BaseVM):
  754. raise TypeError(
  755. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  756. super(VMProperty, self).__init__(name, **kwargs)
  757. self.vmclass = vmclass
  758. self.allow_none = allow_none
  759. def __set__(self, instance, value):
  760. if value is None:
  761. if self.allow_none:
  762. super(VMProperty, self).__set__(self, instance, value)
  763. return
  764. else:
  765. raise ValueError(
  766. 'Property {!r} does not allow setting to {!r}'.format(
  767. self.__name__, value))
  768. # XXX this may throw LookupError; that's good until introduction
  769. # of QubesNoSuchVMException or whatever
  770. vm = instance.app.domains[value]
  771. if not isinstance(vm, self.vmclass):
  772. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} '
  773. 'and not {!s}'.format(value,
  774. vm.__class__.__name__,
  775. self.vmclass.__name__))
  776. super(VMProperty, self).__set__(self, instance, vm)
  777. import qubes.vm.qubesvm
  778. import qubes.vm.templatevm
  779. class Qubes(PropertyHolder):
  780. '''Main Qubes application
  781. :param str store: path to ``qubes.xml``
  782. The store is loaded in stages:
  783. 1. In the first stage there are loaded some basic features from store
  784. (currently labels).
  785. 2. In the second stage stubs for all VMs are loaded. They are filled
  786. with their basic properties, like ``qid`` and ``name``.
  787. 3. In the third stage all global properties are loaded. They often
  788. reference VMs, like default netvm, so they should be filled after
  789. loading VMs.
  790. 4. In the fourth stage all remaining VM properties are loaded. They
  791. also need all VMs loaded, because they represent dependencies
  792. between VMs like aforementioned netvm.
  793. 5. In the fifth stage there are some fixups to ensure sane system
  794. operation.
  795. This class emits following events:
  796. .. event:: domain-added (subject, event, vm)
  797. When domain is added.
  798. :param subject: Event emitter
  799. :param event: Event name (``'domain-added'``)
  800. :param vm: Domain object
  801. .. event:: domain-deleted (subject, event, vm)
  802. When domain is deleted. VM still has reference to ``app`` object,
  803. but is not contained within VMCollection.
  804. :param subject: Event emitter
  805. :param event: Event name (``'domain-deleted'``)
  806. :param vm: Domain object
  807. Methods and attributes:
  808. '''
  809. default_netvm = VMProperty('default_netvm', load_stage=3,
  810. default=None,
  811. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  812. that AppVMs are not connected to the Internet.''')
  813. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3,
  814. default=None,
  815. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  816. that ProxyVMs (including FirewallVM) are not connected to the
  817. Internet.''')
  818. default_template = VMProperty('default_template', load_stage=3,
  819. vmclass=qubes.vm.templatevm.TemplateVM,
  820. doc='Default template for new AppVMs')
  821. updatevm = VMProperty('updatevm', load_stage=3,
  822. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  823. TemplateVMs''')
  824. clockvm = VMProperty('clockvm', load_stage=3,
  825. doc='Which VM to use as NTP proxy for updating AdminVM')
  826. default_kernel = property('default_kernel', load_stage=3,
  827. doc='Which kernel to use when not overriden in VM')
  828. def __init__(self, store=None, load=True):
  829. super(Qubes, self).__init__(xml=None)
  830. #: logger instance for logging global messages
  831. self.log = logging.getLogger('app')
  832. # pylint: disable=no-member
  833. self._extensions = set(
  834. ext(self) for ext in qubes.ext.Extension.register.values())
  835. #: collection of all VMs managed by this Qubes instance
  836. self.domains = VMCollection(self)
  837. #: collection of all available labels for VMs
  838. self.labels = {}
  839. #: Connection to VMM
  840. self.vmm = VMMConnection()
  841. #: Information about host system
  842. self.host = QubesHost(self)
  843. self._store = store if store is not None else os.path.join(
  844. qubes.config.system_path['qubes_base_dir'],
  845. qubes.config.system_path['qubes_store_filename'])
  846. if load:
  847. self.load()
  848. self.events_enabled = True
  849. def load(self):
  850. '''Open qubes.xml
  851. :throws EnvironmentError: failure on parsing store
  852. :throws xml.parsers.expat.ExpatError: failure on parsing store
  853. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  854. '''
  855. fd = os.open(self._store, os.O_RDWR) # no O_CREAT
  856. fh = os.fdopen(fd, 'rb')
  857. if os.name == 'posix':
  858. fcntl.lockf(fh, fcntl.LOCK_EX)
  859. elif os.name == 'nt':
  860. # pylint: disable=protected-access
  861. win32file.LockFileEx(
  862. win32file._get_osfhandle(fh.fileno()),
  863. win32con.LOCKFILE_EXCLUSIVE_LOCK,
  864. 0, -0x10000,
  865. pywintypes.OVERLAPPED())
  866. self.xml = lxml.etree.parse(fh)
  867. # stage 1: load labels
  868. for node in self.xml.xpath('./labels/label'):
  869. label = Label.fromxml(node)
  870. self.labels[label.index] = label
  871. # stage 2: load VMs
  872. for node in self.xml.xpath('./domains/domain'):
  873. # pylint: disable=no-member
  874. cls = qubes.vm.BaseVM.register[node.get('class')]
  875. vm = cls(self, node)
  876. vm.load_properties(load_stage=2)
  877. self.domains.add(vm)
  878. if not 0 in self.domains:
  879. self.domains.add(qubes.vm.adminvm.AdminVM(
  880. self, None, qid=0, name='dom0'))
  881. # stage 3: load global properties
  882. self.load_properties(load_stage=3)
  883. # stage 4: fill all remaining VM properties
  884. for vm in self.domains:
  885. vm.load_properties(load_stage=4)
  886. # stage 5: misc fixups
  887. self.property_require('default_fw_netvm', allow_none=True)
  888. self.property_require('default_netvm', allow_none=True)
  889. self.property_require('default_template')
  890. self.property_require('clockvm')
  891. self.property_require('updatevm')
  892. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  893. # using 123/udp port)
  894. if hasattr(self, 'clockvm'):
  895. if 'ntpd' in self.clockvm.services:
  896. if self.clockvm.services['ntpd']:
  897. self.log.warning("VM set as clockvm ({!r}) has enabled "
  898. "'ntpd' service! Expect failure when syncing time in "
  899. "dom0.".format(self.clockvm))
  900. else:
  901. self.clockvm.services['ntpd'] = False
  902. for vm in self.domains:
  903. vm.events_enabled = True
  904. vm.fire_event('domain-loaded')
  905. # intentionally do not call explicit unlock
  906. fh.close()
  907. del fh
  908. def __xml__(self):
  909. element = lxml.etree.Element('qubes')
  910. element.append(self.xml_labels())
  911. element.append(self.xml_properties())
  912. domains = lxml.etree.Element('domains')
  913. for vm in self.domains:
  914. domains.append(vm.__xml__())
  915. element.append(domains)
  916. return element
  917. def save(self):
  918. '''Save all data to qubes.xml
  919. :throws EnvironmentError: failure on saving
  920. '''
  921. fh = tempfile.NamedTemporaryFile(prefix=self._store, delete=False)
  922. if os.name == 'posix':
  923. fcntl.lockf(fh, fcntl.LOCK_EX)
  924. elif os.name == 'nt':
  925. overlapped = pywintypes.OVERLAPPED()
  926. win32file.LockFileEx(
  927. win32file._get_osfhandle(fh.fileno()),
  928. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  929. lxml.etree.ElementTree(self.__xml__()).write(
  930. fh, encoding='utf-8', pretty_print=True)
  931. fh.flush()
  932. os.chmod(fh.name, 0660)
  933. os.chown(fh.name, -1, grp.getgrnam('qubes').gr_gid)
  934. os.rename(fh.name, self._store)
  935. # intentionally do not call explicit unlock to not unlock the file
  936. # before all buffers are flushed
  937. fh.close()
  938. del fh
  939. @classmethod
  940. def create_empty_store(cls, *args, **kwargs):
  941. self = cls(*args, load=False, **kwargs)
  942. self.labels = {
  943. 1: Label(1, '0xcc0000', 'red'),
  944. 2: Label(2, '0xf57900', 'orange'),
  945. 3: Label(3, '0xedd400', 'yellow'),
  946. 4: Label(4, '0x73d216', 'green'),
  947. 5: Label(5, '0x555753', 'gray'),
  948. 6: Label(6, '0x3465a4', 'blue'),
  949. 7: Label(7, '0x75507b', 'purple'),
  950. 8: Label(8, '0x000000', 'black'),
  951. }
  952. self.domains.add(
  953. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'))
  954. self.save()
  955. return self
  956. def xml_labels(self):
  957. '''Serialise labels
  958. :rtype: lxml.etree._Element
  959. '''
  960. labels = lxml.etree.Element('labels')
  961. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  962. labels.append(label.__xml__())
  963. return labels
  964. def add_new_vm(self, vm):
  965. '''Add new Virtual Machine to colletion
  966. '''
  967. self.domains.add(vm)
  968. @qubes.events.handler('domain-pre-deleted')
  969. def on_domain_pre_deleted(self, event, vm):
  970. # pylint: disable=unused-argument
  971. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  972. appvms = self.domains.get_vms_based_on(vm)
  973. if appvms:
  974. raise QubesException(
  975. 'Cannot remove template that has dependent AppVMs. '
  976. 'Affected are: {}'.format(', '.join(
  977. vm.name for name in sorted(appvms))))
  978. @qubes.events.handler('domain-deleted')
  979. def on_domain_deleted(self, event, vm):
  980. # pylint: disable=unused-argument
  981. if self.default_netvm == vm:
  982. del self.default_netvm
  983. if self.default_fw_netvm == vm:
  984. del self.default_fw_netvm
  985. if self.clockvm == vm:
  986. del self.clockvm
  987. if self.updatevm == vm:
  988. del self.updatevm
  989. if self.default_template == vm:
  990. del self.default_template
  991. @qubes.events.handler('property-pre-set:clockvm')
  992. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  993. # pylint: disable=unused-argument,no-self-use
  994. if 'ntpd' in newvalue.services:
  995. if newvalue.services['ntpd']:
  996. raise QubesException('Cannot set {!r} as {!r} property since '
  997. 'it has ntpd enabled.'.format(newvalue, name))
  998. else:
  999. newvalue.services['ntpd'] = False
  1000. @qubes.events.handler(
  1001. 'property-pre-set:default_netvm',
  1002. 'property-pre-set:default_fw_netvm')
  1003. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1004. oldvalue=None):
  1005. # pylint: disable=unused-argument,invalid-name
  1006. if newvalue is not None and oldvalue is not None \
  1007. and oldvalue.is_running() and not newvalue.is_running() \
  1008. and self.domains.get_vms_connected_to(oldvalue):
  1009. raise QubesException('Cannot change default_netvm to domain that '
  1010. 'is not running ({!r}).'.format(newvalue))
  1011. @qubes.events.handler('property-set:default_fw_netvm')
  1012. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1013. oldvalue=None):
  1014. # pylint: disable=unused-argument,invalid-name
  1015. for vm in self.domains:
  1016. if not vm.provides_network and vm.property_is_default('netvm'):
  1017. # fire property-del:netvm as it is responsible for resetting
  1018. # netvm to it's default value
  1019. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1020. @qubes.events.handler('property-set:default_netvm')
  1021. def on_property_set_default_netvm(self, event, name, newvalue,
  1022. oldvalue=None):
  1023. # pylint: disable=unused-argument
  1024. for vm in self.domains:
  1025. if vm.provides_network and vm.property_is_default('netvm'):
  1026. # fire property-del:netvm as it is responsible for resetting
  1027. # netvm to it's default value
  1028. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1029. # load plugins
  1030. import qubes._pluginloader