qvm_start_gui.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. ''' GUI daemon launcher tool'''
  21. import os
  22. import signal
  23. import subprocess
  24. import asyncio
  25. import re
  26. import daemon.pidfile
  27. import qubesadmin
  28. import qubesadmin.events
  29. import qubesadmin.tools
  30. import qubesadmin.vm
  31. GUI_DAEMON_PATH = '/usr/bin/qubes-guid'
  32. QUBES_ICON_DIR = '/usr/share/icons/hicolor/128x128/devices'
  33. # "LVDS connected 1024x768+0+0 (normal left inverted right) 304mm x 228mm"
  34. REGEX_OUTPUT = re.compile(r'''
  35. (?x) # ignore whitespace
  36. ^ # start of string
  37. (?P<output>[A-Za-z0-9\-]*)[ ] # LVDS VGA etc
  38. (?P<connect>(dis)?connected) # dis/connected
  39. ([ ]
  40. (?P<primary>(primary)?)[ ]?
  41. (( # a group
  42. (?P<width>\d+)x # either 1024x768+0+0
  43. (?P<height>\d+)[+]
  44. (?P<x>\d+)[+]
  45. (?P<y>\d+)
  46. )|[\D]) # or not a digit
  47. ([ ]\(.*\))?[ ]? # ignore options
  48. ( # 304mm x 228mm
  49. (?P<width_mm>\d+)mm[ ]x[ ]
  50. (?P<height_mm>\d+)mm
  51. )?
  52. .* # ignore rest of line
  53. )? # everything after (dis)connect is optional
  54. ''')
  55. def get_monitor_layout():
  56. '''Get list of monitors and their size/position'''
  57. outputs = []
  58. for line in subprocess.Popen(
  59. ['xrandr', '-q'], stdout=subprocess.PIPE).stdout:
  60. line = line.decode()
  61. if not line.startswith("Screen") and not line.startswith(" "):
  62. output_params = REGEX_OUTPUT.match(line).groupdict()
  63. if output_params['width']:
  64. phys_size = ""
  65. if output_params['width_mm'] and int(output_params['width_mm']):
  66. # don't provide real values for privacy reasons - see
  67. # #1951 for details
  68. dpi = (int(output_params['width']) * 254 //
  69. int(output_params['width_mm']) // 10)
  70. if dpi > 300:
  71. dpi = 300
  72. elif dpi > 200:
  73. dpi = 200
  74. elif dpi > 150:
  75. dpi = 150
  76. else:
  77. # if lower, don't provide this info to the VM at all
  78. dpi = 0
  79. if dpi:
  80. # now calculate dimensions based on approximate DPI
  81. phys_size = " {} {}".format(
  82. int(output_params['width']) * 254 // dpi // 10,
  83. int(output_params['height']) * 254 // dpi // 10,
  84. )
  85. outputs.append("%s %s %s %s%s\n" % (
  86. output_params['width'],
  87. output_params['height'],
  88. output_params['x'],
  89. output_params['y'],
  90. phys_size,
  91. ))
  92. return outputs
  93. class GUILauncher(object):
  94. '''Launch GUI daemon for VMs'''
  95. def __init__(self, app: qubesadmin.app.QubesBase):
  96. ''' Initialize GUILauncher.
  97. :param app: :py:class:`qubesadmin.Qubes` instance
  98. '''
  99. self.app = app
  100. self.started_processes = {}
  101. @staticmethod
  102. def kde_guid_args(vm):
  103. '''Return KDE-specific arguments for gui-daemon, if applicable'''
  104. guid_cmd = []
  105. # Avoid using environment variables for checking the current session,
  106. # because this script may be called with cleared env (like with sudo).
  107. if subprocess.check_output(
  108. ['xprop', '-root', '-notype', 'KWIN_RUNNING']) == \
  109. b'KWIN_RUNNING = 0x1\n':
  110. # native decoration plugins is used, so adjust window properties
  111. # accordingly
  112. guid_cmd += ['-T'] # prefix window titles with VM name
  113. # get owner of X11 session
  114. session_owner = None
  115. for line in subprocess.check_output(['xhost']).splitlines():
  116. if line == b'SI:localuser:root':
  117. pass
  118. elif line.startswith(b'SI:localuser:'):
  119. session_owner = line.split(b':')[2].decode()
  120. if session_owner is not None:
  121. data_dir = os.path.expanduser(
  122. '~{}/.local/share'.format(session_owner))
  123. else:
  124. # fallback to current user
  125. data_dir = os.path.expanduser('~/.local/share')
  126. guid_cmd += ['-p',
  127. '_KDE_NET_WM_COLOR_SCHEME=s:{}'.format(
  128. os.path.join(data_dir,
  129. 'qubes-kde', vm.label.name + '.colors'))]
  130. return guid_cmd
  131. def common_guid_args(self, vm):
  132. '''Common qubes-guid arguments for PV(H), HVM and Stubdomain'''
  133. guid_cmd = [GUI_DAEMON_PATH,
  134. '-N', vm.name,
  135. '-c', vm.label.color,
  136. '-i', os.path.join(QUBES_ICON_DIR, vm.label.icon) + '.png',
  137. '-l', str(vm.label.index)]
  138. if vm.debug:
  139. guid_cmd += ['-v', '-v']
  140. # elif not verbose:
  141. else:
  142. guid_cmd += ['-q']
  143. guid_cmd += self.kde_guid_args(vm)
  144. return guid_cmd
  145. @staticmethod
  146. def guid_pidfile(xid):
  147. '''Helper function to construct a pidfile path'''
  148. return '/var/run/qubes/guid-running.{}'.format(xid)
  149. def start_gui_for_vm(self, vm):
  150. '''Start GUI daemon (qubes-guid) connected directly to a VM
  151. This function is a coroutine.
  152. '''
  153. guid_cmd = self.common_guid_args(vm)
  154. guid_cmd.extend(['-d', str(vm.xid)])
  155. if vm.hvm:
  156. guid_cmd.extend(['-n'])
  157. if vm.features.check_with_template('rpc-clipboard', False):
  158. guid_cmd.extend(['-Q'])
  159. stubdom_guid_pidfile = self.guid_pidfile(vm.stubdom_xid)
  160. if not vm.debug and os.path.exists(stubdom_guid_pidfile):
  161. # Terminate stubdom guid once "real" gui agent connects
  162. with open(stubdom_guid_pidfile, 'r') as pidfile:
  163. stubdom_guid_pid = pidfile.read().strip()
  164. guid_cmd += ['-K', stubdom_guid_pid]
  165. return asyncio.create_subprocess_exec(*guid_cmd)
  166. def start_gui_for_stubdomain(self, vm):
  167. '''Start GUI daemon (qubes-guid) connected to a stubdomain
  168. This function is a coroutine.
  169. '''
  170. guid_cmd = self.common_guid_args(vm)
  171. guid_cmd.extend(['-d', str(vm.stubdom_xid), '-t', str(vm.xid)])
  172. return asyncio.create_subprocess_exec(*guid_cmd)
  173. @asyncio.coroutine
  174. def start_gui(self, vm, force_stubdom=False, monitor_layout=None):
  175. '''Start GUI daemon regardless of start event.
  176. This function is a coroutine.
  177. :param vm: VM for which GUI daemon should be started
  178. :param force_stubdom: Force GUI daemon for stubdomain, even if the
  179. one for target AppVM is running.
  180. '''
  181. if not vm.features.check_with_template('gui', True):
  182. return
  183. vm.log.info('Starting GUI')
  184. if vm.hvm:
  185. if force_stubdom or not os.path.exists(self.guid_pidfile(vm.xid)):
  186. if not os.path.exists(self.guid_pidfile(vm.stubdom_xid)):
  187. yield from self.start_gui_for_stubdomain(vm)
  188. if not os.path.exists(self.guid_pidfile(vm.xid)):
  189. yield from self.start_gui_for_vm(vm)
  190. yield from self.send_monitor_layout(vm, layout=monitor_layout,
  191. startup=True)
  192. @asyncio.coroutine
  193. def send_monitor_layout(self, vm, layout=None, startup=False):
  194. '''Send monitor layout to a given VM
  195. This function is a coroutine.
  196. :param vm: VM to which send monitor layout
  197. :param layout: monitor layout to send; if None, fetch it from
  198. local X server.
  199. :param startup:
  200. :return: None
  201. '''
  202. # pylint: disable=no-self-use
  203. if vm.features.check_with_template('no-monitor-layout', False) \
  204. or not vm.is_running():
  205. return
  206. if layout is None:
  207. layout = get_monitor_layout()
  208. if not layout:
  209. return
  210. vm.log.info('Sending monitor layout')
  211. if not startup:
  212. with open(self.guid_pidfile(vm.xid)) as pidfile:
  213. pid = int(pidfile.read())
  214. os.kill(pid, signal.SIGHUP)
  215. try:
  216. with open(self.guid_pidfile(vm.stubdom_xid)) as pidfile:
  217. pid = int(pidfile.read())
  218. os.kill(pid, signal.SIGHUP)
  219. except FileNotFoundError:
  220. pass
  221. yield from asyncio.get_event_loop().run_in_executor(None,
  222. vm.run_service_for_stdio, 'qubes.SetMonitorLayout',
  223. ''.join(layout).encode())
  224. def send_monitor_layout_all(self):
  225. '''Send monitor layout to all (running) VMs'''
  226. monitor_layout = get_monitor_layout()
  227. for vm in self.app.domains:
  228. if isinstance(vm, qubesadmin.vm.AdminVM):
  229. continue
  230. if vm.is_running():
  231. if not vm.features.check_with_template('gui', True):
  232. continue
  233. asyncio.ensure_future(self.send_monitor_layout(vm,
  234. monitor_layout))
  235. def on_domain_spawn(self, vm, _event, **kwargs):
  236. '''Handler of 'domain-spawn' event, starts GUI daemon for stubdomain'''
  237. if not vm.features.check_with_template('gui', True):
  238. return
  239. if vm.hvm and kwargs.get('start_guid', 'True') == 'True':
  240. asyncio.ensure_future(self.start_gui_for_stubdomain(vm))
  241. def on_domain_start(self, vm, _event, **kwargs):
  242. '''Handler of 'domain-start' event, starts GUI daemon for actual VM'''
  243. if not vm.features.check_with_template('gui', True):
  244. return
  245. if kwargs.get('start_guid', 'True') == 'True':
  246. asyncio.ensure_future(self.start_gui_for_vm(vm))
  247. def on_connection_established(self, _subject, _event, **_kwargs):
  248. '''Handler of 'connection-established' event, used to launch GUI
  249. daemon for domains started before this tool. '''
  250. monitor_layout = get_monitor_layout()
  251. for vm in self.app.domains:
  252. if isinstance(vm, qubesadmin.vm.AdminVM):
  253. continue
  254. if vm.is_running():
  255. asyncio.ensure_future(self.start_gui(vm,
  256. monitor_layout=monitor_layout))
  257. def register_events(self, events):
  258. '''Register domain startup events in app.events dispatcher'''
  259. events.add_handler('domain-spawn', self.on_domain_spawn)
  260. events.add_handler('domain-start', self.on_domain_start)
  261. events.add_handler('connection-established',
  262. self.on_connection_established)
  263. if 'XDG_RUNTIME_DIR' in os.environ:
  264. pidfile_path = os.path.join(os.environ['XDG_RUNTIME_DIR'],
  265. 'qvm-start-gui.pid')
  266. else:
  267. pidfile_path = os.path.join(os.environ.get('HOME', '/'),
  268. '.qvm-start-gui.pid')
  269. parser = qubesadmin.tools.QubesArgumentParser(
  270. description='start GUI for qube(s)', vmname_nargs='*')
  271. parser.add_argument('--watch', action='store_true',
  272. help='Keep watching for further domains startups, must be used with --all')
  273. parser.add_argument('--pidfile', action='store', default=pidfile_path,
  274. help='Pidfile path to create in --watch mode')
  275. parser.add_argument('--notify-monitory-layout', action='store_true',
  276. help='Notify running instance in --watch mode about changed monitor layout')
  277. def main(args=None):
  278. ''' Main function of qvm-start-gui tool'''
  279. args = parser.parse_args(args)
  280. if args.watch and not args.all_domains:
  281. parser.error('--watch option must be used with --all')
  282. if args.watch and args.notify_monitor_layout:
  283. parser.error('--watch cannot be used with --notify-monitor-layout')
  284. launcher = GUILauncher(args.app)
  285. if args.watch:
  286. with daemon.pidfile.TimeoutPIDLockFile(args.pidfile):
  287. loop = asyncio.get_event_loop()
  288. events = qubesadmin.events.EventsDispatcher(args.app)
  289. launcher.register_events(events)
  290. events_listener = asyncio.ensure_future(events.listen_for_events())
  291. for signame in ('SIGINT', 'SIGTERM'):
  292. loop.add_signal_handler(getattr(signal, signame),
  293. events_listener.cancel) # pylint: disable=no-member
  294. loop.add_signal_handler(signal.SIGHUP,
  295. launcher.send_monitor_layout_all)
  296. try:
  297. loop.run_until_complete(events_listener)
  298. except asyncio.CancelledError:
  299. pass
  300. loop.stop()
  301. loop.run_forever()
  302. loop.close()
  303. elif args.notify_monitor_layout:
  304. try:
  305. with open(pidfile_path, 'r') as pidfile:
  306. pid = int(pidfile.read().strip())
  307. os.kill(pid, signal.SIGHUP)
  308. except (FileNotFoundError, ValueError) as e:
  309. parser.error('Cannot open pidfile {}: {}'.format(pidfile_path,
  310. str(e)))
  311. else:
  312. loop = asyncio.get_event_loop()
  313. tasks = []
  314. for vm in args.domains:
  315. if vm.is_running():
  316. tasks.append(asyncio.ensure_future(launcher.start_gui(vm)))
  317. if tasks:
  318. loop.run_until_complete(asyncio.wait(tasks))
  319. loop.stop()
  320. loop.run_forever()
  321. loop.close()
  322. if __name__ == '__main__':
  323. main()