app.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. '''
  21. Main Qubes() class and related classes.
  22. '''
  23. import os
  24. import shlex
  25. import socket
  26. import subprocess
  27. import sys
  28. import logging
  29. import qubesadmin.base
  30. import qubesadmin.exc
  31. import qubesadmin.label
  32. import qubesadmin.storage
  33. import qubesadmin.utils
  34. import qubesadmin.vm
  35. import qubesadmin.config
  36. BUF_SIZE = 4096
  37. class VMCollection(object):
  38. '''Collection of VMs objects'''
  39. def __init__(self, app):
  40. self.app = app
  41. self._vm_list = None
  42. self._vm_objects = {}
  43. def clear_cache(self):
  44. '''Clear cached list of VMs'''
  45. self._vm_list = None
  46. def refresh_cache(self, force=False):
  47. '''Refresh cached list of VMs'''
  48. if not force and self._vm_list is not None:
  49. return
  50. vm_list_data = self.app.qubesd_call(
  51. 'dom0',
  52. 'admin.vm.List'
  53. )
  54. new_vm_list = {}
  55. # FIXME: this will probably change
  56. for vm_data in vm_list_data.splitlines():
  57. vm_name, props = vm_data.decode('ascii').split(' ', 1)
  58. vm_name = str(vm_name)
  59. props = props.split(' ')
  60. new_vm_list[vm_name] = dict(
  61. [vm_prop.split('=', 1) for vm_prop in props])
  62. self._vm_list = new_vm_list
  63. for name, vm in list(self._vm_objects.items()):
  64. if vm.name not in self._vm_list:
  65. # VM no longer exists
  66. del self._vm_objects[name]
  67. elif vm.__class__.__name__ != self._vm_list[vm.name]['class']:
  68. # VM class have changed
  69. del self._vm_objects[name]
  70. # TODO: some generation ID, to detect VM re-creation
  71. elif name != vm.name:
  72. # renamed
  73. self._vm_objects[vm.name] = vm
  74. del self._vm_objects[name]
  75. def __getitem__(self, item):
  76. if not self.app.blind_mode and item not in self:
  77. raise KeyError(item)
  78. return self.get_blind(item)
  79. def get_blind(self, item):
  80. '''
  81. Get a vm without downloading the list
  82. and checking if exists
  83. '''
  84. if item not in self._vm_objects:
  85. cls = qubesadmin.vm.QubesVM
  86. # provide class name to constructor, if already cached (which can be
  87. # done by 'item not in self' check above, unless blind_mode is
  88. # enabled
  89. klass = None
  90. if self._vm_list and item in self._vm_list:
  91. klass = self._vm_list[item]['class']
  92. self._vm_objects[item] = cls(self.app, item, klass=klass)
  93. return self._vm_objects[item]
  94. def __contains__(self, item):
  95. self.refresh_cache()
  96. return item in self._vm_list
  97. def __delitem__(self, key):
  98. self.app.qubesd_call(key, 'admin.vm.Remove')
  99. self.clear_cache()
  100. def __iter__(self):
  101. self.refresh_cache()
  102. for vm in sorted(self._vm_list):
  103. yield self[vm]
  104. def keys(self):
  105. '''Get list of VM names.'''
  106. self.refresh_cache()
  107. return self._vm_list.keys()
  108. def values(self):
  109. '''Get list of VM objects.'''
  110. self.refresh_cache()
  111. return [self[name] for name in self._vm_list]
  112. class QubesBase(qubesadmin.base.PropertyHolder):
  113. '''Main Qubes application.
  114. This is a base abstract class, don't use it directly. Use specialized
  115. class in py:class:`qubesadmin.Qubes` instead, which points at
  116. :py:class:`QubesLocal` or :py:class:`QubesRemote`.
  117. '''
  118. #: domains (VMs) collection
  119. domains = None
  120. #: labels collection
  121. labels = None
  122. #: storage pools
  123. pools = None
  124. #: type of qubesd connection: either 'socket' or 'qrexec'
  125. qubesd_connection_type = None
  126. #: logger
  127. log = None
  128. #: do not check for object (VM, label etc) existence before really needed
  129. blind_mode = False
  130. def __init__(self):
  131. super(QubesBase, self).__init__(self, 'admin.property.', 'dom0')
  132. self.domains = VMCollection(self)
  133. self.labels = qubesadmin.base.WrapperObjectsCollection(
  134. self, 'admin.label.List', qubesadmin.label.Label)
  135. self.pools = qubesadmin.base.WrapperObjectsCollection(
  136. self, 'admin.pool.List', qubesadmin.storage.Pool)
  137. #: cache for available storage pool drivers and options to create them
  138. self._pool_drivers = None
  139. self.log = logging.getLogger('app')
  140. def _refresh_pool_drivers(self):
  141. '''
  142. Refresh cached storage pool drivers and their parameters.
  143. :return: None
  144. '''
  145. if self._pool_drivers is None:
  146. pool_drivers_data = self.qubesd_call(
  147. 'dom0', 'admin.pool.ListDrivers', None, None)
  148. assert pool_drivers_data.endswith(b'\n')
  149. pool_drivers = {}
  150. for driver_line in pool_drivers_data.decode('ascii').splitlines():
  151. if not driver_line:
  152. continue
  153. driver_name, driver_options = driver_line.split(' ', 1)
  154. pool_drivers[driver_name] = driver_options.split(' ')
  155. self._pool_drivers = pool_drivers
  156. @property
  157. def pool_drivers(self):
  158. ''' Available storage pool drivers '''
  159. self._refresh_pool_drivers()
  160. return self._pool_drivers.keys()
  161. def pool_driver_parameters(self, driver):
  162. ''' Parameters to initialize storage pool using given driver '''
  163. self._refresh_pool_drivers()
  164. return self._pool_drivers[driver]
  165. def add_pool(self, name, driver, **kwargs):
  166. ''' Add a storage pool to config
  167. :param name: name of storage pool to create
  168. :param driver: driver to use, see :py:meth:`pool_drivers` for
  169. available drivers
  170. :param kwargs: configuration parameters for storage pool,
  171. see :py:meth:`pool_driver_parameters` for a list
  172. '''
  173. # sort parameters only to ease testing, not required by API
  174. payload = 'name={}\n'.format(name) + \
  175. ''.join('{}={}\n'.format(key, value)
  176. for key, value in sorted(kwargs.items()))
  177. self.qubesd_call('dom0', 'admin.pool.Add', driver,
  178. payload.encode('utf-8'))
  179. def remove_pool(self, name):
  180. ''' Remove a storage pool '''
  181. self.qubesd_call('dom0', 'admin.pool.Remove', name, None)
  182. def get_label(self, label):
  183. '''Get label as identified by index or name
  184. :throws KeyError: when label is not found
  185. '''
  186. # first search for name, verbatim
  187. try:
  188. return self.labels[label]
  189. except KeyError:
  190. pass
  191. # then search for index
  192. if isinstance(label, int) or label.isdigit():
  193. for i in self.labels.values():
  194. if i.index == int(label):
  195. return i
  196. raise KeyError(label)
  197. @staticmethod
  198. def get_vm_class(clsname):
  199. '''Find the class for a domain.
  200. Compatibility function, client tools use str to identify domain classes.
  201. :param str clsname: name of the class
  202. :return str: class
  203. '''
  204. return clsname
  205. def add_new_vm(self, cls, name, label, template=None, pool=None,
  206. pools=None):
  207. '''Create new Virtual Machine
  208. Example usage with custom storage pools:
  209. >>> app = qubesadmin.Qubes()
  210. >>> pools = {'private': 'external'}
  211. >>> vm = app.add_new_vm('AppVM', 'my-new-vm', 'red',
  212. >>> 'my-template', pools=pools)
  213. >>> vm.netvm = app.domains['sys-whonix']
  214. :param str cls: name of VM class (`AppVM`, `TemplateVM` etc)
  215. :param str name: name of VM
  216. :param str label: label color for new VM
  217. :param str template: template to use (if apply for given VM class),
  218. can be also VM object; use None for default value
  219. :param str pool: storage pool to use instead of default one
  220. :param dict pools: storage pool for specific volumes
  221. :return new VM object
  222. '''
  223. if not isinstance(cls, str):
  224. cls = cls.__name__
  225. if template is qubesadmin.DEFAULT:
  226. template = None
  227. elif template is not None:
  228. template = str(template)
  229. if pool and pools:
  230. raise ValueError('only one of pool= and pools= can be used')
  231. method_prefix = 'admin.vm.Create.'
  232. payload = 'name={} label={}'.format(name, label)
  233. if pool:
  234. payload += ' pool={}'.format(str(pool))
  235. method_prefix = 'admin.vm.CreateInPool.'
  236. if pools:
  237. payload += ''.join(' pool:{}={}'.format(vol, str(pool))
  238. for vol, pool in sorted(pools.items()))
  239. method_prefix = 'admin.vm.CreateInPool.'
  240. self.qubesd_call('dom0', method_prefix + cls, template,
  241. payload.encode('utf-8'))
  242. self.domains.clear_cache()
  243. return self.domains[name]
  244. def clone_vm(self, src_vm, new_name, new_cls=None,
  245. pool=None, pools=None, ignore_errors=False, ignore_volumes=None):
  246. '''Clone Virtual Machine
  247. Example usage with custom storage pools:
  248. >>> app = qubesadmin.Qubes()
  249. >>> pools = {'private': 'external'}
  250. >>> src_vm = app.domains['personal']
  251. >>> vm = app.clone_vm(src_vm, 'my-new-vm', pools=pools)
  252. >>> vm.label = app.labels['green']
  253. :param QubesVM or str src_vm: source VM
  254. :param str new_name: name of new VM
  255. :param str new_cls: name of VM class (`AppVM`, `TemplateVM` etc) - use
  256. None to copy it from *src_vm*
  257. :param str pool: storage pool to use instead of default one
  258. :param dict pools: storage pool for specific volumes
  259. :param bool ignore_errors: should errors on meta-data setting be only
  260. logged, or abort the whole operation?
  261. :param list ignore_volumes: do not clone volumes on this list,
  262. like 'private' or 'root'
  263. :return new VM object
  264. '''
  265. if pool and pools:
  266. raise ValueError('only one of pool= and pools= can be used')
  267. if isinstance(src_vm, str):
  268. src_vm = self.domains[src_vm]
  269. if new_cls is None:
  270. new_cls = src_vm.klass
  271. template = getattr(src_vm, 'template', None)
  272. if template is not None:
  273. template = str(template)
  274. label = src_vm.label
  275. method_prefix = 'admin.vm.Create.'
  276. payload = 'name={} label={}'.format(new_name, label)
  277. if pool:
  278. payload += ' pool={}'.format(str(pool))
  279. method_prefix = 'admin.vm.CreateInPool.'
  280. if pools:
  281. payload += ''.join(' pool:{}={}'.format(vol, str(pool))
  282. for vol, pool in sorted(pools.items()))
  283. method_prefix = 'admin.vm.CreateInPool.'
  284. self.qubesd_call('dom0', method_prefix + new_cls, template,
  285. payload.encode('utf-8'))
  286. self.domains.clear_cache()
  287. dst_vm = self.domains[new_name]
  288. try:
  289. assert isinstance(dst_vm, qubesadmin.vm.QubesVM)
  290. for prop in src_vm.property_list():
  291. # handled by admin.vm.Create call
  292. if prop in ('name', 'qid', 'template', 'label', 'uuid',
  293. 'installed_by_rpm'):
  294. continue
  295. if src_vm.property_is_default(prop):
  296. continue
  297. try:
  298. setattr(dst_vm, prop, getattr(src_vm, prop))
  299. except AttributeError:
  300. pass
  301. except qubesadmin.exc.QubesException as e:
  302. dst_vm.log.error(
  303. 'Failed to set {!s} property: {!s}'.format(prop, e))
  304. if not ignore_errors:
  305. raise
  306. for tag in src_vm.tags:
  307. if tag.startswith('created-by-'):
  308. continue
  309. try:
  310. dst_vm.tags.add(tag)
  311. except qubesadmin.exc.QubesException as e:
  312. dst_vm.log.error(
  313. 'Failed to add {!s} tag: {!s}'.format(tag, e))
  314. if not ignore_errors:
  315. raise
  316. for feature, value in src_vm.features.items():
  317. try:
  318. dst_vm.features[feature] = value
  319. except qubesadmin.exc.QubesException as e:
  320. dst_vm.log.error(
  321. 'Failed to set {!s} feature: {!s}'.format(feature, e))
  322. if not ignore_errors:
  323. raise
  324. try:
  325. dst_vm.firewall.save_rules(src_vm.firewall.rules)
  326. except qubesadmin.exc.QubesException as e:
  327. self.log.error('Failed to set firewall: %s', e)
  328. if not ignore_errors:
  329. raise
  330. try:
  331. # FIXME: convert to qrexec calls to dom0/GUI VM
  332. appmenus_cmd = \
  333. ['qvm-appmenus', '--init', '--update',
  334. '--source', src_vm.name, dst_vm.name]
  335. subprocess.check_output(appmenus_cmd, stderr=subprocess.STDOUT)
  336. except OSError:
  337. # this file needs to be python 2.7 compatible,
  338. # so no FileNotFoundError
  339. self.log.error('Failed to clone appmenus, qvm-appmenus missing')
  340. if not ignore_errors:
  341. raise qubesadmin.exc.QubesException(
  342. 'Failed to clone appmenus')
  343. except subprocess.CalledProcessError as e:
  344. self.log.error('Failed to clone appmenus: %s',
  345. e.output.decode())
  346. if not ignore_errors:
  347. raise qubesadmin.exc.QubesException(
  348. 'Failed to clone appmenus')
  349. except qubesadmin.exc.QubesException:
  350. if not ignore_errors:
  351. del self.domains[dst_vm.name]
  352. raise
  353. try:
  354. for dst_volume in sorted(dst_vm.volumes.values()):
  355. if not dst_volume.save_on_stop:
  356. # clone only persistent volumes
  357. continue
  358. if ignore_volumes and dst_volume.name in ignore_volumes:
  359. continue
  360. src_volume = src_vm.volumes[dst_volume.name]
  361. dst_vm.log.info('Cloning {} volume'.format(dst_volume.name))
  362. dst_volume.clone(src_volume)
  363. except qubesadmin.exc.QubesException:
  364. del self.domains[dst_vm.name]
  365. raise
  366. return dst_vm
  367. def qubesd_call(self, dest, method, arg=None, payload=None,
  368. payload_stream=None):
  369. '''
  370. Execute Admin API method.
  371. Only one of `payload` and `payload_stream` can be specified.
  372. :param dest: Destination VM name
  373. :param method: Full API method name ('admin...')
  374. :param arg: Method argument (if any)
  375. :param payload: Payload send to the method
  376. :param payload_stream: file-like object to read payload from
  377. :return: Data returned by qubesd (string)
  378. .. warning:: *payload_stream* will get closed by this function
  379. '''
  380. raise NotImplementedError(
  381. 'qubesd_call not implemented in QubesBase class; use specialized '
  382. 'class: qubesadmin.Qubes()')
  383. def run_service(self, dest, service, filter_esc=False, user=None,
  384. localcmd=None, wait=True, **kwargs):
  385. '''Run qrexec service in a given destination
  386. *kwargs* are passed verbatim to :py:meth:`subprocess.Popen`.
  387. :param str dest: Destination - may be a VM name or empty
  388. string for default (for a given service)
  389. :param str service: service name
  390. :param bool filter_esc: filter escape sequences to protect terminal \
  391. emulator
  392. :param str user: username to run service as
  393. :param str localcmd: Command to connect stdin/stdout to
  394. :rtype: subprocess.Popen
  395. '''
  396. raise NotImplementedError(
  397. 'run_service not implemented in QubesBase class; use specialized '
  398. 'class: qubesadmin.Qubes()')
  399. class QubesLocal(QubesBase):
  400. '''Application object communicating through local socket.
  401. Used when running in dom0.
  402. '''
  403. qubesd_connection_type = 'socket'
  404. def qubesd_call(self, dest, method, arg=None, payload=None,
  405. payload_stream=None):
  406. '''
  407. Execute Admin API method.
  408. Only one of `payload` and `payload_stream` can be specified.
  409. :param dest: Destination VM name
  410. :param method: Full API method name ('admin...')
  411. :param arg: Method argument (if any)
  412. :param payload: Payload send to the method
  413. :param payload_stream: file-like object to read payload from
  414. :return: Data returned by qubesd (string)
  415. .. warning:: *payload_stream* will get closed by this function
  416. '''
  417. if payload and payload_stream:
  418. raise ValueError(
  419. 'Only one of payload and payload_stream can be used')
  420. if payload_stream:
  421. # payload_stream can be used for large amount of data,
  422. # so optimize for throughput, not latency: spawn actual qrexec
  423. # service implementation, which may use some optimization there (
  424. # see admin.vm.volume.Import - actual data handling is done with dd)
  425. method_path = os.path.join(
  426. qubesadmin.config.QREXEC_SERVICES_DIR, method)
  427. if not os.path.exists(method_path):
  428. raise qubesadmin.exc.QubesDaemonCommunicationError(
  429. '{} not found'.format(method_path))
  430. command = ['env', 'QREXEC_REMOTE_DOMAIN=dom0',
  431. 'QREXEC_REQUESTED_TARGET=' + dest, method_path, arg]
  432. if os.getuid() != 0:
  433. command.insert(0, 'sudo')
  434. proc = subprocess.Popen(command, stdin=payload_stream,
  435. stdout=subprocess.PIPE)
  436. payload_stream.close()
  437. (return_data, _) = proc.communicate()
  438. return self._parse_qubesd_response(return_data)
  439. try:
  440. client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  441. client_socket.connect(qubesadmin.config.QUBESD_SOCKET)
  442. except (IOError, OSError) as e:
  443. raise qubesadmin.exc.QubesDaemonCommunicationError(
  444. 'Failed to connect to qubesd service: %s', str(e))
  445. # src, method, dest, arg
  446. for call_arg in ('dom0', method, dest, arg):
  447. if call_arg is not None:
  448. client_socket.sendall(call_arg.encode('ascii'))
  449. client_socket.sendall(b'\0')
  450. if payload is not None:
  451. client_socket.sendall(payload)
  452. client_socket.shutdown(socket.SHUT_WR)
  453. return_data = client_socket.makefile('rb').read()
  454. client_socket.close()
  455. return self._parse_qubesd_response(return_data)
  456. def run_service(self, dest, service, filter_esc=False, user=None,
  457. localcmd=None, wait=True, **kwargs):
  458. '''Run qrexec service in a given destination
  459. :param str dest: Destination - may be a VM name or empty
  460. string for default (for a given service)
  461. :param str service: service name
  462. :param bool filter_esc: filter escape sequences to protect terminal \
  463. emulator
  464. :param str user: username to run service as
  465. :param str localcmd: Command to connect stdin/stdout to
  466. :param bool wait: wait for remote process to finish
  467. :param int connect_timeout: qrexec client connection timeout
  468. :rtype: subprocess.Popen
  469. '''
  470. if not dest:
  471. raise ValueError('Empty destination name allowed only from a VM')
  472. if not wait and localcmd:
  473. raise ValueError('wait=False incompatible with localcmd')
  474. try:
  475. self.qubesd_call(dest, 'admin.vm.Start')
  476. except qubesadmin.exc.QubesVMNotHaltedError:
  477. pass
  478. qrexec_opts = ['-d', dest]
  479. if filter_esc:
  480. qrexec_opts.extend(['-t'])
  481. if filter_esc or os.isatty(sys.stderr.fileno()):
  482. qrexec_opts.extend(['-T'])
  483. if localcmd:
  484. qrexec_opts.extend(['-l', localcmd])
  485. if user is None:
  486. user = 'DEFAULT'
  487. if not wait:
  488. qrexec_opts.extend(['-e'])
  489. if 'connect_timeout' in kwargs:
  490. qrexec_opts.extend(['-w', str(kwargs.pop('connect_timeout'))])
  491. kwargs.setdefault('stdin', subprocess.PIPE)
  492. kwargs.setdefault('stdout', subprocess.PIPE)
  493. kwargs.setdefault('stderr', subprocess.PIPE)
  494. proc = subprocess.Popen([qubesadmin.config.QREXEC_CLIENT] +
  495. qrexec_opts + ['{}:QUBESRPC {} dom0'.format(user, service)],
  496. **kwargs)
  497. return proc
  498. class QubesRemote(QubesBase):
  499. '''Application object communicating through qrexec services.
  500. Used when running in VM.
  501. '''
  502. qubesd_connection_type = 'qrexec'
  503. def qubesd_call(self, dest, method, arg=None, payload=None,
  504. payload_stream=None):
  505. '''
  506. Execute Admin API method.
  507. Only one of `payload` and `payload_stream` can be specified.
  508. :param dest: Destination VM name
  509. :param method: Full API method name ('admin...')
  510. :param arg: Method argument (if any)
  511. :param payload: Payload send to the method
  512. :param payload_stream: file-like object to read payload from
  513. :return: Data returned by qubesd (string)
  514. .. warning:: *payload_stream* will get closed by this function
  515. '''
  516. if payload and payload_stream:
  517. raise ValueError(
  518. 'Only one of payload and payload_stream can be used')
  519. service_name = method
  520. if arg is not None:
  521. service_name += '+' + arg
  522. p = subprocess.Popen([qubesadmin.config.QREXEC_CLIENT_VM,
  523. dest, service_name],
  524. stdin=(payload_stream or subprocess.PIPE),
  525. stdout=subprocess.PIPE,
  526. stderr=subprocess.PIPE)
  527. if payload_stream is not None:
  528. payload_stream.close()
  529. (stdout, stderr) = p.communicate(payload)
  530. if p.returncode != 0:
  531. raise qubesadmin.exc.QubesDaemonNoResponseError(
  532. 'Service call error: %s', stderr.decode())
  533. return self._parse_qubesd_response(stdout)
  534. def run_service(self, dest, service, filter_esc=False, user=None,
  535. localcmd=None, wait=True, **kwargs):
  536. '''Run qrexec service in a given destination
  537. :param str dest: Destination - may be a VM name or empty
  538. string for default (for a given service)
  539. :param str service: service name
  540. :param bool filter_esc: filter escape sequences to protect terminal \
  541. emulator
  542. :param str user: username to run service as
  543. :param str localcmd: Command to connect stdin/stdout to
  544. :param bool wait: wait for process to finish
  545. :rtype: subprocess.Popen
  546. '''
  547. if filter_esc:
  548. raise NotImplementedError(
  549. 'filter_esc not implemented for calls from VM')
  550. if user:
  551. raise ValueError(
  552. 'non-default user not possible for calls from VM')
  553. if not wait and localcmd:
  554. raise ValueError('wait=False incompatible with localcmd')
  555. if not wait:
  556. # qrexec-client-vm can only request service calls, which are
  557. # started using MSG_EXEC_CMDLINE qrexec protocol message; this
  558. # message means "start the process, pipe its stdin/out/err,
  559. # and when it terminates, send exit code back".
  560. # According to the protocol qrexec-client-vm needs to wait for
  561. # MSG_DATA_EXIT_CODE, so implementing wait=False would require
  562. # some protocol change (or protocol violation).
  563. raise NotImplementedError(
  564. 'wait=False not implemented for calls from VM')
  565. kwargs.setdefault('stdin', subprocess.PIPE)
  566. kwargs.setdefault('stdout', subprocess.PIPE)
  567. kwargs.setdefault('stderr', subprocess.PIPE)
  568. proc = subprocess.Popen([qubesadmin.config.QREXEC_CLIENT_VM,
  569. dest or '', service] + (shlex.split(localcmd) if localcmd else []),
  570. **kwargs)
  571. return proc