settings.py 56 KB

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