settings.py 56 KB

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