qvm_start_gui.py 18 KB

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