blob: e3f45d7dd7c8d2aa9983483799c5ee21d49bc53f [file]
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Shared library containing desktop session startup logic (Xorg/Xvfb, Wayland,
# PipeWire, and desktop environment management) and process supervision helpers
# used by Chrome Remote Desktop Linux scripts.
import sys
if sys.version_info[0] != 3 or sys.version_info[1] < 5:
print("This script requires Python version 3.5")
sys.exit(1)
import abc
import dbus
import errno
import hashlib
import logging
import os
import platform
import re
import shlex
import shutil
import socket
import string
import struct
import subprocess
import tempfile
import threading
import time
import psutil
import xdg.BaseDirectory
from packaging import version
# This script has a sensible default for the initial and maximum desktop size,
# which can be overridden via a comma-separated list of sizes in this
# environment variable.
DEFAULT_SIZES_ENV_VAR = "CHROME_REMOTE_DESKTOP_DEFAULT_DESKTOP_SIZES"
# By default, this script launches Xorg as the virtual X display, using the
# dummy display driver and void input device, unless Xorg+Dummy is deemed
# unsupported. When this environment variable is set, the script will instead
# launch Xvfb.
USE_XVFB_ENV_VAR = "CHROME_REMOTE_DESKTOP_USE_XVFB"
# If this environment variable is set, the script will launch a Wayland
# session instead of X11.
USE_WAYLAND_ENV_VAR = "CHROME_REMOTE_DESKTOP_USE_WAYLAND"
# Environment variable used to pass the audio pipe path to the host/desktop
# process.
# LINT.IfChange(audio_pipe_env_var)
AUDIO_PIPE_ENV_VAR = "CHROME_REMOTE_DESKTOP_AUDIO_PIPE"
# LINT.ThenChange(//remoting/host/linux/pulse_audio_capturer.cc:audio_pipe_env_var)
# Environment variables that CRD imports into the systemd user manager and
# that must be unset when the session terminates so they do not interfere with
# the multi-process host or subsequent local sessions.
CRD_SYSTEMD_ENV_VARS_TO_IMPORT_AND_UNSET = [
AUDIO_PIPE_ENV_VAR,
"CHROME_CONFIG_HOME",
"CHROME_REMOTE_DESKTOP_SESSION",
"CHROME_USER_DATA_DIR",
"DISPLAY",
"GDK_BACKEND",
"LD_LIBRARY_PATH",
"PIPEWIRE_REMOTE",
"PULSE_CONFIG_PATH",
"PULSE_RUNTIME_PATH",
"PULSE_SINK",
"PULSE_STATE_PATH",
"SSH_AUTH_SOCK",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_SEAT",
"XDG_SESSION_ID",
]
# Complete allowlist of environment variables to import into `systemd --user`.
# Using an explicit allowlist prevents `XDesktop` (which copies all of
# `os.environ` into `self.child_env`) from uploading unpruned shell/SSH
# variables into `systemd --user`.
#
# While most desktop environments (or
# `/etc/X11/Xsession.d/95dbus_update-activation-env`) attempt to import their
# environment variables into `systemd --user`, this is not guaranteed (for
# example, when a custom `~/.chrome-remote-desktop-session` or minimal window
# manager is used). CRD therefore imports them explicitly because:
# 1. For the multi-process host, the desktop process is not a child of the
# session script; `UserDesktopSessionBackend` captures the `systemd --user`
# environment (via `chrome-remote-desktop-environment.service`) to launch the
# desktop process, which requires `DISPLAY`, `XAUTHORITY`,
# `WAYLAND_DISPLAY`, `GDK_BACKEND`, `CHROME_REMOTE_DESKTOP_AUDIO_PIPE`,
# `SSH_AUTH_SOCK`, and `LD_LIBRARY_PATH`.
# 2. For both single-process and multi-process hosts, services and applications
# started via `systemd --user` or D-Bus activation (such as
# `xdg-desktop-portal` and its GNOME/KDE/GTK backends,
# `gnome-terminal-server`, and audio clients) inherit the `systemd --user`
# environment rather than `self.child_env`, and need the CRD display,
# PipeWire/PulseAudio, gnubby, and software GL variables.
#
# In addition to `CRD_SYSTEMD_ENV_VARS_TO_IMPORT_AND_UNSET`, this includes:
# - `PATH`: May be customized by the user's `~/.profile` via
# `exec_self_via_login_shell()`.
# - `XDG_CURRENT_DESKTOP`, `XDG_SESSION_CLASS`, `XDG_SESSION_TYPE`: Needed by
# `xdg-desktop-portal` (to select the matching GNOME/KDE/GTK portal backend)
# and systemd-activated desktop services. These do not need to be unset on
# exit because subsequent desktop sessions overwrite them.
# - `GDK_DEBUG`, `G_DEBUG`, `G_MESSAGES_DEBUG`, `WAYLAND_DEBUG`: Optional debug
# variables when `WaylandDesktop.debug` is enabled.
CRD_SYSTEMD_ENV_VARS_TO_IMPORT = CRD_SYSTEMD_ENV_VARS_TO_IMPORT_AND_UNSET + [
"GDK_DEBUG",
"G_DEBUG",
"G_MESSAGES_DEBUG",
"PATH",
"WAYLAND_DEBUG",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_CLASS",
"XDG_SESSION_TYPE",
]
# Environment variables to unset from `systemd --user` when the session
# terminates.
#
# In addition to `CRD_SYSTEMD_ENV_VARS_TO_IMPORT_AND_UNSET`, this includes
# variables that CRD does not import, but that the desktop environment may
# import (e.g. `/etc/X11/Xsession.d/95dbus_update-activation-env` imports the
# whole session environment):
# - `SSH_CONNECTION`: If set, libpulse makes a blocking connection to
# `$DISPLAY`, which deadlocks gnome-shell against its own Xwayland on startup.
CRD_SYSTEMD_ENV_VARS_TO_UNSET = CRD_SYSTEMD_ENV_VARS_TO_IMPORT_AND_UNSET + [
"SSH_CONNECTION",
]
# The amount of video RAM the dummy driver should claim to have, which limits
# the maximum possible resolution.
# 1048576 KiB = 1 GiB, which is the amount of video RAM needed to have a
# 16384x16384 pixel frame buffer (the maximum size supported by VP8) with 32
# bits per pixel.
XORG_DUMMY_VIDEO_RAM = 1048576 # KiB
# By default, provide a maximum size that is large enough to support clients
# with large or multiple monitors. This is a list of (width, height)
# resolutions that will be made available if the X server supports RANDR. These
# defaults can be overridden in ~/.profile.
DEFAULT_SIZES = [(1600, 1200), (3840, 2560)]
SCRIPT_PATH = os.path.abspath(sys.argv[0])
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if os.path.basename(sys.argv[0]) == 'linux_me2me_host.py':
# Needed for swarming/isolate tests.
HOST_BINARY_PATH = os.path.join(
SCRIPT_DIR, "../../../out/Release/remoting_me2me_host"
)
else:
HOST_BINARY_PATH = os.path.join(SCRIPT_DIR, "chrome-remote-desktop-host")
HOME_DIR = os.environ["HOME"]
CONFIG_DIR = os.path.join(HOME_DIR, ".config/chrome-remote-desktop")
SESSION_FILE_PATH = os.path.join(HOME_DIR, ".chrome-remote-desktop-session")
SYSTEM_SESSION_FILE_PATH = "/etc/chrome-remote-desktop-session"
SYSTEM_PRE_SESSION_FILE_PATH = "/etc/chrome-remote-desktop-pre-session"
PRE_SESSION_TIMEOUT_SECONDS = 30
DEBIAN_XSESSION_PATH = "/etc/X11/Xsession"
X_SOCKET_FILE_TEMPLATE = "/tmp/.X11-unix/X%d"
FIRST_X_DISPLAY_NUMBER = 20
# Amount of time to wait between relaunching processes.
SHORT_BACKOFF_TIME = 5
LONG_BACKOFF_TIME = 60
# How long a process must run in order not to be counted against the restart
# thresholds.
MINIMUM_PROCESS_LIFETIME = 60
# Thresholds for switching from fast- to slow-restart and for giving up
# trying to restart entirely.
SHORT_BACKOFF_THRESHOLD = 5
MAX_LAUNCH_FAILURES = SHORT_BACKOFF_THRESHOLD + 10
# Number of seconds to save session output to the log.
SESSION_OUTPUT_TIME_LIMIT_SECONDS = 300
# Number of seconds to save the display server output to the log.
SERVER_OUTPUT_TIME_LIMIT_SECONDS = 300
# Host offline reason if the X server retry count is exceeded.
HOST_OFFLINE_REASON_X_SERVER_RETRIES_EXCEEDED = "X_SERVER_RETRIES_EXCEEDED"
# Host offline reason if the wayland server retry count is exceeded.
HOST_OFFLINE_REASON_WAYLAND_SERVER_RETRIES_EXCEEDED = (
"WAYLAND_SERVER_RETRIES_EXCEEDED"
)
# Host offline reason if the X session retry count is exceeded.
HOST_OFFLINE_REASON_SESSION_RETRIES_EXCEEDED = "SESSION_RETRIES_EXCEEDED"
# This is the exit code used to signal to wrapper that it should restart instead
# of exiting. It must be kept in sync with RestartForceExitStatus in
# chrome-remote-desktop@.service and chrome-remote-desktop-x11-session@.service.
RELAUNCH_EXIT_CODE = 41
# Globals needed by the atexit cleanup() handler.
g_desktop = None
g_host_hash = hashlib.md5(socket.gethostname().encode()).hexdigest()
def gen_xorg_config():
return (
# This causes X to load the default GLX module, even if a proprietary one
# is installed in a different directory.
'Section "Files"\n'
' ModulePath "/usr/lib/xorg/modules"\n'
'EndSection\n'
'\n'
# Suppress device probing, which happens by default.
'Section "ServerFlags"\n'
' Option "AutoAddDevices" "false"\n'
' Option "AutoEnableDevices" "false"\n'
' Option "DontVTSwitch" "true"\n'
' Option "PciForceNone" "true"\n'
'EndSection\n'
'\n'
'Section "InputDevice"\n'
# The host looks for this name to check whether it's running in a virtual
# session
' Identifier "Chrome Remote Desktop Input"\n'
# While the xorg.conf man page specifies that both of these options are
# deprecated synonyms for `Option "Floating" "false"`, it turns out that
# if both aren't specified, the Xorg server will automatically attempt to
# add additional devices.
' Option "CoreKeyboard" "true"\n'
' Option "CorePointer" "true"\n'
# The "void" driver is no longer available since Debian 11, but having an
# InputDevice section with an invalid driver will still prevent the Xorg
# server from using a fallback InputDevice setting. However, "Chrome
# Remote Desktop Input" will not appear in the device list if the driver
# is not available.
' Driver "void"\n'
'EndSection\n'
'\n'
'Section "Device"\n'
' Identifier "Chrome Remote Desktop Videocard"\n'
' Driver "dummy"\n'
' VideoRam {video_ram}\n'
'EndSection\n'
'\n'
'Section "Monitor"\n'
' Identifier "Chrome Remote Desktop Monitor"\n'
'EndSection\n'
'\n'
'Section "Screen"\n'
' Identifier "Chrome Remote Desktop Screen"\n'
' Device "Chrome Remote Desktop Videocard"\n'
' Monitor "Chrome Remote Desktop Monitor"\n'
' DefaultDepth 24\n'
' SubSection "Display"\n'
' Viewport 0 0\n'
' Depth 24\n'
' EndSubSection\n'
'EndSection\n'
'\n'
'Section "ServerLayout"\n'
' Identifier "Chrome Remote Desktop Layout"\n'
' Screen "Chrome Remote Desktop Screen"\n'
' InputDevice "Chrome Remote Desktop Input"\n'
'EndSection\n'.format(video_ram=XORG_DUMMY_VIDEO_RAM)
)
def display_manager_is_gdm():
try:
# Open as binary to avoid any encoding errors
with open('/etc/X11/default-display-manager', 'rb') as file:
if file.read().strip() in [b'/usr/sbin/gdm', b'/usr/sbin/gdm3']:
return True
# Fall through to process checking even if the file doesn't contain gdm.
except: # noqa: E722
# If we can't read the file, move on to checking the process list.
pass
for process in psutil.process_iter():
try:
if process.name() in ['gdm', 'gdm3']:
return True
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return False
def get_pipewire_session_manager():
"""Returns the PipeWire session manager supported on this system (either
"wireplumber" or "pipewire-media-session"), or None if a supported PipeWire
installation is not found."""
if shutil.which("pipewire") is None:
logging.warning("PipeWire not found. Not enabling PipeWire audio support.")
return None
try:
version_output = subprocess.check_output(
["pipewire", "--version"], universal_newlines=True
)
except subprocess.CalledProcessError as e:
logging.warning(
"Failed to execute pipewire. Not enabling PipeWire audio"
+ " support: "
+ str(e)
)
return None
match = re.search(r"pipewire (\S+)$", version_output, re.MULTILINE)
if not match:
logging.warning(
"Failed to determine pipewire version. Not enabling"
+ " PipeWire audio support."
)
return None
try:
pipewire_version = version.parse(match[1])
except version.InvalidVersion as e:
logging.warning(
"Failed to parse pipewire version. Not enabling PipeWire"
+ " audio support: "
+ str(e)
)
return None
if pipewire_version < version.parse("0.3.53"):
logging.warning(
"Installed pipewire version is too old. Not enabling"
+ " PipeWire audio support."
)
return None
session_manager = None
for binary in ["wireplumber", "pipewire-media-session"]:
if shutil.which(binary) is not None:
session_manager = binary
break
if session_manager is None:
logging.warning(
"No session manager found. Not enabling PipeWire audio" + " support."
)
return None
return session_manager
def get_wireplumber_version():
"""Returns the WirePlumber version installed on this system, or None if the
version could not be obtained."""
try:
version_output = subprocess.check_output(
["wireplumber", "--version"], universal_newlines=True
)
except subprocess.CalledProcessError as e:
logging.warning("Failed to execute wireplumber: " + str(e))
return None
match = re.search(r"wireplumber (\S+)$", version_output, re.MULTILINE)
if not match:
logging.warning("Failed to determine wireplumber version.")
return None
try:
wireplumber_version = version.parse(match[1])
except version.InvalidVersion as e:
logging.warning("Failed to parse wireplumber version: " + str(e))
return None
return wireplumber_version
def terminate_process(pid, name):
"""Terminates the process with the given |pid|. Initially sends SIGTERM, but
falls back to SIGKILL if the process fails to exit after 10 seconds. |name|
is used for logging. Throws psutil.NoSuchProcess if the pid doesn't exist."""
logging.info("Sending SIGTERM to %s proc (pid=%s)", name, pid)
psutil_proc = psutil.Process(pid)
try:
psutil_proc.terminate()
# Use a short timeout, to avoid delaying service shutdown if the
# process refuses to die for some reason.
psutil_proc.wait(timeout=10)
except psutil.TimeoutExpired:
logging.error("Timed out - sending SIGKILL to %s proc (pid=%s)", name, pid)
try:
psutil_proc.kill()
psutil_proc.wait(timeout=10)
except psutil.TimeoutExpired:
logging.error(
"Timed out - process did not die after SIGKILL: %s proc (pid=%s)",
name,
pid,
)
except psutil.NoSuchProcess:
# The process exited before or while sending SIGKILL, which is harmless.
pass
except psutil.Error:
logging.error("Error terminating process")
def terminate_command_if_running(command_line):
"""Terminate any processes that match |command_line| (including all arguments)
exactly. Note: this does not attempt to resolve the actual path to the
executable. As such, arg0 much match exactly."""
uid = os.getuid()
this_pid = os.getpid()
# This function should return the process with the --child-process flag if it
# exists. If there's only a process without, it might be a legacy process.
non_child_process = None # noqa: F841
# Support new & old psutil API. This is the right way to check, according to
# http://grodola.blogspot.com/2014/01/psutil-20-porting.html
if psutil.version_info >= (2, 0):
psget = lambda x: x() # noqa: E731
else:
psget = lambda x: x # noqa: E731
for process in psutil.process_iter():
# Skip any processes that raise an exception, as processes may terminate
# during iteration over the list.
try:
# Skip other users' processes.
if psget(process.uids).real != uid:
continue
# Skip the current process.
if process.pid == this_pid:
continue
# |cmdline| will be [python-interpreter, script-file, other arguments...]
if psget(process.cmdline) == command_line:
terminate_process(process.pid, command_line[0])
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
class SessionOutputFilterThread(threading.Thread):
"""Reads session log from a pipe and logs the output with the provided prefix
for amount of time defined by time_limit, or indefinitely if time_limit is
None."""
def __init__(self, stream, prefix, time_limit):
threading.Thread.__init__(self)
self.stream = stream
self.daemon = True
self.prefix = prefix
self.time_limit = time_limit
def run(self):
started_time = time.time()
is_logging = True
while True:
try:
line = self.stream.readline()
except IOError as e:
print("IOError when reading session output: ", e)
return
if line == b"":
# EOF reached. Just stop the thread.
return
if not is_logging:
continue
if self.time_limit and time.time() - started_time >= self.time_limit:
is_logging = False
print("Suppressing rest of the session output.", flush=True)
else:
# Pass stream bytes through as is instead of decoding and encoding.
sys.stdout.buffer.write(self.prefix.encode(sys.stdout.encoding) + line)
sys.stdout.flush()
class Desktop(abc.ABC):
"""Manage a single virtual desktop"""
def __init__(
self,
host_delegate=None,
server_inhibitor=None,
pipewire_inhibitor=None,
session_inhibitor=None,
):
self.host_delegate = host_delegate
self.server_proc = None
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager = None
self.pipewire_session_manager_proc = None
self.session_proc = None
self.child_env = None
self.ssh_auth_sockname = None
self.server_inhibitor = server_inhibitor
self.pipewire_inhibitor = pipewire_inhibitor
self.session_inhibitor = session_inhibitor
self._init_child_env()
if self.server_inhibitor is None:
self.server_inhibitor = RelaunchInhibitor("Display server")
if self.pipewire_inhibitor is None:
self.pipewire_inhibitor = RelaunchInhibitor("PipeWire")
if self.session_inhibitor is None:
self.session_inhibitor = RelaunchInhibitor("session")
# Map of inhibitors to the corresponding host offline reason should that
# session component fail. None indicates that the session component isn't
# mandatory and its failure should not result in the host shutting down.
self.inhibitors = {
self.server_inhibitor: HOST_OFFLINE_REASON_X_SERVER_RETRIES_EXCEEDED,
self.pipewire_inhibitor: None,
self.session_inhibitor: HOST_OFFLINE_REASON_SESSION_RETRIES_EXCEEDED,
}
if self.host_delegate is not None:
self.inhibitors.update(self.host_delegate.inhibitors)
def _init_child_env(self):
# For Wayland, initialize using a safe subset of the current environment.
# GNOME starts 'gnome-shell' as a system service, and it may import its
# full environment into systemd. This script may run in an environment
# with values that may break 'gnome-shell' - see
# http://crbug.com/431672013.
self.child_env = {}
for key in [
# These values are set by the remoting-user-session binary when it
# launches this script.
"USER",
"LOGNAME",
"HOME",
"SHELL",
"PATH",
# These values are set by pam_systemd when this script is launched via
# systemd.
"XDG_SESSION_ID",
"XDG_RUNTIME_DIR",
"XDG_SESSION_CLASS",
"XDG_SEAT",
# DBUS_SESSION_BUS_ADDRESS is needed by `gnome-session-binary` - see
# https://crbug.com/432108529 for more details.
"DBUS_SESSION_BUS_ADDRESS",
]:
if key in os.environ:
self.child_env[key] = os.environ[key]
self.child_env["CHROME_REMOTE_DESKTOP_SESSION"] = "1"
# We used to create a separate profile/chrome config home for the virtual
# session since the virtual session was independent of the local session in
# curtain mode, and using the same Chrome profile between sessions would
# lead to cross talk issues. This is no longer the case given modern desktop
# environments don't support running two graphical sessions simultaneously.
# Therefore, we don't set the env var unless the directory already exists.
#
# M61 introduced CHROME_CONFIG_HOME, which allows specifying a different
# config base path while still using different user data directories for
# different channels (Stable, Beta, Dev). For existing users who only have
# chrome-profile, continue using CHROME_USER_DATA_DIR so they don't have to
# set up their profile again.
chrome_profile = os.path.join(CONFIG_DIR, "chrome-profile")
chrome_config_home = os.path.join(CONFIG_DIR, "chrome-config")
if os.path.exists(chrome_profile) and not os.path.exists(
chrome_config_home
):
self.child_env["CHROME_USER_DATA_DIR"] = chrome_profile
elif os.path.exists(chrome_config_home):
self.child_env["CHROME_CONFIG_HOME"] = chrome_config_home
# Ensure that the software-rendering GL drivers are loaded by the desktop
# session, instead of any hardware GL drivers installed on the system.
library_path = (
"/usr/lib/mesa-diverted/%(arch)s-linux-gnu:"
"/usr/lib/%(arch)s-linux-gnu/mesa:"
"/usr/lib/%(arch)s-linux-gnu/dri:"
"/usr/lib/%(arch)s-linux-gnu/gallium-pipe" % {"arch": platform.machine()}
)
if "LD_LIBRARY_PATH" in self.child_env:
library_path += ":" + self.child_env["LD_LIBRARY_PATH"]
self.child_env["LD_LIBRARY_PATH"] = library_path
def _setup_gnubby(self):
# LINT.IfChange(ssh_auth_sock_name)
self.ssh_auth_sockname = os.path.join(
xdg.BaseDirectory.get_runtime_dir(strict=False), "crd_ssh_auth_sock"
)
# LINT.ThenChange(//remoting/base/security_key_socket_name.cc:ssh_auth_sock_name)
self.child_env["SSH_AUTH_SOCK"] = self.ssh_auth_sockname
def _import_systemd_env_vars(self):
"""Imports session environment variables from child_env into the systemd
user manager."""
vars_to_import = [
var for var in CRD_SYSTEMD_ENV_VARS_TO_IMPORT if var in self.child_env
]
if not vars_to_import:
return True
try:
subprocess.check_output(
["systemctl", "--user", "import-environment"] + vars_to_import,
stderr=subprocess.STDOUT,
env=self.child_env,
text=True,
)
return True
except subprocess.CalledProcessError as err:
logging.error(
"Unable to import env vars into systemd, "
"returncode: %s, output: %s" % (err.returncode, err.output)
)
return False
def _launch_pipewire(self, instance_name, runtime_path, sink_name):
self.pipewire_session_manager = get_pipewire_session_manager()
if self.pipewire_session_manager is None:
return False
try:
for config_file in [
"pipewire.conf",
"pipewire-pulse.conf",
self.pipewire_session_manager + ".conf",
]:
with (
open(
os.path.join(SCRIPT_DIR, config_file + ".template"), "r"
) as infile,
open(os.path.join(runtime_path, config_file), "w") as outfile,
):
template = string.Template(infile.read())
outfile.write(
template.substitute(
{
"instance_name": instance_name,
"runtime_path": runtime_path,
"sink_name": sink_name,
}
)
)
logging.info("Launching pipewire")
pipewire_cmd = [
"pipewire",
"-c",
os.path.join(runtime_path, "pipewire.conf"),
]
# PulseAudio protocol support is built into PipeWire for the versions we
# support. Invoking the pipewire binary directly instead of via the
# pipewire-pulse symlink allows this to work even if the pipewire-pulse
# package is not installed (e.g., if the user is still using PulseAudio
# for local sessions).
pipewire_pulse_cmd = [
"pipewire",
"-c",
os.path.join(runtime_path, "pipewire-pulse.conf"),
]
session_manager_cmd = [
self.pipewire_session_manager,
"-c",
os.path.join(runtime_path, self.pipewire_session_manager + ".conf"),
]
# The WirePlumber config template does not work with versions 0.5 or
# later. Instead, launch it with the system config, and use the
# customized "chrome-remote-desktop" profile from the installed config
# fragment.
if self.pipewire_session_manager.endswith("wireplumber"):
wireplumber_version = get_wireplumber_version()
if wireplumber_version is None:
logging.error("Failed to get WirePlumber version.")
return False
if wireplumber_version >= version.parse("0.5"):
session_manager_cmd = [
self.pipewire_session_manager,
"--profile",
"chrome-remote-desktop",
]
# Terminate any stale processes before relaunching.
for command in [pipewire_cmd, pipewire_pulse_cmd, session_manager_cmd]:
terminate_command_if_running(command)
self.pipewire_proc = subprocess.Popen(pipewire_cmd, env=self.child_env)
self.pipewire_pulse_proc = subprocess.Popen(
pipewire_pulse_cmd, env=self.child_env
)
# Directs native PipeWire clients to the correct instance.
self.child_env["PIPEWIRE_REMOTE"] = instance_name
# MEDIA_SESSION_CONFIG_DIR is needed to use an absolute path with
# pipewire-media-session.
self.pipewire_session_manager_proc = subprocess.Popen(
session_manager_cmd,
env={**self.child_env, "MEDIA_SESSION_CONFIG_DIR": "/"},
)
return True
except (IOError, OSError) as e:
logging.error("Failed to start PipeWire: " + str(e))
# Clean up any processes that did start
for proc, name in [
(self.pipewire_proc, "pipewire"),
(self.pipewire_pulse_proc, "pipewire-pulse"),
(self.pipewire_session_manager_proc, self.pipewire_session_manager),
]:
if proc is not None:
terminate_process(proc.pid, name)
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager_proc = None
return False
def _run_pre_session(self):
# Runs the pre-session script synchronously, if it exists. Returns true if
# the script was run successfully or didn't exist, false if it failed.
if os.path.exists(SYSTEM_PRE_SESSION_FILE_PATH):
pre_session_command = bash_invocation_for_script(
SYSTEM_PRE_SESSION_FILE_PATH
)
logging.info("Running pre-session: %s" % pre_session_command)
try:
proc = subprocess.run(
pre_session_command,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=PRE_SESSION_TIMEOUT_SECONDS,
cwd=HOME_DIR,
env=self.child_env,
text=True,
errors="replace",
)
except subprocess.TimeoutExpired as e:
logging.error(
"Pre-session timed out after %d seconds" % PRE_SESSION_TIMEOUT_SECONDS
)
if e.output:
for line in e.output.splitlines():
logging.info("Pre-session output: %s" % line)
return False
except OSError as e:
logging.error("Could not run pre-session: %s" % e)
return False
if proc.stdout:
for line in proc.stdout.splitlines():
logging.info("Pre-session output: %s" % line)
if proc.returncode != 0:
logging.error("Pre-session failed with code %d" % proc.returncode)
return False
logging.info("Pre-session finished successfully.")
return True
def launch_session(self, server_args, backoff_time):
"""Launches process required for session and records the backoff time
for inhibitors so that process restarts are not attempted again until
that time has passed."""
logging.info("Setting up and launching session")
self._setup_gnubby()
if not self._run_pre_session():
logging.error("Pre-session failed. Tearing down.")
self.session_inhibitor.record_started(
MINIMUM_PROCESS_LIFETIME, backoff_time
)
self.session_inhibitor.record_stopped(expected=False)
return
self._launch_server(server_args)
self.launch_desktop_session()
self.server_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME, backoff_time)
self.session_inhibitor.record_started(
MINIMUM_PROCESS_LIFETIME, backoff_time
)
def cleanup(self):
"""Send SIGTERM to all procs and wait for them to exit. Will fallback to
SIGKILL if a process doesn't exit within 10 seconds.
"""
if self.host_delegate is not None:
self.host_delegate.cleanup()
for proc, name in [
(self.session_proc, "session"),
(self.pipewire_proc, "pipewire"),
(self.pipewire_pulse_proc, "pipewire-pulse"),
(self.pipewire_session_manager_proc, self.pipewire_session_manager),
(self.server_proc, "display server"),
]:
if proc is not None:
terminate_process(proc.pid, name)
self.server_proc = None
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager_proc = None
self.session_proc = None
def on_process_exit(self, pid, status):
"""Checks for which process has exited and whether or not the exit was
expected. Returns a boolean indicating whether or not tear down of the
processes is needed."""
tear_down = False
pipewire_process = False
if self.server_proc is not None and pid == self.server_proc.pid:
logging.info("Display server process terminated")
self.server_proc = None
self.server_inhibitor.record_stopped(expected=False)
tear_down = True
if self.pipewire_proc is not None and pid == self.pipewire_proc.pid:
logging.info("PipeWire process terminated")
self.pipewire_proc = None
pipewire_process = True
if (
self.pipewire_pulse_proc is not None
and pid == self.pipewire_pulse_proc.pid
):
logging.info("PipeWire-Pulse process terminated")
self.pipewire_pulse_proc = None
pipewire_process = True
if (
self.pipewire_session_manager_proc is not None
and pid == self.pipewire_session_manager_proc.pid
):
logging.info(self.pipewire_session_manager + " process terminated")
self.pipewire_session_manager_proc = None
pipewire_process = True
if pipewire_process:
self.pipewire_inhibitor.record_stopped(expected=False)
# Terminate other PipeWire-related processes to start fresh.
for proc, name in [
(self.pipewire_proc, "pipewire"),
(self.pipewire_pulse_proc, "pipewire-pulse"),
(self.pipewire_session_manager_proc, self.pipewire_session_manager),
]:
if proc is not None:
terminate_process(proc.pid, name)
self.pipewire_proc = None
self.pipewire_pulse_proc = None
self.pipewire_session_manager_proc = None
if self.session_proc is not None and pid == self.session_proc.pid:
logging.info("Session process terminated")
self.session_proc = None
# The session may have exited on its own or been brought down by the
# display server dying. Check if the display server is still running so we
# know whom to penalize.
if self.check_server_responding():
self.session_inhibitor.record_stopped(expected=False)
else:
self.server_inhibitor.record_stopped(expected=False)
# Either way, we want to tear down the session.
tear_down = True
if self.host_delegate is not None:
if self.host_delegate.on_process_exit(self, pid, status):
tear_down = True
return tear_down
def aggregate_failure_count(self):
failure_count = 0
for inhibitor, offline_reason in self.inhibitors.items():
if inhibitor.running:
inhibitor.record_stopped(True)
# Only count mandatory processes
if offline_reason is not None:
failure_count += inhibitor.failures
return failure_count
def run(self, server_args):
"""Runs the main supervision loop for the desktop session and any attached
host delegate processes."""
# Whether we are tearing down because the display server and/or session
# exited. This keeps us from counting processes exiting because we've
# terminated them as errors.
tear_down = False
while True:
# If the session process or display server stops running (e.g. because the
# user logged out), terminate all processes. The session will be restarted
# once everything has exited.
if tear_down:
self.cleanup()
failure_count = self.aggregate_failure_count()
tear_down = False
if failure_count == 0:
# Since the user's desktop is already gone at this point, there's no
# state to lose and now is a good time to pick up any updates to this
# script that might have been installed.
logging.info("Relaunching self")
relaunch_self()
else:
# If there is a non-zero |failures| count, restarting the whole script
# would lose this information, so just launch the session as normal,
# below.
pass
relaunch_times = []
# Set the backoff interval and exit if a process failed too many times.
backoff_time = SHORT_BACKOFF_TIME
for inhibitor, offline_reason in self.inhibitors.items():
if inhibitor.disabled:
continue
if inhibitor.failures >= MAX_LAUNCH_FAILURES:
if offline_reason is None:
logging.error(
"Too many launch failures of '%s', not retrying."
% inhibitor.label
)
else:
logging.error(
"Too many launch failures of '%s', exiting." % inhibitor.label
)
if self.host_delegate is not None:
self.host_delegate.report_offline_reason(self, offline_reason)
sys.exit(1)
elif inhibitor.failures >= SHORT_BACKOFF_THRESHOLD:
backoff_time = LONG_BACKOFF_TIME
if inhibitor.is_inhibited():
relaunch_times.append(inhibitor.earliest_relaunch_time)
if relaunch_times:
# We want to wait until everything is ready to start so we don't end up
# launching things in the wrong order due to differing relaunch times.
logging.info("Waiting before relaunching")
else:
if (
self.pipewire_proc is None
and self.pipewire_pulse_proc is None
and self.pipewire_session_manager_proc is None
and not self.pipewire_inhibitor.disabled
and self.pipewire_inhibitor.failures < MAX_LAUNCH_FAILURES
):
self.setup_audio(backoff_time)
if self.server_proc is None and self.session_proc is None:
self.launch_session(server_args, backoff_time)
if self.host_delegate is not None:
self.host_delegate.launch_processes(self, backoff_time)
deadline = max(relaunch_times) if relaunch_times else 0
pid, status = waitpid_handle_exceptions(-1, deadline)
if pid == 0:
continue
logging.info("wait() returned (%s,%s)" % (pid, status))
# When a process has terminated, and we've reaped its exit-code, any Popen
# instance for that process is no longer valid. Reset any affected
# instance to None.
tear_down = self.on_process_exit(pid, status)
def setup_audio(self, backoff_time):
"""Launches a CRD-specific instance of PipeWire for audio forwarding within
the session and sets up the restart inhibitor for it, if supported on this
system. Otherwise, falls back to writing a legacy PulseAudio
configuration."""
runtime_dirname = "crd_audio"
pipewire_instance = runtime_dirname + "/pipewire"
runtime_path = os.path.join(
xdg.BaseDirectory.get_runtime_dir(strict=False), runtime_dirname
)
if len(runtime_path) + len("/pipewire") >= 108:
logging.error(
"Audio will not be enabled because audio UNIX socket path"
+ " is too long."
)
self.pipewire_inhibitor.disable()
return
sink_name = "chrome_remote_desktop_session"
pipe_name = os.path.join(runtime_path, "fifo_output")
try:
if not os.path.exists(runtime_path):
os.mkdir(runtime_path)
except IOError as e:
logging.error("Failed to create audio runtime path: " + str(e))
self.pipewire_inhibitor.disable()
return
self.child_env[AUDIO_PIPE_ENV_VAR] = pipe_name
# Used both with PipeWire-Pulse and PulseAudio
self.child_env["PULSE_RUNTIME_PATH"] = runtime_path
self.child_env["PULSE_SINK"] = sink_name
# Configure and launch PipeWire if supported on this system.
if self._launch_pipewire(pipewire_instance, runtime_path, sink_name):
self.pipewire_inhibitor.record_started(
MINIMUM_PROCESS_LIFETIME, backoff_time
)
return
self.pipewire_inhibitor.disable()
# Used only by the PulseAudio daemon in a legacy setup.
self.child_env["PULSE_CONFIG_PATH"] = runtime_path
self.child_env["PULSE_STATE_PATH"] = runtime_path
# Write a legacy PulseAudio config. This isn't used by PipeWire, but allows
# users with a legacy configuration without PipeWire where PulseAudio is
# started by their session to continue functioning.
try:
with open(os.path.join(runtime_path, "daemon.conf"), "w") as pulse_config:
pulse_config.write("default-sample-format = s16le\n")
pulse_config.write("default-sample-rate = 48000\n")
pulse_config.write("default-sample-channels = 2\n")
with open(os.path.join(runtime_path, "default.pa"), "w") as pulse_script:
pulse_script.write("load-module module-native-protocol-unix\n")
pulse_script.write(
(
"load-module module-pipe-sink sink_name=%s file=\"%s\" "
+ "rate=48000 channels=2 format=s16le\n"
)
% (sink_name, pipe_name)
)
except IOError as e:
logging.error("Failed to write pulseaudio config: " + str(e))
@abc.abstractmethod
def launch_desktop_session(self):
"""Start desktop session."""
pass
@abc.abstractmethod
def check_server_responding(self):
"""Checks if the display server is responding to connections."""
return False
class WaylandSession(abc.ABC):
"""Abstract base class for Wayland desktop environment specific logic."""
@classmethod
@abc.abstractmethod
def get_xdg_current_desktop(cls):
"""Returns the value of the XDG_CURRENT_DESKTOP environment variable."""
pass
@abc.abstractmethod
def get_session_binary(self):
"""Returns the name of the binary to start the Wayland session."""
pass
@abc.abstractmethod
def get_portal_services(self):
"""Returns a list of XDG portal packages to restart."""
pass
@abc.abstractmethod
def pre_session_launch(self):
"""Called before starting the Wayland session."""
pass
@abc.abstractmethod
def cleanup(self):
"""Called during session cleanup."""
pass
class GnomeWaylandSession(WaylandSession):
"""GNOME Wayland desktop environment specific logic."""
@classmethod
def get_xdg_current_desktop(cls):
return "GNOME"
def get_session_binary(self):
return "gnome-session"
def get_portal_services(self):
return ["xdg-desktop-portal-gnome", "xdg-desktop-portal-gtk"]
def pre_session_launch(self):
pass
def cleanup(self):
pass
class KdeWaylandSession(WaylandSession):
"""KDE Plasma Wayland desktop environment specific logic."""
@classmethod
def get_xdg_current_desktop(cls):
return "KDE"
def get_session_binary(self):
return "startplasma-wayland"
def get_portal_services(self):
return ["plasma-xdg-desktop-portal-kde"]
def pre_session_launch(self):
self._terminate_kwin_wayland()
def cleanup(self):
self._terminate_kwin_wayland()
def _terminate_kwin_wayland(self):
# Killing startplasma-wayland does not kill kwin_wayland_wrapper and its
# subprocesses, so we need to manually terminate them.
for process in psutil.process_iter():
try:
if process.name() in ['kwin_wayland', 'kwin_wayland_wrapper']:
terminate_process(process.pid, process.name())
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
WAYLAND_SESSIONS = {
GnomeWaylandSession.get_xdg_current_desktop(): GnomeWaylandSession,
KdeWaylandSession.get_xdg_current_desktop(): KdeWaylandSession,
}
class WaylandDesktop(Desktop):
"""Manage a single virtual wayland based desktop"""
WL_SERVER_CHECK_DELAY_SECONDS = 1
WL_SERVER_CHECK_TIMEOUT_SECONDS = 60
WL_SERVER_REPLY_TIMEOUT_SECONDS = 1
def __init__(self, wayland_session, host_delegate=None):
self.debug = False
self._wayland_socket = None
self._wayland_session = wayland_session
super(WaylandDesktop, self).__init__(host_delegate=host_delegate)
self.inhibitors[self.server_inhibitor] = (
HOST_OFFLINE_REASON_WAYLAND_SERVER_RETRIES_EXCEEDED
)
global g_desktop
assert g_desktop is None
g_desktop = self
def _init_child_env(self):
super(WaylandDesktop, self)._init_child_env()
self.child_env["XDG_SESSION_TYPE"] = "wayland"
self.child_env["XDG_CURRENT_DESKTOP"] = (
self._wayland_session.get_xdg_current_desktop()
)
if self.debug:
self.child_env["G_MESSAGES_DEBUG"] = "all"
self.child_env["GDK_DEBUG"] = "all"
self.child_env["G_DEBUG"] = "fatal-criticals"
self.child_env["WAYLAND_DEBUG"] = "1"
def _launch_server(self, *args, **kwargs):
logging.info("Launching wayland server.")
# Remove the display layout file, which will cause problems if it is applied
# right after the session is launched. See: http://crbug.com/487749302
display_layout_file = os.path.join(
CONFIG_DIR, "host#%s.display_layout.pb" % g_host_hash
)
try:
os.remove(display_layout_file)
logging.info("Existing display layout file deleted.")
except FileNotFoundError:
pass
session_binary = self._wayland_session.get_session_binary()
if not shutil.which(session_binary):
logging.error("Unable to find '%s' on the host" % session_binary)
sys.exit(1)
# Remove variables from the systemd environment that are known to cause
# problems in the Wayland session if present - see
# http://crbug.com/444255720.
subprocess.call(
[
"systemctl",
"--user",
"unset-environment",
"GDK_BACKEND",
"SSH_CONNECTION",
],
stdout=subprocess.DEVNULL,
)
self._wayland_session.pre_session_launch()
self.server_proc = subprocess.Popen(
[session_binary],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=self.child_env,
)
if not self.server_proc.pid:
raise Exception("Could not start wayland session")
output_filter_thread = SessionOutputFilterThread(
self.server_proc.stdout,
"Wayland server output: ",
SERVER_OUTPUT_TIME_LIMIT_SECONDS,
)
output_filter_thread.start()
def _fetch_wayland_socket_from_systemd(self):
"""
Fetches the wayland socket name from $WAYLAND_DISPLAY in the systemd user
environment. This is set by the GNOME Shell service when it becomes active.
If successful, the value is stored in `_wayland_socket`. It is also
stored in `child_env` for child processes that might want to connect to
Wayland (such as the host process). Returns True if successful.
"""
# Use the D-Bus API directly, instead of parsing the output of
# "systemctl --user show-environment". That command may shell-escape its
# output, and there may be issues with embedded newlines or invalid UTF-8
# encoding.
bus = None
try:
# A private connection is needed. The systemd user "dbus" service runs
# on-demand (whenever the dbus socket is accessed) so it may stop and
# start. This causes disconnection errors if a global connection is
# re-used here.
bus = dbus.SessionBus(private=True)
systemd_object = bus.get_object(
"org.freedesktop.systemd1", "/org/freedesktop/systemd1"
)
systemd_properties = dbus.Interface(
systemd_object, "org.freedesktop.DBus.Properties"
)
systemd_environment = systemd_properties.Get(
"org.freedesktop.systemd1.Manager", "Environment"
)
except dbus.exceptions.DBusException:
# D-Bus errors should be rare - include exception info for debugging.
logging.error("Failed to get Wayland socket name", exc_info=True)
return False
finally:
if bus is not None:
bus.close()
wayland_display_env = "WAYLAND_DISPLAY"
wayland_env_prefix = wayland_display_env + "="
for setting in systemd_environment:
if setting.startswith(wayland_env_prefix):
self._wayland_socket = setting[len(wayland_env_prefix) :]
self.child_env[wayland_display_env] = self._wayland_socket
logging.info("Fetched Wayland socket name: %s" % self._wayland_socket)
return True
return False
def _wait_for_wayland_compositor_running(self):
"""
Waits for the Wayland display socket to be exported to systemd and for the
Wayland server to respond to connections. Returns true if this happens
within the allowed timeout, else false.
"""
self._wayland_socket = None
start_time = time.time()
while time.time() - start_time < self.WL_SERVER_CHECK_TIMEOUT_SECONDS:
if not self._wayland_socket:
if not self._fetch_wayland_socket_from_systemd():
time.sleep(self.WL_SERVER_CHECK_DELAY_SECONDS)
continue
if self.check_server_responding():
logging.info(
"Wayland compositor socket (%s) is active and responding in %s "
"seconds",
self._wayland_socket,
time.time() - start_time,
)
return True
time.sleep(self.WL_SERVER_CHECK_DELAY_SECONDS)
logging.error(
"Waited for Wayland compositor to become active and responding, "
"but it didn't happen in %s seconds",
self.WL_SERVER_CHECK_TIMEOUT_SECONDS,
)
return False
def launch_desktop_session(self):
"""
Restarts the portal services so that they can connect to the wayland socket.
This helps host process to talk to call into the the xdg-desktop-portal
APIs.
"""
if not self._wait_for_wayland_compositor_running():
logging.error("Aborting wayland session since compositor isn't running")
sys.exit(RELAUNCH_EXIT_CODE)
logging.info(
"Wayland compositor is running, restarting the portal services now"
)
if not self._import_systemd_env_vars():
logging.error(
"Continuing without restarting Portal services - "
"this may cause some unexpected problems."
)
return
try:
portals = [
"xdg-desktop-portal"
] + self._wayland_session.get_portal_services()
subprocess.check_output(
["systemctl", "--user", "restart"] + portals,
stderr=subprocess.STDOUT,
env=self.child_env,
)
except subprocess.CalledProcessError as err:
logging.error(
"Unable to restart portal services on the host, "
"returncode: %s, output: %s" % (err.returncode, err.output)
)
# For GNOME, the Portal services are not required, since the host process
# uses the private GNOME APIs. For non-GNOME desktops, the Portal services
# are needed, but a failure to restart them here is not necessarily fatal.
# If the Portal services are needed but are not running, the host process
# can detect this condition and terminate with an exit-code.
return
logging.info("Done restarting the portal services")
def cleanup(self):
super(WaylandDesktop, self).cleanup()
self._wayland_session.cleanup()
def check_server_responding(self):
"""
Connects to the server that is listening on the wayland socket.
If the connection succeeds, it means that the server is still up and
running.
"""
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
runtime_dir = xdg.BaseDirectory.get_runtime_dir(strict=True)
sock.connect(os.path.join(runtime_dir, self._wayland_socket))
# Asks the server for the global registry object
# (See: https://wayland-book.com/registry.html)
sock.sendall(struct.pack("<III", 0x00000001, 0x000C0001, 0x00000002))
num_bytes_received = 0
NUM_BYTES_EXPECTED = 32
# We don't want to wait forever for a reply so we set a timeout here.
sock.settimeout(self.WL_SERVER_REPLY_TIMEOUT_SECONDS)
while num_bytes_received < NUM_BYTES_EXPECTED:
data = sock.recv(NUM_BYTES_EXPECTED)
if len(data) == 0: # Expect empty reply if server dies
break
num_bytes_received += len(data)
logging.debug("Wayland server replied with: %s" % data)
if not num_bytes_received:
# If we don't receive a reply at all then the server is likely not
# listening on the socket.
return False
except socket.error as err:
logging.info("Wayland server is not responding: %s" % err)
return False
return True
class XDesktop(Desktop):
"""Manage a single virtual X desktop"""
def __init__(self, host_delegate=None):
super(XDesktop, self).__init__(host_delegate=host_delegate)
self.sizes = self._get_desktop_sizes()
self.xorg_conf = None
self.server_supports_randr = False
self.randr_add_sizes = False
self.ssh_auth_sockname = None
self.use_xvfb = self.should_use_xvfb()
global g_desktop
assert g_desktop is None
g_desktop = self
@staticmethod
def _get_desktop_sizes():
if DEFAULT_SIZES_ENV_VAR not in os.environ:
return list(DEFAULT_SIZES)
sizes = []
for size in os.environ[DEFAULT_SIZES_ENV_VAR].split(","):
size_components = size.split("x")
if len(size_components) != 2:
logging.error(
"Incorrect size format '%s', should be WIDTHxHEIGHT; using "
"default sizes",
size,
)
return list(DEFAULT_SIZES)
try:
width = int(size_components[0])
height = int(size_components[1])
# Enforce minimum desktop size, as a sanity-check. The limit of 100 will
# detect typos of 2 instead of 3 digits.
if width < 100 or height < 100:
raise ValueError
except ValueError:
logging.error(
"Width and height should be 100 pixels or greater; using default "
"sizes"
)
return list(DEFAULT_SIZES)
sizes.append((width, height))
return sizes
@staticmethod
def should_use_xvfb():
"""Return whether XVFB should be used. This will be true if USE_XVFB_ENV_VAR
is set, or if installed dependencies can't support Xorg+Dummy. Note that
this method performs expensive IO so the output should be cached."""
if USE_XVFB_ENV_VAR in os.environ:
return True
# Check if xserver-xorg-video-dummy is up-to-date. Older versions don't
# support the DUMMY* outputs and can't be used.
# Unfortunately, dummy_drv.so doesn't seem to have any version info so we
# have to query the dpkg database.
try:
video_dummy_info = subprocess.check_output(
['dpkg-query', '-s', 'xserver-xorg-video-dummy']
)
match = re.search(rb'^Version: (\S+)$', video_dummy_info, re.MULTILINE)
if not match:
logging.error('Version line is not found')
return True
version = match[1]
retcode = subprocess.call(
['dpkg', '--compare-versions', version, 'ge', '1:0.4.0']
)
if retcode != 0:
logging.info('xserver-xorg-video-dummy is not up-to-date')
return True
except subprocess.CalledProcessError:
logging.info('xserver-xorg-video-dummy is not installed')
return True
except Exception as e:
logging.warning(
'Failed to get xserver-xorg-video-dummy version: ' + str(e)
)
return False
@staticmethod
def get_unused_display_number():
"""Return a candidate display number for which there is currently no
X Server domain socket"""
display = FIRST_X_DISPLAY_NUMBER
while os.path.exists(X_SOCKET_FILE_TEMPLATE % display):
display += 1
return display
def _init_child_env(self):
super(XDesktop, self)._init_child_env()
# For backwards compatibility, copy the full environment into
# self.child_env, without overwriting any values that were set earlier by
# this script.
for key in os.environ:
if key not in self.child_env:
self.child_env[key] = os.environ[key]
# Force GDK to use the X11 backend, as otherwise parts of the host that use
# GTK can end up connecting to an active Wayland display instead of the
# CRD X11 session.
self.child_env["GDK_BACKEND"] = "x11"
self.child_env["XDG_SESSION_TYPE"] = "x11"
def launch_session(self, *args, **kwargs):
logging.info("Launching X server and X session.")
super(XDesktop, self).launch_session(*args, **kwargs)
# Returns child environment not containing TMPDIR.
# Certain values of TMPDIR can break the X server (crbug.com/672684), so we
# want to make sure it isn't set in the environment used to start the server.
def _x_env(self):
if "TMPDIR" not in self.child_env:
return self.child_env
else:
env_copy = dict(self.child_env)
del env_copy["TMPDIR"]
return env_copy
def check_server_responding(self):
"""Checks if the X server is responding to connections."""
exit_code = subprocess.call(
"xdpyinfo", env=self.child_env, stdout=subprocess.DEVNULL
)
return exit_code == 0
def _wait_for_x(self):
# Wait for X to be active.
for _test in range(20):
if self.check_server_responding():
logging.info("X server is active.")
return
time.sleep(0.5)
raise Exception("Could not connect to X server.")
def _launch_xvfb(self, display, x_auth_file, extra_x_args):
max_width = max([width for width, height in self.sizes])
max_height = max([height for width, height in self.sizes])
logging.info("Starting Xvfb on display :%d" % display)
screen_option = "%dx%dx24" % (max_width, max_height)
self.server_proc = subprocess.Popen(
[
"Xvfb",
":%d" % display,
"-auth",
x_auth_file,
"-nolisten",
"tcp",
"-noreset",
"-screen",
"0",
screen_option,
]
+ extra_x_args,
env=self._x_env(),
)
if not self.server_proc.pid:
raise Exception("Could not start Xvfb.")
self._wait_for_x()
exit_code = subprocess.call(
"xrandr",
env=self.child_env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if exit_code == 0:
# RandR is supported
self.server_supports_randr = True
self.randr_add_sizes = True
def _launch_xorg(self, display, x_auth_file, extra_x_args):
config_dir = tempfile.mkdtemp(prefix="chrome_remote_desktop_")
with open(os.path.join(config_dir, "xorg.conf"), "wb") as config_file:
config_file.write(gen_xorg_config().encode())
self.server_supports_randr = True
self.randr_add_sizes = True
self.xorg_conf = config_file.name
xorg_binary = "/usr/lib/xorg/Xorg"
if not os.access(xorg_binary, os.X_OK):
xorg_binary = "Xorg"
logging.info("Starting %s on display :%d" % (xorg_binary, display))
# We use the child environment so the Xorg server picks up the Mesa libGL
# instead of any proprietary versions that may be installed, thanks to
# LD_LIBRARY_PATH.
# Note: This prevents any environment variable the user has set from
# affecting the Xorg server.
self.server_proc = subprocess.Popen(
[
xorg_binary,
":%d" % display,
"-auth",
x_auth_file,
"-nolisten",
"tcp",
"-noreset",
# Disable logging to a file and instead bump up the stderr verbosity
# so the equivalent information gets logged in our main log file.
"-logfile",
"/dev/null",
"-verbose",
"3",
"-configdir",
config_dir,
# Pass a non-existent file, to prevent Xorg from reading the default
# config file: /etc/X11/xorg.conf
"-config",
os.path.join(config_dir, "none"),
]
+ extra_x_args,
env=self._x_env(),
)
if not self.server_proc.pid:
raise Exception("Could not start Xorg.")
self._wait_for_x()
def _launch_server(self, extra_x_args):
x_auth_file = os.path.expanduser("~/.Xauthority")
self.child_env["XAUTHORITY"] = x_auth_file
display = self.get_unused_display_number()
# Run "xauth add" with |child_env| so that it modifies the same XAUTHORITY
# file which will be used for the X session.
exit_code = subprocess.call(
"xauth add :%d . `mcookie`" % display, env=self.child_env, shell=True
)
if exit_code != 0:
raise Exception("xauth failed with code %d" % exit_code)
# Disable the Composite extension iff the X session is the default
# Unity-2D, since it uses Metacity which fails to generate DAMAGE
# notifications correctly. See crbug.com/166468.
x_session = choose_x_session()
if (
len(x_session) == 2
and x_session[1] == "/usr/bin/gnome-session --session=ubuntu-2d"
):
extra_x_args.extend(["-extension", "Composite"])
self.child_env["DISPLAY"] = ":%d" % display
if self.use_xvfb:
self._launch_xvfb(display, x_auth_file, extra_x_args)
else:
self._launch_xorg(display, x_auth_file, extra_x_args)
# The remoting host expects the server to use "evdev" keycodes, but Xvfb
# starts configured to use the "base" ruleset, resulting in XKB configuring
# for "xfree86" keycodes, and screwing up some keys. See crbug.com/119013.
# Reconfigure the X server to use "evdev" keymap rules. The X server must
# be started with -noreset otherwise it'll reset as soon as the command
# completes, since there are no other X clients running yet.
exit_code = subprocess.call(
["setxkbmap", "-rules", "evdev"], env=self.child_env
)
if exit_code != 0:
logging.error("Failed to set XKB to 'evdev'")
if not self.server_supports_randr:
return
# Register the screen sizes with RandR, if needed. Errors here are
# non-fatal; the X server will continue to run with the dimensions from
# the "-screen" option.
if self.randr_add_sizes:
refresh_rates = ["60"]
try:
proc_num = subprocess.check_output("nproc", universal_newlines=True)
# Keep the proc_num logic in sync with desktop_resizer_x11.cc
if int(proc_num) > 16:
refresh_rates.append("120")
except (ValueError, OSError, subprocess.CalledProcessError) as e:
logging.error("Failed to retrieve processor count: " + str(e))
output_names = (
["screen"]
if self.use_xvfb
else ["DUMMY0", "DUMMY1", "DUMMY2", "DUMMY3"]
)
for output_name in output_names:
for refresh_rate in refresh_rates:
for width, height in self.sizes:
# This sets dot-clock, vtotal and htotal such that the computed
# refresh-rate will have a realistic value:
# refresh rate = dot-clock / (vtotal * htotal).
label = "%dx%d_%s" % (width, height, refresh_rate)
args = [
"xrandr",
"--newmode",
label,
refresh_rate,
str(width),
"0",
"0",
"1000",
str(height),
"0",
"0",
"1000",
]
subprocess.call(
args,
env=self.child_env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
args = ["xrandr", "--addmode", output_name, label]
subprocess.call(
args,
env=self.child_env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Set the initial mode to the first size specified, otherwise the X server
# would default to (max_width, max_height), which might not even be in the
# list.
initial_size = self.sizes[0]
label = "%dx%d" % initial_size
args = ["xrandr", "-s", label]
subprocess.call(
args,
env=self.child_env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Set the physical size of the display so that the initial mode is running
# at approximately 96 DPI, since some desktops require the DPI to be set
# to something realistic.
args = ["xrandr", "--dpi", "96"]
subprocess.call(
args,
env=self.child_env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if self.use_xvfb:
# Monitor for any automatic resolution changes from the desktop
# environment. This is needed only for Xvfb sessions because Xvfb sets
# the first mode to be the maximum supported resolution, and some
# desktop-environments would mistakenly set this as the preferred mode,
# leading to a huge desktop with tiny text. With Xorg, the modes are
# all reasonably sized, so the problem doesn't occur.
args = [
SCRIPT_PATH,
"--watch-resolution",
str(initial_size[0]),
str(initial_size[1]),
]
# It is not necessary to wait() on the process here, as this script's main
# loop will reap the exit-codes of all child processes.
subprocess.Popen(
args,
env=self.child_env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def launch_desktop_session(self):
# Start desktop session.
# The /dev/null input redirection is necessary to prevent the X session
# reading from stdin. If this code runs as a shell background job in a
# terminal, any reading from stdin causes the job to be suspended.
# Daemonization would solve this problem by separating the process from the
# controlling terminal.
xsession_command = choose_x_session()
if xsession_command is None:
raise Exception("Unable to choose suitable X session command.")
self._import_systemd_env_vars()
logging.info("Launching X session: %s" % xsession_command)
self.session_proc = subprocess.Popen(
xsession_command,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=HOME_DIR,
env=self.child_env,
)
if not self.session_proc.pid:
raise Exception("Could not start X session")
output_filter_thread = SessionOutputFilterThread(
self.session_proc.stdout,
"Session output: ",
SESSION_OUTPUT_TIME_LIMIT_SECONDS,
)
output_filter_thread.start()
def bash_invocation_for_script(script):
"""Chooses the appropriate bash command to run the provided script."""
if os.path.exists(script):
if os.access(script, os.X_OK):
# "/bin/sh -c" is smart about how to execute the session script and
# works in cases where plain exec() fails (for example, if the file is
# marked executable, but is a plain script with no shebang line).
return ["/bin/sh", "-c", shlex.quote(script)]
else:
# If this is a system-wide session script, it should be run using the
# system shell, ignoring any login shell that might be set for the
# current user.
return ["/bin/sh", script]
def choose_x_session():
"""Chooses the most appropriate X session command for this system.
Returns:
A string containing the command to run, or a list of strings containing
the executable program and its arguments, which is suitable for passing as
the first parameter of subprocess.Popen(). If a suitable session cannot
be found, returns None.
"""
XSESSION_FILES = [SESSION_FILE_PATH, SYSTEM_SESSION_FILE_PATH]
for startup_file in XSESSION_FILES:
startup_file = os.path.expanduser(startup_file)
if os.path.exists(startup_file):
return bash_invocation_for_script(startup_file)
# If there's no configuration, show the user a session chooser.
return [HOST_BINARY_PATH, "--type=xsession_chooser"]
def exec_self_via_login_shell():
"""Attempt to run the user's login shell and run this script under it. This
will allow the user's ~/.profile or similar to be processed, which may set
environment variables to configure Chrome Remote Desktop."""
args = [sys.argv[0], "--child-process"] + [
arg for arg in sys.argv[1:] if arg != "--new-session"
]
try:
shell = os.getenv("SHELL")
if shell is not None:
# Shells consider themselves a login shell if arg0 starts with a '-'.
shell_arg0 = "-" + os.path.basename(shell)
# First, ensure we can execute commands via the user's login shell. Some
# users have an incorrect .profile or similar that breaks this.
output = subprocess.check_output(
[shell_arg0],
executable=shell,
input=b"exec echo CRD_SHELL_TEST_OUTPUT",
timeout=15,
)
if b"CRD_SHELL_TEST_OUTPUT" in output:
# subprocess doesn't support calling exec without fork, so we need to
# set up our pipe manually.
read_fd, write_fd = os.pipe()
# The command line should easily fit in the 16KiB pipe buffer.
os.write(
write_fd, b"exec " + os.fsencode(" ".join(map(shlex.quote, args)))
)
os.close(write_fd)
os.dup2(read_fd, 0)
os.close(read_fd)
os.execv(shell, [shell_arg0])
else:
logging.warning("Login shell doesn't execute standard input.")
else:
logging.warning("SHELL envirionment variable not set.")
except Exception as e:
logging.warning(str(e))
logging.warning(
"Failed to run via login shell; continuing without. Environment "
"variables set via ~/.profile or similar won't be processed."
)
os.execv(args[0], args)
def unset_crd_systemd_env_vars():
"""Unsets environment variables set by this script that could interfere
with the multi-process host or local sessions."""
# If we immediately unset these environment variables, something (probably
# a (sub)process of gnome-session) will add them back, so we wait for a
# second to allow the GNOME session to terminate cleanly.
logging.info(
"Waiting for one second before unsetting systemd environment variables."
)
time.sleep(1)
logging.info("Unsetting systemd user environment variables.")
subprocess.call(
["systemctl", "--user", "unset-environment"] + CRD_SYSTEMD_ENV_VARS_TO_UNSET
)
def cleanup():
logging.info("Cleanup.")
global g_desktop
if g_desktop is not None:
g_desktop.cleanup()
if getattr(g_desktop, 'xorg_conf', None) is not None:
os.remove(g_desktop.xorg_conf)
os.rmdir(os.path.dirname(g_desktop.xorg_conf))
g_desktop = None
unset_crd_systemd_env_vars()
class RelaunchInhibitor:
"""Helper class for inhibiting launch of a child process before a timeout has
elapsed.
A managed process can be in one of these states:
running, not inhibited (running == True)
stopped and inhibited (running == False and is_inhibited() == True)
stopped but not inhibited (running == False and is_inhibited() == False)
Attributes:
label: Name of the tracked process. Only used for logging.
running: Whether the process is currently running.
earliest_relaunch_time: Time before which the process should not be
relaunched, or 0 if there is no limit.
failures: The number of times that the process ran for less than a
specified timeout, and had to be inhibited. This count is reset to 0
whenever the process has run for longer than the timeout.
"""
def __init__(self, label):
self.label = label
self.running = False
self.disabled = False
self.earliest_relaunch_time = 0
self.earliest_successful_termination = 0
self.failures = 0
def is_inhibited(self):
return (not self.running) and (time.time() < self.earliest_relaunch_time)
def record_started(self, minimum_lifetime, relaunch_delay):
"""Record that the process was launched, and set the inhibit time to
|timeout| seconds in the future."""
self.earliest_relaunch_time = time.time() + relaunch_delay
self.earliest_successful_termination = time.time() + minimum_lifetime
self.running = True
def record_stopped(self, expected):
"""Record that the process was stopped, and adjust the failure count
depending on whether the process ran long enough. If the process was
intentionally stopped (expected is True), the failure count will not be
incremented."""
self.running = False
if time.time() >= self.earliest_successful_termination:
self.failures = 0
elif not expected:
self.failures += 1
logging.info("Failure count for '%s' is now %d", self.label, self.failures)
def disable(self):
"""Disable launching this process, such as if the needed components are
missing and launching it is never expected to succeed. Only makes sense for
non-critical processes. (Otherwise, the script should just bail.)"""
self.disabled = True
def relaunch_self():
"""Relaunches the session to pick up any changes to the session logic in case
Chrome Remote Desktop has been upgraded. We return a special exit code to
inform user-session that it should relaunch.
"""
# cleanup run via atexit
sys.exit(RELAUNCH_EXIT_CODE)
def waitpid_with_timeout(pid, deadline):
"""Wrapper around os.waitpid() which waits until either a child process dies
or the deadline elapses.
Args:
pid: Process ID to wait for, or -1 to wait for any child process.
deadline: Waiting stops when time.time() exceeds this value.
Returns:
(pid, status): Same as for os.waitpid(), except that |pid| is 0 if no child
changed state within the timeout.
Raises:
Same as for os.waitpid().
"""
while time.time() < deadline:
pid, status = os.waitpid(pid, os.WNOHANG)
if pid != 0:
return (pid, status)
time.sleep(1)
return (0, 0)
def waitpid_handle_exceptions(pid, deadline):
"""Wrapper around os.waitpid()/waitpid_with_timeout(), which waits until
either a child process exits or the deadline elapses, and retries if certain
exceptions occur.
Args:
pid: Process ID to wait for, or -1 to wait for any child process.
deadline: If non-zero, waiting stops when time.time() exceeds this value.
If zero, waiting stops when a child process exits.
Returns:
(pid, status): Same as for waitpid_with_timeout(). |pid| is non-zero if and
only if a child exited during the wait.
Raises:
Same as for os.waitpid(), except:
OSError with errno==EINTR causes the wait to be retried (this can happen,
for example, if this parent process receives SIGHUP).
OSError with errno==ECHILD means there are no child processes, and so
this function sleeps until |deadline|. If |deadline| is zero, this is an
error and the OSError exception is raised in this case.
"""
while True:
try:
if deadline == 0:
pid_result, status = os.waitpid(pid, 0)
else:
pid_result, status = waitpid_with_timeout(pid, deadline)
return (pid_result, status)
except OSError as e:
if e.errno == errno.EINTR:
continue
elif e.errno == errno.ECHILD:
now = time.time()
if deadline == 0:
# No time-limit and no child processes. This is treated as an error
# (see docstring).
raise
elif deadline > now:
time.sleep(deadline - now)
return (0, 0)
else:
# Anything else is an unexpected error.
raise
def watch_for_resolution_changes(initial_size):
"""Watches for any resolution-changes which set the maximum screen resolution,
and resets the initial size if this happens.
The Ubuntu desktop has a component (the 'xrandr' plugin of
unity-settings-daemon) which often changes the screen resolution to the
first listed mode. This is the built-in mode for the maximum screen size,
which can trigger excessive CPU usage in some situations. So this is a hack
which waits for any such events, and undoes the change if it occurs.
Sometimes, the user might legitimately want to use the maximum available
resolution, so this monitoring is limited to a short time-period.
"""
for _ in range(30):
time.sleep(1)
xrandr_output = subprocess.Popen(
["xrandr"], stdout=subprocess.PIPE
).communicate()[0]
match = re.search(
rb'current (\d+) x (\d+), maximum (\d+) x (\d+)', xrandr_output
)
# No need to handle ValueError. If xrandr fails to give valid output,
# there's no point in continuing to monitor.
current_size = (int(match.group(1)), int(match.group(2)))
maximum_size = (int(match.group(3)), int(match.group(4)))
if current_size != initial_size:
# Resolution change detected.
if current_size == maximum_size:
# This was probably an automated change from unity-settings-daemon, so
# undo it.
label = "%dx%d" % initial_size
args = ["xrandr", "-s", label]
subprocess.call(args)
args = ["xrandr", "--dpi", "96"]
subprocess.call(args)
# Stop monitoring after any change was detected.
break
def create_desktop(extra_start_host_args=None, host_delegate=None):
"""Instantiates either a WaylandDesktop or XDesktop based on the environment
and optional extra start-host arguments."""
if extra_start_host_args is None:
extra_start_host_args = []
is_wayland = (
USE_WAYLAND_ENV_VAR in os.environ
or '--enable-wayland' in extra_start_host_args
)
if is_wayland:
wayland_session_type = os.environ.get(USE_WAYLAND_ENV_VAR)
# Use GNOME as the default Wayland session.
wayland_session_class = (
WAYLAND_SESSIONS[wayland_session_type]
if wayland_session_type in WAYLAND_SESSIONS
else GnomeWaylandSession
)
return WaylandDesktop(wayland_session_class(), host_delegate=host_delegate)
else:
return XDesktop(host_delegate=host_delegate)