qvm_template.py 56 KB

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