__init__.py 11 KB

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