__init__.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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. self.app.fire_event('domain-added', value)
  338. def __getitem__(self, key):
  339. if isinstance(key, int):
  340. return self._dict[key]
  341. if isinstance(key, basestring):
  342. for vm in self:
  343. if vm.name == key:
  344. return vm
  345. raise KeyError(key)
  346. if isinstance(key, qubes.vm.BaseVM):
  347. if key in self:
  348. return key
  349. raise KeyError(key)
  350. raise KeyError(key)
  351. def __delitem__(self, key):
  352. vm = self[key]
  353. del self._dict[vm.qid]
  354. self.app.fire_event('domain-deleted', vm)
  355. def __contains__(self, key):
  356. return any((key == vm or key == vm.qid or key == vm.name)
  357. for vm in self)
  358. def __len__(self):
  359. return len(self._dict)
  360. def get_vms_based_on(self, template):
  361. template = self[template]
  362. return set(vm for vm in self if vm.template == template)
  363. def get_vms_connected_to(self, netvm):
  364. new_vms = set([self[netvm]])
  365. dependent_vms = set()
  366. # Dependency resolving only makes sense on NetVM (or derivative)
  367. # if not self[netvm_qid].is_netvm():
  368. # return set([])
  369. while len(new_vms) > 0:
  370. cur_vm = new_vms.pop()
  371. for vm in cur_vm.connected_vms.values():
  372. if vm in dependent_vms:
  373. continue
  374. dependent_vms.add(vm.qid)
  375. # if vm.is_netvm():
  376. new_vms.add(vm.qid)
  377. return dependent_vms
  378. # XXX with Qubes Admin Api this will probably lead to race condition
  379. # whole process of creating and adding should be synchronised
  380. def get_new_unused_qid(self):
  381. used_ids = set(self.qids())
  382. for i in range(1, qubes.config.max_qid):
  383. if i not in used_ids:
  384. return i
  385. raise LookupError("Cannot find unused qid!")
  386. def get_new_unused_netid(self):
  387. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  388. for i in range(1, qubes.config.max_netid):
  389. if i not in used_ids:
  390. return i
  391. raise LookupError("Cannot find unused netid!")
  392. class property(object): # pylint: disable=redefined-builtin,invalid-name
  393. '''Qubes property.
  394. This class holds one property that can be saved to and loaded from
  395. :file:`qubes.xml`. It is used for both global and per-VM properties.
  396. Property can be unset by ordinary ``del`` statement or assigning
  397. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  398. assignment/load) attempting to read a property will get its default value
  399. or, when no default, py:class:`exceptions.AttributeError`.
  400. :param str name: name of the property
  401. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  402. initialise value; first parameter to the function is holder instance \
  403. and the second is value; this is called before ``type``
  404. :param collections.Callable saver: function to coerce value to something \
  405. readable by setter
  406. :param type type: if not :py:obj:`None`, value is coerced to this type
  407. :param object default: default value; if callable, will be called with \
  408. holder as first argument
  409. :param int load_stage: stage when property should be loaded (see \
  410. :py:class:`Qubes` for description of stages)
  411. :param int order: order of evaluation (bigger order values are later)
  412. :param str ls_head: column head for :program:`qvm-ls`
  413. :param int ls_width: column width in :program:`qvm-ls`
  414. :param str doc: docstring; this should be one paragraph of plain RST, no \
  415. sphinx-specific features
  416. Setters and savers have following signatures:
  417. .. :py:function:: setter(self, prop, value)
  418. :noindex:
  419. :param self: instance of object that is holding property
  420. :param prop: property object
  421. :param value: value being assigned
  422. .. :py:function:: saver(self, prop, value)
  423. :noindex:
  424. :param self: instance of object that is holding property
  425. :param prop: property object
  426. :param value: value being saved
  427. :rtype: str
  428. :raises property.DontSave: when property should not be saved at all
  429. '''
  430. #: Assigning this value to property means setting it to its default value.
  431. #: If property has no default value, this will unset it.
  432. DEFAULT = object()
  433. # internal use only
  434. _NO_DEFAULT = object()
  435. def __init__(self, name, setter=None, saver=None, type=None,
  436. default=_NO_DEFAULT, load_stage=2, order=0, save_via_ref=False,
  437. ls_head=None, ls_width=None, doc=None):
  438. # pylint: disable=redefined-builtin
  439. self.__name__ = name
  440. self._setter = setter
  441. self._saver = saver if saver is not None else (
  442. lambda self, prop, value: str(value))
  443. self._type = type
  444. self._default = default
  445. self.order = order
  446. self.load_stage = load_stage
  447. self.save_via_ref = save_via_ref
  448. self.__doc__ = doc
  449. self._attr_name = '_qubesprop_' + name
  450. if ls_head is not None or ls_width is not None:
  451. self.ls_head = ls_head or self.__name__.replace('_', '-').upper()
  452. self.ls_width = max(ls_width or 0, len(self.ls_head) + 1)
  453. def __get__(self, instance, owner):
  454. if instance is None:
  455. return self
  456. # XXX this violates duck typing, shall we keep it?
  457. if not isinstance(instance, PropertyHolder):
  458. raise AttributeError('qubes.property should be used on '
  459. 'qubes.PropertyHolder instances only')
  460. try:
  461. return getattr(instance, self._attr_name)
  462. except AttributeError:
  463. if self._default is self._NO_DEFAULT:
  464. raise AttributeError(
  465. 'property {!r} not set'.format(self.__name__))
  466. elif isinstance(self._default, collections.Callable):
  467. return self._default(instance)
  468. else:
  469. return self._default
  470. def __set__(self, instance, value):
  471. if value is self.__class__.DEFAULT:
  472. self.__delete__(instance)
  473. return
  474. try:
  475. oldvalue = getattr(instance, self.__name__)
  476. has_oldvalue = True
  477. except AttributeError:
  478. has_oldvalue = False
  479. if self._setter is not None:
  480. value = self._setter(instance, self, value)
  481. if self._type is not None:
  482. value = self._type(value)
  483. if has_oldvalue:
  484. instance.fire_event_pre(
  485. 'property-pre-set:' + self.__name__, value, oldvalue)
  486. else:
  487. instance.fire_event_pre('property-pre-set:' + self.__name__, value)
  488. instance._property_init(self, value) # pylint: disable=protected-access
  489. if has_oldvalue:
  490. instance.fire_event(
  491. 'property-set:' + self.__name__, value, oldvalue)
  492. else:
  493. instance.fire_event('property-set:' + self.__name__, value)
  494. def __delete__(self, instance):
  495. try:
  496. oldvalue = getattr(instance, self.__name__)
  497. has_oldvalue = True
  498. except AttributeError:
  499. has_oldvalue = False
  500. if has_oldvalue:
  501. instance.fire_event_pre('property-pre-deleted:' + self.__name__,
  502. oldvalue)
  503. else:
  504. instance.fire_event_pre('property-pre-deleted:' + self.__name__)
  505. delattr(instance, self._attr_name)
  506. if has_oldvalue:
  507. instance.fire_event('property-deleted:' + self.__name__,
  508. oldvalue)
  509. else:
  510. instance.fire_event('property-deleted:' + self.__name__)
  511. def __repr__(self):
  512. return '<{} object at {:#x} name={!r} default={!r}>'.format(
  513. self.__class__.__name__, id(self), self.__name__, self._default)
  514. def __hash__(self):
  515. return hash(self.__name__)
  516. def __eq__(self, other):
  517. return self.__name__ == other.__name__
  518. #
  519. # exceptions
  520. #
  521. class DontSave(Exception):
  522. '''This exception may be raised from saver to sing that property should
  523. not be saved.
  524. '''
  525. pass
  526. @staticmethod
  527. def dontsave(self, prop, value):
  528. '''Dummy saver that never saves anything.'''
  529. # pylint: disable=bad-staticmethod-argument,unused-argument
  530. raise property.DontSave()
  531. #
  532. # some setters provided
  533. #
  534. @staticmethod
  535. def forbidden(self, prop, value):
  536. '''Property setter that forbids loading a property.
  537. This is used to effectively disable property in classes which inherit
  538. unwanted property. When someone attempts to load such a property, it
  539. :throws AttributeError: always
  540. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  541. raise AttributeError(
  542. 'setting {} property on {} instance is forbidden'.format(
  543. prop.__name__, self.__class__.__name__))
  544. @staticmethod
  545. def bool(self, prop, value):
  546. '''Property setter for boolean properties.
  547. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  548. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  549. :py:obj:`True`.
  550. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  551. lcvalue = value.lower()
  552. if lcvalue in ('0', 'no', 'false'):
  553. return False
  554. if lcvalue in ('1', 'yes', 'true'):
  555. return True
  556. raise ValueError(
  557. 'Invalid literal for boolean property: {!r}'.format(value))
  558. class PropertyHolder(qubes.events.Emitter):
  559. '''Abstract class for holding :py:class:`qubes.property`
  560. Events fired by instances of this class:
  561. .. event:: property-load (subject, event)
  562. Fired once after all properties are loaded from XML. Individual
  563. ``property-set`` events are not fired.
  564. .. event:: property-set:<propname> \
  565. (subject, event, name, newvalue[, oldvalue])
  566. Fired when property changes state. Signature is variable,
  567. *oldvalue* is present only if there was an old value.
  568. :param name: Property name
  569. :param newvalue: New value of the property
  570. :param oldvalue: Old value of the property
  571. .. event:: property-pre-set:<propname> \
  572. (subject, event, name, newvalue[, oldvalue])
  573. Fired before property changes state. Signature is variable,
  574. *oldvalue* is present only if there was an old value.
  575. :param name: Property name
  576. :param newvalue: New value of the property
  577. :param oldvalue: Old value of the property
  578. .. event:: property-del:<propname> \
  579. (subject, event, name[, oldvalue])
  580. Fired when property gets deleted (is set to default). Signature is
  581. variable, *oldvalue* is present only if there was an old value.
  582. :param name: Property name
  583. :param oldvalue: Old value of the property
  584. .. event:: property-pre-del:<propname> \
  585. (subject, event, name[, oldvalue])
  586. Fired before property gets deleted (is set to default). Signature
  587. is variable, *oldvalue* is present only if there was an old value.
  588. :param name: Property name
  589. :param oldvalue: Old value of the property
  590. Members:
  591. '''
  592. def __init__(self, xml, **kwargs):
  593. self.xml = xml
  594. for key, value in kwargs.items():
  595. setattr(self, key, value)
  596. all_names = set(prop.__name__ for prop in self.property_list())
  597. for key in list(kwargs.keys()):
  598. if not key in all_names:
  599. continue
  600. setattr(self, key, kwargs.pop(key))
  601. super(PropertyHolder, self).__init__(**kwargs)
  602. @classmethod
  603. def property_list(cls, load_stage=None):
  604. '''List all properties attached to this VM's class
  605. :param load_stage: Filter by load stage
  606. :type load_stage: :py:func:`int` or :py:obj:`None`
  607. '''
  608. props = set()
  609. for class_ in cls.__mro__:
  610. props.update(prop for prop in class_.__dict__.values()
  611. if isinstance(prop, property))
  612. if load_stage is not None:
  613. props = set(prop for prop in props
  614. if prop.load_stage == load_stage)
  615. return sorted(props,
  616. key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  617. def _property_init(self, prop, value):
  618. '''Initialise property to a given value, without side effects.
  619. :param qubes.property prop: property object of particular interest
  620. :param value: value
  621. '''
  622. # pylint: disable=protected-access
  623. setattr(self, self.property_get_def(prop)._attr_name, value)
  624. def property_is_default(self, prop):
  625. '''Check whether property is in it's default value.
  626. Properties when unset may return some default value, so
  627. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  628. method allows for checking if the value returned is in fact it's
  629. default value.
  630. :param qubes.property prop: property object of particular interest
  631. :rtype: bool
  632. '''
  633. # pylint: disable=protected-access
  634. return hasattr(self, self.property_get_def(prop)._attr_name)
  635. @classmethod
  636. def property_get_def(cls, prop):
  637. '''Return property definition object.
  638. If prop is already :py:class:`qubes.property` instance, return the same
  639. object.
  640. :param prop: property object or name
  641. :type prop: qubes.property or str
  642. :rtype: qubes.property
  643. '''
  644. if isinstance(prop, qubes.property):
  645. return prop
  646. for p in cls.property_list():
  647. if p.__name__ == prop:
  648. return p
  649. raise AttributeError('No property {!r} found in {!r}'.format(
  650. prop, cls))
  651. def load_properties(self, load_stage=None):
  652. '''Load properties from immediate children of XML node.
  653. ``property-set`` events are not fired for each individual property.
  654. :param int load_stage: Stage of loading.
  655. '''
  656. all_names = set(
  657. prop.__name__ for prop in self.property_list(load_stage))
  658. for node in self.xml.xpath('./properties/property'):
  659. name = node.get('name')
  660. value = node.get('ref') or node.text
  661. if not name in all_names:
  662. continue
  663. setattr(self, name, value)
  664. def xml_properties(self, with_defaults=False):
  665. '''Iterator that yields XML nodes representing set properties.
  666. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  667. properties which were not set explicite, but have default values \
  668. filled.
  669. '''
  670. properties = lxml.etree.Element('properties')
  671. for prop in self.property_list():
  672. # pylint: disable=protected-access
  673. try:
  674. value = getattr(
  675. self, (prop.__name__ if with_defaults else prop._attr_name))
  676. except AttributeError:
  677. continue
  678. try:
  679. value = prop._saver(self, prop, value)
  680. except property.DontSave:
  681. continue
  682. element = lxml.etree.Element('property', name=prop.__name__)
  683. if prop.save_via_ref:
  684. element.set('ref', value)
  685. else:
  686. element.text = value
  687. properties.append(element)
  688. return properties
  689. # this was clone_attrs
  690. def clone_properties(self, src, proplist=None):
  691. '''Clone properties from other object.
  692. :param PropertyHolder src: source object
  693. :param list proplist: list of properties \
  694. (:py:obj:`None` for all properties)
  695. '''
  696. if proplist is None:
  697. proplist = self.property_list()
  698. else:
  699. proplist = [prop for prop in self.property_list()
  700. if prop.__name__ in proplist or prop in proplist]
  701. for prop in self.property_list():
  702. try:
  703. # pylint: disable=protected-access
  704. self._property_init(prop, getattr(src, prop._attr_name))
  705. except AttributeError:
  706. continue
  707. self.fire_event('cloned-properties', src, proplist)
  708. def property_require(self, prop, allow_none=False, hard=False):
  709. '''Complain badly when property is not set.
  710. :param prop: property name or object
  711. :type prop: qubes.property or str
  712. :param bool allow_none: if :py:obj:`True`, don't complain if \
  713. :py:obj:`None` is found
  714. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  715. if :py:obj:`False`, log warning instead
  716. '''
  717. if isinstance(qubes.property, prop):
  718. prop = prop.__name__
  719. try:
  720. value = getattr(self, prop)
  721. if value is None and not allow_none:
  722. raise AttributeError()
  723. except AttributeError:
  724. # pylint: disable=no-member
  725. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  726. if hard:
  727. raise AssertionError(msg)
  728. else:
  729. # pylint: disable=no-member
  730. self.log.fatal(msg)
  731. import qubes.vm
  732. class VMProperty(property):
  733. '''Property that is referring to a VM
  734. :param type vmclass: class that returned VM is supposed to be instance of
  735. and all supported by :py:class:`property` with the exception of ``type`` \
  736. and ``setter``
  737. '''
  738. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False,
  739. **kwargs):
  740. if 'type' in kwargs:
  741. raise TypeError(
  742. "'type' keyword parameter is unsupported in {}".format(
  743. self.__class__.__name__))
  744. if 'setter' in kwargs:
  745. raise TypeError(
  746. "'setter' keyword parameter is unsupported in {}".format(
  747. self.__class__.__name__))
  748. if not issubclass(vmclass, qubes.vm.BaseVM):
  749. raise TypeError(
  750. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  751. super(VMProperty, self).__init__(name, **kwargs)
  752. self.vmclass = vmclass
  753. self.allow_none = allow_none
  754. def __set__(self, instance, value):
  755. if value is None:
  756. if self.allow_none:
  757. super(VMProperty, self).__set__(self, instance, value)
  758. return
  759. else:
  760. raise ValueError(
  761. 'Property {!r} does not allow setting to {!r}'.format(
  762. self.__name__, value))
  763. # XXX this may throw LookupError; that's good until introduction
  764. # of QubesNoSuchVMException or whatever
  765. vm = instance.app.domains[value]
  766. if not isinstance(vm, self.vmclass):
  767. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} '
  768. 'and not {!s}'.format(value,
  769. vm.__class__.__name__,
  770. self.vmclass.__name__))
  771. super(VMProperty, self).__set__(self, instance, vm)
  772. import qubes.vm.qubesvm
  773. import qubes.vm.templatevm
  774. class Qubes(PropertyHolder):
  775. '''Main Qubes application
  776. :param str store: path to ``qubes.xml``
  777. The store is loaded in stages:
  778. 1. In the first stage there are loaded some basic features from store
  779. (currently labels).
  780. 2. In the second stage stubs for all VMs are loaded. They are filled
  781. with their basic properties, like ``qid`` and ``name``.
  782. 3. In the third stage all global properties are loaded. They often
  783. reference VMs, like default netvm, so they should be filled after
  784. loading VMs.
  785. 4. In the fourth stage all remaining VM properties are loaded. They
  786. also need all VMs loaded, because they represent dependencies
  787. between VMs like aforementioned netvm.
  788. 5. In the fifth stage there are some fixups to ensure sane system
  789. operation.
  790. This class emits following events:
  791. .. event:: domain-added (subject, event, vm)
  792. When domain is added.
  793. :param subject: Event emitter
  794. :param event: Event name (``'domain-added'``)
  795. :param vm: Domain object
  796. .. event:: domain-deleted (subject, event, vm)
  797. When domain is deleted. VM still has reference to ``app`` object,
  798. but is not contained within VMCollection.
  799. :param subject: Event emitter
  800. :param event: Event name (``'domain-deleted'``)
  801. :param vm: Domain object
  802. Methods and attributes:
  803. '''
  804. default_netvm = VMProperty('default_netvm', load_stage=3,
  805. default=None,
  806. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  807. that AppVMs are not connected to the Internet.''')
  808. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3,
  809. default=None,
  810. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  811. that ProxyVMs (including FirewallVM) are not connected to the
  812. Internet.''')
  813. default_template = VMProperty('default_template', load_stage=3,
  814. vmclass=qubes.vm.templatevm.TemplateVM,
  815. doc='Default template for new AppVMs')
  816. updatevm = VMProperty('updatevm', load_stage=3,
  817. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  818. TemplateVMs''')
  819. clockvm = VMProperty('clockvm', load_stage=3,
  820. doc='Which VM to use as NTP proxy for updating AdminVM')
  821. default_kernel = property('default_kernel', load_stage=3,
  822. doc='Which kernel to use when not overriden in VM')
  823. def __init__(self, store=None, load=True):
  824. super(Qubes, self).__init__(xml=None)
  825. #: logger instance for logging global messages
  826. self.log = logging.getLogger('app')
  827. # pylint: disable=no-member
  828. self._extensions = set(
  829. ext(self) for ext in qubes.ext.Extension.register.values())
  830. #: collection of all VMs managed by this Qubes instance
  831. self.domains = VMCollection(self)
  832. #: collection of all available labels for VMs
  833. self.labels = {}
  834. #: Connection to VMM
  835. self.vmm = VMMConnection()
  836. #: Information about host system
  837. self.host = QubesHost(self)
  838. self._store = store if store is not None else os.path.join(
  839. qubes.config.system_path['qubes_base_dir'],
  840. qubes.config.system_path['qubes_store_filename'])
  841. if load:
  842. self.load()
  843. def load(self):
  844. '''Open qubes.xml
  845. :throws EnvironmentError: failure on parsing store
  846. :throws xml.parsers.expat.ExpatError: failure on parsing store
  847. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  848. '''
  849. fd = os.open(self._store, os.O_RDWR) # no O_CREAT
  850. fh = os.fdopen(fd, 'rb')
  851. if os.name == 'posix':
  852. fcntl.lockf(fh, fcntl.LOCK_EX)
  853. elif os.name == 'nt':
  854. # pylint: disable=protected-access
  855. win32file.LockFileEx(
  856. win32file._get_osfhandle(fh.fileno()),
  857. win32con.LOCKFILE_EXCLUSIVE_LOCK,
  858. 0, -0x10000,
  859. pywintypes.OVERLAPPED())
  860. self.xml = lxml.etree.parse(fh)
  861. # stage 1: load labels
  862. for node in self.xml.xpath('./labels/label'):
  863. label = Label.fromxml(node)
  864. self.labels[label.index] = label
  865. # stage 2: load VMs
  866. for node in self.xml.xpath('./domains/domain'):
  867. # pylint: disable=no-member
  868. cls = qubes.vm.BaseVM.register[node.get('class')]
  869. vm = cls(self, node)
  870. vm.load_properties(load_stage=2)
  871. self.domains.add(vm)
  872. if not 0 in self.domains:
  873. self.domains.add(qubes.vm.adminvm.AdminVM(
  874. self, None, qid=0, name='dom0'))
  875. # stage 3: load global properties
  876. self.load_properties(load_stage=3)
  877. # stage 4: fill all remaining VM properties
  878. for vm in self.domains:
  879. vm.load_properties(load_stage=4)
  880. # stage 5: misc fixups
  881. self.property_require('default_fw_netvm', allow_none=True)
  882. self.property_require('default_netvm', allow_none=True)
  883. self.property_require('default_template')
  884. self.property_require('clockvm')
  885. self.property_require('updatevm')
  886. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  887. # using 123/udp port)
  888. if hasattr(self, 'clockvm'):
  889. if 'ntpd' in self.clockvm.services:
  890. if self.clockvm.services['ntpd']:
  891. self.log.warning("VM set as clockvm ({!r}) has enabled "
  892. "'ntpd' service! Expect failure when syncing time in "
  893. "dom0.".format(self.clockvm))
  894. else:
  895. self.clockvm.services['ntpd'] = False
  896. for vm in self.domains:
  897. vm.events_enabled = True
  898. vm.fire_event('domain-loaded')
  899. # intentionally do not call explicit unlock
  900. fh.close()
  901. del fh
  902. def __xml__(self):
  903. element = lxml.etree.Element('qubes')
  904. element.append(self.xml_labels())
  905. element.append(self.xml_properties())
  906. domains = lxml.etree.Element('domains')
  907. for vm in self.domains:
  908. domains.append(vm.__xml__())
  909. element.append(domains)
  910. return element
  911. def save(self):
  912. '''Save all data to qubes.xml
  913. :throws EnvironmentError: failure on saving
  914. '''
  915. fh = tempfile.NamedTemporaryFile(prefix=self._store, delete=False)
  916. if os.name == 'posix':
  917. fcntl.lockf(fh, fcntl.LOCK_EX)
  918. elif os.name == 'nt':
  919. overlapped = pywintypes.OVERLAPPED()
  920. win32file.LockFileEx(
  921. win32file._get_osfhandle(fh.fileno()),
  922. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  923. lxml.etree.ElementTree(self.__xml__()).write(
  924. fh, encoding='utf-8', pretty_print=True)
  925. fh.flush()
  926. os.chmod(fh.name, 0660)
  927. os.chown(fh.name, -1, grp.getgrnam('qubes').gr_gid)
  928. os.rename(fh.name, self._store)
  929. # intentionally do not call explicit unlock to not unlock the file
  930. # before all buffers are flushed
  931. fh.close()
  932. del fh
  933. @classmethod
  934. def create_empty_store(cls, *args, **kwargs):
  935. self = cls(*args, load=False, **kwargs)
  936. self.labels = {
  937. 1: Label(1, '0xcc0000', 'red'),
  938. 2: Label(2, '0xf57900', 'orange'),
  939. 3: Label(3, '0xedd400', 'yellow'),
  940. 4: Label(4, '0x73d216', 'green'),
  941. 5: Label(5, '0x555753', 'gray'),
  942. 6: Label(6, '0x3465a4', 'blue'),
  943. 7: Label(7, '0x75507b', 'purple'),
  944. 8: Label(8, '0x000000', 'black'),
  945. }
  946. self.domains.add(
  947. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'))
  948. self.save()
  949. return self
  950. def xml_labels(self):
  951. '''Serialise labels
  952. :rtype: lxml.etree._Element
  953. '''
  954. labels = lxml.etree.Element('labels')
  955. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  956. labels.append(label.__xml__())
  957. return labels
  958. def add_new_vm(self, vm):
  959. '''Add new Virtual Machine to colletion
  960. '''
  961. self.domains.add(vm)
  962. @qubes.events.handler('domain-pre-deleted')
  963. def on_domain_pre_deleted(self, event, vm):
  964. # pylint: disable=unused-argument
  965. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  966. appvms = self.domains.get_vms_based_on(vm)
  967. if appvms:
  968. raise QubesException(
  969. 'Cannot remove template that has dependent AppVMs. '
  970. 'Affected are: {}'.format(', '.join(
  971. vm.name for name in sorted(appvms))))
  972. @qubes.events.handler('domain-deleted')
  973. def on_domain_deleted(self, event, vm):
  974. # pylint: disable=unused-argument
  975. if self.default_netvm == vm:
  976. del self.default_netvm
  977. if self.default_fw_netvm == vm:
  978. del self.default_fw_netvm
  979. if self.clockvm == vm:
  980. del self.clockvm
  981. if self.updatevm == vm:
  982. del self.updatevm
  983. if self.default_template == vm:
  984. del self.default_template
  985. @qubes.events.handler('property-pre-set:clockvm')
  986. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  987. # pylint: disable=unused-argument,no-self-use
  988. if 'ntpd' in newvalue.services:
  989. if newvalue.services['ntpd']:
  990. raise QubesException('Cannot set {!r} as {!r} property since '
  991. 'it has ntpd enabled.'.format(newvalue, name))
  992. else:
  993. newvalue.services['ntpd'] = False
  994. @qubes.events.handler(
  995. 'property-pre-set:default_netvm',
  996. 'property-pre-set:default_fw_netvm')
  997. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  998. oldvalue=None):
  999. # pylint: disable=unused-argument,invalid-name
  1000. if newvalue is not None and oldvalue is not None \
  1001. and oldvalue.is_running() and not newvalue.is_running() \
  1002. and self.domains.get_vms_connected_to(oldvalue):
  1003. raise QubesException('Cannot change default_netvm to domain that '
  1004. 'is not running ({!r}).'.format(newvalue))
  1005. @qubes.events.handler('property-set:default_fw_netvm')
  1006. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1007. oldvalue=None):
  1008. # pylint: disable=unused-argument,invalid-name
  1009. for vm in self.domains:
  1010. if not vm.provides_network and vm.property_is_default('netvm'):
  1011. # fire property-del:netvm as it is responsible for resetting
  1012. # netvm to it's default value
  1013. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1014. @qubes.events.handler('property-set:default_netvm')
  1015. def on_property_set_default_netvm(self, event, name, newvalue,
  1016. oldvalue=None):
  1017. # pylint: disable=unused-argument
  1018. for vm in self.domains:
  1019. if vm.provides_network and vm.property_is_default('netvm'):
  1020. # fire property-del:netvm as it is responsible for resetting
  1021. # netvm to it's default value
  1022. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1023. # load plugins
  1024. import qubes._pluginloader