Skip to content
Snippets Groups Projects
launch-client.c 53.9 KiB
Newer Older
 * steam-runtime-launch-client — send IPC requests to create child processes
 *
 * Copyright © 2018 Red Hat, Inc.
 * Copyright © 2020-2021 Collabora Ltd.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Based on flatpak-spawn from the flatpak-xdg-utils package.
 * Copyright © 2018 Red Hat, Inc.
 * Authors:
 *       Alexander Larsson <alexl@redhat.com>
 */

#include "config.h"

#include <stdlib.h>
#include <sysexits.h>
#include <sys/signalfd.h>

#include <glib.h>
#include <glib/gstdio.h>
#include <glib-unix.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>

#include "steam-runtime-tools/glib-backports-internal.h"
#include "steam-runtime-tools/launcher-internal.h"
#include "steam-runtime-tools/log-internal.h"
#include "steam-runtime-tools/pty-bridge-internal.h"
#include "steam-runtime-tools/utils-internal.h"
#include "flatpak-portal.h"
#include "flatpak-session-helper.h"
typedef enum {
  FLATPAK_HOST_COMMAND_FLAGS_CLEAR_ENV = 1 << 0,
  FLATPAK_HOST_COMMAND_FLAGS_WATCH_BUS = 1 << 1, /* Since 1.2 */
} FlatpakHostCommandFlags;

typedef struct
{
  const char *service_iface;
  const char *service_obj_path;
  const char *service_bus_name;
  const char *send_signal_method;
  const char *exit_signal;
  const char *launch_method;
  guint clear_env_flag;
  gboolean default_dir_is_cwd;
} Api;

static Api launcher_api =
{
  .service_iface = LAUNCHER_IFACE,
  .service_obj_path = LAUNCHER_PATH,
  .service_bus_name = NULL,
  .send_signal_method = "SendSignal",
  .exit_signal = "ProcessExited",
  .launch_method = "Launch",
  .clear_env_flag = PV_LAUNCH_FLAGS_CLEAR_ENV,
  .default_dir_is_cwd = FALSE,
  .service_iface = FLATPAK_SESSION_HELPER_INTERFACE_DEVELOPMENT,
  .service_obj_path = FLATPAK_SESSION_HELPER_PATH_DEVELOPMENT,
  .service_bus_name = FLATPAK_SESSION_HELPER_BUS_NAME,
  .send_signal_method = "HostCommandSignal",
  .exit_signal = "HostCommandExited",
  .launch_method = "HostCommand",
  .clear_env_flag = FLATPAK_HOST_COMMAND_FLAGS_CLEAR_ENV,
};

