utils.py 6.8 KB

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