__init__.py 43 KB

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