__init__.py 10 KB

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