utils.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 functools
  23. import os
  24. import re
  25. import qubesadmin
  26. from PyQt4.QtGui import QIcon
  27. def _filter_internal(vm):
  28. return (not isinstance(vm, qubesadmin.vm.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):
  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 allow_internal is None:
  47. allow_internal = propname is None or not propname.endswith('vm')
  48. if propname is not None:
  49. oldvalue = getattr(holder, propname)
  50. is_default = holder.property_is_default(propname)
  51. else:
  52. oldvalue = object() # won't match for identity
  53. is_default = False
  54. idx = 0
  55. choice_list = list(choice)[:]
  56. if not allow_internal:
  57. choice_list = filter(_filter_internal, choice_list)
  58. if filter_function is not None:
  59. choice_list = filter(filter_function, choice_list)
  60. choice_list = list(choice_list)
  61. if allow_default:
  62. choice_list.insert(0, qubesadmin.DEFAULT)
  63. if allow_none:
  64. choice_list.append(None)
  65. for i, item in enumerate(choice_list):
  66. debug('i={} item={}'.format(i, item))
  67. # 0: default (unset)
  68. if item is qubesadmin.DEFAULT:
  69. text = 'default ({})'.format(
  70. str(default) if default is not None else 'none')
  71. # N+1: explicit None
  72. elif item is None:
  73. text = 'none'
  74. # 1..N: choices
  75. else:
  76. text = str(item)
  77. if item is qubesadmin.DEFAULT and is_default \
  78. or item is not qubesadmin.DEFAULT and item is oldvalue:
  79. text += ' (current)'
  80. idx = i
  81. widget.insertItem(i, text)
  82. if icon_getter is not None:
  83. icon = icon_getter(item)
  84. if icon is not None:
  85. widget.setItemIcon(i, icon)
  86. widget.setCurrentIndex(idx)
  87. return choice_list, idx
  88. def prepare_kernel_choice(widget, holder, propname, default, *args, **kwargs):
  89. # TODO get from storage API (pool 'linux-kernel') (suggested by @marmarta)
  90. return prepare_choice(widget, holder, propname,
  91. os.listdir('/var/lib/qubes/vm-kernels'), default, *args, **kwargs)
  92. def prepare_label_choice(widget, holder, propname, default, *args, **kwargs):
  93. try:
  94. app = holder.app
  95. except AttributeError:
  96. app = holder
  97. return prepare_choice(widget, holder, propname,
  98. sorted(app.labels, key=lambda l: l.index),
  99. default, *args,
  100. icon_getter=(lambda label: QIcon.fromTheme(label.icon)),
  101. **kwargs)
  102. def prepare_vm_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, app.domains, default,
  108. *args, **kwargs)
  109. def is_debug():
  110. return os.getenv('QUBES_MANAGER_DEBUG', '') not in ('', '0')
  111. def debug(*args, **kwargs):
  112. if not is_debug():
  113. return
  114. print(*args, **kwargs)
  115. def get_path_from_vm(vm, service_name):
  116. """
  117. Displays a file/directory selection window for the given VM.
  118. :param vm: vm from which to select path
  119. :param service_name: qubes.SelectFile or qubes.SelectDirectory
  120. :return: path to file, checked for validity
  121. """
  122. path_re = re.compile(r"[a-zA-Z0-9/:.,_+=() -]*")
  123. path_max_len = 512
  124. if not vm:
  125. return None
  126. stdout, stderr = vm.run_service_for_stdio(service_name)
  127. untrusted_path = stdout.decode(encoding='ascii')[:path_max_len]
  128. if len(untrusted_path) == 0:
  129. return None
  130. if path_re.match(untrusted_path):
  131. assert '../' not in untrusted_path
  132. assert '\0' not in untrusted_path
  133. return untrusted_path.strip()
  134. else:
  135. raise ValueError('Unexpected characters in path.')