settings.py 34 KB

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