qvm_template.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  1. #!/usr/bin/env python3
  2. '''Tool for managing VM templates.'''
  3. import argparse
  4. import collections
  5. import datetime
  6. import enum
  7. import fnmatch
  8. import functools
  9. import itertools
  10. import json
  11. import operator
  12. import os
  13. import re
  14. import shutil
  15. import subprocess
  16. import sys
  17. import tempfile
  18. import time
  19. import typing
  20. import rpm
  21. import tqdm
  22. import xdg.BaseDirectory
  23. import qubesadmin
  24. import qubesadmin.tools
  25. import qubesadmin.tools.qvm_kill
  26. import qubesadmin.tools.qvm_remove
  27. PATH_PREFIX = '/var/lib/qubes/vm-templates'
  28. TEMP_DIR = '/var/tmp'
  29. PACKAGE_NAME_PREFIX = 'qubes-template-'
  30. CACHE_DIR = os.path.join(xdg.BaseDirectory.xdg_cache_home, 'qvm-template')
  31. UNVERIFIED_SUFFIX = '.unverified'
  32. LOCK_FILE = '/var/tmp/qvm-template.lck'
  33. def qubes_release() -> str:
  34. """Return the Qubes release."""
  35. if os.path.exists('/usr/share/qubes/marker-vm'):
  36. with open('/usr/share/qubes/marker-vm', 'r') as fd:
  37. # Get last line (in the format `x.x`)
  38. return fd.readlines()[-1].strip()
  39. with open('/etc/os-release', 'r') as fd:
  40. for line in fd:
  41. line = line.strip()
  42. if not line or line[0] == '#':
  43. continue
  44. key, val = line.split('=', 1)
  45. if key != 'VERSION_ID':
  46. continue
  47. val = val.strip('\'"') # strip possible quotes
  48. return val
  49. def parser_gen() -> argparse.ArgumentParser:
  50. """Generate argument parser for the application."""
  51. formatter = argparse.ArgumentDefaultsHelpFormatter
  52. parser_main = argparse.ArgumentParser(description='Qubes Template Manager',
  53. formatter_class=formatter)
  54. subparsers = parser_main.add_subparsers(dest='operation', required=True,
  55. description='Command to run.')
  56. def parser_add_command(cmd, help_str):
  57. return subparsers.add_parser(
  58. cmd,
  59. formatter_class=formatter,
  60. help=help_str,
  61. description=help_str)
  62. parser_main.add_argument('--repo-files', action='append',
  63. default=['/usr/share/qubes/repo-templates/qubes-templates.repo'],
  64. help=('Specify files containing DNF repository configuration.'
  65. ' Can be used more than once.'))
  66. parser_main.add_argument('--keyring',
  67. default='/usr/share/qubes/repo-templates/keys',
  68. help='Specify directory containing RPM public keys.')
  69. parser_main.add_argument('--updatevm', default='sys-firewall',
  70. help='Specify VM to download updates from.')
  71. parser_main.add_argument('--enablerepo', action='append', default=[],
  72. metavar='REPOID',
  73. help=('Enable additional repositories by an id or a glob.'
  74. ' Can be used more than once.'))
  75. parser_main.add_argument('--disablerepo', action='append', default=[],
  76. metavar='REPOID',
  77. help=('Disable certain repositories by an id or a glob.'
  78. ' Can be used more than once.'))
  79. parser_main.add_argument('--repoid', action='append', default=[],
  80. help=('Enable just specific repositories by an id or a glob.'
  81. ' Can be used more than once.'))
  82. parser_main.add_argument('--releasever', default=qubes_release(),
  83. help='Override Qubes release version.')
  84. parser_main.add_argument('--refresh', action='store_true',
  85. help='Set repository metadata as expired before running the command.')
  86. parser_main.add_argument('--cachedir', default=CACHE_DIR,
  87. help='Specify cache directory.')
  88. parser_main.add_argument('--yes', action='store_true',
  89. help='Assume "yes" to questions.')
  90. parser_main.add_argument('--quiet', action='store_true',
  91. help='Decrease verbosity.')
  92. # qvm-template {install,reinstall,downgrade,upgrade}
  93. parser_install = parser_add_command('install',
  94. help_str='Install template packages.')
  95. parser_install.add_argument('--pool',
  96. help='Specify pool to store created VMs in.')
  97. parser_reinstall = parser_add_command('reinstall',
  98. help_str='Reinstall template packages.')
  99. parser_downgrade = parser_add_command('downgrade',
  100. help_str='Downgrade template packages.')
  101. parser_upgrade = parser_add_command('upgrade',
  102. help_str='Upgrade template packages.')
  103. for parser_x in [parser_install, parser_reinstall,
  104. parser_downgrade, parser_upgrade]:
  105. parser_x.add_argument('--nogpgcheck', action='store_true',
  106. help='Disable signature checks.')
  107. parser_x.add_argument('--allow-pv', action='store_true',
  108. help='Allow templates that set virt_mode to pv.')
  109. parser_x.add_argument('templates', nargs='*', metavar='TEMPLATESPEC')
  110. # qvm-template download
  111. parser_download = parser_add_command('download',
  112. help_str='Download template packages.')
  113. for parser_x in [parser_install, parser_reinstall,
  114. parser_downgrade, parser_upgrade, parser_download]:
  115. parser_x.add_argument('--downloaddir', default='.',
  116. help='Specify download directory.')
  117. parser_x.add_argument('--retries', default=5, type=int,
  118. help='Specify maximum number of retries for downloads.')
  119. parser_download.add_argument('templates', nargs='*',
  120. metavar='TEMPLATESPEC')
  121. # qvm-template {list,info}
  122. parser_list = parser_add_command('list',
  123. help_str='List templates.')
  124. parser_info = parser_add_command('info',
  125. help_str='Display details about templates.')
  126. for parser_x in [parser_list, parser_info]:
  127. parser_x.add_argument('--all', action='store_true',
  128. help='Show all templates (default).')
  129. parser_x.add_argument('--installed', action='store_true',
  130. help='Show installed templates.')
  131. parser_x.add_argument('--available', action='store_true',
  132. help='Show available templates.')
  133. parser_x.add_argument('--extras', action='store_true',
  134. help=('Show extras (e.g., ones that exist'
  135. ' locally but not in repos) templates.'))
  136. parser_x.add_argument('--upgrades', action='store_true',
  137. help='Show available upgrades.')
  138. readable = parser_x.add_mutually_exclusive_group()
  139. readable.add_argument('--machine-readable', action='store_true',
  140. help='Enable machine-readable output.')
  141. readable.add_argument('--machine-readable-json', action='store_true',
  142. help='Enable machine-readable output (JSON).')
  143. parser_x.add_argument('templates', nargs='*', metavar='TEMPLATESPEC')
  144. # qvm-template search
  145. parser_search = parser_add_command('search',
  146. help_str='Search template details for the given string.')
  147. parser_search.add_argument('--all', action='store_true',
  148. help=('Search also in the template description and URL. In addition,'
  149. ' the criterion are evaluated with OR instead of AND.'))
  150. parser_search.add_argument('templates', nargs='*', metavar='PATTERN')
  151. # qvm-template remove
  152. parser_remove = parser_add_command('remove',
  153. help_str='Remove installed templates.')
  154. parser_remove.add_argument('--disassoc', action='store_true',
  155. help=('Also disassociate VMs from the templates to be removed.'
  156. ' This creates a dummy template for the VMs to link with.'))
  157. parser_remove.add_argument('templates', nargs='*', metavar='TEMPLATE')
  158. # qvm-template purge
  159. parser_purge = parser_add_command('purge',
  160. help_str='Remove installed templates and associated VMs.')
  161. parser_purge.add_argument('templates', nargs='*', metavar='TEMPLATE')
  162. # qvm-template clean
  163. parser_clean = parser_add_command('clean',
  164. help_str='Remove locally cached packages.')
  165. _ = parser_clean # unused
  166. # qvm-template repolist
  167. parser_repolist = parser_add_command('repolist',
  168. help_str='Show configured repositories.')
  169. repolim = parser_repolist.add_mutually_exclusive_group()
  170. repolim.add_argument('--all', action='store_true',
  171. help='Show all repos.')
  172. repolim.add_argument('--enabled', action='store_true',
  173. help='Show only enabled repos (default).')
  174. repolim.add_argument('--disabled', action='store_true',
  175. help='Show only disabled repos.')
  176. parser_repolist.add_argument('repos', nargs='*', metavar='REPOS')
  177. return parser_main
  178. parser = parser_gen()
  179. class TemplateState(enum.Enum):
  180. """Enum representing the state of a template."""
  181. INSTALLED = 'installed'
  182. AVAILABLE = 'available'
  183. EXTRA = 'extra'
  184. UPGRADABLE = 'upgradable'
  185. def title(self) -> str:
  186. """Return a long description of the state. Can be used as headings."""
  187. #pylint: disable=invalid-name
  188. TEMPLATE_TITLES = {
  189. TemplateState.INSTALLED: 'Installed Templates',
  190. TemplateState.AVAILABLE: 'Available Templates',
  191. TemplateState.EXTRA: 'Extra Templates',
  192. TemplateState.UPGRADABLE: 'Available Upgrades'
  193. }
  194. return TEMPLATE_TITLES[self]
  195. class VersionSelector(enum.Enum):
  196. """Enum representing how the candidate template version is chosen."""
  197. LATEST = enum.auto()
  198. """Install latest version."""
  199. REINSTALL = enum.auto()
  200. """Reinstall current version."""
  201. LATEST_LOWER = enum.auto()
  202. """Downgrade to the highest version that is lower than the current one."""
  203. LATEST_HIGHER = enum.auto()
  204. """Upgrade to the highest version that is higher than the current one."""
  205. class Template(typing.NamedTuple):
  206. """Details of a template."""
  207. name: str
  208. epoch: str
  209. version: str
  210. release: str
  211. reponame: str
  212. dlsize: int
  213. buildtime: datetime.datetime
  214. licence: str
  215. url: str
  216. summary: str
  217. description: str
  218. class DlEntry(typing.NamedTuple):
  219. """Information about a template to be downloaded."""
  220. evr: typing.Tuple[str, str, str]
  221. reponame: str
  222. dlsize: int
  223. def build_version_str(evr: typing.Tuple[str, str, str]) -> str:
  224. """Return version string described by ``evr``, which is in (epoch, version,
  225. release) format."""
  226. return '%s:%s-%s' % evr
  227. def is_match_spec(name: str, epoch: str, version: str, release: str, spec: str
  228. ) -> typing.Tuple[bool, float]:
  229. """Check whether (name, epoch, version, release) matches the spec string.
  230. For the algorithm, refer to section "NEVRA Matching" in the DNF
  231. documentation.
  232. Note that currently ``arch`` is ignored as the templates should be of
  233. ``noarch``.
  234. :return: A tuple. The first element indicates whether there is a match; the
  235. second element represents the priority of the match (lower is better)
  236. """
  237. if epoch != 0:
  238. targets = [
  239. f'{name}-{epoch}:{version}-{release}',
  240. f'{name}',
  241. f'{name}-{epoch}:{version}'
  242. ]
  243. else:
  244. targets = [
  245. f'{name}-{epoch}:{version}-{release}',
  246. f'{name}-{version}-{release}',
  247. f'{name}',
  248. f'{name}-{epoch}:{version}',
  249. f'{name}-{version}'
  250. ]
  251. for prio, target in enumerate(targets):
  252. if fnmatch.fnmatch(target, spec):
  253. return True, prio
  254. return False, float('inf')
  255. def query_local(vm: qubesadmin.vm.QubesVM) -> Template:
  256. """Return Template object associated with ``vm``.
  257. Requires the VM to be managed by qvm-template.
  258. """
  259. return Template(
  260. vm.features['template-name'],
  261. vm.features['template-epoch'],
  262. vm.features['template-version'],
  263. vm.features['template-release'],
  264. vm.features['template-reponame'],
  265. vm.get_disk_utilization(),
  266. datetime.datetime.fromisoformat(vm.features['template-buildtime']),
  267. vm.features['template-license'],
  268. vm.features['template-url'],
  269. vm.features['template-summary'],
  270. vm.features['template-description'].replace('|', '\n'))
  271. def query_local_evr(vm: qubesadmin.vm.QubesVM) -> typing.Tuple[str, str, str]:
  272. """Return the (epoch, version, release) of ``vm``.
  273. Requires the VM to be managed by qvm-template.
  274. """
  275. return (
  276. vm.features['template-epoch'],
  277. vm.features['template-version'],
  278. vm.features['template-release'])
  279. def is_managed_template(vm: qubesadmin.vm.QubesVM) -> bool:
  280. """Return whether the VM is managed by qvm-template."""
  281. return vm.features.get('template-name', None) == vm.name
  282. def get_managed_template_vm(app: qubesadmin.app.QubesBase, name: str
  283. ) -> qubesadmin.vm.QubesVM:
  284. """Return the QubesVM object associated with the given name if it exists
  285. and is managed by qvm-template, otherwise raise a parser error."""
  286. if name not in app.domains:
  287. parser.error("Template '%s' not already installed." % name)
  288. vm = app.domains[name]
  289. if not is_managed_template(vm):
  290. parser.error("Template '%s' is not managed by qvm-template." % name)
  291. return vm
  292. def confirm_action(msg: str, affected: typing.List[str]) -> None:
  293. """Confirm user action."""
  294. print(msg)
  295. for name in affected:
  296. print(' ' + name)
  297. confirm = ''
  298. while confirm != 'y':
  299. confirm = input('Are you sure? [y/N] ').lower()
  300. if confirm == 'n':
  301. print('Operation cancelled.')
  302. sys.exit(1)
  303. def qrexec_popen(
  304. args: argparse.Namespace,
  305. app: qubesadmin.app.QubesBase,
  306. service: str,
  307. stdout: typing.Union[int, typing.IO] = subprocess.PIPE,
  308. filter_esc: bool = True) -> subprocess.Popen:
  309. """Return ``Popen`` object that communicates with the given qrexec call in
  310. ``args.updatevm``.
  311. Note that this falls back to invoking ``/etc/qubes-rpc/*`` directly if
  312. ``args.updatevm`` is None.
  313. :param args: Arguments received by the application. ``args.updatevm`` is
  314. used
  315. :param app: Qubes application object
  316. :param service: The qrexec call to invoke
  317. :param stdout: Where the process stdout points to. This is passed directly
  318. to ``subprocess.Popen``. Defaults to ``subprocess.PIPE``
  319. Note that stderr is always set to ``subprocess.PIPE``
  320. :param filter_esc: Whether to filter out escape sequences from
  321. stdout/stderr. Defaults to True
  322. :returns: ``Popen`` object that communicates with the given qrexec call
  323. """
  324. if args.updatevm:
  325. return app.domains[args.updatevm].run_service(
  326. service,
  327. filter_esc=filter_esc,
  328. stdout=stdout)
  329. return subprocess.Popen([
  330. '/etc/qubes-rpc/%s' % service,
  331. ],
  332. stdin=subprocess.PIPE,
  333. stdout=stdout,
  334. stderr=subprocess.PIPE)
  335. def qrexec_payload(args: argparse.Namespace, app: qubesadmin.app.QubesBase,
  336. spec: str, refresh: bool) -> str:
  337. """Return payload string for the ``qubes.Template*`` qrexec calls.
  338. :param args: Arguments received by the application. Specifically,
  339. ``args.{enablerepo,disablerepo,repoid,releasever,repo_files}`` are used
  340. :param app: Qubes application object
  341. :param spec: Package spec to query (refer to ``<package-name-spec>`` in the
  342. DNF documentation)
  343. :param refresh: Whether to force refresh repo metadata
  344. :return: Payload string
  345. :raises: Parser error if spec equals ``---`` or input contains ``\\n``
  346. """
  347. _ = app # unused
  348. if spec == '---':
  349. parser.error("Malformed template name: argument should not be '---'.")
  350. def check_newline(string, name):
  351. if '\n' in string:
  352. parser.error(f"Malformed {name}:" +
  353. " argument should not contain '\\n'.")
  354. payload = ''
  355. for repo in args.enablerepo:
  356. check_newline(repo, '--enablerepo')
  357. payload += '--enablerepo=%s\n' % repo
  358. for repo in args.disablerepo:
  359. check_newline(repo, '--disablerepo')
  360. payload += '--disablerepo=%s\n' % repo
  361. for repo in args.repoid:
  362. check_newline(repo, '--repoid')
  363. payload += '--repoid=%s\n' % repo
  364. if refresh:
  365. payload += '--refresh\n'
  366. check_newline(args.releasever, '--releasever')
  367. payload += '--releasever=%s\n' % args.releasever
  368. check_newline(spec, 'template name')
  369. payload += spec + '\n'
  370. payload += '---\n'
  371. for path in args.repo_files:
  372. with open(path, 'r') as fd:
  373. payload += fd.read() + '\n'
  374. return payload
  375. def qrexec_repoquery(
  376. args: argparse.Namespace,
  377. app: qubesadmin.app.QubesBase,
  378. spec: str = '*',
  379. refresh: bool = False) -> typing.List[Template]:
  380. """Query template information from repositories.
  381. :param args: Arguments received by the application. Specifically,
  382. ``args.{enablerepo,disablerepo,repoid,releasever,repo_files,updatevm}``
  383. are used
  384. :param app: Qubes application object
  385. :param spec: Package spec to query (refer to ``<package-name-spec>`` in the
  386. DNF documentation). Defaults to ``*``
  387. :param refresh: Whether to force refresh repo metadata. Defaults to False
  388. :raises ConnectionError: if the qrexec call fails
  389. :return: List of ``Template`` objects representing the result of the query
  390. """
  391. payload = qrexec_payload(args, app, spec, refresh)
  392. proc = qrexec_popen(args, app, 'qubes.TemplateSearch')
  393. stdout, stderr = proc.communicate(payload.encode('UTF-8'))
  394. stdout = stdout.decode('ASCII')
  395. if proc.wait() != 0:
  396. for line in stderr.decode('ASCII').rstrip().split('\n'):
  397. print('[Qrexec] %s' % line, file=sys.stderr)
  398. raise ConnectionError("qrexec call 'qubes.TemplateSearch' failed.")
  399. name_re = re.compile(r'^[A-Za-z0-9._+\-]*$')
  400. evr_re = re.compile(r'^[A-Za-z0-9._+~]*$')
  401. date_re = re.compile(r'^\d+-\d+-\d+ \d+:\d+$')
  402. licence_re = re.compile(r'^[A-Za-z0-9._+\-()]*$')
  403. result = []
  404. for line in stdout.split('|\n'):
  405. # Note that there's an empty entry at the end as .strip() is not used.
  406. # This is because if .strip() is used, the .split() will not work.
  407. if line == '':
  408. continue
  409. entry = line.split('|')
  410. try:
  411. # If there is an incorrect number of entries, raise an error
  412. # Unpack manually instead of stuffing into `Template` right away
  413. # so that it's easier to mutate stuff.
  414. name, epoch, version, release, reponame, dlsize, \
  415. buildtime, licence, url, summary, description = entry
  416. # Ignore packages that are not templates
  417. if not name.startswith(PACKAGE_NAME_PREFIX):
  418. continue
  419. name = name[len(PACKAGE_NAME_PREFIX):]
  420. # Check that the values make sense
  421. if not re.fullmatch(name_re, name):
  422. raise ValueError
  423. for val in [epoch, version, release]:
  424. if not re.fullmatch(evr_re, val):
  425. raise ValueError
  426. if not re.fullmatch(name_re, reponame):
  427. raise ValueError
  428. dlsize = int(dlsize)
  429. # First verify that the date does not look weird, then parse it
  430. if not re.fullmatch(date_re, buildtime):
  431. raise ValueError
  432. buildtime = datetime.datetime.strptime(buildtime, '%Y-%m-%d %H:%M')
  433. # XXX: Perhaps whitelist licenses directly?
  434. if not re.fullmatch(licence_re, licence):
  435. raise ValueError
  436. # Check name actually matches spec
  437. if not is_match_spec(name, epoch, version, release, spec):
  438. continue
  439. result.append(Template(name, epoch, version, release, reponame,
  440. dlsize, buildtime, licence, url, summary, description))
  441. except (TypeError, ValueError):
  442. raise ConnectionError(("qrexec call 'qubes.TemplateSearch' failed:"
  443. " unexpected data format."))
  444. return result
  445. def qrexec_download(
  446. args: argparse.Namespace,
  447. app: qubesadmin.app.QubesBase,
  448. spec: str,
  449. path: str,
  450. dlsize: typing.Optional[int] = None,
  451. refresh: bool = False) -> None:
  452. """Download a template from repositories.
  453. :param args: Arguments received by the application. Specifically,
  454. ``args.{enablerepo,disablerepo,repoid,releasever,repo_files,updatevm,
  455. quiet}`` are used
  456. :param app: Qubes application object
  457. :param spec: Package spec to query (refer to ``<package-name-spec>`` in the
  458. DNF documentation)
  459. :param path: Path to place the downloaded template
  460. :param dlsize: Size of template to be downloaded. Used for the progress
  461. bar. Optional
  462. :param refresh: Whether to force refresh repo metadata. Defaults to False
  463. :raises ConnectionError: if the qrexec call fails
  464. """
  465. with open(path, 'wb') as fd:
  466. payload = qrexec_payload(args, app, spec, refresh)
  467. # Don't filter ESCs for binary files
  468. proc = qrexec_popen(args, app, 'qubes.TemplateDownload',
  469. stdout=fd, filter_esc=False)
  470. proc.stdin.write(payload.encode('UTF-8'))
  471. proc.stdin.close()
  472. with tqdm.tqdm(desc=spec, total=dlsize, unit_scale=True,
  473. unit_divisor=1000, unit='B', disable=args.quiet) as pbar:
  474. last = 0
  475. while proc.poll() is None:
  476. cur = fd.tell()
  477. pbar.update(cur - last)
  478. last = cur
  479. time.sleep(0.1)
  480. if proc.wait() != 0:
  481. raise ConnectionError(
  482. "qrexec call 'qubes.TemplateDownload' failed.")
  483. def rpm_transactionset(key_dir: str) -> rpm.transaction.TransactionSet:
  484. """Create RPM TransactionSet using the keys in the given directory."""
  485. tset = rpm.TransactionSet()
  486. kring = rpm.keyring()
  487. for name in os.listdir(key_dir):
  488. path = os.path.join(key_dir, name)
  489. if os.path.isfile(path):
  490. with open(path, 'rb') as fd:
  491. kring.addKey(rpm.pubkey(fd.read()))
  492. tset.setKeyring(kring)
  493. return tset
  494. def verify_rpm(
  495. path: str,
  496. transaction_set: rpm.transaction.TransactionSet,
  497. nogpgcheck: bool = False
  498. ) -> rpm.hdr:
  499. """Verify the digest and signature of a RPM package and return the package
  500. header.
  501. Note that verifying RPMs this way is prone to TOCTOU. This is okay for
  502. local files, but may create problems if multiple instances of
  503. **qvm-template** are downloading the same file, so a lock is needed in that
  504. case.
  505. :param path: Location of the RPM package
  506. :param transaction_set: RPM ``TransactionSet``
  507. :param nogpgcheck: Whether to allow invalid GPG signatures
  508. :return: RPM package header. If verification fails, ``None`` is returned.
  509. """
  510. with open(path, 'rb') as fd:
  511. try:
  512. hdr = transaction_set.hdrFromFdno(fd)
  513. if hdr[rpm.RPMTAG_SIGPGP] is None \
  514. and hdr[rpm.RPMTAG_SIGGPG] is None:
  515. return hdr if nogpgcheck else None
  516. except rpm.error as e:
  517. if str(e) == 'public key not trusted' \
  518. or str(e) == 'public key not available':
  519. # TODO: This does not work
  520. # Should just tell TransactionSet not to verify sigs
  521. return hdr if nogpgcheck else None
  522. return None
  523. return hdr
  524. def extract_rpm(name: str, path: str, target: str) -> bool:
  525. """Extract a template RPM package.
  526. :param name: Name of the template
  527. :param path: Location of the RPM package
  528. :param target: Target path to extract to
  529. :return: Whether the extraction succeeded
  530. """
  531. rpm2cpio = subprocess.Popen(['rpm2cpio', path], stdout=subprocess.PIPE)
  532. # `-D` is GNUism
  533. cpio = subprocess.Popen([
  534. 'cpio',
  535. '-idm',
  536. '-D',
  537. target,
  538. '.%s/%s/*' % (PATH_PREFIX, name)
  539. ], stdin=rpm2cpio.stdout, stdout=subprocess.DEVNULL)
  540. return rpm2cpio.wait() == 0 and cpio.wait() == 0
  541. def get_dl_list(
  542. args: argparse.Namespace,
  543. app: qubesadmin.app.QubesBase,
  544. version_selector: VersionSelector = VersionSelector.LATEST
  545. ) -> typing.Dict[str, DlEntry]:
  546. """Return list of templates that needs to be downloaded.
  547. :param args: Arguments received by the application.
  548. :param app: Qubes application object
  549. :param version_selector: Specify algorithm to select the candidate version
  550. of a package. Defaults to ``VersionSelector.LATEST``
  551. :return: Dictionary that maps to ``DlEntry`` the names of templates that
  552. needs to be downloaded
  553. """
  554. full_candid: typing.Dict[str, DlEntry] = {}
  555. for template in args.templates:
  556. # This will be merged into `full_candid` later.
  557. # It is separated so that we can check whether it is empty.
  558. candid: typing.Dict[str, DlEntry] = {}
  559. # Skip local RPMs
  560. if template.endswith('.rpm'):
  561. continue
  562. query_res = qrexec_repoquery(args, app, PACKAGE_NAME_PREFIX + template)
  563. # We only select one package for each distinct package name
  564. for entry in query_res:
  565. ver = (entry.epoch, entry.version, entry.release)
  566. insert = False
  567. if version_selector == VersionSelector.LATEST:
  568. if entry.name not in candid \
  569. or rpm.labelCompare(candid[entry.name][0], ver) < 0:
  570. insert = True
  571. elif version_selector == VersionSelector.REINSTALL:
  572. vm = get_managed_template_vm(app, entry.name)
  573. cur_ver = query_local_evr(vm)
  574. if rpm.labelCompare(ver, cur_ver) == 0:
  575. insert = True
  576. elif version_selector in [VersionSelector.LATEST_LOWER,
  577. VersionSelector.LATEST_HIGHER]:
  578. vm = get_managed_template_vm(app, entry.name)
  579. cur_ver = query_local_evr(vm)
  580. cmp_res = -1 \
  581. if version_selector == VersionSelector.LATEST_LOWER \
  582. else 1
  583. if rpm.labelCompare(ver, cur_ver) == cmp_res:
  584. if entry.name not in candid \
  585. or rpm.labelCompare(candid[entry.name][0], ver) < 0:
  586. insert = True
  587. if insert:
  588. candid[entry.name] = DlEntry(ver, entry.reponame, entry.dlsize)
  589. # XXX: As it's possible to include version information in `template`,
  590. # perhaps the messages can be improved
  591. if len(candid) == 0:
  592. if version_selector == VersionSelector.LATEST:
  593. parser.error('Template \'%s\' not found.' % template)
  594. elif version_selector == VersionSelector.REINSTALL:
  595. parser.error('Same version of template \'%s\' not found.' \
  596. % template)
  597. # Copy behavior of DNF and do nothing if version not found
  598. elif version_selector == VersionSelector.LATEST_LOWER:
  599. print(("Template '%s' of lowest version"
  600. " already installed, skipping..." % template),
  601. file=sys.stderr)
  602. elif version_selector == VersionSelector.LATEST_HIGHER:
  603. print(("Template '%s' of highest version"
  604. " already installed, skipping..." % template),
  605. file=sys.stderr)
  606. # Merge & choose the template with the highest version
  607. for name, dlentry in candid.items():
  608. if name not in full_candid \
  609. or rpm.labelCompare(full_candid[name].evr, dlentry.evr) < 0:
  610. full_candid[name] = dlentry
  611. return full_candid
  612. def download(
  613. args: argparse.Namespace,
  614. app: qubesadmin.app.QubesBase,
  615. path_override: typing.Optional[str] = None,
  616. dl_list: typing.Optional[typing.Dict[str, DlEntry]] = None,
  617. suffix: str = '',
  618. version_selector: VersionSelector = VersionSelector.LATEST) -> None:
  619. """Command that downloads template packages.
  620. :param args: Arguments received by the application.
  621. :param app: Qubes application object
  622. :param path_override: Override path to store downloads. If not set or set
  623. to None, ``args.downloaddir`` is used. Optional
  624. :param dl_list: Override list of templates to download. If not set or set
  625. to None, ``get_dl_list`` is called, which generates the list from
  626. ``args``. Optional
  627. :param suffix: Suffix to add to the file name of downloaded packages. This
  628. is useful if you want to distinguish between verified and unverified
  629. packages. Defaults to an empty string
  630. :param version_selector: Specify algorithm to select the candidate version
  631. of a package. Defaults to ``VersionSelector.LATEST``
  632. """
  633. if dl_list is None:
  634. dl_list = get_dl_list(args, app, version_selector=version_selector)
  635. path = path_override if path_override is not None else args.downloaddir
  636. for name, entry in dl_list.items():
  637. version_str = build_version_str(entry.evr)
  638. spec = PACKAGE_NAME_PREFIX + name + '-' + version_str
  639. target = os.path.join(path, '%s.rpm' % spec)
  640. target_suffix = target + suffix
  641. if suffix != '' and os.path.exists(target_suffix):
  642. print('\'%s\' already exists, skipping...' % target,
  643. file=sys.stderr)
  644. if os.path.exists(target):
  645. print('\'%s\' already exists, skipping...' % target,
  646. file=sys.stderr)
  647. if suffix != '':
  648. os.rename(target, target_suffix)
  649. else:
  650. print('Downloading \'%s\'...' % spec, file=sys.stderr)
  651. done = False
  652. for attempt in range(args.retries):
  653. try:
  654. qrexec_download(args, app, spec, target_suffix,
  655. entry.dlsize)
  656. done = True
  657. break
  658. except ConnectionError:
  659. os.remove(target_suffix)
  660. if attempt + 1 < args.retries:
  661. print('\'%s\' download failed, retrying...' % spec,
  662. file=sys.stderr)
  663. except:
  664. # Also remove file if interrupted by other means
  665. os.remove(target_suffix)
  666. raise
  667. if not done:
  668. print('Error: \'%s\' download failed.' % spec, file=sys.stderr)
  669. sys.exit(1)
  670. def install(
  671. args: argparse.Namespace,
  672. app: qubesadmin.app.QubesBase,
  673. version_selector: VersionSelector = VersionSelector.LATEST,
  674. override_existing: bool = False) -> None:
  675. """Command that installs template packages.
  676. This command creates a lock file to ensure that two instances are not
  677. running at the same time.
  678. :param args: Arguments received by the application.
  679. :param app: Qubes application object
  680. :param version_selector: Specify algorithm to select the candidate version
  681. of a package. Defaults to ``VersionSelector.LATEST``
  682. :param override_existing: Whether to override existing packages. Used for
  683. reinstall, upgrade, and downgrade operations
  684. """
  685. try:
  686. with open(LOCK_FILE, 'x') as _:
  687. pass
  688. except FileExistsError:
  689. parser.error(('%s already exists.'
  690. ' Perhaps another instance of qvm-template is running?')
  691. % LOCK_FILE)
  692. try:
  693. transaction_set = rpm_transactionset(args.keyring)
  694. unverified_rpm_list = [] # rpmfile, reponame
  695. verified_rpm_list = []
  696. def verify(rpmfile, reponame):
  697. """Verify package signature and version, remove "unverified"
  698. suffix, and parse package header."""
  699. if reponame != '@commandline':
  700. path = rpmfile + UNVERIFIED_SUFFIX
  701. else:
  702. path = rpmfile
  703. package_hdr = verify_rpm(path, transaction_set, args.nogpgcheck)
  704. if not package_hdr:
  705. parser.error('Package \'%s\' verification failed.' % rpmfile)
  706. package_name = package_hdr[rpm.RPMTAG_NAME]
  707. if not package_name.startswith(PACKAGE_NAME_PREFIX):
  708. parser.error(
  709. 'Illegal package name for package \'%s\'.' % rpmfile)
  710. # Remove prefix to get the real template name
  711. name = package_name[len(PACKAGE_NAME_PREFIX):]
  712. if path != rpmfile:
  713. os.rename(path, rpmfile)
  714. # Check if already installed
  715. if not override_existing and name in app.domains:
  716. print(('Template \'%s\' already installed, skipping...'
  717. ' (You may want to use the'
  718. ' {reinstall,upgrade,downgrade}'
  719. ' operations.)') % name, file=sys.stderr)
  720. return
  721. # Check if version is really what we want
  722. if override_existing:
  723. vm = get_managed_template_vm(app, name)
  724. pkg_evr = (
  725. str(package_hdr[rpm.RPMTAG_EPOCHNUM]),
  726. package_hdr[rpm.RPMTAG_VERSION],
  727. package_hdr[rpm.RPMTAG_RELEASE])
  728. vm_evr = query_local_evr(vm)
  729. cmp_res = rpm.labelCompare(pkg_evr, vm_evr)
  730. if version_selector == VersionSelector.REINSTALL \
  731. and cmp_res != 0:
  732. parser.error(
  733. 'Same version of template \'%s\' not found.' \
  734. % name)
  735. elif version_selector == VersionSelector.LATEST_LOWER \
  736. and cmp_res != -1:
  737. print(("Template '%s' of lower version"
  738. " already installed, skipping..." % name),
  739. file=sys.stderr)
  740. return
  741. elif version_selector == VersionSelector.LATEST_HIGHER \
  742. and cmp_res != 1:
  743. print(("Template '%s' of higher version"
  744. " already installed, skipping..." % name),
  745. file=sys.stderr)
  746. return
  747. verified_rpm_list.append((rpmfile, reponame, name, package_hdr))
  748. # Process local templates
  749. for template in args.templates:
  750. if template.endswith('.rpm'):
  751. if not os.path.exists(template):
  752. parser.error('RPM file \'%s\' not found.' % template)
  753. unverified_rpm_list.append((template, '@commandline'))
  754. # First verify local RPMs and extract header
  755. for rpmfile, reponame in unverified_rpm_list:
  756. verify(rpmfile, reponame)
  757. unverified_rpm_list = []
  758. os.makedirs(args.cachedir, exist_ok=True)
  759. # Get list of templates to download
  760. dl_list = get_dl_list(args, app, version_selector=version_selector)
  761. dl_list_copy = dl_list.copy()
  762. for name, entry in dl_list.items():
  763. # Should be ensured by checks in repoquery
  764. assert entry.reponame != '@commandline'
  765. # Verify that the templates to be downloaded are not yet installed
  766. # Note that we *still* have to do this again in verify() for
  767. # already-downloaded templates
  768. if not override_existing and name in app.domains:
  769. print(('Template \'%s\' already installed, skipping...'
  770. ' (You may want to use the'
  771. ' {reinstall,upgrade,downgrade}'
  772. ' operations.)') % name, file=sys.stderr)
  773. del dl_list_copy[name]
  774. else:
  775. # XXX: Perhaps this is better returned by download()
  776. version_str = build_version_str(entry.evr)
  777. target_file = \
  778. '%s%s-%s.rpm' % (PACKAGE_NAME_PREFIX, name, version_str)
  779. unverified_rpm_list.append(
  780. (os.path.join(args.cachedir, target_file), entry.reponame))
  781. dl_list = dl_list_copy
  782. # Ask the user for confirmation before we actually download stuff
  783. if override_existing and not args.yes:
  784. override_tpls = []
  785. # Local templates, already verified
  786. for _, _, name, _ in verified_rpm_list:
  787. override_tpls.append(name)
  788. # Templates not yet downloaded
  789. for name in dl_list:
  790. override_tpls.append(name)
  791. confirm_action(
  792. 'This will override changes made in the following VMs:',
  793. override_tpls)
  794. download(args, app, path_override=args.cachedir,
  795. dl_list=dl_list, suffix=UNVERIFIED_SUFFIX,
  796. version_selector=version_selector)
  797. # Verify downloaded templates
  798. for rpmfile, reponame in unverified_rpm_list:
  799. verify(rpmfile, reponame)
  800. unverified_rpm_list = []
  801. # Unpack and install
  802. for rpmfile, reponame, name, package_hdr in verified_rpm_list:
  803. with tempfile.TemporaryDirectory(dir=TEMP_DIR) as target:
  804. print('Installing template \'%s\'...' % name, file=sys.stderr)
  805. # TODO: Handle return value
  806. extract_rpm(name, rpmfile, target)
  807. cmdline = [
  808. 'qvm-template-postprocess',
  809. '--really',
  810. '--no-installed-by-rpm',
  811. ]
  812. if args.allow_pv:
  813. cmdline.append('--allow-pv')
  814. if not override_existing and args.pool:
  815. cmdline += ['--pool', args.pool]
  816. subprocess.check_call(cmdline + [
  817. 'post-install',
  818. name,
  819. target + PATH_PREFIX + '/' + name])
  820. app.domains.refresh_cache(force=True)
  821. tpl = app.domains[name]
  822. tpl.features['template-name'] = name
  823. tpl.features['template-epoch'] = \
  824. package_hdr[rpm.RPMTAG_EPOCHNUM]
  825. tpl.features['template-version'] = \
  826. package_hdr[rpm.RPMTAG_VERSION]
  827. tpl.features['template-release'] = \
  828. package_hdr[rpm.RPMTAG_RELEASE]
  829. tpl.features['template-reponame'] = reponame
  830. tpl.features['template-buildtime'] = \
  831. str(datetime.datetime.fromtimestamp(
  832. int(package_hdr[rpm.RPMTAG_BUILDTIME])))
  833. tpl.features['template-installtime'] = \
  834. str(datetime.datetime.today())
  835. tpl.features['template-license'] = \
  836. package_hdr[rpm.RPMTAG_LICENSE]
  837. tpl.features['template-url'] = \
  838. package_hdr[rpm.RPMTAG_URL]
  839. tpl.features['template-summary'] = \
  840. package_hdr[rpm.RPMTAG_SUMMARY]
  841. tpl.features['template-description'] = \
  842. package_hdr[rpm.RPMTAG_DESCRIPTION].replace('\n', '|')
  843. finally:
  844. os.remove(LOCK_FILE)
  845. def list_templates(args: argparse.Namespace,
  846. app: qubesadmin.app.QubesBase, operation: str) -> None:
  847. """Command that lists templates.
  848. :param args: Arguments received by the application.
  849. :param app: Qubes application object
  850. :param operation: If set to ``list``, display a listing similar to ``dnf
  851. list``. If set to ``info``, display detailed template information
  852. similar to ``dnf info``. Otherwise, an ``AssertionError`` is raised.
  853. """
  854. tpl_list = []
  855. def append_list(data, status, install_time=None):
  856. _ = install_time # unused
  857. version_str = build_version_str(
  858. (data.epoch, data.version, data.release))
  859. tpl_list.append((status, data.name, version_str, data.reponame))
  860. def append_info(data, status, install_time=None):
  861. tpl_list.append((status, data, install_time))
  862. def list_to_human_output(tpls):
  863. outputs = []
  864. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  865. def convert(row):
  866. return row[1:]
  867. outputs.append((status, list(map(convert, grp))))
  868. return outputs
  869. def list_to_machine_output(tpls):
  870. outputs = {}
  871. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  872. def convert(row):
  873. _, name, evr, reponame = row
  874. return {'name': name, 'evr': evr, 'reponame': reponame}
  875. outputs[status.value] = list(map(convert, grp))
  876. return outputs
  877. def info_to_human_output(tpls):
  878. outputs = []
  879. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  880. output = []
  881. for _, data, install_time in grp:
  882. output.append(('Name', ':', data.name))
  883. output.append(('Epoch', ':', data.epoch))
  884. output.append(('Version', ':', data.version))
  885. output.append(('Release', ':', data.release))
  886. output.append(('Size', ':',
  887. qubesadmin.utils.size_to_human(data.dlsize)))
  888. output.append(('Repository', ':', data.reponame))
  889. output.append(('Buildtime', ':', str(data.buildtime)))
  890. if install_time:
  891. output.append(('Install time', ':', str(install_time)))
  892. output.append(('URL', ':', data.url))
  893. output.append(('License', ':', data.licence))
  894. output.append(('Summary', ':', data.summary))
  895. # Only show "Description" for the first line
  896. title = 'Description'
  897. for line in data.description.splitlines():
  898. output.append((title, ':', line))
  899. title = ''
  900. output.append((' ', ' ', ' ')) # empty line
  901. outputs.append((status, output))
  902. return outputs
  903. def info_to_machine_output(tpls, replace_newline=True):
  904. outputs = {}
  905. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  906. output = []
  907. for _, data, install_time in grp:
  908. name, epoch, version, release, reponame, dlsize, \
  909. buildtime, licence, url, summary, description = data
  910. dlsize = str(dlsize)
  911. buildtime = str(buildtime)
  912. install_time = str(install_time) if install_time else ''
  913. if replace_newline:
  914. description = description.replace('\n', '|')
  915. output.append({
  916. 'name': name,
  917. 'epoch': epoch,
  918. 'version': version,
  919. 'release': release,
  920. 'reponame': reponame,
  921. 'size': dlsize,
  922. 'buildtime': buildtime,
  923. 'installtime': install_time,
  924. 'license': licence,
  925. 'url': url,
  926. 'summary': summary,
  927. 'description': description})
  928. outputs[status.value] = output
  929. return outputs
  930. if operation == 'list':
  931. append = append_list
  932. elif operation == 'info':
  933. append = append_info
  934. else:
  935. assert False and 'Unknown operation'
  936. def append_vm(vm, status):
  937. append(query_local(vm), status, vm.features['template-installtime'])
  938. if not (args.installed or args.available or args.extras or args.upgrades):
  939. args.all = True
  940. if args.all or args.available or args.extras or args.upgrades:
  941. if args.templates:
  942. query_res_set: typing.Set[Template] = set()
  943. for spec in args.templates:
  944. query_res_set |= set(qrexec_repoquery(args, app, spec))
  945. query_res = list(query_res_set)
  946. else:
  947. query_res = qrexec_repoquery(args, app)
  948. if args.installed or args.all:
  949. for vm in app.domains:
  950. if is_managed_template(vm):
  951. if not args.templates or \
  952. any(is_match_spec(
  953. vm.name,
  954. *query_local_evr(vm),
  955. spec)[0]
  956. for spec in args.templates):
  957. append_vm(vm, TemplateState.INSTALLED)
  958. if args.available or args.all:
  959. for data in query_res:
  960. append(data, TemplateState.AVAILABLE)
  961. if args.extras:
  962. remote = set()
  963. for data in query_res:
  964. remote.add(data.name)
  965. for vm in app.domains:
  966. if is_managed_template(vm) and vm.name not in remote:
  967. append_vm(vm, TemplateState.EXTRA)
  968. if args.upgrades:
  969. local = {}
  970. for vm in app.domains:
  971. if is_managed_template(vm):
  972. local[vm.name] = query_local_evr(vm)
  973. for entry in query_res:
  974. if entry.name in local:
  975. if rpm.labelCompare(local[entry.name],
  976. (entry.epoch, entry.version, entry.release)) < 0:
  977. append(entry, TemplateState.UPGRADABLE)
  978. if len(tpl_list) == 0:
  979. parser.error('No matching templates to list')
  980. if args.machine_readable:
  981. if operation == 'info':
  982. tpl_list = info_to_machine_output(tpl_list)
  983. elif operation == 'list':
  984. tpl_list = list_to_machine_output(tpl_list)
  985. for status, grp in tpl_list.items():
  986. for line in grp:
  987. print('|'.join([status] + list(line.values())))
  988. elif args.machine_readable_json:
  989. if operation == 'info':
  990. tpl_list = info_to_machine_output(tpl_list, replace_newline=False)
  991. elif operation == 'list':
  992. tpl_list = list_to_machine_output(tpl_list)
  993. print(json.dumps(tpl_list))
  994. else:
  995. if operation == 'info':
  996. tpl_list = info_to_human_output(tpl_list)
  997. elif operation == 'list':
  998. tpl_list = list_to_human_output(tpl_list)
  999. for status, grp in tpl_list:
  1000. print(status.title())
  1001. qubesadmin.tools.print_table(grp)
  1002. def search(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
  1003. """Command that searches template details for given patterns.
  1004. :param args: Arguments received by the application.
  1005. :param app: Qubes application object
  1006. """
  1007. # Search in both installed and available templates
  1008. query_res = qrexec_repoquery(args, app)
  1009. for vm in app.domains:
  1010. if is_managed_template(vm):
  1011. query_res.append(query_local(vm))
  1012. # Get latest version for each template
  1013. query_res_tmp = []
  1014. for _, grp in itertools.groupby(sorted(query_res), lambda x: x[0]):
  1015. def compare(lhs, rhs):
  1016. return lhs if rpm.labelCompare(lhs[1:4], rhs[1:4]) < 0 else rhs
  1017. query_res_tmp.append(functools.reduce(compare, grp))
  1018. query_res = query_res_tmp
  1019. #pylint: disable=invalid-name
  1020. WEIGHT_NAME_EXACT = 1 << 4
  1021. WEIGHT_NAME = 1 << 3
  1022. WEIGHT_SUMMARY = 1 << 2
  1023. WEIGHT_DESCRIPTION = 1 << 1
  1024. WEIGHT_URL = 1 << 0
  1025. WEIGHT_TO_FIELD = [
  1026. (WEIGHT_NAME_EXACT, 'Name'),
  1027. (WEIGHT_NAME, 'Name'),
  1028. (WEIGHT_SUMMARY, 'Summary'),
  1029. (WEIGHT_DESCRIPTION, 'Description'),
  1030. (WEIGHT_URL, 'URL')]
  1031. search_res_by_idx: \
  1032. typing.Dict[int, typing.List[typing.Tuple[int, str, bool]]] = \
  1033. collections.defaultdict(list)
  1034. for keyword in args.templates:
  1035. for idx, entry in enumerate(query_res):
  1036. needle_types = \
  1037. [(entry.name, WEIGHT_NAME), (entry.summary, WEIGHT_SUMMARY)]
  1038. if args.all:
  1039. needle_types += [(entry.description, WEIGHT_DESCRIPTION),
  1040. (entry.url, WEIGHT_URL)]
  1041. for key, weight in needle_types:
  1042. if fnmatch.fnmatch(key, '*' + keyword + '*'):
  1043. exact = keyword == key
  1044. if exact and weight == WEIGHT_NAME:
  1045. weight = WEIGHT_NAME_EXACT
  1046. search_res_by_idx[idx].append((weight, keyword, exact))
  1047. if not args.all:
  1048. keywords = set(args.templates)
  1049. idxs = list(search_res_by_idx.keys())
  1050. for idx in idxs:
  1051. if keywords != set(x[1] for x in search_res_by_idx[idx]):
  1052. del search_res_by_idx[idx]
  1053. def key_func(x):
  1054. # ORDER BY weight DESC, list_of_needles ASC, name ASC
  1055. idx, needles = x
  1056. weight = sum(t[0] for t in needles)
  1057. name = query_res[idx][0]
  1058. return (-weight, needles, name)
  1059. search_res = sorted(search_res_by_idx.items(), key=key_func)
  1060. def gen_header(needles):
  1061. fields = []
  1062. weight_types = set(x[0] for x in needles)
  1063. for weight, field in WEIGHT_TO_FIELD:
  1064. if weight in weight_types:
  1065. fields.append(field)
  1066. exact = all(x[-1] for x in needles)
  1067. match = 'Exactly Matched' if exact else 'Matched'
  1068. keywords = sorted(list(set(x[1] for x in needles)))
  1069. return ' & '.join(fields) + ' ' + match + ': ' + ', '.join(keywords)
  1070. last_header = ''
  1071. for idx, needles in search_res:
  1072. # Print headers
  1073. cur_header = gen_header(needles)
  1074. if last_header != cur_header:
  1075. last_header = cur_header
  1076. # XXX: The style is different from that of DNF
  1077. print('===', cur_header, '===')
  1078. print(query_res[idx].name, ':', query_res[idx].summary)
  1079. def remove(
  1080. args: argparse.Namespace,
  1081. app: qubesadmin.app.QubesBase,
  1082. disassoc: bool = False,
  1083. purge: bool = False,
  1084. dummy: str = 'dummy'
  1085. ) -> None:
  1086. """Command that remove templates.
  1087. :param args: Arguments received by the application.
  1088. :param app: Qubes application object
  1089. :param disassoc: Whether to disassociate VMs from the templates
  1090. :param purge: Whether to remove VMs based on the templates
  1091. :param dummy: Name of dummy VM if disassoc is used
  1092. """
  1093. # NOTE: While QubesArgumentParser provide similar functionality
  1094. # it does not seem to work as a parent parser
  1095. for tpl in args.templates:
  1096. if tpl not in app.domains:
  1097. parser.error("no such domain: '%s'" % tpl)
  1098. remove_list = args.templates
  1099. if purge:
  1100. # Not disassociating first may result in dependency ordering issues
  1101. disassoc = True
  1102. # Remove recursively via BFS
  1103. remove_set = set(remove_list) # visited
  1104. idx = 0
  1105. while idx < len(remove_list):
  1106. tpl = remove_list[idx]
  1107. idx += 1
  1108. vm = app.domains[tpl]
  1109. for holder, prop in qubesadmin.utils.vm_dependencies(app, vm):
  1110. if holder is not None and holder.name not in remove_set:
  1111. remove_list.append(holder.name)
  1112. remove_set.add(holder.name)
  1113. if not args.yes:
  1114. repeat = 3 if purge else 1
  1115. for _ in range(repeat):
  1116. confirm_action(
  1117. 'This will completely remove the selected VM(s)...',
  1118. remove_list)
  1119. if disassoc:
  1120. # Remove the dummy afterwards if we're purging
  1121. remove_dummy = purge
  1122. # Create dummy template; handle name collisions
  1123. orig_dummy = dummy
  1124. cnt = 1
  1125. while dummy in app.domains \
  1126. and app.domains[dummy].features.get(
  1127. 'template-dummy', '0') == '0':
  1128. dummy = '%s-%d' % (orig_dummy, cnt)
  1129. cnt += 1
  1130. if dummy not in app.domains:
  1131. dummy_vm = app.add_new_vm('TemplateVM', dummy, 'red')
  1132. dummy_vm.features['template-dummy'] = 1
  1133. else:
  1134. dummy_vm = app.domains[dummy]
  1135. for tpl in remove_list:
  1136. vm = app.domains[tpl]
  1137. for holder, prop in qubesadmin.utils.vm_dependencies(app, vm):
  1138. if holder:
  1139. setattr(holder, prop, dummy_vm)
  1140. holder.template = dummy_vm
  1141. print("Property '%s' of '%s' set to '%s'." % (
  1142. prop, holder.name, dummy), file=sys.stderr)
  1143. else:
  1144. print("Global property '%s' set to ''." % prop,
  1145. file=sys.stderr)
  1146. setattr(app, prop, '')
  1147. if remove_dummy:
  1148. remove_list.append(dummy)
  1149. if disassoc or purge:
  1150. qubesadmin.tools.qvm_kill.main(['--'] + remove_list, app)
  1151. qubesadmin.tools.qvm_remove.main(['--force', '--'] + remove_list, app)
  1152. def clean(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
  1153. """Command that cleans the local package cache.
  1154. :param args: Arguments received by the application.
  1155. :param app: Qubes application object
  1156. """
  1157. # TODO: More fine-grained options
  1158. _ = app # unused
  1159. shutil.rmtree(args.cachedir)
  1160. def repolist(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
  1161. """Command that lists configured repositories.
  1162. :param args: Arguments received by the application.
  1163. :param app: Qubes application object
  1164. """
  1165. _ = app # unused
  1166. # python-dnf is not packaged on Debian
  1167. # As this is not an "essential operation", the module is imported here
  1168. # instead of top-level so that other operations still work.
  1169. try:
  1170. import dnf
  1171. except ModuleNotFoundError:
  1172. print("Error: Python module 'dnf' not found.", file=sys.stderr)
  1173. sys.exit(1)
  1174. if not args.all and not args.disabled:
  1175. args.enabled = True
  1176. with tempfile.TemporaryDirectory(dir=TEMP_DIR) as reposdir:
  1177. for idx, path in enumerate(args.repo_files):
  1178. src = os.path.abspath(path)
  1179. # Use index as file name in case of collisions
  1180. dst = os.path.join(reposdir, '%d.repo' % idx)
  1181. os.symlink(src, dst)
  1182. conf = dnf.conf.Conf()
  1183. conf.substitutions['releasever'] = args.releasever
  1184. conf.reposdir = reposdir
  1185. base = dnf.Base(conf)
  1186. base.read_all_repos()
  1187. if args.repoid:
  1188. base.repos.get_matching('*').disable()
  1189. for repo in args.repoid:
  1190. base.repos.get_matching(repo).enable()
  1191. else:
  1192. for repo in args.enablerepo:
  1193. base.repos.get_matching(repo).enable()
  1194. for repo in args.disablerepo:
  1195. base.repos.get_matching(repo).disable()
  1196. repos: typing.List[dnf.repo.Repo]
  1197. if args.repos:
  1198. repos = []
  1199. for repo in args.repos:
  1200. repos += list(base.repos.get_matching(repo))
  1201. repos = list(set(repos))
  1202. repos.sort(key=operator.attrgetter('id'))
  1203. else:
  1204. repos = list(base.repos.values())
  1205. repos.sort(key=operator.attrgetter('id'))
  1206. table = []
  1207. for repo in repos:
  1208. if args.all or (args.enabled == repo.enabled):
  1209. state = 'enabled' if repo.enabled else 'disabled'
  1210. table.append((repo.id, repo.name, state))
  1211. qubesadmin.tools.print_table(table)
  1212. def main(args: typing.Optional[typing.Sequence[str]] = None,
  1213. app: typing.Optional[qubesadmin.app.QubesBase] = None) -> int:
  1214. """Main routine of **qvm-template**.
  1215. :param args: Override arguments received by the application. Optional
  1216. :param app: Override Qubes application object. Optional
  1217. :return: Return code of the application
  1218. """
  1219. p_args = parser.parse_args(args)
  1220. # If the user specified other repo files...
  1221. if len(p_args.repo_files) > 1:
  1222. # ...remove the default entry
  1223. p_args.repo_files.pop(0)
  1224. if app is None:
  1225. app = qubesadmin.Qubes()
  1226. if p_args.refresh:
  1227. qrexec_repoquery(p_args, app, refresh=True)
  1228. if p_args.operation == 'download':
  1229. download(p_args, app)
  1230. elif p_args.operation == 'install':
  1231. install(p_args, app)
  1232. elif p_args.operation == 'reinstall':
  1233. install(p_args, app, version_selector=VersionSelector.REINSTALL,
  1234. override_existing=True)
  1235. elif p_args.operation == 'downgrade':
  1236. install(p_args, app, version_selector=VersionSelector.LATEST_LOWER,
  1237. override_existing=True)
  1238. elif p_args.operation == 'upgrade':
  1239. install(p_args, app, version_selector=VersionSelector.LATEST_HIGHER,
  1240. override_existing=True)
  1241. elif p_args.operation == 'list':
  1242. list_templates(p_args, app, 'list')
  1243. elif p_args.operation == 'info':
  1244. list_templates(p_args, app, 'info')
  1245. elif p_args.operation == 'search':
  1246. search(p_args, app)
  1247. elif p_args.operation == 'remove':
  1248. remove(p_args, app, disassoc=p_args.disassoc)
  1249. elif p_args.operation == 'purge':
  1250. remove(p_args, app, purge=True)
  1251. elif p_args.operation == 'clean':
  1252. clean(p_args, app)
  1253. elif p_args.operation == 'repolist':
  1254. repolist(p_args, app)
  1255. else:
  1256. parser.error('Operation \'%s\' not supported.' % p_args.operation)
  1257. return 0
  1258. if __name__ == '__main__':
  1259. sys.exit(main())