settings.py 41 KB

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