settings.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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 os.path
  26. import os
  27. import re
  28. import subprocess
  29. import threading
  30. import time
  31. import traceback
  32. import sys
  33. from qubesadmin.tools import QubesArgumentParser
  34. from qubesadmin import devices
  35. import qubesadmin.exc
  36. from . import utils
  37. from . import multiselectwidget
  38. from . import thread_monitor
  39. from . import device_list
  40. from .appmenu_select import AppmenuSelectManager
  41. from . import firewall
  42. from PyQt4 import QtCore, QtGui # pylint: disable=import-error
  43. from . import ui_settingsdlg # pylint: disable=no-name-in-module
  44. # pylint: disable=too-many-instance-attributes
  45. class VMSettingsWindow(ui_settingsdlg.Ui_SettingsDialog, QtGui.QDialog):
  46. tabs_indices = collections.OrderedDict((
  47. ('basic', 0),
  48. ('advanced', 1),
  49. ('firewall', 2),
  50. ('devices', 3),
  51. ('applications', 4),
  52. ('services', 5),
  53. ))
  54. def __init__(self, vm, qapp, init_page="basic", parent=None):
  55. super(VMSettingsWindow, self).__init__(parent)
  56. self.vm = vm
  57. self.qapp = qapp
  58. try:
  59. self.source_vm = self.vm.template
  60. except AttributeError:
  61. self.source_vm = self.vm
  62. self.setupUi(self)
  63. self.setWindowTitle(self.tr("Settings: {vm}").format(vm=self.vm.name))
  64. if init_page in self.tabs_indices:
  65. idx = self.tabs_indices[init_page]
  66. assert idx in range(self.tabWidget.count())
  67. self.tabWidget.setCurrentIndex(idx)
  68. self.buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect(
  69. self.save_and_apply)
  70. self.buttonBox.button(QtGui.QDialogButtonBox.Cancel).clicked.connect(
  71. self.reject)
  72. self.buttonBox.button(QtGui.QDialogButtonBox.Apply).clicked.connect(
  73. self.apply)
  74. self.tabWidget.currentChanged.connect(self.current_tab_changed)
  75. ###### basic tab
  76. self.__init_basic_tab__()
  77. self.rename_vm_button.clicked.connect(self.rename_vm)
  78. self.delete_vm_button.clicked.connect(self.remove_vm)
  79. self.clone_vm_button.clicked.connect(self.clone_vm)
  80. ###### advanced tab
  81. self.__init_advanced_tab__()
  82. self.include_in_balancing.stateChanged.connect(
  83. self.include_in_balancing_changed)
  84. self.connect(self.init_mem,
  85. QtCore.SIGNAL("editingFinished()"),
  86. self.check_mem_changes)
  87. self.connect(self.max_mem_size,
  88. QtCore.SIGNAL("editingFinished()"),
  89. self.check_mem_changes)
  90. self.boot_from_device_button.clicked.connect(
  91. self.boot_from_cdrom_button_pressed)
  92. ###### firewall tab
  93. if self.tabWidget.isTabEnabled(self.tabs_indices['firewall']):
  94. model = firewall.QubesFirewallRulesModel()
  95. try:
  96. model.set_vm(vm)
  97. self.set_fw_model(model)
  98. self.firewall_modified_outside_label.setVisible(False)
  99. except firewall.FirewallModifiedOutsideError:
  100. self.disable_all_fw_conf()
  101. self.new_rule_button.clicked.connect(self.new_rule_button_pressed)
  102. self.edit_rule_button.clicked.connect(self.edit_rule_button_pressed)
  103. self.delete_rule_button.clicked.connect(
  104. self.delete_rule_button_pressed)
  105. self.policy_deny_radio_button.clicked.connect(self.policy_changed)
  106. self.policy_allow_radio_button.clicked.connect(self.policy_changed)
  107. if init_page == 'firewall':
  108. self.check_network_availability()
  109. ####### devices tab
  110. self.__init_devices_tab__()
  111. self.connect(self.dev_list,
  112. QtCore.SIGNAL("selected_changed()"),
  113. self.devices_selection_changed)
  114. self.no_strict_reset_button.clicked.connect(
  115. self.strict_reset_button_pressed)
  116. self.current_strict_reset_list = []
  117. self.new_strict_reset_list = []
  118. self.define_strict_reset_devices()
  119. ####### services tab
  120. self.__init_services_tab__()
  121. self.service_line_edit.lineEdit().returnPressed.connect(
  122. self.__add_service__)
  123. self.add_srv_button.clicked.connect(self.__add_service__)
  124. self.remove_srv_button.clicked.connect(self.__remove_service__)
  125. ####### apps tab
  126. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  127. self.app_list = multiselectwidget.MultiSelectWidget(self)
  128. self.apps_layout.addWidget(self.app_list)
  129. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  130. self.refresh_apps_button.clicked.connect(
  131. self.refresh_apps_button_pressed)
  132. def keyPressEvent(self, event): # pylint: disable=invalid-name
  133. if event.key() == QtCore.Qt.Key_Enter \
  134. or event.key() == QtCore.Qt.Key_Return:
  135. return
  136. super(VMSettingsWindow, self).keyPressEvent(event)
  137. def reject(self):
  138. self.done(0)
  139. # needed not to close the dialog before applying changes
  140. def accept(self):
  141. pass
  142. def save_changes(self):
  143. t_monitor = thread_monitor.ThreadMonitor()
  144. thread = threading.Thread(target=self.__save_changes__,
  145. args=(t_monitor,))
  146. thread.daemon = True
  147. thread.start()
  148. progress = QtGui.QProgressDialog(
  149. self.tr("Applying settings to <b>{0}</b>...").format(self.vm.name),
  150. "", 0, 0)
  151. progress.setCancelButton(None)
  152. progress.setModal(True)
  153. progress.show()
  154. while not t_monitor.is_finished():
  155. self.qapp.processEvents()
  156. time.sleep(0.1)
  157. progress.hide()
  158. if not t_monitor.success:
  159. QtGui.QMessageBox.warning(
  160. self,
  161. self.tr("Error while changing settings for {0}!"
  162. ).format(self.vm.name),
  163. self.tr("ERROR: {0}").format(t_monitor.error_msg))
  164. def apply(self):
  165. self.save_changes()
  166. def save_and_apply(self):
  167. self.save_changes()
  168. self.done(0)
  169. def __save_changes__(self, t_monitor):
  170. ret = []
  171. try:
  172. ret_tmp = self.__apply_basic_tab__()
  173. if ret_tmp:
  174. ret += ["Basic tab:"] + ret_tmp
  175. ret_tmp = self.__apply_advanced_tab__()
  176. if ret_tmp:
  177. ret += ["Advanced tab:"] + ret_tmp
  178. ret_tmp = self.__apply_devices_tab__()
  179. if ret_tmp:
  180. ret += ["Devices tab:"] + ret_tmp
  181. ret_tmp = self.__apply_services_tab__()
  182. if ret_tmp:
  183. ret += ["Sevices tab:"] + ret_tmp
  184. except qubesadmin.exc.QubesException as qex:
  185. ret.append(self.tr('Error while saving changes: ') + str(qex))
  186. except Exception as ex: # pylint: disable=broad-except
  187. ret.append(repr(ex))
  188. try:
  189. if self.policy_allow_radio_button.isEnabled():
  190. self.fw_model.apply_rules(
  191. self.policy_allow_radio_button.isChecked(),
  192. self.temp_full_access.isChecked(),
  193. self.temp_full_access_time.value())
  194. except qubesadmin.exc.QubesException as qex:
  195. ret += [self.tr("Firewall tab:"), str(qex)]
  196. except Exception as ex: # pylint: disable=broad-except
  197. ret += [self.tr("Firewall tab:"), repr(ex)]
  198. try:
  199. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  200. self.app_list_manager.save_appmenu_select_changes()
  201. except qubesadmin.exc.QubesException as qex:
  202. ret += [self.tr("Applications tab:"), str(qex)]
  203. except Exception as ex: # pylint: disable=broad-except
  204. ret += [self.tr("Applications tab:"), repr(ex)]
  205. if ret:
  206. t_monitor.set_error_msg('\n'.join(ret))
  207. utils.debug('\n'.join(ret))
  208. t_monitor.set_finished()
  209. def check_network_availability(self):
  210. netvm = self.vm.netvm
  211. self.no_netvm_label.setVisible(netvm is None)
  212. self.netvm_no_firewall_label.setVisible(
  213. netvm is not None and
  214. not netvm.features.check_with_template('qubes-firewall', False))
  215. if netvm is None:
  216. QtGui.QMessageBox.warning(
  217. self,
  218. self.tr("Qube configuration problem!"),
  219. self.tr('This qube has networking disabled '
  220. '(Basic -> Networking) - network will be disabled. '
  221. 'If you want to use firewall, '
  222. 'please enable networking.')
  223. )
  224. if netvm is not None and \
  225. not netvm.features.check_with_template(
  226. 'qubes-firewall',
  227. False):
  228. QtGui.QMessageBox.warning(
  229. self,
  230. self.tr("Qube configuration problem!"),
  231. self.tr("The '{vm}' qube is network connected to "
  232. "'{netvm}', which does not support firewall!<br/>"
  233. "You may edit the '{vm}' qube firewall rules, but "
  234. "these will not take any effect until you connect it "
  235. "to a working Firewall qube.").format(
  236. vm=self.vm.name, netvm=netvm.name))
  237. def current_tab_changed(self, idx):
  238. if idx == self.tabs_indices["firewall"]:
  239. self.check_network_availability()
  240. ######### basic tab
  241. # TODO LISTENERS
  242. # - vm start/shutdown -> setEnabled on fields: template labels
  243. # - vm create/delete -> choices lists, whole window deactiv (if self.vm)
  244. # - property-set -> individual fields
  245. # TODO INTERACTIONS
  246. # netvm -> networking_groupbox
  247. # hvm -> include_in_balancing
  248. # TODO REMOVE
  249. # other_groupbox
  250. def __init_basic_tab__(self):
  251. self.vmname.setText(self.vm.name)
  252. self.vmname.setValidator(
  253. QtGui.QRegExpValidator(
  254. QtCore.QRegExp("[a-zA-Z0-9_-]*",
  255. QtCore.Qt.CaseInsensitive), None))
  256. self.vmname.setEnabled(False)
  257. self.rename_vm_button.setEnabled(not self.vm.is_running())
  258. self.delete_vm_button.setEnabled(not self.vm.is_running())
  259. if self.vm.is_running():
  260. self.delete_vm_button.setText(
  261. self.tr('Delete qube (cannot delete a running qube)'))
  262. if self.vm.qid == 0:
  263. self.vmlabel.setVisible(False)
  264. else:
  265. self.label_list, self.label_idx = utils.prepare_label_choice(
  266. self.vmlabel,
  267. self.vm, 'label',
  268. None,
  269. allow_default=False
  270. )
  271. self.vmlabel.setVisible(True)
  272. self.vmlabel.setEnabled(not self.vm.is_running())
  273. if self.vm.klass == 'AppVM':
  274. self.template_list, self.template_idx = utils.prepare_vm_choice(
  275. self.template_name,
  276. self.vm, 'template',
  277. self.vm.app.default_template,
  278. (lambda vm: vm.klass == 'TemplateVM'),
  279. allow_default=False, allow_none=False)
  280. else:
  281. self.template_name.setEnabled(False)
  282. self.template_idx = -1
  283. self.netvm_list, self.netvm_idx = utils.prepare_vm_choice(
  284. self.netVM,
  285. self.vm, 'netvm',
  286. self.vm.app.default_netvm,
  287. (lambda vm: vm.provides_network),
  288. allow_default=True, allow_none=True)
  289. self.include_in_backups.setChecked(self.vm.include_in_backups)
  290. try:
  291. self.run_in_debug_mode.setChecked(self.vm.debug)
  292. self.run_in_debug_mode.setVisible(True)
  293. except AttributeError:
  294. self.run_in_debug_mode.setVisible(False)
  295. try:
  296. self.autostart_vm.setChecked(self.vm.autostart)
  297. self.autostart_vm.setVisible(True)
  298. except AttributeError:
  299. self.autostart_vm.setVisible(False)
  300. # type
  301. self.type_label.setText(self.vm.klass)
  302. # installed by rpm
  303. self.rpm_label.setText('Yes' if self.vm.installed_by_rpm else 'No')
  304. # networking info
  305. if self.vm.netvm:
  306. self.networking_groupbox.setEnabled(True)
  307. self.ip_label.setText(self.vm.ip or "none")
  308. self.netmask_label.setText(self.vm.visible_netmask or "none")
  309. self.gateway_label.setText(self.vm.visible_gateway or "none")
  310. else:
  311. self.networking_groupbox.setEnabled(False)
  312. # max priv storage
  313. self.priv_img_size = self.vm.volumes['private'].size // 1024**2
  314. self.max_priv_storage.setMinimum(self.priv_img_size)
  315. self.max_priv_storage.setValue(self.priv_img_size)
  316. self.root_img_size = self.vm.volumes['root'].size // 1024**2
  317. self.root_resize.setValue(self.root_img_size)
  318. self.root_resize.setMinimum(self.root_img_size)
  319. self.root_resize.setEnabled(self.vm.volumes['root'].save_on_stop)
  320. self.root_resize_label.setEnabled(self.root_resize.isEnabled())
  321. def __apply_basic_tab__(self):
  322. msg = []
  323. # vm label changed
  324. try:
  325. if self.vmlabel.isVisible():
  326. if self.vmlabel.currentIndex() != self.label_idx:
  327. label = self.label_list[self.vmlabel.currentIndex()]
  328. self.vm.label = label
  329. except qubesadmin.exc.QubesException as ex:
  330. msg.append(str(ex))
  331. # vm template changed
  332. try:
  333. if self.template_name.currentIndex() != self.template_idx:
  334. self.vm.template = \
  335. self.template_list[self.template_name.currentIndex()]
  336. except qubesadmin.exc.QubesException as ex:
  337. msg.append(str(ex))
  338. # vm netvm changed
  339. try:
  340. if self.netVM.currentIndex() != self.netvm_idx:
  341. self.vm.netvm = self.netvm_list[self.netVM.currentIndex()]
  342. except qubesadmin.exc.QubesException as ex:
  343. msg.append(str(ex))
  344. # include in backups
  345. try:
  346. if self.vm.include_in_backups != \
  347. self.include_in_backups.isChecked():
  348. self.vm.include_in_backups = self.include_in_backups.isChecked()
  349. except qubesadmin.exc.QubesException as ex:
  350. msg.append(str(ex))
  351. # run_in_debug_mode
  352. try:
  353. if self.run_in_debug_mode.isVisible():
  354. if self.vm.debug != self.run_in_debug_mode.isChecked():
  355. self.vm.debug = self.run_in_debug_mode.isChecked()
  356. except qubesadmin.exc.QubesException as ex:
  357. msg.append(str(ex))
  358. # autostart_vm
  359. try:
  360. if self.autostart_vm.isVisible():
  361. if self.vm.autostart != self.autostart_vm.isChecked():
  362. self.vm.autostart = self.autostart_vm.isChecked()
  363. except qubesadmin.exc.QubesException as ex:
  364. msg.append(str(ex))
  365. # max priv storage
  366. priv_size = self.max_priv_storage.value()
  367. if self.priv_img_size != priv_size:
  368. try:
  369. self.vm.volumes['private'].resize(priv_size * 1024**2)
  370. except qubesadmin.exc.QubesException as ex:
  371. msg.append(str(ex))
  372. # max sys storage
  373. sys_size = self.root_resize.value()
  374. if self.root_img_size != sys_size:
  375. try:
  376. self.vm.volumes['root'].resize(sys_size * 1024**2)
  377. except qubesadmin.exc.QubesException as ex:
  378. msg.append(str(ex))
  379. return msg
  380. def check_mem_changes(self):
  381. if self.max_mem_size.value() < self.init_mem.value():
  382. QtGui.QMessageBox.warning(
  383. self,
  384. self.tr("Warning!"),
  385. self.tr("Max memory can not be less than initial memory.<br>"
  386. "Setting max memory to equal initial memory."))
  387. self.max_mem_size.setValue(self.init_mem.value())
  388. # Linux specific limit: init memory must not be below
  389. # max_mem_size/10.79 in order to allow scaling up to
  390. # max_mem_size (or else "add_memory() failed: -17" problem)
  391. if self.init_mem.value() * 10 < self.max_mem_size.value():
  392. QtGui.QMessageBox.warning(
  393. self,
  394. self.tr("Warning!"),
  395. self.tr("Initial memory can not be less than one tenth "
  396. "Max memory.<br>Setting initial memory to the minimum "
  397. "allowed value."))
  398. self.init_mem.setValue(self.max_mem_size.value() / 10)
  399. def _run_in_thread(self, func, *args):
  400. t_monitor = thread_monitor.ThreadMonitor()
  401. thread = threading.Thread(target=func, args=(t_monitor, *args,))
  402. thread.daemon = True
  403. thread.start()
  404. while not t_monitor.is_finished():
  405. self.qapp.processEvents()
  406. time.sleep(0.1)
  407. if not t_monitor.success:
  408. QtGui.QMessageBox.warning(self,
  409. self.tr("Error!"),
  410. self.tr("ERROR: {}").format(
  411. t_monitor.error_msg))
  412. return False
  413. return True
  414. def _rename_vm(self, t_monitor, name):
  415. try:
  416. self.vm.app.clone_vm(self.vm, name)
  417. del self.vm.app.domains[self.vm.name]
  418. except qubesadmin.exc.QubesException as qex:
  419. t_monitor.set_error_msg(str(qex))
  420. except Exception as ex: # pylint: disable=broad-except
  421. t_monitor.set_error_msg(repr(ex))
  422. t_monitor.set_finished()
  423. def rename_vm(self):
  424. new_vm_name, ok = QtGui.QInputDialog.getText(
  425. self,
  426. self.tr('Rename qube'),
  427. self.tr('New name: (WARNING: all other changes will be discarded)'))
  428. if ok:
  429. if self._run_in_thread(self._rename_vm, new_vm_name):
  430. self.done(0)
  431. def _remove_vm(self, t_monitor):
  432. try:
  433. del self.vm.app.domains[self.vm.name]
  434. except qubesadmin.exc.QubesException as qex:
  435. t_monitor.set_error_msg(str(qex))
  436. except Exception as ex: # pylint: disable=broad-except
  437. t_monitor.set_error_msg(repr(ex))
  438. t_monitor.set_finished()
  439. def remove_vm(self):
  440. answer, ok = QtGui.QInputDialog.getText(
  441. self,
  442. self.tr('Delete qube'),
  443. self.tr('Are you absolutely sure you want to delete this qube? '
  444. '<br/> All qube settings and data will be irrevocably'
  445. ' deleted. <br/> If you are sure, please enter this '
  446. 'qube\'s name below.'))
  447. if ok and answer == self.vm.name:
  448. self._run_in_thread(self._remove_vm)
  449. self.done(0)
  450. elif ok:
  451. QtGui.QMessageBox.warning(
  452. self,
  453. self.tr("Removal cancelled"),
  454. self.tr("The qube will not be removed."))
  455. def _clone_vm(self, t_monitor, name):
  456. try:
  457. self.vm.app.clone_vm(self.vm, name)
  458. except qubesadmin.exc.QubesException as qex:
  459. t_monitor.set_error_msg(str(qex))
  460. except Exception as ex: # pylint: disable=broad-except
  461. t_monitor.set_error_msg(repr(ex))
  462. t_monitor.set_finished()
  463. def clone_vm(self):
  464. cloned_vm_name, ok = QtGui.QInputDialog.getText(
  465. self,
  466. self.tr('Clone qube'),
  467. self.tr('Name for the cloned qube:'))
  468. if ok:
  469. self._run_in_thread(self._clone_vm, cloned_vm_name)
  470. QtGui.QMessageBox.warning(
  471. self,
  472. self.tr("Success"),
  473. self.tr("The qube was cloned successfully."))
  474. ######### advanced tab
  475. def __init_advanced_tab__(self):
  476. # mem/cpu
  477. # qubes_memory = QubesHost().memory_total/1024
  478. self.init_mem.setValue(int(self.vm.memory))
  479. # self.init_mem.setMaximum(qubes_memory)
  480. self.max_mem_size.setValue(int(self.vm.maxmem))
  481. # self.max_mem_size.setMaximum(qubes_memory)
  482. self.vcpus.setMinimum(1)
  483. # self.vcpus.setMaximum(QubesHost().no_cpus)
  484. self.vcpus.setValue(int(self.vm.vcpus))
  485. self.include_in_balancing.setEnabled(True)
  486. self.include_in_balancing.setChecked(
  487. bool(self.vm.features.get('service.meminfo-writer', True)))
  488. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  489. # in case VM is HVM
  490. if hasattr(self.vm, "kernel"):
  491. self.kernel_groupbox.setVisible(True)
  492. self.kernel_list, self.kernel_idx = utils.prepare_kernel_choice(
  493. self.kernel, self.vm, 'kernel',
  494. None,
  495. allow_default=True, allow_none=True)
  496. self.kernel.currentIndexChanged.connect(self.kernel_changed)
  497. else:
  498. self.kernel_groupbox.setVisible(False)
  499. self.other_groupbox.setVisible(False)
  500. if not hasattr(self.vm, 'default_dispvm'):
  501. self.other_groupbox.setVisible(False)
  502. else:
  503. self.other_groupbox.setVisible(True)
  504. self.default_dispvm_list, self.default_dispvm_idx = \
  505. utils.prepare_vm_choice(
  506. self.default_dispvm,
  507. self.vm, 'default_dispvm',
  508. None,
  509. (lambda vm: getattr(vm, 'template_for_dispvms', False)),
  510. allow_default=True, allow_none=True)
  511. self.update_virt_mode_list()
  512. def __apply_advanced_tab__(self):
  513. msg = []
  514. # mem/cpu
  515. try:
  516. if self.init_mem.value() != int(self.vm.memory):
  517. self.vm.memory = self.init_mem.value()
  518. if self.max_mem_size.value() != int(self.vm.maxmem):
  519. self.vm.maxmem = self.max_mem_size.value()
  520. if self.vcpus.value() != int(self.vm.vcpus):
  521. self.vm.vcpus = self.vcpus.value()
  522. except qubesadmin.exc.QubesException as ex:
  523. msg.append(str(ex))
  524. # include_in_memory_balancing applied in services tab
  525. # in case VM is not Linux
  526. if hasattr(self.vm, "kernel") and self.kernel_groupbox.isVisible():
  527. try:
  528. if self.kernel.currentIndex() != self.kernel_idx:
  529. self.vm.kernel = self.kernel_list[
  530. self.kernel.currentIndex()]
  531. except qubesadmin.exc.QubesException as ex:
  532. msg.append(str(ex))
  533. # vm default_dispvm changed
  534. try:
  535. if self.default_dispvm.currentIndex() != self.default_dispvm_idx:
  536. self.vm.default_dispvm = \
  537. self.default_dispvm_list[self.default_dispvm.currentIndex()]
  538. except qubesadmin.exc.QubesException as ex:
  539. msg.append(str(ex))
  540. try:
  541. if self.virt_mode.currentIndex() != self.virt_mode_idx:
  542. self.vm.virt_mode = self.selected_virt_mode()
  543. except Exception as ex: # pylint: disable=broad-except
  544. msg.append(str(ex))
  545. return msg
  546. def boot_from_cdrom_button_pressed(self):
  547. self.save_and_apply()
  548. subprocess.check_call(['qubes-vm-boot-from-device', self.vm.name])
  549. def selected_virt_mode(self):
  550. return self.virt_mode_list[self.virt_mode.currentIndex()]
  551. def virt_mode_changed(self, new_idx): # pylint: disable=unused-argument
  552. self.update_pv_warning()
  553. self.update_pvh_dont_support_devs()
  554. self.update_pvh_kernel_ver_warning()
  555. def update_pv_warning(self):
  556. if self.selected_virt_mode() == 'PV':
  557. self.pv_warning.show()
  558. else:
  559. self.pv_warning.hide()
  560. def update_virt_mode_list(self):
  561. choices = ['HVM', 'PV']
  562. if hasattr(self, 'dev_list'):
  563. devs_attached = self.dev_list.selected_list.count() != 0
  564. else:
  565. devs_attached = bool(list(self.vm.devices['pci'].persistent()))
  566. if devs_attached:
  567. self.pvh_mode_hidden.show()
  568. else:
  569. choices.insert(0, 'PVH')
  570. self.pvh_mode_hidden.hide()
  571. if hasattr(self, 'virt_mode_list'):
  572. old_mode = self.selected_virt_mode()
  573. self.virt_mode.currentIndexChanged.disconnect()
  574. else:
  575. old_mode = None
  576. self.virt_mode.clear()
  577. # pylint: disable=attribute-defined-outside-init
  578. self.virt_mode_list, self.virt_mode_idx = utils.prepare_choice(
  579. self.virt_mode, self.vm, 'virt_mode', choices, None,
  580. allow_default=True, transform=(lambda x: str(x).upper()))
  581. if old_mode is not None:
  582. self.virt_mode.setCurrentIndex(self.virt_mode_list.index(old_mode))
  583. self.virt_mode.currentIndexChanged.connect(self.virt_mode_changed)
  584. self.update_pv_warning()
  585. self.update_pvh_kernel_ver_warning()
  586. def update_pvh_kernel_ver_warning(self):
  587. if self.selected_virt_mode() != 'PVH':
  588. self.pvh_kernel_version_warning.hide()
  589. return
  590. kernel = self.kernel_list[self.kernel.currentIndex()]
  591. if self.pvh_kernel_version_ok(kernel):
  592. self.pvh_kernel_version_warning.hide()
  593. else:
  594. self.pvh_kernel_version_warning.show()
  595. def kernel_changed(self):
  596. self.update_pvh_kernel_ver_warning()
  597. def pvh_kernel_version_ok(self, name):
  598. # There are nearly no limitaions on kernel names (only file system and
  599. # general qvm-prefs rules). So we just look if we see something which
  600. # looks like a version number. It's just a warning to help the user
  601. # anyways.
  602. if name is None:
  603. return False
  604. if name is qubesadmin.DEFAULT:
  605. name = self.vm.app.default_kernel
  606. m = re.search(r'(\d+)\.(\d+)', name)
  607. if m is None:
  608. return False
  609. return (int(m.group(1)), int(m.group(2))) >= (4, 11)
  610. ######## devices tab
  611. def __init_devices_tab__(self):
  612. self.dev_list = multiselectwidget.MultiSelectWidget(self)
  613. self.dev_list.add_all_button.setVisible(False)
  614. self.devices_layout.addWidget(self.dev_list)
  615. devs = []
  616. lspci = subprocess.check_output(['/usr/sbin/lspci']).decode()
  617. for dev in lspci.splitlines():
  618. devs.append((dev.rstrip(), dev.split(' ')[0]))
  619. # pylint: disable=too-few-public-methods
  620. class DevListWidgetItem(QtGui.QListWidgetItem):
  621. def __init__(self, name, ident, parent=None):
  622. super(DevListWidgetItem, self).__init__(name, parent)
  623. self.ident = ident
  624. persistent = [ass.ident.replace('_', ':')
  625. for ass in self.vm.devices['pci'].persistent()]
  626. for name, ident in devs:
  627. if ident in persistent:
  628. self.dev_list.selected_list.addItem(
  629. DevListWidgetItem(name, ident))
  630. else:
  631. self.dev_list.available_list.addItem(
  632. DevListWidgetItem(name, ident))
  633. if self.dev_list.selected_list.count() > 0\
  634. and self.include_in_balancing.isChecked():
  635. self.dmm_warning_adv.show()
  636. self.dmm_warning_dev.show()
  637. else:
  638. self.dmm_warning_adv.hide()
  639. self.dmm_warning_dev.hide()
  640. if self.vm.is_running():
  641. self.dev_list.setEnabled(False)
  642. self.turn_off_vm_to_modify_devs.setVisible(True)
  643. self.no_strict_reset_button.setEnabled(False)
  644. else:
  645. self.dev_list.setEnabled(True)
  646. self.turn_off_vm_to_modify_devs.setVisible(False)
  647. self.update_pvh_dont_support_devs()
  648. def __apply_devices_tab__(self):
  649. msg = []
  650. try:
  651. old = [ass.ident.replace('_', ':')
  652. for ass in self.vm.devices['pci'].persistent()]
  653. new = [self.dev_list.selected_list.item(i).ident
  654. for i in range(self.dev_list.selected_list.count())]
  655. for ident in new:
  656. if ident not in old:
  657. options = {}
  658. if ident in self.new_strict_reset_list:
  659. options['no-strict-reset'] = True
  660. ass = devices.DeviceAssignment(
  661. self.vm.app.domains['dom0'],
  662. ident.replace(':', '_'),
  663. persistent=True, options=options)
  664. self.vm.devices['pci'].attach(ass)
  665. elif (ident in self.current_strict_reset_list) != \
  666. (ident in self.new_strict_reset_list):
  667. current_assignment = None
  668. for assignment in self.vm.devices['pci'].assignments(
  669. persistent=True):
  670. if assignment.ident.replace("_", ":") == ident:
  671. current_assignment = assignment
  672. break
  673. if current_assignment is None:
  674. # it would be very weird if this happened
  675. msg.append(self.tr("Error re-assigning device ") +
  676. ident)
  677. continue
  678. self.vm.devices['pci'].detach(current_assignment)
  679. current_assignment.options['no-strict-reset'] = \
  680. (ident in self.new_strict_reset_list)
  681. self.vm.devices['pci'].attach(current_assignment)
  682. for ass in self.vm.devices['pci'].assignments(persistent=True):
  683. if ass.ident.replace('_', ':') not in new:
  684. self.vm.devices['pci'].detach(ass)
  685. except qubesadmin.exc.QubesException as ex:
  686. if utils.is_debug():
  687. traceback.print_exc()
  688. msg.append(str(ex))
  689. return msg
  690. def include_in_balancing_changed(self, state):
  691. for i in range(self.services_list.count()):
  692. item = self.services_list.item(i)
  693. if str(item.text()) == 'meminfo-writer':
  694. item.setCheckState(state)
  695. break
  696. if self.dev_list.selected_list.count() > 0:
  697. if state == ui_settingsdlg.QtCore.Qt.Checked:
  698. self.dmm_warning_adv.show()
  699. self.dmm_warning_dev.show()
  700. else:
  701. self.dmm_warning_adv.hide()
  702. self.dmm_warning_dev.hide()
  703. self.max_mem_size.setEnabled(self.include_in_balancing.isChecked())
  704. def devices_selection_changed(self):
  705. if self.include_in_balancing.isChecked():
  706. if self.dev_list.selected_list.count() > 0:
  707. self.dmm_warning_adv.show()
  708. self.dmm_warning_dev.show()
  709. else:
  710. self.dmm_warning_adv.hide()
  711. self.dmm_warning_dev.hide()
  712. self.update_virt_mode_list()
  713. def update_pvh_dont_support_devs(self):
  714. if self.selected_virt_mode() == 'PVH':
  715. self.dev_list.setEnabled(False)
  716. self.pvh_dont_support_devs.setVisible(True)
  717. else:
  718. self.dev_list.setEnabled(True)
  719. self.pvh_dont_support_devs.setVisible(False)
  720. def define_strict_reset_devices(self):
  721. for assignment in self.vm.devices['pci'].assignments():
  722. if assignment.options.get('no-strict-reset', False):
  723. self.current_strict_reset_list.append(
  724. assignment.ident.replace('_', ':'))
  725. self.new_strict_reset_list = self.current_strict_reset_list.copy()
  726. def strict_reset_button_pressed(self):
  727. device_list_window = device_list.PCIDeviceListWindow(
  728. self.vm, self.qapp, self.dev_list, self.new_strict_reset_list, self)
  729. device_list_window.exec()
  730. ######## applications tab
  731. def refresh_apps_in_vm(self, t_monitor):
  732. try:
  733. target_vm = self.vm.template
  734. except AttributeError:
  735. target_vm = self.vm
  736. if not target_vm.is_running():
  737. not_running = True
  738. target_vm.start()
  739. else:
  740. not_running = False
  741. subprocess.check_call(['qvm-sync-appmenus', target_vm.name])
  742. if not_running:
  743. target_vm.shutdown()
  744. t_monitor.set_finished()
  745. def refresh_apps_button_pressed(self):
  746. self.refresh_apps_button.setEnabled(False)
  747. self.refresh_apps_button.setText(self.tr('Refresh in progress...'))
  748. t_monitor = thread_monitor.ThreadMonitor()
  749. thread = threading.Thread(
  750. target=self.refresh_apps_in_vm,
  751. args=(t_monitor,))
  752. thread.daemon = True
  753. thread.start()
  754. while not t_monitor.is_finished():
  755. self.qapp.processEvents()
  756. time.sleep(0.1)
  757. self.app_list_manager = AppmenuSelectManager(self.vm, self.app_list)
  758. self.refresh_apps_button.setEnabled(True)
  759. self.refresh_apps_button.setText(self.tr('Refresh Applications'))
  760. ######## services tab
  761. def __init_services_tab__(self):
  762. self.new_srv_dict = {}
  763. for feature in self.vm.features:
  764. if not feature.startswith('service.'):
  765. continue
  766. service = feature[len('service.'):]
  767. item = QtGui.QListWidgetItem(service)
  768. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked
  769. if self.vm.features[feature]
  770. else ui_settingsdlg.QtCore.Qt.Unchecked)
  771. self.services_list.addItem(item)
  772. self.new_srv_dict[service] = self.vm.features[feature]
  773. self.connect(
  774. self.services_list,
  775. QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),
  776. self.services_item_clicked)
  777. # add suggested services
  778. self.service_line_edit.addItem('clocksync')
  779. self.service_line_edit.addItem('crond')
  780. self.service_line_edit.addItem('cups')
  781. self.service_line_edit.addItem('disable-default-route')
  782. self.service_line_edit.addItem('disable-dns-server')
  783. self.service_line_edit.addItem('meminfo-writer')
  784. self.service_line_edit.addItem('network-manager')
  785. self.service_line_edit.addItem('qubes-firewall')
  786. self.service_line_edit.addItem('qubes-network')
  787. self.service_line_edit.addItem('qubes-update-check')
  788. self.service_line_edit.addItem('qubes-updates-proxy')
  789. self.service_line_edit.addItem('qubes-yum-proxy')
  790. self.service_line_edit.addItem('updates-proxy-setup')
  791. self.service_line_edit.addItem('yum-proxy-setup')
  792. self.service_line_edit.setEditText("")
  793. def __add_service__(self):
  794. srv = str(self.service_line_edit.currentText()).strip()
  795. if srv != "":
  796. if srv in self.new_srv_dict:
  797. QtGui.QMessageBox.information(
  798. self,
  799. '',
  800. self.tr('Service already on the list!'))
  801. else:
  802. item = QtGui.QListWidgetItem(srv)
  803. item.setCheckState(ui_settingsdlg.QtCore.Qt.Checked)
  804. self.services_list.addItem(item)
  805. self.new_srv_dict[srv] = True
  806. def __remove_service__(self):
  807. item = self.services_list.currentItem()
  808. if not item:
  809. return
  810. if str(item.text()) == 'meminfo-writer':
  811. QtGui.QMessageBox.information(
  812. self,
  813. self.tr('Service can not be removed'),
  814. self.tr('Service meminfo-writer can not '
  815. 'be removed from the list.'))
  816. return
  817. row = self.services_list.currentRow()
  818. item = self.services_list.takeItem(row)
  819. del self.new_srv_dict[str(item.text())]
  820. def services_item_clicked(self, item):
  821. if str(item.text()) == 'meminfo-writer':
  822. if item.checkState() == ui_settingsdlg.QtCore.Qt.Checked:
  823. if not self.include_in_balancing.isChecked():
  824. self.include_in_balancing.setChecked(True)
  825. elif item.checkState() == ui_settingsdlg.QtCore.Qt.Unchecked:
  826. if self.include_in_balancing.isChecked():
  827. self.include_in_balancing.setChecked(False)
  828. def __apply_services_tab__(self):
  829. msg = []
  830. try:
  831. for i in range(self.services_list.count()):
  832. item = self.services_list.item(i)
  833. self.new_srv_dict[str(item.text())] = \
  834. (item.checkState() == ui_settingsdlg.QtCore.Qt.Checked)
  835. balancing_was_checked = self.vm.features.get(
  836. 'service.meminfo-writer', True)
  837. balancing_is_checked = self.include_in_balancing.isChecked()
  838. meminfo_writer_checked = self.new_srv_dict.get(
  839. 'meminfo-writer', True)
  840. if balancing_is_checked != meminfo_writer_checked:
  841. if balancing_is_checked != balancing_was_checked:
  842. self.new_srv_dict['meminfo-writer'] = balancing_is_checked
  843. for service, v in self.new_srv_dict.items():
  844. feature = 'service.' + service
  845. if v != self.vm.features.get(feature, object()):
  846. self.vm.features[feature] = v
  847. for feature in self.vm.features:
  848. if not feature.startswith('service.'):
  849. continue
  850. service = feature[len('service.'):]
  851. if service not in self.new_srv_dict:
  852. del self.vm.features[feature]
  853. except qubesadmin.exc.QubesException as ex:
  854. msg.append(str(ex))
  855. return msg
  856. ######### firewall tab related
  857. def set_fw_model(self, model):
  858. self.fw_model = model
  859. self.rulesTreeView.setModel(model)
  860. self.rulesTreeView.header().setResizeMode(
  861. QtGui.QHeaderView.ResizeToContents)
  862. self.rulesTreeView.header().setResizeMode(0, QtGui.QHeaderView.Stretch)
  863. self.set_allow(model.allow)
  864. if model.temp_full_access_expire_time:
  865. self.temp_full_access.setChecked(True)
  866. self.temp_full_access_time.setValue(
  867. (model.temp_full_access_expire_time -
  868. int(firewall.datetime.datetime.now().strftime("%s"))) / 60)
  869. def disable_all_fw_conf(self):
  870. self.firewall_modified_outside_label.setVisible(True)
  871. self.policy_allow_radio_button.setEnabled(False)
  872. self.policy_deny_radio_button.setEnabled(False)
  873. self.rulesTreeView.setEnabled(False)
  874. self.new_rule_button.setEnabled(False)
  875. self.edit_rule_button.setEnabled(False)
  876. self.delete_rule_button.setEnabled(False)
  877. self.firewal_rules_label.setEnabled(False)
  878. self.tempFullAccessWidget.setEnabled(False)
  879. def set_allow(self, allow):
  880. self.policy_allow_radio_button.setChecked(allow)
  881. self.policy_deny_radio_button.setChecked(not allow)
  882. self.policy_changed()
  883. def policy_changed(self):
  884. self.rulesTreeView.setEnabled(
  885. self.policy_deny_radio_button.isChecked())
  886. self.new_rule_button.setEnabled(
  887. self.policy_deny_radio_button.isChecked())
  888. self.edit_rule_button.setEnabled(
  889. self.policy_deny_radio_button.isChecked())
  890. self.delete_rule_button.setEnabled(
  891. self.policy_deny_radio_button.isChecked())
  892. self.firewal_rules_label.setEnabled(
  893. self.policy_deny_radio_button.isChecked())
  894. self.tempFullAccessWidget.setEnabled(
  895. self.policy_deny_radio_button.isChecked())
  896. def new_rule_button_pressed(self):
  897. dialog = firewall.NewFwRuleDlg()
  898. self.fw_model.run_rule_dialog(dialog)
  899. def edit_rule_button_pressed(self):
  900. selected = self.rulesTreeView.selectedIndexes()
  901. if selected:
  902. dialog = firewall.NewFwRuleDlg()
  903. dialog.set_ok_state(True)
  904. row = self.rulesTreeView.selectedIndexes().pop().row()
  905. self.fw_model.populate_edit_dialog(dialog, row)
  906. self.fw_model.run_rule_dialog(dialog, row)
  907. def delete_rule_button_pressed(self):
  908. for i in {index.row() for index
  909. in self.rulesTreeView.selectedIndexes()}:
  910. self.fw_model.remove_child(i)
  911. # Bases on the original code by:
  912. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  913. def handle_exception(exc_type, exc_value, exc_traceback):
  914. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  915. filename = os.path.basename(filename)
  916. error = "%s: %s" % (exc_type.__name__, exc_value)
  917. strace = ""
  918. stacktrace = traceback.extract_tb(exc_traceback)
  919. while stacktrace:
  920. (filename, line, func, txt) = stacktrace.pop()
  921. strace += "----\n"
  922. strace += "line: %s\n" % txt
  923. strace += "func: %s\n" % func
  924. strace += "line no.: %d\n" % line
  925. strace += "file: %s\n" % filename
  926. msg_box = QtGui.QMessageBox()
  927. msg_box.setDetailedText(strace)
  928. msg_box.setIcon(QtGui.QMessageBox.Critical)
  929. msg_box.setWindowTitle("Houston, we have a problem...")
  930. msg_box.setText("Whoops. A critical error has occured. "
  931. "This is most likely a bug in Qubes Manager.<br><br>"
  932. "<b><i>%s</i></b>" % error +
  933. "<br/>at line <b>%d</b><br/>of file %s.<br/><br/>"
  934. % (line, filename))
  935. msg_box.exec_()
  936. parser = QubesArgumentParser(vmname_nargs=1)
  937. parser.add_argument('--tab', metavar='TAB',
  938. action='store',
  939. choices=VMSettingsWindow.tabs_indices.keys())
  940. parser.set_defaults(
  941. tab='basic',
  942. )
  943. def main(args=None):
  944. args = parser.parse_args(args)
  945. vm = args.domains.pop()
  946. qapp = QtGui.QApplication(sys.argv)
  947. qapp.setOrganizationName('Invisible Things Lab')
  948. qapp.setOrganizationDomain("https://www.qubes-os.org/")
  949. qapp.setApplicationName("Qube Settings")
  950. if not utils.is_debug():
  951. sys.excepthook = handle_exception
  952. settings_window = VMSettingsWindow(vm, qapp, args.tab)
  953. settings_window.show()
  954. qapp.exec_()
  955. qapp.exit()
  956. if __name__ == "__main__":
  957. main()
  958. # vim:sw=4:et: