utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org
  3. #
  4. # Copyright (C) 2012 Agnieszka Kostrzewa <agnieszka.kostrzewa@gmail.com>
  5. # Copyright (C) 2012 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. #
  22. import itertools
  23. import os
  24. import re
  25. import qubesadmin
  26. import traceback
  27. import asyncio
  28. from contextlib import suppress
  29. import sys
  30. import quamash
  31. from qubesadmin import events
  32. from PyQt5 import QtWidgets, QtCore, QtGui # pylint: disable=import-error
  33. #TODO: remove
  34. def _filter_internal(vm):
  35. return (not vm.klass == 'AdminVM'
  36. and not vm.features.get('internal', False))
  37. def is_internal(vm):
  38. return (vm.klass == 'AdminVM'
  39. or vm.features.get('internal', False))
  40. def translate(string):
  41. return QtCore.QCoreApplication.translate(
  42. "ManagerUtils", string)
  43. class SizeSpinBox(QtWidgets.QSpinBox):
  44. # pylint: disable=invalid-name, no-self-use
  45. def __init__(self, *args, **kwargs):
  46. super(SizeSpinBox, self).__init__(*args, **kwargs)
  47. self.pattern = r'(\d+\.?\d?) ?(GB|MB)'
  48. self.regex = re.compile(self.pattern)
  49. self.validator = QtGui.QRegExpValidator(QtCore.QRegExp(
  50. self.pattern), self)
  51. def textFromValue(self, v: int) -> str:
  52. if v > 1024:
  53. return '{:.1f} GB'.format(v / 1024)
  54. return '{} MB'.format(v)
  55. def validate(self, text: str, pos: int):
  56. return self.validator.validate(text, pos)
  57. def valueFromText(self, text: str) -> int:
  58. value, unit = self.regex.fullmatch(text.strip()).groups()
  59. if unit == 'GB':
  60. multiplier = 1024
  61. else:
  62. multiplier = 1
  63. return int(float(value) * multiplier)
  64. def get_boolean_feature(vm, feature_name):
  65. result = vm.features.get(feature_name, None)
  66. if result is not None:
  67. result = bool(result)
  68. return result
  69. # TODO: doublecheck translation
  70. def did_widget_selection_change(widget):
  71. return not translate(" (current)") in widget.currentText()
  72. def initialize_widget(widget, choices,
  73. selected_value=None):
  74. """
  75. populates widget (ListBox or ComboBox) with items. Previous widget contents
  76. are erased.
  77. :param widget: widget to populate
  78. :param choices: list of tuples (text, value) to use to populate widget
  79. :param selected_value: value to populate widget with
  80. :return:
  81. """
  82. widget.clear()
  83. selected_item = None
  84. for (name, value) in choices:
  85. if value == selected_value:
  86. selected_item = name
  87. widget.addItem(name, value)
  88. if selected_item is not None:
  89. widget.setCurrentIndex(widget.findText(selected_item))
  90. else:
  91. widget.addItem(str(selected_value), selected_value)
  92. widget.setCurrentIndex(widget.findText(str(selected_value)))
  93. widget.setItemText(widget.currentIndex(),
  94. widget.currentText() + translate(" (current)"))
  95. def initialize_widget_for_property(
  96. widget, choices, holder, property_name, allow_default=False):
  97. # potentially add default
  98. if allow_default:
  99. default_property = holder.property_get_default(property_name)
  100. if default_property is None:
  101. default_property = "none"
  102. choices.append(
  103. (translate("default ({})").format(default_property),
  104. qubesadmin.DEFAULT))
  105. # calculate current (can be default)
  106. if holder.property_is_default(property_name):
  107. current_value = qubesadmin.DEFAULT
  108. else:
  109. current_value = getattr(holder, property_name)
  110. initialize_widget(widget, choices, selected_value=current_value)
  111. def initialize_widget_with_vms(widget,
  112. qubes_app,
  113. filter_function=(lambda x: True),
  114. allow_none=False,
  115. holder=None,
  116. property_name=None,
  117. allow_default=False,
  118. allow_internal=False):
  119. choices = []
  120. for vm in qubes_app.domains:
  121. if not allow_internal and is_internal(vm):
  122. continue
  123. if not filter_function(vm):
  124. continue
  125. else:
  126. choices.append((vm.name, vm))
  127. if allow_none:
  128. choices.append((translate("(none)"), None))
  129. initialize_widget_for_property(
  130. widget=widget, choices=choices, holder=holder,
  131. property_name=property_name, allow_default=allow_default)
  132. def initialize_widget_with_kernels(widget,
  133. qubes_app,
  134. allow_none=False,
  135. holder=None,
  136. property_name=None,
  137. allow_default=False
  138. ):
  139. kernels = [kernel.vid for kernel in qubes_app.pools['linux-kernel'].volumes]
  140. kernels = sorted(kernels, key=KernelVersion)
  141. choices = [(kernel, kernel) for kernel in kernels]
  142. if allow_none:
  143. choices.append((translate("(none)"), None))
  144. initialize_widget_for_property(
  145. widget=widget, choices=choices, holder=holder,
  146. property_name=property_name, allow_default=allow_default)
  147. def prepare_choice(widget, holder, propname, choice, default,
  148. filter_function=None, *,
  149. icon_getter=None, allow_internal=None, allow_default=False,
  150. allow_none=False, transform=None):
  151. # for newly created vms, set propname to None
  152. # clear the widget, so that prepare_choice functions can be used
  153. # to refresh widget values
  154. while widget.count() > 0:
  155. widget.removeItem(0)
  156. debug(
  157. 'prepare_choice(widget={widget!r}, '
  158. 'holder={holder!r}, '
  159. 'propname={propname!r}, '
  160. 'choice={choice!r}, '
  161. 'default={default!r}, '
  162. 'filter_function={filter_function!r}, '
  163. 'icon_getter={icon_getter!r}, '
  164. 'allow_internal={allow_internal!r}, '
  165. 'allow_default={allow_default!r}, '
  166. 'allow_none={allow_none!r})'.format(**locals()))
  167. if propname is not None and allow_default:
  168. default = holder.property_get_default(propname)
  169. if allow_internal is None:
  170. allow_internal = propname is None or not propname.endswith('vm')
  171. if propname is not None:
  172. if holder.property_is_default(propname):
  173. oldvalue = qubesadmin.DEFAULT
  174. else:
  175. oldvalue = getattr(holder, propname)
  176. if oldvalue == '':
  177. oldvalue = None
  178. if transform is not None and oldvalue is not None:
  179. oldvalue = transform(oldvalue)
  180. else:
  181. oldvalue = object() # won't match for identity
  182. idx = 0
  183. choice_list = list(choice)[:]
  184. if not allow_internal:
  185. choice_list = filter(_filter_internal, choice_list)
  186. if filter_function is not None:
  187. choice_list = filter(filter_function, choice_list)
  188. choice_list = list(choice_list)
  189. if allow_default:
  190. choice_list.insert(0, qubesadmin.DEFAULT)
  191. if allow_none:
  192. choice_list.append(None)
  193. for i, item in enumerate(choice_list):
  194. debug('i={} item={}'.format(i, item))
  195. # 0: default (unset)
  196. if item is qubesadmin.DEFAULT:
  197. default_string = str(default) if default is not None else 'none'
  198. if transform is not None:
  199. default_string = transform(default_string)
  200. text = QtCore.QCoreApplication.translate(
  201. "ManagerUtils", 'default ({})').format(default_string)
  202. # N+1: explicit None
  203. elif item is None:
  204. text = QtCore.QCoreApplication.translate("ManagerUtils", '(none)')
  205. # 1..N: choices
  206. else:
  207. text = str(item)
  208. if transform is not None:
  209. text = transform(text)
  210. if item == oldvalue:
  211. text += QtCore.QCoreApplication.translate(
  212. "ManagerUtils", ' (current)')
  213. idx = i
  214. widget.insertItem(i, text)
  215. if icon_getter is not None:
  216. icon = icon_getter(item)
  217. if icon is not None:
  218. widget.setItemIcon(i, icon)
  219. widget.setCurrentIndex(idx)
  220. return choice_list, idx
  221. class KernelVersion: # pylint: disable=too-few-public-methods
  222. # Cannot use distutils.version.LooseVersion, because it fails at handling
  223. # versions that have no numbers in them
  224. def __init__(self, string):
  225. self.string = string
  226. self.groups = re.compile(r'(\d+)').split(self.string)
  227. def __lt__(self, other):
  228. for (self_content, other_content) in itertools.zip_longest(
  229. self.groups, other.groups):
  230. if self_content == other_content:
  231. continue
  232. if self_content is None:
  233. return True
  234. if other_content is None:
  235. return False
  236. if self_content.isdigit() and other_content.isdigit():
  237. return int(self_content) < int(other_content)
  238. return self_content < other_content
  239. def prepare_kernel_choice(widget, holder, propname, default, *args, **kwargs):
  240. try:
  241. app = holder.app
  242. except AttributeError:
  243. app = holder
  244. kernels = [kernel.vid for kernel in app.pools['linux-kernel'].volumes]
  245. kernels = sorted(kernels, key=KernelVersion)
  246. return prepare_choice(
  247. widget, holder, propname, kernels, default, *args, **kwargs)
  248. def prepare_label_choice(widget, holder, propname, default, *args, **kwargs):
  249. try:
  250. app = holder.app
  251. except AttributeError:
  252. app = holder
  253. return prepare_choice(widget, holder, propname,
  254. sorted(app.labels.values(), key=lambda l: l.index),
  255. default, *args,
  256. icon_getter=(lambda label:
  257. QtGui.QIcon.fromTheme(label.icon)),
  258. **kwargs)
  259. def prepare_vm_choice(widget, holder, propname, default, *args, **kwargs):
  260. try:
  261. app = holder.app
  262. except AttributeError:
  263. app = holder
  264. return prepare_choice(widget, holder, propname, app.domains, default,
  265. *args, **kwargs)
  266. def is_debug():
  267. return os.getenv('QUBES_MANAGER_DEBUG', '') not in ('', '0')
  268. def debug(*args, **kwargs):
  269. if not is_debug():
  270. return
  271. print(*args, **kwargs)
  272. def get_path_from_vm(vm, service_name):
  273. """
  274. Displays a file/directory selection window for the given VM.
  275. :param vm: vm from which to select path
  276. :param service_name: qubes.SelectFile or qubes.SelectDirectory
  277. :return: path to file, checked for validity
  278. """
  279. path_re = re.compile(r"[a-zA-Z0-9/:.,_+=() -]*")
  280. path_max_len = 512
  281. if not vm:
  282. return None
  283. stdout, _stderr = vm.run_service_for_stdio(service_name)
  284. stdout = stdout.strip()
  285. untrusted_path = stdout.decode(encoding='ascii')[:path_max_len]
  286. if not untrusted_path:
  287. return None
  288. if path_re.fullmatch(untrusted_path):
  289. assert '../' not in untrusted_path
  290. assert '\0' not in untrusted_path
  291. return untrusted_path.strip()
  292. raise ValueError(QtCore.QCoreApplication.translate(
  293. "ManagerUtils", 'Unexpected characters in path.'))
  294. def format_dependencies_list(dependencies):
  295. """Given a list of tuples representing properties, formats them in
  296. a readable list."""
  297. list_text = ""
  298. for (holder, prop) in dependencies:
  299. if holder is None:
  300. list_text += QtCore.QCoreApplication.translate(
  301. "ManagerUtils", "- Global property <b>{}</b> <br>").format(prop)
  302. else:
  303. list_text += QtCore.QCoreApplication.translate(
  304. "ManagerUtils", "- <b>{0}</b> for qube <b>{1}</b> <br>").format(
  305. prop, holder.name)
  306. return list_text
  307. def loop_shutdown():
  308. pending = asyncio.Task.all_tasks()
  309. for task in pending:
  310. with suppress(asyncio.CancelledError):
  311. task.cancel()
  312. # Bases on the original code by:
  313. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  314. def handle_exception(exc_type, exc_value, exc_traceback):
  315. filename, line, _, _ = traceback.extract_tb(exc_traceback).pop()
  316. filename = os.path.basename(filename)
  317. error = "%s: %s" % (exc_type.__name__, exc_value)
  318. strace = ""
  319. stacktrace = traceback.extract_tb(exc_traceback)
  320. while stacktrace:
  321. (filename, line, func, txt) = stacktrace.pop()
  322. strace += "----\n"
  323. strace += "line: %s\n" % txt
  324. strace += "func: %s\n" % func
  325. strace += "line no.: %d\n" % line
  326. strace += "file: %s\n" % filename
  327. msg_box = QtWidgets.QMessageBox()
  328. msg_box.setDetailedText(strace)
  329. msg_box.setIcon(QtWidgets.QMessageBox.Critical)
  330. msg_box.setWindowTitle(QtCore.QCoreApplication.translate(
  331. "ManagerUtils", "Houston, we have a problem..."))
  332. msg_box.setText(QtCore.QCoreApplication.translate(
  333. "ManagerUtils", "Whoops. A critical error has occured. "
  334. "This is most likely a bug in Qubes Manager.<br><br>"
  335. "<b><i>{0}</i></b><br/>at line <b>{1}</b><br/>of file "
  336. "{2}.<br/><br/>").format(error, line, filename))
  337. msg_box.exec_()
  338. def run_asynchronous(window_class):
  339. qt_app = QtWidgets.QApplication(sys.argv)
  340. translator = QtCore.QTranslator(qt_app)
  341. locale = QtCore.QLocale.system().name()
  342. i18n_dir = os.path.join(
  343. os.path.dirname(os.path.realpath(__file__)),
  344. 'i18n')
  345. translator.load("qubesmanager_{!s}.qm".format(locale), i18n_dir)
  346. qt_app.installTranslator(translator)
  347. QtCore.QCoreApplication.installTranslator(translator)
  348. qt_app.setOrganizationName("The Qubes Project")
  349. qt_app.setOrganizationDomain("http://qubes-os.org")
  350. qt_app.lastWindowClosed.connect(loop_shutdown)
  351. qubes_app = qubesadmin.Qubes()
  352. loop = quamash.QEventLoop(qt_app)
  353. asyncio.set_event_loop(loop)
  354. dispatcher = events.EventsDispatcher(qubes_app)
  355. window = window_class(qt_app, qubes_app, dispatcher)
  356. if hasattr(window, "setup_application"):
  357. window.setup_application()
  358. window.show()
  359. try:
  360. loop.run_until_complete(
  361. asyncio.ensure_future(dispatcher.listen_for_events()))
  362. except asyncio.CancelledError:
  363. pass
  364. except Exception: # pylint: disable=broad-except
  365. loop_shutdown()
  366. exc_type, exc_value, exc_traceback = sys.exc_info()[:3]
  367. handle_exception(exc_type, exc_value, exc_traceback)
  368. def run_synchronous(window_class):
  369. qt_app = QtWidgets.QApplication(sys.argv)
  370. translator = QtCore.QTranslator(qt_app)
  371. locale = QtCore.QLocale.system().name()
  372. i18n_dir = os.path.join(
  373. os.path.dirname(os.path.realpath(__file__)),
  374. 'i18n')
  375. translator.load("qubesmanager_{!s}.qm".format(locale), i18n_dir)
  376. qt_app.installTranslator(translator)
  377. QtCore.QCoreApplication.installTranslator(translator)
  378. qt_app.setOrganizationName("The Qubes Project")
  379. qt_app.setOrganizationDomain("http://qubes-os.org")
  380. sys.excepthook = handle_exception
  381. qubes_app = qubesadmin.Qubes()
  382. window = window_class(qt_app, qubes_app)
  383. if hasattr(window, "setup_application"):
  384. window.setup_application()
  385. window.show()
  386. qt_app.exec_()
  387. qt_app.exit()