__init__.py 42 KB

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