settings.py 56 KB

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