settings.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. #!/usr/bin/python2.6
  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 <marmarek@mimuw.edu.pl>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. import sys
  24. import os
  25. from PyQt4.QtCore import *
  26. from PyQt4.QtGui import *
  27. from qubes.qubes import QubesVmCollection
  28. from qubes.qubes import QubesVmLabels
  29. from qubes.qubes import QubesException
  30. from qubes.qubes import qubes_appmenu_create_cmd
  31. from qubes.qubes import qubes_appmenu_remove_cmd
  32. from qubes.qubes import QubesDaemonPidfile
  33. from qubes.qubes import QubesHost
  34. from qubes.qubes import qrexec_client_path
  35. from qubes.qubes import qubes_kernels_base_dir
  36. import qubesmanager.resources_rc
  37. from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent
  38. import subprocess
  39. import time
  40. import threading
  41. from operator import itemgetter
  42. from copy import copy
  43. from ui_settingsdlg import *
  44. from multiselectwidget import *
  45. from appmenu_select import *
  46. from firewall import *
  47. class VMSettingsWindow(Ui_SettingsDialog, QDialog):
  48. tabs_indices = {"basic": 0,
  49. "advanced": 1,
  50. "firewall": 2,
  51. "devices": 3,
  52. "applications": 4,
  53. "services": 5,}
  54. def __init__(self, vm, app, qvm_collection, init_page="basic", parent=None):
  55. super(VMSettingsWindow, self).__init__(parent)
  56. self.app = app
  57. self.qvm_collection = qvm_collection
  58. self.vm = vm
  59. if self.vm.template:
  60. self.source_vm = self.vm.template
  61. else:
  62. self.source_vm = self.vm
  63. self.setupUi(self)
  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.connect(self.buttonBox, SIGNAL("accepted()"), self.save_and_apply)
  69. self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
  70. self.tabWidget.currentChanged.connect(self.current_tab_changed)
  71. self.tabWidget.setTabEnabled(self.tabs_indices["applications"], not vm.is_netvm())
  72. self.tabWidget.setTabEnabled(self.tabs_indices["firewall"], vm.is_networked() and not (vm.is_netvm() and not vm.is_proxyvm()))
  73. ###### basic tab
  74. self.__init_basic_tab__()
  75. ###### advanced tab
  76. self.__init_advanced_tab__()
  77. self.include_in_balancing.stateChanged.connect(self.include_in_balancing_state_changed)
  78. ###### firewall tab
  79. if self.tabWidget.isTabEnabled(self.tabs_indices["firewall"]):
  80. model = QubesFirewallRulesModel()
  81. model.set_vm(vm)
  82. self.set_fw_model(model)
  83. self.newRuleButton.clicked.connect(self.new_rule_button_pressed)
  84. self.editRuleButton.clicked.connect(self.edit_rule_button_pressed)
  85. self.deleteRuleButton.clicked.connect(self.delete_rule_button_pressed)
  86. ####### devices tab
  87. self.__init_devices_tab__()
  88. self.connect(self.dev_list, SIGNAL("selected_changed()"), self.devices_selection_changed)
  89. ####### services tab
  90. self.__init_services_tab__()
  91. self.add_srv_button.clicked.connect(self.__add_service__)
  92. self.remove_srv_button.clicked.connect(self.__remove_service__)
  93. ####### apps tab
  94. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  95. self.app_list = MultiSelectWidget(self)
  96. self.apps_layout.addWidget(self.app_list)
  97. self.AppListManager = AppmenuSelectManager(self.vm, self.app_list)
  98. def reject(self):
  99. self.done(0)
  100. #needed not to close the dialog before applying changes
  101. def accept(self):
  102. pass
  103. def save_and_apply(self):
  104. thread_monitor = ThreadMonitor()
  105. thread = threading.Thread (target=self.__save_changes__, args=(thread_monitor,))
  106. thread.daemon = True
  107. thread.start()
  108. progress = QProgressDialog ("Applying settings to <b>{0}</b>...".format(self.vm.name), "", 0, 0)
  109. progress.setCancelButton(None)
  110. progress.setModal(True)
  111. progress.show()
  112. while not thread_monitor.is_finished():
  113. self.app.processEvents()
  114. time.sleep (0.1)
  115. progress.hide()
  116. if not thread_monitor.success:
  117. QMessageBox.warning (None, "Error while changing settings for {0}!", "ERROR: {1}".format(self.vm.name, thread_monitor.error_msg))
  118. self.done(0)
  119. def __save_changes__(self, thread_monitor):
  120. self.qvm_collection.lock_db_for_writing()
  121. self.anything_changed = False
  122. ret = self.__apply_basic_tab__()
  123. self.__apply_advanced_tab__()
  124. self.__apply_devices_tab__()
  125. self.__apply_services_tab__()
  126. if len(ret) > 0 :
  127. thread_monitor.set_error_msg('\n'.join(ret))
  128. if self.anything_changed == True:
  129. self.qvm_collection.save()
  130. self.qvm_collection.unlock_db()
  131. if self.tabWidget.isTabEnabled(self.tabs_indices["firewall"]):
  132. self.fw_model.apply_rules(self.policyAllowRadioButton.isChecked(), self.dnsCheckBox.isChecked(), self.icmpCheckBox.isChecked())
  133. if self.tabWidget.isTabEnabled(self.tabs_indices["applications"]):
  134. self.AppListManager.save_appmenu_select_changes()
  135. thread_monitor.set_finished()
  136. def current_tab_changed(self, idx):
  137. if idx == self.tabs_indices["firewall"]:
  138. if self.vm.netvm is not None and not self.vm.netvm.is_proxyvm():
  139. QMessageBox.warning (None, "VM configuration problem!", "The '{0}' AppVM is not network connected to a FirewallVM!<p>".format(self.vm.name) +\
  140. "You may edit the '{0}' VM firewall rules, but these will not take any effect until you connect it to a working Firewall VM.".format(self.vm.name))
  141. ######### basic tab
  142. def __init_basic_tab__(self):
  143. self.vmname.setText(self.vm.name)
  144. #self.qvm_collection.lock_db_for_reading()
  145. #self.qvm_collection.load()
  146. #self.qvm_collection.unlock_db()
  147. self.label_list = QubesVmLabels.values()
  148. self.label_list.sort(key=lambda l: l.index)
  149. self.label_idx = 0
  150. for (i, label) in enumerate(self.label_list):
  151. if label == self.vm.label:
  152. self.label_idx = i
  153. self.vmlabel.insertItem(i, label.name)
  154. self.vmlabel.setItemIcon (i, QIcon(label.icon_path))
  155. self.vmlabel.setCurrentIndex(self.label_idx)
  156. if not self.vm.is_template() and self.vm.template is not None:
  157. template_vm_list = [vm for vm in self.qvm_collection.values() if not vm.internal and vm.is_template()]
  158. self.template_idx = -1
  159. for (i, vm) in enumerate(template_vm_list):
  160. text = vm.name
  161. if vm is self.qvm_collection.get_default_template():
  162. text += " (default)"
  163. if vm.qid == self.vm.template.qid:
  164. self.template_idx = i
  165. text += " (current)"
  166. self.template_name.insertItem(i, text)
  167. self.template_name.setCurrentIndex(self.template_idx)
  168. else:
  169. self.template_name.setEnabled(False)
  170. self.template_idx = -1
  171. if (not self.vm.is_netvm() or self.vm.is_proxyvm()):
  172. netvm_list = [vm for vm in self.qvm_collection.values() if not vm.internal and vm.is_netvm()]
  173. self.netvm_idx = -1
  174. text = "default ("+self.qvm_collection.get_default_netvm().name+")"
  175. if self.vm.uses_default_netvm:
  176. text += " (current)"
  177. self.netvm_idx = 0
  178. self.netVM.insertItem(0, text)
  179. for (i, vm) in enumerate(netvm_list):
  180. text = vm.name
  181. if self.vm.netvm is not None and vm.qid == self.vm.netvm.qid and not self.vm.uses_default_netvm:
  182. self.netvm_idx = i+1
  183. text += " (current)"
  184. self.netVM.insertItem(i+1, text)
  185. none_text = "none"
  186. if self.vm.netvm is None:
  187. none_text += " (current)"
  188. self.netvm_idx = len(netvm_list)+1
  189. self.netVM.insertItem(len(netvm_list)+1, none_text)
  190. self.netVM.setCurrentIndex(self.netvm_idx)
  191. else:
  192. self.netVM.setEnabled(False)
  193. self.netvm_idx = -1
  194. self.include_in_backups.setChecked(self.vm.include_in_backups)
  195. if hasattr(self.vm, 'debug'):
  196. self.run_in_debug_mode.setVisible(True)
  197. self.run_in_debug_mode.setChecked(self.vm.debug)
  198. else:
  199. self.run_in_debug_mode.setVisible(False)
  200. #type
  201. self.type_label.setText(self.vm.type)
  202. #installed by rpm
  203. text = "Yes" if self.vm.installed_by_rpm == True else "No"
  204. self.rpm_label.setText(text)
  205. #networking info
  206. if self.vm.is_networked():
  207. self.networking_groupbox.setEnabled(True);
  208. self.ip_label.setText(self.vm.ip if self.vm.ip is not None else "none")
  209. self.netmask_label.setText(self.vm.netmask if self.vm.netmask is not None else "none")
  210. self.gateway_label.setText(self.vm.gateway if self.vm.gateway is not None else "none")
  211. else:
  212. self.networking_groupbox.setEnabled(False);
  213. #max priv storage
  214. self.priv_img_size = self.vm.get_private_img_sz()/1024/1024
  215. self.max_priv_storage.setMinimum(self.priv_img_size)
  216. self.max_priv_storage.setValue(self.priv_img_size)
  217. def __apply_basic_tab__(self):
  218. msg = []
  219. # vmname changed
  220. vmname = str(self.vmname.text())
  221. if self.vm.name != vmname:
  222. if self.vm.is_running():
  223. msg.append("Can't change name of a running VM.")
  224. elif self.qvm_collection.get_vm_by_name(vmname) is not None:
  225. msg.append("Can't change VM name - a VM named <b>{0}</b> already exists in the system!".format(vmname))
  226. else:
  227. oldname = self.vm.name
  228. try:
  229. self.vm.set_name(vmname)
  230. self.anything_changed = True
  231. except Exception as ex:
  232. msg.append(str(ex))
  233. #vm label changed
  234. if self.vmlabel.currentIndex() != self.label_idx:
  235. label = self.label_list[self.vmlabel.currentIndex()]
  236. self.vm.label = label
  237. self.anything_changed = True
  238. #vm template changed
  239. if self.template_name.currentIndex() != self.template_idx:
  240. new_template_name = self.template_name.currentText()
  241. new_template_name = new_template_name.split(' ')[0]
  242. template_vm = self.qvm_collection.get_vm_by_name(new_template_name)
  243. assert (template_vm is not None and template_vm.qid in self.qvm_collection)
  244. assert template_vm.is_template()
  245. self.vm.template = template_vm
  246. self.anything_changed = True
  247. #vm netvm changed
  248. if self.netVM.currentIndex() != self.netvm_idx:
  249. new_netvm_name = self.netVM.currentText()
  250. new_netvm_name = new_netvm_name.split(' ')[0]
  251. uses_default_netvm = False
  252. if new_netvm_name == "default":
  253. new_netvm_name = self.qvm_collection.get_default_netvm().name
  254. uses_default_netvm = True
  255. if new_netvm_name == "none":
  256. netvm = None
  257. else:
  258. netvm = self.qvm_collection.get_vm_by_name(new_netvm_name)
  259. assert (netvm is None or (netvm is not None and netvm.qid in self.qvm_collection and netvm.is_netvm()))
  260. self.vm.netvm = netvm
  261. self.vm.uses_default_netvm = uses_default_netvm
  262. self.anything_changed = True
  263. #include in backups
  264. if self.vm.include_in_backups != self.include_in_backups.isChecked():
  265. self.vm.include_in_backups = self.include_in_backups.isChecked()
  266. self.anything_changed = True
  267. #run_in_debug_mode
  268. if self.run_in_debug_mode.isVisible():
  269. if self.vm.debug != self.run_in_debug_mode.isChecked():
  270. self.vm.debug = self.run_in_debug_mode.isChecked()
  271. self.anything_changed = True
  272. #max priv storage
  273. priv_size = self.max_priv_storage.value()
  274. if self.priv_img_size != priv_size:
  275. try:
  276. self.vm.resize_private_img(priv_size*1024*1024)
  277. self.anything_changed = True
  278. except Exception as ex:
  279. msg.append(str(ex))
  280. return msg
  281. ######### advanced tab
  282. def __init_advanced_tab__(self):
  283. #mem/cpu
  284. self.init_mem.setValue(int(self.vm.memory))
  285. self.init_mem.setMaximum(int(self.vm.maxmem))
  286. self.max_mem_size.setValue(int(self.vm.maxmem))
  287. self.max_mem_size.setMaximum(QubesHost().memory_total/1024)
  288. self.vcpus.setMinimum(1);
  289. self.vcpus.setMaximum(QubesHost().no_cpus)
  290. self.vcpus.setValue(int(self.vm.vcpus))
  291. self.include_in_balancing.setChecked(self.vm.services['meminfo-writer']==True)
  292. #paths
  293. self.dir_path.setText(self.vm.dir_path)
  294. self.config_path.setText(self.vm.conf_file)
  295. if self.vm.template is not None:
  296. self.root_img_path.setText(self.vm.template.root_img)
  297. else:
  298. self.root_img_path.setText("n/a")
  299. self.volatile_img_path.setText(self.vm.volatile_img)
  300. self.private_img_path.setText(self.vm.private_img)
  301. #kernel
  302. #in case VM is HVM
  303. if not hasattr(self.vm, "kernel"):
  304. self.kernel_groupbox.setVisible(False)
  305. return;
  306. # construct available kernels list
  307. text = "default (" + self.qvm_collection.get_default_kernel() +")"
  308. kernel_list = [text]
  309. for k in os.listdir(qubes_kernels_base_dir):
  310. kernel_list.append(k)
  311. kernel_list.append("none")
  312. self.kernel_idx = 0
  313. # put available kernels to a combobox
  314. for (i, k) in enumerate(kernel_list):
  315. text = k
  316. # and mark the current choice
  317. if (text.startswith("default") and self.vm.uses_default_kernel) or ( self.vm.kernel == k and not self.vm.uses_default_kernel) or (k=="none" and self.vm.kernel==None):
  318. text += " (current)"
  319. self.kernel_idx = i
  320. self.kernel.insertItem(i,text)
  321. self.kernel.setCurrentIndex(self.kernel_idx)
  322. #kernel opts
  323. if self.vm.uses_default_kernelopts:
  324. self.kernel_opts.setText(self.vm.kernelopts + " (default)")
  325. else:
  326. self.kernel_opts.setText(self.vm.kernelopts)
  327. def __apply_advanced_tab__(self):
  328. #mem/cpu
  329. if self.init_mem.value() != int(self.vm.memory):
  330. self.vm.memory = self.init_mem.value()
  331. self.anything_changed = True
  332. if self.max_mem_size.value() != int(self.vm.maxmem):
  333. self.vm.maxmem = self.max_mem_size.value()
  334. self.anything_changed = True
  335. if self.vcpus.value() != int(self.vm.vcpus):
  336. self.vm.vcpus = self.vcpus.value()
  337. self.anything_changed = True
  338. #include_in_memory_balancing applied in services tab
  339. #in case VM is not Linux
  340. if not hasattr(self.vm, "kernel"):
  341. return;
  342. #kernel changed
  343. if not self.kernel_groupbox.isVisible():
  344. return
  345. if self.kernel.currentIndex() != self.kernel_idx:
  346. new_kernel = self.kernel.currentText()
  347. new_kernel = new_kernel.split(' ')[0]
  348. if(new_kernel == "default"):
  349. kernel = self.qvm_collection.get_default_kernel()
  350. self.vm.uses_default_kernel = True
  351. elif(new_kernel == "none"):
  352. kernel = None
  353. self.vm.uses_default_kernel = False;
  354. else:
  355. kernel = new_kernel
  356. self.vm.uses_default_kernel = False;
  357. self.vm.kernel = kernel
  358. self.anything_changed = True
  359. ######## devices tab
  360. def __init_devices_tab__(self):
  361. self.dev_list = MultiSelectWidget(self)
  362. self.devices_layout.addWidget(self.dev_list)
  363. devs = []
  364. lspci = subprocess.Popen(["lspci",], stdout = subprocess.PIPE)
  365. for dev in lspci.stdout:
  366. devs.append( (dev.rstrip(), dev.split(' ')[0]) )
  367. class DevListWidgetItem(QListWidgetItem):
  368. def __init__(self, name, slot, parent = None):
  369. super(DevListWidgetItem, self).__init__(name, parent)
  370. self.slot = slot
  371. for d in devs:
  372. if d[1] in self.vm.pcidevs:
  373. self.dev_list.selected_list.addItem( DevListWidgetItem(d[0], d[1]))
  374. else:
  375. self.dev_list.available_list.addItem( DevListWidgetItem(d[0], d[1]))
  376. if self.dev_list.selected_list.count() > 0 and self.include_in_balancing.isChecked():
  377. self.dmm_warning_adv.show()
  378. self.dmm_warning_dev.show()
  379. else:
  380. self.dmm_warning_adv.hide()
  381. self.dmm_warning_dev.hide()
  382. if self.vm.is_running():
  383. self.dev_list.setEnabled(False)
  384. self.turn_off_vm_to_modify_devs.setVisible(True)
  385. else:
  386. self.dev_list.setEnabled(True)
  387. self.turn_off_vm_to_modify_devs.setVisible(False)
  388. def __apply_devices_tab__(self):
  389. sth_changed = False
  390. added = []
  391. for i in range(self.dev_list.selected_list.count()):
  392. item = self.dev_list.selected_list.item(i)
  393. if item.slot not in self.vm.pcidevs:
  394. added.append(item)
  395. if self.dev_list.selected_list.count() - len(added) < len(self.vm.pcidevs): #sth removed
  396. sth_changed = True;
  397. elif len(added) > 0:
  398. sth_changed = True;
  399. if sth_changed == True:
  400. pcidevs = []
  401. for i in range(self.dev_list.selected_list.count()):
  402. slot = self.dev_list.selected_list.item(i).slot
  403. pcidevs.append(slot)
  404. self.vm.pcidevs = pcidevs
  405. self.anything_changed = True
  406. def include_in_balancing_state_changed(self, state):
  407. for r in range (self.services_list.count()):
  408. item = self.services_list.item(r)
  409. if str(item.text()) == 'meminfo-writer':
  410. item.setCheckState(state)
  411. break;
  412. if self.dev_list.selected_list.count() > 0:
  413. if state == QtCore.Qt.Checked:
  414. self.dmm_warning_adv.show()
  415. self.dmm_warning_dev.show()
  416. else:
  417. self.dmm_warning_adv.hide()
  418. self.dmm_warning_dev.hide()
  419. def devices_selection_changed(self):
  420. if self.include_in_balancing.isChecked():
  421. if self.dev_list.selected_list.count() > 0 :
  422. self.dmm_warning_adv.show()
  423. self.dmm_warning_dev.show()
  424. else:
  425. self.dmm_warning_adv.hide()
  426. self.dmm_warning_dev.hide()
  427. ######## services tab
  428. def __init_services_tab__(self):
  429. for srv in self.vm.services:
  430. item = QListWidgetItem(srv)
  431. if self.vm.services[srv] == True:
  432. item.setCheckState(QtCore.Qt.Checked)
  433. else:
  434. item.setCheckState(QtCore.Qt.Unchecked)
  435. self.services_list.addItem(item)
  436. self.connect(self.services_list, SIGNAL("itemClicked(QListWidgetItem *)"), self.services_item_clicked)
  437. self.new_srv_dict = copy(self.vm.services)
  438. def __add_service__(self):
  439. srv = str(self.service_line_edit.text()).strip()
  440. if srv != "":
  441. if srv in self.new_srv_dict:
  442. QMessageBox.information(None, "", "Service already on the list!")
  443. else:
  444. item = QListWidgetItem(srv)
  445. item.setCheckState(QtCore.Qt.Checked)
  446. self.services_list.addItem(item)
  447. self.new_srv_dict[srv] = True
  448. def __remove_service__(self):
  449. item = self.services_list.currentItem()
  450. if str(item.text()) == 'meminfo-writer':
  451. QMessageBox.information(None, "Service can not be removed", "Service meminfo-writer can not be removed from the list.")
  452. else:
  453. row = self.services_list.currentRow()
  454. item = self.services_list.takeItem(row)
  455. del self.new_srv_dict[str(item.text())]
  456. def services_item_clicked(self, item):
  457. if str(item.text()) == 'meminfo-writer':
  458. if item.checkState() == QtCore.Qt.Checked:
  459. if not self.include_in_balancing.isChecked():
  460. self.include_in_balancing.setChecked(True)
  461. elif item.checkState() == QtCore.Qt.Unchecked:
  462. if self.include_in_balancing.isChecked():
  463. self.include_in_balancing.setChecked(False)
  464. def __apply_services_tab__(self):
  465. for r in range (self.services_list.count()):
  466. item = self.services_list.item(r)
  467. self.new_srv_dict[str(item.text())] = (item.checkState() == QtCore.Qt.Checked)
  468. balancing_was_checked = (self.vm.services['meminfo-writer']==True)
  469. balancing_is_checked = self.include_in_balancing.isChecked()
  470. meminfo_writer_checked = (self.new_srv_dict['meminfo-writer'] == True)
  471. if balancing_is_checked != meminfo_writer_checked:
  472. if balancing_is_checked != balancing_was_checked:
  473. self.new_srv_dict['meminfo-writer'] = balancing_is_checked
  474. if self.new_srv_dict != self.vm.services:
  475. self.vm.services = self.new_srv_dict
  476. self.anything_changed = True
  477. ######### firewall tab related
  478. def set_fw_model(self, model):
  479. self.fw_model = model
  480. self.rulesTreeView.setModel(model)
  481. self.rulesTreeView.header().setResizeMode(QHeaderView.ResizeToContents)
  482. self.rulesTreeView.header().setResizeMode(0, QHeaderView.Stretch)
  483. self.set_allow(model.allow)
  484. self.dnsCheckBox.setChecked(model.allowDns)
  485. self.icmpCheckBox.setChecked(model.allowIcmp)
  486. def set_allow(self, allow):
  487. self.policyAllowRadioButton.setChecked(allow)
  488. self.policyDenyRadioButton.setChecked(not allow)
  489. def new_rule_button_pressed(self):
  490. dialog = NewFwRuleDlg()
  491. self.run_rule_dialog(dialog)
  492. def edit_rule_button_pressed(self):
  493. dialog = NewFwRuleDlg()
  494. dialog.set_ok_enabled(True)
  495. selected = self.rulesTreeView.selectedIndexes()
  496. if len(selected) > 0:
  497. row = self.rulesTreeView.selectedIndexes().pop().row()
  498. address = self.fw_model.get_column_string(0, row).replace(' ', '')
  499. dialog.addressComboBox.setItemText(0, address)
  500. dialog.addressComboBox.setCurrentIndex(0)
  501. service = self.fw_model.get_column_string(1, row)
  502. if service == "any":
  503. service = ""
  504. dialog.serviceComboBox.setItemText(0, service)
  505. dialog.serviceComboBox.setCurrentIndex(0)
  506. protocol = self.fw_model.get_column_string(2, row)
  507. if protocol == "tcp":
  508. dialog.tcp_radio.setChecked(True)
  509. elif protocol == "udp":
  510. dialog.udp_radio.setChecked(True)
  511. else:
  512. dialog.any_radio.setChecked(True)
  513. self.run_rule_dialog(dialog, row)
  514. def delete_rule_button_pressed(self):
  515. for i in set([index.row() for index in self.rulesTreeView.selectedIndexes()]):
  516. self.fw_model.removeChild(i)
  517. self.fw_model.fw_changed = True
  518. def run_rule_dialog(self, dialog, row = None):
  519. if dialog.exec_():
  520. address = str(dialog.addressComboBox.currentText())
  521. service = str(dialog.serviceComboBox.currentText())
  522. port = None
  523. port2 = None
  524. unmask = address.split("/", 1)
  525. if len(unmask) == 2:
  526. address = unmask[0]
  527. netmask = int(unmask[1])
  528. else:
  529. netmask = 32
  530. if address == "*":
  531. address = "0.0.0.0"
  532. netmask = 0
  533. if dialog.any_radio.isChecked():
  534. protocol = "any"
  535. port = 0
  536. else:
  537. if dialog.tcp_radio.isChecked():
  538. protocol = "tcp"
  539. elif dialog.udp_radio.isChecked():
  540. protocol = "udp"
  541. try:
  542. range = service.split("-", 1)
  543. if len(range) == 2:
  544. port = int(range[0])
  545. port2 = int(range[1])
  546. else:
  547. port = int(service)
  548. except (TypeError, ValueError) as ex:
  549. port = self.fw_model.get_service_port(service)
  550. if port is not None:
  551. if port2 is not None and port2 <= port:
  552. QMessageBox.warning(None, "Invalid service ports range", "Port {0} is lower than port {1}.".format(port2, port))
  553. else:
  554. item = QubesFirewallRuleItem(address, netmask, port, port2, protocol)
  555. if row is not None:
  556. self.fw_model.setChild(row, item)
  557. self.fw_model.fw_changed = True
  558. else:
  559. self.fw_model.appendChild(item)
  560. self.fw_model.fw_changed = True
  561. else:
  562. QMessageBox.warning(None, "Invalid service name", "Service '{0} is unknown.".format(service))
  563. # Bases on the original code by:
  564. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  565. def handle_exception( exc_type, exc_value, exc_traceback ):
  566. import sys
  567. import os.path
  568. import traceback
  569. filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
  570. filename = os.path.basename( filename )
  571. error = "%s: %s" % ( exc_type.__name__, exc_value )
  572. strace = ""
  573. stacktrace = traceback.extract_tb( exc_traceback )
  574. while len(stacktrace) > 0:
  575. (filename, line, func, txt) = stacktrace.pop()
  576. strace += "----\n"
  577. strace += "line: %s\n" %txt
  578. strace += "func: %s\n" %func
  579. strace += "line no.: %d\n" %line
  580. strace += "file: %s\n" %filename
  581. msg_box = QMessageBox()
  582. msg_box.setDetailedText(strace)
  583. msg_box.setIcon(QMessageBox.Critical)
  584. msg_box.setWindowTitle( "Houston, we have a problem...")
  585. msg_box.setText("Whoops. A critical error has occured. This is most likely a bug "
  586. "in Qubes Manager.<br><br>"
  587. "<b><i>%s</i></b>" % error +
  588. "<br/>at line <b>%d</b><br/>of file %s.<br/><br/>"
  589. % ( line, filename ))
  590. msg_box.exec_()
  591. def main():
  592. global qubes_host
  593. qubes_host = QubesHost()
  594. global app
  595. app = QApplication(sys.argv)
  596. app.setOrganizationName("The Qubes Project")
  597. app.setOrganizationDomain("http://qubes-os.org")
  598. app.setApplicationName("Qubes VM Settings")
  599. sys.excepthook = handle_exception
  600. qvm_collection = QubesVmCollection()
  601. qvm_collection.lock_db_for_reading()
  602. qvm_collection.load()
  603. qvm_collection.unlock_db()
  604. vm = None
  605. if len(sys.argv) > 1:
  606. vm = qvm_collection.get_vm_by_name(sys.argv[1])
  607. if vm is None or vm.qid not in qvm_collection:
  608. QMessageBox.critical(None, "Qubes VM Settings Error",
  609. "A VM with the name '{0}' does not exist in the system.".format(sys.argv[1]))
  610. sys.exit(1)
  611. else:
  612. vms_list = [vm.name for vm in qvm_collection.values() if (vm.is_appvm() or vm.is_template())]
  613. vmname = QInputDialog.getItem(None, "Select VM", "Select VM:", vms_list, editable = False)
  614. if not vmname[1]:
  615. sys.exit(1)
  616. vm = qvm_collection.get_vm_by_name(vmname[0])
  617. global settings_window
  618. settings_window = VMSettingsWindow(vm, app, qvm_collection, "basic")
  619. settings_window.show()
  620. app.exec_()
  621. app.exit()
  622. if __name__ == "__main__":
  623. main()