__init__.py 43 KB

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