qvm_template.py 58 KB

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