qubes.py 31 KB

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