settings.py 30 KB

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