__init__.py 43 KB

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