static const Api subsandbox_api =
{
  .service_iface = FLATPAK_PORTAL_INTERFACE,
  .service_obj_path = FLATPAK_PORTAL_PATH,
  .service_bus_name = FLATPAK_PORTAL_BUS_NAME,
  .send_signal_method = "SpawnSignal",
  .exit_signal = "SpawnExited",
  .launch_method = "Spawn",
  .clear_env_flag = FLATPAK_SPAWN_FLAGS_CLEAR_ENV,
static const char *service_bus_name = NULL;

typedef GUnixFDList AutoUnixFDList;
G_DEFINE_AUTOPTR_CLEANUP_FUNC(AutoUnixFDList, g_object_unref)

static const char * const *global_original_environ = NULL;
static GDBusConnection *bus_or_peer_connection = NULL;
static guint child_pid = 0;
static int launch_exit_status = LAUNCH_EX_USAGE;
static SrtPtyBridge *first_pty_bridge = NULL;

static void
process_exited_cb (G_GNUC_UNUSED GDBusConnection *connection,
                   G_GNUC_UNUSED const gchar     *sender_name,
                   G_GNUC_UNUSED const gchar     *object_path,
                   G_GNUC_UNUSED const gchar     *interface_name,
                   G_GNUC_UNUSED const gchar     *signal_name,
                   GVariant                      *parameters,
                   gpointer                       user_data)
{
  GMainLoop *loop = user_data;
  guint32 client_pid = 0;
  guint32 wait_status = 0;

  if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(uu)")))
    return;

  g_variant_get (parameters, "(uu)", &client_pid, &wait_status);
  g_debug ("child %d exited: wait status %d", client_pid, wait_status);

  if (child_pid == client_pid)
    {
      int exit_code = 0;

      if (WIFEXITED (wait_status))
          exit_code = WEXITSTATUS (wait_status);
      else if (WIFSIGNALED (wait_status))
        {
          /* Smush the signal into an unsigned byte, as the shell does. This is
           * not quite right from the perspective of whatever ran flatpak-spawn
           * — it will get WIFEXITED() not WIFSIGNALED() — but the
           *  alternative is to disconnect all signal() handlers then send this
           *  signal to ourselves and hope it kills us.
           */
          exit_code = 128 + WTERMSIG (wait_status);
        }
      else
        {
          /* wait(3p) claims that if the waitpid() call that returned the exit
           * code specified neither WUNTRACED nor WIFSIGNALED, then exactly one
           * of WIFEXITED() or WIFSIGNALED() will be true.
           */
          g_warning ("wait status %d is neither WIFEXITED() nor WIFSIGNALED()",
                     wait_status);
          exit_code = LAUNCH_EX_CANNOT_REPORT;
        }

      g_debug ("child exit code %d: %d", client_pid, exit_code);
      launch_exit_status = exit_code;
      g_main_loop_quit (loop);
    }
}

static void
forward_signal (int sig)
{
  G_GNUC_UNUSED g_autoptr(GVariant) reply = NULL;
  gboolean to_process_group = FALSE;
  g_autoptr(GError) error = NULL;
  if (first_pty_bridge != NULL)
    {
      if (!_srt_pty_bridge_handle_signal (first_pty_bridge, sig, &handled, &error))
        {
          g_debug ("%s", error->message);
          g_clear_error (&error);
        }
      else if (handled)
        {
          if (G_IN_SET (sig, SIGSTOP, SIGTSTP))
            {
              g_info ("SIGSTOP:ing myself");
              raise (SIGSTOP);
            }

          return;
        }
    }

  if (child_pid == 0)
    {
      /* We are not monitoring a child yet, so let the signal act on
       * this main process instead */
      if (sig == SIGTSTP || sig == SIGSTOP || sig == SIGTTIN || sig == SIGTTOU)
        {
          raise (SIGSTOP);
        }
      else if (sig != SIGCONT && sig != SIGWINCH)
        {
          sigset_t mask;

          sigemptyset (&mask);
          sigaddset (&mask, sig);
          /* Unblock it, so that it will be delivered properly this time.
           * Use pthread_sigmask instead of sigprocmask because the latter
           * has unspecified behaviour in a multi-threaded process. */
          pthread_sigmask (SIG_UNBLOCK, &mask, NULL);
          raise (sig);
        }

      return;
    }

  g_debug ("Forwarding signal: %d", sig);

  /* We forward stop requests as real stop, because the default doesn't
     seem to be to stop for non-kernel sent TSTP??? */
  if (sig == SIGTSTP)
    sig = SIGSTOP;

  /* ctrl-c/z is typically for the entire process group */
  if (sig == SIGINT || sig == SIGSTOP || sig == SIGCONT)
    to_process_group = TRUE;

  reply = g_dbus_connection_call_sync (bus_or_peer_connection,
                                       service_bus_name,        /* NULL if p2p */
                                       api->service_obj_path,
                                       api->service_iface,
                                       api->send_signal_method,
                                       g_variant_new ("(uub)",
                                                      child_pid, sig,
                                                      to_process_group),
                                       G_VARIANT_TYPE ("()"),
                                       G_DBUS_CALL_FLAGS_NONE,
                                       -1, NULL, &error);

  if (error)
    g_info ("Failed to forward signal: %s", error->message);
      g_info ("SIGSTOP:ing myself");
      raise (SIGSTOP);
    }
}

static gboolean
forward_signal_handler (int sfd,
                        G_GNUC_UNUSED GIOCondition condition,
                        G_GNUC_UNUSED gpointer data)
{
  struct signalfd_siginfo info;
  ssize_t size;

  size = read (sfd, &info, sizeof (info));

  if (size < 0)
    {
      if (errno != EINTR && errno != EAGAIN)
        g_warning ("Unable to read struct signalfd_siginfo: %s",
                   g_strerror (errno));
    }
  else if (size != sizeof (info))
    {
      g_warning ("Expected struct signalfd_siginfo of size %"
                 G_GSIZE_FORMAT ", got %" G_GSSIZE_FORMAT,
                 sizeof (info), size);
    }
  else
    {
      forward_signal (info.ssi_signo);
    }

  return G_SOURCE_CONTINUE;
}

static guint
forward_signals (GError **error)
    SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGCONT, SIGTSTP, SIGUSR1, SIGUSR2,
    SIGTTIN, SIGTTOU, SIGWINCH,
  };
  sigset_t mask;
  guint i;
  int sfd;

  sigemptyset (&mask);

  for (i = 0; i < G_N_ELEMENTS (forward); i++)
    sigaddset (&mask, forward[i]);

  sfd = signalfd (-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);

  if (sfd < 0)
    {
      glnx_throw_errno_prefix (error, "Unable to watch signals");
      return 0;
    }

  /*
   * We have to block the signals, for two reasons:
   * - If we didn't, most of them would kill our process.
   *   Listening for a signal with a signalfd does not prevent the signal's
   *   default disposition from being acted on.
   * - Reading from a signalfd only returns information about the signals
   *   that are still pending for the process. If we ignored them instead
   *   of blocking them, they would no longer be pending by the time the
   *   main loop wakes up and reads from the signalfd.
   */
  if (pthread_sigmask (SIG_BLOCK, &mask, NULL) != 0)
    {
      glnx_throw_errno_prefix (error, "Unable to block signals");
      return 0;
    }

  return g_unix_fd_add (sfd, G_IO_IN, forward_signal_handler, NULL);
}

static void
name_owner_changed (G_GNUC_UNUSED GDBusConnection *connection,
                    G_GNUC_UNUSED const gchar     *sender_name,
                    G_GNUC_UNUSED const gchar     *object_path,
                    G_GNUC_UNUSED const gchar     *interface_name,
                    G_GNUC_UNUSED const gchar     *signal_name,
                    GVariant                      *parameters,
                    G_GNUC_UNUSED gpointer         user_data)
{
  GMainLoop *loop = user_data;
  const char *name, *from, *to;

  g_return_if_fail (api != NULL);
  g_return_if_fail (service_bus_name != NULL);
  g_variant_get (parameters, "(&s&s&s)", &name, &from, &to);

  /* Check if the service dies, then we exit, because we can't track it anymore */
  if (strcmp (name, service_bus_name) == 0 &&
      strcmp (to, "") == 0)
    {
      g_debug ("portal exited");

      if (child_pid == 0)
        launch_exit_status = LAUNCH_EX_FAILED;
      else
        launch_exit_status = LAUNCH_EX_CANNOT_REPORT;

      g_main_loop_quit (loop);
    }
}

static void
connection_closed_cb (G_GNUC_UNUSED GDBusConnection *conn,
                      G_GNUC_UNUSED gboolean remote_peer_vanished,
                      G_GNUC_UNUSED GError *error,
                      GMainLoop *loop)
{
  g_debug ("D-Bus connection closed, quitting");

  if (child_pid == 0)
    launch_exit_status = LAUNCH_EX_FAILED;
  else
    launch_exit_status = LAUNCH_EX_CANNOT_REPORT;

  g_main_loop_quit (loop);
}

