__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. '''Qubes' command line tools
  21. '''
  22. from __future__ import print_function
  23. import argparse
  24. import importlib
  25. import logging
  26. import os
  27. import subprocess
  28. import sys
  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 QubesAction(argparse.Action):
  34. ''' Interface providing a convinience method to be called, after
  35. `namespace.app` is instantiated.
  36. '''
  37. # pylint: disable=too-few-public-methods
  38. def parse_qubes_app(self, parser, namespace):
  39. ''' This method is called by :py:class:`qubes.tools.QubesArgumentParser`
  40. after the `namespace.app` is instantiated. Oerwrite this method when
  41. extending :py:class:`qubes.tools.QubesAction` to initialized values
  42. based on the `namespace.app`
  43. '''
  44. raise NotImplementedError
  45. class PropertyAction(argparse.Action):
  46. '''Action for argument parser that stores a property.'''
  47. # pylint: disable=redefined-builtin,too-few-public-methods
  48. def __init__(self,
  49. option_strings,
  50. dest,
  51. metavar='NAME=VALUE',
  52. required=False,
  53. help='set property to a value'):
  54. super(PropertyAction, self).__init__(option_strings, 'properties',
  55. metavar=metavar, default={}, help=help)
  56. def __call__(self, parser, namespace, values, option_string=None):
  57. try:
  58. prop, value = values.split('=', 1)
  59. except ValueError:
  60. parser.error('invalid property token: {!r}'.format(values))
  61. getattr(namespace, self.dest)[prop] = value
  62. class SinglePropertyAction(argparse.Action):
  63. '''Action for argument parser that stores a property.'''
  64. # pylint: disable=redefined-builtin,too-few-public-methods
  65. def __init__(self,
  66. option_strings,
  67. dest,
  68. metavar='VALUE',
  69. const=None,
  70. nargs=None,
  71. required=False,
  72. help=None):
  73. if help is None:
  74. help = 'set {!r} property to a value'.format(dest)
  75. if const is not None:
  76. help += ' {!r}'.format(const)
  77. if const is not None:
  78. nargs = 0
  79. super(SinglePropertyAction, self).__init__(option_strings, 'properties',
  80. metavar=metavar, help=help, default={}, const=const,
  81. nargs=nargs)
  82. self.name = dest
  83. def __call__(self, parser, namespace, values, option_string=None):
  84. getattr(namespace, self.dest)[self.name] = values \
  85. if self.const is None else self.const
  86. class HelpPropertiesAction(argparse.Action):
  87. '''Action for argument parser that displays all properties and exits.'''
  88. # pylint: disable=redefined-builtin,too-few-public-methods
  89. def __init__(self,
  90. option_strings,
  91. klass=None,
  92. dest=argparse.SUPPRESS,
  93. default=argparse.SUPPRESS,
  94. help='list all available properties with short descriptions'
  95. ' and exit'):
  96. super(HelpPropertiesAction, self).__init__(
  97. option_strings=option_strings,
  98. dest=dest,
  99. default=default,
  100. nargs=0,
  101. help=help)
  102. # late import because of circular dependency
  103. import qubes # pylint: disable=redefined-outer-name
  104. self._klass = klass if klass is not None else qubes.Qubes
  105. def __call__(self, parser, namespace, values, option_string=None):
  106. # pylint: disable=redefined-outer-name
  107. properties = self._klass.property_list()
  108. width = max(len(prop.__name__) for prop in properties)
  109. wrapper = textwrap.TextWrapper(width=80,
  110. initial_indent=' ', subsequent_indent=' ' * (width + 6))
  111. text = 'Common properties:\n' + '\n'.join(
  112. wrapper.fill('{name:{width}s} {doc}'.format(
  113. name=prop.__name__,
  114. doc=qubes.utils.format_doc(prop.__doc__) if prop.__doc__ else'',
  115. width=width))
  116. for prop in sorted(properties))
  117. if self._klass is not qubes.Qubes:
  118. text += '\n\n' \
  119. 'There may be more properties in specific domain classes.\n'
  120. parser.exit(message=text)
  121. class VmNameAction(QubesAction):
  122. ''' Action for parsing one ore multiple domains from provided VMNAMEs '''
  123. # pylint: disable=too-few-public-methods,redefined-builtin
  124. def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
  125. **kwargs):
  126. if help is None:
  127. if nargs == argparse.OPTIONAL:
  128. help = 'at most one domain name'
  129. elif nargs == 1:
  130. help = 'a domain name'
  131. elif nargs == argparse.ZERO_OR_MORE:
  132. help = 'zero or more domain names'
  133. elif nargs == argparse.ONE_OR_MORE:
  134. help = 'one or more domain names'
  135. elif nargs > 1:
  136. help = '%s domain names' % nargs
  137. else:
  138. raise argparse.ArgumentError(
  139. nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
  140. nargs, dest))
  141. super(VmNameAction, self).__init__(option_strings, dest=dest, help=help,
  142. nargs=nargs, **kwargs)
  143. def __call__(self, parser, namespace, values, option_string=None):
  144. ''' Set ``namespace.vmname`` to ``values`` '''
  145. setattr(namespace, self.dest, values)
  146. def parse_qubes_app(self, parser, namespace):
  147. assert hasattr(namespace, 'app')
  148. setattr(namespace, 'domains', [])
  149. app = namespace.app
  150. if hasattr(namespace, 'all_domains') and namespace.all_domains:
  151. namespace.domains = [
  152. vm
  153. for vm in app.domains
  154. if vm.qid != 0 and vm.name not in namespace.exclude
  155. ]
  156. else:
  157. if hasattr(namespace, 'exclude') and namespace.exclude:
  158. parser.error('--exclude can only be used with --all')
  159. for vm_name in getattr(namespace, self.dest):
  160. try:
  161. namespace.domains += [app.domains[vm_name]]
  162. except KeyError:
  163. parser.error('no such domain: {!r}'.format(vm_name))
  164. class RunningVmNameAction(VmNameAction):
  165. ''' Action for argument parser that gets a running domain from VMNAME '''
  166. # pylint: disable=too-few-public-methods
  167. def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
  168. **kwargs):
  169. # pylint: disable=redefined-builtin
  170. if help is None:
  171. if nargs == argparse.OPTIONAL:
  172. help = 'at most one running domain'
  173. elif nargs == 1:
  174. help = 'running domain name'
  175. elif nargs == argparse.ZERO_OR_MORE:
  176. help = 'zero or more running domains'
  177. elif nargs == argparse.ONE_OR_MORE:
  178. help = 'one or more running domains'
  179. elif nargs > 1:
  180. help = '%s running domains' % nargs
  181. else:
  182. raise argparse.ArgumentError(
  183. nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
  184. nargs, dest))
  185. super(RunningVmNameAction, self).__init__(
  186. option_strings, dest=dest, help=help, nargs=nargs, **kwargs)
  187. def parse_qubes_app(self, parser, namespace):
  188. super(RunningVmNameAction, self).parse_qubes_app(parser, namespace)
  189. for vm in namespace.domains:
  190. if not vm.is_running():
  191. parser.error_runtime("domain {!r} is not running".format(
  192. vm.name))
  193. class VolumeAction(QubesAction):
  194. ''' Action for argument parser that gets the
  195. :py:class:``qubes.storage.Volume`` from a POOL_NAME:VOLUME_ID string.
  196. '''
  197. # pylint: disable=too-few-public-methods
  198. def __init__(self, help='A pool & volume id combination',
  199. required=True, **kwargs):
  200. # pylint: disable=redefined-builtin
  201. super(VolumeAction, self).__init__(help=help, required=required,
  202. **kwargs)
  203. def __call__(self, parser, namespace, values, option_string=None):
  204. ''' Set ``namespace.vmname`` to ``values`` '''
  205. setattr(namespace, self.dest, values)
  206. def parse_qubes_app(self, parser, namespace):
  207. ''' Acquire the :py:class:``qubes.storage.Volume`` object from
  208. ``namespace.app``.
  209. '''
  210. assert hasattr(namespace, 'app')
  211. app = namespace.app
  212. try:
  213. pool_name, vid = getattr(namespace, self.dest).split(':')
  214. try:
  215. pool = app.pools[pool_name]
  216. volume = [v for v in pool.volumes if v.vid == vid]
  217. assert len(volume) == 1, 'Duplicate vids in pool %s' % pool_name
  218. if not volume:
  219. parser.error_runtime(
  220. 'no volume with id {!r} pool: {!r}'.format(vid,
  221. pool_name))
  222. else:
  223. setattr(namespace, self.dest, volume[0])
  224. except KeyError:
  225. parser.error_runtime('no pool {!r}'.format(pool_name))
  226. except ValueError:
  227. parser.error('expected a pool & volume id combination like foo:bar')
  228. class PoolsAction(QubesAction):
  229. ''' Action for argument parser to gather multiple pools '''
  230. # pylint: disable=too-few-public-methods
  231. def __call__(self, parser, namespace, values, option_string=None):
  232. ''' Set ``namespace.vmname`` to ``values`` '''
  233. if hasattr(namespace, self.dest) and getattr(namespace, self.dest):
  234. names = getattr(namespace, self.dest)
  235. else:
  236. names = []
  237. names += [values]
  238. setattr(namespace, self.dest, names)
  239. def parse_qubes_app(self, parser, namespace):
  240. app = namespace.app
  241. pool_names = getattr(namespace, self.dest)
  242. if pool_names:
  243. try:
  244. pools = [app.get_pool(name) for name in pool_names]
  245. setattr(namespace, self.dest, pools)
  246. except qubes.exc.QubesException as e:
  247. parser.error(str(e))
  248. sys.exit(2)
  249. class QubesArgumentParser(argparse.ArgumentParser):
  250. '''Parser preconfigured for use in most of the Qubes command-line tools.
  251. :param bool want_app: instantiate :py:class:`qubes.Qubes` object
  252. :param bool want_app_no_instance: don't actually instantiate \
  253. :py:class:`qubes.Qubes` object, just add argument for custom xml file
  254. :param bool want_force_root: add ``--force-root`` option
  255. :param mixed vmname_nargs: The number of ``VMNAME`` arguments that should be
  256. consumed. Values include:
  257. - N (an integer) consumes N arguments (and produces a list)
  258. - '?' consumes zero or one arguments
  259. - '*' consumes zero or more arguments (and produces a list)
  260. - '+' consumes one or more arguments (and produces a list)
  261. *kwargs* are passed to :py:class:`argparser.ArgumentParser`.
  262. Currenty supported options:
  263. ``--force-root`` (optional)
  264. ``--qubesxml`` location of :file:`qubes.xml` (help is suppressed)
  265. ``--offline-mode`` do not talk to hypervisor (help is suppressed)
  266. ``--verbose`` and ``--quiet``
  267. '''
  268. def __init__(self, want_app=True, want_app_no_instance=False,
  269. want_force_root=False, vmname_nargs=None, **kwargs):
  270. super(QubesArgumentParser, self).__init__(**kwargs)
  271. self._want_app = want_app
  272. self._want_app_no_instance = want_app_no_instance
  273. self._want_force_root = want_force_root
  274. self._vmname_nargs = vmname_nargs
  275. if self._want_app:
  276. self.add_argument('--qubesxml', metavar='FILE', action='store',
  277. dest='app', help=argparse.SUPPRESS)
  278. self.add_argument('--offline-mode', action='store_true',
  279. default=None, dest='offline_mode', help=argparse.SUPPRESS)
  280. self.add_argument('--verbose', '-v', action='count',
  281. help='increase verbosity')
  282. self.add_argument('--quiet', '-q', action='count',
  283. help='decrease verbosity')
  284. if self._want_force_root:
  285. self.add_argument('--force-root', action='store_true',
  286. default=False, help='force to run as root')
  287. if self._vmname_nargs in [argparse.ZERO_OR_MORE, argparse.ONE_OR_MORE]:
  288. vm_name_group = VmNameGroup(self, self._vmname_nargs)
  289. self._mutually_exclusive_groups.append(vm_name_group)
  290. elif self._vmname_nargs is not None:
  291. self.add_argument('VMNAME', nargs=self._vmname_nargs,
  292. action=VmNameAction)
  293. self.set_defaults(verbose=1, quiet=0)
  294. def parse_args(self, args=None, namespace=None):
  295. namespace = super(QubesArgumentParser, self).parse_args(args, namespace)
  296. if self._want_app and not self._want_app_no_instance:
  297. self.set_qubes_verbosity(namespace)
  298. namespace.app = qubes.Qubes(namespace.app,
  299. offline_mode=namespace.offline_mode)
  300. if self._want_force_root:
  301. self.dont_run_as_root(namespace)
  302. for action in self._actions:
  303. # pylint: disable=protected-access
  304. if issubclass(action.__class__, QubesAction):
  305. action.parse_qubes_app(self, namespace)
  306. elif issubclass(action.__class__,
  307. argparse._SubParsersAction): # pylint: disable=no-member
  308. assert hasattr(namespace, 'command')
  309. command = namespace.command
  310. subparser = action._name_parser_map[command]
  311. for subaction in subparser._actions:
  312. if issubclass(subaction.__class__, QubesAction):
  313. subaction.parse_qubes_app(self, namespace)
  314. return namespace
  315. def error_runtime(self, message):
  316. '''Runtime error, without showing usage.
  317. :param str message: message to show
  318. '''
  319. self.exit(1, '{}: error: {}\n'.format(self.prog, message))
  320. def dont_run_as_root(self, namespace):
  321. '''Prevent running as root.
  322. :param argparse.Namespace args: if there is ``.force_root`` attribute \
  323. set to true, run anyway
  324. '''
  325. try:
  326. euid = os.geteuid()
  327. except AttributeError: # no geteuid(), probably NT
  328. return
  329. if euid == 0 and not namespace.force_root:
  330. self.error_runtime(
  331. 'refusing to run as root; add --force-root to override')
  332. @staticmethod
  333. def get_loglevel_from_verbosity(namespace):
  334. ''' Return loglevel calculated from quiet and verbose arguments '''
  335. return (namespace.quiet - namespace.verbose) * 10 + logging.WARNING
  336. @staticmethod
  337. def set_qubes_verbosity(namespace):
  338. '''Apply a verbosity setting.
  339. This is done by configuring global logging.
  340. :param argparse.Namespace args: args as parsed by parser
  341. '''
  342. verbose = namespace.verbose - namespace.quiet
  343. if verbose >= 2:
  344. qubes.log.enable_debug()
  345. elif verbose >= 1:
  346. qubes.log.enable()
  347. # pylint: disable=no-self-use
  348. def print_error(self, *args, **kwargs):
  349. ''' Print to ``sys.stderr``'''
  350. print(*args, file=sys.stderr, **kwargs)
  351. class AliasedSubParsersAction(argparse._SubParsersAction):
  352. # source https://gist.github.com/sampsyo/471779
  353. # pylint: disable=protected-access,too-few-public-methods
  354. class _AliasedPseudoAction(argparse.Action):
  355. # pylint: disable=redefined-builtin,arguments-differ
  356. def __init__(self, name, aliases, help):
  357. dest = name
  358. if aliases:
  359. dest += ' (%s)' % ','.join(aliases)
  360. sup = super(AliasedSubParsersAction._AliasedPseudoAction, self)
  361. sup.__init__(option_strings=[], dest=dest, help=help)
  362. def __call__(self, parser, namespace, values, option_string=None):
  363. raise NotImplementedError
  364. def add_parser(self, name, **kwargs):
  365. if 'aliases' in kwargs:
  366. aliases = kwargs['aliases']
  367. del kwargs['aliases']
  368. else:
  369. aliases = []
  370. local_parser = super(AliasedSubParsersAction, self).add_parser(
  371. name, **kwargs)
  372. # Make the aliases work.
  373. for alias in aliases:
  374. self._name_parser_map[alias] = local_parser
  375. # Make the help text reflect them, first removing old help entry.
  376. if 'help' in kwargs:
  377. self._choices_actions.pop()
  378. pseudo_action = self._AliasedPseudoAction(name, aliases,
  379. kwargs.pop('help'))
  380. self._choices_actions.append(pseudo_action)
  381. return local_parser
  382. def get_parser_for_command(command):
  383. '''Get parser for given qvm-tool.
  384. :param str command: command name
  385. :rtype: argparse.ArgumentParser
  386. :raises ImportError: when command's module is not found
  387. :raises AttributeError: when parser was not found
  388. '''
  389. module = importlib.import_module(
  390. '.' + command.replace('-', '_'), 'qubes.tools')
  391. try:
  392. parser = module.parser
  393. except AttributeError:
  394. try:
  395. parser = module.get_parser()
  396. except AttributeError:
  397. raise AttributeError('cannot find parser in module')
  398. return parser
  399. # pylint: disable=protected-access
  400. class VmNameGroup(argparse._MutuallyExclusiveGroup):
  401. ''' Adds an a VMNAME, --all & --exclude parameters to a
  402. :py:class:``argparse.ArgumentParser```.
  403. '''
  404. def __init__(self, container, required, vm_action=VmNameAction, help=None):
  405. # pylint: disable=redefined-builtin
  406. super(VmNameGroup, self).__init__(container, required=required)
  407. if not help:
  408. help = 'perform the action on all qubes'
  409. self.add_argument('--all', action='store_true', dest='all_domains',
  410. help=help)
  411. container.add_argument('--exclude', action='append', default=[],
  412. help='exclude the qube from --all')
  413. # ⚠ the default parameter below is important! ⚠
  414. # See https://stackoverflow.com/questions/35044288 and
  415. # `argparse.ArgumentParser.parse_args()` implementation
  416. self.add_argument('VMNAME', action=vm_action, nargs='*', default=[])
  417. def print_table(table):
  418. ''' Uses the unix column command to print pretty table.
  419. :param str text: list of lists/sets
  420. '''
  421. unit_separator = chr(31)
  422. cmd = ['column', '-t', '-s', unit_separator]
  423. text_table = '\n'.join([unit_separator.join(row) for row in table])
  424. text_table += '\n'
  425. # for tests...
  426. if sys.stdout != sys.__stdout__:
  427. p = subprocess.Popen(cmd + ['-c', '80'], stdin=subprocess.PIPE,
  428. stdout=subprocess.PIPE)
  429. p.stdin.write(text_table.encode())
  430. (out, _) = p.communicate()
  431. sys.stdout.write(out.decode())
  432. else:
  433. p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  434. p.communicate(text_table.encode())