settings.py 57 KB

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