2017-04-30 15:20:35 +02:00
|
|
|
# encoding=utf-8
|
|
|
|
|
|
|
|
#
|
|
|
|
# The Qubes OS Project, http://www.qubes-os.org
|
|
|
|
#
|
|
|
|
# Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
|
|
|
|
# Copyright (C) 2016 Marek Marczykowski-Górecki
|
|
|
|
# <marmarek@invisiblethingslab.com>
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2.1 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU Lesser General Public License along
|
|
|
|
# with this program; if not, write to the Free Software Foundation, Inc.,
|
|
|
|
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
|
|
|
2019-08-06 14:43:25 +02:00
|
|
|
"""Qubes volume and block device managment"""
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
import argparse
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
2017-05-11 23:21:04 +02:00
|
|
|
import qubesadmin
|
|
|
|
import qubesadmin.exc
|
|
|
|
import qubesadmin.tools
|
|
|
|
import qubesadmin.devices
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
def prepare_table(dev_list):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Converts a list of :py:class:`qubes.devices.DeviceInfo` objects to a
|
2017-04-30 15:20:35 +02:00
|
|
|
list of tupples for the :py:func:`qubes.tools.print_table`.
|
|
|
|
|
2018-12-08 23:53:55 +01:00
|
|
|
If :program:`qvm-devices` is running in a TTY, it will ommit duplicate
|
|
|
|
data.
|
2017-04-30 15:20:35 +02:00
|
|
|
|
2018-12-08 23:53:55 +01:00
|
|
|
:param iterable dev_list: List of :py:class:`qubes.devices.DeviceInfo`
|
2017-04-30 15:20:35 +02:00
|
|
|
objects.
|
2018-12-08 23:53:55 +01:00
|
|
|
:returns: list of tupples
|
2019-08-06 14:43:25 +02:00
|
|
|
"""
|
2017-04-30 15:20:35 +02:00
|
|
|
output = []
|
|
|
|
header = []
|
|
|
|
if sys.stdout.isatty():
|
|
|
|
header += [('BACKEND:DEVID', 'DESCRIPTION', 'USED BY')] # NOQA
|
|
|
|
|
|
|
|
for line in dev_list:
|
|
|
|
output += [(
|
|
|
|
line.ident,
|
|
|
|
line.description,
|
|
|
|
str(line.assignments),
|
|
|
|
)]
|
|
|
|
|
|
|
|
return header + sorted(output)
|
|
|
|
|
|
|
|
|
|
|
|
class Line(object):
|
2019-08-06 14:43:25 +02:00
|
|
|
"""Helper class to hold single device info for listing"""
|
|
|
|
|
2017-04-30 15:20:35 +02:00
|
|
|
# pylint: disable=too-few-public-methods
|
2017-05-11 23:21:04 +02:00
|
|
|
def __init__(self, device: qubesadmin.devices.DeviceInfo, attached_to=None):
|
2017-04-30 15:20:35 +02:00
|
|
|
self.ident = "{!s}:{!s}".format(device.backend_domain, device.ident)
|
|
|
|
self.description = device.description
|
|
|
|
self.attached_to = attached_to if attached_to else ""
|
|
|
|
self.frontends = []
|
|
|
|
|
|
|
|
@property
|
|
|
|
def assignments(self):
|
2019-08-06 14:43:25 +02:00
|
|
|
"""list of frontends the device is assigned to"""
|
2017-04-30 15:20:35 +02:00
|
|
|
return ', '.join(self.frontends)
|
|
|
|
|
|
|
|
|
|
|
|
def list_devices(args):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Called by the parser to execute the qubes-devices list
|
|
|
|
subcommand. """
|
2017-04-30 15:20:35 +02:00
|
|
|
app = args.app
|
|
|
|
|
|
|
|
devices = set()
|
2020-09-16 13:34:56 +02:00
|
|
|
try:
|
|
|
|
if hasattr(args, 'domains') and args.domains:
|
|
|
|
for domain in args.domains:
|
|
|
|
for dev in domain.devices[args.devclass].attached():
|
|
|
|
devices.add(dev)
|
|
|
|
for dev in domain.devices[args.devclass].available():
|
|
|
|
devices.add(dev)
|
|
|
|
|
|
|
|
else:
|
|
|
|
for domain in app.domains:
|
2021-04-09 18:19:39 +02:00
|
|
|
try:
|
|
|
|
for dev in domain.devices[args.devclass].available():
|
|
|
|
devices.add(dev)
|
|
|
|
except qubesadmin.exc.QubesVMNotFoundError:
|
|
|
|
continue
|
2020-09-16 13:34:56 +02:00
|
|
|
except qubesadmin.exc.QubesDaemonAccessError:
|
|
|
|
raise qubesadmin.exc.QubesException(
|
|
|
|
"Failed to list '%s' devices, this device type either "
|
|
|
|
"does not exist or you do not have access to it.", args.devclass)
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
result = {dev: Line(dev) for dev in devices}
|
|
|
|
|
|
|
|
for dev in result:
|
|
|
|
for domain in app.domains:
|
|
|
|
if domain == dev.backend_domain:
|
|
|
|
continue
|
|
|
|
|
2021-04-09 18:19:39 +02:00
|
|
|
try:
|
|
|
|
for assignment in domain.devices[args.devclass].assignments():
|
|
|
|
if dev != assignment:
|
|
|
|
continue
|
|
|
|
if assignment.options:
|
|
|
|
result[dev].frontends.append('{!s} ({})'.format(
|
|
|
|
domain, ', '.join('{}={}'.format(key, value)
|
|
|
|
for key, value in
|
|
|
|
assignment.options.items())))
|
|
|
|
else:
|
|
|
|
result[dev].frontends.append(str(domain))
|
|
|
|
except qubesadmin.exc.QubesVMNotFoundError:
|
|
|
|
continue
|
2017-04-30 15:20:35 +02:00
|
|
|
|
2017-05-11 23:21:04 +02:00
|
|
|
qubesadmin.tools.print_table(prepare_table(result.values()))
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
def attach_device(args):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Called by the parser to execute the :program:`qvm-devices attach`
|
2017-04-30 15:20:35 +02:00
|
|
|
subcommand.
|
2019-08-06 14:43:25 +02:00
|
|
|
"""
|
2017-04-30 15:20:35 +02:00
|
|
|
device_assignment = args.device_assignment
|
|
|
|
vm = args.domains[0]
|
|
|
|
options = dict(opt.split('=', 1) for opt in args.option or [])
|
2018-01-10 20:30:30 +01:00
|
|
|
if args.ro:
|
|
|
|
options['read-only'] = 'yes'
|
2017-04-30 15:20:35 +02:00
|
|
|
device_assignment.persistent = args.persistent
|
|
|
|
device_assignment.options = options
|
|
|
|
vm.devices[args.devclass].attach(device_assignment)
|
|
|
|
|
|
|
|
|
|
|
|
def detach_device(args):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Called by the parser to execute the :program:`qvm-devices detach`
|
2017-04-30 15:20:35 +02:00
|
|
|
subcommand.
|
2019-08-06 14:43:25 +02:00
|
|
|
"""
|
2017-04-30 15:20:35 +02:00
|
|
|
vm = args.domains[0]
|
2018-12-07 21:50:55 +01:00
|
|
|
if args.device_assignment:
|
|
|
|
vm.devices[args.devclass].detach(args.device_assignment)
|
|
|
|
else:
|
|
|
|
for device_assignment in vm.devices[args.devclass].assignments():
|
|
|
|
vm.devices[args.devclass].detach(device_assignment)
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
def init_list_parser(sub_parsers):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Configures the parser for the :program:`qvm-devices list` subcommand """
|
2017-04-30 15:20:35 +02:00
|
|
|
# pylint: disable=protected-access
|
|
|
|
list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
|
|
|
|
help='list devices')
|
|
|
|
|
2017-05-11 23:21:04 +02:00
|
|
|
vm_name_group = qubesadmin.tools.VmNameGroup(
|
|
|
|
list_parser, required=False, vm_action=qubesadmin.tools.VmNameAction,
|
2017-04-30 15:20:35 +02:00
|
|
|
help='list devices assigned to specific domain(s)')
|
|
|
|
list_parser._mutually_exclusive_groups.append(vm_name_group)
|
|
|
|
list_parser.set_defaults(func=list_devices)
|
|
|
|
|
|
|
|
|
2017-05-11 23:21:04 +02:00
|
|
|
class DeviceAction(qubesadmin.tools.QubesAction):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Action for argument parser that gets the
|
2017-05-11 23:21:04 +02:00
|
|
|
:py:class:``qubesadmin.device.DeviceAssignment`` from a
|
2017-04-30 15:20:35 +02:00
|
|
|
BACKEND:DEVICE_ID string.
|
2019-08-06 14:43:25 +02:00
|
|
|
""" # pylint: disable=too-few-public-methods
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
def __init__(self, help='A backend & device id combination',
|
|
|
|
required=True, allow_unknown=False, **kwargs):
|
|
|
|
# pylint: disable=redefined-builtin
|
|
|
|
self.allow_unknown = allow_unknown
|
2020-08-23 03:31:39 +02:00
|
|
|
super().__init__(help=help, required=required,
|
2017-04-30 15:20:35 +02:00
|
|
|
**kwargs)
|
|
|
|
|
|
|
|
def __call__(self, parser, namespace, values, option_string=None):
|
2019-08-06 14:43:25 +02:00
|
|
|
""" Set ``namespace.device_assignment`` to ``values`` """
|
2017-04-30 15:20:35 +02:00
|
|
|
setattr(namespace, self.dest, values)
|
|
|
|
|
|
|
|
def parse_qubes_app(self, parser, namespace):
|
|
|
|
app = namespace.app
|
|
|
|
backend_device_id = getattr(namespace, self.dest)
|
|
|
|
devclass = namespace.devclass
|
2018-12-07 21:50:55 +01:00
|
|
|
if backend_device_id is None:
|
|
|
|
return
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
vmname, device_id = backend_device_id.split(':', 1)
|
2019-08-06 14:43:25 +02:00
|
|
|
vm = None
|
2017-04-30 15:20:35 +02:00
|
|
|
try:
|
|
|
|
vm = app.domains[vmname]
|
|
|
|
except KeyError:
|
|
|
|
parser.error_runtime("no backend vm {!r}".format(vmname))
|
|
|
|
|
|
|
|
try:
|
|
|
|
dev = vm.devices[devclass][device_id]
|
2019-08-06 14:43:25 +02:00
|
|
|
if not self.allow_unknown and \
|
|
|
|
isinstance(dev, qubesadmin.devices.UnknownDevice):
|
2017-04-30 15:20:35 +02:00
|
|
|
raise KeyError(device_id)
|
|
|
|
except KeyError:
|
|
|
|
parser.error_runtime(
|
2019-08-06 14:43:25 +02:00
|
|
|
"backend vm {!r} doesn't expose device {!r}".format(
|
|
|
|
vmname, device_id))
|
|
|
|
device_assignment = qubesadmin.devices.DeviceAssignment(
|
|
|
|
vm, device_id)
|
2017-04-30 15:20:35 +02:00
|
|
|
setattr(namespace, self.dest, device_assignment)
|
|
|
|
except ValueError:
|
2019-08-06 14:43:25 +02:00
|
|
|
parser.error(
|
|
|
|
'expected a backend vm & device id combination like foo:bar '
|
|
|
|
'got %s' % backend_device_id)
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
|
|
|
|
def get_parser(device_class=None):
|
2019-08-06 14:43:25 +02:00
|
|
|
"""Create :py:class:`argparse.ArgumentParser` suitable for
|
2017-04-30 15:20:35 +02:00
|
|
|
:program:`qvm-block`.
|
2019-08-06 14:43:25 +02:00
|
|
|
"""
|
2019-10-18 05:38:55 +02:00
|
|
|
parser = qubesadmin.tools.QubesArgumentParser(description=__doc__)
|
2017-04-30 15:20:35 +02:00
|
|
|
parser.register('action', 'parsers',
|
2019-08-06 14:43:25 +02:00
|
|
|
qubesadmin.tools.AliasedSubParsersAction)
|
2019-08-24 13:29:07 +02:00
|
|
|
parser.allow_abbrev = False
|
2017-04-30 15:20:35 +02:00
|
|
|
if device_class:
|
|
|
|
parser.add_argument('devclass', const=device_class,
|
2019-08-06 14:43:25 +02:00
|
|
|
action='store_const',
|
|
|
|
help=argparse.SUPPRESS)
|
2017-04-30 15:20:35 +02:00
|
|
|
else:
|
|
|
|
parser.add_argument('devclass', metavar='DEVICE_CLASS', action='store',
|
2019-08-06 14:43:25 +02:00
|
|
|
help="Device class to manage ('pci', 'usb', etc)")
|
2017-05-30 01:39:35 +02:00
|
|
|
|
|
|
|
# default action
|
|
|
|
parser.set_defaults(func=list_devices)
|
|
|
|
|
2017-04-30 15:20:35 +02:00
|
|
|
sub_parsers = parser.add_subparsers(
|
|
|
|
title='commands',
|
|
|
|
description="For more information see qvm-device command -h",
|
|
|
|
dest='command')
|
|
|
|
init_list_parser(sub_parsers)
|
|
|
|
attach_parser = sub_parsers.add_parser(
|
|
|
|
'attach', help="Attach device to domain", aliases=('at', 'a'))
|
|
|
|
detach_parser = sub_parsers.add_parser(
|
|
|
|
"detach", help="Detach device from domain", aliases=('d', 'dt'))
|
|
|
|
|
|
|
|
attach_parser.add_argument('VMNAME', nargs=1,
|
2019-08-06 14:43:25 +02:00
|
|
|
action=qubesadmin.tools.VmNameAction)
|
2017-04-30 15:20:35 +02:00
|
|
|
detach_parser.add_argument('VMNAME', nargs=1,
|
2019-08-06 14:43:25 +02:00
|
|
|
action=qubesadmin.tools.VmNameAction)
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
attach_parser.add_argument(metavar='BACKEND:DEVICE_ID',
|
2019-08-06 14:43:25 +02:00
|
|
|
dest='device_assignment',
|
|
|
|
action=DeviceAction)
|
2017-04-30 15:20:35 +02:00
|
|
|
detach_parser.add_argument(metavar='BACKEND:DEVICE_ID',
|
2019-08-06 14:43:25 +02:00
|
|
|
dest='device_assignment',
|
|
|
|
nargs=argparse.OPTIONAL,
|
|
|
|
action=DeviceAction, allow_unknown=True)
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
attach_parser.add_argument('--option', '-o', action='append',
|
2019-08-06 14:43:25 +02:00
|
|
|
help="Set option for the device in opt=value "
|
|
|
|
"form (can be specified "
|
|
|
|
"multiple times), see man qvm-device for "
|
|
|
|
"details")
|
2018-01-10 20:30:30 +01:00
|
|
|
attach_parser.add_argument('--ro', action='store_true', default=False,
|
2019-08-06 14:43:25 +02:00
|
|
|
help="Attach device read-only (alias for "
|
|
|
|
"read-only=yes option, "
|
|
|
|
"takes precedence)")
|
2017-04-30 15:20:35 +02:00
|
|
|
attach_parser.add_argument('--persistent', '-p', action='store_true',
|
2019-08-06 14:43:25 +02:00
|
|
|
default=False,
|
|
|
|
help="Attach device persistently (so it will "
|
|
|
|
"be automatically "
|
|
|
|
"attached at qube startup)")
|
2017-04-30 15:20:35 +02:00
|
|
|
|
|
|
|
attach_parser.set_defaults(func=attach_device)
|
|
|
|
detach_parser.set_defaults(func=detach_device)
|
|
|
|
|
2019-08-10 22:10:31 +02:00
|
|
|
parser.add_argument('--list-device-classes', action='store_true',
|
|
|
|
default=False)
|
|
|
|
|
2017-04-30 15:20:35 +02:00
|
|
|
return parser
|
|
|
|
|
|
|
|
|
|
|
|
def main(args=None, app=None):
|
2019-08-06 14:43:25 +02:00
|
|
|
"""Main routine of :program:`qvm-block`."""
|
2017-04-30 15:20:35 +02:00
|
|
|
basename = os.path.basename(sys.argv[0])
|
|
|
|
devclass = None
|
|
|
|
if basename.startswith('qvm-') and basename != 'qvm-device':
|
|
|
|
devclass = basename[4:]
|
2019-08-10 22:10:31 +02:00
|
|
|
|
2021-04-09 18:19:39 +02:00
|
|
|
parser = get_parser(devclass)
|
|
|
|
args = parser.parse_args(args, app=app)
|
2019-08-10 22:10:31 +02:00
|
|
|
|
|
|
|
if args.list_device_classes:
|
|
|
|
print('\n'.join(qubesadmin.Qubes().list_deviceclass()))
|
|
|
|
return 0
|
|
|
|
|
2017-04-30 15:20:35 +02:00
|
|
|
try:
|
|
|
|
args.func(args)
|
2017-05-11 23:21:04 +02:00
|
|
|
except qubesadmin.exc.QubesException as e:
|
2021-04-09 18:19:39 +02:00
|
|
|
parser.print_error(str(e))
|
2017-04-30 15:20:35 +02:00
|
|
|
return 1
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2019-08-10 22:10:31 +02:00
|
|
|
# Special treatment for '--list-device-classes' (alias --list-classes)
|
|
|
|
curr_action = sys.argv[1:]
|
|
|
|
if set(curr_action).intersection(
|
|
|
|
{'--list-device-classes', '--list-classes'}):
|
|
|
|
sys.exit(main(args=['', '--list-device-classes']))
|
|
|
|
|
2017-04-30 15:20:35 +02:00
|
|
|
sys.exit(main())
|