settings.py 32 KB

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