settings.py 32 KB

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