static guint32
get_portal_version (void)
{
  static guint32 version = 0;

  g_return_val_if_fail (api != NULL, 0);
  g_return_val_if_fail (api == &host_api || api == &subsandbox_api, 0);

  if (version == 0)
    {
      g_autoptr(GError) error = NULL;
      g_autoptr(GVariant) reply =
        g_dbus_connection_call_sync (bus_or_peer_connection,
                                     api->service_obj_path,
                                     "org.freedesktop.DBus.Properties",
                                     "Get",
                                     g_variant_new ("(ss)", api->service_iface, "version"),
                                     G_VARIANT_TYPE ("(v)"),
                                     G_DBUS_CALL_FLAGS_NONE,
                                     -1,
                                     NULL, &error);

      if (reply == NULL)
        g_debug ("Failed to get version: %s", error->message);
      else
        {
          g_autoptr(GVariant) v = g_variant_get_child_value (reply, 0);
          g_autoptr(GVariant) v2 = g_variant_get_variant (v);
          version = g_variant_get_uint32 (v2);
        }
    }

  return version;
}

static void
check_portal_version (const char *option, guint32 version_needed)
{
  guint32 portal_version = get_portal_version ();
  if (portal_version < version_needed)
    {
      g_printerr ("--%s not supported by host portal version (need version %d, has %d)\n", option, version_needed, portal_version);
      exit (1);
    }
}

static guint32
get_portal_supports (void)
{
  static guint32 supports = 0;
  static gboolean ran = FALSE;

  g_return_val_if_fail (api != NULL, 0);
  g_return_val_if_fail (api == &host_api || api == &subsandbox_api, 0);

  if (!ran)
    {
      g_autoptr(GError) error = NULL;
      g_autoptr(GVariant) reply = NULL;

      ran = TRUE;

      /* Support flags were added in version 3 */
      if (get_portal_version () >= 3)
        {
          reply = g_dbus_connection_call_sync (bus_or_peer_connection,
                                               api->service_obj_path,
                                               "org.freedesktop.DBus.Properties",
                                               "Get",
                                               g_variant_new ("(ss)", api->service_iface, "supports"),
                                               G_VARIANT_TYPE ("(v)"),
                                               G_DBUS_CALL_FLAGS_NONE,
                                               -1,
                                               NULL, &error);
          if (reply == NULL)
            g_debug ("Failed to get supports: %s", error->message);
          else
            {
              g_autoptr(GVariant) v = g_variant_get_child_value (reply, 0);
              g_autoptr(GVariant) v2 = g_variant_get_variant (v);
              supports = g_variant_get_uint32 (v2);
            }
        }
    }

  return supports;
}

#define NOT_SETUID_ROOT_MESSAGE \
"This feature requires Flatpak to be using a bubblewrap (bwrap) executable\n" \
"that is not setuid root.\n" \
"\n" \
"The non-setuid version of bubblewrap requires a kernel that allows\n" \
"unprivileged users to create new user namespaces.\n" \
"\n" \
"For more details please see:\n" \
"https://github.com/flatpak/flatpak/wiki/User-namespace-requirements\n" \
"\n"

static void
check_portal_supports (const char *option, guint32 supports_needed)
{
  guint32 supports = get_portal_supports ();

  if ((supports & supports_needed) != supports_needed)
    {
      g_printerr ("--%s not supported by host portal\n", option);

      if (supports_needed == FLATPAK_SPAWN_SUPPORT_FLAGS_EXPOSE_PIDS)
        g_printerr ("\n%s", NOT_SETUID_ROOT_MESSAGE);

static gint32
path_to_handle (GUnixFDList *fd_list,
                const char *path,
                const char *home_realpath,
                const char *flatpak_id,
                GError **error)
{
  int path_fd = open (path, O_PATH|O_CLOEXEC|O_NOFOLLOW|O_RDONLY);
  int saved_errno;
  gint32 handle;

  if (path_fd < 0)
    {
      saved_errno = errno;
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
                   "Failed to open %s to expose in sandbox: %s",
                   path, g_strerror (saved_errno));
      return -1;
    }

  if (home_realpath != NULL && flatpak_id != NULL)
    {
      g_autofree char *real = NULL;
      const char *after = NULL;

      real = realpath (path, NULL);

      if (real != NULL)
        after = _srt_get_path_after (real, home_realpath);

      if (after != NULL)
        {
          g_autofree char *var_path = NULL;
          int var_fd = -1;
          struct stat path_buf;
          struct stat var_buf;

          /* @after is possibly "", but that's OK: if @path is exactly $HOME,
           * we want to check whether it's the same file as
           * ~/.var/app/$FLATPAK_ID, with no suffix */
          var_path = g_build_filename (home_realpath, ".var", "app", flatpak_id,
                                       after, NULL);

          var_fd = open (var_path, O_PATH|O_CLOEXEC|O_NOFOLLOW|O_RDONLY);

          if (var_fd >= 0 &&
              fstat (path_fd, &path_buf) == 0 &&
              fstat (var_fd, &var_buf) == 0 &&
              path_buf.st_dev == var_buf.st_dev &&
              path_buf.st_ino == var_buf.st_ino)
            {
              close (path_fd);
              path_fd = var_fd;
            }
          else
            {
              close (var_fd);
            }
        }
    }


  handle = g_unix_fd_list_append (fd_list, path_fd, error);

  if (handle < 0)
    {
      g_prefix_error (error, "Failed to add fd to list for %s: ", path);
      return -1;
    }

  /* The GUnixFdList keeps a duplicate, so we should release the original */
  close (path_fd);
  return handle;
}

static int
list_servers (FILE *original_stdout,
              GError **error)
{
  static const char * const flatpak_names[] =
  {
    FLATPAK_PORTAL_BUS_NAME,
    FLATPAK_SESSION_HELPER_BUS_NAME,
  };
  g_autoptr(GDBusConnection) session_bus = NULL;
  g_autoptr(GVariant) reply = NULL;
  g_auto(GStrv) running = NULL;
  g_auto(GStrv) activatable = NULL;
  gsize i;

  session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, error);

  if (session_bus == NULL)
    {
      glnx_prefix_error (error, "Can't find session bus");
      return LAUNCH_EX_FAILED;
    }

  reply = g_dbus_connection_call_sync (session_bus,
                                       DBUS_NAME_DBUS,
                                       DBUS_PATH_DBUS,
                                       DBUS_INTERFACE_DBUS,
                                       "ListNames",
                                       NULL,
                                       G_VARIANT_TYPE ("(as)"),
                                       G_DBUS_CALL_FLAGS_NONE,
                                       -1, NULL, error);

  if (reply == NULL)
    return LAUNCH_EX_FAILED;

  g_variant_get (reply, "(^as)", &running);

  g_clear_pointer (&reply, g_variant_unref);
  reply = g_dbus_connection_call_sync (session_bus,
                                       DBUS_NAME_DBUS,
                                       DBUS_PATH_DBUS,
                                       DBUS_INTERFACE_DBUS,
                                       "ListActivatableNames",
                                       NULL,
                                       G_VARIANT_TYPE ("(as)"),
                                       G_DBUS_CALL_FLAGS_NONE,
                                       -1, NULL, error);

  if (reply == NULL)
    return LAUNCH_EX_FAILED;

  g_variant_get (reply, "(^as)", &activatable);

  qsort (running, g_strv_length (running), sizeof (char *),
         _srt_indirect_strcmp0);

  for (i = 0; running[i] != NULL; i++)
    {
      if (g_str_has_prefix (running[i], "com.steampowered.App"))
        fprintf (original_stdout, "--bus-name=%s\n", running[i]);
    }

  for (i = 0; i < G_N_ELEMENTS (flatpak_names); i++)
    {
      if (g_strv_contains ((const char * const *) running, flatpak_names[i])
          || g_strv_contains ((const char * const *) activatable, flatpak_names[i]))
        fprintf (original_stdout, "--bus-name=%s\n", flatpak_names[i]);
static gchar **forward_fds = NULL;
static gchar *opt_app_path = NULL;
static gboolean opt_clear_env = FALSE;
static gchar *opt_dbus_address = NULL;
static gchar *opt_directory = NULL;
static gboolean opt_list = FALSE;
static gchar *opt_shell_command = NULL;
static gchar *opt_socket = NULL;
static GHashTable *opt_env = NULL;
static GHashTable *opt_unsetenv = NULL;
static gboolean opt_share_pids = FALSE;
static gboolean opt_terminate = FALSE;
static gchar *opt_usr_path = NULL;
static gboolean opt_verbose = FALSE;
static gboolean opt_version = FALSE;

static void
remove_keys_matching_pattern (GHashTable *table,
                              const char *pattern)
{
  GHashTableIter iter;
  gpointer k;

  g_hash_table_iter_init (&iter, table);

  while (g_hash_table_iter_next (&iter, &k, NULL))
    {
      if (fnmatch (pattern, k, 0) == 0)
        g_hash_table_iter_remove (&iter);
    }
}

static gboolean
opt_env_cb (const char *option_name,
            const gchar *value,
            G_GNUC_UNUSED gpointer data,
            GError **error)
{
  g_assert (opt_env != NULL);
  g_assert (opt_unsetenv != NULL);

  if (g_strcmp0 (option_name, "--env") == 0)
    {
      g_auto(GStrv) split = g_strsplit (value, "=", 2);

      if (split == NULL ||
          split[0] == NULL ||
          split[0][0] == 0 ||
          split[1] == NULL)
        {
          g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
                       "Invalid env format %s", value);
          return FALSE;
        }

      g_hash_table_remove (opt_unsetenv, split[0]);
      g_hash_table_replace (opt_env,
                            g_steal_pointer (&split[0]),
                            g_steal_pointer (&split[1]));
      return TRUE;
    }

  if (g_strcmp0 (option_name, "--inherit-env") == 0)
    {
      g_hash_table_remove (opt_env, value);
      g_hash_table_remove (opt_unsetenv, value);
      return TRUE;
    }

  if (g_strcmp0 (option_name, "--pass-env") == 0)
    {
      const gchar *env = g_getenv (value);

      if (env != NULL)
        {
          g_hash_table_remove (opt_unsetenv, value);
          g_hash_table_replace (opt_env, g_strdup (value), g_strdup (env));
        }
      else
        {
          g_hash_table_remove (opt_env, value);
          g_hash_table_add (opt_unsetenv, g_strdup (value));
        }

      return TRUE;
    }

  if (g_strcmp0 (option_name, "--inherit-env-matching") == 0)
    {
      remove_keys_matching_pattern (opt_env, value);
      remove_keys_matching_pattern (opt_unsetenv, value);
      return TRUE;
    }

  if (g_strcmp0 (option_name, "--pass-env-matching") == 0)
    {
      const char * const *iter;
      if (global_original_environ == NULL)
      for (iter = global_original_environ; *iter != NULL; iter++)
        {
          g_auto(GStrv) split = g_strsplit (*iter, "=", 2);

          if (split == NULL ||
              split[0] == NULL ||
              split[0][0] == 0 ||
              split[1] == NULL)
            continue;

          if (fnmatch (value, split[0], 0) == 0)
            {
              g_hash_table_remove (opt_unsetenv, split[0]);
              g_hash_table_replace (opt_env,
                                    g_steal_pointer (&split[0]),
                                    g_steal_pointer (&split[1]));
            }
        }

      return TRUE;
    }

  if (g_strcmp0 (option_name, "--unset-env") == 0)
    {
      g_hash_table_remove (opt_env, value);
      g_hash_table_add (opt_unsetenv, g_strdup (value));
      return TRUE;
    }

  g_return_val_if_reached (FALSE);
}

static gboolean
option_env_fd_cb (G_GNUC_UNUSED const gchar *option_name,
                  const gchar *value,
                  G_GNUC_UNUSED gpointer data,
                  GError **error)
{
  g_autofree gchar *proc_filename = NULL;
  g_autofree gchar *env_block = NULL;
  gsize remaining;
  const char *p;
  guint64 fd;
  gchar *endptr;

  g_assert (opt_env != NULL);
  g_assert (opt_unsetenv != NULL);

  fd = g_ascii_strtoull (value, &endptr, 10);

  if (endptr == NULL || *endptr != '\0' || fd > G_MAXINT)
    {
      g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
                   "Not a valid file descriptor: %s", value);
      return FALSE;
    }

  proc_filename = g_strdup_printf ("/proc/self/fd/%d", (int) fd);

  if (!g_file_get_contents (proc_filename, &env_block, &remaining, error))
    return FALSE;

  p = env_block;

  while (remaining > 0)
    {
      g_autofree gchar *var = NULL;
      g_autofree gchar *val = NULL;
      size_t len = strnlen (p, remaining);
      const char *equals;

      g_assert (len <= remaining);

      equals = memchr (p, '=', len);

      if (equals == NULL || equals == p)
        {
          g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
                       "Environment variable must be given in the form VARIABLE=VALUE, not %.*s",
                       (int) len, p);
          return FALSE;
        }

      var = g_strndup (p, equals - p);
      val = g_strndup (equals + 1, len - (equals - p) - 1);
      g_hash_table_remove (opt_unsetenv, var);
      g_hash_table_replace (opt_env,
                            g_steal_pointer (&var),
                            g_steal_pointer (&val));

      p += len;
      remaining -= len;

      if (remaining > 0)
        {
          g_assert (*p == '\0');
          p += 1;
          remaining -= 1;
        }
    }

  if (fd >= 3)
    close (fd);

  return TRUE;
}

static const GOptionEntry options[] =
{
  { "app-path", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_FILENAME, &opt_app_path,
    "Use DIR as the /app for a Flatpak sub-sandbox. "
    "Requires '--bus-name=org.freedesktop.portal.Flatpak'.",
    "DIR" },
    G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING, &launcher_api.service_bus_name,
    "Connect to a Launcher service with this name on the session bus.",
    "NAME" },
  { "dbus-address", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING, &opt_dbus_address,
    "Connect to a Launcher server listening on this D-Bus address.",
    "ADDRESS" },
  { "clear-env", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &opt_clear_env,
    "Run with clean environment.", NULL },
  { "directory", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_FILENAME, &opt_directory,
    "Working directory in which to run the command.", "DIR" },
  { "env", '\0',
    G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, opt_env_cb,
    "Set environment variable.", "VAR=VALUE" },
  { "env-fd", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_CALLBACK, option_env_fd_cb,
    "Read environment variables in env -0 format from FD", "FD" },
  { "forward-fd", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING_ARRAY, &forward_fds,
    "Connect a file descriptor to the launched process. "
    "fds 0, 1 and 2 are automatically forwarded.",
    "FD" },
  { "inherit-env", '\0',
    G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, opt_env_cb,
    "Undo a previous --env, --unset-env, --pass-env, etc.", "VAR" },
  { "inherit-env-matching", '\0',
    G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, opt_env_cb,
    "Undo previous --env, --unset-env, etc. matching a shell-style wildcard",
    "WILDCARD" },
  { "list", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &opt_list,
    "List some of the available servers and then exit.",
    NULL },
  { "pass-env", '\0',
    G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, opt_env_cb,
    "Pass environment variable through, or unset if set.", "VAR" },
  { "pass-env-matching", '\0',
    G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, opt_env_cb,
    "Pass environment variables matching a shell-style wildcard.",
    "WILDCARD" },
  { "share-pids", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &opt_share_pids,
    "Use same pid namespace as calling sandbox.", NULL },
  { "shell-command", 'c',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING, &opt_shell_command,
    "Run this command via /bin/sh, with COMMAND as $0 and ARG... as $@.",
    "SHELL_COMMAND" },
  { "usr-path", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_FILENAME, &opt_usr_path,
    "Use DIR as the /usr for a Flatpak sub-sandbox. "
    "Requires '--bus-name=org.freedesktop.portal.Flatpak'.",
    "DIR" },
  { "socket", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING, &opt_socket,
    "Connect to a Launcher server listening on this AF_UNIX socket.",
    "ABSPATH|@ABSTRACT" },
  { "terminate", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &opt_terminate,
    "Terminate the Launcher server after the COMMAND (if any) has run.",
    NULL },
  { "unset-env", '\0',
    G_OPTION_FLAG_FILENAME, G_OPTION_ARG_CALLBACK, opt_env_cb,
    "Unset environment variable, like env -u.", "VAR" },
  { "verbose", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &opt_verbose,
    "Be more verbose.", NULL },
  { "version", '\0',
    G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, &opt_version,
    "Print version number and exit.", NULL },
  { NULL }
};

int
main (int argc,
      char *argv[])
{
  g_auto(GStrv) original_environ = NULL;
  g_autoptr(GMainLoop) loop = NULL;
  g_autoptr(GOptionContext) context = NULL;
  g_autoptr(GPtrArray) replacement_command_and_args = NULL;
  g_autoptr(GPtrArray) shell_argv = NULL;
  g_autoptr(GError) local_error = NULL;
  GError **error = &local_error;
  char **command_and_args;
  g_autoptr(FILE) original_stdout = NULL;
  g_autoptr(GDBusConnection) session_bus = NULL;
  g_autoptr(GDBusConnection) peer_connection = NULL;
  g_auto(GVariantBuilder) fd_builder = {};
  g_auto(GVariantBuilder) env_builder = {};
  g_auto(GVariantBuilder) options_builder = {};
  g_autoptr(AutoUnixFDList) fd_list = NULL;
  g_autoptr(GHashTable) pty_bridges = NULL;
  G_GNUC_UNUSED g_autoptr(GVariant) reply = NULL;
  gint stdin_handle = -1;
  gint stdout_handle = -1;
  gint stderr_handle = -1;
  GHashTableIter iter;
  gpointer key, value;
  g_autofree char *home_realpath = NULL;
  g_autofree char *service_unique_name = NULL;
  const char *flatpak_id = NULL;
  static const char * const run_interactive_shell[] =
  {
    "sh",
    "-euc",
    ("if [ -n \"${SHELL-}\" ]; then\n"
     "  if command -v \"$SHELL\" >/dev/null; then\n"
     "    exec \"$SHELL\"\n"
     "  fi\n"
     "  echo \"Shell '$SHELL' not available, falling back to bash\" >&2\n"
     "fi\n"
     "if command -v bash >/dev/null; then\n"
     "  exec bash\n"
     "fi\n"
     "echo 'bash not available, falling back to sh' >&2\n"
     "exec sh"),
    NULL
  };
  original_environ = g_get_environ ();
  global_original_environ = (const char * const *) original_environ;

  /* Set up the initial base logging */
  _srt_util_set_glib_log_handler ("steam-runtime-launch-client",
                                  G_LOG_DOMAIN, SRT_LOG_FLAGS_NONE);
  original_stdout = _srt_divert_stdout_to_stderr (error);

  if (original_stdout == NULL)
    {
      launch_exit_status = LAUNCH_EX_FAILED;
      goto out;
    }

  context = g_option_context_new ("COMMAND [ARG...]");