settings.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2012 Agnieszka Kostrzewa <agnieszka.kostrzewa@gmail.com>
  6. # Copyright (C) 2012 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or
  11. # modify it under the terms of the GNU General Public License
  12. # as published by the Free Software Foundation; either version 2
  13. # of the License, or (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public License along
  21. # with this program; if not, see <http://www.gnu.org/licenses/>.
  22. #
  23. #
  24. import collections
  25. import subprocess
  26. import threading
  27. import time
  28. import traceback
  29. import os
  30. import sys
  31. from qubesadmin.tools import QubesArgumentParser
  32. import qubesadmin.exc
  33. from . import utils
  34. from . import multiselectwidget
  35. from . import thread_monitor
  36. from .appmenu_select import AppmenuSelectManager
  37. from . import firewall
  38. from PyQt4 import QtCore, QtGui
  39. from . import ui_settingsdlg
  40. class VMSettingsWindow(ui_settingsdlg.Ui_SettingsDialog, QtGui.QDialog):
  41. tabs_indices = collections.OrderedDict((
  42. ('basic', 0),
  43. ('advanced', 1),
  44. ('firewall', 2),
  45. ('devices', 3),
  46. ('applications', 4),
  47. ('services', 5),
  48. ))
  49. def __init__(self, vm, qapp, init_page="basic", parent=None):
  50. super(VMSettingsWindow, self).__init__(parent)
  51. self.vm = vm
  52. self.qapp = qapp
  53. try:
  54. self.source_vm = self.vm.template
  55. except AttributeError:
  56. self.source_vm = self.vm
  57. self.setupUi(self)
  58. self.setWindowTitle(self.tr("Settings: {vm}").format(vm=self.vm.name))
  59. if init_page in self.tabs_indices:
  60. idx = self.tabs_indices[init_page]
  61. assert (idx in range(self.tabWidget.count()))
  62. self.tabWidget.setCurrentIndex(idx)
  63. self.connect(self.buttonBox,
  64. QtCore.SIGNAL("accepted()"),
  65. self.save_and_apply)
  66. self.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.reject)
  67. self.tabWidget.currentChanged.connect(self.current_tab_changed)
  68. self.tabWidget.setTabEnabled(self.tabs_indices["firewall"],
  69. vm.netvm is not None and not vm.provides_network)
  70. ###### basic tab
  71. self.__init_basic_tab__()
  72. self.rename_vm_button.clicked.connect(self.rename_vm)
  73. self.delete_vm_button.clicked.connect(self.remove_vm)
  74. self.clone_vm_button.clicked.connect(self.clone_vm)
  75. ###### advanced tab
  76. self.__init_advanced_tab__()
  77. self.include_in_balancing.stateChanged.connect(
  78. self.include_in_balancing_changed)
  79. self.connect(self.init_mem,
  80. QtCore.SIGNAL("editingFinished()"),
  81. self.check_mem_changes)
  82. self.connect(self.max_mem_size,
  83. QtCore.SIGNAL("editingFinished()"),
  84. self.check_mem_changes)
  85. self.boot_from_device_button.clicked.connect(
  86. self.boot_from_cdrom_button_pressed)
  87. ###### firewall tab
  88. if self.tabWidget.isTabEnabled(self.tabs_indices['firewall']):
  89. model = firewall.QubesFirewallRulesModel()
  90. try:
  91. model.set_vm(vm)
  92. self.set_fw_model(model)
  93. self.firewall_modified_outside_label.setVisible(False)
  94. except firewall.FirewallModifiedOutsideError:
  95. self.disable_all_fw_conf()
  96. self.new_rule_button.clicked.connect(self.new_rule_button_pressed)
  97. self.edit_rule_button.clicked.connect(self.edit_rule_button_pressed)
  98. self.delete_rule_button.clicked.connect(
  99. self.delete_rule_button_pressed)
  100. self.policy_deny_radio_button.clicked.connect(self.policy_changed)
  101. self.policy_allow_radio_button.clicked.connect(self.policy_changed)
  102. ####### devices tab
  103. self.__init_devices_tab__()
  104. self.connect(self.dev_list,
  105. QtCore.SIGNAL("selected_changed()"),
  106. self.devices_selection_changed)
  107. ####### services tab
  108. self.__init_services_tab__()
  109. self.add_srv_button.clicked.connect(self.__add_service__)
  110. self.remove_srv_button.clicked.connect(self.__remove_service__)
  111. ####### apps tab
  112. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  113. self.app_list = multiselectwidget.MultiSelectWidget(self)
  114. self.apps_layout.addWidget(self.app_list)
  115. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  116. self.refresh_apps_button.clicked.connect(
  117. self.refresh_apps_button_pressed)
  118. def reject(self):
  119. self.done(0)
  120. #needed not to close the dialog before applying changes
  121. def accept(self):
  122. pass
  123. def save_and_apply(self):
  124. t_monitor = thread_monitor.ThreadMonitor()
  125. thread = threading.Thread(target=self.__save_changes__,
  126. args=(t_monitor,))
  127. thread.daemon = True
  128. thread.start()
  129. progress = QtGui.QProgressDialog(
  130. self.tr("Applying settings to <b>{0}</b>...").format(self.vm.name),
  131. "", 0, 0)
  132. progress.setCancelButton(None)
  133. progress.setModal(True)
  134. progress.show()
  135. while not t_monitor.is_finished():
  136. self.qapp.processEvents()
  137. time.sleep(0.1)
  138. progress.hide()
  139. if not t_monitor.success:
  140. QtGui.QMessageBox.warning(
  141. None,
  142. self.tr("Error while changing settings for {0}!"
  143. ).format(self.vm.name),
  144. self.tr("ERROR: {0}").format(t_monitor.error_msg))
  145. self.done(0)
  146. def __save_changes__(self, t_monitor):
  147. ret = []
  148. try:
  149. ret_tmp = self.__apply_basic_tab__()
  150. if len(ret_tmp) > 0:
  151. ret += ["Basic tab:"] + ret_tmp
  152. ret_tmp = self.__apply_advanced_tab__()
  153. if len(ret_tmp) > 0:
  154. ret += ["Advanced tab:"] + ret_tmp
  155. ret_tmp = self.__apply_devices_tab__()
  156. if len(ret_tmp) > 0:
  157. ret += ["Devices tab:"] + ret_tmp
  158. ret_tmp = self.__apply_services_tab__()
  159. if len(ret_tmp) > 0:
  160. ret += ["Sevices tab:"] + ret_tmp
  161. except qubesadmin.exc.QubesException as qex:
  162. ret.append(self.tr('Error while saving changes: ') + str(qex))
  163. except Exception as ex: # pylint: disable=broad-except
  164. ret.append(repr(ex))
  165. try:
  166. if self.policy_allow_radio_button.isEnabled():
  167. self.fw_model.apply_rules(
  168. self.policy_allow_radio_button.isChecked(),
  169. self.temp_full_access.isChecked(),
  170. self.temp_full_access_time.value())
  171. except qubesadmin.exc.QubesException as qex:
  172. ret+= [self.tr("Firewall tab:"), str(qex)]
  173. except Exception as ex: # pylint: disable=broad-except
  174. ret += [self.tr("Firewall tab:"), repr(ex)]
  175. try:
  176. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  177. self.app_list_manager.save_appmenu_select_changes()
  178. except qubesadmin.exc.QubesException as qex:
  179. ret += [self.tr("Applications tab:"), str(qex)]
  180. except Exception as ex: # pylint: disable=broad-except
  181. ret += [self.tr("Applications tab:"), repr(ex)]
  182. if len(ret) > 0:
  183. t_monitor.set_error_msg('\n'.join(ret))
  184. utils.debug('\n'.join(ret))
  185. t_monitor.set_finished()
  186. def current_tab_changed(self, idx):
  187. if idx == self.tabs_indices["firewall"]:
  188. netvm = self.vm.netvm
  189. if netvm is not None and \
  190. not netvm.features.check_with_template(
  191. 'qubes-firewall',
  192. False):
  193. QtGui.QMessageBox.warning(
  194. None,
  195. self.tr("VM configuration problem!"),
  196. self.tr("The '{vm}' AppVM is network connected to "
  197. "'{netvm}', which does not support firewall!<br/>"
  198. "You may edit the '{vm}' VM firewall rules, but these "
  199. "will not take any effect until you connect it to "
  200. "a working Firewall VM.").format(
  201. vm=self.vm.name, netvm=netvm.name))
  202. ######### basic tab
  203. # TODO LISTENERS
  204. # - vm start/shutdown -> setEnabled on fields: template labels
  205. # - vm create/delete -> choices lists, whole window deactiv (if self.vm)
  206. # - property-set -> individual fields
  207. # TODO INTERACTIONS
  208. # netvm -> networking_groupbox
  209. # hvm -> include_in_balancing
  210. # TODO REMOVE
  211. # other_groupbox
  212. def __init_basic_tab__(self):
  213. self.vmname.setText(self.vm.name)
  214. self.vmname.setValidator(
  215. QtGui.QRegExpValidator(
  216. QtCore.QRegExp("[a-zA-Z0-9-]*",
  217. QtCore.Qt.CaseInsensitive), None))
  218. self.vmname.setEnabled(False)
  219. self.rename_vm_button.setEnabled(not self.vm.is_running())
  220. self.delete_vm_button.setEnabled(not self.vm.is_running())
  221. if self.vm.is_running():
  222. self.delete_vm_button.setText(self.tr('Delete VM '
  223. '(cannot delete a running VM)'))
  224. if self.vm.qid == 0:
  225. self.vmlabel.setVisible(False)
  226. else:
  227. self.label_list, self.label_idx = utils.prepare_label_choice(
  228. self.vmlabel,
  229. self.vm, 'label',
  230. None,
  231. allow_default=False
  232. )
  233. self.vmlabel.setVisible(True)
  234. self.vmlabel.setEnabled(not self.vm.is_running())
  235. if self.vm.klass == 'AppVM':
  236. self.template_list, self.template_idx = utils.prepare_vm_choice(
  237. self.template_name,
  238. self.vm, 'template',
  239. self.vm.app.default_template,
  240. (lambda vm: vm.klass == 'TemplateVM'),
  241. allow_default=True, allow_none=False)
  242. else:
  243. self.template_name.setEnabled(False)
  244. self.template_idx = -1
  245. self.netvm_list, self.netvm_idx = utils.prepare_vm_choice(
  246. self.netVM,
  247. self.vm, 'netvm',
  248. self.vm.app.default_netvm,
  249. (lambda vm: vm.provides_network),
  250. allow_default=True, allow_none=True)
  251. self.include_in_backups.setChecked(self.vm.include_in_backups)
  252. try:
  253. self.run_in_debug_mode.setChecked(self.vm.debug)
  254. self.run_in_debug_mode.setVisible(True)
  255. except AttributeError:
  256. self.run_in_debug_mode.setVisible(False)
  257. try:
  258. self.autostart_vm.setChecked(self.vm.autostart)
  259. self.autostart_vm.setVisible(True)
  260. except AttributeError:
  261. self.autostart_vm.setVisible(False)
  262. #type
  263. self.type_label.setText(self.vm.klass)
  264. #installed by rpm
  265. self.rpm_label.setText('Yes' if self.vm.installed_by_rpm else 'No')
  266. #networking info
  267. if self.vm.netvm:
  268. self.networking_groupbox.setEnabled(True)
  269. self.ip_label.setText(self.vm.ip or "none")
  270. self.netmask_label.setText(self.vm.visible_netmask or "none")
  271. self.gateway_label.setText(self.vm.visible_gateway or "none")
  272. else:
  273. self.networking_groupbox.setEnabled(False)
  274. #max priv storage
  275. self.priv_img_size = self.vm.volumes['private'].size // 1024**2
  276. self.max_priv_storage.setMinimum(self.priv_img_size)
  277. self.max_priv_storage.setValue(self.priv_img_size)
  278. self.root_img_size = self.vm.volumes['root'].size // 1024**2
  279. self.root_resize.setValue(self.root_img_size)
  280. self.root_resize.setMinimum(self.root_img_size)
  281. self.root_resize.setEnabled(self.vm.volumes['root'].save_on_stop)
  282. self.root_resize_label.setEnabled(self.root_resize.isEnabled())
  283. def __apply_basic_tab__(self):
  284. msg = []
  285. #vm label changed
  286. try:
  287. if self.vmlabel.isVisible():
  288. if self.vmlabel.currentIndex() != self.label_idx:
  289. label = self.label_list[self.vmlabel.currentIndex()]
  290. self.vm.label = label
  291. except qubesadmin.exc.QubesException as ex:
  292. msg.append(str(ex))
  293. #vm template changed
  294. try:
  295. if self.template_name.currentIndex() != self.template_idx:
  296. self.vm.template = \
  297. self.template_list[self.template_name.currentIndex()]
  298. except qubesadmin.exc.QubesException as ex:
  299. msg.append(str(ex))
  300. #vm netvm changed
  301. try:
  302. if self.netVM.currentIndex() != self.netvm_idx:
  303. self.vm.netvm = self.netvm_list[self.netVM.currentIndex()]
  304. except qubesadmin.exc.QubesException as ex:
  305. msg.append(str(ex))
  306. #include in backups
  307. try:
  308. if self.vm.include_in_backups != \
  309. self.include_in_backups.isChecked():
  310. self.vm.include_in_backups = self.include_in_backups.isChecked()
  311. except qubesadmin.exc.QubesException as ex:
  312. msg.append(str(ex))
  313. #run_in_debug_mode
  314. try:
  315. if self.run_in_debug_mode.isVisible():
  316. if self.vm.debug != self.run_in_debug_mode.isChecked():
  317. self.vm.debug = self.run_in_debug_mode.isChecked()
  318. except qubesadmin.exc.QubesException as ex:
  319. msg.append(str(ex))
  320. #autostart_vm
  321. try:
  322. if self.autostart_vm.isVisible():
  323. if self.vm.autostart != self.autostart_vm.isChecked():
  324. self.vm.autostart = self.autostart_vm.isChecked()
  325. except qubesadmin.exc.QubesException as ex:
  326. msg.append(str(ex))
  327. #max priv storage
  328. priv_size = self.max_priv_storage.value()
  329. if self.priv_img_size != priv_size:
  330. try:
  331. self.vm.volumes['private'].resize(priv_size * 1024**2)
  332. except qubesadmin.exc.QubesException as ex:
  333. msg.append(str(ex))
  334. #max sys storage
  335. sys_size = self.root_resize.value()
  336. if self.root_img_size != sys_size:
  337. try:
  338. self.vm.volumes['root'].resize(sys_size * 1024**2)
  339. except qubesadmin.exc.QubesException as ex:
  340. msg.append(str(ex))
  341. return msg
  342. def check_mem_changes(self):
  343. if self.max_mem_size.value() < self.init_mem.value():
  344. QtGui.QMessageBox.warning(
  345. None,
  346. self.tr("Warning!"),
  347. self.tr("Max memory can not be less than initial memory.<br>"
  348. "Setting max memory to equal initial memory."))
  349. self.max_mem_size.setValue(self.init_mem.value())
  350. # Linux specific limit: init memory must not be below
  351. # max_mem_size/10.79 in order to allow scaling up to
  352. # max_mem_size (or else "add_memory() failed: -17" problem)
  353. if self.init_mem.value() * 10 < self.max_mem_size.value():
  354. QtGui.QMessageBox.warning(
  355. None,
  356. self.tr("Warning!"),
  357. self.tr("Initial memory can not be less than one tenth "
  358. "Max memory.<br>Setting initial memory to the minimum "
  359. "allowed value."))
  360. self.init_mem.setValue(self.max_mem_size.value() / 10)
  361. def _run_in_thread(self, func, *args):
  362. t_monitor = thread_monitor.ThreadMonitor()
  363. thread = threading.Thread(target=func, args=(t_monitor, *args,))
  364. thread.daemon = True
  365. thread.start()
  366. while not t_monitor.is_finished():
  367. self.qapp.processEvents()
  368. time.sleep(0.1)
  369. if not t_monitor.success:
  370. QtGui.QMessageBox.warning(None,
  371. self.tr("Error!"),
  372. self.tr("ERROR: {}").format(
  373. t_monitor.error_msg))
  374. def _rename_vm(self, t_monitor, name):
  375. try:
  376. self.vm.app.clone_vm(self.vm, name)
  377. del self.vm.app.domains[self.vm.name]
  378. except qubesadmin.exc.QubesException as qex:
  379. t_monitor.set_error_msg(str(qex))
  380. except Exception as ex: # pylint: disable=broad-except
  381. t_monitor.set_error_msg(repr(ex))
  382. t_monitor.set_finished()
  383. def rename_vm(self):
  384. new_vm_name, ok = QtGui.QInputDialog.getText(
  385. self,
  386. self.tr('Rename VM'),
  387. self.tr('New name: (WARNING: all other changes will be discarded)'))
  388. if ok:
  389. self._run_in_thread(self._rename_vm, new_vm_name)
  390. self.done(0)
  391. def _remove_vm(self, t_monitor):
  392. try:
  393. del self.vm.app.domains[self.vm.name]
  394. except qubesadmin.exc.QubesException as qex:
  395. t_monitor.set_error_msg(str(qex))
  396. except Exception as ex: # pylint: disable=broad-except
  397. t_monitor.set_error_msg(repr(ex))
  398. t_monitor.set_finished()
  399. def remove_vm(self):
  400. answer, ok = QtGui.QInputDialog.getText(
  401. self,
  402. self.tr('Delete VM'),
  403. self.tr('Are you absolutely sure you want to delete this VM? '
  404. '<br/> All VM settings and data will be irrevocably'
  405. ' deleted. <br/> If you are sure, please enter this '
  406. 'VM\'s name below.'))
  407. if ok and answer == self.vm.name:
  408. self._run_in_thread(self._remove_vm)
  409. self.done(0)
  410. elif ok:
  411. QtGui.QMessageBox.warning(
  412. None,
  413. self.tr("Removal cancelled"),
  414. self.tr("The VM will not be removed."))
  415. def _clone_vm(self, t_monitor, name):
  416. try:
  417. self.vm.app.clone_vm(self.vm, name)
  418. except qubesadmin.exc.QubesException as qex:
  419. t_monitor.set_error_msg(str(qex))
  420. except Exception as ex: # pylint: disable=broad-except
  421. t_monitor.set_error_msg(repr(ex))
  422. t_monitor.set_finished()
  423. def clone_vm(self):
  424. cloned_vm_name, ok = QtGui.QInputDialog.getText(
  425. self,
  426. self.tr('Clone VM'),
  427. self.tr('Name for the cloned VM:'))
  428. if ok:
  429. self._run_in_thread(self._clone_vm, cloned_vm_name)
  430. QtGui.QMessageBox.warning(
  431. None,
  432. self.tr("Success"),
  433. self.tr("The VM was cloned successfully."))
  434. ######### advanced tab
  435. def __init_advanced_tab__(self):
  436. #mem/cpu
  437. # qubes_memory = QubesHost().memory_total/1024
  438. self.init_mem.setValue(int(self.vm.memory))
  439. # self.init_mem.setMaximum(qubes_memory)
  440. self.max_mem_size.setValue(int(self.vm.maxmem))
  441. # self.max_mem_size.setMaximum(qubes_memory)
  442. self.vcpus.setMinimum(1)
  443. # self.vcpus.setMaximum(QubesHost().no_cpus)
  444. self.vcpus.setValue(int(self.vm.vcpus))
  445. self.include_in_balancing.setEnabled(True)
  446. self.include_in_balancing.setChecked(
  447. bool(self.vm.features.get('service.meminfo-writer', True)))
  448. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  449. #in case VM is HVM
  450. if hasattr(self.vm, "kernel"):
  451. self.kernel_groupbox.setVisible(True)
  452. self.kernel_list, self.kernel_idx = utils.prepare_kernel_choice(
  453. self.kernel, self.vm, 'kernel',
  454. self.vm.app.default_kernel,
  455. allow_default=True, allow_none=True)
  456. else:
  457. self.kernel_groupbox.setVisible(False)
  458. self.other_groupbox.setVisible(False)
  459. if not hasattr(self.vm, 'default_dispvm'):
  460. self.other_groupbox.setVisible(False)
  461. else:
  462. self.other_groupbox.setVisible(True)
  463. self.default_dispvm_list, self.default_dispvm_idx = \
  464. utils.prepare_vm_choice(
  465. self.default_dispvm,
  466. self.vm, 'default_dispvm',
  467. self.vm.app.default_dispvm,
  468. (lambda vm: vm.klass == 'DispVM'),
  469. allow_default=True, allow_none=True)
  470. def __apply_advanced_tab__(self):
  471. msg = []
  472. #mem/cpu
  473. try:
  474. if self.init_mem.value() != int(self.vm.memory):
  475. self.vm.memory = self.init_mem.value()
  476. if self.max_mem_size.value() != int(self.vm.maxmem):
  477. self.vm.maxmem = self.max_mem_size.value()
  478. if self.vcpus.value() != int(self.vm.vcpus):
  479. self.vm.vcpus = self.vcpus.value()
  480. except qubesadmin.exc.QubesException as ex:
  481. msg.append(str(ex))
  482. #include_in_memory_balancing applied in services tab
  483. #in case VM is not Linux
  484. if hasattr(self.vm, "kernel") and self.kernel_groupbox.isVisible():
  485. try:
  486. if self.kernel.currentIndex() != self.kernel_idx:
  487. self.vm.kernel = self.kernel_list[
  488. self.kernel.currentIndex()]
  489. except qubesadmin.exc.QubesException as ex:
  490. msg.append(str(ex))
  491. #vm default_dispvm changed
  492. try:
  493. if self.default_dispvm.currentIndex() != self.default_dispvm_idx:
  494. self.vm.default_dispvm = \
  495. self.default_dispvm_list[self.default_dispvm.currentIndex()]
  496. except qubesadmin.exc.QubesException as ex:
  497. msg.append(str(ex))
  498. return msg
  499. def boot_from_cdrom_button_pressed(self):
  500. self.save_and_apply()
  501. subprocess.check_call(['qubes-vm-boot-from-device', self.vm.name])
  502. ######## devices tab
  503. def __init_devices_tab__(self):
  504. self.dev_list = multiselectwidget.MultiSelectWidget(self)
  505. self.dev_list.add_all_button.setVisible(False)
  506. self.devices_layout.addWidget(self.dev_list)
  507. devs = []
  508. lspci = subprocess.check_output(['/usr/sbin/lspci']).decode()
  509. for dev in lspci.splitlines():
  510. devs.append((dev.rstrip(), dev.split(' ')[0]))
  511. class DevListWidgetItem(QtGui.QListWidgetItem):
  512. def __init__(self, name, ident, parent=None):
  513. super(DevListWidgetItem, self).__init__(name, parent)
  514. self.ident = ident
  515. self.Type
  516. persistent = [ass.ident.replace('_', ':')
  517. for ass in self.vm.devices['pci'].persistent()]
  518. for name, ident in devs:
  519. if ident in persistent:
  520. self.dev_list.selected_list.addItem(
  521. DevListWidgetItem(name, ident))
  522. else:
  523. self.dev_list.available_list.addItem(
  524. DevListWidgetItem(name, ident))
  525. if self.dev_list.selected_list.count() > 0\
  526. and self.include_in_balancing.isChecked():
  527. self.dmm_warning_adv.show()
  528. self.dmm_warning_dev.show()
  529. else:
  530. self.dmm_warning_adv.hide()
  531. self.dmm_warning_dev.hide()
  532. if self.vm.is_running():
  533. self.dev_list.setEnabled(False)
  534. self.turn_off_vm_to_modify_devs.setVisible(True)
  535. else:
  536. self.dev_list.setEnabled(True)
  537. self.turn_off_vm_to_modify_devs.setVisible(False)
  538. def __apply_devices_tab__(self):
  539. msg = []
  540. try:
  541. old = [ass.ident.replace('_', ':')
  542. for ass in self.vm.devices['pci'].persistent()]
  543. new = [self.dev_list.selected_list.item(i).ident
  544. for i in range(self.dev_list.selected_list.count())]
  545. for ident in new:
  546. if ident not in old:
  547. ass = firewall.qubesadmin.devices.DeviceAssignment(
  548. self.vm.app.domains['dom0'],
  549. ident.replace(':', '_'),
  550. persistent=True)
  551. self.vm.devices['pci'].attach(ass)
  552. for ass in self.vm.devices['pci'].assignments(persistent=True):
  553. if ass.ident.replace('_', ':') not in new:
  554. self.vm.devices['pci'].detach(ass)
  555. except qubesadmin.exc.QubesException as ex:
  556. if utils.is_debug():
  557. traceback.print_exc()
  558. msg.append(str(ex))
  559. return msg
  560. def include_in_balancing_changed(self, state):
  561. for i in range(self.services_list.count()):
  562. item = self.services_list.item(i)
  563. if str(item.text()) == 'meminfo-writer':
  564. item.setCheckState(state)
  565. break
  566. if self.dev_list.selected_list.count() > 0:
  567. if state == ui_settingsdlg.QtCore.Qt.Checked:
  568. self.dmm_warning_adv.show()
  569. self.dmm_warning_dev.show()
  570. else:
  571. self.dmm_warning_adv.hide()
  572. self.dmm_warning_dev.hide()
  573. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  574. def devices_selection_changed(self):
  575. if self.include_in_balancing.isChecked():
  576. if self.dev_list.selected_list.count() > 0:
  577. self.dmm_warning_adv.show()
  578. self.dmm_warning_dev.show()
  579. else:
  580. self.dmm_warning_adv.hide()
  581. self.dmm_warning_dev.hide()
  582. ######## applications tab
  583. def refresh_apps_in_vm(self, t_monitor):
  584. try:
  585. target_vm = self.vm.template
  586. except AttributeError:
  587. target_vm = self.vm
  588. if not target_vm.is_running():
  589. not_running = True
  590. target_vm.start()
  591. else:
  592. not_running = False
  593. subprocess.check_call(['qvm-sync-appmenus', target_vm.name])
  594. if not_running:
  595. target_vm.shutdown()
  596. t_monitor.set_finished()
  597. def refresh_apps_button_pressed(self):
  598. self.refresh_apps_button.setEnabled(False)
  599. self.refresh_apps_button.setText(self.tr('Refresh in progress...'))
  600. t_monitor = thread_monitor.ThreadMonitor()
  601. thread = threading.Thread(
  602. target=self.refresh_apps_in_vm,
  603. args=(t_monitor,))
  604. thread.daemon = True
  605. thread.start()
  606. while not t_monitor.is_finished():
  607. self.qapp.processEvents()
  608. time.sleep(0.1)
  609. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  610. self.refresh_apps_button.setEnabled(True)
  611. self.refresh_apps_button.setText(self.tr('Refresh Applications'))
  612. ######## services tab
  613. def __init_services_tab__(self):
  614. self.new_srv_dict = {}
  615. for feature in self.vm.features:
  616. if not feature.startswith('service.'):
  617. continue
  618. service = feature[len('service.'):]
  619. item = QtGui.QListWidgetItem(service)
  620. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked
  621. if self.vm.features[feature]
  622. else ui_settingsdlg.QtCore.Qt.Unchecked)
  623. self.services_list.addItem(item)
  624. self.new_srv_dict[service] = self.vm.features[feature]
  625. self.connect(
  626. self.services_list,
  627. QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),
  628. self.services_item_clicked)
  629. def __add_service__(self):
  630. srv = str(self.service_line_edit.text()).strip()
  631. if srv != "":
  632. if srv in self.new_srv_dict:
  633. QtGui.QMessageBox.information(
  634. None,
  635. '',
  636. self.tr('Service already on the list!'))
  637. else:
  638. item = QtGui.QListWidgetItem(srv)
  639. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked)
  640. self.services_list.addItem(item)
  641. self.new_srv_dict[srv] = True
  642. def __remove_service__(self):
  643. item = self.services_list.currentItem()
  644. if not item:
  645. return
  646. if str(item.text()) == 'meminfo-writer':
  647. QtGui.QMessageBox.information(
  648. None,
  649. self.tr('Service can not be removed'),
  650. self.tr('Service meminfo-writer can not '
  651. 'be removed from the list.'))
  652. return
  653. row = self.services_list.currentRow()
  654. item = self.services_list.takeItem(row)
  655. del self.new_srv_dict[str(item.text())]
  656. def services_item_clicked(self, item):
  657. if str(item.text()) == 'meminfo-writer':
  658. if item.checkState() == ui_settingsdlg.QtCore.Qt.Checked:
  659. if not self.include_in_balancing.isChecked():
  660. self.include_in_balancing.setChecked(True)
  661. elif item.checkState() == ui_settingsdlg.QtCore.Qt.Unchecked:
  662. if self.include_in_balancing.isChecked():
  663. self.include_in_balancing.setChecked(False)
  664. def __apply_services_tab__(self):
  665. msg = []
  666. try:
  667. for i in range(self.services_list.count()):
  668. item = self.services_list.item(i)
  669. self.new_srv_dict[str(item.text())] = \
  670. (item.checkState() == ui_settingsdlg.QtCore.Qt.Checked)
  671. balancing_was_checked = self.vm.features.get(
  672. 'service.meminfo-writer', True)
  673. balancing_is_checked = self.include_in_balancing.isChecked()
  674. meminfo_writer_checked = self.new_srv_dict.get(
  675. 'meminfo-writer', True)
  676. if balancing_is_checked != meminfo_writer_checked:
  677. if balancing_is_checked != balancing_was_checked:
  678. self.new_srv_dict['meminfo-writer'] = balancing_is_checked
  679. for service, v in self.new_srv_dict.items():
  680. feature = 'service.' + service
  681. if v != self.vm.features.get(feature, object()):
  682. self.vm.features[feature] = v
  683. for feature in self.vm.features:
  684. if not feature.startswith('service.'):
  685. continue
  686. service = feature[len('service.'):]
  687. if service not in self.new_srv_dict:
  688. del self.vm.features[feature]
  689. except qubesadmin.exc.QubesException as ex:
  690. msg.append(str(ex))
  691. return msg
  692. ######### firewall tab related
  693. def set_fw_model(self, model):
  694. self.fw_model = model
  695. self.rulesTreeView.setModel(model)
  696. self.rulesTreeView.header().setResizeMode(
  697. QtGui.QHeaderView.ResizeToContents)
  698. self.rulesTreeView.header().setResizeMode(0, QtGui.QHeaderView.Stretch)
  699. self.set_allow(model.allow)
  700. if model.temp_full_access_expire_time:
  701. self.temp_full_access.setChecked(True)
  702. self.temp_full_access_time.setValue(
  703. (model.temp_full_access_expire_time -
  704. int(firewall.datetime.datetime.now().strftime("%s"))) / 60)
  705. def disable_all_fw_conf(self):
  706. self.firewall_modified_outside_label.setVisible(True)
  707. self.policy_allow_radio_button.setEnabled(False)
  708. self.policy_deny_radio_button.setEnabled(False)
  709. self.rulesTreeView.setEnabled(False)
  710. self.new_rule_button.setEnabled(False)
  711. self.edit_rule_button.setEnabled(False)
  712. self.delete_rule_button.setEnabled(False)
  713. self.firewal_rules_label.setEnabled(False)
  714. self.tempFullAccessWidget.setEnabled(False)
  715. def set_allow(self, allow):
  716. self.policy_allow_radio_button.setChecked(allow)
  717. self.policy_deny_radio_button.setChecked(not allow)
  718. self.policy_changed()
  719. def policy_changed(self):
  720. self.rulesTreeView.setEnabled(
  721. self.policy_deny_radio_button.isChecked())
  722. self.new_rule_button.setEnabled(
  723. self.policy_deny_radio_button.isChecked())
  724. self.edit_rule_button.setEnabled(
  725. self.policy_deny_radio_button.isChecked())
  726. self.delete_rule_button.setEnabled(
  727. self.policy_deny_radio_button.isChecked())
  728. self.firewal_rules_label.setEnabled(
  729. self.policy_deny_radio_button.isChecked())
  730. self.tempFullAccessWidget.setEnabled(
  731. self.policy_deny_radio_button.isChecked())
  732. def new_rule_button_pressed(self):
  733. dialog = firewall.NewFwRuleDlg()
  734. self.fw_model.run_rule_dialog(dialog)
  735. def edit_rule_button_pressed(self):
  736. selected = self.rulesTreeView.selectedIndexes()
  737. if len(selected) > 0:
  738. dialog = firewall.NewFwRuleDlg()
  739. dialog.set_ok_state(True)
  740. row = self.rulesTreeView.selectedIndexes().pop().row()
  741. self.fw_model.populate_edit_dialog(dialog, row)
  742. self.fw_model.run_rule_dialog(dialog, row)
  743. def delete_rule_button_pressed(self):
  744. for i in set([index.row() for index
  745. in self.rulesTreeView.selectedIndexes()]):
  746. self.fw_model.remove_child(i)
  747. # Bases on the original code by:
  748. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  749. def handle_exception(exc_type, exc_value, exc_traceback):
  750. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  751. filename = os.path.basename(filename)
  752. error = "%s: %s" % (exc_type.__name__, exc_value)
  753. strace = ""
  754. stacktrace = traceback.extract_tb(exc_traceback)
  755. while len(stacktrace) > 0:
  756. (filename, line, func, txt) = stacktrace.pop()
  757. strace += "----\n"
  758. strace += "line: %s\n" %txt
  759. strace += "func: %s\n" %func
  760. strace += "line no.: %d\n" %line
  761. strace += "file: %s\n" %filename
  762. msg_box = QtGui.QMessageBox()
  763. msg_box.setDetailedText(strace)
  764. msg_box.setIcon(QtGui.QMessageBox.Critical)
  765. msg_box.setWindowTitle("Houston, we have a problem...")
  766. msg_box.setText("Whoops. A critical error has occured. "
  767. "This is most likely a bug in Qubes Manager.<br><br>"
  768. "<b><i>%s</i></b>" % error +
  769. "<br/>at line <b>%d</b><br/>of file %s.<br/><br/>"
  770. % (line, filename))
  771. msg_box.exec_()
  772. parser = QubesArgumentParser(vmname_nargs=1)
  773. parser.add_argument('--tab', metavar='TAB',
  774. action='store',
  775. choices=VMSettingsWindow.tabs_indices.keys())
  776. parser.set_defaults(
  777. tab='basic',
  778. )
  779. def main(args=None):
  780. global settings_window
  781. args = parser.parse_args(args)
  782. vm = args.domains.pop()
  783. qapp = QtGui.QApplication(sys.argv)
  784. qapp.setOrganizationName('Invisible Things Lab')
  785. qapp.setOrganizationDomain("https://www.qubes-os.org/")
  786. qapp.setApplicationName("Qubes VM Settings")
  787. if not utils.is_debug():
  788. sys.excepthook = handle_exception
  789. settings_window = VMSettingsWindow(vm, qapp, args.tab)
  790. settings_window.show()
  791. qapp.exec_()
  792. qapp.exit()
  793. if __name__ == "__main__":
  794. main()
  795. # vim:sw=4:et: