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