utils.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 os
  23. import re
  24. import qubesadmin
  25. from PyQt5.QtGui import QIcon # pylint: disable=import-error
  26. def _filter_internal(vm):
  27. return (not vm.klass == 'AdminVM'
  28. and not vm.features.get('internal', False))
  29. def prepare_choice(widget, holder, propname, choice, default,
  30. filter_function=None, *,
  31. icon_getter=None, allow_internal=None, allow_default=False,
  32. allow_none=False, transform=None):
  33. # for newly created vms, set propname to None
  34. debug(
  35. 'prepare_choice(widget={widget!r}, '
  36. 'holder={holder!r}, '
  37. 'propname={propname!r}, '
  38. 'choice={choice!r}, '
  39. 'default={default!r}, '
  40. 'filter_function={filter_function!r}, '
  41. 'icon_getter={icon_getter!r}, '
  42. 'allow_internal={allow_internal!r}, '
  43. 'allow_default={allow_default!r}, '
  44. 'allow_none={allow_none!r})'.format(**locals()))
  45. if propname is not None and allow_default:
  46. default = holder.property_get_default(propname)
  47. if allow_internal is None:
  48. allow_internal = propname is None or not propname.endswith('vm')
  49. if propname is not None:
  50. if holder.property_is_default(propname):
  51. oldvalue = qubesadmin.DEFAULT
  52. else:
  53. oldvalue = getattr(holder, propname)
  54. if oldvalue == '':
  55. oldvalue = None
  56. if transform is not None and oldvalue is not None:
  57. oldvalue = transform(oldvalue)
  58. else:
  59. oldvalue = object() # won't match for identity
  60. idx = 0
  61. choice_list = list(choice)[:]
  62. if not allow_internal:
  63. choice_list = filter(_filter_internal, choice_list)
  64. if filter_function is not None:
  65. choice_list = filter(filter_function, choice_list)
  66. choice_list = list(choice_list)
  67. if allow_default:
  68. choice_list.insert(0, qubesadmin.DEFAULT)
  69. if allow_none:
  70. choice_list.append(None)
  71. for i, item in enumerate(choice_list):
  72. debug('i={} item={}'.format(i, item))
  73. # 0: default (unset)
  74. if item is qubesadmin.DEFAULT:
  75. default_string = str(default) if default is not None else 'none'
  76. if transform is not None:
  77. default_string = transform(default_string)
  78. text = 'default ({})'.format(default_string)
  79. # N+1: explicit None
  80. elif item is None:
  81. text = '(none)'
  82. # 1..N: choices
  83. else:
  84. text = str(item)
  85. if transform is not None:
  86. text = transform(text)
  87. if item == oldvalue:
  88. text += ' (current)'
  89. idx = i
  90. widget.insertItem(i, text)
  91. if icon_getter is not None:
  92. icon = icon_getter(item)
  93. if icon is not None:
  94. widget.setItemIcon(i, icon)
  95. widget.setCurrentIndex(idx)
  96. return choice_list, idx
  97. def prepare_kernel_choice(widget, holder, propname, default, *args, **kwargs):
  98. # TODO get from storage API (pool 'linux-kernel') (suggested by @marmarta)
  99. return prepare_choice(widget, holder, propname,
  100. os.listdir('/var/lib/qubes/vm-kernels'),
  101. default, *args, **kwargs)
  102. def prepare_label_choice(widget, holder, propname, default, *args, **kwargs):
  103. try:
  104. app = holder.app
  105. except AttributeError:
  106. app = holder
  107. return prepare_choice(widget, holder, propname,
  108. sorted(app.labels.values(), key=lambda l: l.index),
  109. default, *args,
  110. icon_getter=(lambda label:
  111. QIcon.fromTheme(label.icon)),
  112. **kwargs)
  113. def prepare_vm_choice(widget, holder, propname, default, *args, **kwargs):
  114. try:
  115. app = holder.app
  116. except AttributeError:
  117. app = holder
  118. return prepare_choice(widget, holder, propname, app.domains, default,
  119. *args, **kwargs)
  120. def is_debug():
  121. return os.getenv('QUBES_MANAGER_DEBUG', '') not in ('', '0')
  122. def debug(*args, **kwargs):
  123. if not is_debug():
  124. return
  125. print(*args, **kwargs)
  126. def get_path_from_vm(vm, service_name):
  127. """
  128. Displays a file/directory selection window for the given VM.
  129. :param vm: vm from which to select path
  130. :param service_name: qubes.SelectFile or qubes.SelectDirectory
  131. :return: path to file, checked for validity
  132. """
  133. path_re = re.compile(r"[a-zA-Z0-9/:.,_+=() -]*")
  134. path_max_len = 512
  135. if not vm:
  136. return None
  137. stdout, _stderr = vm.run_service_for_stdio(service_name)
  138. stdout = stdout.strip()
  139. untrusted_path = stdout.decode(encoding='ascii')[:path_max_len]
  140. if not untrusted_path:
  141. return None
  142. if path_re.fullmatch(untrusted_path):
  143. assert '../' not in untrusted_path
  144. assert '\0' not in untrusted_path
  145. return untrusted_path.strip()
  146. raise ValueError('Unexpected characters in path.')
  147. def format_dependencies_list(dependencies):
  148. """Given a list of tuples representing properties, formats them in
  149. a readable list."""
  150. list_text = ""
  151. for (holder, prop) in dependencies:
  152. if holder is None:
  153. list_text += "- Global property <b>{}</b> <br>".format(prop)
  154. else:
  155. list_text += "- <b>{}</b> for qube <b>{}</b> <br>".format(
  156. prop, holder.name)
  157. return list_text