qvm_template.py 57 KB

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