__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2015 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 along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''Qubes' command line tools
  24. '''
  25. from __future__ import print_function
  26. import argparse
  27. import importlib
  28. import logging
  29. import os
  30. import sys
  31. import textwrap
  32. import qubes.log
  33. #: constant returned when some action should be performed on all qubes
  34. VM_ALL = object()
  35. class PropertyAction(argparse.Action):
  36. '''Action for argument parser that stores a property.'''
  37. # pylint: disable=redefined-builtin,too-few-public-methods
  38. def __init__(self,
  39. option_strings,
  40. dest,
  41. metavar='NAME=VALUE',
  42. required=False,
  43. help='set property to a value'):
  44. super(PropertyAction, self).__init__(option_strings, 'properties',
  45. metavar=metavar, default={}, help=help)
  46. def __call__(self, parser, namespace, values, option_string=None):
  47. try:
  48. prop, value = values.split('=', 1)
  49. except ValueError:
  50. parser.error('invalid property token: {!r}'.format(values))
  51. getattr(namespace, self.dest)[prop] = value
  52. class SinglePropertyAction(argparse.Action):
  53. '''Action for argument parser that stores a property.'''
  54. # pylint: disable=redefined-builtin,too-few-public-methods
  55. def __init__(self,
  56. option_strings,
  57. dest,
  58. metavar='VALUE',
  59. const=None,
  60. nargs=None,
  61. required=False,
  62. help=None):
  63. if help is None:
  64. help = 'set {!r} property to a value'.format(dest)
  65. if const is not None:
  66. help += ' {!r}'.format(const)
  67. if const is not None:
  68. nargs = 0
  69. super(SinglePropertyAction, self).__init__(option_strings, 'properties',
  70. metavar=metavar, help=help, default={}, const=const,
  71. nargs=nargs)
  72. self.name = dest
  73. def __call__(self, parser, namespace, values, option_string=None):
  74. getattr(namespace, self.dest)[self.name] = values \
  75. if self.const is None else self.const
  76. class HelpPropertiesAction(argparse.Action):
  77. '''Action for argument parser that displays all properties and exits.'''
  78. # pylint: disable=redefined-builtin,too-few-public-methods
  79. def __init__(self,
  80. option_strings,
  81. klass=None,
  82. dest=argparse.SUPPRESS,
  83. default=argparse.SUPPRESS,
  84. help='list all available properties with short descriptions'
  85. ' and exit'):
  86. super(HelpPropertiesAction, self).__init__(
  87. option_strings=option_strings,
  88. dest=dest,
  89. default=default,
  90. nargs=0,
  91. help=help)
  92. # late import because of circular dependency
  93. import qubes # pylint: disable=redefined-outer-name
  94. self._klass = klass if klass is not None else qubes.Qubes
  95. def __call__(self, parser, namespace, values, option_string=None):
  96. # pylint: disable=redefined-outer-name
  97. properties = self._klass.property_list()
  98. width = max(len(prop.__name__) for prop in properties)
  99. wrapper = textwrap.TextWrapper(width=80,
  100. initial_indent=' ', subsequent_indent=' ' * (width + 6))
  101. text = 'Common properties:\n' + '\n'.join(
  102. wrapper.fill('{name:{width}s} {doc}'.format(
  103. name=prop.__name__,
  104. doc=qubes.utils.format_doc(prop.__doc__) if prop.__doc__ else'',
  105. width=width))
  106. for prop in sorted(properties))
  107. if self._klass is not qubes.Qubes:
  108. text += '\n\n' \
  109. 'There may be more properties in specific domain classes.\n'
  110. parser.exit(message=text)
  111. class QubesArgumentParser(argparse.ArgumentParser):
  112. '''Parser preconfigured for use in most of the Qubes command-line tools.
  113. :param bool want_app: instantiate :py:class:`qubes.Qubes` object
  114. :param bool want_app_no_instance: don't actually instantiate \
  115. :py:class:`qubes.Qubes` object, just add argument for custom xml file
  116. :param bool want_force_root: add ``--force-root`` option
  117. :param bool want_vm: add ``VMNAME`` as first positional argument
  118. *kwargs* are passed to :py:class:`argparser.ArgumentParser`.
  119. Currenty supported options:
  120. ``--force-root`` (optional)
  121. ``--qubesxml`` location of :file:`qubes.xml` (help is suppressed)
  122. ``--verbose`` and ``--quiet``
  123. '''
  124. def __init__(self,
  125. want_app=True,
  126. want_app_no_instance=False,
  127. want_force_root=False,
  128. want_vm=False,
  129. want_vm_optional=False,
  130. want_vm_all=False,
  131. **kwargs):
  132. super(QubesArgumentParser, self).__init__(**kwargs)
  133. self._want_app = want_app
  134. self._want_app_no_instance = want_app_no_instance
  135. self._want_force_root = want_force_root
  136. self._want_vm = want_vm
  137. self._want_vm_optional = want_vm_optional
  138. self._want_vm_all = want_vm_all
  139. if self._want_app:
  140. self.add_argument('--qubesxml', metavar='FILE',
  141. action='store', dest='app',
  142. help=argparse.SUPPRESS)
  143. self.add_argument('--verbose', '-v',
  144. action='count',
  145. help='increase verbosity')
  146. self.add_argument('--quiet', '-q',
  147. action='count',
  148. help='decrease verbosity')
  149. if self._want_force_root:
  150. self.add_argument('--force-root',
  151. action='store_true', default=False,
  152. help='force to run as root')
  153. if self._want_vm:
  154. if self._want_vm_all:
  155. vmchoice = self.add_mutually_exclusive_group()
  156. vmchoice.add_argument('--all',
  157. action='store_const', const=VM_ALL, dest='vm',
  158. help='perform the action on all qubes')
  159. self.add_argument('--exclude',
  160. action='append', default=[],
  161. help='exclude the qube from --all')
  162. nargs = '?'
  163. else:
  164. vmchoice = self
  165. nargs = '?' if self._want_vm_optional else None
  166. vmchoice.add_argument('vm', metavar='VMNAME',
  167. action='store', nargs=nargs,
  168. help='name of the domain')
  169. self.set_defaults(verbose=1, quiet=0)
  170. def parse_args(self, *args, **kwargs):
  171. namespace = super(QubesArgumentParser, self).parse_args(*args, **kwargs)
  172. if self._want_app and not self._want_app_no_instance:
  173. self.set_qubes_verbosity(namespace)
  174. namespace.app = qubes.Qubes(namespace.app)
  175. if self._want_vm:
  176. if self._want_vm_all:
  177. if namespace.vm is VM_ALL:
  178. namespace.vm = [vm for vm in namespace.app.domains
  179. if vm.qid != 0 and vm.name not in namespace.exclude]
  180. else:
  181. if namespace.exclude:
  182. self.error('--exclude can only be used with --all')
  183. try:
  184. namespace.vm = \
  185. (namespace.app.domains[namespace.vm],)
  186. except KeyError:
  187. self.error(
  188. 'no such domain: {!r}'.format(namespace.vm))
  189. else:
  190. try:
  191. namespace.vm = namespace.app.domains[namespace.vm]
  192. except KeyError:
  193. self.error('no such domain: {!r}'.format(namespace.vm))
  194. if self._want_force_root:
  195. self.dont_run_as_root(namespace)
  196. return namespace
  197. def error_runtime(self, message):
  198. '''Runtime error, without showing usage.
  199. :param str message: message to show
  200. '''
  201. self.exit(1, '{}: error: {}\n'.format(self.prog, message))
  202. def dont_run_as_root(self, namespace):
  203. '''Prevent running as root.
  204. :param argparse.Namespace args: if there is ``.force_root`` attribute \
  205. set to true, run anyway
  206. '''
  207. try:
  208. euid = os.geteuid()
  209. except AttributeError: # no geteuid(), probably NT
  210. return
  211. if euid == 0 and not namespace.force_root:
  212. self.error_runtime(
  213. 'refusing to run as root; add --force-root to override')
  214. @staticmethod
  215. def get_loglevel_from_verbosity(namespace):
  216. return (namespace.quiet - namespace.verbose) * 10 + logging.WARNING
  217. @staticmethod
  218. def set_qubes_verbosity(namespace):
  219. '''Apply a verbosity setting.
  220. This is done by configuring global logging.
  221. :param argparse.Namespace args: args as parsed by parser
  222. '''
  223. verbose = namespace.verbose - namespace.quiet
  224. if verbose >= 2:
  225. qubes.log.enable_debug()
  226. elif verbose >= 1:
  227. qubes.log.enable()
  228. # pylint: disable=no-self-use
  229. def print_error(self, *args, **kwargs):
  230. ''' Print to ``sys.stderr``'''
  231. print(*args, file=sys.stderr, **kwargs)
  232. def get_parser_for_command(command):
  233. '''Get parser for given qvm-tool.
  234. :param str command: command name
  235. :rtype: argparse.ArgumentParser
  236. :raises ImportError: when command's module is not found
  237. :raises AttributeError: when parser was not found
  238. '''
  239. module = importlib.import_module(
  240. '.' + command.replace('-', '_'), 'qubes.tools')
  241. try:
  242. parser = module.parser
  243. except AttributeError:
  244. try:
  245. parser = module.get_parser()
  246. except AttributeError:
  247. raise AttributeError('cannot find parser in module')
  248. return parser