settings.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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 functools
  26. import re
  27. import subprocess
  28. import traceback
  29. from qubesadmin.tools import QubesArgumentParser
  30. from qubesadmin import devices
  31. from qubesadmin import utils as admin_utils
  32. import qubesadmin.exc
  33. from . import utils
  34. from . import multiselectwidget
  35. from . import common_threads
  36. from . import device_list
  37. from . import clone_vm
  38. from .appmenu_select import AppmenuSelectManager
  39. from . import firewall
  40. from PyQt5 import QtCore, QtWidgets, QtGui # pylint: disable=import-error
  41. from . import ui_settingsdlg # pylint: disable=no-name-in-module
  42. # pylint: disable=too-few-public-methods
  43. class RenameVMThread(common_threads.QubesThread):
  44. def __init__(self, vm, new_vm_name, dependencies):
  45. super().__init__(vm)
  46. self.new_vm_name = new_vm_name
  47. self.dependencies = dependencies
  48. def run(self):
  49. try:
  50. new_vm = self.vm.app.clone_vm(self.vm, self.new_vm_name)
  51. failed_props = []
  52. for (holder, prop) in self.dependencies:
  53. try:
  54. if holder is None:
  55. setattr(self.vm.app, prop, new_vm)
  56. else:
  57. setattr(holder, prop, new_vm)
  58. except qubesadmin.exc.QubesException:
  59. failed_props += [(holder, prop)]
  60. if not failed_props:
  61. del self.vm.app.domains[self.vm.name]
  62. else:
  63. list_text = utils.format_dependencies_list(failed_props)
  64. self.msg = (self.tr("Warning: rename partially unsuccessful!"),
  65. self.tr("Some properties could not be changed to "
  66. "the new name. The system has now both {} "
  67. "and {} qubes. To resolve this, please "
  68. "check and change the following properties "
  69. "and remove the qube {} manually.<br>"
  70. ).format(self.vm.name, self.vm.name,
  71. self.vm.name) + list_text)
  72. except qubesadmin.exc.QubesException as ex:
  73. self.msg = (self.tr("Rename error!"), str(ex))
  74. except Exception as ex: # pylint: disable=broad-except
  75. self.msg = (self.tr("Rename error!"), repr(ex))
  76. # pylint: disable=too-few-public-methods
  77. class RefreshAppsVMThread(common_threads.QubesThread):
  78. def __init__(self, vm, button):
  79. super().__init__(vm)
  80. self.button = button
  81. def run(self):
  82. vms_to_refresh = [self.vm]
  83. template = getattr(self.vm, 'template', None)
  84. if template:
  85. vms_to_refresh.append(template)
  86. for vm in vms_to_refresh:
  87. self.button.setText(
  88. self.tr('Refresh in progress (refreshing applications '
  89. 'from {})').format(vm.name))
  90. try:
  91. if not utils.is_running(vm, True):
  92. not_running = True
  93. vm.start()
  94. else:
  95. not_running = False
  96. subprocess.check_call(['qvm-sync-appmenus', vm.name])
  97. if not_running:
  98. vm.shutdown()
  99. except Exception as ex: # pylint: disable=broad-except
  100. self.msg = (self.tr("Refresh failed!"), str(ex))
  101. # pylint: disable=too-many-instance-attributes
  102. class VMSettingsWindow(ui_settingsdlg.Ui_SettingsDialog, QtWidgets.QDialog):
  103. tabs_indices = collections.OrderedDict((
  104. ('basic', 0),
  105. ('advanced', 1),
  106. ('firewall', 2),
  107. ('devices', 3),
  108. ('applications', 4),
  109. ('services', 5),
  110. ))
  111. def __init__(self, vm, init_page="basic", qapp=None, qubesapp=None,
  112. parent=None):
  113. super().__init__(parent)
  114. self.vm = vm
  115. self.qapp = qapp
  116. self.qubesapp = qubesapp
  117. self.threads_list = []
  118. self.progress = None
  119. self.thread_closes = False
  120. self.setupUi(self)
  121. self.setWindowTitle(self.tr("Settings: {vm}").format(vm=self.vm.name))
  122. if init_page in self.tabs_indices:
  123. idx = self.tabs_indices[init_page]
  124. assert idx in range(self.tabWidget.count())
  125. self.tabWidget.setCurrentIndex(idx)
  126. self.buttonBox.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(
  127. self.apply)
  128. self.tabWidget.currentChanged.connect(self.current_tab_changed)
  129. # Initialize several auxillary variables for pylint's sake
  130. self.root_img_size = None
  131. self.priv_img_size = None
  132. ###### basic tab
  133. self.__init_basic_tab__()
  134. self.rename_vm_button.clicked.connect(self.rename_vm)
  135. self.delete_vm_button.clicked.connect(self.remove_vm)
  136. self.clone_vm_button.clicked.connect(self.clone_vm)
  137. ###### advanced tab
  138. self.__init_advanced_tab__()
  139. self.include_in_balancing.stateChanged.connect(
  140. self.include_in_balancing_changed)
  141. self.init_mem.editingFinished.connect(self.check_mem_changes)
  142. self.max_mem_size.editingFinished.connect(self.check_mem_changes)
  143. self.check_mem_changes()
  144. self.boot_from_device_button.clicked.connect(
  145. self.boot_from_cdrom_button_pressed)
  146. ###### firewall tab
  147. if self.tabWidget.isTabEnabled(self.tabs_indices['firewall']):
  148. model = firewall.QubesFirewallRulesModel()
  149. try:
  150. model.set_vm(vm)
  151. self.set_fw_model(model)
  152. self.firewall_modified_outside_label.setVisible(False)
  153. except firewall.FirewallModifiedOutsideError:
  154. self.disable_all_fw_conf()
  155. except qubesadmin.exc.QubesException:
  156. self.tabWidget.setTabEnabled(
  157. self.tabs_indices['firewall'], False)
  158. self.new_rule_button.clicked.connect(self.new_rule_button_pressed)
  159. self.edit_rule_button.clicked.connect(self.edit_rule_button_pressed)
  160. self.delete_rule_button.clicked.connect(
  161. self.delete_rule_button_pressed)
  162. self.policy_deny_radio_button.clicked.connect(self.policy_changed)
  163. self.policy_allow_radio_button.clicked.connect(self.policy_changed)
  164. if init_page == 'firewall':
  165. self.check_network_availability()
  166. ####### devices tab
  167. self.__init_devices_tab__()
  168. self.dev_list.selectedChanged.connect(self.devices_selection_changed)
  169. self.no_strict_reset_button.clicked.connect(
  170. self.strict_reset_button_pressed)
  171. self.current_strict_reset_list = []
  172. self.new_strict_reset_list = []
  173. self.define_strict_reset_devices()
  174. ####### services tab
  175. self.__init_services_tab__()
  176. self.add_srv_button.clicked.connect(self.__add_service__)
  177. self.remove_srv_button.clicked.connect(self.__remove_service__)
  178. ####### apps tab
  179. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  180. self.app_list = multiselectwidget.MultiSelectWidget(self)
  181. self.apps_layout.addWidget(self.app_list)
  182. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  183. self.refresh_apps_button.clicked.connect(
  184. self.refresh_apps_button_pressed)
  185. # template change
  186. if self.template_name.isEnabled():
  187. self.template_name.currentIndexChanged.connect(
  188. self.template_apps_change)
  189. self.warn_template_missing_apps.setVisible(
  190. self.app_list_manager.has_missing)
  191. def setup_application(self):
  192. self.qapp.setApplicationName(self.tr("Qube Settings"))
  193. self.qapp.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  194. def clear_threads(self):
  195. for thread in self.threads_list:
  196. if thread.isFinished():
  197. if self.progress:
  198. self.progress.hide()
  199. self.progress = None
  200. if thread.msg:
  201. (title, msg) = thread.msg
  202. QtWidgets.QMessageBox.warning(
  203. self,
  204. title,
  205. msg)
  206. self.threads_list.remove(thread)
  207. if self.thread_closes:
  208. self.done(0)
  209. return
  210. raise RuntimeError(self.tr('No finished thread found'))
  211. def keyPressEvent(self, event): # pylint: disable=invalid-name
  212. if event.key() == QtCore.Qt.Key_Enter \
  213. or event.key() == QtCore.Qt.Key_Return:
  214. return
  215. super().keyPressEvent(event)
  216. def accept(self):
  217. self.save_and_apply()
  218. def save_changes(self):
  219. with common_threads.busy_cursor():
  220. error = self.__save_changes__()
  221. if error:
  222. QtWidgets.QMessageBox.warning(
  223. self,
  224. self.tr("Error while changing settings for {0}!"
  225. ).format(self.vm.name),
  226. self.tr("ERROR: {0}").format('\n'.join(error)))
  227. def apply(self):
  228. self.save_changes()
  229. # these signals must be disconnected to avoid unintended behavior
  230. # on refreshing the drop-downs
  231. self.netVM.currentIndexChanged.disconnect()
  232. self.kernel.currentIndexChanged.disconnect()
  233. self.default_dispvm.currentIndexChanged.disconnect()
  234. self.__init_basic_tab__()
  235. self.__init_advanced_tab__()
  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 += [self.tr("Basic tab:")] + ret_tmp
  245. ret_tmp = self.__apply_advanced_tab__()
  246. if ret_tmp:
  247. ret += [self.tr("Advanced tab:")] + ret_tmp
  248. ret_tmp = self.__apply_devices_tab__()
  249. if ret_tmp:
  250. ret += [self.tr("Devices tab:")] + ret_tmp
  251. ret_tmp = self.__apply_services_tab__()
  252. if ret_tmp:
  253. ret += [self.tr("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.tabWidget.isTabEnabled(self.tabs_indices['firewall']) and \
  260. self.policy_allow_radio_button.isEnabled():
  261. self.fw_model.apply_rules(
  262. self.policy_allow_radio_button.isChecked(),
  263. self.temp_full_access.isChecked(),
  264. self.temp_full_access_time.value())
  265. except qubesadmin.exc.QubesException as qex:
  266. ret += [self.tr("Firewall tab:"), str(qex)]
  267. except Exception as ex: # pylint: disable=broad-except
  268. ret += [self.tr("Firewall tab:"), repr(ex)]
  269. try:
  270. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  271. self.app_list_manager.save_appmenu_select_changes()
  272. except qubesadmin.exc.QubesException as qex:
  273. ret += [self.tr("Applications tab:"), str(qex)]
  274. except Exception as ex: # pylint: disable=broad-except
  275. ret += [self.tr("Applications tab:"), repr(ex)]
  276. utils.debug('\n'.join(ret))
  277. return ret
  278. def check_network_availability(self):
  279. netvm = getattr(self.vm, 'netvm', None)
  280. provides_network = getattr(self.vm, 'provides_network', False)
  281. self.no_netvm_label.setVisible(netvm is None and not provides_network)
  282. try:
  283. no_firewall_state = \
  284. netvm is not None and \
  285. not netvm.features.check_with_template('qubes-firewall', False)
  286. except qubesadmin.exc.QubesDaemonAccessError:
  287. no_firewall_state = False
  288. self.netvm_no_firewall_label.setVisible(no_firewall_state)
  289. self.sysnet_warning_label.setVisible(netvm is None and provides_network)
  290. def current_tab_changed(self, idx):
  291. if idx == self.tabs_indices["firewall"]:
  292. self.check_network_availability()
  293. ######### basic tab
  294. # TODO LISTENERS
  295. # - vm start/shutdown -> setEnabled on fields: template labels
  296. # - vm create/delete -> choices lists, whole window deactiv (if self.vm)
  297. # - property-set -> individual fields
  298. # TODO INTERACTIONS
  299. # netvm -> networking_groupbox
  300. # hvm -> include_in_balancing
  301. def __init_basic_tab__(self):
  302. self.vmname.setText(self.vm.name)
  303. self.vmname.setValidator(
  304. QtGui.QRegExpValidator(
  305. QtCore.QRegExp("[a-zA-Z0-9_-]*",
  306. QtCore.Qt.CaseInsensitive), None))
  307. self.vmname.setEnabled(False)
  308. self.rename_vm_button.setEnabled(not self.vm.is_running())
  309. self.delete_vm_button.setEnabled(not self.vm.is_running())
  310. if utils.is_running(self.vm, False):
  311. self.delete_vm_button.setText(
  312. self.tr('Delete qube (cannot delete a running qube)'))
  313. if self.vm.klass == 'AdminVM':
  314. self.vmlabel.setVisible(False)
  315. else:
  316. try:
  317. utils.initialize_widget_with_labels(
  318. widget=self.vmlabel,
  319. qubes_app=self.qubesapp,
  320. holder=self.vm)
  321. self.vmlabel.setVisible(True)
  322. self.vmlabel.setEnabled(not utils.is_running(self.vm, False))
  323. except qubesadmin.exc.QubesDaemonAccessError:
  324. self.vmlabel.setEnabled(False)
  325. if self.vm.klass == 'AppVM':
  326. try:
  327. utils.initialize_widget_with_vms(
  328. widget=self.template_name,
  329. qubes_app=self.qubesapp,
  330. filter_function=(lambda vm: vm.klass == 'TemplateVM'),
  331. holder=self.vm,
  332. property_name='template')
  333. except qubesadmin.exc.QubesDaemonAccessError:
  334. self.template_name.setCurrentIndex(-1)
  335. self.template_name.setEnabled(False)
  336. elif self.vm.klass == 'DispVM':
  337. try:
  338. utils.initialize_widget_with_vms(
  339. widget=self.template_name,
  340. qubes_app=self.qubesapp,
  341. filter_function=(
  342. lambda vm: getattr(vm, 'template_for_dispvms', False)),
  343. holder=self.vm,
  344. property_name='template')
  345. except qubesadmin.exc.QubesDaemonAccessError:
  346. self.template_name.setCurrentIndex(-1)
  347. self.template_name.setEnabled(False)
  348. else:
  349. self.template_name.setEnabled(False)
  350. if utils.is_running(self.vm, False):
  351. self.template_name.setEnabled(False)
  352. try:
  353. utils.initialize_widget_with_vms(
  354. widget=self.netVM,
  355. qubes_app=self.qubesapp,
  356. filter_function=(lambda vm:
  357. getattr(vm, 'provides_network', False)),
  358. holder=self.vm,
  359. property_name='netvm',
  360. allow_default=True,
  361. allow_none=True)
  362. except qubesadmin.exc.QubesDaemonAccessError:
  363. self.netVM.setEnabled(False)
  364. self.netVM.setCurrentIndex(-1)
  365. self.netVM.currentIndexChanged.connect(self.check_warn_dispvmnetvm)
  366. try:
  367. self.include_in_backups.setChecked(self.vm.include_in_backups)
  368. except qubesadmin.exc.QubesDaemonAccessError:
  369. self.include_in_backups.setEnabled(False)
  370. try:
  371. has_shutdown_idle = self.vm.features.get(
  372. "supported-service.shutdown-idle", False)
  373. if has_shutdown_idle:
  374. self.idle_shutdown_checkbox.setChecked(self.vm.features.get(
  375. "shutdown-idle", False))
  376. else:
  377. text = "Shut down when idle "
  378. if getattr(self.vm, 'template', None):
  379. additional_text = "(unavailable: package " \
  380. "qubes-app-shutdown-idle missing " \
  381. "in the template)"
  382. else:
  383. additional_text = "(unavailable: package " \
  384. "qubes-app-shutdown-idle missing " \
  385. "in the qube)"
  386. self.idle_shutdown_checkbox.setText(
  387. text + additional_text)
  388. self.idle_shutdown_checkbox.setEnabled(False)
  389. except qubesadmin.exc.QubesDaemonCommunicationError:
  390. self.idle_shutdown_checkbox.setText(
  391. self.idle_shutdown_checkbox.text() +
  392. " (unavailable: permission denied)")
  393. self.idle_shutdown_checkbox.setEnabled(False)
  394. try:
  395. self.autostart_vm.setChecked(self.vm.autostart)
  396. self.autostart_vm.setVisible(True)
  397. except qubesadmin.exc.QubesDaemonAccessError:
  398. self.autostart_vm.setEnabled(False)
  399. except AttributeError:
  400. self.autostart_vm.setVisible(False)
  401. # type
  402. self.type_label.setText(self.vm.klass)
  403. # installed by rpm
  404. self.rpm_label.setText(
  405. 'Yes' if getattr(self.vm, 'installed_by_rpm', False) else 'No')
  406. # networking info
  407. if getattr(self.vm, 'netvm', None):
  408. self.networking_groupbox.setEnabled(True)
  409. self.ip_label.setText(getattr(self.vm, 'ip', None) or "none")
  410. self.netmask_label.setText(
  411. getattr(self.vm, 'visible_netmask', None) or "none")
  412. self.gateway_label.setText(
  413. getattr(self.vm, 'visible_gateway', None) or "none")
  414. dns_list = getattr(self.vm, 'dns', ['10.139.1.1', '10.139.1.2'])
  415. self.dns_label.setText(", ".join(dns_list))
  416. else:
  417. self.networking_groupbox.setEnabled(False)
  418. # max priv storage
  419. try:
  420. self.priv_img_size = self.vm.volumes['private'].size // 1024**2
  421. self.max_priv_storage.setMinimum(self.priv_img_size)
  422. self.max_priv_storage.setValue(self.priv_img_size)
  423. self.max_priv_storage.setMaximum(
  424. max(self.priv_img_size,
  425. self.qubesapp.pools[self.vm.volumes['private'].pool].size
  426. // 1024**2))
  427. except qubesadmin.exc.QubesException:
  428. self.max_priv_storage.setEnabled(False)
  429. try:
  430. self.root_img_size = self.vm.volumes['root'].size // 1024**2
  431. self.root_resize.setValue(self.root_img_size)
  432. self.root_resize.setMinimum(self.root_img_size)
  433. self.root_resize.setMaximum(
  434. max(self.root_img_size,
  435. self.qubesapp.pools[self.vm.volumes['root'].pool].size
  436. // 1024**2))
  437. self.root_resize.setEnabled(self.vm.volumes['root'].save_on_stop)
  438. if not self.root_resize.isEnabled():
  439. self.root_resize.setToolTip(
  440. self.tr("To change system storage size, change properties "
  441. "of the underlying template."))
  442. self.root_resize_label.setEnabled(self.root_resize.isEnabled())
  443. except qubesadmin.exc.QubesException:
  444. self.root_resize.setEnabled(False)
  445. self.warn_template_missing_apps.setVisible(False)
  446. def __apply_basic_tab__(self):
  447. msg = []
  448. # vm label changed
  449. try:
  450. if self.vmlabel.isVisible():
  451. if utils.did_widget_selection_change(self.vmlabel):
  452. self.vm.label = self.vmlabel.currentData()
  453. except qubesadmin.exc.QubesException as ex:
  454. msg.append(str(ex))
  455. # vm template changed
  456. try:
  457. if utils.did_widget_selection_change(self.template_name):
  458. self.vm.template = self.template_name.currentData()
  459. except qubesadmin.exc.QubesException as ex:
  460. msg.append(str(ex))
  461. # vm netvm changed
  462. try:
  463. if utils.did_widget_selection_change(self.netVM):
  464. self.vm.netvm = self.netVM.currentData()
  465. except qubesadmin.exc.QubesException as ex:
  466. msg.append(str(ex))
  467. # include in backups
  468. try:
  469. if self.include_in_backups.isEnabled() and\
  470. self.vm.include_in_backups != \
  471. self.include_in_backups.isChecked():
  472. self.vm.include_in_backups = self.include_in_backups.isChecked()
  473. except qubesadmin.exc.QubesException as ex:
  474. msg.append(str(ex))
  475. # autostart_vm
  476. try:
  477. if self.autostart_vm.isVisible():
  478. if self.vm.autostart != self.autostart_vm.isChecked():
  479. self.vm.autostart = self.autostart_vm.isChecked()
  480. except qubesadmin.exc.QubesException as ex:
  481. msg.append(str(ex))
  482. # shutdown-idle
  483. try:
  484. current_idle = self.vm.features.get("shutdown-idle", False)
  485. if self.idle_shutdown_checkbox.isEnabled() and \
  486. self.idle_shutdown_checkbox.isChecked() != current_idle:
  487. self.vm.features["shutdown-idle"] = \
  488. self.idle_shutdown_checkbox.isChecked()
  489. except qubesadmin.exc.QubesException as ex:
  490. msg.append(str(ex))
  491. # max priv storage
  492. if self.max_priv_storage.isEnabled():
  493. priv_size = self.max_priv_storage.value()
  494. if self.priv_img_size != priv_size:
  495. try:
  496. self.vm.volumes['private'].resize(priv_size * 1024**2)
  497. self.priv_img_size = priv_size
  498. except qubesadmin.exc.QubesException as ex:
  499. msg.append(str(ex))
  500. # max sys storage
  501. if self.root_resize.isEnabled():
  502. sys_size = self.root_resize.value()
  503. if self.root_img_size != sys_size:
  504. try:
  505. self.vm.volumes['root'].resize(sys_size * 1024**2)
  506. self.root_img_size = sys_size
  507. except qubesadmin.exc.QubesException as ex:
  508. msg.append(str(ex))
  509. return msg
  510. def check_mem_changes(self):
  511. self.warn_too_much_mem_label.setVisible(False)
  512. if not self.include_in_balancing.isChecked():
  513. # do not interfere with settings if the VM is not included in memory
  514. # balancing
  515. return
  516. if not self.max_mem_size.isEnabled() or not self.init_mem.isEnabled():
  517. # do not interfere with settings if they are unavailable
  518. return
  519. if self.max_mem_size.value() < self.init_mem.value():
  520. QtWidgets.QMessageBox.warning(
  521. self,
  522. self.tr("Warning!"),
  523. self.tr("Max memory can not be less than initial memory.<br>"
  524. "Setting max memory to equal initial memory."))
  525. self.max_mem_size.setValue(self.init_mem.value())
  526. # Linux specific limit: init memory must not be below
  527. # max_mem_size/10.79 in order to allow scaling up to
  528. # max_mem_size (or else "add_memory() failed: -17" problem)
  529. try:
  530. is_linux = self.vm.features.check_with_template('os', None) == \
  531. 'Linux'
  532. except qubesadmin.exc.QubesException:
  533. is_linux = False
  534. if is_linux and \
  535. self.init_mem.value() * 10 < self.max_mem_size.value():
  536. self.warn_too_much_mem_label.setVisible(True)
  537. def check_warn_dispvmnetvm(self):
  538. if not hasattr(self.vm, 'default_dispvm'):
  539. self.warn_netvm_dispvm.setVisible(False)
  540. return
  541. dispvm = self.default_dispvm.currentData()
  542. own_netvm = self.netVM.currentData()
  543. if dispvm == qubesadmin.DEFAULT:
  544. try:
  545. dispvm = self.vm.property_get_default('default_dispvm')
  546. except qubesadmin.exc.QubesDaemonAccessError:
  547. pass
  548. if dispvm == self.vm:
  549. self.warn_netvm_dispvm.setVisible(False)
  550. return
  551. dispvm_netvm = getattr(dispvm, 'netvm', None)
  552. if own_netvm == qubesadmin.DEFAULT:
  553. try:
  554. own_netvm = self.vm.property_get_default('netvm')
  555. except qubesadmin.exc.QubesDaemonAccessError:
  556. # no point in warning if we don't know what we're warning about
  557. self.warn_netvm_dispvm.setVisible(False)
  558. return
  559. if dispvm_netvm and dispvm_netvm != own_netvm:
  560. self.warn_netvm_dispvm.setVisible(True)
  561. else:
  562. self.warn_netvm_dispvm.setVisible(False)
  563. def rename_vm(self):
  564. dependencies = admin_utils.vm_dependencies(self.vm.app, self.vm)
  565. running_dependencies = [vm.name for (vm, prop) in dependencies
  566. if vm and prop == 'template'
  567. and utils.is_running(vm, False)]
  568. if running_dependencies:
  569. QtWidgets.QMessageBox.warning(
  570. self,
  571. self.tr("Qube cannot be renamed!"),
  572. self.tr(
  573. "The following qubes using this qube as a template are "
  574. "running: <br> {}. <br> In order to rename this qube, you "
  575. "must first shut them down.").format(
  576. ", ".join(running_dependencies)))
  577. return
  578. new_vm_name, ok = QtWidgets.QInputDialog.getText(
  579. self,
  580. self.tr('Rename qube'),
  581. self.tr('New name: (WARNING: all other changes will be discarded)'),
  582. text=self.vm.name)
  583. if ok:
  584. thread = RenameVMThread(self.vm, new_vm_name, dependencies)
  585. self.threads_list.append(thread)
  586. thread.finished.connect(self.clear_threads)
  587. self.progress = QtWidgets.QProgressDialog(
  588. self.tr("Renaming Qube..."), "", 0, 0)
  589. self.progress.setCancelButton(None)
  590. self.progress.setModal(True)
  591. self.thread_closes = True
  592. self.progress.show()
  593. thread.start()
  594. def remove_vm(self):
  595. dependencies = admin_utils.vm_dependencies(self.vm.app, self.vm)
  596. if dependencies:
  597. list_text = utils.format_dependencies_list(dependencies)
  598. QtWidgets.QMessageBox.warning(
  599. self,
  600. self.tr("Qube cannot be removed!"),
  601. self.tr("This qube cannot be removed. It is used as:"
  602. " <br> {} <small>If you want to remove this qube, "
  603. "you should remove or change settings of each qube "
  604. "or setting that uses it.</small>").format(list_text))
  605. return
  606. answer, ok = QtWidgets.QInputDialog.getText(
  607. self,
  608. self.tr('Delete qube'),
  609. self.tr('Are you absolutely sure you want to delete this qube? '
  610. '<br/> All qube settings and data will be irrevocably'
  611. ' deleted. <br/> If you are sure, please enter this '
  612. 'qube\'s name below.'))
  613. if ok and answer == self.vm.name:
  614. thread = common_threads.RemoveVMThread(self.vm)
  615. thread.finished.connect(self.clear_threads)
  616. self.threads_list.append(thread)
  617. self.progress = QtWidgets.QProgressDialog(
  618. self.tr("Deleting Qube..."), "", 0, 0)
  619. self.progress.setCancelButton(None)
  620. self.progress.setModal(True)
  621. self.thread_closes = True
  622. self.progress.show()
  623. thread.start()
  624. elif ok:
  625. QtWidgets.QMessageBox.warning(
  626. self,
  627. self.tr("Removal cancelled"),
  628. self.tr("The qube will not be removed."))
  629. def clone_vm(self):
  630. with common_threads.busy_cursor():
  631. clone_window = clone_vm.CloneVMDlg(
  632. self.qapp, self.qubesapp, src_vm=self.vm)
  633. clone_window.exec_()
  634. ######### advanced tab
  635. def __init_advanced_tab__(self):
  636. vm_memory = getattr(self.vm, 'memory', None)
  637. vm_maxmem = getattr(self.vm, 'maxmem', None)
  638. if vm_memory is None:
  639. self.init_mem.setEnabled(False)
  640. else:
  641. self.init_mem.setValue(int(vm_memory))
  642. if vm_maxmem is None:
  643. self.max_mem_size.setEnabled(False)
  644. elif vm_maxmem > 0:
  645. self.max_mem_size.setValue(int(vm_maxmem))
  646. else:
  647. try:
  648. maxmem = self.vm.property_get_default('maxmem')
  649. except qubesadmin.exc.QubesDaemonAccessError:
  650. maxmem = 0
  651. if maxmem == 0:
  652. maxmem = vm_memory
  653. self.max_mem_size.setValue(
  654. int(utils.get_feature(
  655. self.vm, 'qubesmanager.maxmem_value', maxmem)))
  656. self.vcpus.setMinimum(1)
  657. self.vcpus.setValue(int(getattr(self.vm, 'vcpus', 1)))
  658. self.include_in_balancing.setEnabled(True)
  659. self.include_in_balancing.setChecked(
  660. int(getattr(self.vm, 'maxmem', 0)) > 0)
  661. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  662. # in case VM is HVM
  663. if hasattr(self.vm, "kernel"):
  664. self.kernel_groupbox.setVisible(True)
  665. try:
  666. utils.initialize_widget_with_kernels(
  667. widget=self.kernel,
  668. qubes_app=self.qubesapp,
  669. allow_none=True,
  670. allow_default=True,
  671. holder=self.vm,
  672. property_name='kernel')
  673. self.kernel.currentIndexChanged.connect(self.kernel_changed)
  674. self.kernel_opts.setText(getattr(self.vm, 'kernelopts', '-'))
  675. except qubesadmin.exc.QubesDaemonAccessError:
  676. self.kernel_groupbox.setVisible(False)
  677. else:
  678. self.kernel_groupbox.setVisible(False)
  679. if not hasattr(self.vm, 'default_dispvm'):
  680. self.other_groupbox.setVisible(False)
  681. else:
  682. try:
  683. self.other_groupbox.setVisible(True)
  684. utils.initialize_widget_with_vms(
  685. widget=self.default_dispvm,
  686. qubes_app=self.qubesapp,
  687. filter_function=(lambda vm:
  688. getattr(
  689. vm, 'template_for_dispvms', False)),
  690. allow_none=True,
  691. allow_default=True,
  692. holder=self.vm,
  693. property_name='default_dispvm'
  694. )
  695. self.default_dispvm.currentIndexChanged.connect(
  696. self.check_warn_dispvmnetvm)
  697. except qubesadmin.exc.QubesDaemonAccessError:
  698. self.other_groupbox.setVisible(False)
  699. self.check_warn_dispvmnetvm()
  700. self.update_virt_mode_list()
  701. try:
  702. windows_running = \
  703. self.vm.features.check_with_template('os', None) == 'Windows' \
  704. and self.vm.is_running()
  705. except qubesadmin.exc.QubesException:
  706. windows_running = False
  707. self.seamless_on_button.setEnabled(windows_running)
  708. self.seamless_off_button.setEnabled(windows_running)
  709. self.seamless_on_button.clicked.connect(self.enable_seamless)
  710. self.seamless_off_button.clicked.connect(self.disable_seamless)
  711. self.dvm_template_checkbox.setChecked(
  712. getattr(self.vm, 'template_for_dispvms', False))
  713. self.provides_network_checkbox.setChecked(
  714. getattr(self.vm, 'provides_network', False))
  715. if self.provides_network_checkbox.isChecked():
  716. domains_using = [vm.name for vm
  717. in getattr(self.vm, 'connected_vms', [])]
  718. if domains_using:
  719. self.provides_network_checkbox.setEnabled(False)
  720. self.provides_network_checkbox.setToolTip(self.tr(
  721. "Cannot change this setting while this qube is used as a "
  722. "NetVM by the following qubes:\n") +
  723. "\n".join(domains_using))
  724. try:
  725. self.run_in_debug_mode.setChecked(self.vm.debug)
  726. self.run_in_debug_mode.setVisible(True)
  727. except AttributeError:
  728. self.run_in_debug_mode.setVisible(False)
  729. utils.initialize_widget(
  730. widget=self.allow_fullscreen,
  731. choices=[
  732. ('(use system default)', None),
  733. ('allow', True),
  734. ('disallow', False)
  735. ],
  736. selected_value=utils.get_boolean_feature(self.vm,
  737. 'gui-allow-fullscreen'))
  738. self.allow_fullscreen_initial = self.allow_fullscreen.currentIndex()
  739. utils.initialize_widget(
  740. widget=self.allow_utf8,
  741. choices=[
  742. ('(use system default)', None),
  743. ('allow', True),
  744. ('disallow', False)
  745. ],
  746. selected_value=utils.get_boolean_feature(self.vm,
  747. 'gui-allow-utf8-titles'))
  748. self.allow_utf8_initial = self.allow_utf8.currentIndex()
  749. def enable_seamless(self):
  750. try:
  751. self.vm.run_service_for_stdio("qubes.SetGuiMode", input=b'SEAMLESS')
  752. except qubesadmin.exc.QubesException as ex:
  753. QtWidgets.QMessageBox.warning(
  754. self,
  755. self.tr("Failed to set seamless mode"),
  756. self.tr("Error occured: {}".format(str(ex))))
  757. def disable_seamless(self):
  758. try:
  759. self.vm.run_service_for_stdio("qubes.SetGuiMode",
  760. input=b'FULLSCREEN')
  761. except qubesadmin.exc.QubesException as ex:
  762. QtWidgets.QMessageBox.warning(
  763. self,
  764. self.tr("Failed to set fullscreen mode"),
  765. self.tr("Error occured: {}".format(str(ex))))
  766. def __apply_advanced_tab__(self):
  767. msg = []
  768. # mem/cpu
  769. try:
  770. if self.init_mem.isEnabled() and \
  771. self.init_mem.value() != int(self.vm.memory):
  772. self.vm.memory = self.init_mem.value()
  773. curr_maxmem = int(getattr(self.vm, 'maxmem', 0))
  774. if not self.include_in_balancing.isChecked():
  775. maxmem = 0
  776. else:
  777. maxmem = self.max_mem_size.value()
  778. if maxmem != curr_maxmem:
  779. if curr_maxmem > 0:
  780. self.vm.features['qubesmanager.maxmem_value'] = curr_maxmem
  781. if maxmem == 0 or self.max_mem_size.isEnabled():
  782. self.vm.maxmem = maxmem
  783. if self.vcpus.isEnabled() and \
  784. self.vcpus.value() != int(self.vm.vcpus):
  785. self.vm.vcpus = self.vcpus.value()
  786. except qubesadmin.exc.QubesException as ex:
  787. msg.append(str(ex))
  788. # in case VM is not Linux
  789. if hasattr(self.vm, "kernel") and self.kernel_groupbox.isVisible():
  790. try:
  791. if utils.did_widget_selection_change(self.kernel):
  792. self.vm.kernel = self.kernel.currentData()
  793. except qubesadmin.exc.QubesException as ex:
  794. msg.append(str(ex))
  795. # vm default_dispvm changed
  796. try:
  797. if utils.did_widget_selection_change(self.default_dispvm):
  798. self.vm.default_dispvm = self.default_dispvm.currentData()
  799. except qubesadmin.exc.QubesException as ex:
  800. msg.append(str(ex))
  801. try:
  802. if utils.did_widget_selection_change(self.virt_mode):
  803. self.vm.virt_mode = self.virt_mode.currentData()
  804. except Exception as ex: # pylint: disable=broad-except
  805. msg.append(str(ex))
  806. if getattr(self.vm, "template_for_dispvms", False) != \
  807. self.dvm_template_checkbox.isChecked():
  808. try:
  809. self.vm.template_for_dispvms = \
  810. self.dvm_template_checkbox.isChecked()
  811. if self.dvm_template_checkbox.isChecked():
  812. self.vm.features["appmenus-dispvm"] = True
  813. else:
  814. del self.vm.features["appmenus-dispvm"]
  815. except Exception as ex: # pylint: disable=broad-except
  816. msg.append(str(ex))
  817. if getattr(self.vm, 'provides_network', False) != \
  818. self.provides_network_checkbox.isChecked():
  819. try:
  820. self.vm.provides_network = \
  821. self.provides_network_checkbox.isChecked()
  822. except Exception as ex: # pylint: disable=broad-except
  823. msg.append(str(ex))
  824. # run_in_debug_mode
  825. try:
  826. if self.run_in_debug_mode.isVisible():
  827. if self.vm.debug != self.run_in_debug_mode.isChecked():
  828. self.vm.debug = self.run_in_debug_mode.isChecked()
  829. except qubesadmin.exc.QubesException as ex:
  830. msg.append(str(ex))
  831. if self.allow_fullscreen_initial !=\
  832. self.allow_fullscreen.currentIndex():
  833. try:
  834. if self.allow_fullscreen.currentData() is None:
  835. del self.vm.features['gui-allow-fullscreen']
  836. else:
  837. self.vm.features['gui-allow-fullscreen'] = \
  838. self.allow_fullscreen.currentData()
  839. except qubesadmin.exc.QubesException as ex:
  840. msg.append(str(ex))
  841. if self.allow_utf8_initial !=\
  842. self.allow_utf8.currentIndex():
  843. try:
  844. if self.allow_utf8.currentData() is None:
  845. del self.vm.features['gui-allow-utf8-titles']
  846. else:
  847. self.vm.features['gui-allow-utf8-titles'] = \
  848. self.allow_utf8.currentData()
  849. except qubesadmin.exc.QubesException as ex:
  850. msg.append(str(ex))
  851. return msg
  852. def include_in_balancing_changed(self, state):
  853. if self.dev_list.selected_list.count() > 0:
  854. if state == ui_settingsdlg.QtCore.Qt.Checked:
  855. self.dmm_warning_adv.show()
  856. self.dmm_warning_dev.show()
  857. else:
  858. self.dmm_warning_adv.hide()
  859. self.dmm_warning_dev.hide()
  860. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  861. if self.include_in_balancing.isChecked():
  862. self.check_mem_changes()
  863. def boot_from_cdrom_button_pressed(self):
  864. self.save_and_apply()
  865. subprocess.check_call(['qubes-vm-boot-from-device', self.vm.name])
  866. def virt_mode_changed(self, new_idx): # pylint: disable=unused-argument
  867. self.update_pv_warning()
  868. self.update_pvh_dont_support_devs()
  869. self.update_pvh_kernel_ver_warning()
  870. def update_pv_warning(self):
  871. if self.virt_mode.currentData() == 'pv':
  872. self.pv_warning.show()
  873. else:
  874. self.pv_warning.hide()
  875. def update_virt_mode_list(self):
  876. choices = [('HVM', 'hvm'),
  877. ('PV', 'pv')]
  878. if hasattr(self, "dev_list"):
  879. devs_attached = self.dev_list.selected_list.count() != 0
  880. else:
  881. try:
  882. devs_attached = bool(list(self.vm.devices['pci'].persistent()))
  883. except qubesadmin.exc.QubesException:
  884. devs_attached = False
  885. if devs_attached:
  886. self.pvh_mode_hidden.show()
  887. else:
  888. choices.insert(0, ('PVH', 'pvh'))
  889. self.pvh_mode_hidden.hide()
  890. old_mode = self.virt_mode.currentData()
  891. if old_mode:
  892. self.virt_mode.currentIndexChanged.disconnect()
  893. # due to how virtualization mode has uniquely different displayed and
  894. # actual name of the default value, I will add it manually
  895. try:
  896. choices.insert(0, (
  897. "default ({})".format(
  898. self.vm.property_get_default('virt_mode').upper()),
  899. qubesadmin.DEFAULT))
  900. except qubesadmin.exc.QubesException:
  901. choices.insert(0,
  902. ("default ({SYSTEM DEFAULT})", qubesadmin.DEFAULT))
  903. try:
  904. utils.initialize_widget_for_property(
  905. widget=self.virt_mode,
  906. choices=choices,
  907. holder=self.vm,
  908. property_name='virt_mode')
  909. except qubesadmin.exc.QubesDaemonAccessError:
  910. self.virt_mode.setEnabled(False)
  911. if self.virt_mode.isEnabled() and old_mode is not None:
  912. self.virt_mode.setCurrentIndex(self.virt_mode.findData(old_mode))
  913. self.virt_mode.currentIndexChanged.connect(self.virt_mode_changed)
  914. self.update_pv_warning()
  915. self.update_pvh_kernel_ver_warning()
  916. def update_pvh_kernel_ver_warning(self):
  917. if self.virt_mode.currentData() != 'pvh':
  918. self.pvh_kernel_version_warning.hide()
  919. return
  920. kernel = self.kernel.currentData()
  921. if self.pvh_kernel_version_ok(kernel):
  922. self.pvh_kernel_version_warning.hide()
  923. else:
  924. self.pvh_kernel_version_warning.show()
  925. def kernel_changed(self):
  926. self.update_pvh_kernel_ver_warning()
  927. def pvh_kernel_version_ok(self, name):
  928. # There are nearly no limitaions on kernel names (only file system and
  929. # general qvm-prefs rules). So we just look if we see something which
  930. # looks like a version number. It's just a warning to help the user
  931. # anyways.
  932. if name is None:
  933. return False
  934. if name is qubesadmin.DEFAULT:
  935. name = getattr(self.vm.app, 'default_kernel', None)
  936. m = re.search(r'(\d+)\.(\d+)', name)
  937. if m is None:
  938. return False
  939. return (int(m.group(1)), int(m.group(2))) >= (4, 11)
  940. ######## devices tab
  941. def __init_devices_tab__(self):
  942. self.dev_list = multiselectwidget.MultiSelectWidget(self)
  943. self.dev_list.add_all_button.setVisible(False)
  944. self.devices_layout.addWidget(self.dev_list)
  945. try:
  946. dom0_devs = \
  947. list(self.vm.app.domains['dom0'].devices['pci'].available())
  948. attached_devs = list(self.vm.devices['pci'].persistent())
  949. except qubesadmin.exc.QubesException:
  950. # no permission to access devices
  951. self.tabWidget.setTabEnabled(self.tabs_indices['devices'], False)
  952. return
  953. # pylint: disable=too-few-public-methods
  954. class DevListWidgetItem(QtWidgets.QListWidgetItem):
  955. def __init__(self, dev, unknown=False, parent=None):
  956. super().__init__(parent)
  957. name = dev.ident.replace('_', ":") + ' ' + dev.description
  958. if unknown:
  959. name += ' (unknown)'
  960. self.setText(name)
  961. self.dev = dev
  962. for dev in dom0_devs:
  963. if dev in attached_devs:
  964. self.dev_list.selected_list.addItem(DevListWidgetItem(dev))
  965. else:
  966. self.dev_list.available_list.addItem(DevListWidgetItem(dev))
  967. for dev in attached_devs:
  968. if dev not in dom0_devs:
  969. self.dev_list.selected_list.addItem(
  970. DevListWidgetItem(dev, unknown=True))
  971. if self.dev_list.selected_list.count() > 0\
  972. and self.include_in_balancing.isChecked():
  973. self.dmm_warning_adv.show()
  974. self.dmm_warning_dev.show()
  975. else:
  976. self.dmm_warning_adv.hide()
  977. self.dmm_warning_dev.hide()
  978. if utils.is_running(self.vm, False):
  979. self.dev_list.setEnabled(False)
  980. self.turn_off_vm_to_modify_devs.setVisible(True)
  981. self.no_strict_reset_button.setEnabled(False)
  982. else:
  983. self.dev_list.setEnabled(True)
  984. self.turn_off_vm_to_modify_devs.setVisible(False)
  985. self.update_pvh_dont_support_devs()
  986. self.dev_list.setEnabled(not utils.is_running(self.vm, False))
  987. def __apply_devices_tab__(self):
  988. msg = []
  989. if not self.tabWidget.isTabEnabled(self.tabs_indices['devices']):
  990. return msg
  991. try:
  992. old_devs = list(self.vm.devices['pci'].persistent())
  993. new_devs = [self.dev_list.selected_list.item(i).dev
  994. for i in range(self.dev_list.selected_list.count())]
  995. for dev in new_devs:
  996. if dev not in old_devs:
  997. options = {}
  998. if dev.ident in self.new_strict_reset_list:
  999. options['no-strict-reset'] = True
  1000. ass = devices.DeviceAssignment(
  1001. self.vm.app.domains['dom0'],
  1002. dev.ident, persistent=True, options=options)
  1003. self.vm.devices['pci'].attach(ass)
  1004. elif (dev.ident in self.current_strict_reset_list) != \
  1005. (dev.ident in self.new_strict_reset_list):
  1006. current_assignment = None
  1007. for assignment in self.vm.devices['pci'].assignments(
  1008. persistent=True):
  1009. if assignment.ident == dev.ident:
  1010. current_assignment = assignment
  1011. break
  1012. if current_assignment is None:
  1013. # it would be very weird if this happened
  1014. msg.append(self.tr("Error re-assigning device ") +
  1015. dev.ident)
  1016. continue
  1017. self.vm.devices['pci'].detach(current_assignment)
  1018. current_assignment.options['no-strict-reset'] = \
  1019. (dev.ident in self.new_strict_reset_list)
  1020. self.vm.devices['pci'].attach(current_assignment)
  1021. for ass in self.vm.devices['pci'].assignments(persistent=True):
  1022. if ass.device not in new_devs:
  1023. self.vm.devices['pci'].detach(ass)
  1024. except qubesadmin.exc.QubesException as ex:
  1025. if utils.is_debug():
  1026. traceback.print_exc()
  1027. msg.append(str(ex))
  1028. return msg
  1029. def devices_selection_changed(self):
  1030. if self.include_in_balancing.isChecked():
  1031. if self.dev_list.selected_list.count() > 0:
  1032. self.dmm_warning_adv.show()
  1033. self.dmm_warning_dev.show()
  1034. else:
  1035. self.dmm_warning_adv.hide()
  1036. self.dmm_warning_dev.hide()
  1037. self.update_virt_mode_list()
  1038. def update_pvh_dont_support_devs(self):
  1039. if self.virt_mode.currentData() == 'pvh':
  1040. self.dev_list.setEnabled(False)
  1041. self.pvh_dont_support_devs.setVisible(True)
  1042. else:
  1043. self.dev_list.setEnabled(True)
  1044. self.pvh_dont_support_devs.setVisible(False)
  1045. def define_strict_reset_devices(self):
  1046. for assignment in self.vm.devices['pci'].assignments():
  1047. if assignment.options.get('no-strict-reset', False):
  1048. self.current_strict_reset_list.append(
  1049. assignment.ident.replace('_', ':'))
  1050. self.new_strict_reset_list = self.current_strict_reset_list.copy()
  1051. def strict_reset_button_pressed(self):
  1052. device_list_window = device_list.PCIDeviceListWindow(
  1053. self.vm, self.qapp, self.dev_list, self.new_strict_reset_list, self)
  1054. device_list_window.exec()
  1055. ######## applications tab
  1056. def refresh_apps_button_pressed(self):
  1057. self.refresh_apps_button.setEnabled(False)
  1058. self.refresh_apps_button.setText(self.tr('Refresh in progress...'))
  1059. thread = RefreshAppsVMThread(self.vm, self.refresh_apps_button)
  1060. thread.finished.connect(self.clear_threads)
  1061. thread.finished.connect(self.refresh_finished)
  1062. self.threads_list.append(thread)
  1063. thread.start()
  1064. def refresh_finished(self):
  1065. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  1066. self.refresh_apps_button.setEnabled(True)
  1067. self.refresh_apps_button.setText(self.tr('Refresh Applications'))
  1068. def template_apps_change(self):
  1069. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  1070. self.app_list_manager.fill_apps_list(
  1071. template=self.template_name.currentData())
  1072. # add a label to show
  1073. self.warn_template_missing_apps.setVisible(
  1074. self.app_list_manager.has_missing)
  1075. ######## services tab
  1076. def __init_services_tab__(self):
  1077. self.new_srv_dict = {}
  1078. try:
  1079. for feature in self.vm.features:
  1080. if not feature.startswith('service.'):
  1081. continue
  1082. service = feature[len('service.'):]
  1083. item = QtWidgets.QListWidgetItem(service)
  1084. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked
  1085. if self.vm.features[feature]
  1086. else ui_settingsdlg.QtCore.Qt.Unchecked)
  1087. self.services_list.addItem(item)
  1088. self.new_srv_dict[service] = self.vm.features[feature]
  1089. except qubesadmin.exc.QubesDaemonAccessError:
  1090. self.tabWidget.setTabEnabled(self.tabs_indices["services"], False)
  1091. return
  1092. self.service_line_edit.addItem("")
  1093. supported_services = set()
  1094. service_prefix = "supported-service."
  1095. for feature in self.vm.features:
  1096. if feature.startswith(service_prefix):
  1097. supported_services.add(feature[len(service_prefix):])
  1098. if getattr(self.vm, "template", None):
  1099. try:
  1100. for feature in self.vm.template.features:
  1101. if feature.startswith(service_prefix):
  1102. supported_services.add(feature[len(service_prefix):])
  1103. except qubesadmin.exc.QubesDaemonAccessError:
  1104. pass
  1105. for service in sorted(supported_services):
  1106. self.service_line_edit.addItem(service)
  1107. self.service_line_edit.addItem(self.tr('(custom...)'))
  1108. self.service_line_edit.setEditText("")
  1109. def __add_service__(self):
  1110. srv = str(self.service_line_edit.currentText()).strip()
  1111. if srv != "":
  1112. if self.service_line_edit.currentIndex() == \
  1113. len(self.service_line_edit) - 1:
  1114. (custom_name, ok) = QtWidgets.QInputDialog.getText(
  1115. self, self.tr("Custom service name"),
  1116. self.tr(
  1117. "Name of the service:"))
  1118. if ok:
  1119. srv = custom_name.strip()
  1120. else:
  1121. return
  1122. if srv in self.new_srv_dict:
  1123. QtWidgets.QMessageBox.information(
  1124. self,
  1125. '',
  1126. self.tr('Service already on the list!'))
  1127. return
  1128. item = QtWidgets.QListWidgetItem(srv)
  1129. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked)
  1130. self.services_list.addItem(item)
  1131. self.new_srv_dict[srv] = True
  1132. def __remove_service__(self):
  1133. item = self.services_list.currentItem()
  1134. if not item:
  1135. return
  1136. row = self.services_list.currentRow()
  1137. item = self.services_list.takeItem(row)
  1138. del self.new_srv_dict[str(item.text())]
  1139. def __apply_services_tab__(self):
  1140. msg = []
  1141. if not self.tabWidget.isTabEnabled(self.tabs_indices['services']):
  1142. return msg
  1143. try:
  1144. for i in range(self.services_list.count()):
  1145. item = self.services_list.item(i)
  1146. self.new_srv_dict[str(item.text())] = \
  1147. (item.checkState() == ui_settingsdlg.QtCore.Qt.Checked)
  1148. for service, v in self.new_srv_dict.items():
  1149. feature = 'service.' + service
  1150. if v != self.vm.features.get(feature, object()):
  1151. self.vm.features[feature] = v
  1152. for feature in self.vm.features:
  1153. if not feature.startswith('service.'):
  1154. continue
  1155. service = feature[len('service.'):]
  1156. if service not in self.new_srv_dict:
  1157. del self.vm.features[feature]
  1158. except qubesadmin.exc.QubesException as ex:
  1159. msg.append(str(ex))
  1160. return msg
  1161. ######### firewall tab related
  1162. def set_fw_model(self, model):
  1163. self.fw_model = model
  1164. self.rulesTreeView.setModel(model)
  1165. self.rulesTreeView.header().setSectionResizeMode(
  1166. QtWidgets.QHeaderView.ResizeToContents)
  1167. self.rulesTreeView.header().setSectionResizeMode(
  1168. 0, QtWidgets.QHeaderView.Stretch)
  1169. self.set_allow(model.allow)
  1170. if model.temp_full_access_expire_time:
  1171. self.temp_full_access.setChecked(True)
  1172. self.temp_full_access_time.setValue(
  1173. (model.temp_full_access_expire_time -
  1174. int(firewall.datetime.datetime.now().strftime("%s"))) / 60)
  1175. def disable_all_fw_conf(self):
  1176. self.firewall_modified_outside_label.setVisible(True)
  1177. self.policy_allow_radio_button.setEnabled(False)
  1178. self.policy_deny_radio_button.setEnabled(False)
  1179. self.rulesTreeView.setEnabled(False)
  1180. self.new_rule_button.setEnabled(False)
  1181. self.edit_rule_button.setEnabled(False)
  1182. self.delete_rule_button.setEnabled(False)
  1183. self.firewal_rules_label.setEnabled(False)
  1184. self.tempFullAccessWidget.setEnabled(False)
  1185. def set_allow(self, allow):
  1186. self.policy_allow_radio_button.setChecked(allow)
  1187. self.policy_deny_radio_button.setChecked(not allow)
  1188. self.policy_changed()
  1189. def policy_changed(self):
  1190. self.rulesTreeView.setEnabled(
  1191. self.policy_deny_radio_button.isChecked())
  1192. self.new_rule_button.setEnabled(
  1193. self.policy_deny_radio_button.isChecked())
  1194. self.edit_rule_button.setEnabled(
  1195. self.policy_deny_radio_button.isChecked())
  1196. self.delete_rule_button.setEnabled(
  1197. self.policy_deny_radio_button.isChecked())
  1198. self.firewal_rules_label.setEnabled(
  1199. self.policy_deny_radio_button.isChecked())
  1200. self.tempFullAccessWidget.setEnabled(
  1201. self.policy_deny_radio_button.isChecked())
  1202. def new_rule_button_pressed(self):
  1203. dialog = firewall.NewFwRuleDlg()
  1204. self.fw_model.run_rule_dialog(dialog)
  1205. def edit_rule_button_pressed(self):
  1206. selected = self.rulesTreeView.selectedIndexes()
  1207. if selected:
  1208. dialog = firewall.NewFwRuleDlg()
  1209. dialog.set_ok_state(True)
  1210. row = self.rulesTreeView.selectedIndexes().pop().row()
  1211. self.fw_model.populate_edit_dialog(dialog, row)
  1212. self.fw_model.run_rule_dialog(dialog, row)
  1213. def delete_rule_button_pressed(self):
  1214. for i in {index.row() for index
  1215. in self.rulesTreeView.selectedIndexes()}:
  1216. self.fw_model.remove_child(i)
  1217. parser = QubesArgumentParser(vmname_nargs=1)
  1218. parser.add_argument('--tab', metavar='TAB',
  1219. action='store',
  1220. choices=VMSettingsWindow.tabs_indices.keys())
  1221. parser.set_defaults(
  1222. tab='basic',
  1223. )
  1224. def main(args=None):
  1225. args = parser.parse_args(args)
  1226. vm = args.domains.pop()
  1227. utils.run_synchronous(functools.partial(VMSettingsWindow, vm, args.tab))
  1228. if __name__ == "__main__":
  1229. main()
  1230. # vim:sw=4:et: