gui.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. #!/usr/bin/env python
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2016 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013-2016 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2016 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. import os
  26. import re
  27. import subprocess
  28. import qubes.config
  29. import qubes.ext
  30. # "LVDS connected 1024x768+0+0 (normal left inverted right) 304mm x 228mm"
  31. REGEX_OUTPUT = re.compile(r'''
  32. (?x) # ignore whitespace
  33. ^ # start of string
  34. (?P<output>[A-Za-z0-9\-]*)[ ] # LVDS VGA etc
  35. (?P<connect>(dis)?connected)[ ]# dis/connected
  36. (?P<primary>(primary)?)[ ]?
  37. (( # a group
  38. (?P<width>\d+)x # either 1024x768+0+0
  39. (?P<height>\d+)[+]
  40. (?P<x>\d+)[+]
  41. (?P<y>\d+)
  42. )|[\D]) # or not a digit
  43. ([ ]\(.*\))?[ ]? # ignore options
  44. ( # 304mm x 228mm
  45. (?P<width_mm>\d+)mm[ ]x[ ]
  46. (?P<height_mm>\d+)mm
  47. )?
  48. .* # ignore rest of line
  49. ''')
  50. def get_monitor_layout():
  51. outputs = []
  52. for line in subprocess.Popen(
  53. ['xrandr', '-q'], stdout=subprocess.PIPE).stdout:
  54. if not line.startswith("Screen") and not line.startswith(" "):
  55. output_params = REGEX_OUTPUT.match(line).groupdict()
  56. if output_params['width']:
  57. phys_size = ""
  58. if output_params['width_mm']:
  59. # don't provide real values for privacy reasons - see
  60. # #1951 for details
  61. dpi = (int(output_params['width']) * 254 /
  62. int(output_params['width_mm']) / 10)
  63. if dpi > 300:
  64. dpi = 300
  65. elif dpi > 200:
  66. dpi = 200
  67. elif dpi > 150:
  68. dpi = 150
  69. else:
  70. # if lower, don't provide this info to the VM at all
  71. dpi = 0
  72. if dpi:
  73. # now calculate dimensions based on approximate DPI
  74. phys_size = " {} {}".format(
  75. int(output_params['width']) * 254 / dpi / 10,
  76. int(output_params['height']) * 254 / dpi / 10,
  77. )
  78. outputs.append("%s %s %s %s%s\n" % (
  79. output_params['width'],
  80. output_params['height'],
  81. output_params['x'],
  82. output_params['y'],
  83. phys_size,
  84. ))
  85. return outputs
  86. class GUI(qubes.ext.Extension):
  87. @staticmethod
  88. def kde_guid_args(vm):
  89. '''Return KDE-specific arguments for guid, if applicable'''
  90. guid_cmd = []
  91. # Avoid using environment variables for checking the current session,
  92. # because this script may be called with cleared env (like with sudo).
  93. if subprocess.check_output(
  94. ['xprop', '-root', '-notype', 'KDE_SESSION_VERSION']) == \
  95. 'KDE_SESSION_VERSION = 5\n':
  96. # native decoration plugins is used, so adjust window properties
  97. # accordingly
  98. guid_cmd += ['-T'] # prefix window titles with VM name
  99. # get owner of X11 session
  100. session_owner = None
  101. for line in subprocess.check_output(['xhost']).splitlines():
  102. if line == 'SI:localuser:root':
  103. pass
  104. elif line.startswith('SI:localuser:'):
  105. session_owner = line.split(":")[2]
  106. if session_owner is not None:
  107. data_dir = os.path.expanduser(
  108. '~{}/.local/share'.format(session_owner))
  109. else:
  110. # fallback to current user
  111. data_dir = os.path.expanduser('~/.local/share')
  112. guid_cmd += ['-p',
  113. '_KDE_NET_WM_COLOR_SCHEME=s:{}'.format(
  114. os.path.join(data_dir,
  115. 'qubes-kde', vm.label.name + '.colors'))]
  116. return guid_cmd
  117. @qubes.ext.handler('domain-start', 'domain-cmd-pre-run')
  118. def start_guid(self, vm, event, preparing_dvm=False, start_guid=True,
  119. extra_guid_args=None, **kwargs):
  120. '''Launch gui daemon.
  121. GUI daemon securely displays windows from domain.
  122. ''' # pylint: disable=no-self-use,unused-argument
  123. if not start_guid or preparing_dvm \
  124. or not os.path.exists('/var/run/shm.id'):
  125. return
  126. if self.is_guid_running(vm):
  127. return
  128. if not vm.features.check_with_template('gui', not vm.hvm):
  129. vm.log.debug('Not starting gui daemon, disabled by features')
  130. return
  131. if not os.getenv('DISPLAY'):
  132. vm.log.error('Not starting gui daemon, no DISPLAY set')
  133. return
  134. vm.log.info('Starting gui daemon')
  135. guid_cmd = [qubes.config.system_path['qubes_guid_path'],
  136. '-d', str(vm.xid), '-N', vm.name,
  137. '-c', vm.label.color,
  138. '-i', vm.label.icon_path,
  139. '-l', str(vm.label.index)]
  140. if extra_guid_args is not None:
  141. guid_cmd += extra_guid_args
  142. if vm.debug:
  143. guid_cmd += ['-v', '-v']
  144. # elif not verbose:
  145. else:
  146. guid_cmd += ['-q']
  147. if vm.hvm:
  148. guid_cmd += ['-Q', '-n']
  149. stubdom_guid_pidfile = '/var/run/qubes/guid-running.{}'.format(
  150. self.get_stubdom_xid(vm))
  151. if not vm.debug and os.path.exists(stubdom_guid_pidfile):
  152. # Terminate stubdom guid once "real" gui agent connects
  153. stubdom_guid_pid = \
  154. open(stubdom_guid_pidfile, 'r').read().strip()
  155. guid_cmd += ['-K', stubdom_guid_pid]
  156. guid_cmd += self.kde_guid_args(vm)
  157. try:
  158. vm.start_daemon(guid_cmd)
  159. except subprocess.CalledProcessError:
  160. raise qubes.exc.QubesVMError(vm,
  161. 'Cannot start qubes-guid for domain {!r}'.format(vm.name))
  162. vm.fire_event('monitor-layout-change')
  163. vm.wait_for_session()
  164. @staticmethod
  165. def get_stubdom_xid(vm):
  166. if vm.xid < 0:
  167. return -1
  168. if vm.app.vmm.xs is None:
  169. return -1
  170. stubdom_xid_str = vm.app.vmm.xs.read('',
  171. '/local/domain/{}/image/device-model-domid'.format(vm.xid))
  172. if stubdom_xid_str is None or not stubdom_xid_str.isdigit():
  173. return -1
  174. return int(stubdom_xid_str)
  175. @staticmethod
  176. def send_gui_mode(vm):
  177. vm.run_service('qubes.SetGuiMode',
  178. input=('SEAMLESS'
  179. if vm.features.get('gui-seamless', False)
  180. else 'FULLSCREEN'))
  181. @qubes.ext.handler('domain-spawn')
  182. def on_domain_spawn(self, vm, event, start_guid=True, **kwargs):
  183. # pylint: disable=unused-argument
  184. if not start_guid:
  185. return
  186. if not vm.hvm:
  187. return
  188. if not os.getenv('DISPLAY'):
  189. vm.log.error('Not starting gui daemon, no DISPLAY set')
  190. return
  191. guid_cmd = [qubes.config.system_path['qubes_guid_path'],
  192. '-d', str(self.get_stubdom_xid(vm)),
  193. '-t', str(vm.xid),
  194. '-N', vm.name,
  195. '-c', vm.label.color,
  196. '-i', vm.label.icon_path,
  197. '-l', str(vm.label.index),
  198. ]
  199. if vm.debug:
  200. guid_cmd += ['-v', '-v']
  201. else:
  202. guid_cmd += ['-q']
  203. guid_cmd += self.kde_guid_args(vm)
  204. try:
  205. vm.start_daemon(guid_cmd)
  206. except subprocess.CalledProcessError:
  207. raise qubes.exc.QubesVMError(vm, 'Cannot start gui daemon')
  208. @qubes.ext.handler('monitor-layout-change')
  209. def on_monitor_layout_change(self, vm, event, monitor_layout=None):
  210. # pylint: disable=no-self-use,unused-argument
  211. if vm.features.check_with_template('no-monitor-layout', False) \
  212. or not vm.is_running():
  213. return
  214. if monitor_layout is None:
  215. monitor_layout = get_monitor_layout()
  216. if not monitor_layout:
  217. return
  218. pipe = vm.run('QUBESRPC qubes.SetMonitorLayout dom0',
  219. passio_popen=True, wait=True)
  220. pipe.stdin.write(''.join(monitor_layout))
  221. pipe.stdin.close()
  222. pipe.wait()
  223. @staticmethod
  224. def is_guid_running(vm):
  225. '''Check whether gui daemon for this domain is available.
  226. :returns: :py:obj:`True` if guid is running, \
  227. :py:obj:`False` otherwise.
  228. :rtype: bool
  229. '''
  230. xid = vm.xid
  231. if xid < 0:
  232. return False
  233. if not os.path.exists('/var/run/qubes/guid-running.{}'.format(xid)):
  234. return False
  235. return True
  236. @qubes.ext.handler('domain-is-fully-usable')
  237. def on_domain_is_fully_usable(self, vm, event):
  238. # pylint: disable=unused-argument
  239. if not self.is_guid_running(vm):
  240. yield False