qvm_template.py 56 KB

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