__init__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. class PropertyAction(argparse.Action):
  31. '''Action for argument parser that stores a property.'''
  32. # pylint: disable=redefined-builtin,too-few-public-methods
  33. def __init__(self,
  34. option_strings,
  35. dest,
  36. metavar='NAME=VALUE',
  37. required=False,
  38. help='set property to a value'):
  39. super(PropertyAction, self).__init__(option_strings, 'properties',
  40. metavar=metavar, default={}, help=help)
  41. def __call__(self, parser, namespace, values, option_string=None):
  42. try:
  43. prop, value = values.split('=', 1)
  44. except ValueError:
  45. parser.error('invalid property token: {!r}'.format(values))
  46. getattr(namespace, self.dest)[prop] = value
  47. class SinglePropertyAction(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='VALUE',
  54. const=None,
  55. nargs=None,
  56. required=False,
  57. help=None):
  58. if help is None:
  59. help = 'set {!r} property to a value'.format(dest)
  60. if const is not None:
  61. help += ' {!r}'.format(const)
  62. if const is not None:
  63. nargs = 0
  64. super(SinglePropertyAction, self).__init__(option_strings, 'properties',
  65. metavar=metavar, help=help, default={}, const=const,
  66. nargs=nargs)
  67. self.name = dest
  68. def __call__(self, parser, namespace, values, option_string=None):
  69. getattr(namespace, self.dest)[self.name] = values \
  70. if self.const is None else self.const
  71. class QubesArgumentParser(argparse.ArgumentParser):
  72. '''Parser preconfigured for use in most of the Qubes command-line tools.
  73. :param bool want_app: instantiate :py:class:`qubes.Qubes` object
  74. :param bool want_app_no_instance: don't actually instantiate \
  75. :py:class:`qubes.Qubes` object, just add argument for custom xml file
  76. :param bool want_force_root: add ``--force-root`` option
  77. :param bool want_vm: add ``VMNAME`` as first positional argument
  78. *kwargs* are passed to :py:class:`argparser.ArgumentParser`.
  79. Currenty supported options:
  80. ``--force-root`` (optional)
  81. ``--qubesxml`` location of :file:`qubes.xml` (help is suppressed)
  82. ``--verbose`` and ``--quiet``
  83. '''
  84. def __init__(self,
  85. want_app=True,
  86. want_app_no_instance=False,
  87. want_force_root=False,
  88. want_vm=False,
  89. **kwargs):
  90. super(QubesArgumentParser, self).__init__(**kwargs)
  91. self._want_app = want_app
  92. self._want_app_no_instance = want_app_no_instance
  93. self._want_force_root = want_force_root
  94. self._want_vm = want_vm
  95. if self._want_app:
  96. self.add_argument('--qubesxml', metavar='FILE',
  97. action='store', dest='app',
  98. help=argparse.SUPPRESS)
  99. self.add_argument('--verbose', '-v',
  100. action='count',
  101. help='increase verbosity')
  102. self.add_argument('--quiet', '-q',
  103. action='count',
  104. help='decrease verbosity')
  105. if self._want_force_root:
  106. self.add_argument('--force-root',
  107. action='store_true', default=False,
  108. help='force to run as root')
  109. if self._want_vm:
  110. self.add_argument('vm', metavar='VMNAME',
  111. action='store',
  112. help='name of the domain')
  113. self.set_defaults(verbose=1, quiet=0)
  114. def parse_args(self, *args, **kwargs):
  115. namespace = super(QubesArgumentParser, self).parse_args(*args, **kwargs)
  116. if self._want_app and not self._want_app_no_instance:
  117. self.set_qubes_verbosity(namespace)
  118. namespace.app = qubes.Qubes(namespace.app)
  119. if self._want_vm:
  120. try:
  121. namespace.vm = namespace.app.domains[namespace.vm]
  122. except KeyError:
  123. self.error('no such domain: {!r}'.format(namespace.vm))
  124. if self._want_force_root:
  125. self.dont_run_as_root(namespace)
  126. return namespace
  127. def error_runtime(self, message):
  128. '''Runtime error, without showing usage.
  129. :param str message: message to show
  130. '''
  131. self.exit(1, '{}: error: {}\n'.format(self.prog, message))
  132. def dont_run_as_root(self, namespace):
  133. '''Prevent running as root.
  134. :param argparse.Namespace args: if there is ``.force_root`` attribute \
  135. set to true, run anyway
  136. '''
  137. try:
  138. euid = os.geteuid()
  139. except AttributeError: # no geteuid(), probably NT
  140. return
  141. if euid == 0 and not namespace.force_root:
  142. self.error_runtime(
  143. 'refusing to run as root; add --force-root to override')
  144. @staticmethod
  145. def get_loglevel_from_verbosity(namespace):
  146. return (namespace.quiet - namespace.verbose) * 10 + logging.WARNING
  147. @staticmethod
  148. def set_qubes_verbosity(namespace):
  149. '''Apply a verbosity setting.
  150. This is done by configuring global logging.
  151. :param argparse.Namespace args: args as parsed by parser
  152. '''
  153. verbose = namespace.verbose - namespace.quiet
  154. if verbose >= 2:
  155. qubes.log.enable_debug()
  156. elif verbose >= 1:
  157. qubes.log.enable()
  158. def get_parser_for_command(command):
  159. '''Get parser for given qvm-tool.
  160. :param str command: command name
  161. :rtype: argparse.ArgumentParser
  162. :raises ImportError: when command's module is not found
  163. :raises AttributeError: when parser was not found
  164. '''
  165. module = importlib.import_module(
  166. '.' + command.replace('-', '_'), 'qubes.tools')
  167. try:
  168. parser = module.parser
  169. except AttributeError:
  170. try:
  171. parser = module.get_parser()
  172. except AttributeError:
  173. raise AttributeError('cannot find parser in module')
  174. return parser