__init__.py 10 KB

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