utils.py 12 KB

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