qvm_template.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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. 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. return hdr if nogpgcheck else None
  520. return None
  521. return hdr
  522. def extract_rpm(name: str, path: str, target: str) -> bool:
  523. """Extract a template RPM package.
  524. :param name: Name of the template
  525. :param path: Location of the RPM package
  526. :param target: Target path to extract to
  527. :return: Whether the extraction succeeded
  528. """
  529. rpm2cpio = subprocess.Popen(['rpm2cpio', path], stdout=subprocess.PIPE)
  530. # `-D` is GNUism
  531. cpio = subprocess.Popen([
  532. 'cpio',
  533. '-idm',
  534. '-D',
  535. target,
  536. '.%s/%s/*' % (PATH_PREFIX, name)
  537. ], stdin=rpm2cpio.stdout, stdout=subprocess.DEVNULL)
  538. return rpm2cpio.wait() == 0 and cpio.wait() == 0
  539. def get_dl_list(
  540. args: argparse.Namespace,
  541. app: qubesadmin.app.QubesBase,
  542. version_selector: VersionSelector = VersionSelector.LATEST
  543. ) -> typing.Dict[str, DlEntry]:
  544. """Return list of templates that needs to be downloaded.
  545. :param args: Arguments received by the application.
  546. :param app: Qubes application object
  547. :param version_selector: Specify algorithm to select the candidate version
  548. of a package. Defaults to ``VersionSelector.LATEST``
  549. :return: Dictionary that maps to ``DlEntry`` the names of templates that
  550. needs to be downloaded
  551. """
  552. full_candid: typing.Dict[str, DlEntry] = {}
  553. for template in args.templates:
  554. # This will be merged into `full_candid` later.
  555. # It is separated so that we can check whether it is empty.
  556. candid: typing.Dict[str, DlEntry] = {}
  557. # Skip local RPMs
  558. if template.endswith('.rpm'):
  559. continue
  560. query_res = qrexec_repoquery(args, app, PACKAGE_NAME_PREFIX + template)
  561. # We only select one package for each distinct package name
  562. for entry in query_res:
  563. ver = (entry.epoch, entry.version, entry.release)
  564. insert = False
  565. if version_selector == VersionSelector.LATEST:
  566. if entry.name not in candid \
  567. or rpm.labelCompare(candid[entry.name][0], ver) < 0:
  568. insert = True
  569. elif version_selector == VersionSelector.REINSTALL:
  570. vm = get_managed_template_vm(app, entry.name)
  571. cur_ver = query_local_evr(vm)
  572. if rpm.labelCompare(ver, cur_ver) == 0:
  573. insert = True
  574. elif version_selector in [VersionSelector.LATEST_LOWER,
  575. VersionSelector.LATEST_HIGHER]:
  576. vm = get_managed_template_vm(app, entry.name)
  577. cur_ver = query_local_evr(vm)
  578. cmp_res = -1 \
  579. if version_selector == VersionSelector.LATEST_LOWER \
  580. else 1
  581. if rpm.labelCompare(ver, cur_ver) == cmp_res:
  582. if entry.name not in candid \
  583. or rpm.labelCompare(candid[entry.name][0], ver) < 0:
  584. insert = True
  585. if insert:
  586. candid[entry.name] = DlEntry(ver, entry.reponame, entry.dlsize)
  587. # XXX: As it's possible to include version information in `template`,
  588. # perhaps the messages can be improved
  589. if len(candid) == 0:
  590. if version_selector == VersionSelector.LATEST:
  591. parser.error('Template \'%s\' not found.' % template)
  592. elif version_selector == VersionSelector.REINSTALL:
  593. parser.error('Same version of template \'%s\' not found.' \
  594. % template)
  595. # Copy behavior of DNF and do nothing if version not found
  596. elif version_selector == VersionSelector.LATEST_LOWER:
  597. print(("Template '%s' of lowest version"
  598. " already installed, skipping..." % template),
  599. file=sys.stderr)
  600. elif version_selector == VersionSelector.LATEST_HIGHER:
  601. print(("Template '%s' of highest version"
  602. " already installed, skipping..." % template),
  603. file=sys.stderr)
  604. # Merge & choose the template with the highest version
  605. for name, dlentry in candid.items():
  606. if name not in full_candid \
  607. or rpm.labelCompare(full_candid[name].evr, dlentry.evr) < 0:
  608. full_candid[name] = dlentry
  609. return full_candid
  610. def download(
  611. args: argparse.Namespace,
  612. app: qubesadmin.app.QubesBase,
  613. path_override: typing.Optional[str] = None,
  614. dl_list: typing.Optional[typing.Dict[str, DlEntry]] = None,
  615. suffix: str = '',
  616. version_selector: VersionSelector = VersionSelector.LATEST) -> None:
  617. """Command that downloads template packages.
  618. :param args: Arguments received by the application.
  619. :param app: Qubes application object
  620. :param path_override: Override path to store downloads. If not set or set
  621. to None, ``args.downloaddir`` is used. Optional
  622. :param dl_list: Override list of templates to download. If not set or set
  623. to None, ``get_dl_list`` is called, which generates the list from
  624. ``args``. Optional
  625. :param suffix: Suffix to add to the file name of downloaded packages. This
  626. is useful if you want to distinguish between verified and unverified
  627. packages. Defaults to an empty string
  628. :param version_selector: Specify algorithm to select the candidate version
  629. of a package. Defaults to ``VersionSelector.LATEST``
  630. """
  631. if dl_list is None:
  632. dl_list = get_dl_list(args, app, version_selector=version_selector)
  633. path = path_override if path_override is not None else args.downloaddir
  634. for name, entry in dl_list.items():
  635. version_str = build_version_str(entry.evr)
  636. spec = PACKAGE_NAME_PREFIX + name + '-' + version_str
  637. target = os.path.join(path, '%s.rpm' % spec)
  638. target_suffix = target + suffix
  639. if suffix != '' and os.path.exists(target_suffix):
  640. print('\'%s\' already exists, skipping...' % target,
  641. file=sys.stderr)
  642. if os.path.exists(target):
  643. print('\'%s\' already exists, skipping...' % target,
  644. file=sys.stderr)
  645. if suffix != '':
  646. os.rename(target, target_suffix)
  647. else:
  648. print('Downloading \'%s\'...' % spec, file=sys.stderr)
  649. done = False
  650. for attempt in range(args.retries):
  651. try:
  652. qrexec_download(args, app, spec, target_suffix,
  653. entry.dlsize)
  654. done = True
  655. break
  656. except ConnectionError:
  657. os.remove(target_suffix)
  658. if attempt + 1 < args.retries:
  659. print('\'%s\' download failed, retrying...' % spec,
  660. file=sys.stderr)
  661. except:
  662. # Also remove file if interrupted by other means
  663. os.remove(target_suffix)
  664. raise
  665. if not done:
  666. print('Error: \'%s\' download failed.' % spec, file=sys.stderr)
  667. sys.exit(1)
  668. def install(
  669. args: argparse.Namespace,
  670. app: qubesadmin.app.QubesBase,
  671. version_selector: VersionSelector = VersionSelector.LATEST,
  672. override_existing: bool = False) -> None:
  673. """Command that installs template packages.
  674. This command creates a lock file to ensure that two instances are not
  675. running at the same time.
  676. :param args: Arguments received by the application.
  677. :param app: Qubes application object
  678. :param version_selector: Specify algorithm to select the candidate version
  679. of a package. Defaults to ``VersionSelector.LATEST``
  680. :param override_existing: Whether to override existing packages. Used for
  681. reinstall, upgrade, and downgrade operations
  682. """
  683. try:
  684. with open(LOCK_FILE, 'x') as _:
  685. pass
  686. except FileExistsError:
  687. parser.error(('%s already exists.'
  688. ' Perhaps another instance of qvm-template is running?')
  689. % LOCK_FILE)
  690. try:
  691. transaction_set = rpm_transactionset(args.keyring)
  692. unverified_rpm_list = [] # rpmfile, reponame
  693. verified_rpm_list = []
  694. def verify(rpmfile, reponame):
  695. """Verify package signature and version, remove "unverified"
  696. suffix, and parse package header."""
  697. if reponame != '@commandline':
  698. path = rpmfile + UNVERIFIED_SUFFIX
  699. else:
  700. path = rpmfile
  701. package_hdr = verify_rpm(path, transaction_set, args.nogpgcheck)
  702. if not package_hdr:
  703. parser.error('Package \'%s\' verification failed.' % rpmfile)
  704. package_name = package_hdr[rpm.RPMTAG_NAME]
  705. if not package_name.startswith(PACKAGE_NAME_PREFIX):
  706. parser.error(
  707. 'Illegal package name for package \'%s\'.' % rpmfile)
  708. # Remove prefix to get the real template name
  709. name = package_name[len(PACKAGE_NAME_PREFIX):]
  710. if path != rpmfile:
  711. os.rename(path, rpmfile)
  712. # Check if already installed
  713. if not override_existing and name in app.domains:
  714. print(('Template \'%s\' already installed, skipping...'
  715. ' (You may want to use the'
  716. ' {reinstall,upgrade,downgrade}'
  717. ' operations.)') % name, file=sys.stderr)
  718. return
  719. # Check if version is really what we want
  720. if override_existing:
  721. vm = get_managed_template_vm(app, name)
  722. pkg_evr = (
  723. str(package_hdr[rpm.RPMTAG_EPOCHNUM]),
  724. package_hdr[rpm.RPMTAG_VERSION],
  725. package_hdr[rpm.RPMTAG_RELEASE])
  726. vm_evr = query_local_evr(vm)
  727. cmp_res = rpm.labelCompare(pkg_evr, vm_evr)
  728. if version_selector == VersionSelector.REINSTALL \
  729. and cmp_res != 0:
  730. parser.error(
  731. 'Same version of template \'%s\' not found.' \
  732. % name)
  733. elif version_selector == VersionSelector.LATEST_LOWER \
  734. and cmp_res != -1:
  735. print(("Template '%s' of lower version"
  736. " already installed, skipping..." % name),
  737. file=sys.stderr)
  738. return
  739. elif version_selector == VersionSelector.LATEST_HIGHER \
  740. and cmp_res != 1:
  741. print(("Template '%s' of higher version"
  742. " already installed, skipping..." % name),
  743. file=sys.stderr)
  744. return
  745. verified_rpm_list.append((rpmfile, reponame, name, package_hdr))
  746. # Process local templates
  747. for template in args.templates:
  748. if template.endswith('.rpm'):
  749. if not os.path.exists(template):
  750. parser.error('RPM file \'%s\' not found.' % template)
  751. unverified_rpm_list.append((template, '@commandline'))
  752. # First verify local RPMs and extract header
  753. for rpmfile, reponame in unverified_rpm_list:
  754. verify(rpmfile, reponame)
  755. unverified_rpm_list = []
  756. os.makedirs(args.cachedir, exist_ok=True)
  757. # Get list of templates to download
  758. dl_list = get_dl_list(args, app, version_selector=version_selector)
  759. dl_list_copy = dl_list.copy()
  760. for name, entry in dl_list.items():
  761. # Should be ensured by checks in repoquery
  762. assert entry.reponame != '@commandline'
  763. # Verify that the templates to be downloaded are not yet installed
  764. # Note that we *still* have to do this again in verify() for
  765. # already-downloaded templates
  766. if not override_existing and name in app.domains:
  767. print(('Template \'%s\' already installed, skipping...'
  768. ' (You may want to use the'
  769. ' {reinstall,upgrade,downgrade}'
  770. ' operations.)') % name, file=sys.stderr)
  771. del dl_list_copy[name]
  772. else:
  773. # XXX: Perhaps this is better returned by download()
  774. version_str = build_version_str(entry.evr)
  775. target_file = \
  776. '%s%s-%s.rpm' % (PACKAGE_NAME_PREFIX, name, version_str)
  777. unverified_rpm_list.append(
  778. (os.path.join(args.cachedir, target_file), entry.reponame))
  779. dl_list = dl_list_copy
  780. # Ask the user for confirmation before we actually download stuff
  781. if override_existing and not args.yes:
  782. override_tpls = []
  783. # Local templates, already verified
  784. for _, _, name, _ in verified_rpm_list:
  785. override_tpls.append(name)
  786. # Templates not yet downloaded
  787. for name in dl_list:
  788. override_tpls.append(name)
  789. confirm_action(
  790. 'This will override changes made in the following VMs:',
  791. override_tpls)
  792. download(args, app, path_override=args.cachedir,
  793. dl_list=dl_list, suffix=UNVERIFIED_SUFFIX,
  794. version_selector=version_selector)
  795. # Verify downloaded templates
  796. for rpmfile, reponame in unverified_rpm_list:
  797. verify(rpmfile, reponame)
  798. unverified_rpm_list = []
  799. # Unpack and install
  800. for rpmfile, reponame, name, package_hdr in verified_rpm_list:
  801. with tempfile.TemporaryDirectory(dir=TEMP_DIR) as target:
  802. print('Installing template \'%s\'...' % name, file=sys.stderr)
  803. extract_rpm(name, rpmfile, target)
  804. cmdline = [
  805. 'qvm-template-postprocess',
  806. '--really',
  807. '--no-installed-by-rpm',
  808. ]
  809. if args.allow_pv:
  810. cmdline.append('--allow-pv')
  811. if not override_existing and args.pool:
  812. cmdline += ['--pool', args.pool]
  813. subprocess.check_call(cmdline + [
  814. 'post-install',
  815. name,
  816. target + PATH_PREFIX + '/' + name])
  817. app.domains.refresh_cache(force=True)
  818. tpl = app.domains[name]
  819. tpl.features['template-name'] = name
  820. tpl.features['template-epoch'] = \
  821. package_hdr[rpm.RPMTAG_EPOCHNUM]
  822. tpl.features['template-version'] = \
  823. package_hdr[rpm.RPMTAG_VERSION]
  824. tpl.features['template-release'] = \
  825. package_hdr[rpm.RPMTAG_RELEASE]
  826. tpl.features['template-reponame'] = reponame
  827. tpl.features['template-buildtime'] = \
  828. str(datetime.datetime.fromtimestamp(
  829. int(package_hdr[rpm.RPMTAG_BUILDTIME])))
  830. tpl.features['template-installtime'] = \
  831. str(datetime.datetime.today())
  832. tpl.features['template-license'] = \
  833. package_hdr[rpm.RPMTAG_LICENSE]
  834. tpl.features['template-url'] = \
  835. package_hdr[rpm.RPMTAG_URL]
  836. tpl.features['template-summary'] = \
  837. package_hdr[rpm.RPMTAG_SUMMARY]
  838. tpl.features['template-description'] = \
  839. package_hdr[rpm.RPMTAG_DESCRIPTION].replace('\n', '|')
  840. finally:
  841. os.remove(LOCK_FILE)
  842. def list_templates(args: argparse.Namespace,
  843. app: qubesadmin.app.QubesBase, operation: str) -> None:
  844. """Command that lists templates.
  845. :param args: Arguments received by the application.
  846. :param app: Qubes application object
  847. :param operation: If set to ``list``, display a listing similar to ``dnf
  848. list``. If set to ``info``, display detailed template information
  849. similar to ``dnf info``. Otherwise, an ``AssertionError`` is raised.
  850. """
  851. tpl_list = []
  852. def append_list(data, status, install_time=None):
  853. _ = install_time # unused
  854. version_str = build_version_str(
  855. (data.epoch, data.version, data.release))
  856. tpl_list.append((status, data.name, version_str, data.reponame))
  857. def append_info(data, status, install_time=None):
  858. tpl_list.append((status, data, install_time))
  859. def list_to_human_output(tpls):
  860. outputs = []
  861. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  862. def convert(row):
  863. return row[1:]
  864. outputs.append((status, list(map(convert, grp))))
  865. return outputs
  866. def list_to_machine_output(tpls):
  867. outputs = {}
  868. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  869. def convert(row):
  870. _, name, evr, reponame = row
  871. return {'name': name, 'evr': evr, 'reponame': reponame}
  872. outputs[status.value] = list(map(convert, grp))
  873. return outputs
  874. def info_to_human_output(tpls):
  875. outputs = []
  876. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  877. output = []
  878. for _, data, install_time in grp:
  879. output.append(('Name', ':', data.name))
  880. output.append(('Epoch', ':', data.epoch))
  881. output.append(('Version', ':', data.version))
  882. output.append(('Release', ':', data.release))
  883. output.append(('Size', ':',
  884. qubesadmin.utils.size_to_human(data.dlsize)))
  885. output.append(('Repository', ':', data.reponame))
  886. output.append(('Buildtime', ':', str(data.buildtime)))
  887. if install_time:
  888. output.append(('Install time', ':', str(install_time)))
  889. output.append(('URL', ':', data.url))
  890. output.append(('License', ':', data.licence))
  891. output.append(('Summary', ':', data.summary))
  892. # Only show "Description" for the first line
  893. title = 'Description'
  894. for line in data.description.splitlines():
  895. output.append((title, ':', line))
  896. title = ''
  897. output.append((' ', ' ', ' ')) # empty line
  898. outputs.append((status, output))
  899. return outputs
  900. def info_to_machine_output(tpls, replace_newline=True):
  901. outputs = {}
  902. for status, grp in itertools.groupby(tpls, lambda x: x[0]):
  903. output = []
  904. for _, data, install_time in grp:
  905. name, epoch, version, release, reponame, dlsize, \
  906. buildtime, licence, url, summary, description = data
  907. dlsize = str(dlsize)
  908. buildtime = str(buildtime)
  909. install_time = str(install_time) if install_time else ''
  910. if replace_newline:
  911. description = description.replace('\n', '|')
  912. output.append({
  913. 'name': name,
  914. 'epoch': epoch,
  915. 'version': version,
  916. 'release': release,
  917. 'reponame': reponame,
  918. 'size': dlsize,
  919. 'buildtime': buildtime,
  920. 'installtime': install_time,
  921. 'license': licence,
  922. 'url': url,
  923. 'summary': summary,
  924. 'description': description})
  925. outputs[status.value] = output
  926. return outputs
  927. if operation == 'list':
  928. append = append_list
  929. elif operation == 'info':
  930. append = append_info
  931. else:
  932. assert False and 'Unknown operation'
  933. def append_vm(vm, status):
  934. append(query_local(vm), status, vm.features['template-installtime'])
  935. if not (args.installed or args.available or args.extras or args.upgrades):
  936. args.all = True
  937. if args.all or args.available or args.extras or args.upgrades:
  938. if args.templates:
  939. query_res_set: typing.Set[Template] = set()
  940. for spec in args.templates:
  941. query_res_set |= set(qrexec_repoquery(args, app, spec))
  942. query_res = list(query_res_set)
  943. else:
  944. query_res = qrexec_repoquery(args, app)
  945. if args.installed or args.all:
  946. for vm in app.domains:
  947. if is_managed_template(vm):
  948. if not args.templates or \
  949. any(is_match_spec(
  950. vm.name,
  951. *query_local_evr(vm),
  952. spec)[0]
  953. for spec in args.templates):
  954. append_vm(vm, TemplateState.INSTALLED)
  955. if args.available or args.all:
  956. for data in query_res:
  957. append(data, TemplateState.AVAILABLE)
  958. if args.extras:
  959. remote = set()
  960. for data in query_res:
  961. remote.add(data.name)
  962. for vm in app.domains:
  963. if is_managed_template(vm) and vm.name not in remote:
  964. append_vm(vm, TemplateState.EXTRA)
  965. if args.upgrades:
  966. local = {}
  967. for vm in app.domains:
  968. if is_managed_template(vm):
  969. local[vm.name] = query_local_evr(vm)
  970. for entry in query_res:
  971. if entry.name in local:
  972. if rpm.labelCompare(local[entry.name],
  973. (entry.epoch, entry.version, entry.release)) < 0:
  974. append(entry, TemplateState.UPGRADABLE)
  975. if len(tpl_list) == 0:
  976. parser.error('No matching templates to list')
  977. if args.machine_readable:
  978. if operation == 'info':
  979. tpl_list = info_to_machine_output(tpl_list)
  980. elif operation == 'list':
  981. tpl_list = list_to_machine_output(tpl_list)
  982. for status, grp in tpl_list.items():
  983. for line in grp:
  984. print('|'.join([status] + list(line.values())))
  985. elif args.machine_readable_json:
  986. if operation == 'info':
  987. tpl_list = info_to_machine_output(tpl_list, replace_newline=False)
  988. elif operation == 'list':
  989. tpl_list = list_to_machine_output(tpl_list)
  990. print(json.dumps(tpl_list))
  991. else:
  992. if operation == 'info':
  993. tpl_list = info_to_human_output(tpl_list)
  994. elif operation == 'list':
  995. tpl_list = list_to_human_output(tpl_list)
  996. for status, grp in tpl_list:
  997. print(status.title())
  998. qubesadmin.tools.print_table(grp)
  999. def search(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
  1000. """Command that searches template details for given patterns.
  1001. :param args: Arguments received by the application.
  1002. :param app: Qubes application object
  1003. """
  1004. # Search in both installed and available templates
  1005. query_res = qrexec_repoquery(args, app)
  1006. for vm in app.domains:
  1007. if is_managed_template(vm):
  1008. query_res.append(query_local(vm))
  1009. # Get latest version for each template
  1010. query_res_tmp = []
  1011. for _, grp in itertools.groupby(sorted(query_res), lambda x: x[0]):
  1012. def compare(lhs, rhs):
  1013. return lhs if rpm.labelCompare(lhs[1:4], rhs[1:4]) < 0 else rhs
  1014. query_res_tmp.append(functools.reduce(compare, grp))
  1015. query_res = query_res_tmp
  1016. #pylint: disable=invalid-name
  1017. WEIGHT_NAME_EXACT = 1 << 4
  1018. WEIGHT_NAME = 1 << 3
  1019. WEIGHT_SUMMARY = 1 << 2
  1020. WEIGHT_DESCRIPTION = 1 << 1
  1021. WEIGHT_URL = 1 << 0
  1022. WEIGHT_TO_FIELD = [
  1023. (WEIGHT_NAME_EXACT, 'Name'),
  1024. (WEIGHT_NAME, 'Name'),
  1025. (WEIGHT_SUMMARY, 'Summary'),
  1026. (WEIGHT_DESCRIPTION, 'Description'),
  1027. (WEIGHT_URL, 'URL')]
  1028. search_res_by_idx: \
  1029. typing.Dict[int, typing.List[typing.Tuple[int, str, bool]]] = \
  1030. collections.defaultdict(list)
  1031. for keyword in args.templates:
  1032. for idx, entry in enumerate(query_res):
  1033. needle_types = \
  1034. [(entry.name, WEIGHT_NAME), (entry.summary, WEIGHT_SUMMARY)]
  1035. if args.all:
  1036. needle_types += [(entry.description, WEIGHT_DESCRIPTION),
  1037. (entry.url, WEIGHT_URL)]
  1038. for key, weight in needle_types:
  1039. if fnmatch.fnmatch(key, '*' + keyword + '*'):
  1040. exact = keyword == key
  1041. if exact and weight == WEIGHT_NAME:
  1042. weight = WEIGHT_NAME_EXACT
  1043. search_res_by_idx[idx].append((weight, keyword, exact))
  1044. if not args.all:
  1045. keywords = set(args.templates)
  1046. idxs = list(search_res_by_idx.keys())
  1047. for idx in idxs:
  1048. if keywords != set(x[1] for x in search_res_by_idx[idx]):
  1049. del search_res_by_idx[idx]
  1050. def key_func(x):
  1051. # ORDER BY weight DESC, list_of_needles ASC, name ASC
  1052. idx, needles = x
  1053. weight = sum(t[0] for t in needles)
  1054. name = query_res[idx][0]
  1055. return (-weight, needles, name)
  1056. search_res = sorted(search_res_by_idx.items(), key=key_func)
  1057. def gen_header(needles):
  1058. fields = []
  1059. weight_types = set(x[0] for x in needles)
  1060. for weight, field in WEIGHT_TO_FIELD:
  1061. if weight in weight_types:
  1062. fields.append(field)
  1063. exact = all(x[-1] for x in needles)
  1064. match = 'Exactly Matched' if exact else 'Matched'
  1065. keywords = sorted(list(set(x[1] for x in needles)))
  1066. return ' & '.join(fields) + ' ' + match + ': ' + ', '.join(keywords)
  1067. last_header = ''
  1068. for idx, needles in search_res:
  1069. # Print headers
  1070. cur_header = gen_header(needles)
  1071. if last_header != cur_header:
  1072. last_header = cur_header
  1073. # XXX: The style is different from that of DNF
  1074. print('===', cur_header, '===')
  1075. print(query_res[idx].name, ':', query_res[idx].summary)
  1076. def remove(
  1077. args: argparse.Namespace,
  1078. app: qubesadmin.app.QubesBase,
  1079. disassoc: bool = False,
  1080. purge: bool = False,
  1081. dummy: str = 'dummy'
  1082. ) -> None:
  1083. """Command that remove templates.
  1084. :param args: Arguments received by the application.
  1085. :param app: Qubes application object
  1086. :param disassoc: Whether to disassociate VMs from the templates
  1087. :param purge: Whether to remove VMs based on the templates
  1088. :param dummy: Name of dummy VM if disassoc is used
  1089. """
  1090. # NOTE: While QubesArgumentParser provide similar functionality
  1091. # it does not seem to work as a parent parser
  1092. for tpl in args.templates:
  1093. if tpl not in app.domains:
  1094. parser.error("no such domain: '%s'" % tpl)
  1095. remove_list = args.templates
  1096. if purge:
  1097. # Not disassociating first may result in dependency ordering issues
  1098. disassoc = True
  1099. # Remove recursively via BFS
  1100. remove_set = set(remove_list) # visited
  1101. idx = 0
  1102. while idx < len(remove_list):
  1103. tpl = remove_list[idx]
  1104. idx += 1
  1105. vm = app.domains[tpl]
  1106. for holder, prop in qubesadmin.utils.vm_dependencies(app, vm):
  1107. if holder is not None and holder.name not in remove_set:
  1108. remove_list.append(holder.name)
  1109. remove_set.add(holder.name)
  1110. if not args.yes:
  1111. repeat = 3 if purge else 1
  1112. for _ in range(repeat):
  1113. confirm_action(
  1114. 'This will completely remove the selected VM(s)...',
  1115. remove_list)
  1116. if disassoc:
  1117. # Remove the dummy afterwards if we're purging
  1118. remove_dummy = purge
  1119. # Create dummy template; handle name collisions
  1120. orig_dummy = dummy
  1121. cnt = 1
  1122. while dummy in app.domains \
  1123. and app.domains[dummy].features.get(
  1124. 'template-dummy', '0') == '0':
  1125. dummy = '%s-%d' % (orig_dummy, cnt)
  1126. cnt += 1
  1127. if dummy not in app.domains:
  1128. dummy_vm = app.add_new_vm('TemplateVM', dummy, 'red')
  1129. dummy_vm.features['template-dummy'] = 1
  1130. else:
  1131. dummy_vm = app.domains[dummy]
  1132. for tpl in remove_list:
  1133. vm = app.domains[tpl]
  1134. for holder, prop in qubesadmin.utils.vm_dependencies(app, vm):
  1135. if holder:
  1136. setattr(holder, prop, dummy_vm)
  1137. holder.template = dummy_vm
  1138. print("Property '%s' of '%s' set to '%s'." % (
  1139. prop, holder.name, dummy), file=sys.stderr)
  1140. else:
  1141. print("Global property '%s' set to ''." % prop,
  1142. file=sys.stderr)
  1143. setattr(app, prop, '')
  1144. if remove_dummy:
  1145. remove_list.append(dummy)
  1146. if disassoc or purge:
  1147. qubesadmin.tools.qvm_kill.main(['--'] + remove_list, app)
  1148. qubesadmin.tools.qvm_remove.main(['--force', '--'] + remove_list, app)
  1149. def clean(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
  1150. """Command that cleans the local package cache.
  1151. :param args: Arguments received by the application.
  1152. :param app: Qubes application object
  1153. """
  1154. # TODO: More fine-grained options
  1155. _ = app # unused
  1156. shutil.rmtree(args.cachedir)
  1157. def repolist(args: argparse.Namespace, app: qubesadmin.app.QubesBase) -> None:
  1158. """Command that lists configured repositories.
  1159. :param args: Arguments received by the application.
  1160. :param app: Qubes application object
  1161. """
  1162. _ = app # unused
  1163. # python-dnf is not packaged on Debian
  1164. # As this is not an "essential operation", the module is imported here
  1165. # instead of top-level so that other operations still work.
  1166. try:
  1167. import dnf
  1168. except ModuleNotFoundError:
  1169. print("Error: Python module 'dnf' not found.", file=sys.stderr)
  1170. sys.exit(1)
  1171. if not args.all and not args.disabled:
  1172. args.enabled = True
  1173. with tempfile.TemporaryDirectory(dir=TEMP_DIR) as reposdir:
  1174. for idx, path in enumerate(args.repo_files):
  1175. src = os.path.abspath(path)
  1176. # Use index as file name in case of collisions
  1177. dst = os.path.join(reposdir, '%d.repo' % idx)
  1178. os.symlink(src, dst)
  1179. conf = dnf.conf.Conf()
  1180. conf.substitutions['releasever'] = args.releasever
  1181. conf.reposdir = reposdir
  1182. base = dnf.Base(conf)
  1183. base.read_all_repos()
  1184. if args.repoid:
  1185. base.repos.get_matching('*').disable()
  1186. for repo in args.repoid:
  1187. base.repos.get_matching(repo).enable()
  1188. else:
  1189. for repo in args.enablerepo:
  1190. base.repos.get_matching(repo).enable()
  1191. for repo in args.disablerepo:
  1192. base.repos.get_matching(repo).disable()
  1193. repos: typing.List[dnf.repo.Repo]
  1194. if args.repos:
  1195. repos = []
  1196. for repo in args.repos:
  1197. repos += list(base.repos.get_matching(repo))
  1198. repos = list(set(repos))
  1199. repos.sort(key=operator.attrgetter('id'))
  1200. else:
  1201. repos = list(base.repos.values())
  1202. repos.sort(key=operator.attrgetter('id'))
  1203. table = []
  1204. for repo in repos:
  1205. if args.all or (args.enabled == repo.enabled):
  1206. state = 'enabled' if repo.enabled else 'disabled'
  1207. table.append((repo.id, repo.name, state))
  1208. qubesadmin.tools.print_table(table)
  1209. def main(args: typing.Optional[typing.Sequence[str]] = None,
  1210. app: typing.Optional[qubesadmin.app.QubesBase] = None) -> int:
  1211. """Main routine of **qvm-template**.
  1212. :param args: Override arguments received by the application. Optional
  1213. :param app: Override Qubes application object. Optional
  1214. :return: Return code of the application
  1215. """
  1216. p_args = parser.parse_args(args)
  1217. # If the user specified other repo files...
  1218. if len(p_args.repo_files) > 1:
  1219. # ...remove the default entry
  1220. p_args.repo_files.pop(0)
  1221. if app is None:
  1222. app = qubesadmin.Qubes()
  1223. if p_args.refresh:
  1224. qrexec_repoquery(p_args, app, refresh=True)
  1225. if p_args.operation == 'download':
  1226. download(p_args, app)
  1227. elif p_args.operation == 'install':
  1228. install(p_args, app)
  1229. elif p_args.operation == 'reinstall':
  1230. install(p_args, app, version_selector=VersionSelector.REINSTALL,
  1231. override_existing=True)
  1232. elif p_args.operation == 'downgrade':
  1233. install(p_args, app, version_selector=VersionSelector.LATEST_LOWER,
  1234. override_existing=True)
  1235. elif p_args.operation == 'upgrade':
  1236. install(p_args, app, version_selector=VersionSelector.LATEST_HIGHER,
  1237. override_existing=True)
  1238. elif p_args.operation == 'list':
  1239. list_templates(p_args, app, 'list')
  1240. elif p_args.operation == 'info':
  1241. list_templates(p_args, app, 'info')
  1242. elif p_args.operation == 'search':
  1243. search(p_args, app)
  1244. elif p_args.operation == 'remove':
  1245. remove(p_args, app, disassoc=p_args.disassoc)
  1246. elif p_args.operation == 'purge':
  1247. remove(p_args, app, purge=True)
  1248. elif p_args.operation == 'clean':
  1249. clean(p_args, app)
  1250. elif p_args.operation == 'repolist':
  1251. repolist(p_args, app)
  1252. else:
  1253. parser.error('Operation \'%s\' not supported.' % p_args.operation)
  1254. return 0
  1255. if __name__ == '__main__':
  1256. sys.exit(main())