qubes.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. from __future__ import absolute_import
  24. import atexit
  25. import grp
  26. import logging
  27. import os
  28. import os.path
  29. import sys
  30. import tempfile
  31. import time
  32. import warnings
  33. import xml.parsers.expat
  34. import lxml.etree
  35. if os.name == 'posix':
  36. import fcntl
  37. elif os.name == 'nt':
  38. import win32con
  39. import win32file
  40. import pywintypes
  41. else:
  42. raise RuntimeError, "Qubes works only on POSIX or WinNT systems"
  43. # Do not use XenAPI or create/read any VM files
  44. # This is for testing only!
  45. dry_run = False
  46. #dry_run = True
  47. if not dry_run:
  48. import libvirt
  49. try:
  50. import xen.lowlevel.xs
  51. except ImportError:
  52. pass
  53. qubes_base_dir = "/var/lib/qubes"
  54. system_path = {
  55. 'qubes_guid_path': '/usr/bin/qubes-guid',
  56. 'qrexec_daemon_path': '/usr/lib/qubes/qrexec-daemon',
  57. 'qrexec_client_path': '/usr/lib/qubes/qrexec-client',
  58. 'qubesdb_daemon_path': '/usr/sbin/qubesdb-daemon',
  59. 'qubes_base_dir': qubes_base_dir,
  60. # Relative to qubes_base_dir
  61. 'qubes_appvms_dir': 'appvms',
  62. 'qubes_templates_dir': 'vm-templates',
  63. 'qubes_servicevms_dir': 'servicevms',
  64. 'qubes_store_filename': 'qubes.xml',
  65. 'qubes_kernels_base_dir': 'vm-kernels',
  66. # qubes_icon_dir is obsolete
  67. # use QIcon.fromTheme() where applicable
  68. 'qubes_icon_dir': '/usr/share/icons/hicolor/128x128/devices',
  69. 'qrexec_policy_dir': '/etc/qubes-rpc/policy',
  70. 'config_template_pv': '/usr/share/qubes/vm-template.xml',
  71. 'qubes_pciback_cmd': '/usr/lib/qubes/unbind-pci-device.sh',
  72. 'prepare_volatile_img_cmd': '/usr/lib/qubes/prepare-volatile-img.sh',
  73. }
  74. vm_files = {
  75. 'root_img': 'root.img',
  76. 'rootcow_img': 'root-cow.img',
  77. 'volatile_img': 'volatile.img',
  78. 'private_img': 'private.img',
  79. 'kernels_subdir': 'kernels',
  80. 'firewall_conf': 'firewall.xml',
  81. 'whitelisted_appmenus': 'whitelisted-appmenus.list',
  82. 'updates_stat_file': 'updates.stat',
  83. }
  84. defaults = {
  85. 'libvirt_uri': 'xen:///',
  86. 'memory': 400,
  87. 'kernelopts': "nopat",
  88. 'kernelopts_pcidevs': "nopat iommu=soft swiotlb=4096",
  89. 'dom0_update_check_interval': 6*3600,
  90. 'private_img_size': 2*1024*1024*1024,
  91. 'root_img_size': 10*1024*1024*1024,
  92. 'storage_class': None,
  93. # how long (in sec) to wait for VMs to shutdown,
  94. # before killing them (when used qvm-run with --wait option),
  95. 'shutdown_counter_max': 60,
  96. 'vm_default_netmask': "255.255.255.0",
  97. # Set later
  98. 'appvm_label': None,
  99. 'template_label': None,
  100. 'servicevm_label': None,
  101. }
  102. qubes_max_qid = 254
  103. qubes_max_netid = 254
  104. class QubesException (Exception):
  105. pass
  106. class QubesVMMConnection(object):
  107. def __init__(self):
  108. self._libvirt_conn = None
  109. self._xs = None
  110. self._xc = None
  111. self._offline_mode = False
  112. @property
  113. def offline_mode(self):
  114. return self._offline_mode
  115. @offline_mode.setter
  116. def offline_mode(self, value):
  117. if not value and self._libvirt_conn is not None:
  118. raise QubesException("Cannot change offline mode while already connected")
  119. self._offline_mode = value
  120. def _libvirt_error_handler(self, ctx, error):
  121. pass
  122. def init_vmm_connection(self):
  123. if self._libvirt_conn is not None:
  124. # Already initialized
  125. return
  126. if self._offline_mode:
  127. # Do not initialize in offline mode
  128. return
  129. if 'xen.lowlevel.xs' in sys.modules:
  130. self._xs = xen.lowlevel.xs.xs()
  131. libvirt.virEventRegisterDefaultImpl()
  132. self._libvirt_conn = libvirt.open(defaults['libvirt_uri'])
  133. if self._libvirt_conn == None:
  134. raise QubesException("Failed connect to libvirt driver")
  135. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  136. atexit.register(self._libvirt_conn.close)
  137. def _common_getter(self, name):
  138. if self._offline_mode:
  139. # Do not initialize in offline mode
  140. raise QubesException("VMM operations disabled in offline mode")
  141. if self._libvirt_conn is None:
  142. self.init_vmm_connection()
  143. return getattr(self, name)
  144. @property
  145. def libvirt_conn(self):
  146. return self._common_getter('_libvirt_conn')
  147. @property
  148. def xs(self):
  149. if 'xen.lowlevel.xs' in sys.modules:
  150. return self._common_getter('_xs')
  151. else:
  152. return None
  153. ##### VMM global variable definition #####
  154. if not dry_run:
  155. vmm = QubesVMMConnection()
  156. ##########################################
  157. class QubesHost(object):
  158. def __init__(self):
  159. (model, memory, cpus, mhz, nodes, socket, cores, threads) = vmm.libvirt_conn.getInfo()
  160. self._total_mem = long(memory)*1024
  161. self._no_cpus = cpus
  162. # print "QubesHost: total_mem = {0}B".format (self.xen_total_mem)
  163. # print "QubesHost: free_mem = {0}".format (self.get_free_xen_memory())
  164. # print "QubesHost: total_cpus = {0}".format (self.xen_no_cpus)
  165. @property
  166. def memory_total(self):
  167. return self._total_mem
  168. @property
  169. def no_cpus(self):
  170. return self._no_cpus
  171. # TODO
  172. def measure_cpu_usage(self, qvmc, previous=None, previous_time = None,
  173. wait_time=1):
  174. """measure cpu usage for all domains at once"""
  175. if previous is None:
  176. previous_time = time.time()
  177. previous = {}
  178. for vm in qvmc.values():
  179. if not vm.is_running():
  180. continue
  181. cputime = vm.get_cputime()
  182. previous[vm.xid] = {}
  183. previous[vm.xid]['cpu_time'] = (
  184. cputime / vm.vcpus)
  185. previous[vm.xid]['cpu_usage'] = 0
  186. time.sleep(wait_time)
  187. current_time = time.time()
  188. current = {}
  189. for vm in qvmc.values():
  190. if not vm.is_running():
  191. continue
  192. cputime = vm.get_cputime()
  193. current[vm.xid] = {}
  194. current[vm.xid]['cpu_time'] = (
  195. cputime / max(vm.vcpus, 1))
  196. if vm.xid in previous.keys():
  197. current[vm.xid]['cpu_usage'] = (
  198. float(current[vm.xid]['cpu_time'] -
  199. previous[vm.xid]['cpu_time']) /
  200. long(1000**3) / (current_time-previous_time) * 100)
  201. if current[vm.xid]['cpu_usage'] < 0:
  202. # VM has been rebooted
  203. current[vm.xid]['cpu_usage'] = 0
  204. else:
  205. current[vm.xid]['cpu_usage'] = 0
  206. return (current_time, current)
  207. class QubesVmLabel(object):
  208. def __init__(self, index, color, name, dispvm=False):
  209. self.index = index
  210. self.color = color
  211. self.name = name
  212. self.dispvm = dispvm
  213. self.icon = '{}-{}'.format(('dispvm' if dispvm else 'appvm'), name)
  214. def __repr__(self):
  215. return '{}({!r}, {!r}, {!r}, dispvm={!r})'.format(
  216. self.__class__.__name__,
  217. self.index,
  218. self.color,
  219. self.name,
  220. self.dispvm)
  221. # self.icon_path is obsolete
  222. # use QIcon.fromTheme(label.icon) where applicable
  223. @property
  224. def icon_path(self):
  225. return os.path.join(system_path['qubes_icon_dir'], self.icon) + ".png"
  226. def register_qubes_vm_class(vm_class):
  227. QubesVmClasses[vm_class.__name__] = vm_class
  228. # register class as local for this module - to make it easy to import from
  229. # other modules
  230. setattr(sys.modules[__name__], vm_class.__name__, vm_class)
  231. class QubesVmCollection(dict):
  232. """
  233. A collection of Qubes VMs indexed by Qubes id (qid)
  234. """
  235. def __init__(self, store_filename=None):
  236. super(QubesVmCollection, self).__init__()
  237. self.default_netvm_qid = None
  238. self.default_fw_netvm_qid = None
  239. self.default_template_qid = None
  240. self.default_kernel = None
  241. self.updatevm_qid = None
  242. self.qubes_store_filename = store_filename
  243. if not store_filename:
  244. self.qubes_store_filename = system_path["qubes_store_filename"]
  245. self.clockvm_qid = None
  246. self.qubes_store_file = None
  247. self.log = logging.getLogger('qubes.qvmc.{:x}'.format(id(self)))
  248. self.log.debug('instantiated store_filename={!r}'.format(
  249. self.qubes_store_filename))
  250. def __repr__(self):
  251. return '<{} {!r}>'.format(self.__class__.__name__, list(sorted(self.keys())))
  252. def clear(self):
  253. self.log.debug('clear()')
  254. super(QubesVmCollection, self).clear()
  255. def values(self):
  256. for qid in self.keys():
  257. yield self[qid]
  258. def items(self):
  259. for qid in self.keys():
  260. yield (qid, self[qid])
  261. def __iter__(self):
  262. for qid in sorted(super(QubesVmCollection, self).keys()):
  263. yield qid
  264. keys = __iter__
  265. def __setitem__(self, key, value):
  266. self.log.debug('[{!r}] = {!r}'.format(key, value))
  267. if key not in self:
  268. return super(QubesVmCollection, self).__setitem__(key, value)
  269. else:
  270. assert False, "Attempt to add VM with qid that already exists in the collection!"
  271. def add_new_vm(self, vm_type, **kwargs):
  272. self.log.debug('add_new_vm(vm_type={}, **kwargs={!r})'.format(
  273. vm_type, kwargs))
  274. if vm_type not in QubesVmClasses.keys():
  275. raise ValueError("Unknown VM type: %s" % vm_type)
  276. qid = self.get_new_unused_qid()
  277. vm_cls = QubesVmClasses[vm_type]
  278. if 'template' in kwargs:
  279. if not vm_cls.is_template_compatible(kwargs['template']):
  280. raise QubesException("Template not compatible with selected "
  281. "VM type")
  282. vm = vm_cls(qid=qid, collection=self, **kwargs)
  283. if not self.verify_new_vm(vm):
  284. raise QubesException("Wrong VM description!")
  285. self[vm.qid] = vm
  286. # make first created NetVM the default one
  287. if self.default_fw_netvm_qid is None and vm.is_netvm():
  288. self.set_default_fw_netvm(vm)
  289. if self.default_netvm_qid is None and vm.is_proxyvm():
  290. self.set_default_netvm(vm)
  291. # make first created TemplateVM the default one
  292. if self.default_template_qid is None and vm.is_template():
  293. self.set_default_template(vm)
  294. # make first created ProxyVM the UpdateVM
  295. if self.updatevm_qid is None and vm.is_proxyvm():
  296. self.set_updatevm_vm(vm)
  297. # by default ClockVM is the first NetVM
  298. if self.clockvm_qid is None and vm.is_netvm():
  299. self.set_clockvm_vm(vm)
  300. return vm
  301. def add_new_appvm(self, name, template,
  302. dir_path = None, conf_file = None,
  303. private_img = None,
  304. label = None):
  305. warnings.warn("Call to deprecated function, use add_new_vm instead",
  306. DeprecationWarning, stacklevel=2)
  307. return self.add_new_vm("QubesAppVm", name=name, template=template,
  308. dir_path=dir_path, conf_file=conf_file,
  309. private_img=private_img,
  310. netvm = self.get_default_netvm(),
  311. kernel = self.get_default_kernel(),
  312. uses_default_kernel = True,
  313. label=label)
  314. def add_new_hvm(self, name, label = None):
  315. warnings.warn("Call to deprecated function, use add_new_vm instead",
  316. DeprecationWarning, stacklevel=2)
  317. return self.add_new_vm("QubesHVm", name=name, label=label)
  318. def add_new_disposablevm(self, name, template, dispid,
  319. label = None, netvm = None):
  320. warnings.warn("Call to deprecated function, use add_new_vm instead",
  321. DeprecationWarning, stacklevel=2)
  322. return self.add_new_vm("QubesDisposableVm", name=name, template=template,
  323. netvm = netvm,
  324. label=label, dispid=dispid)
  325. def add_new_templatevm(self, name,
  326. dir_path = None, conf_file = None,
  327. root_img = None, private_img = None,
  328. installed_by_rpm = True):
  329. warnings.warn("Call to deprecated function, use add_new_vm instead",
  330. DeprecationWarning, stacklevel=2)
  331. return self.add_new_vm("QubesTemplateVm", name=name,
  332. dir_path=dir_path, conf_file=conf_file,
  333. root_img=root_img, private_img=private_img,
  334. installed_by_rpm=installed_by_rpm,
  335. netvm = self.get_default_netvm(),
  336. kernel = self.get_default_kernel(),
  337. uses_default_kernel = True)
  338. def add_new_netvm(self, name, template,
  339. dir_path = None, conf_file = None,
  340. private_img = None, installed_by_rpm = False,
  341. label = None):
  342. warnings.warn("Call to deprecated function, use add_new_vm instead",
  343. DeprecationWarning, stacklevel=2)
  344. return self.add_new_vm("QubesNetVm", name=name, template=template,
  345. label=label,
  346. private_img=private_img, installed_by_rpm=installed_by_rpm,
  347. uses_default_kernel = True,
  348. dir_path=dir_path, conf_file=conf_file)
  349. def add_new_proxyvm(self, name, template,
  350. dir_path = None, conf_file = None,
  351. private_img = None, installed_by_rpm = False,
  352. label = None):
  353. warnings.warn("Call to deprecated function, use add_new_vm instead",
  354. DeprecationWarning, stacklevel=2)
  355. return self.add_new_vm("QubesProxyVm", name=name, template=template,
  356. label=label,
  357. private_img=private_img, installed_by_rpm=installed_by_rpm,
  358. dir_path=dir_path, conf_file=conf_file,
  359. uses_default_kernel = True,
  360. netvm = self.get_default_fw_netvm())
  361. def set_default_template(self, vm):
  362. self.log.debug('set_default_template({!r})'.format(vm))
  363. if vm is None:
  364. self.default_template_qid = None
  365. else:
  366. assert vm.is_template(), "VM {0} is not a TemplateVM!".format(vm.name)
  367. self.default_template_qid = vm.qid
  368. def get_default_template(self):
  369. if self.default_template_qid is None:
  370. return None
  371. else:
  372. return self[self.default_template_qid]
  373. def set_default_netvm(self, vm):
  374. self.log.debug('set_default_netvm({!r})'.format(vm))
  375. if vm is None:
  376. self.default_netvm_qid = None
  377. else:
  378. assert vm.is_netvm(), "VM {0} does not provide network!".format(vm.name)
  379. self.default_netvm_qid = vm.qid
  380. def get_default_netvm(self):
  381. if self.default_netvm_qid is None:
  382. return None
  383. else:
  384. return self[self.default_netvm_qid]
  385. def set_default_kernel(self, kernel):
  386. self.log.debug('set_default_kernel({!r})'.format(kernel))
  387. assert os.path.exists(
  388. os.path.join(system_path["qubes_kernels_base_dir"], kernel)), \
  389. "Kerel {0} not installed!".format(kernel)
  390. self.default_kernel = kernel
  391. def get_default_kernel(self):
  392. return self.default_kernel
  393. def set_default_fw_netvm(self, vm):
  394. self.log.debug('set_default_fw_netvm({!r})'.format(vm))
  395. if vm is None:
  396. self.default_fw_netvm_qid = None
  397. else:
  398. assert vm.is_netvm(), "VM {0} does not provide network!".format(vm.name)
  399. self.default_fw_netvm_qid = vm.qid
  400. def get_default_fw_netvm(self):
  401. if self.default_fw_netvm_qid is None:
  402. return None
  403. else:
  404. return self[self.default_fw_netvm_qid]
  405. def set_updatevm_vm(self, vm):
  406. self.log.debug('set_updatevm_vm({!r})'.format(vm))
  407. if vm is None:
  408. self.updatevm_qid = None
  409. else:
  410. self.updatevm_qid = vm.qid
  411. def get_updatevm_vm(self):
  412. if self.updatevm_qid is None:
  413. return None
  414. else:
  415. return self[self.updatevm_qid]
  416. def set_clockvm_vm(self, vm):
  417. self.log.debug('set_clockvm({!r})'.format(vm))
  418. if vm is None:
  419. self.clockvm_qid = None
  420. else:
  421. self.clockvm_qid = vm.qid
  422. def get_clockvm_vm(self):
  423. if self.clockvm_qid is None:
  424. return None
  425. else:
  426. return self[self.clockvm_qid]
  427. def get_vm_by_name(self, name):
  428. for vm in self.values():
  429. if (vm.name == name):
  430. return vm
  431. return None
  432. def get_qid_by_name(self, name):
  433. vm = self.get_vm_by_name(name)
  434. return vm.qid if vm is not None else None
  435. def get_vms_based_on(self, template_qid):
  436. vms = set([vm for vm in self.values()
  437. if (vm.template and vm.template.qid == template_qid)])
  438. return vms
  439. def get_vms_connected_to(self, netvm_qid):
  440. new_vms = [ netvm_qid ]
  441. dependend_vms_qid = []
  442. # Dependency resolving only makes sense on NetVM (or derivative)
  443. if not self[netvm_qid].is_netvm():
  444. return set([])
  445. while len(new_vms) > 0:
  446. cur_vm = new_vms.pop()
  447. for vm in self[cur_vm].connected_vms.values():
  448. if vm.qid not in dependend_vms_qid:
  449. dependend_vms_qid.append(vm.qid)
  450. if vm.is_netvm():
  451. new_vms.append(vm.qid)
  452. vms = [vm for vm in self.values() if vm.qid in dependend_vms_qid]
  453. return vms
  454. def verify_new_vm(self, new_vm):
  455. # Verify that qid is unique
  456. for vm in self.values():
  457. if vm.qid == new_vm.qid:
  458. print >> sys.stderr, "ERROR: The qid={0} is already used by VM '{1}'!".\
  459. format(vm.qid, vm.name)
  460. return False
  461. # Verify that name is unique
  462. for vm in self.values():
  463. if vm.name == new_vm.name:
  464. print >> sys.stderr, \
  465. "ERROR: The name={0} is already used by other VM with qid='{1}'!".\
  466. format(vm.name, vm.qid)
  467. return False
  468. return True
  469. def get_new_unused_qid(self):
  470. used_ids = set([vm.qid for vm in self.values()])
  471. for id in range (1, qubes_max_qid):
  472. if id not in used_ids:
  473. return id
  474. raise LookupError ("Cannot find unused qid!")
  475. def get_new_unused_netid(self):
  476. used_ids = set([vm.netid for vm in self.values() if vm.is_netvm()])
  477. for id in range (1, qubes_max_netid):
  478. if id not in used_ids:
  479. return id
  480. raise LookupError ("Cannot find unused netid!")
  481. def check_if_storage_exists(self):
  482. try:
  483. f = open (self.qubes_store_filename, 'r')
  484. except IOError:
  485. return False
  486. f.close()
  487. return True
  488. def create_empty_storage(self):
  489. self.log.debug('create_empty_storage()')
  490. self.qubes_store_file = open (self.qubes_store_filename, 'w')
  491. self.clear()
  492. self.save()
  493. def lock_db_for_reading(self):
  494. if self.qubes_store_file is not None:
  495. raise QubesException("lock already taken")
  496. # save() would rename the file over qubes.xml, _then_ release lock,
  497. # so we need to ensure that the file for which we've got the lock is
  498. # still the right file
  499. self.log.debug('lock_db_for_reading()')
  500. while True:
  501. self.qubes_store_file = open (self.qubes_store_filename, 'r')
  502. if os.name == 'posix':
  503. fcntl.lockf (self.qubes_store_file, fcntl.LOCK_SH)
  504. elif os.name == 'nt':
  505. overlapped = pywintypes.OVERLAPPED()
  506. win32file.LockFileEx(win32file._get_osfhandle(self.qubes_store_file.fileno()),
  507. 0, 0, -0x10000, overlapped)
  508. if os.fstat(self.qubes_store_file.fileno()) == os.stat(
  509. self.qubes_store_filename):
  510. break
  511. self.qubes_store_file.close()
  512. def lock_db_for_writing(self):
  513. if self.qubes_store_file is not None:
  514. raise QubesException("lock already taken")
  515. # save() would rename the file over qubes.xml, _then_ release lock,
  516. # so we need to ensure that the file for which we've got the lock is
  517. # still the right file
  518. self.log.debug('lock_db_for_writing()')
  519. while True:
  520. self.qubes_store_file = open (self.qubes_store_filename, 'r+')
  521. if os.name == 'posix':
  522. fcntl.lockf (self.qubes_store_file, fcntl.LOCK_EX)
  523. elif os.name == 'nt':
  524. overlapped = pywintypes.OVERLAPPED()
  525. win32file.LockFileEx(win32file._get_osfhandle(self.qubes_store_file.fileno()),
  526. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  527. if os.fstat(self.qubes_store_file.fileno()) == os.stat(
  528. self.qubes_store_filename):
  529. break
  530. self.qubes_store_file.close()
  531. def unlock_db(self):
  532. # intentionally do not call explicit unlock to not unlock the file
  533. # before all buffers are flushed
  534. self.log.debug('unlock_db()')
  535. self.qubes_store_file.close()
  536. self.qubes_store_file = None
  537. def save(self):
  538. self.log.debug('save()')
  539. root = lxml.etree.Element(
  540. "QubesVmCollection",
  541. default_template=str(self.default_template_qid) \
  542. if self.default_template_qid is not None else "None",
  543. default_netvm=str(self.default_netvm_qid) \
  544. if self.default_netvm_qid is not None else "None",
  545. default_fw_netvm=str(self.default_fw_netvm_qid) \
  546. if self.default_fw_netvm_qid is not None else "None",
  547. updatevm=str(self.updatevm_qid) \
  548. if self.updatevm_qid is not None else "None",
  549. clockvm=str(self.clockvm_qid) \
  550. if self.clockvm_qid is not None else "None",
  551. default_kernel=str(self.default_kernel) \
  552. if self.default_kernel is not None else "None",
  553. )
  554. for vm in self.values():
  555. element = vm.create_xml_element()
  556. if element is not None:
  557. root.append(element)
  558. tree = lxml.etree.ElementTree(root)
  559. try:
  560. new_store_file = tempfile.NamedTemporaryFile(prefix=self.qubes_store_filename, delete=False)
  561. if os.name == 'posix':
  562. fcntl.lockf (new_store_file, fcntl.LOCK_EX)
  563. elif os.name == 'nt':
  564. overlapped = pywintypes.OVERLAPPED()
  565. win32file.LockFileEx(win32file._get_osfhandle(new_store_file.fileno()),
  566. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  567. tree.write(new_store_file, encoding="UTF-8", pretty_print=True)
  568. new_store_file.flush()
  569. os.chmod(new_store_file.name, 0660)
  570. os.chown(new_store_file.name, -1, grp.getgrnam('qubes').gr_gid)
  571. os.rename(new_store_file.name, self.qubes_store_filename)
  572. self.qubes_store_file.close()
  573. self.qubes_store_file = new_store_file
  574. except EnvironmentError as err:
  575. print("{0}: export error: {1}".format(
  576. os.path.basename(sys.argv[0]), err))
  577. return False
  578. return True
  579. def set_netvm_dependency(self, element):
  580. kwargs = {}
  581. attr_list = ("qid", "uses_default_netvm", "netvm_qid")
  582. for attribute in attr_list:
  583. kwargs[attribute] = element.get(attribute)
  584. vm = self[int(kwargs["qid"])]
  585. if "uses_default_netvm" not in kwargs:
  586. vm.uses_default_netvm = True
  587. else:
  588. vm.uses_default_netvm = (
  589. True if kwargs["uses_default_netvm"] == "True" else False)
  590. if vm.uses_default_netvm is True:
  591. if vm.is_proxyvm():
  592. netvm = self.get_default_fw_netvm()
  593. else:
  594. netvm = self.get_default_netvm()
  595. kwargs.pop("netvm_qid")
  596. else:
  597. if kwargs["netvm_qid"] == "none" or kwargs["netvm_qid"] is None:
  598. netvm = None
  599. kwargs.pop("netvm_qid")
  600. else:
  601. netvm_qid = int(kwargs.pop("netvm_qid"))
  602. if netvm_qid not in self:
  603. netvm = None
  604. else:
  605. netvm = self[netvm_qid]
  606. # directly set internal attr to not call setters...
  607. vm._netvm = netvm
  608. if netvm:
  609. netvm.connected_vms[vm.qid] = vm
  610. def load_globals(self, element):
  611. default_template = element.get("default_template")
  612. self.default_template_qid = int(default_template) \
  613. if default_template.lower() != "none" else None
  614. default_netvm = element.get("default_netvm")
  615. if default_netvm is not None:
  616. self.default_netvm_qid = int(default_netvm) \
  617. if default_netvm != "None" else None
  618. #assert self.default_netvm_qid is not None
  619. default_fw_netvm = element.get("default_fw_netvm")
  620. if default_fw_netvm is not None:
  621. self.default_fw_netvm_qid = int(default_fw_netvm) \
  622. if default_fw_netvm != "None" else None
  623. #assert self.default_netvm_qid is not None
  624. updatevm = element.get("updatevm")
  625. if updatevm is not None:
  626. self.updatevm_qid = int(updatevm) \
  627. if updatevm != "None" else None
  628. #assert self.default_netvm_qid is not None
  629. clockvm = element.get("clockvm")
  630. if clockvm is not None:
  631. self.clockvm_qid = int(clockvm) \
  632. if clockvm != "None" else None
  633. self.default_kernel = element.get("default_kernel")
  634. def _check_global(self, attr, default):
  635. qid = getattr(self, attr)
  636. if qid is None:
  637. return
  638. try:
  639. self[qid]
  640. except KeyError:
  641. setattr(self, attr, default)
  642. def check_globals(self):
  643. '''Ensure that all referenced qids are present in the collection'''
  644. self._check_global('default_template_qid', None)
  645. self._check_global('default_fw_netvm_qid', None)
  646. self._check_global('default_netvm_qid', self.default_fw_netvm_qid)
  647. self._check_global('updatevm_qid', self.default_netvm_qid)
  648. self._check_global('clockvm_qid', self.default_netvm_qid)
  649. def load(self):
  650. self.log.debug('load()')
  651. self.clear()
  652. try:
  653. self.qubes_store_file.seek(0)
  654. tree = lxml.etree.parse(self.qubes_store_file)
  655. except (EnvironmentError,
  656. xml.parsers.expat.ExpatError) as err:
  657. print("{0}: import error: {1}".format(
  658. os.path.basename(sys.argv[0]), err))
  659. return False
  660. self.load_globals(tree.getroot())
  661. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  662. key=lambda _x: _x[1].load_order):
  663. vms_of_class = tree.findall(vm_class_name)
  664. # first non-template based, then template based
  665. sorted_vms_of_class = sorted(vms_of_class, key= \
  666. lambda x: str(x.get('template_qid')).lower() != "none")
  667. for element in sorted_vms_of_class:
  668. try:
  669. vm = vm_class(xml_element=element, collection=self)
  670. self[vm.qid] = vm
  671. except (ValueError, LookupError) as err:
  672. print("{0}: import error ({1}): {2}".format(
  673. os.path.basename(sys.argv[0]), vm_class_name, err))
  674. raise
  675. return False
  676. # After importing all VMs, set netvm references, in the same order
  677. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  678. key=lambda _x: _x[1].load_order):
  679. for element in tree.findall(vm_class_name):
  680. try:
  681. self.set_netvm_dependency(element)
  682. except (ValueError, LookupError) as err:
  683. print("{0}: import error2 ({}): {}".format(
  684. os.path.basename(sys.argv[0]), vm_class_name, err))
  685. return False
  686. self.check_globals()
  687. # if there was no clockvm entry in qubes.xml, try to determine default:
  688. # root of default NetVM chain
  689. if tree.getroot().get("clockvm") is None:
  690. if self.default_netvm_qid is not None:
  691. clockvm = self[self.default_netvm_qid]
  692. # Find root of netvm chain
  693. while clockvm.netvm is not None:
  694. clockvm = clockvm.netvm
  695. self.clockvm_qid = clockvm.qid
  696. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  697. # using 123/udp port)
  698. if self.clockvm_qid is not None:
  699. self[self.clockvm_qid].services['ntpd'] = False
  700. # Add dom0 if wasn't present in qubes.xml
  701. if not 0 in self.keys():
  702. dom0vm = QubesAdminVm (collection=self)
  703. self[dom0vm.qid] = dom0vm
  704. return True
  705. def pop(self, qid):
  706. self.log.debug('pop({})'.format(qid))
  707. if self.default_netvm_qid == qid:
  708. self.default_netvm_qid = None
  709. if self.default_fw_netvm_qid == qid:
  710. self.default_fw_netvm_qid = None
  711. if self.clockvm_qid == qid:
  712. self.clockvm_qid = None
  713. if self.updatevm_qid == qid:
  714. self.updatevm_qid = None
  715. if self.default_template_qid == qid:
  716. self.default_template_qid = None
  717. return super(QubesVmCollection, self).pop(qid)
  718. class QubesDaemonPidfile(object):
  719. def __init__(self, name):
  720. self.name = name
  721. self.path = "/var/run/qubes/" + name + ".pid"
  722. def create_pidfile(self):
  723. f = open (self.path, 'w')
  724. f.write(str(os.getpid()))
  725. f.close()
  726. def pidfile_exists(self):
  727. return os.path.exists(self.path)
  728. def read_pid(self):
  729. f = open (self.path)
  730. pid = f.read ().strip()
  731. f.close()
  732. return int(pid)
  733. def pidfile_is_stale(self):
  734. if not self.pidfile_exists():
  735. return False
  736. # check if the pid file is valid...
  737. proc_path = "/proc/" + str(self.read_pid()) + "/cmdline"
  738. if not os.path.exists (proc_path):
  739. print >> sys.stderr, \
  740. "Path {0} doesn't exist, assuming stale pidfile.".\
  741. format(proc_path)
  742. return True
  743. return False # It's a good pidfile
  744. def remove_pidfile(self):
  745. os.remove (self.path)
  746. def __enter__ (self):
  747. # assumes the pidfile doesn't exist -- you should ensure it before opening the context
  748. self.create_pidfile()
  749. def __exit__ (self, exc_type, exc_val, exc_tb):
  750. self.remove_pidfile()
  751. return False
  752. ### Initialization code
  753. # Globally defined lables
  754. QubesVmLabels = {
  755. "red": QubesVmLabel(1, "0xcc0000", "red" ),
  756. "orange": QubesVmLabel(2, "0xf57900", "orange" ),
  757. "yellow": QubesVmLabel(3, "0xedd400", "yellow" ),
  758. "green": QubesVmLabel(4, "0x73d216", "green" ),
  759. "gray": QubesVmLabel(5, "0x555753", "gray" ),
  760. "blue": QubesVmLabel(6, "0x3465a4", "blue" ),
  761. "purple": QubesVmLabel(7, "0x75507b", "purple" ),
  762. "black": QubesVmLabel(8, "0x000000", "black" ),
  763. }
  764. QubesDispVmLabels = {
  765. "red": QubesVmLabel(1, "0xcc0000", "red", dispvm=True),
  766. "orange": QubesVmLabel(2, "0xf57900", "orange", dispvm=True),
  767. "yellow": QubesVmLabel(3, "0xedd400", "yellow", dispvm=True),
  768. "green": QubesVmLabel(4, "0x73d216", "green", dispvm=True),
  769. "gray": QubesVmLabel(5, "0x555753", "gray", dispvm=True),
  770. "blue": QubesVmLabel(6, "0x3465a4", "blue", dispvm=True),
  771. "purple": QubesVmLabel(7, "0x75507b", "purple", dispvm=True),
  772. "black": QubesVmLabel(8, "0x000000", "black", dispvm=True),
  773. }
  774. defaults["appvm_label"] = QubesVmLabels["red"]
  775. defaults["template_label"] = QubesVmLabels["black"]
  776. defaults["servicevm_label"] = QubesVmLabels["red"]
  777. QubesVmClasses = {}
  778. modules_dir = os.path.join(os.path.dirname(__file__), 'modules')
  779. for module_file in sorted(os.listdir(modules_dir)):
  780. if not module_file.endswith(".py") or module_file == "__init__.py":
  781. continue
  782. __import__('qubes.modules.%s' % module_file[:-3])
  783. try:
  784. import qubes.settings
  785. qubes.settings.apply(system_path, vm_files, defaults)
  786. except ImportError:
  787. pass
  788. for path_key in system_path.keys():
  789. if not os.path.isabs(system_path[path_key]):
  790. system_path[path_key] = os.path.join(
  791. system_path['qubes_base_dir'], system_path[path_key])
  792. # vim:sw=4:et: