Advertisement
ATGardner

chrome-remote-desktop

Apr 26th, 2015
628
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 48.87 KB | None | 0 0
  1. #!/usr/bin/python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5.  
  6. # Virtual Me2Me implementation.  This script runs and manages the processes
  7. # required for a Virtual Me2Me desktop, which are: X server, X desktop
  8. # session, and Host process.
  9. # This script is intended to run continuously as a background daemon
  10. # process, running under an ordinary (non-root) user account.
  11.  
  12. import atexit
  13. import errno
  14. import fcntl
  15. import getpass
  16. import grp
  17. import hashlib
  18. import json
  19. import logging
  20. import optparse
  21. import os
  22. import pipes
  23. import platform
  24. import psutil
  25. import platform
  26. import re
  27. import signal
  28. import socket
  29. import subprocess
  30. import sys
  31. import tempfile
  32. import time
  33. import uuid
  34.  
  35. LOG_FILE_ENV_VAR = "CHROME_REMOTE_DESKTOP_LOG_FILE"
  36.  
  37. # This script has a sensible default for the initial and maximum desktop size,
  38. # which can be overridden either on the command-line, or via a comma-separated
  39. # list of sizes in this environment variable.
  40. DEFAULT_SIZES_ENV_VAR = "CHROME_REMOTE_DESKTOP_DEFAULT_DESKTOP_SIZES"
  41.  
  42. # By default, provide a maximum size that is large enough to support clients
  43. # with large or multiple monitors. This is a comma-separated list of
  44. # resolutions that will be made available if the X server supports RANDR. These
  45. # defaults can be overridden in ~/.profile.
  46. DEFAULT_SIZES = "1600x1200,3840x2560"
  47.  
  48. # If RANDR is not available, use a smaller default size. Only a single
  49. # resolution is supported in this case.
  50. DEFAULT_SIZE_NO_RANDR = "1600x1200"
  51.  
  52. SCRIPT_PATH = sys.path[0]
  53.  
  54. IS_INSTALLED = (os.path.basename(sys.argv[0]) != 'linux_me2me_host.py')
  55.  
  56. if IS_INSTALLED:
  57.   HOST_BINARY_NAME = "chrome-remote-desktop-host"
  58. else:
  59.   HOST_BINARY_NAME = "remoting_me2me_host"
  60.  
  61. CHROME_REMOTING_GROUP_NAME = "chrome-remote-desktop"
  62.  
  63. HOME_DIR = os.environ["HOME"]
  64. CONFIG_DIR = os.path.join(HOME_DIR, ".config/chrome-remote-desktop")
  65. SESSION_FILE_PATH = os.path.join(HOME_DIR, ".chrome-remote-desktop-session")
  66. SYSTEM_SESSION_FILE_PATH = "/etc/chrome-remote-desktop-session"
  67.  
  68. X_LOCK_FILE_TEMPLATE = "/tmp/.X%d-lock"
  69. FIRST_X_DISPLAY_NUMBER = 20
  70.  
  71. # Amount of time to wait between relaunching processes.
  72. SHORT_BACKOFF_TIME = 5
  73. LONG_BACKOFF_TIME = 60
  74.  
  75. # How long a process must run in order not to be counted against the restart
  76. # thresholds.
  77. MINIMUM_PROCESS_LIFETIME = 60
  78.  
  79. # Thresholds for switching from fast- to slow-restart and for giving up
  80. # trying to restart entirely.
  81. SHORT_BACKOFF_THRESHOLD = 5
  82. MAX_LAUNCH_FAILURES = SHORT_BACKOFF_THRESHOLD + 10
  83.  
  84. # Globals needed by the atexit cleanup() handler.
  85. g_desktops = []
  86. g_host_hash = hashlib.md5(socket.gethostname()).hexdigest()
  87.  
  88.  
  89. def is_supported_platform():
  90.   # Always assume that the system is supported if the config directory or
  91.   # session file exist.
  92.   if (os.path.isdir(CONFIG_DIR) or os.path.isfile(SESSION_FILE_PATH) or
  93.       os.path.isfile(SYSTEM_SESSION_FILE_PATH)):
  94.     return True
  95.  
  96.   # The host has been tested only on Ubuntu.
  97.   distribution = platform.linux_distribution()
  98.   return (distribution[0]).lower() == 'ubuntu'
  99.  
  100.  
  101. def get_randr_supporting_x_server():
  102.   """Returns a path to an X server that supports the RANDR extension, if this
  103.  is found on the system. Otherwise returns None."""
  104.   try:
  105.     xvfb = "/usr/bin/Xvfb-randr"
  106.     if not os.path.exists(xvfb):
  107.       xvfb = locate_executable("Xvfb-randr")
  108.     return xvfb
  109.   except Exception:
  110.     return None
  111.  
  112.  
  113. class Config:
  114.   def __init__(self, path):
  115.     self.path = path
  116.     self.data = {}
  117.     self.changed = False
  118.  
  119.   def load(self):
  120.     """Loads the config from file.
  121.  
  122.    Raises:
  123.      IOError: Error reading data
  124.      ValueError: Error parsing JSON
  125.    """
  126.     settings_file = open(self.path, 'r')
  127.     self.data = json.load(settings_file)
  128.     self.changed = False
  129.     settings_file.close()
  130.  
  131.   def save(self):
  132.     """Saves the config to file.
  133.  
  134.    Raises:
  135.      IOError: Error writing data
  136.      TypeError: Error serialising JSON
  137.    """
  138.     if not self.changed:
  139.       return
  140.     old_umask = os.umask(0066)
  141.     try:
  142.       settings_file = open(self.path, 'w')
  143.       settings_file.write(json.dumps(self.data, indent=2))
  144.       settings_file.close()
  145.       self.changed = False
  146.     finally:
  147.       os.umask(old_umask)
  148.  
  149.   def save_and_log_errors(self):
  150.     """Calls self.save(), trapping and logging any errors."""
  151.     try:
  152.       self.save()
  153.     except (IOError, TypeError) as e:
  154.       logging.error("Failed to save config: " + str(e))
  155.  
  156.   def get(self, key):
  157.     return self.data.get(key)
  158.  
  159.   def __getitem__(self, key):
  160.     return self.data[key]
  161.  
  162.   def __setitem__(self, key, value):
  163.     self.data[key] = value
  164.     self.changed = True
  165.  
  166.   def clear(self):
  167.     self.data = {}
  168.     self.changed = True
  169.  
  170.  
  171. class Authentication:
  172.   """Manage authentication tokens for Chromoting/xmpp"""
  173.  
  174.   def __init__(self):
  175.     self.login = None
  176.     self.oauth_refresh_token = None
  177.  
  178.   def copy_from(self, config):
  179.     """Loads the config and returns false if the config is invalid."""
  180.     try:
  181.       self.login = config["xmpp_login"]
  182.       self.oauth_refresh_token = config["oauth_refresh_token"]
  183.     except KeyError:
  184.       return False
  185.     return True
  186.  
  187.   def copy_to(self, config):
  188.     config["xmpp_login"] = self.login
  189.     config["oauth_refresh_token"] = self.oauth_refresh_token
  190.  
  191.  
  192. class Host:
  193.   """This manages the configuration for a host."""
  194.  
  195.   def __init__(self):
  196.     self.host_id = str(uuid.uuid1())
  197.     self.host_name = socket.gethostname()
  198.     self.host_secret_hash = None
  199.     self.private_key = None
  200.  
  201.   def copy_from(self, config):
  202.     try:
  203.       self.host_id = config["host_id"]
  204.       self.host_name = config["host_name"]
  205.       self.host_secret_hash = config.get("host_secret_hash")
  206.       self.private_key = config["private_key"]
  207.     except KeyError:
  208.       return False
  209.     return True
  210.  
  211.   def copy_to(self, config):
  212.     config["host_id"] = self.host_id
  213.     config["host_name"] = self.host_name
  214.     config["host_secret_hash"] = self.host_secret_hash
  215.     config["private_key"] = self.private_key
  216.  
  217.  
  218. class Desktop:
  219.   """Manage a single virtual desktop"""
  220.  
  221.   def __init__(self, sizes):
  222.     self.x_proc = None
  223.     self.session_proc = None
  224.     self.host_proc = None
  225.     self.child_env = None
  226.     self.sizes = sizes
  227.     self.pulseaudio_pipe = None
  228.     self.server_supports_exact_resize = False
  229.     self.host_ready = False
  230.     self.ssh_auth_sockname = None
  231.     g_desktops.append(self)
  232.  
  233.   @staticmethod
  234.   def get_unused_display_number():
  235.     """Return a candidate display number for which there is currently no
  236.    X Server lock file"""
  237.     display = FIRST_X_DISPLAY_NUMBER
  238.     while os.path.exists(X_LOCK_FILE_TEMPLATE % display):
  239.       display += 1
  240.     return display
  241.  
  242.   def _init_child_env(self):
  243.     # Create clean environment for new session, so it is cleanly separated from
  244.     # the user's console X session.
  245.     self.child_env = {}
  246.  
  247.     for key in [
  248.         "HOME",
  249.         "LANG",
  250.         "LOGNAME",
  251.         "PATH",
  252.         "SHELL",
  253.         "USER",
  254.         "USERNAME",
  255.         LOG_FILE_ENV_VAR]:
  256.       if os.environ.has_key(key):
  257.         self.child_env[key] = os.environ[key]
  258.  
  259.     # Ensure that the software-rendering GL drivers are loaded by the desktop
  260.     # session, instead of any hardware GL drivers installed on the system.
  261.     self.child_env["LD_LIBRARY_PATH"] = (
  262.         "/usr/lib/%(arch)s-linux-gnu/mesa:"
  263.         "/usr/lib/%(arch)s-linux-gnu/dri:"
  264.         "/usr/lib/%(arch)s-linux-gnu/gallium-pipe" %
  265.         { "arch": platform.machine() })
  266.  
  267.     # Read from /etc/environment if it exists, as it is a standard place to
  268.     # store system-wide environment settings. During a normal login, this would
  269.     # typically be done by the pam_env PAM module, depending on the local PAM
  270.     # configuration.
  271.     env_filename = "/etc/environment"
  272.     try:
  273.       with open(env_filename, "r") as env_file:
  274.         for line in env_file:
  275.           line = line.rstrip("\n")
  276.           # Split at the first "=", leaving any further instances in the value.
  277.           key_value_pair = line.split("=", 1)
  278.           if len(key_value_pair) == 2:
  279.             key, value = tuple(key_value_pair)
  280.             # The file stores key=value assignments, but the value may be
  281.             # quoted, so strip leading & trailing quotes from it.
  282.             value = value.strip("'\"")
  283.             self.child_env[key] = value
  284.     except IOError:
  285.       logging.info("Failed to read %s, skipping." % env_filename)
  286.  
  287.   def _setup_pulseaudio(self):
  288.     self.pulseaudio_pipe = None
  289.  
  290.     # pulseaudio uses UNIX sockets for communication. Length of UNIX socket
  291.     # name is limited to 108 characters, so audio will not work properly if
  292.     # the path is too long. To workaround this problem we use only first 10
  293.     # symbols of the host hash.
  294.     pulse_path = os.path.join(CONFIG_DIR,
  295.                               "pulseaudio#%s" % g_host_hash[0:10])
  296.     if len(pulse_path) + len("/native") >= 108:
  297.       logging.error("Audio will not be enabled because pulseaudio UNIX " +
  298.                     "socket path is too long.")
  299.       return False
  300.  
  301.     sink_name = "chrome_remote_desktop_session"
  302.     pipe_name = os.path.join(pulse_path, "fifo_output")
  303.  
  304.     try:
  305.       if not os.path.exists(pulse_path):
  306.         os.mkdir(pulse_path)
  307.     except IOError, e:
  308.       logging.error("Failed to create pulseaudio pipe: " + str(e))
  309.       return False
  310.  
  311.     try:
  312.       pulse_config = open(os.path.join(pulse_path, "daemon.conf"), "w")
  313.       pulse_config.write("default-sample-format = s16le\n")
  314.       pulse_config.write("default-sample-rate = 48000\n")
  315.       pulse_config.write("default-sample-channels = 2\n")
  316.       pulse_config.close()
  317.  
  318.       pulse_script = open(os.path.join(pulse_path, "default.pa"), "w")
  319.       pulse_script.write("load-module module-native-protocol-unix\n")
  320.       pulse_script.write(
  321.           ("load-module module-pipe-sink sink_name=%s file=\"%s\" " +
  322.            "rate=48000 channels=2 format=s16le\n") %
  323.           (sink_name, pipe_name))
  324.       pulse_script.close()
  325.     except IOError, e:
  326.       logging.error("Failed to write pulseaudio config: " + str(e))
  327.       return False
  328.  
  329.     self.child_env["PULSE_CONFIG_PATH"] = pulse_path
  330.     self.child_env["PULSE_RUNTIME_PATH"] = pulse_path
  331.     self.child_env["PULSE_STATE_PATH"] = pulse_path
  332.     self.child_env["PULSE_SINK"] = sink_name
  333.     self.pulseaudio_pipe = pipe_name
  334.  
  335.     return True
  336.  
  337.   def _setup_gnubby(self):
  338.     self.ssh_auth_sockname = ("/tmp/chromoting.%s.ssh_auth_sock" %
  339.                               os.environ["USER"])
  340.  
  341.   def _launch_x_server(self, extra_x_args):
  342.     x_auth_file = os.path.expanduser("~/.Xauthority")
  343.     self.child_env["XAUTHORITY"] = x_auth_file
  344.     devnull = open(os.devnull, "rw")
  345.     display = self.get_unused_display_number()
  346.  
  347.     # Run "xauth add" with |child_env| so that it modifies the same XAUTHORITY
  348.     # file which will be used for the X session.
  349.     ret_code = subprocess.call("xauth add :%d . `mcookie`" % display,
  350.                                env=self.child_env, shell=True)
  351.     if ret_code != 0:
  352.       raise Exception("xauth failed with code %d" % ret_code)
  353.  
  354.     max_width = max([width for width, height in self.sizes])
  355.     max_height = max([height for width, height in self.sizes])
  356.  
  357.     xvfb = get_randr_supporting_x_server()
  358.     if xvfb:
  359.       self.server_supports_exact_resize = True
  360.     else:
  361.       xvfb = "Xvfb"
  362.       self.server_supports_exact_resize = False
  363.  
  364.     # Disable the Composite extension iff the X session is the default
  365.     # Unity-2D, since it uses Metacity which fails to generate DAMAGE
  366.     # notifications correctly. See crbug.com/166468.
  367.     x_session = choose_x_session()
  368.     if (len(x_session) == 2 and
  369.         x_session[1] == "/usr/bin/gnome-session --session=ubuntu-2d"):
  370.       extra_x_args.extend(["-extension", "Composite"])
  371.  
  372.     logging.info("Starting %s on display :%d" % (xvfb, display))
  373.     screen_option = "%dx%dx24" % (max_width, max_height)
  374.     self.x_proc = subprocess.Popen(
  375.         [xvfb, ":%d" % display,
  376.          "-auth", x_auth_file,
  377.          "-nolisten", "tcp",
  378.          "-noreset",
  379.          "-screen", "0", screen_option
  380.         ] + extra_x_args)
  381.     if not self.x_proc.pid:
  382.       raise Exception("Could not start Xvfb.")
  383.  
  384.     self.child_env["DISPLAY"] = ":%d" % display
  385.     self.child_env["CHROME_REMOTE_DESKTOP_SESSION"] = "1"
  386.  
  387.     # Use a separate profile for any instances of Chrome that are started in
  388.     # the virtual session. Chrome doesn't support sharing a profile between
  389.     # multiple DISPLAYs, but Chrome Sync allows for a reasonable compromise.
  390.     chrome_profile = os.path.join(CONFIG_DIR, "chrome-profile")
  391.     self.child_env["CHROME_USER_DATA_DIR"] = chrome_profile
  392.  
  393.     # Set SSH_AUTH_SOCK to the file name to listen on.
  394.     if self.ssh_auth_sockname:
  395.       self.child_env["SSH_AUTH_SOCK"] = self.ssh_auth_sockname
  396.  
  397.     # Wait for X to be active.
  398.     for _test in range(20):
  399.       retcode = subprocess.call("xdpyinfo", env=self.child_env, stdout=devnull)
  400.       if retcode == 0:
  401.         break
  402.       time.sleep(0.5)
  403.     if retcode != 0:
  404.       raise Exception("Could not connect to Xvfb.")
  405.     else:
  406.       logging.info("Xvfb is active.")
  407.  
  408.     # The remoting host expects the server to use "evdev" keycodes, but Xvfb
  409.     # starts configured to use the "base" ruleset, resulting in XKB configuring
  410.     # for "xfree86" keycodes, and screwing up some keys. See crbug.com/119013.
  411.     # Reconfigure the X server to use "evdev" keymap rules.  The X server must
  412.     # be started with -noreset otherwise it'll reset as soon as the command
  413.     # completes, since there are no other X clients running yet.
  414.     retcode = subprocess.call("setxkbmap -rules evdev", env=self.child_env,
  415.                               shell=True)
  416.     if retcode != 0:
  417.       logging.error("Failed to set XKB to 'evdev'")
  418.  
  419.     if not self.server_supports_exact_resize:
  420.       return
  421.  
  422.     # Register the screen sizes if the X server's RANDR extension supports it.
  423.     # Errors here are non-fatal; the X server will continue to run with the
  424.     # dimensions from the "-screen" option.
  425.     for width, height in self.sizes:
  426.       label = "%dx%d" % (width, height)
  427.       args = ["xrandr", "--newmode", label, "0", str(width), "0", "0", "0",
  428.               str(height), "0", "0", "0"]
  429.       subprocess.call(args, env=self.child_env, stdout=devnull, stderr=devnull)
  430.       args = ["xrandr", "--addmode", "screen", label]
  431.       subprocess.call(args, env=self.child_env, stdout=devnull, stderr=devnull)
  432.  
  433.     # Set the initial mode to the first size specified, otherwise the X server
  434.     # would default to (max_width, max_height), which might not even be in the
  435.     # list.
  436.     initial_size = self.sizes[0]
  437.     label = "%dx%d" % initial_size
  438.     args = ["xrandr", "-s", label]
  439.     subprocess.call(args, env=self.child_env, stdout=devnull, stderr=devnull)
  440.  
  441.     # Set the physical size of the display so that the initial mode is running
  442.     # at approximately 96 DPI, since some desktops require the DPI to be set to
  443.     # something realistic.
  444.     args = ["xrandr", "--dpi", "96"]
  445.     subprocess.call(args, env=self.child_env, stdout=devnull, stderr=devnull)
  446.  
  447.     # Monitor for any automatic resolution changes from the desktop environment.
  448.     args = [sys.argv[0], "--watch-resolution", str(initial_size[0]),
  449.             str(initial_size[1])]
  450.  
  451.     # It is not necessary to wait() on the process here, as this script's main
  452.     # loop will reap the exit-codes of all child processes.
  453.     subprocess.Popen(args, env=self.child_env, stdout=devnull, stderr=devnull)
  454.  
  455.     devnull.close()
  456.  
  457.   def _launch_x_session(self):
  458.     # Start desktop session.
  459.     # The /dev/null input redirection is necessary to prevent the X session
  460.     # reading from stdin.  If this code runs as a shell background job in a
  461.     # terminal, any reading from stdin causes the job to be suspended.
  462.     # Daemonization would solve this problem by separating the process from the
  463.     # controlling terminal.
  464.     xsession_command = choose_x_session()
  465.     if xsession_command is None:
  466.       raise Exception("Unable to choose suitable X session command.")
  467.  
  468.     logging.info("Launching X session: %s" % xsession_command)
  469.     self.session_proc = subprocess.Popen(xsession_command,
  470.                                          stdin=open(os.devnull, "r"),
  471.                                          cwd=HOME_DIR,
  472.                                          env=self.child_env)
  473.     if not self.session_proc.pid:
  474.       raise Exception("Could not start X session")
  475.  
  476.   def launch_session(self, x_args):
  477.     self._init_child_env()
  478.     self._setup_pulseaudio()
  479.     self._setup_gnubby()
  480.     self._launch_x_server(x_args)
  481.     self._launch_x_session()
  482.  
  483.   def launch_host(self, host_config):
  484.     # Start remoting host
  485.     args = [locate_executable(HOST_BINARY_NAME), "--host-config=-"]
  486.     if self.pulseaudio_pipe:
  487.       args.append("--audio-pipe-name=%s" % self.pulseaudio_pipe)
  488.     if self.server_supports_exact_resize:
  489.       args.append("--server-supports-exact-resize")
  490.     if self.ssh_auth_sockname:
  491.       args.append("--ssh-auth-sockname=%s" % self.ssh_auth_sockname)
  492.  
  493.     # Have the host process use SIGUSR1 to signal a successful start.
  494.     def sigusr1_handler(signum, frame):
  495.       _ = signum, frame
  496.       logging.info("Host ready to receive connections.")
  497.       self.host_ready = True
  498.       if (ParentProcessLogger.instance() and
  499.           False not in [desktop.host_ready for desktop in g_desktops]):
  500.         ParentProcessLogger.instance().release_parent()
  501.  
  502.     signal.signal(signal.SIGUSR1, sigusr1_handler)
  503.     args.append("--signal-parent")
  504.  
  505.     self.host_proc = subprocess.Popen(args, env=self.child_env,
  506.                                       stdin=subprocess.PIPE)
  507.     logging.info(args)
  508.     if not self.host_proc.pid:
  509.       raise Exception("Could not start Chrome Remote Desktop host")
  510.     self.host_proc.stdin.write(json.dumps(host_config.data))
  511.     self.host_proc.stdin.close()
  512.  
  513.  
  514. def get_daemon_proc():
  515.   """Checks if there is already an instance of this script running, and returns
  516.  a psutil.Process instance for it.
  517.  
  518.  Returns:
  519.    A Process instance for the existing daemon process, or None if the daemon
  520.    is not running.
  521.  """
  522.  
  523.   uid = os.getuid()
  524.   this_pid = os.getpid()
  525.  
  526.   # Support new & old psutil API. This is the right way to check, according to
  527.   # http://grodola.blogspot.com/2014/01/psutil-20-porting.html
  528.   if psutil.version_info >= (2, 0):
  529.     psget = lambda x: x()
  530.   else:
  531.     psget = lambda x: x
  532.  
  533.   for process in psutil.process_iter():
  534.     # Skip any processes that raise an exception, as processes may terminate
  535.     # during iteration over the list.
  536.     try:
  537.       # Skip other users' processes.
  538.       if psget(process.uids).real != uid:
  539.         continue
  540.  
  541.       # Skip the process for this instance.
  542.       if process.pid == this_pid:
  543.         continue
  544.  
  545.       # |cmdline| will be [python-interpreter, script-file, other arguments...]
  546.       cmdline = psget(process.cmdline)
  547.       if len(cmdline) < 2:
  548.         continue
  549.       if cmdline[0] == sys.executable and cmdline[1] == sys.argv[0]:
  550.         return process
  551.     except (psutil.NoSuchProcess, psutil.AccessDenied):
  552.       continue
  553.  
  554.   return None
  555.  
  556.  
  557. def choose_x_session():
  558.   """Chooses the most appropriate X session command for this system.
  559.  
  560.  Returns:
  561.    A string containing the command to run, or a list of strings containing
  562.    the executable program and its arguments, which is suitable for passing as
  563.    the first parameter of subprocess.Popen().  If a suitable session cannot
  564.    be found, returns None.
  565.  """
  566.   XSESSION_FILES = [
  567.     SESSION_FILE_PATH,
  568.     SYSTEM_SESSION_FILE_PATH ]
  569.   for startup_file in XSESSION_FILES:
  570.     startup_file = os.path.expanduser(startup_file)
  571.     if os.path.exists(startup_file):
  572.       if os.access(startup_file, os.X_OK):
  573.         # "/bin/sh -c" is smart about how to execute the session script and
  574.         # works in cases where plain exec() fails (for example, if the file is
  575.         # marked executable, but is a plain script with no shebang line).
  576.         return ["/bin/sh", "-c", pipes.quote(startup_file)]
  577.       else:
  578.         # If this is a system-wide session script, it should be run using the
  579.         # system shell, ignoring any login shell that might be set for the
  580.         # current user.
  581.         return ["/bin/sh", startup_file]
  582.  
  583.   # Choose a session wrapper script to run the session. On some systems,
  584.   # /etc/X11/Xsession fails to load the user's .profile, so look for an
  585.   # alternative wrapper that is more likely to match the script that the
  586.   # system actually uses for console desktop sessions.
  587.   SESSION_WRAPPERS = [
  588.     "/usr/sbin/lightdm-session",
  589.     "/etc/gdm/Xsession",
  590.     "/etc/X11/Xsession" ]
  591.   for session_wrapper in SESSION_WRAPPERS:
  592.     if os.path.exists(session_wrapper):
  593.       if os.path.exists("/usr/bin/unity-2d-panel"):
  594.         # On Ubuntu 12.04, the default session relies on 3D-accelerated
  595.         # hardware. Trying to run this with a virtual X display produces
  596.         # weird results on some systems (for example, upside-down and
  597.         # corrupt displays).  So if the ubuntu-2d session is available,
  598.         # choose it explicitly.
  599.         return [session_wrapper, "/usr/bin/gnome-session --session=ubuntu-2d"]
  600.       else:
  601.         # Use the session wrapper by itself, and let the system choose a
  602.         # session.
  603.         return [session_wrapper]
  604.   return None
  605.  
  606.  
  607. def locate_executable(exe_name):
  608.   if IS_INSTALLED:
  609.     # If the script is running from its installed location, search the host
  610.     # binary only in the same directory.
  611.     paths_to_try = [ SCRIPT_PATH ]
  612.   else:
  613.     paths_to_try = map(lambda p: os.path.join(SCRIPT_PATH, p),
  614.                        [".", "../../../out/Debug", "../../../out/Release" ])
  615.   for path in paths_to_try:
  616.     exe_path = os.path.join(path, exe_name)
  617.     if os.path.exists(exe_path):
  618.       return exe_path
  619.  
  620.   raise Exception("Could not locate executable '%s'" % exe_name)
  621.  
  622.  
  623. class ParentProcessLogger(object):
  624.   """Redirects logs to the parent process, until the host is ready or quits.
  625.  
  626.  This class creates a pipe to allow logging from the daemon process to be
  627.  copied to the parent process. The daemon process adds a log-handler that
  628.  directs logging output to the pipe. The parent process reads from this pipe
  629.  until and writes the content to stderr.  When the pipe is no longer needed
  630.  (for example, the host signals successful launch or permanent failure), the
  631.  daemon removes the log-handler and closes the pipe, causing the the parent
  632.  process to reach end-of-file while reading the pipe and exit.
  633.  
  634.  The (singleton) logger should be instantiated before forking. The parent
  635.  process should call wait_for_logs() before exiting. The (grand-)child process
  636.  should call start_logging() when it starts, and then use logging.* to issue
  637.  log statements, as usual. When the child has either succesfully started the
  638.  host or terminated, it must call release_parent() to allow the parent to exit.
  639.  """
  640.  
  641.   __instance = None
  642.  
  643.   def __init__(self):
  644.     """Constructor. Must be called before forking."""
  645.     read_pipe, write_pipe = os.pipe()
  646.     # Ensure write_pipe is closed on exec, otherwise it will be kept open by
  647.     # child processes (X, host), preventing the read pipe from EOF'ing.
  648.     old_flags = fcntl.fcntl(write_pipe, fcntl.F_GETFD)
  649.     fcntl.fcntl(write_pipe, fcntl.F_SETFD, old_flags | fcntl.FD_CLOEXEC)
  650.     self._read_file = os.fdopen(read_pipe, 'r')
  651.     self._write_file = os.fdopen(write_pipe, 'a')
  652.     self._logging_handler = None
  653.     ParentProcessLogger.__instance = self
  654.  
  655.   def start_logging(self):
  656.     """Installs a logging handler that sends log entries to a pipe.
  657.  
  658.    Must be called by the child process.
  659.    """
  660.     self._read_file.close()
  661.     self._logging_handler = logging.StreamHandler(self._write_file)
  662.     logging.getLogger().addHandler(self._logging_handler)
  663.  
  664.   def release_parent(self):
  665.     """Uninstalls logging handler and closes the pipe, releasing the parent.
  666.  
  667.    Must be called by the child process.
  668.    """
  669.     if self._logging_handler:
  670.       logging.getLogger().removeHandler(self._logging_handler)
  671.       self._logging_handler = None
  672.     if not self._write_file.closed:
  673.       self._write_file.close()
  674.  
  675.   def wait_for_logs(self):
  676.     """Waits and prints log lines from the daemon until the pipe is closed.
  677.  
  678.    Must be called by the parent process.
  679.    """
  680.     # If Ctrl-C is pressed, inform the user that the daemon is still running.
  681.     # This signal will cause the read loop below to stop with an EINTR IOError.
  682.     def sigint_handler(signum, frame):
  683.       _ = signum, frame
  684.       print >> sys.stderr, ("Interrupted. The daemon is still running in the "
  685.                             "background.")
  686.  
  687.     signal.signal(signal.SIGINT, sigint_handler)
  688.  
  689.     # Install a fallback timeout to release the parent process, in case the
  690.     # daemon never responds (e.g. host crash-looping, daemon killed).
  691.     # This signal will cause the read loop below to stop with an EINTR IOError.
  692.     def sigalrm_handler(signum, frame):
  693.       _ = signum, frame
  694.       print >> sys.stderr, ("No response from daemon. It may have crashed, or "
  695.                             "may still be running in the background.")
  696.  
  697.     signal.signal(signal.SIGALRM, sigalrm_handler)
  698.     signal.alarm(30)
  699.  
  700.     self._write_file.close()
  701.  
  702.     # Print lines as they're logged to the pipe until EOF is reached or readline
  703.     # is interrupted by one of the signal handlers above.
  704.     try:
  705.       for line in iter(self._read_file.readline, ''):
  706.         sys.stderr.write(line)
  707.     except IOError as e:
  708.       if e.errno != errno.EINTR:
  709.         raise
  710.     print >> sys.stderr, "Log file: %s" % os.environ[LOG_FILE_ENV_VAR]
  711.  
  712.   @staticmethod
  713.   def instance():
  714.     """Returns the singleton instance, if it exists."""
  715.     return ParentProcessLogger.__instance
  716.  
  717.  
  718. def daemonize():
  719.   """Background this process and detach from controlling terminal, redirecting
  720.  stdout/stderr to a log file."""
  721.  
  722.   # TODO(lambroslambrou): Having stdout/stderr redirected to a log file is not
  723.   # ideal - it could create a filesystem DoS if the daemon or a child process
  724.   # were to write excessive amounts to stdout/stderr.  Ideally, stdout/stderr
  725.   # should be redirected to a pipe or socket, and a process at the other end
  726.   # should consume the data and write it to a logging facility which can do
  727.   # data-capping or log-rotation. The 'logger' command-line utility could be
  728.   # used for this, but it might cause too much syslog spam.
  729.  
  730.   # Create new (temporary) file-descriptors before forking, so any errors get
  731.   # reported to the main process and set the correct exit-code.
  732.   # The mode is provided, since Python otherwise sets a default mode of 0777,
  733.   # which would result in the new file having permissions of 0777 & ~umask,
  734.   # possibly leaving the executable bits set.
  735.   if not os.environ.has_key(LOG_FILE_ENV_VAR):
  736.     log_file_prefix = "chrome_remote_desktop_%s_" % time.strftime(
  737.         '%Y%m%d_%H%M%S', time.localtime(time.time()))
  738.     log_file = tempfile.NamedTemporaryFile(prefix=log_file_prefix, delete=False)
  739.     os.environ[LOG_FILE_ENV_VAR] = log_file.name
  740.     log_fd = log_file.file.fileno()
  741.   else:
  742.     log_fd = os.open(os.environ[LOG_FILE_ENV_VAR],
  743.                      os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
  744.  
  745.   devnull_fd = os.open(os.devnull, os.O_RDONLY)
  746.  
  747.   parent_logger = ParentProcessLogger()
  748.  
  749.   pid = os.fork()
  750.  
  751.   if pid == 0:
  752.     # Child process
  753.     os.setsid()
  754.  
  755.     # The second fork ensures that the daemon isn't a session leader, so that
  756.     # it doesn't acquire a controlling terminal.
  757.     pid = os.fork()
  758.  
  759.     if pid == 0:
  760.       # Grandchild process
  761.       pass
  762.     else:
  763.       # Child process
  764.       os._exit(0)  # pylint: disable=W0212
  765.   else:
  766.     # Parent process
  767.     parent_logger.wait_for_logs()
  768.     os._exit(0)  # pylint: disable=W0212
  769.  
  770.   logging.info("Daemon process started in the background, logging to '%s'" %
  771.                os.environ[LOG_FILE_ENV_VAR])
  772.  
  773.   os.chdir(HOME_DIR)
  774.  
  775.   parent_logger.start_logging()
  776.  
  777.   # Copy the file-descriptors to create new stdin, stdout and stderr.  Note
  778.   # that dup2(oldfd, newfd) closes newfd first, so this will close the current
  779.   # stdin, stdout and stderr, detaching from the terminal.
  780.   os.dup2(devnull_fd, sys.stdin.fileno())
  781.   os.dup2(log_fd, sys.stdout.fileno())
  782.   os.dup2(log_fd, sys.stderr.fileno())
  783.  
  784.   # Close the temporary file-descriptors.
  785.   os.close(devnull_fd)
  786.   os.close(log_fd)
  787.  
  788.  
  789. def cleanup():
  790.   logging.info("Cleanup.")
  791.  
  792.   global g_desktops
  793.   for desktop in g_desktops:
  794.     for proc, name in [(desktop.x_proc, "Xvfb"),
  795.                        (desktop.session_proc, "session"),
  796.                        (desktop.host_proc, "host")]:
  797.       if proc is not None:
  798.         logging.info("Terminating " + name)
  799.         try:
  800.           psutil_proc = psutil.Process(proc.pid)
  801.           psutil_proc.terminate()
  802.  
  803.           # Use a short timeout, to avoid delaying service shutdown if the
  804.           # process refuses to die for some reason.
  805.           psutil_proc.wait(timeout=10)
  806.         except psutil.TimeoutExpired:
  807.           logging.error("Timed out - sending SIGKILL")
  808.           psutil_proc.kill()
  809.         except psutil.Error:
  810.           logging.error("Error terminating process")
  811.  
  812.   g_desktops = []
  813.   if ParentProcessLogger.instance():
  814.     ParentProcessLogger.instance().release_parent()
  815.  
  816. class SignalHandler:
  817.   """Reload the config file on SIGHUP. Since we pass the configuration to the
  818.  host processes via stdin, they can't reload it, so terminate them. They will
  819.  be relaunched automatically with the new config."""
  820.  
  821.   def __init__(self, host_config):
  822.     self.host_config = host_config
  823.  
  824.   def __call__(self, signum, _stackframe):
  825.     if signum == signal.SIGHUP:
  826.       logging.info("SIGHUP caught, restarting host.")
  827.       try:
  828.         self.host_config.load()
  829.       except (IOError, ValueError) as e:
  830.         logging.error("Failed to load config: " + str(e))
  831.       for desktop in g_desktops:
  832.         if desktop.host_proc:
  833.           desktop.host_proc.send_signal(signal.SIGTERM)
  834.     else:
  835.       # Exit cleanly so the atexit handler, cleanup(), gets called.
  836.       raise SystemExit
  837.  
  838.  
  839. class RelaunchInhibitor:
  840.   """Helper class for inhibiting launch of a child process before a timeout has
  841.  elapsed.
  842.  
  843.  A managed process can be in one of these states:
  844.    running, not inhibited (running == True)
  845.    stopped and inhibited (running == False and is_inhibited() == True)
  846.    stopped but not inhibited (running == False and is_inhibited() == False)
  847.  
  848.  Attributes:
  849.    label: Name of the tracked process. Only used for logging.
  850.    running: Whether the process is currently running.
  851.    earliest_relaunch_time: Time before which the process should not be
  852.      relaunched, or 0 if there is no limit.
  853.    failures: The number of times that the process ran for less than a
  854.      specified timeout, and had to be inhibited.  This count is reset to 0
  855.      whenever the process has run for longer than the timeout.
  856.  """
  857.  
  858.   def __init__(self, label):
  859.     self.label = label
  860.     self.running = False
  861.     self.earliest_relaunch_time = 0
  862.     self.earliest_successful_termination = 0
  863.     self.failures = 0
  864.  
  865.   def is_inhibited(self):
  866.     return (not self.running) and (time.time() < self.earliest_relaunch_time)
  867.  
  868.   def record_started(self, minimum_lifetime, relaunch_delay):
  869.     """Record that the process was launched, and set the inhibit time to
  870.    |timeout| seconds in the future."""
  871.     self.earliest_relaunch_time = time.time() + relaunch_delay
  872.     self.earliest_successful_termination = time.time() + minimum_lifetime
  873.     self.running = True
  874.  
  875.   def record_stopped(self):
  876.     """Record that the process was stopped, and adjust the failure count
  877.    depending on whether the process ran long enough."""
  878.     self.running = False
  879.     if time.time() < self.earliest_successful_termination:
  880.       self.failures += 1
  881.     else:
  882.       self.failures = 0
  883.     logging.info("Failure count for '%s' is now %d", self.label, self.failures)
  884.  
  885.  
  886. def relaunch_self():
  887.   cleanup()
  888.   os.execvp(sys.argv[0], sys.argv)
  889.  
  890.  
  891. def waitpid_with_timeout(pid, deadline):
  892.   """Wrapper around os.waitpid() which waits until either a child process dies
  893.  or the deadline elapses.
  894.  
  895.  Args:
  896.    pid: Process ID to wait for, or -1 to wait for any child process.
  897.    deadline: Waiting stops when time.time() exceeds this value.
  898.  
  899.  Returns:
  900.    (pid, status): Same as for os.waitpid(), except that |pid| is 0 if no child
  901.    changed state within the timeout.
  902.  
  903.  Raises:
  904.    Same as for os.waitpid().
  905.  """
  906.   while time.time() < deadline:
  907.     pid, status = os.waitpid(pid, os.WNOHANG)
  908.     if pid != 0:
  909.       return (pid, status)
  910.     time.sleep(1)
  911.   return (0, 0)
  912.  
  913.  
  914. def waitpid_handle_exceptions(pid, deadline):
  915.   """Wrapper around os.waitpid()/waitpid_with_timeout(), which waits until
  916.  either a child process exits or the deadline elapses, and retries if certain
  917.  exceptions occur.
  918.  
  919.  Args:
  920.    pid: Process ID to wait for, or -1 to wait for any child process.
  921.    deadline: If non-zero, waiting stops when time.time() exceeds this value.
  922.      If zero, waiting stops when a child process exits.
  923.  
  924.  Returns:
  925.    (pid, status): Same as for waitpid_with_timeout(). |pid| is non-zero if and
  926.    only if a child exited during the wait.
  927.  
  928.  Raises:
  929.    Same as for os.waitpid(), except:
  930.      OSError with errno==EINTR causes the wait to be retried (this can happen,
  931.      for example, if this parent process receives SIGHUP).
  932.      OSError with errno==ECHILD means there are no child processes, and so
  933.      this function sleeps until |deadline|. If |deadline| is zero, this is an
  934.      error and the OSError exception is raised in this case.
  935.  """
  936.   while True:
  937.     try:
  938.       if deadline == 0:
  939.         pid_result, status = os.waitpid(pid, 0)
  940.       else:
  941.         pid_result, status = waitpid_with_timeout(pid, deadline)
  942.       return (pid_result, status)
  943.     except OSError, e:
  944.       if e.errno == errno.EINTR:
  945.         continue
  946.       elif e.errno == errno.ECHILD:
  947.         now = time.time()
  948.         if deadline == 0:
  949.           # No time-limit and no child processes. This is treated as an error
  950.           # (see docstring).
  951.           raise
  952.         elif deadline > now:
  953.           time.sleep(deadline - now)
  954.         return (0, 0)
  955.       else:
  956.         # Anything else is an unexpected error.
  957.         raise
  958.  
  959.  
  960. def watch_for_resolution_changes(initial_size):
  961.   """Watches for any resolution-changes which set the maximum screen resolution,
  962.  and resets the initial size if this happens.
  963.  
  964.  The Ubuntu desktop has a component (the 'xrandr' plugin of
  965.  unity-settings-daemon) which often changes the screen resolution to the
  966.  first listed mode. This is the built-in mode for the maximum screen size,
  967.  which can trigger excessive CPU usage in some situations. So this is a hack
  968.  which waits for any such events, and undoes the change if it occurs.
  969.  
  970.  Sometimes, the user might legitimately want to use the maximum available
  971.  resolution, so this monitoring is limited to a short time-period.
  972.  """
  973.   for _ in range(30):
  974.     time.sleep(1)
  975.  
  976.     xrandr_output = subprocess.Popen(["xrandr"],
  977.                                      stdout=subprocess.PIPE).communicate()[0]
  978.     matches = re.search(r'current (\d+) x (\d+), maximum (\d+) x (\d+)',
  979.                         xrandr_output)
  980.  
  981.     # No need to handle ValueError. If xrandr fails to give valid output,
  982.     # there's no point in continuing to monitor.
  983.     current_size = (int(matches.group(1)), int(matches.group(2)))
  984.     maximum_size = (int(matches.group(3)), int(matches.group(4)))
  985.  
  986.     if current_size != initial_size:
  987.       # Resolution change detected.
  988.       if current_size == maximum_size:
  989.         # This was probably an automated change from unity-settings-daemon, so
  990.         # undo it.
  991.         label = "%dx%d" % initial_size
  992.         args = ["xrandr", "-s", label]
  993.         subprocess.call(args)
  994.         args = ["xrandr", "--dpi", "96"]
  995.         subprocess.call(args)
  996.  
  997.       # Stop monitoring after any change was detected.
  998.       break
  999.  
  1000.  
  1001. def main():
  1002.   EPILOG = """This script is not intended for use by end-users.  To configure
  1003. Chrome Remote Desktop, please install the app from the Chrome
  1004. Web Store: https://chrome.google.com/remotedesktop"""
  1005.   parser = optparse.OptionParser(
  1006.       usage="Usage: %prog [options] [ -- [ X server options ] ]",
  1007.       epilog=EPILOG)
  1008.   parser.add_option("-s", "--size", dest="size", action="append",
  1009.                     help="Dimensions of virtual desktop. This can be specified "
  1010.                     "multiple times to make multiple screen resolutions "
  1011.                     "available (if the Xvfb server supports this).")
  1012.   parser.add_option("-f", "--foreground", dest="foreground", default=False,
  1013.                     action="store_true",
  1014.                     help="Don't run as a background daemon.")
  1015.   parser.add_option("", "--start", dest="start", default=False,
  1016.                     action="store_true",
  1017.                     help="Start the host.")
  1018.   parser.add_option("-k", "--stop", dest="stop", default=False,
  1019.                     action="store_true",
  1020.                     help="Stop the daemon currently running.")
  1021.   parser.add_option("", "--get-status", dest="get_status", default=False,
  1022.                     action="store_true",
  1023.                     help="Prints host status")
  1024.   parser.add_option("", "--check-running", dest="check_running", default=False,
  1025.                     action="store_true",
  1026.                     help="Return 0 if the daemon is running, or 1 otherwise.")
  1027.   parser.add_option("", "--config", dest="config", action="store",
  1028.                     help="Use the specified configuration file.")
  1029.   parser.add_option("", "--reload", dest="reload", default=False,
  1030.                     action="store_true",
  1031.                     help="Signal currently running host to reload the config.")
  1032.   parser.add_option("", "--add-user", dest="add_user", default=False,
  1033.                     action="store_true",
  1034.                     help="Add current user to the chrome-remote-desktop group.")
  1035.   parser.add_option("", "--host-version", dest="host_version", default=False,
  1036.                     action="store_true",
  1037.                     help="Prints version of the host.")
  1038.   parser.add_option("", "--watch-resolution", dest="watch_resolution",
  1039.                     type="int", nargs=2, default=False, action="store",
  1040.                     help=optparse.SUPPRESS_HELP)
  1041.   (options, args) = parser.parse_args()
  1042.  
  1043.   # Determine the filename of the host configuration and PID files.
  1044.   if not options.config:
  1045.     options.config = os.path.join(CONFIG_DIR, "host#%s.json" % g_host_hash)
  1046.  
  1047.   # Check for a modal command-line option (start, stop, etc.)
  1048.   if options.get_status:
  1049.     proc = get_daemon_proc()
  1050.     if proc is not None:
  1051.       print "STARTED"
  1052.     elif is_supported_platform():
  1053.       print "STOPPED"
  1054.     else:
  1055.       print "NOT_IMPLEMENTED"
  1056.     return 0
  1057.  
  1058.   # TODO(sergeyu): Remove --check-running once NPAPI plugin and NM host are
  1059.   # updated to always use get-status flag instead.
  1060.   if options.check_running:
  1061.     proc = get_daemon_proc()
  1062.     return 1 if proc is None else 0
  1063.  
  1064.   if options.stop:
  1065.     proc = get_daemon_proc()
  1066.     if proc is None:
  1067.       print "The daemon is not currently running"
  1068.     else:
  1069.       print "Killing process %s" % proc.pid
  1070.       proc.terminate()
  1071.       try:
  1072.         proc.wait(timeout=30)
  1073.       except psutil.TimeoutExpired:
  1074.         print "Timed out trying to kill daemon process"
  1075.         return 1
  1076.     return 0
  1077.  
  1078.   if options.reload:
  1079.     proc = get_daemon_proc()
  1080.     if proc is None:
  1081.       return 1
  1082.     proc.send_signal(signal.SIGHUP)
  1083.     return 0
  1084.  
  1085.   if options.add_user:
  1086.     user = getpass.getuser()
  1087.     try:
  1088.       if user in grp.getgrnam(CHROME_REMOTING_GROUP_NAME).gr_mem:
  1089.         logging.info("User '%s' is already a member of '%s'." %
  1090.                      (user, CHROME_REMOTING_GROUP_NAME))
  1091.         return 0
  1092.     except KeyError:
  1093.       logging.info("Group '%s' not found." % CHROME_REMOTING_GROUP_NAME)
  1094.  
  1095.     if os.getenv("DISPLAY"):
  1096.       sudo_command = "gksudo --description \"Chrome Remote Desktop\""
  1097.     else:
  1098.       sudo_command = "sudo"
  1099.     command = ("sudo -k && exec %(sudo)s -- sh -c "
  1100.                "\"groupadd -f %(group)s && gpasswd --add %(user)s %(group)s\"" %
  1101.                { 'group': CHROME_REMOTING_GROUP_NAME,
  1102.                  'user': user,
  1103.                  'sudo': sudo_command })
  1104.     os.execv("/bin/sh", ["/bin/sh", "-c", command])
  1105.     return 1
  1106.  
  1107.   if options.host_version:
  1108.     # TODO(sergeyu): Also check RPM package version once we add RPM package.
  1109.     return os.system(locate_executable(HOST_BINARY_NAME) + " --version") >> 8
  1110.  
  1111.   if options.watch_resolution:
  1112.     watch_for_resolution_changes(options.watch_resolution)
  1113.     return 0
  1114.  
  1115.   if not options.start:
  1116.     # If no modal command-line options specified, print an error and exit.
  1117.     print >> sys.stderr, EPILOG
  1118.     return 1
  1119.  
  1120.   # If a RANDR-supporting Xvfb is not available, limit the default size to
  1121.   # something more sensible.
  1122.   if get_randr_supporting_x_server():
  1123.     default_sizes = DEFAULT_SIZES
  1124.   else:
  1125.     default_sizes = DEFAULT_SIZE_NO_RANDR
  1126.  
  1127.   # Collate the list of sizes that XRANDR should support.
  1128.   if not options.size:
  1129.     if os.environ.has_key(DEFAULT_SIZES_ENV_VAR):
  1130.       default_sizes = os.environ[DEFAULT_SIZES_ENV_VAR]
  1131.     options.size = default_sizes.split(",")
  1132.  
  1133.   sizes = []
  1134.   for size in options.size:
  1135.     size_components = size.split("x")
  1136.     if len(size_components) != 2:
  1137.       parser.error("Incorrect size format '%s', should be WIDTHxHEIGHT" % size)
  1138.  
  1139.     try:
  1140.       width = int(size_components[0])
  1141.       height = int(size_components[1])
  1142.  
  1143.       # Enforce minimum desktop size, as a sanity-check.  The limit of 100 will
  1144.       # detect typos of 2 instead of 3 digits.
  1145.       if width < 100 or height < 100:
  1146.         raise ValueError
  1147.     except ValueError:
  1148.       parser.error("Width and height should be 100 pixels or greater")
  1149.  
  1150.     sizes.append((width, height))
  1151.  
  1152.   # Register an exit handler to clean up session process and the PID file.
  1153.   atexit.register(cleanup)
  1154.  
  1155.   # Load the initial host configuration.
  1156.   host_config = Config(options.config)
  1157.   try:
  1158.     host_config.load()
  1159.   except (IOError, ValueError) as e:
  1160.     print >> sys.stderr, "Failed to load config: " + str(e)
  1161.     return 1
  1162.  
  1163.   # Register handler to re-load the configuration in response to signals.
  1164.   for s in [signal.SIGHUP, signal.SIGINT, signal.SIGTERM]:
  1165.     signal.signal(s, SignalHandler(host_config))
  1166.  
  1167.   # Verify that the initial host configuration has the necessary fields.
  1168.   auth = Authentication()
  1169.   auth_config_valid = auth.copy_from(host_config)
  1170.   host = Host()
  1171.   host_config_valid = host.copy_from(host_config)
  1172.   if not host_config_valid or not auth_config_valid:
  1173.     logging.error("Failed to load host configuration.")
  1174.     return 1
  1175.  
  1176.   # Determine whether a desktop is already active for the specified host
  1177.   # host configuration.
  1178.   proc = get_daemon_proc()
  1179.   if proc is not None:
  1180.     # Debian policy requires that services should "start" cleanly and return 0
  1181.     # if they are already running.
  1182.     print "Service already running."
  1183.     return 0
  1184.  
  1185.   # Detach a separate "daemon" process to run the session, unless specifically
  1186.   # requested to run in the foreground.
  1187.   if not options.foreground:
  1188.     daemonize()
  1189.  
  1190.   logging.info("Using host_id: " + host.host_id)
  1191.  
  1192.   desktop = Desktop(sizes)
  1193.  
  1194.   # Keep track of the number of consecutive failures of any child process to
  1195.   # run for longer than a set period of time. The script will exit after a
  1196.   # threshold is exceeded.
  1197.   # There is no point in tracking the X session process separately, since it is
  1198.   # launched at (roughly) the same time as the X server, and the termination of
  1199.   # one of these triggers the termination of the other.
  1200.   x_server_inhibitor = RelaunchInhibitor("X server")
  1201.   host_inhibitor = RelaunchInhibitor("host")
  1202.   all_inhibitors = [x_server_inhibitor, host_inhibitor]
  1203.  
  1204.   # Don't allow relaunching the script on the first loop iteration.
  1205.   allow_relaunch_self = False
  1206.  
  1207.   while True:
  1208.     # Set the backoff interval and exit if a process failed too many times.
  1209.     backoff_time = SHORT_BACKOFF_TIME
  1210.     for inhibitor in all_inhibitors:
  1211.       if inhibitor.failures >= MAX_LAUNCH_FAILURES:
  1212.         logging.error("Too many launch failures of '%s', exiting."
  1213.                       % inhibitor.label)
  1214.         return 1
  1215.       elif inhibitor.failures >= SHORT_BACKOFF_THRESHOLD:
  1216.         backoff_time = LONG_BACKOFF_TIME
  1217.  
  1218.     relaunch_times = []
  1219.  
  1220.     # If the session process or X server stops running (e.g. because the user
  1221.     # logged out), kill the other. This will trigger the next conditional block
  1222.     # as soon as os.waitpid() reaps its exit-code.
  1223.     if desktop.session_proc is None and desktop.x_proc is not None:
  1224.       logging.info("Terminating X server")
  1225.       desktop.x_proc.terminate()
  1226.     elif desktop.x_proc is None and desktop.session_proc is not None:
  1227.       logging.info("Terminating X session")
  1228.       desktop.session_proc.terminate()
  1229.     elif desktop.x_proc is None and desktop.session_proc is None:
  1230.       # Both processes have terminated.
  1231.       if (allow_relaunch_self and x_server_inhibitor.failures == 0 and
  1232.           host_inhibitor.failures == 0):
  1233.         # Since the user's desktop is already gone at this point, there's no
  1234.         # state to lose and now is a good time to pick up any updates to this
  1235.         # script that might have been installed.
  1236.         logging.info("Relaunching self")
  1237.         relaunch_self()
  1238.       else:
  1239.         # If there is a non-zero |failures| count, restarting the whole script
  1240.         # would lose this information, so just launch the session as normal.
  1241.         if x_server_inhibitor.is_inhibited():
  1242.           logging.info("Waiting before launching X server")
  1243.           relaunch_times.append(x_server_inhibitor.earliest_relaunch_time)
  1244.         else:
  1245.           logging.info("Launching X server and X session.")
  1246.           desktop.launch_session(args)
  1247.           x_server_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME,
  1248.                                             backoff_time)
  1249.           allow_relaunch_self = True
  1250.  
  1251.     if desktop.host_proc is None:
  1252.       if host_inhibitor.is_inhibited():
  1253.         logging.info("Waiting before launching host process")
  1254.         relaunch_times.append(host_inhibitor.earliest_relaunch_time)
  1255.       else:
  1256.         logging.info("Launching host process")
  1257.         desktop.launch_host(host_config)
  1258.         host_inhibitor.record_started(MINIMUM_PROCESS_LIFETIME,
  1259.                                       backoff_time)
  1260.  
  1261.     deadline = min(relaunch_times) if relaunch_times else 0
  1262.     pid, status = waitpid_handle_exceptions(-1, deadline)
  1263.     if pid == 0:
  1264.       continue
  1265.  
  1266.     logging.info("wait() returned (%s,%s)" % (pid, status))
  1267.  
  1268.     # When a process has terminated, and we've reaped its exit-code, any Popen
  1269.     # instance for that process is no longer valid. Reset any affected instance
  1270.     # to None.
  1271.     if desktop.x_proc is not None and pid == desktop.x_proc.pid:
  1272.       logging.info("X server process terminated")
  1273.       desktop.x_proc = None
  1274.       x_server_inhibitor.record_stopped()
  1275.  
  1276.     if desktop.session_proc is not None and pid == desktop.session_proc.pid:
  1277.       logging.info("Session process terminated")
  1278.       desktop.session_proc = None
  1279.  
  1280.     if desktop.host_proc is not None and pid == desktop.host_proc.pid:
  1281.       logging.info("Host process terminated")
  1282.       desktop.host_proc = None
  1283.       desktop.host_ready = False
  1284.       host_inhibitor.record_stopped()
  1285.  
  1286.       # These exit-codes must match the ones used by the host.
  1287.       # See remoting/host/host_error_codes.h.
  1288.       # Delete the host or auth configuration depending on the returned error
  1289.       # code, so the next time this script is run, a new configuration
  1290.       # will be created and registered.
  1291.       if os.WIFEXITED(status):
  1292.         if os.WEXITSTATUS(status) == 100:
  1293.           logging.info("Host configuration is invalid - exiting.")
  1294.           return 0
  1295.         elif os.WEXITSTATUS(status) == 101:
  1296.           logging.info("Host ID has been deleted - exiting.")
  1297.           host_config.clear()
  1298.           host_config.save_and_log_errors()
  1299.           return 0
  1300.         elif os.WEXITSTATUS(status) == 102:
  1301.           logging.info("OAuth credentials are invalid - exiting.")
  1302.           return 0
  1303.         elif os.WEXITSTATUS(status) == 103:
  1304.           logging.info("Host domain is blocked by policy - exiting.")
  1305.           return 0
  1306.         # Nothing to do for Mac-only status 104 (login screen unsupported)
  1307.         elif os.WEXITSTATUS(status) == 105:
  1308.           logging.info("Username is blocked by policy - exiting.")
  1309.           return 0
  1310.         else:
  1311.           logging.info("Host exited with status %s." % os.WEXITSTATUS(status))
  1312.       elif os.WIFSIGNALED(status):
  1313.         logging.info("Host terminated by signal %s." % os.WTERMSIG(status))
  1314.  
  1315.  
  1316. if __name__ == "__main__":
  1317.   logging.basicConfig(level=logging.DEBUG,
  1318.                       format="%(asctime)s:%(levelname)s:%(message)s")
  1319.   sys.exit(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement