__init__.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 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. '''Event handling implementation, require Python >=3.5.2 for asyncio.'''
  21. import asyncio
  22. import subprocess
  23. import qubesadmin.config
  24. import qubesadmin.exc
  25. class EventsDispatcher(object):
  26. ''' Events dispatcher, responsible for receiving events and calling
  27. appropriate handlers'''
  28. def __init__(self, app, api_method='admin.Events'):
  29. '''Initialize EventsDispatcher'''
  30. #: Qubes() object
  31. self.app = app
  32. self._api_method = api_method
  33. #: event handlers - dict of event -> handlers
  34. self.handlers = {}
  35. def add_handler(self, event, handler):
  36. '''Register handler for event
  37. Use '*' as event to register a handler for all events.
  38. Handler function is called with:
  39. * subject (VM object or None)
  40. * event name (str)
  41. * keyword arguments related to the event, if any - all values as str
  42. :param event Event name, or '*' for all events
  43. :param handler Handler function'''
  44. self.handlers.setdefault(event, set()).add(handler)
  45. def remove_handler(self, event, handler):
  46. '''Remove previously registered event handler
  47. :param event Event name
  48. :param handler Handler function
  49. '''
  50. self.handlers[event].remove(handler)
  51. @asyncio.coroutine
  52. def _get_events_reader(self, vm=None) -> (asyncio.StreamReader, callable):
  53. '''Make connection to qubesd and return stream to read events from
  54. :param vm: Specific VM for which events should be handled, use None
  55. to handle events from all VMs (and non-VM objects)
  56. :return stream to read events from and a cleanup function
  57. (call it to terminate qubesd connection)'''
  58. if vm is not None:
  59. dest = vm.name
  60. else:
  61. dest = 'dom0'
  62. if self.app.qubesd_connection_type == 'socket':
  63. reader, writer = yield from asyncio.open_unix_connection(
  64. qubesadmin.config.QUBESD_SOCKET)
  65. writer.write(b'dom0\0') # source
  66. writer.write(self._api_method.encode() + b'\0') # method
  67. writer.write(dest.encode('ascii') + b'\0') # dest
  68. writer.write(b'\0') # arg
  69. writer.write_eof()
  70. def cleanup_func():
  71. '''Close connection to qubesd'''
  72. writer.close()
  73. elif self.app.qubesd_connection_type == 'qrexec':
  74. proc = yield from asyncio.create_subprocess_exec(
  75. 'qrexec-client-vm', dest, self._api_method,
  76. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  77. proc.stdin.write_eof()
  78. reader = proc.stdout
  79. def cleanup_func():
  80. '''Close connection to qubesd'''
  81. try:
  82. proc.kill()
  83. except ProcessLookupError:
  84. pass
  85. else:
  86. raise NotImplementedError('Unsupported qubesd connection type: '
  87. + self.app.qubesd_connection_type)
  88. return reader, cleanup_func
  89. @asyncio.coroutine
  90. def listen_for_events(self, vm=None, reconnect=True):
  91. '''
  92. Listen for events and call appropriate handlers.
  93. This function do not exit until manually terminated.
  94. This is coroutine.
  95. :param vm: Listen for events only for this VM, use None to listen for
  96. events about all VMs and not related to any particular VM.
  97. :param reconnect: should reconnect to qubesd if connection is
  98. interrupted?
  99. :rtype: None
  100. '''
  101. while True:
  102. try:
  103. yield from self._listen_for_events(vm)
  104. except (ConnectionRefusedError, ConnectionResetError,
  105. FileNotFoundError):
  106. pass
  107. if not reconnect:
  108. break
  109. self.app.log.warning(
  110. 'Connection to qubesd terminated, reconnecting in {} '
  111. 'seconds'.format(qubesadmin.config.QUBESD_RECONNECT_DELAY))
  112. # avoid busy-loop if qubesd is dead
  113. yield from asyncio.sleep(qubesadmin.config.QUBESD_RECONNECT_DELAY)
  114. @asyncio.coroutine
  115. def _listen_for_events(self, vm=None):
  116. '''
  117. Listen for events and call appropriate handlers.
  118. This function do not exit until manually terminated.
  119. This is coroutine.
  120. :param vm: Listen for events only for this VM, use None to listen for
  121. events about all VMs and not related to any particular VM.
  122. :return: True if any event was received, otherwise False
  123. :rtype: bool
  124. '''
  125. reader, cleanup_func = yield from self._get_events_reader(vm)
  126. try:
  127. some_event_received = False
  128. while not reader.at_eof():
  129. try:
  130. event_header = yield from reader.readuntil(b'\0')
  131. if event_header != b'1\0':
  132. raise qubesadmin.exc.QubesDaemonCommunicationError(
  133. 'Non-event received on events connection: '
  134. + repr(event_header))
  135. subject = (yield from reader.readuntil(b'\0'))[:-1].decode(
  136. 'utf-8')
  137. event = (yield from reader.readuntil(b'\0'))[:-1].decode(
  138. 'utf-8')
  139. kwargs = {}
  140. while True:
  141. key = (yield from reader.readuntil(b'\0'))[:-1].decode(
  142. 'utf-8')
  143. if not key:
  144. break
  145. value = (yield from reader.readuntil(b'\0'))[:-1].\
  146. decode('utf-8')
  147. kwargs[key] = value
  148. except asyncio.IncompleteReadError as err:
  149. if err.partial == b'':
  150. break
  151. else:
  152. raise
  153. if not subject:
  154. subject = None
  155. self.handle(subject, event, **kwargs)
  156. some_event_received = True
  157. finally:
  158. cleanup_func()
  159. return some_event_received
  160. def handle(self, subject, event, **kwargs):
  161. '''Call handlers for given event'''
  162. if subject:
  163. if event in ['property-set:name']:
  164. self.app.domains.clear_cache()
  165. try:
  166. subject = self.app.domains[subject]
  167. except KeyError:
  168. return
  169. else:
  170. # handle cache refreshing on best-effort basis
  171. if event in ['domain-add', 'domain-delete']:
  172. self.app.domains.clear_cache()
  173. subject = None
  174. for handler in self.handlers.get(event, []):
  175. handler(subject, event, **kwargs)
  176. for handler in self.handlers.get('*', []):
  177. handler(subject, event, **kwargs)