__init__.py 43 KB

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