__init__.py 45 KB

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