__init__.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 fnmatch
  23. import subprocess
  24. import qubesadmin.config
  25. import qubesadmin.exc
  26. class EventsDispatcher(object):
  27. ''' Events dispatcher, responsible for receiving events and calling
  28. appropriate handlers'''
  29. def __init__(self, app, api_method='admin.Events'):
  30. '''Initialize EventsDispatcher'''
  31. #: Qubes() object
  32. self.app = app
  33. self._api_method = api_method
  34. #: event handlers - dict of event -> handlers
  35. self.handlers = {}
  36. def add_handler(self, event, handler):
  37. '''Register handler for event
  38. Use '*' as event to register a handler for all events.
  39. Handler function is called with:
  40. * subject (VM object or None)
  41. * event name (str)
  42. * keyword arguments related to the event, if any - all values as str
  43. :param event Event name, or '*' for all events
  44. :param handler Handler function'''
  45. self.handlers.setdefault(event, set()).add(handler)
  46. def remove_handler(self, event, handler):
  47. '''Remove previously registered event handler
  48. :param event Event name
  49. :param handler Handler function
  50. '''
  51. self.handlers[event].remove(handler)
  52. @asyncio.coroutine
  53. def _get_events_reader(self, vm=None) -> (asyncio.StreamReader, callable):
  54. '''Make connection to qubesd and return stream to read events from
  55. :param vm: Specific VM for which events should be handled, use None
  56. to handle events from all VMs (and non-VM objects)
  57. :return stream to read events from and a cleanup function
  58. (call it to terminate qubesd connection)'''
  59. if vm is not None:
  60. dest = vm.name
  61. else:
  62. dest = 'dom0'
  63. if self.app.qubesd_connection_type == 'socket':
  64. reader, writer = yield from asyncio.open_unix_connection(
  65. qubesadmin.config.QUBESD_SOCKET)
  66. writer.write(self._api_method.encode() + b'+ ') # method+arg
  67. writer.write(b'dom0 ') # source
  68. writer.write(b'name ' + dest.encode('ascii') + b'\0') # dest
  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 (OSError, qubesadmin.exc.QubesDaemonCommunicationError):
  105. pass
  106. if not reconnect:
  107. break
  108. self.app.log.warning(
  109. 'Connection to qubesd terminated, reconnecting in {} '
  110. 'seconds'.format(qubesadmin.config.QUBESD_RECONNECT_DELAY))
  111. # avoid busy-loop if qubesd is dead
  112. yield from asyncio.sleep(qubesadmin.config.QUBESD_RECONNECT_DELAY)
  113. @asyncio.coroutine
  114. def _listen_for_events(self, vm=None):
  115. '''
  116. Listen for events and call appropriate handlers.
  117. This function do not exit until manually terminated.
  118. This is coroutine.
  119. :param vm: Listen for events only for this VM, use None to listen for
  120. events about all VMs and not related to any particular VM.
  121. :return: True if any event was received, otherwise False
  122. :rtype: bool
  123. '''
  124. reader, cleanup_func = yield from self._get_events_reader(vm)
  125. try:
  126. some_event_received = False
  127. while not reader.at_eof():
  128. try:
  129. event_header = yield from reader.readuntil(b'\0')
  130. if event_header != b'1\0':
  131. raise qubesadmin.exc.QubesDaemonCommunicationError(
  132. 'Non-event received on events connection: '
  133. + repr(event_header))
  134. subject = (yield from reader.readuntil(b'\0'))[:-1].decode(
  135. 'utf-8')
  136. event = (yield from reader.readuntil(b'\0'))[:-1].decode(
  137. 'utf-8')
  138. kwargs = {}
  139. while True:
  140. key = (yield from reader.readuntil(b'\0'))[:-1].decode(
  141. 'utf-8')
  142. if not key:
  143. break
  144. value = (yield from reader.readuntil(b'\0'))[:-1].\
  145. decode('utf-8')
  146. kwargs[key] = value
  147. except BrokenPipeError:
  148. break
  149. except asyncio.IncompleteReadError as err:
  150. if err.partial == b'':
  151. break
  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. # pylint: disable=protected-access
  163. if subject:
  164. if event in ['property-set:name']:
  165. self.app.domains.clear_cache()
  166. try:
  167. subject = self.app.domains.get_blind(subject)
  168. except KeyError:
  169. return
  170. else:
  171. # handle cache refreshing on best-effort basis
  172. if event in ['domain-add', 'domain-delete']:
  173. self.app.domains.clear_cache()
  174. subject = None
  175. # deserialize known attributes
  176. if event.startswith('device-') and 'device' in kwargs:
  177. try:
  178. devclass = event.split(':', 1)[1]
  179. backend_domain, ident = kwargs['device'].split(':', 1)
  180. kwargs['device'] = self.app.domains.get_blind(backend_domain)\
  181. .devices[devclass][ident]
  182. except (KeyError, ValueError):
  183. pass
  184. # invalidate cache if needed; call it before other handlers
  185. # as those may want to use cached value
  186. if event.startswith('property-set:') or \
  187. event.startswith('property-reset:'):
  188. self.app._invalidate_cache(subject, event, **kwargs)
  189. handlers = [h_func for h_name, h_func_set in self.handlers.items()
  190. for h_func in h_func_set
  191. if fnmatch.fnmatch(event, h_name)]
  192. for handler in handlers:
  193. handler(subject, event, **kwargs)