settings.py 44 KB

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