settings.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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. return
  543. current_netvm = self.netVM.currentData()
  544. if current_netvm is None:
  545. return
  546. if current_netvm != qubesadmin.DEFAULT:
  547. QtWidgets.QMessageBox.warning(
  548. self,
  549. self.tr("Warning!"),
  550. self.tr(
  551. "Connecting a TemplateVM directly to a network is highly"
  552. " discouraged! <br> <small>You are breaking a basic part "
  553. "of Qubes security and there is probably no real need"
  554. " to do so. Continue at your own risk.</small>"))
  555. def check_warn_dispvmnetvm(self):
  556. if not hasattr(self.vm, 'default_dispvm'):
  557. self.warn_netvm_dispvm.setVisible(False)
  558. return
  559. dispvm = self.default_dispvm.currentData()
  560. own_netvm = self.netVM.currentData()
  561. if dispvm == qubesadmin.DEFAULT:
  562. try:
  563. dispvm = self.vm.property_get_default('default_dispvm')
  564. except qubesadmin.exc.QubesDaemonAccessError:
  565. pass
  566. if dispvm == self.vm:
  567. self.warn_netvm_dispvm.setVisible(False)
  568. return
  569. dispvm_netvm = getattr(dispvm, 'netvm', None)
  570. if own_netvm == qubesadmin.DEFAULT:
  571. try:
  572. own_netvm = self.vm.property_get_default('netvm')
  573. except qubesadmin.exc.QubesDaemonAccessError:
  574. # no point in warning if we don't know what we're warning about
  575. self.warn_netvm_dispvm.setVisible(False)
  576. return
  577. if dispvm_netvm and dispvm_netvm != own_netvm:
  578. self.warn_netvm_dispvm.setVisible(True)
  579. else:
  580. self.warn_netvm_dispvm.setVisible(False)
  581. def rename_vm(self):
  582. dependencies = admin_utils.vm_dependencies(self.vm.app, self.vm)
  583. running_dependencies = [vm.name for (vm, prop) in dependencies
  584. if vm and prop == 'template'
  585. and utils.is_running(vm, False)]
  586. if running_dependencies:
  587. QtWidgets.QMessageBox.warning(
  588. self,
  589. self.tr("Qube cannot be renamed!"),
  590. self.tr(
  591. "The following qubes using this qube as a template are "
  592. "running: <br> {}. <br> In order to rename this qube, you "
  593. "must first shut them down.").format(
  594. ", ".join(running_dependencies)))
  595. return
  596. new_vm_name, ok = QtWidgets.QInputDialog.getText(
  597. self,
  598. self.tr('Rename qube'),
  599. self.tr('New name: (WARNING: all other changes will be discarded)'),
  600. text=self.vm.name)
  601. if ok:
  602. thread = RenameVMThread(self.vm, new_vm_name, dependencies)
  603. self.threads_list.append(thread)
  604. thread.finished.connect(self.clear_threads)
  605. self.progress = QtWidgets.QProgressDialog(
  606. self.tr("Renaming Qube..."), "", 0, 0)
  607. self.progress.setCancelButton(None)
  608. self.progress.setModal(True)
  609. self.thread_closes = True
  610. self.progress.show()
  611. thread.start()
  612. def remove_vm(self):
  613. dependencies = admin_utils.vm_dependencies(self.vm.app, self.vm)
  614. if dependencies:
  615. list_text = utils.format_dependencies_list(dependencies)
  616. QtWidgets.QMessageBox.warning(
  617. self,
  618. self.tr("Qube cannot be removed!"),
  619. self.tr("This qube cannot be removed. It is used as:"
  620. " <br> {} <small>If you want to remove this qube, "
  621. "you should remove or change settings of each qube "
  622. "or setting that uses it.</small>").format(list_text))
  623. return
  624. answer, ok = QtWidgets.QInputDialog.getText(
  625. self,
  626. self.tr('Delete qube'),
  627. self.tr('Are you absolutely sure you want to delete this qube? '
  628. '<br/> All qube settings and data will be irrevocably'
  629. ' deleted. <br/> If you are sure, please enter this '
  630. 'qube\'s name below.'))
  631. if ok and answer == self.vm.name:
  632. thread = common_threads.RemoveVMThread(self.vm)
  633. thread.finished.connect(self.clear_threads)
  634. self.threads_list.append(thread)
  635. self.progress = QtWidgets.QProgressDialog(
  636. self.tr("Deleting Qube..."), "", 0, 0)
  637. self.progress.setCancelButton(None)
  638. self.progress.setModal(True)
  639. self.thread_closes = True
  640. self.progress.show()
  641. thread.start()
  642. elif ok:
  643. QtWidgets.QMessageBox.warning(
  644. self,
  645. self.tr("Removal cancelled"),
  646. self.tr("The qube will not be removed."))
  647. def clone_vm(self):
  648. with common_threads.busy_cursor():
  649. clone_window = clone_vm.CloneVMDlg(
  650. self.qapp, self.qubesapp, src_vm=self.vm)
  651. clone_window.exec_()
  652. ######### advanced tab
  653. def __init_advanced_tab__(self):
  654. vm_memory = getattr(self.vm, 'memory', None)
  655. vm_maxmem = getattr(self.vm, 'maxmem', None)
  656. if vm_memory is None:
  657. self.init_mem.setEnabled(False)
  658. else:
  659. self.init_mem.setValue(int(vm_memory))
  660. if vm_maxmem is None:
  661. self.max_mem_size.setEnabled(False)
  662. elif vm_maxmem > 0:
  663. self.max_mem_size.setValue(int(vm_maxmem))
  664. else:
  665. try:
  666. maxmem = self.vm.property_get_default('maxmem')
  667. except qubesadmin.exc.QubesDaemonAccessError:
  668. maxmem = 0
  669. if maxmem == 0:
  670. maxmem = vm_memory
  671. self.max_mem_size.setValue(
  672. int(utils.get_feature(
  673. self.vm, 'qubesmanager.maxmem_value', maxmem)))
  674. self.vcpus.setMinimum(1)
  675. self.vcpus.setValue(int(getattr(self.vm, 'vcpus', 1)))
  676. self.include_in_balancing.setEnabled(True)
  677. self.include_in_balancing.setChecked(
  678. int(getattr(self.vm, 'maxmem', 0)) > 0)
  679. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  680. # in case VM is HVM
  681. if hasattr(self.vm, "kernel"):
  682. self.kernel_groupbox.setVisible(True)
  683. try:
  684. utils.initialize_widget_with_kernels(
  685. widget=self.kernel,
  686. qubes_app=self.qubesapp,
  687. allow_none=True,
  688. allow_default=True,
  689. holder=self.vm,
  690. property_name='kernel')
  691. self.kernel.currentIndexChanged.connect(self.kernel_changed)
  692. self.kernel_opts.setText(getattr(self.vm, 'kernelopts', '-'))
  693. except qubesadmin.exc.QubesDaemonAccessError:
  694. self.kernel_groupbox.setVisible(False)
  695. else:
  696. self.kernel_groupbox.setVisible(False)
  697. if not hasattr(self.vm, 'default_dispvm'):
  698. self.other_groupbox.setVisible(False)
  699. else:
  700. try:
  701. self.other_groupbox.setVisible(True)
  702. utils.initialize_widget_with_vms(
  703. widget=self.default_dispvm,
  704. qubes_app=self.qubesapp,
  705. filter_function=(lambda vm:
  706. getattr(
  707. vm, 'template_for_dispvms', False)),
  708. allow_none=True,
  709. allow_default=True,
  710. holder=self.vm,
  711. property_name='default_dispvm'
  712. )
  713. self.default_dispvm.currentIndexChanged.connect(
  714. self.check_warn_dispvmnetvm)
  715. except qubesadmin.exc.QubesDaemonAccessError:
  716. self.other_groupbox.setVisible(False)
  717. self.check_warn_dispvmnetvm()
  718. self.update_virt_mode_list()
  719. try:
  720. windows_running = \
  721. self.vm.features.check_with_template('os', None) == 'Windows' \
  722. and self.vm.is_running()
  723. except qubesadmin.exc.QubesException:
  724. windows_running = False
  725. self.seamless_on_button.setEnabled(windows_running)
  726. self.seamless_off_button.setEnabled(windows_running)
  727. self.seamless_on_button.clicked.connect(self.enable_seamless)
  728. self.seamless_off_button.clicked.connect(self.disable_seamless)
  729. self.dvm_template_checkbox.setChecked(
  730. getattr(self.vm, 'template_for_dispvms', False))
  731. self.provides_network_checkbox.setChecked(
  732. getattr(self.vm, 'provides_network', False))
  733. if self.provides_network_checkbox.isChecked():
  734. domains_using = [vm.name for vm
  735. in getattr(self.vm, 'connected_vms', [])]
  736. if domains_using:
  737. self.provides_network_checkbox.setEnabled(False)
  738. self.provides_network_checkbox.setToolTip(self.tr(
  739. "Cannot change this setting while this qube is used as a "
  740. "NetVM by the following qubes:\n") +
  741. "\n".join(domains_using))
  742. try:
  743. self.run_in_debug_mode.setChecked(self.vm.debug)
  744. self.run_in_debug_mode.setVisible(True)
  745. except AttributeError:
  746. self.run_in_debug_mode.setVisible(False)
  747. utils.initialize_widget(
  748. widget=self.allow_fullscreen,
  749. choices=[
  750. ('(use system default)', None),
  751. ('allow', True),
  752. ('disallow', False)
  753. ],
  754. selected_value=utils.get_boolean_feature(self.vm,
  755. 'gui-allow-fullscreen'))
  756. self.allow_fullscreen_initial = self.allow_fullscreen.currentIndex()
  757. utils.initialize_widget(
  758. widget=self.allow_utf8,
  759. choices=[
  760. ('(use system default)', None),
  761. ('allow', True),
  762. ('disallow', False)
  763. ],
  764. selected_value=utils.get_boolean_feature(self.vm,
  765. 'gui-allow-utf8-titles'))
  766. self.allow_utf8_initial = self.allow_utf8.currentIndex()
  767. def enable_seamless(self):
  768. try:
  769. self.vm.run_service_for_stdio("qubes.SetGuiMode", input=b'SEAMLESS')
  770. except qubesadmin.exc.QubesException as ex:
  771. QtWidgets.QMessageBox.warning(
  772. self,
  773. self.tr("Failed to set seamless mode"),
  774. self.tr("Error occured: {}".format(str(ex))))
  775. def disable_seamless(self):
  776. try:
  777. self.vm.run_service_for_stdio("qubes.SetGuiMode",
  778. input=b'FULLSCREEN')
  779. except qubesadmin.exc.QubesException as ex:
  780. QtWidgets.QMessageBox.warning(
  781. self,
  782. self.tr("Failed to set fullscreen mode"),
  783. self.tr("Error occured: {}".format(str(ex))))
  784. def __apply_advanced_tab__(self):
  785. msg = []
  786. # mem/cpu
  787. try:
  788. if self.init_mem.isEnabled() and \
  789. self.init_mem.value() != int(self.vm.memory):
  790. self.vm.memory = self.init_mem.value()
  791. curr_maxmem = int(getattr(self.vm, 'maxmem', 0))
  792. if not self.include_in_balancing.isChecked():
  793. maxmem = 0
  794. else:
  795. maxmem = self.max_mem_size.value()
  796. if maxmem != curr_maxmem:
  797. if curr_maxmem > 0:
  798. self.vm.features['qubesmanager.maxmem_value'] = curr_maxmem
  799. if maxmem == 0 or self.max_mem_size.isEnabled():
  800. self.vm.maxmem = maxmem
  801. if self.vcpus.isEnabled() and \
  802. self.vcpus.value() != int(self.vm.vcpus):
  803. self.vm.vcpus = self.vcpus.value()
  804. except qubesadmin.exc.QubesException as ex:
  805. msg.append(str(ex))
  806. # in case VM is not Linux
  807. if hasattr(self.vm, "kernel") and self.kernel_groupbox.isVisible():
  808. try:
  809. if utils.did_widget_selection_change(self.kernel):
  810. self.vm.kernel = self.kernel.currentData()
  811. except qubesadmin.exc.QubesException as ex:
  812. msg.append(str(ex))
  813. # vm default_dispvm changed
  814. try:
  815. if utils.did_widget_selection_change(self.default_dispvm):
  816. self.vm.default_dispvm = self.default_dispvm.currentData()
  817. except qubesadmin.exc.QubesException as ex:
  818. msg.append(str(ex))
  819. try:
  820. if utils.did_widget_selection_change(self.virt_mode):
  821. self.vm.virt_mode = self.virt_mode.currentData()
  822. except Exception as ex: # pylint: disable=broad-except
  823. msg.append(str(ex))
  824. if getattr(self.vm, "template_for_dispvms", False) != \
  825. self.dvm_template_checkbox.isChecked():
  826. try:
  827. self.vm.template_for_dispvms = \
  828. self.dvm_template_checkbox.isChecked()
  829. if self.dvm_template_checkbox.isChecked():
  830. self.vm.features["appmenus-dispvm"] = True
  831. else:
  832. del self.vm.features["appmenus-dispvm"]
  833. except Exception as ex: # pylint: disable=broad-except
  834. msg.append(str(ex))
  835. if getattr(self.vm, 'provides_network', False) != \
  836. self.provides_network_checkbox.isChecked():
  837. try:
  838. self.vm.provides_network = \
  839. self.provides_network_checkbox.isChecked()
  840. except Exception as ex: # pylint: disable=broad-except
  841. msg.append(str(ex))
  842. # run_in_debug_mode
  843. try:
  844. if self.run_in_debug_mode.isVisible():
  845. if self.vm.debug != self.run_in_debug_mode.isChecked():
  846. self.vm.debug = self.run_in_debug_mode.isChecked()
  847. except qubesadmin.exc.QubesException as ex:
  848. msg.append(str(ex))
  849. if self.allow_fullscreen_initial !=\
  850. self.allow_fullscreen.currentIndex():
  851. try:
  852. if self.allow_fullscreen.currentData() is None:
  853. del self.vm.features['gui-allow-fullscreen']
  854. else:
  855. self.vm.features['gui-allow-fullscreen'] = \
  856. self.allow_fullscreen.currentData()
  857. except qubesadmin.exc.QubesException as ex:
  858. msg.append(str(ex))
  859. if self.allow_utf8_initial !=\
  860. self.allow_utf8.currentIndex():
  861. try:
  862. if self.allow_utf8.currentData() is None:
  863. del self.vm.features['gui-allow-utf8-titles']
  864. else:
  865. self.vm.features['gui-allow-utf8-titles'] = \
  866. self.allow_utf8.currentData()
  867. except qubesadmin.exc.QubesException as ex:
  868. msg.append(str(ex))
  869. return msg
  870. def include_in_balancing_changed(self, state):
  871. if self.dev_list.selected_list.count() > 0:
  872. if state == ui_settingsdlg.QtCore.Qt.Checked:
  873. self.dmm_warning_adv.show()
  874. self.dmm_warning_dev.show()
  875. else:
  876. self.dmm_warning_adv.hide()
  877. self.dmm_warning_dev.hide()
  878. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  879. if self.include_in_balancing.isChecked():
  880. self.check_mem_changes()
  881. def boot_from_cdrom_button_pressed(self):
  882. boot_dialog = bootfromdevice.VMBootFromDeviceWindow(
  883. self.vm.name, self.qapp, self.qubesapp, self)
  884. if boot_dialog.exec_():
  885. self.save_and_apply()
  886. qvm_start.main(
  887. ['--cdrom', boot_dialog.cdrom_location, self.vm.name])
  888. def virt_mode_changed(self, new_idx): # pylint: disable=unused-argument
  889. self.update_pv_warning()
  890. self.update_pvh_dont_support_devs()
  891. self.update_pvh_kernel_ver_warning()
  892. def update_pv_warning(self):
  893. if self.virt_mode.currentData() == 'pv':
  894. self.pv_warning.show()
  895. else:
  896. self.pv_warning.hide()
  897. def update_virt_mode_list(self):
  898. choices = [('HVM', 'hvm'),
  899. ('PV', 'pv')]
  900. if hasattr(self, "dev_list"):
  901. devs_attached = self.dev_list.selected_list.count() != 0
  902. else:
  903. try:
  904. devs_attached = bool(list(self.vm.devices['pci'].persistent()))
  905. except qubesadmin.exc.QubesException:
  906. devs_attached = False
  907. if devs_attached:
  908. self.pvh_mode_hidden.show()
  909. else:
  910. choices.insert(0, ('PVH', 'pvh'))
  911. self.pvh_mode_hidden.hide()
  912. old_mode = self.virt_mode.currentData()
  913. if old_mode:
  914. self.virt_mode.currentIndexChanged.disconnect()
  915. # due to how virtualization mode has uniquely different displayed and
  916. # actual name of the default value, I will add it manually
  917. try:
  918. choices.insert(0, (
  919. "default ({})".format(
  920. self.vm.property_get_default('virt_mode').upper()),
  921. qubesadmin.DEFAULT))
  922. except qubesadmin.exc.QubesException:
  923. choices.insert(0,
  924. ("default ({SYSTEM DEFAULT})", qubesadmin.DEFAULT))
  925. try:
  926. utils.initialize_widget_for_property(
  927. widget=self.virt_mode,
  928. choices=choices,
  929. holder=self.vm,
  930. property_name='virt_mode')
  931. except qubesadmin.exc.QubesDaemonAccessError:
  932. self.virt_mode.setEnabled(False)
  933. if self.virt_mode.isEnabled() and old_mode is not None:
  934. self.virt_mode.setCurrentIndex(self.virt_mode.findData(old_mode))
  935. self.virt_mode.currentIndexChanged.connect(self.virt_mode_changed)
  936. self.update_pv_warning()
  937. self.update_pvh_kernel_ver_warning()
  938. def update_pvh_kernel_ver_warning(self):
  939. if self.virt_mode.currentData() != 'pvh':
  940. self.pvh_kernel_version_warning.hide()
  941. return
  942. kernel = self.kernel.currentData()
  943. if self.pvh_kernel_version_ok(kernel):
  944. self.pvh_kernel_version_warning.hide()
  945. else:
  946. self.pvh_kernel_version_warning.show()
  947. def kernel_changed(self):
  948. self.update_pvh_kernel_ver_warning()
  949. def pvh_kernel_version_ok(self, name):
  950. # There are nearly no limitaions on kernel names (only file system and
  951. # general qvm-prefs rules). So we just look if we see something which
  952. # looks like a version number. It's just a warning to help the user
  953. # anyways.
  954. if name is None:
  955. return False
  956. if name is qubesadmin.DEFAULT:
  957. name = getattr(self.vm.app, 'default_kernel', None)
  958. m = re.search(r'(\d+)\.(\d+)', name)
  959. if m is None:
  960. return False
  961. return (int(m.group(1)), int(m.group(2))) >= (4, 11)
  962. ######## devices tab
  963. def __init_devices_tab__(self):
  964. self.dev_list = multiselectwidget.MultiSelectWidget(self)
  965. self.dev_list.add_all_button.setVisible(False)
  966. self.devices_layout.addWidget(self.dev_list)
  967. try:
  968. dom0_devs = \
  969. list(self.vm.app.domains['dom0'].devices['pci'].available())
  970. attached_devs = list(self.vm.devices['pci'].persistent())
  971. except qubesadmin.exc.QubesException:
  972. # no permission to access devices
  973. self.tabWidget.setTabEnabled(self.tabs_indices['devices'], False)
  974. return
  975. # pylint: disable=too-few-public-methods
  976. class DevListWidgetItem(QtWidgets.QListWidgetItem):
  977. def __init__(self, dev, unknown=False, parent=None):
  978. super().__init__(parent)
  979. name = dev.ident.replace('_', ":") + ' ' + dev.description
  980. if unknown:
  981. name += ' (unknown)'
  982. self.setText(name)
  983. self.dev = dev
  984. for dev in dom0_devs:
  985. if dev in attached_devs:
  986. self.dev_list.selected_list.addItem(DevListWidgetItem(dev))
  987. else:
  988. self.dev_list.available_list.addItem(DevListWidgetItem(dev))
  989. for dev in attached_devs:
  990. if dev not in dom0_devs:
  991. self.dev_list.selected_list.addItem(
  992. DevListWidgetItem(dev, unknown=True))
  993. if self.dev_list.selected_list.count() > 0\
  994. and self.include_in_balancing.isChecked():
  995. self.dmm_warning_adv.show()
  996. self.dmm_warning_dev.show()
  997. else:
  998. self.dmm_warning_adv.hide()
  999. self.dmm_warning_dev.hide()
  1000. if utils.is_running(self.vm, False):
  1001. self.dev_list.setEnabled(False)
  1002. self.turn_off_vm_to_modify_devs.setVisible(True)
  1003. self.no_strict_reset_button.setEnabled(False)
  1004. else:
  1005. self.dev_list.setEnabled(True)
  1006. self.turn_off_vm_to_modify_devs.setVisible(False)
  1007. self.update_pvh_dont_support_devs()
  1008. self.dev_list.setEnabled(not utils.is_running(self.vm, False))
  1009. def __apply_devices_tab__(self):
  1010. msg = []
  1011. if not self.tabWidget.isTabEnabled(self.tabs_indices['devices']):
  1012. return msg
  1013. try:
  1014. old_devs = list(self.vm.devices['pci'].persistent())
  1015. new_devs = [self.dev_list.selected_list.item(i).dev
  1016. for i in range(self.dev_list.selected_list.count())]
  1017. for dev in new_devs:
  1018. if dev not in old_devs:
  1019. options = {}
  1020. if dev.ident in self.new_strict_reset_list:
  1021. options['no-strict-reset'] = True
  1022. ass = devices.DeviceAssignment(
  1023. self.vm.app.domains['dom0'],
  1024. dev.ident, persistent=True, options=options)
  1025. self.vm.devices['pci'].attach(ass)
  1026. elif (dev.ident in self.current_strict_reset_list) != \
  1027. (dev.ident in self.new_strict_reset_list):
  1028. current_assignment = None
  1029. for assignment in self.vm.devices['pci'].assignments(
  1030. persistent=True):
  1031. if assignment.ident == dev.ident:
  1032. current_assignment = assignment
  1033. break
  1034. if current_assignment is None:
  1035. # it would be very weird if this happened
  1036. msg.append(self.tr("Error re-assigning device ") +
  1037. dev.ident)
  1038. continue
  1039. self.vm.devices['pci'].detach(current_assignment)
  1040. current_assignment.options['no-strict-reset'] = \
  1041. (dev.ident in self.new_strict_reset_list)
  1042. self.vm.devices['pci'].attach(current_assignment)
  1043. for ass in self.vm.devices['pci'].assignments(persistent=True):
  1044. if ass.device not in new_devs:
  1045. self.vm.devices['pci'].detach(ass)
  1046. except qubesadmin.exc.QubesException as ex:
  1047. if utils.is_debug():
  1048. traceback.print_exc()
  1049. msg.append(str(ex))
  1050. return msg
  1051. def devices_selection_changed(self):
  1052. if self.include_in_balancing.isChecked():
  1053. if self.dev_list.selected_list.count() > 0:
  1054. self.dmm_warning_adv.show()
  1055. self.dmm_warning_dev.show()
  1056. else:
  1057. self.dmm_warning_adv.hide()
  1058. self.dmm_warning_dev.hide()
  1059. self.update_virt_mode_list()
  1060. def update_pvh_dont_support_devs(self):
  1061. # this is the easiest way to check for both normal 'PVH' and
  1062. # default (PVH) options
  1063. if 'PVH' in self.virt_mode.currentText().upper():
  1064. self.dev_list.setEnabled(False)
  1065. self.pvh_dont_support_devs.setVisible(True)
  1066. else:
  1067. self.dev_list.setEnabled(True)
  1068. self.pvh_dont_support_devs.setVisible(False)
  1069. def define_strict_reset_devices(self):
  1070. for assignment in self.vm.devices['pci'].assignments():
  1071. if assignment.options.get('no-strict-reset', False):
  1072. self.current_strict_reset_list.append(
  1073. assignment.ident.replace('_', ':'))
  1074. self.new_strict_reset_list = self.current_strict_reset_list.copy()
  1075. def strict_reset_button_pressed(self):
  1076. device_list_window = device_list.PCIDeviceListWindow(
  1077. self.vm, self.qapp, self.dev_list, self.new_strict_reset_list, self)
  1078. device_list_window.exec()
  1079. ######## applications tab
  1080. def refresh_apps_button_pressed(self):
  1081. self.refresh_apps_button.setEnabled(False)
  1082. self.refresh_apps_button.setText(self.tr('Refresh in progress...'))
  1083. thread = RefreshAppsVMThread(self.vm, self.refresh_apps_button)
  1084. thread.finished.connect(self.clear_threads)
  1085. thread.finished.connect(self.refresh_finished)
  1086. self.threads_list.append(thread)
  1087. thread.start()
  1088. def refresh_finished(self):
  1089. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  1090. self.refresh_apps_button.setEnabled(True)
  1091. self.refresh_apps_button.setText(self.tr('Refresh Applications'))
  1092. def template_apps_change(self):
  1093. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  1094. self.app_list_manager.fill_apps_list(
  1095. template=self.template_name.currentData())
  1096. # add a label to show
  1097. self.warn_template_missing_apps.setVisible(
  1098. self.app_list_manager.has_missing)
  1099. ######## services tab
  1100. def __init_services_tab__(self):
  1101. self.new_srv_dict = {}
  1102. try:
  1103. for feature in self.vm.features:
  1104. if not feature.startswith('service.'):
  1105. continue
  1106. service = feature[len('service.'):]
  1107. item = QtWidgets.QListWidgetItem(service)
  1108. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked
  1109. if self.vm.features[feature]
  1110. else ui_settingsdlg.QtCore.Qt.Unchecked)
  1111. self.services_list.addItem(item)
  1112. self.new_srv_dict[service] = self.vm.features[feature]
  1113. except qubesadmin.exc.QubesDaemonAccessError:
  1114. self.tabWidget.setTabEnabled(self.tabs_indices["services"], False)
  1115. return
  1116. self.service_line_edit.addItem("")
  1117. supported_services = set()
  1118. service_prefix = "supported-service."
  1119. for feature in self.vm.features:
  1120. if feature.startswith(service_prefix):
  1121. supported_services.add(feature[len(service_prefix):])
  1122. if getattr(self.vm, "template", None):
  1123. try:
  1124. for feature in self.vm.template.features:
  1125. if feature.startswith(service_prefix):
  1126. supported_services.add(feature[len(service_prefix):])
  1127. except qubesadmin.exc.QubesDaemonAccessError:
  1128. pass
  1129. for service in sorted(supported_services):
  1130. self.service_line_edit.addItem(service)
  1131. self.service_line_edit.addItem(self.tr('(custom...)'))
  1132. self.service_line_edit.setEditText("")
  1133. def __add_service__(self):
  1134. srv = str(self.service_line_edit.currentText()).strip()
  1135. if srv != "":
  1136. if self.service_line_edit.currentIndex() == \
  1137. len(self.service_line_edit) - 1:
  1138. (custom_name, ok) = QtWidgets.QInputDialog.getText(
  1139. self, self.tr("Custom service name"),
  1140. self.tr(
  1141. "Name of the service:"))
  1142. if ok:
  1143. srv = custom_name.strip()
  1144. else:
  1145. return
  1146. if srv in self.new_srv_dict:
  1147. QtWidgets.QMessageBox.information(
  1148. self,
  1149. '',
  1150. self.tr('Service already on the list!'))
  1151. return
  1152. item = QtWidgets.QListWidgetItem(srv)
  1153. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked)
  1154. self.services_list.addItem(item)
  1155. self.new_srv_dict[srv] = True
  1156. def __remove_service__(self):
  1157. item = self.services_list.currentItem()
  1158. if not item:
  1159. return
  1160. row = self.services_list.currentRow()
  1161. item = self.services_list.takeItem(row)
  1162. del self.new_srv_dict[str(item.text())]
  1163. def __apply_services_tab__(self):
  1164. msg = []
  1165. if not self.tabWidget.isTabEnabled(self.tabs_indices['services']):
  1166. return msg
  1167. try:
  1168. for i in range(self.services_list.count()):
  1169. item = self.services_list.item(i)
  1170. self.new_srv_dict[str(item.text())] = \
  1171. (item.checkState() == ui_settingsdlg.QtCore.Qt.Checked)
  1172. for service, v in self.new_srv_dict.items():
  1173. feature = 'service.' + service
  1174. if v != self.vm.features.get(feature, object()):
  1175. self.vm.features[feature] = v
  1176. for feature in self.vm.features:
  1177. if not feature.startswith('service.'):
  1178. continue
  1179. service = feature[len('service.'):]
  1180. if service not in self.new_srv_dict:
  1181. del self.vm.features[feature]
  1182. except qubesadmin.exc.QubesException as ex:
  1183. msg.append(str(ex))
  1184. return msg
  1185. ######### firewall tab related
  1186. def set_fw_model(self, model):
  1187. self.fw_model = model
  1188. self.rulesTreeView.setModel(model)
  1189. self.rulesTreeView.header().setSectionResizeMode(
  1190. QtWidgets.QHeaderView.ResizeToContents)
  1191. self.rulesTreeView.header().setSectionResizeMode(
  1192. 0, QtWidgets.QHeaderView.Stretch)
  1193. self.set_allow(model.allow)
  1194. if model.temp_full_access_expire_time:
  1195. self.temp_full_access.setChecked(True)
  1196. self.temp_full_access_time.setValue(
  1197. (model.temp_full_access_expire_time -
  1198. int(firewall.datetime.datetime.now().strftime("%s"))) / 60)
  1199. def disable_all_fw_conf(self):
  1200. self.firewall_modified_outside_label.setVisible(True)
  1201. self.policy_allow_radio_button.setEnabled(False)
  1202. self.policy_deny_radio_button.setEnabled(False)
  1203. self.rulesTreeView.setEnabled(False)
  1204. self.new_rule_button.setEnabled(False)
  1205. self.edit_rule_button.setEnabled(False)
  1206. self.delete_rule_button.setEnabled(False)
  1207. self.firewal_rules_label.setEnabled(False)
  1208. self.tempFullAccessWidget.setEnabled(False)
  1209. def set_allow(self, allow):
  1210. self.policy_allow_radio_button.setChecked(allow)
  1211. self.policy_deny_radio_button.setChecked(not allow)
  1212. self.policy_changed()
  1213. def policy_changed(self):
  1214. self.rulesTreeView.setEnabled(
  1215. self.policy_deny_radio_button.isChecked())
  1216. self.new_rule_button.setEnabled(
  1217. self.policy_deny_radio_button.isChecked())
  1218. self.edit_rule_button.setEnabled(
  1219. self.policy_deny_radio_button.isChecked())
  1220. self.delete_rule_button.setEnabled(
  1221. self.policy_deny_radio_button.isChecked())
  1222. self.firewal_rules_label.setEnabled(
  1223. self.policy_deny_radio_button.isChecked())
  1224. self.tempFullAccessWidget.setEnabled(
  1225. self.policy_deny_radio_button.isChecked())
  1226. def new_rule_button_pressed(self):
  1227. dialog = firewall.NewFwRuleDlg()
  1228. self.fw_model.run_rule_dialog(dialog)
  1229. def edit_rule_button_pressed(self):
  1230. selected = self.rulesTreeView.selectedIndexes()
  1231. if selected:
  1232. dialog = firewall.NewFwRuleDlg()
  1233. dialog.set_ok_state(True)
  1234. row = self.rulesTreeView.selectedIndexes().pop().row()
  1235. self.fw_model.populate_edit_dialog(dialog, row)
  1236. self.fw_model.run_rule_dialog(dialog, row)
  1237. def delete_rule_button_pressed(self):
  1238. for i in {index.row() for index
  1239. in self.rulesTreeView.selectedIndexes()}:
  1240. self.fw_model.remove_child(i)
  1241. parser = QubesArgumentParser(vmname_nargs=1)
  1242. parser.add_argument('--tab', metavar='TAB',
  1243. action='store',
  1244. choices=VMSettingsWindow.tabs_indices.keys())
  1245. parser.set_defaults(
  1246. tab='basic',
  1247. )
  1248. def main(args=None):
  1249. args = parser.parse_args(args)
  1250. vm = args.domains.pop()
  1251. utils.run_synchronous(functools.partial(VMSettingsWindow, vm, args.tab))
  1252. if __name__ == "__main__":
  1253. main()
  1254. # vim:sw=4:et: