qvm_start_gui.py 17 KB

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