gui.py 10 KB

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