qvm_start_gui.py 14 KB

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