settings.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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. if self.vm.qid == 0:
  148. self.vmlabel.setVisible(False)
  149. else:
  150. self.vmlabel.setVisible(True)
  151. self.label_list = QubesVmLabels.values()
  152. self.label_list.sort(key=lambda l: l.index)
  153. self.label_idx = 0
  154. for (i, label) in enumerate(self.label_list):
  155. if label == self.vm.label:
  156. self.label_idx = i
  157. self.vmlabel.insertItem(i, label.name)
  158. self.vmlabel.setItemIcon (i, QIcon(label.icon_path))
  159. self.vmlabel.setCurrentIndex(self.label_idx)
  160. if not self.vm.is_template() and self.vm.template is not None:
  161. template_vm_list = [vm for vm in self.qvm_collection.values() if not vm.internal and vm.is_template()]
  162. self.template_idx = -1
  163. for (i, vm) in enumerate(template_vm_list):
  164. text = vm.name
  165. if vm is self.qvm_collection.get_default_template():
  166. text += " (default)"
  167. if vm.qid == self.vm.template.qid:
  168. self.template_idx = i
  169. text += " (current)"
  170. self.template_name.insertItem(i, text)
  171. self.template_name.setCurrentIndex(self.template_idx)
  172. else:
  173. self.template_name.setEnabled(False)
  174. self.template_idx = -1
  175. if (not self.vm.is_netvm() or self.vm.is_proxyvm()):
  176. netvm_list = [vm for vm in self.qvm_collection.values() if not vm.internal and vm.is_netvm()]
  177. self.netvm_idx = -1
  178. text = "default ("+self.qvm_collection.get_default_netvm().name+")"
  179. if self.vm.uses_default_netvm:
  180. text += " (current)"
  181. self.netvm_idx = 0
  182. self.netVM.insertItem(0, text)
  183. for (i, vm) in enumerate(netvm_list):
  184. text = vm.name
  185. if self.vm.netvm is not None and vm.qid == self.vm.netvm.qid and not self.vm.uses_default_netvm:
  186. self.netvm_idx = i+1
  187. text += " (current)"
  188. self.netVM.insertItem(i+1, text)
  189. none_text = "none"
  190. if self.vm.netvm is None:
  191. none_text += " (current)"
  192. self.netvm_idx = len(netvm_list)+1
  193. self.netVM.insertItem(len(netvm_list)+1, none_text)
  194. self.netVM.setCurrentIndex(self.netvm_idx)
  195. else:
  196. self.netVM.setEnabled(False)
  197. self.netvm_idx = -1
  198. self.include_in_backups.setChecked(self.vm.include_in_backups)
  199. if hasattr(self.vm, 'debug'):
  200. self.run_in_debug_mode.setVisible(True)
  201. self.run_in_debug_mode.setChecked(self.vm.debug)
  202. else:
  203. self.run_in_debug_mode.setVisible(False)
  204. #type
  205. self.type_label.setText(self.vm.type)
  206. #installed by rpm
  207. text = "Yes" if self.vm.installed_by_rpm == True else "No"
  208. self.rpm_label.setText(text)
  209. #networking info
  210. if self.vm.is_networked():
  211. self.networking_groupbox.setEnabled(True);
  212. self.ip_label.setText(self.vm.ip if self.vm.ip is not None else "none")
  213. self.netmask_label.setText(self.vm.netmask if self.vm.netmask is not None else "none")
  214. self.gateway_label.setText(self.vm.gateway if self.vm.gateway is not None else "none")
  215. else:
  216. self.networking_groupbox.setEnabled(False);
  217. #max priv storage
  218. self.priv_img_size = self.vm.get_private_img_sz()/1024/1024
  219. self.max_priv_storage.setMinimum(self.priv_img_size)
  220. self.max_priv_storage.setValue(self.priv_img_size)
  221. def __apply_basic_tab__(self):
  222. msg = []
  223. # vmname changed
  224. vmname = str(self.vmname.text())
  225. if self.vm.name != vmname:
  226. if self.vm.is_running():
  227. msg.append("Can't change name of a running VM.")
  228. elif self.qvm_collection.get_vm_by_name(vmname) is not None:
  229. msg.append("Can't change VM name - a VM named <b>{0}</b> already exists in the system!".format(vmname))
  230. else:
  231. oldname = self.vm.name
  232. try:
  233. self.vm.set_name(vmname)
  234. self.anything_changed = True
  235. except Exception as ex:
  236. msg.append(str(ex))
  237. #vm label changed
  238. if self.vmlabel.isVisible():
  239. if self.vmlabel.currentIndex() != self.label_idx:
  240. label = self.label_list[self.vmlabel.currentIndex()]
  241. self.vm.label = label
  242. self.anything_changed = True
  243. #vm template changed
  244. if self.template_name.currentIndex() != self.template_idx:
  245. new_template_name = self.template_name.currentText()
  246. new_template_name = new_template_name.split(' ')[0]
  247. template_vm = self.qvm_collection.get_vm_by_name(new_template_name)
  248. assert (template_vm is not None and template_vm.qid in self.qvm_collection)
  249. assert template_vm.is_template()
  250. self.vm.template = template_vm
  251. self.anything_changed = True
  252. #vm netvm changed
  253. if self.netVM.currentIndex() != self.netvm_idx:
  254. new_netvm_name = self.netVM.currentText()
  255. new_netvm_name = new_netvm_name.split(' ')[0]
  256. uses_default_netvm = False
  257. if new_netvm_name == "default":
  258. new_netvm_name = self.qvm_collection.get_default_netvm().name
  259. uses_default_netvm = True
  260. if new_netvm_name == "none":
  261. netvm = None
  262. else:
  263. netvm = self.qvm_collection.get_vm_by_name(new_netvm_name)
  264. assert (netvm is None or (netvm is not None and netvm.qid in self.qvm_collection and netvm.is_netvm()))
  265. self.vm.netvm = netvm
  266. self.vm.uses_default_netvm = uses_default_netvm
  267. self.anything_changed = True
  268. #include in backups
  269. if self.vm.include_in_backups != self.include_in_backups.isChecked():
  270. self.vm.include_in_backups = self.include_in_backups.isChecked()
  271. self.anything_changed = True
  272. #run_in_debug_mode
  273. if self.run_in_debug_mode.isVisible():
  274. if self.vm.debug != self.run_in_debug_mode.isChecked():
  275. self.vm.debug = self.run_in_debug_mode.isChecked()
  276. self.anything_changed = True
  277. #max priv storage
  278. priv_size = self.max_priv_storage.value()
  279. if self.priv_img_size != priv_size:
  280. try:
  281. self.vm.resize_private_img(priv_size*1024*1024)
  282. self.anything_changed = True
  283. except Exception as ex:
  284. msg.append(str(ex))
  285. return msg
  286. ######### advanced tab
  287. def __init_advanced_tab__(self):
  288. #mem/cpu
  289. self.init_mem.setValue(int(self.vm.memory))
  290. self.init_mem.setMaximum(int(self.vm.maxmem))
  291. self.max_mem_size.setValue(int(self.vm.maxmem))
  292. self.max_mem_size.setMaximum(QubesHost().memory_total/1024)
  293. self.vcpus.setMinimum(1);
  294. self.vcpus.setMaximum(QubesHost().no_cpus)
  295. self.vcpus.setValue(int(self.vm.vcpus))
  296. self.include_in_balancing.setChecked(self.vm.services['meminfo-writer']==True)
  297. #paths
  298. self.dir_path.setText(self.vm.dir_path)
  299. self.config_path.setText(self.vm.conf_file)
  300. if self.vm.template is not None:
  301. self.root_img_path.setText(self.vm.template.root_img)
  302. elif self.vm.root_img is not None:
  303. self.root_img_path.setText(self.vm.root_img)
  304. else:
  305. self.root_img_path.setText("n/a")
  306. if self.vm.volatile_img is not None:
  307. self.volatile_img_path.setText(self.vm.volatile_img)
  308. else:
  309. self.volatile_img_path.setText('n/a')
  310. self.private_img_path.setText(self.vm.private_img)
  311. #kernel
  312. #in case VM is HVM
  313. if not hasattr(self.vm, "kernel"):
  314. self.kernel_groupbox.setVisible(False)
  315. return;
  316. # construct available kernels list
  317. text = "default (" + self.qvm_collection.get_default_kernel() +")"
  318. kernel_list = [text]
  319. for k in os.listdir(qubes_kernels_base_dir):
  320. kernel_list.append(k)
  321. kernel_list.append("none")
  322. self.kernel_idx = 0
  323. # put available kernels to a combobox
  324. for (i, k) in enumerate(kernel_list):
  325. text = k
  326. # and mark the current choice
  327. 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):
  328. text += " (current)"
  329. self.kernel_idx = i
  330. self.kernel.insertItem(i,text)
  331. self.kernel.setCurrentIndex(self.kernel_idx)
  332. #kernel opts
  333. if self.vm.uses_default_kernelopts:
  334. self.kernel_opts.setText(self.vm.kernelopts + " (default)")
  335. else:
  336. self.kernel_opts.setText(self.vm.kernelopts)
  337. def __apply_advanced_tab__(self):
  338. #mem/cpu
  339. if self.init_mem.value() != int(self.vm.memory):
  340. self.vm.memory = self.init_mem.value()
  341. self.anything_changed = True
  342. if self.max_mem_size.value() != int(self.vm.maxmem):
  343. self.vm.maxmem = self.max_mem_size.value()
  344. self.anything_changed = True
  345. if self.vcpus.value() != int(self.vm.vcpus):
  346. self.vm.vcpus = self.vcpus.value()
  347. self.anything_changed = True
  348. #include_in_memory_balancing applied in services tab
  349. #in case VM is not Linux
  350. if not hasattr(self.vm, "kernel"):
  351. return;
  352. #kernel changed
  353. if not self.kernel_groupbox.isVisible():
  354. return
  355. if self.kernel.currentIndex() != self.kernel_idx:
  356. new_kernel = self.kernel.currentText()
  357. new_kernel = new_kernel.split(' ')[0]
  358. if(new_kernel == "default"):
  359. kernel = self.qvm_collection.get_default_kernel()
  360. self.vm.uses_default_kernel = True
  361. elif(new_kernel == "none"):
  362. kernel = None
  363. self.vm.uses_default_kernel = False;
  364. else:
  365. kernel = new_kernel
  366. self.vm.uses_default_kernel = False;
  367. self.vm.kernel = kernel
  368. self.anything_changed = True
  369. ######## devices tab
  370. def __init_devices_tab__(self):
  371. self.dev_list = MultiSelectWidget(self)
  372. self.devices_layout.addWidget(self.dev_list)
  373. devs = []
  374. lspci = subprocess.Popen(["lspci",], stdout = subprocess.PIPE)
  375. for dev in lspci.stdout:
  376. devs.append( (dev.rstrip(), dev.split(' ')[0]) )
  377. class DevListWidgetItem(QListWidgetItem):
  378. def __init__(self, name, slot, parent = None):
  379. super(DevListWidgetItem, self).__init__(name, parent)
  380. self.slot = slot
  381. for d in devs:
  382. if d[1] in self.vm.pcidevs:
  383. self.dev_list.selected_list.addItem( DevListWidgetItem(d[0], d[1]))
  384. else:
  385. self.dev_list.available_list.addItem( DevListWidgetItem(d[0], d[1]))
  386. if self.dev_list.selected_list.count() > 0 and self.include_in_balancing.isChecked():
  387. self.dmm_warning_adv.show()
  388. self.dmm_warning_dev.show()
  389. else:
  390. self.dmm_warning_adv.hide()
  391. self.dmm_warning_dev.hide()
  392. if self.vm.is_running():
  393. self.dev_list.setEnabled(False)
  394. self.turn_off_vm_to_modify_devs.setVisible(True)
  395. else:
  396. self.dev_list.setEnabled(True)
  397. self.turn_off_vm_to_modify_devs.setVisible(False)
  398. def __apply_devices_tab__(self):
  399. sth_changed = False
  400. added = []
  401. for i in range(self.dev_list.selected_list.count()):
  402. item = self.dev_list.selected_list.item(i)
  403. if item.slot not in self.vm.pcidevs:
  404. added.append(item)
  405. if self.dev_list.selected_list.count() - len(added) < len(self.vm.pcidevs): #sth removed
  406. sth_changed = True;
  407. elif len(added) > 0:
  408. sth_changed = True;
  409. if sth_changed == True:
  410. pcidevs = []
  411. for i in range(self.dev_list.selected_list.count()):
  412. slot = self.dev_list.selected_list.item(i).slot
  413. pcidevs.append(slot)
  414. self.vm.pcidevs = pcidevs
  415. self.anything_changed = True
  416. def include_in_balancing_state_changed(self, state):
  417. for r in range (self.services_list.count()):
  418. item = self.services_list.item(r)
  419. if str(item.text()) == 'meminfo-writer':
  420. item.setCheckState(state)
  421. break;
  422. if self.dev_list.selected_list.count() > 0:
  423. if state == QtCore.Qt.Checked:
  424. self.dmm_warning_adv.show()
  425. self.dmm_warning_dev.show()
  426. else:
  427. self.dmm_warning_adv.hide()
  428. self.dmm_warning_dev.hide()
  429. def devices_selection_changed(self):
  430. if self.include_in_balancing.isChecked():
  431. if self.dev_list.selected_list.count() > 0 :
  432. self.dmm_warning_adv.show()
  433. self.dmm_warning_dev.show()
  434. else:
  435. self.dmm_warning_adv.hide()
  436. self.dmm_warning_dev.hide()
  437. ######## services tab
  438. def __init_services_tab__(self):
  439. for srv in self.vm.services:
  440. item = QListWidgetItem(srv)
  441. if self.vm.services[srv] == True:
  442. item.setCheckState(QtCore.Qt.Checked)
  443. else:
  444. item.setCheckState(QtCore.Qt.Unchecked)
  445. self.services_list.addItem(item)
  446. self.connect(self.services_list, SIGNAL("itemClicked(QListWidgetItem *)"), self.services_item_clicked)
  447. self.new_srv_dict = copy(self.vm.services)
  448. def __add_service__(self):
  449. srv = str(self.service_line_edit.text()).strip()
  450. if srv != "":
  451. if srv in self.new_srv_dict:
  452. QMessageBox.information(None, "", "Service already on the list!")
  453. else:
  454. item = QListWidgetItem(srv)
  455. item.setCheckState(QtCore.Qt.Checked)
  456. self.services_list.addItem(item)
  457. self.new_srv_dict[srv] = True
  458. def __remove_service__(self):
  459. item = self.services_list.currentItem()
  460. if str(item.text()) == 'meminfo-writer':
  461. QMessageBox.information(None, "Service can not be removed", "Service meminfo-writer can not be removed from the list.")
  462. else:
  463. row = self.services_list.currentRow()
  464. item = self.services_list.takeItem(row)
  465. del self.new_srv_dict[str(item.text())]
  466. def services_item_clicked(self, item):
  467. if str(item.text()) == 'meminfo-writer':
  468. if item.checkState() == QtCore.Qt.Checked:
  469. if not self.include_in_balancing.isChecked():
  470. self.include_in_balancing.setChecked(True)
  471. elif item.checkState() == QtCore.Qt.Unchecked:
  472. if self.include_in_balancing.isChecked():
  473. self.include_in_balancing.setChecked(False)
  474. def __apply_services_tab__(self):
  475. for r in range (self.services_list.count()):
  476. item = self.services_list.item(r)
  477. self.new_srv_dict[str(item.text())] = (item.checkState() == QtCore.Qt.Checked)
  478. balancing_was_checked = (self.vm.services['meminfo-writer']==True)
  479. balancing_is_checked = self.include_in_balancing.isChecked()
  480. meminfo_writer_checked = (self.new_srv_dict['meminfo-writer'] == True)
  481. if balancing_is_checked != meminfo_writer_checked:
  482. if balancing_is_checked != balancing_was_checked:
  483. self.new_srv_dict['meminfo-writer'] = balancing_is_checked
  484. if self.new_srv_dict != self.vm.services:
  485. self.vm.services = self.new_srv_dict
  486. self.anything_changed = True
  487. ######### firewall tab related
  488. def set_fw_model(self, model):
  489. self.fw_model = model
  490. self.rulesTreeView.setModel(model)
  491. self.rulesTreeView.header().setResizeMode(QHeaderView.ResizeToContents)
  492. self.rulesTreeView.header().setResizeMode(0, QHeaderView.Stretch)
  493. self.set_allow(model.allow)
  494. self.dnsCheckBox.setChecked(model.allowDns)
  495. self.icmpCheckBox.setChecked(model.allowIcmp)
  496. def set_allow(self, allow):
  497. self.policyAllowRadioButton.setChecked(allow)
  498. self.policyDenyRadioButton.setChecked(not allow)
  499. def new_rule_button_pressed(self):
  500. dialog = NewFwRuleDlg()
  501. self.run_rule_dialog(dialog)
  502. def edit_rule_button_pressed(self):
  503. dialog = NewFwRuleDlg()
  504. dialog.set_ok_enabled(True)
  505. selected = self.rulesTreeView.selectedIndexes()
  506. if len(selected) > 0:
  507. row = self.rulesTreeView.selectedIndexes().pop().row()
  508. address = self.fw_model.get_column_string(0, row).replace(' ', '')
  509. dialog.addressComboBox.setItemText(0, address)
  510. dialog.addressComboBox.setCurrentIndex(0)
  511. service = self.fw_model.get_column_string(1, row)
  512. if service == "any":
  513. service = ""
  514. dialog.serviceComboBox.setItemText(0, service)
  515. dialog.serviceComboBox.setCurrentIndex(0)
  516. protocol = self.fw_model.get_column_string(2, row)
  517. if protocol == "tcp":
  518. dialog.tcp_radio.setChecked(True)
  519. elif protocol == "udp":
  520. dialog.udp_radio.setChecked(True)
  521. else:
  522. dialog.any_radio.setChecked(True)
  523. self.run_rule_dialog(dialog, row)
  524. def delete_rule_button_pressed(self):
  525. for i in set([index.row() for index in self.rulesTreeView.selectedIndexes()]):
  526. self.fw_model.removeChild(i)
  527. self.fw_model.fw_changed = True
  528. def run_rule_dialog(self, dialog, row = None):
  529. if dialog.exec_():
  530. address = str(dialog.addressComboBox.currentText())
  531. service = str(dialog.serviceComboBox.currentText())
  532. port = None
  533. port2 = None
  534. unmask = address.split("/", 1)
  535. if len(unmask) == 2:
  536. address = unmask[0]
  537. netmask = int(unmask[1])
  538. else:
  539. netmask = 32
  540. if address == "*":
  541. address = "0.0.0.0"
  542. netmask = 0
  543. if dialog.any_radio.isChecked():
  544. protocol = "any"
  545. port = 0
  546. else:
  547. if dialog.tcp_radio.isChecked():
  548. protocol = "tcp"
  549. elif dialog.udp_radio.isChecked():
  550. protocol = "udp"
  551. try:
  552. range = service.split("-", 1)
  553. if len(range) == 2:
  554. port = int(range[0])
  555. port2 = int(range[1])
  556. else:
  557. port = int(service)
  558. except (TypeError, ValueError) as ex:
  559. port = self.fw_model.get_service_port(service)
  560. if port is not None:
  561. if port2 is not None and port2 <= port:
  562. QMessageBox.warning(None, "Invalid service ports range", "Port {0} is lower than port {1}.".format(port2, port))
  563. else:
  564. item = QubesFirewallRuleItem(address, netmask, port, port2, protocol)
  565. if row is not None:
  566. self.fw_model.setChild(row, item)
  567. self.fw_model.fw_changed = True
  568. else:
  569. self.fw_model.appendChild(item)
  570. self.fw_model.fw_changed = True
  571. else:
  572. QMessageBox.warning(None, "Invalid service name", "Service '{0} is unknown.".format(service))
  573. # Bases on the original code by:
  574. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  575. def handle_exception( exc_type, exc_value, exc_traceback ):
  576. import sys
  577. import os.path
  578. import traceback
  579. filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
  580. filename = os.path.basename( filename )
  581. error = "%s: %s" % ( exc_type.__name__, exc_value )
  582. strace = ""
  583. stacktrace = traceback.extract_tb( exc_traceback )
  584. while len(stacktrace) > 0:
  585. (filename, line, func, txt) = stacktrace.pop()
  586. strace += "----\n"
  587. strace += "line: %s\n" %txt
  588. strace += "func: %s\n" %func
  589. strace += "line no.: %d\n" %line
  590. strace += "file: %s\n" %filename
  591. msg_box = QMessageBox()
  592. msg_box.setDetailedText(strace)
  593. msg_box.setIcon(QMessageBox.Critical)
  594. msg_box.setWindowTitle( "Houston, we have a problem...")
  595. msg_box.setText("Whoops. A critical error has occured. This is most likely a bug "
  596. "in Qubes Manager.<br><br>"
  597. "<b><i>%s</i></b>" % error +
  598. "<br/>at line <b>%d</b><br/>of file %s.<br/><br/>"
  599. % ( line, filename ))
  600. msg_box.exec_()
  601. def main():
  602. global qubes_host
  603. qubes_host = QubesHost()
  604. global app
  605. app = QApplication(sys.argv)
  606. app.setOrganizationName("The Qubes Project")
  607. app.setOrganizationDomain("http://qubes-os.org")
  608. app.setApplicationName("Qubes VM Settings")
  609. sys.excepthook = handle_exception
  610. qvm_collection = QubesVmCollection()
  611. qvm_collection.lock_db_for_reading()
  612. qvm_collection.load()
  613. qvm_collection.unlock_db()
  614. vm = None
  615. tab = "basic"
  616. if len(sys.argv) > 1:
  617. vm = qvm_collection.get_vm_by_name(sys.argv[1])
  618. if vm is None or vm.qid not in qvm_collection:
  619. QMessageBox.critical(None, "Qubes VM Settings Error",
  620. "A VM with the name '{0}' does not exist in the system.".format(sys.argv[1]))
  621. sys.exit(1)
  622. if len(sys.argv) > 2:
  623. tab_arg = sys.argv[2]
  624. print tab_arg
  625. if tab_arg in VMSettingsWindow.tabs_indices:
  626. tab = tab_arg
  627. else: QMessageBox.warning(None, "Qubes VM Settings Error",
  628. "There is no such tab as '{0}'. Opening default tab instead.".format(tab_arg))
  629. else:
  630. vms_list = [vm.name for vm in qvm_collection.values() if (vm.is_appvm() or vm.is_template())]
  631. vmname = QInputDialog.getItem(None, "Select VM", "Select VM:", vms_list, editable = False)
  632. if not vmname[1]:
  633. sys.exit(1)
  634. vm = qvm_collection.get_vm_by_name(vmname[0])
  635. global settings_window
  636. settings_window = VMSettingsWindow(vm, app, qvm_collection, tab)
  637. settings_window.show()
  638. app.exec_()
  639. app.exit()
  640. if __name__ == "__main__":
  641. main()