__init__.py 43 KB

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