utils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 # pylint: disable=import-error
  33. from PyQt5.QtGui import QIcon # pylint: disable=import-error
  34. def _filter_internal(vm):
  35. return (not vm.klass == 'AdminVM'
  36. and not vm.features.get('internal', False))
  37. def prepare_choice(widget, holder, propname, choice, default,
  38. filter_function=None, *,
  39. icon_getter=None, allow_internal=None, allow_default=False,
  40. allow_none=False, transform=None):
  41. # for newly created vms, set propname to None
  42. debug(
  43. 'prepare_choice(widget={widget!r}, '
  44. 'holder={holder!r}, '
  45. 'propname={propname!r}, '
  46. 'choice={choice!r}, '
  47. 'default={default!r}, '
  48. 'filter_function={filter_function!r}, '
  49. 'icon_getter={icon_getter!r}, '
  50. 'allow_internal={allow_internal!r}, '
  51. 'allow_default={allow_default!r}, '
  52. 'allow_none={allow_none!r})'.format(**locals()))
  53. if propname is not None and allow_default:
  54. default = holder.property_get_default(propname)
  55. if allow_internal is None:
  56. allow_internal = propname is None or not propname.endswith('vm')
  57. if propname is not None:
  58. if holder.property_is_default(propname):
  59. oldvalue = qubesadmin.DEFAULT
  60. else:
  61. oldvalue = getattr(holder, propname)
  62. if oldvalue == '':
  63. oldvalue = None
  64. if transform is not None and oldvalue is not None:
  65. oldvalue = transform(oldvalue)
  66. else:
  67. oldvalue = object() # won't match for identity
  68. idx = 0
  69. choice_list = list(choice)[:]
  70. if not allow_internal:
  71. choice_list = filter(_filter_internal, choice_list)
  72. if filter_function is not None:
  73. choice_list = filter(filter_function, choice_list)
  74. choice_list = list(choice_list)
  75. if allow_default:
  76. choice_list.insert(0, qubesadmin.DEFAULT)
  77. if allow_none:
  78. choice_list.append(None)
  79. for i, item in enumerate(choice_list):
  80. debug('i={} item={}'.format(i, item))
  81. # 0: default (unset)
  82. if item is qubesadmin.DEFAULT:
  83. default_string = str(default) if default is not None else 'none'
  84. if transform is not None:
  85. default_string = transform(default_string)
  86. text = QtCore.QCoreApplication.translate(
  87. "ManagerUtils", 'default ({})').format(default_string)
  88. # N+1: explicit None
  89. elif item is None:
  90. text = QtCore.QCoreApplication.translate("ManagerUtils", '(none)')
  91. # 1..N: choices
  92. else:
  93. text = str(item)
  94. if transform is not None:
  95. text = transform(text)
  96. if item == oldvalue:
  97. text += QtCore.QCoreApplication.translate(
  98. "ManagerUtils", ' (current)')
  99. idx = i
  100. widget.insertItem(i, text)
  101. if icon_getter is not None:
  102. icon = icon_getter(item)
  103. if icon is not None:
  104. widget.setItemIcon(i, icon)
  105. widget.setCurrentIndex(idx)
  106. return choice_list, idx
  107. class KernelVersion: # pylint: disable=too-few-public-methods
  108. # Cannot use distutils.version.LooseVersion, because it fails at handling
  109. # versions that have no numbers in them
  110. def __init__(self, string):
  111. self.string = string
  112. self.groups = re.compile(r'(\d+)').split(self.string)
  113. def __lt__(self, other):
  114. for (self_content, other_content) in itertools.zip_longest(
  115. self.groups, other.groups):
  116. if self_content == other_content:
  117. continue
  118. if self_content.isdigit() and other_content.isdigit():
  119. return int(self_content) < int(other_content)
  120. return self_content < other_content
  121. def prepare_kernel_choice(widget, holder, propname, default, *args, **kwargs):
  122. # TODO get from storage API (pool 'linux-kernel') (suggested by @marmarta)
  123. kernels = sorted(os.listdir('/var/lib/qubes/vm-kernels'),
  124. key=KernelVersion)
  125. return prepare_choice(
  126. widget, holder, propname, kernels, default, *args, **kwargs)
  127. def prepare_label_choice(widget, holder, propname, default, *args, **kwargs):
  128. try:
  129. app = holder.app
  130. except AttributeError:
  131. app = holder
  132. return prepare_choice(widget, holder, propname,
  133. sorted(app.labels.values(), key=lambda l: l.index),
  134. default, *args,
  135. icon_getter=(lambda label:
  136. QIcon.fromTheme(label.icon)),
  137. **kwargs)
  138. def prepare_vm_choice(widget, holder, propname, default, *args, **kwargs):
  139. try:
  140. app = holder.app
  141. except AttributeError:
  142. app = holder
  143. return prepare_choice(widget, holder, propname, app.domains, default,
  144. *args, **kwargs)
  145. def is_debug():
  146. return os.getenv('QUBES_MANAGER_DEBUG', '') not in ('', '0')
  147. def debug(*args, **kwargs):
  148. if not is_debug():
  149. return
  150. print(*args, **kwargs)
  151. def get_path_from_vm(vm, service_name):
  152. """
  153. Displays a file/directory selection window for the given VM.
  154. :param vm: vm from which to select path
  155. :param service_name: qubes.SelectFile or qubes.SelectDirectory
  156. :return: path to file, checked for validity
  157. """
  158. path_re = re.compile(r"[a-zA-Z0-9/:.,_+=() -]*")
  159. path_max_len = 512
  160. if not vm:
  161. return None
  162. stdout, _stderr = vm.run_service_for_stdio(service_name)
  163. stdout = stdout.strip()
  164. untrusted_path = stdout.decode(encoding='ascii')[:path_max_len]
  165. if not untrusted_path:
  166. return None
  167. if path_re.fullmatch(untrusted_path):
  168. assert '../' not in untrusted_path
  169. assert '\0' not in untrusted_path
  170. return untrusted_path.strip()
  171. raise ValueError(QtCore.QCoreApplication.translate(
  172. "ManagerUtils", 'Unexpected characters in path.'))
  173. def format_dependencies_list(dependencies):
  174. """Given a list of tuples representing properties, formats them in
  175. a readable list."""
  176. list_text = ""
  177. for (holder, prop) in dependencies:
  178. if holder is None:
  179. list_text += QtCore.QCoreApplication.translate(
  180. "ManagerUtils", "- Global property <b>{}</b> <br>").format(prop)
  181. else:
  182. list_text += QtCore.QCoreApplication.translate(
  183. "ManagerUtils", "- <b>{0}</b> for qube <b>{1}</b> <br>").format(
  184. prop, holder.name)
  185. return list_text
  186. def loop_shutdown():
  187. pending = asyncio.Task.all_tasks()
  188. for task in pending:
  189. with suppress(asyncio.CancelledError):
  190. task.cancel()
  191. # Bases on the original code by:
  192. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  193. def handle_exception(exc_type, exc_value, exc_traceback):
  194. filename, line, _, _ = traceback.extract_tb(exc_traceback).pop()
  195. filename = os.path.basename(filename)
  196. error = "%s: %s" % (exc_type.__name__, exc_value)
  197. strace = ""
  198. stacktrace = traceback.extract_tb(exc_traceback)
  199. while stacktrace:
  200. (filename, line, func, txt) = stacktrace.pop()
  201. strace += "----\n"
  202. strace += "line: %s\n" % txt
  203. strace += "func: %s\n" % func
  204. strace += "line no.: %d\n" % line
  205. strace += "file: %s\n" % filename
  206. msg_box = QtWidgets.QMessageBox()
  207. msg_box.setDetailedText(strace)
  208. msg_box.setIcon(QtWidgets.QMessageBox.Critical)
  209. msg_box.setWindowTitle(QtCore.QCoreApplication.translate(
  210. "ManagerUtils", "Houston, we have a problem..."))
  211. msg_box.setText(QtCore.QCoreApplication.translate(
  212. "ManagerUtils", "Whoops. A critical error has occured. "
  213. "This is most likely a bug in Qubes Manager.<br><br>"
  214. "<b><i>{0}</i></b><br/>at line <b>{1}</b><br/>of file "
  215. "{2}.<br/><br/>").format(error, line, filename))
  216. msg_box.exec_()
  217. def run_asynchronous(app_name, icon_name, window_class):
  218. qt_app = QtWidgets.QApplication(sys.argv)
  219. translator = QtCore.QTranslator(qt_app)
  220. locale = QtCore.QLocale.system().name()
  221. i18n_dir = os.path.join(
  222. os.path.dirname(os.path.realpath(__file__)),
  223. 'i18n')
  224. translator.load("qubesmanager_{!s}.qm".format(locale), i18n_dir)
  225. qt_app.installTranslator(translator)
  226. qt_app.setOrganizationName("The Qubes Project")
  227. qt_app.setOrganizationDomain("http://qubes-os.org")
  228. qt_app.setApplicationName(app_name)
  229. qt_app.setWindowIcon(QIcon.fromTheme(icon_name))
  230. qt_app.lastWindowClosed.connect(loop_shutdown)
  231. qubes_app = qubesadmin.Qubes()
  232. loop = quamash.QEventLoop(qt_app)
  233. asyncio.set_event_loop(loop)
  234. dispatcher = events.EventsDispatcher(qubes_app)
  235. window = window_class(qt_app, qubes_app, dispatcher)
  236. window.show()
  237. try:
  238. loop.run_until_complete(
  239. asyncio.ensure_future(dispatcher.listen_for_events()))
  240. except asyncio.CancelledError:
  241. pass
  242. except Exception: # pylint: disable=broad-except
  243. loop_shutdown()
  244. exc_type, exc_value, exc_traceback = sys.exc_info()[:3]
  245. handle_exception(exc_type, exc_value, exc_traceback)
  246. def run_synchronous(app_name, window_class):
  247. qt_app = QtWidgets.QApplication(sys.argv)
  248. translator = QtCore.QTranslator(qt_app)
  249. locale = QtCore.QLocale.system().name()
  250. i18n_dir = os.path.join(
  251. os.path.dirname(os.path.realpath(__file__)),
  252. 'i18n')
  253. translator.load("qubesmanager_{!s}.qm".format(locale), i18n_dir)
  254. qt_app.installTranslator(translator)
  255. qt_app.setOrganizationName("The Qubes Project")
  256. qt_app.setOrganizationDomain("http://qubes-os.org")
  257. qt_app.setApplicationName(app_name)
  258. sys.excepthook = handle_exception
  259. qubes_app = qubesadmin.Qubes()
  260. window = window_class(qt_app, qubes_app)
  261. window.show()
  262. qt_app.exec_()
  263. qt_app.exit()