app.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 socket
  24. import subprocess
  25. import qubesmgmt.base
  26. import qubesmgmt.vm
  27. import qubesmgmt.exc
  28. import qubesmgmt.utils
  29. QUBESD_SOCK = '/var/run/qubesd.sock'
  30. BUF_SIZE = 4096
  31. class VMCollection(object):
  32. '''Collection of VMs objects'''
  33. def __init__(self, app):
  34. self.app = app
  35. self._vm_list = None
  36. self._vm_objects = {}
  37. def clear_cache(self):
  38. '''Clear cached list of VMs'''
  39. self._vm_list = None
  40. def refresh_cache(self, force=False):
  41. '''Refresh cached list of VMs'''
  42. if not force and self._vm_list is not None:
  43. return
  44. vm_list_data = self.app.qubesd_call(
  45. 'dom0',
  46. 'mgmt.vm.List'
  47. )
  48. new_vm_list = {}
  49. # FIXME: this will probably change
  50. for vm_data in vm_list_data.splitlines():
  51. vm_name, props = vm_data.decode('ascii').split(' ', 1)
  52. props = props.split(' ')
  53. new_vm_list[vm_name] = dict(
  54. [vm_prop.split('=', 1) for vm_prop in props])
  55. self._vm_list = new_vm_list
  56. for name, vm in self._vm_objects.items():
  57. if vm.name not in self._vm_list:
  58. # VM no longer exists
  59. del self._vm_objects[name]
  60. elif vm.__class__.__name__ != self._vm_list[vm.name]['class']:
  61. # VM class have changed
  62. del self._vm_objects[name]
  63. # TODO: some generation ID, to detect VM re-creation
  64. elif name != vm.name:
  65. # renamed
  66. self._vm_objects[vm.name] = vm
  67. del self._vm_objects[name]
  68. def __getitem__(self, item):
  69. if item not in self:
  70. raise KeyError(item)
  71. if item not in self._vm_objects:
  72. cls = qubesmgmt.utils.get_entry_point_one('qubesmgmt.vm',
  73. self._vm_list[item]['class'])
  74. self._vm_objects[item] = cls(self.app, item)
  75. return self._vm_objects[item]
  76. def __contains__(self, item):
  77. self.refresh_cache()
  78. return item in self._vm_list
  79. def __iter__(self):
  80. self.refresh_cache()
  81. for vm in self._vm_list:
  82. yield self[vm]
  83. def keys(self):
  84. '''Get list of VM names.'''
  85. self.refresh_cache()
  86. return self._vm_list.keys()
  87. class QubesBase(qubesmgmt.base.PropertyHolder):
  88. '''Main Qubes application'''
  89. #: domains (VMs) collection
  90. domains = None
  91. def __init__(self):
  92. super(QubesBase, self).__init__(self, 'mgmt.global.', 'dom0')
  93. self.domains = VMCollection(self)
  94. class QubesLocal(QubesBase):
  95. '''Application object communicating through local socket.
  96. Used when running in dom0.
  97. '''
  98. def qubesd_call(self, dest, method, arg=None, payload=None):
  99. try:
  100. client_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  101. client_socket.connect(QUBESD_SOCK)
  102. except IOError:
  103. # TODO:
  104. raise
  105. # src, method, dest, arg
  106. for call_arg in ('dom0', method, dest, arg):
  107. if call_arg is not None:
  108. client_socket.sendall(call_arg.encode('ascii'))
  109. client_socket.sendall(b'\0')
  110. if payload is not None:
  111. client_socket.sendall(payload)
  112. client_socket.shutdown(socket.SHUT_WR)
  113. return_data = b''.join(iter(lambda: client_socket.recv(BUF_SIZE), b''))
  114. return self._parse_qubesd_response(return_data)
  115. class QubesRemote(QubesBase):
  116. '''Application object communicating through qrexec services.
  117. Used when running in VM.
  118. '''
  119. def qubesd_call(self, dest, method, arg=None, payload=None):
  120. service_name = method
  121. if arg is not None:
  122. service_name += '+' + arg
  123. p = subprocess.Popen(['qrexec-client-vm', dest, service_name],
  124. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  125. stderr=subprocess.PIPE)
  126. (stdout, stderr) = p.communicate(payload)
  127. if p.returncode != 0:
  128. # TODO: use dedicated exception
  129. raise qubesmgmt.exc.QubesException('Service call error: %s',
  130. stderr.decode())
  131. return self._parse_qubesd_response(stdout)