app.py 25 KB

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