settings.py 57 KB

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