Example #1
0
static gboolean
on_handle_stream_socket (CockpitWebServer *server,
                         const gchar *path,
                         GIOStream *io_stream,
                         GHashTable *headers,
                         GByteArray *input,
                         guint in_length,
                         gpointer user_data)
{
  CockpitTransport *transport;
  const gchar *query = NULL;
  CockpitCreds *creds;
  CockpitPipe *pipe;
  gchar *value;
  gchar **env;

  if (!g_str_has_prefix (path, "/cockpit/socket"))
    return FALSE;

  if (path[15] == '?')
    query = path + 16;
  else if (path[15] != '\0')
    return FALSE;

  if (service)
    {
      g_object_ref (service);
    }
  else
    {
      value = g_strdup_printf ("%d", server_port);
      env = g_environ_setenv (g_get_environ (), "COCKPIT_TEST_SERVER_PORT", value, TRUE);

      creds = cockpit_creds_new (g_get_user_name (), "test",
                                 COCKPIT_CRED_CSRF_TOKEN, "myspecialtoken",
                                 NULL);
      pipe = cockpit_pipe_spawn ((const gchar **)bridge_argv, (const gchar **)env, NULL, FALSE);
      transport = cockpit_pipe_transport_new (pipe);
      service = cockpit_web_service_new (creds, transport);
      cockpit_creds_unref (creds);
      g_object_unref (transport);
      g_object_unref (pipe);

      g_free (value);
      g_strfreev (env);

      /* Clear the pointer automatically when service is done */
      g_object_add_weak_pointer (G_OBJECT (service), (gpointer *)&service);
    }

  if (query)
    cockpit_channel_socket_open (service, "/cockpit/socket", query, io_stream, headers, input);
  else
    cockpit_web_service_socket (service, "/cockpit/socket", io_stream, headers, input);

  /* Keeps ref on itself until it closes */
  g_object_unref (service);

  return TRUE;
}
Example #2
0
gboolean
ephy_profile_utils_do_migration (const char *profile_directory, int test_to_run, gboolean debug)
{
    gboolean ret;
    GError *error = NULL;
    char *index = NULL, *version = NULL;
    int status;
    const char *argv[6] = { PKGLIBEXECDIR "/" EPHY_PROFILE_MIGRATOR, "-v" };
    int i = 2; /* index for argv, start filling at 2. */
    char **envp;

    envp = g_environ_setenv (g_get_environ (),
                             "EPHY_LOG_MODULES", "ephy-profile",
                             TRUE);

    argv[i++] = version = g_strdup_printf ("%d", EPHY_PROFILE_MIGRATION_VERSION);

    /* If we're not trying to run a migration step in a test and there
       is nothing to migrate, don't spawn the migrator at all. */
    if (test_to_run == -1 &&
            EPHY_PROFILE_MIGRATION_VERSION == ephy_profile_utils_get_migration_version ()) {
        g_strfreev (envp);
        return TRUE;
    }

    if (test_to_run != -1) {
        index = g_strdup_printf ("%d", test_to_run);

        argv[i++] = "-d";
        argv[i++] = index;
    }

    if (profile_directory != NULL) {
        argv[i++] = "-p";
        argv[i++] = (char *)profile_directory;
    }

    argv[i++] = NULL;

    if (debug)
        argv[0] = ABS_TOP_BUILD_DIR "/lib/"EPHY_PROFILE_MIGRATOR;

    ret = g_spawn_sync (NULL, (char **)argv, envp, G_SPAWN_SEARCH_PATH,
                        NULL, NULL, NULL, NULL,
                        &status, &error);
    g_free (index);
    g_free (version);
    g_strfreev (envp);

    if (error) {
        LOG ("Failed to run migrator: %s", error->message);
        g_error_free (error);
    }

    if (status != 0)
        ret = FALSE;

    return ret;
}
Example #3
0
void SpiceControllerUnix::SetupControllerPipe(GStrv &env)
{
    std::string socket_file(this->m_tmp_dir);
    socket_file += "/spice-xpi";

    this->SetFilename(socket_file);

    env = g_environ_setenv(env, "SPICE_XPI_SOCKET", socket_file.c_str(), TRUE);
}
Example #4
0
gboolean
ephy_profile_utils_do_migration (const char *profile_directory, int test_to_run, gboolean debug)
{
  g_autoptr(GError) error = NULL;
  g_autofree char *index = NULL;
  g_autofree char *version = NULL;
  int status;
  const char *argv[8] = { PKGLIBEXECDIR "/" EPHY_PROFILE_MIGRATOR, "-v" };
  int i = 2; /* index for argv, start filling at 2. */
  g_auto(GStrv) envp = NULL;

  envp = g_environ_setenv (g_get_environ (),
                           "EPHY_LOG_MODULES", "ephy-profile",
                           TRUE);

  argv[i++] = version = g_strdup_printf ("%d", EPHY_PROFILE_MIGRATION_VERSION);

  /* If we're not trying to run a migration step in a test and there
     is nothing to migrate, don't spawn the migrator at all. */
  if (test_to_run == -1 &&
      EPHY_PROFILE_MIGRATION_VERSION == ephy_profile_utils_get_migration_version ()) {
    return TRUE;
  }

  if (test_to_run != -1) {
    index = g_strdup_printf ("%d", test_to_run);

    argv[i++] = "-d";
    argv[i++] = index;
  }

  if (profile_directory != NULL) {
    argv[i++] = "-p";
    argv[i++] = (char *)profile_directory;
  }

  argv[i++] = NULL;

#if DEVELOPER_MODE
  argv[0] = BUILD_ROOT "/src/" EPHY_PROFILE_MIGRATOR;
#else
  if (debug)
    argv[0] = BUILD_ROOT "/src/" EPHY_PROFILE_MIGRATOR;
#endif

  g_spawn_sync (NULL, (char **)argv, envp, G_SPAWN_SEARCH_PATH,
                NULL, NULL, NULL, NULL,
                &status, &error);
  if (error) {
    g_warning ("Failed to run migrator: %s", error->message);
    return FALSE;
  }

  return status == 0;
}
Example #5
0
/**
 * g_app_launch_context_setenv:
 * @context: a #GAppLaunchContext
 * @variable: the environment variable to set
 * @value: the value for to set the variable to.
 *
 * Arranges for @variable to be set to @value in the child's
 * environment when @context is used to launch an application.
 *
 * Since: 2.32
 */
void
g_app_launch_context_setenv (GAppLaunchContext *context,
                             const char        *variable,
                             const char        *value)
{
  if (!context->priv->envp)
    context->priv->envp = g_get_environ ();

  context->priv->envp =
    g_environ_setenv (context->priv->envp, variable, value, TRUE);
}
Example #6
0
File: command.c Project: Onway/anoj
static void
foreach_environ(gpointer data, gpointer user_data)
{
    Environ * ptr;
    char *** env;

    ptr = (Environ *)data;
    env = (char ***)user_data;
    if (!strcmp(ptr->value, ""))
        *env = g_environ_unsetenv(*env, ptr->key);
    else
        *env = g_environ_setenv(*env, ptr->key, ptr->value, TRUE);
}
Example #7
0
static void
button_clicked (GtkButton *button,
                GtkStack *stack)
{
  WakefieldCompositor *compositor;
  char *name = g_strdup_printf ("Child %d", child_count++);
  int fd, fd2;
  char *fd_s;
  char **envv;
  GError *error = NULL;
  char *argv[] = { "./test-embedded", NULL };

  compositor = wakefield_compositor_new ();

  gtk_widget_set_size_request (GTK_WIDGET (compositor), 400, 400);

  gtk_stack_add_titled (stack, GTK_WIDGET (compositor), name, name);
  gtk_widget_show (GTK_WIDGET (compositor));

  fd = wakefield_compositor_create_client_fd (compositor, (GDestroyNotify)gtk_widget_destroy, compositor, &error);
  if (error)
    {
      g_print ("error: %s\n", error->message);
      return;
    }

  /* We dup the fd here to get rid of the CLOEXEC */
  fd2 = dup (fd);
  close (fd);
  fd_s = g_strdup_printf ("%d", fd2);
  envv = g_get_environ ();
  envv = g_environ_setenv (envv, "WAYLAND_SOCKET", fd_s, TRUE);
  g_free (fd_s);

  g_spawn_async (NULL,
                 argv,
                 envv,
                 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
                 NULL,
                 &fd,
                 NULL, &error);
  g_strfreev (envv);
  close (fd2);
  if (error)
    {
      g_print ("error: %s\n", error->message);
      return;
    }
}
Example #8
0
GPid
pipe_stdio_to_hook(const gchar* envvar_name, GSourceFunc callback) {
  gchar** argv;
  gint argc;
  gchar **env = g_get_environ();
  env = g_environ_setenv(env, "NICE_REMOTE_HOSTNAME", remote_hostname, TRUE);

  gchar* cmd = g_getenv(envvar_name);
  g_debug("pipe_stdio_to_hook('%s')=%s\n", envvar_name, cmd);
  if(cmd == NULL || strlen(cmd) == 0)
    return -1;

  // parse command line to argv array
  if(!g_shell_parse_argv(cmd, &argc, &argv, NULL)) {
    g_critical("Error parsing command line '%s'", cmd);

    exit(1);
  }

  gboolean spawned;
  GPid pid;
  gint stdio[2];
  GError* error = NULL;

  g_debug("Executing '%s'\n", cmd);
  spawned = g_spawn_async_with_pipes(".", argv, env, G_SPAWN_CHILD_INHERITS_STDIN, NULL, NULL,
    &pid, NULL, NULL, NULL, &error);

  if(error != NULL) {
    g_critical("Error executing '%s': %s", cmd, error->message);
    return pid;
  }

  if(callback != NULL) {
    // no SIGCHLD, so we cannot
    // g_child_watch_add(pid, callback, NULL);

    gint interval_ms = 500;
    g_timeout_add(interval_ms, callback, (gpointer) pid);
  }

  g_unix_signal_add(SIGTERM, terminate_child_and_exit, (gpointer) pid);
  g_unix_signal_add(SIGINT, terminate_child_and_exit, (gpointer) pid);

  g_assert(spawned);

  return pid;
}
Example #9
0
static char *
get_our_server_response (const char *query)
{
        char *response;
        char *p;
        char *standard_output;
        int exit_status;
        char **environ;
        char *argv[] = { NULL, NULL };
        GError *error = NULL;

        environ = g_get_environ ();
        environ = g_environ_setenv (environ, "QUERY_STRING", query, TRUE);

        argv[0] = g_build_filename (BUILDDIR, "geoip-lookup", NULL);
        g_assert (argv[0] != NULL);

        if (!g_spawn_sync (BUILDDIR,
                           argv,
                           environ,
                           G_SPAWN_STDERR_TO_DEV_NULL,
                           NULL,
                           NULL,
                           &standard_output,
                           NULL,
                           &exit_status,
                           &error)) {
                g_warning ("Failed to execute '%s': %s", argv[0], error->message);
                g_error_free (error);
                g_assert_not_reached ();
        }

        g_strfreev (environ);
        g_free (argv[0]);

        /* Get rid of headers */
        p = strstr (standard_output, "\n\n");
        g_assert (p != NULL);
        p += 2;

        response = g_strdup (p);
        g_free (standard_output);

        return response;
}
static gboolean
_ostree_bootloader_grub2_write_config (OstreeBootloader      *bootloader,
                                       int                    bootversion,
                                       GCancellable          *cancellable,
                                       GError               **error)
{
  OstreeBootloaderGrub2 *self = OSTREE_BOOTLOADER_GRUB2 (bootloader);
  gboolean ret = FALSE;
  gs_unref_object GFile *efi_new_config_temp = NULL;
  gs_unref_object GFile *efi_orig_config = NULL;
  gs_unref_object GFile *new_config_path = NULL;
  gs_unref_object GSSubprocessContext *procctx = NULL;
  gs_unref_object GSSubprocess *proc = NULL;
  gs_strfreev char **child_env = g_get_environ ();
  gs_free char *bootversion_str = g_strdup_printf ("%u", (guint)bootversion);
  gs_unref_object GFile *config_path_efi_dir = NULL;

  if (self->is_efi)
    {
      config_path_efi_dir = g_file_get_parent (self->config_path_efi);
      new_config_path = g_file_get_child (config_path_efi_dir, "grub.cfg.new");
      /* We use grub2-mkconfig to write to a temporary file first */
      if (!ot_gfile_ensure_unlinked (new_config_path, cancellable, error))
        goto out;
    }
  else
    {
      new_config_path = ot_gfile_resolve_path_printf (self->sysroot->path, "boot/loader.%d/grub.cfg",
                                                      bootversion);
    }

  procctx = gs_subprocess_context_newv ("grub2-mkconfig", "-o",
                                        gs_file_get_path_cached (new_config_path),
                                        NULL);
  child_env = g_environ_setenv (child_env, "_OSTREE_GRUB2_BOOTVERSION", bootversion_str, TRUE);
  /* We have to pass our state to the child */
  if (self->is_efi)
    child_env = g_environ_setenv (child_env, "_OSTREE_GRUB2_IS_EFI", "1", TRUE);
  gs_subprocess_context_set_environment (procctx, child_env);
  gs_subprocess_context_set_stdout_disposition (procctx, GS_SUBPROCESS_STREAM_DISPOSITION_NULL);
  if (g_getenv ("OSTREE_DEBUG_GRUB2"))
    gs_subprocess_context_set_stderr_disposition (procctx, GS_SUBPROCESS_STREAM_DISPOSITION_INHERIT);
  else
    gs_subprocess_context_set_stderr_disposition (procctx, GS_SUBPROCESS_STREAM_DISPOSITION_NULL);

  /* In the current Fedora grub2 package, this script doesn't even try
     to be atomic; it just does:

cat ${grub_cfg}.new > ${grub_cfg}
rm -f ${grub_cfg}.new

     Upstream is fixed though.
  */
  proc = gs_subprocess_new (procctx, cancellable, error);
  if (!proc)
    goto out;

  if (!gs_subprocess_wait_sync_check (proc, cancellable, error))
    goto out;

  /* Now let's fdatasync() for the new file */
  if (!gs_file_sync_data (new_config_path, cancellable, error))
    goto out;

  if (self->is_efi)
    {
      gs_unref_object GFile *config_path_efi_old = g_file_get_child (config_path_efi_dir, "grub.cfg.old");
      
      /* copy current to old */
      if (!ot_gfile_ensure_unlinked (config_path_efi_old, cancellable, error))
        goto out;
      if (!g_file_copy (self->config_path_efi, config_path_efi_old,
                        G_FILE_COPY_OVERWRITE, cancellable, NULL, NULL, error))
        goto out;
      if (!ot_gfile_ensure_unlinked (config_path_efi_old, cancellable, error))
        goto out;

      /* NOTE: NON-ATOMIC REPLACEMENT; WE can't do anything else on FAT;
       * see https://bugzilla.gnome.org/show_bug.cgi?id=724246
       */
      if (!ot_gfile_ensure_unlinked (self->config_path_efi, cancellable, error))
        goto out;
      if (!gs_file_rename (new_config_path, self->config_path_efi,
                           cancellable, error))
        goto out;
    }
  
  ret = TRUE;
 out:
  return ret;
}
Example #11
0
static void on_new_message(PurpleAccount *account, const char *remote,
    const char *message)
{
  const char *command = purple_prefs_get_path(PLUGIN_PREF_COMMAND);

  // the command should be never NULL
  g_return_if_fail(command);

  if (!command[0]) {
    // no command is set
    return;
  }

  const char *protocol = purple_account_get_protocol_name(account);
  char *local = g_strdup(purple_normalize(account,
        purple_account_get_username(account)));
  char *nohtml = purple_markup_strip_html(message);
  PurpleBuddy *buddy = purple_find_buddy(account, remote);
  char *icon_encoded = NULL;
  if (buddy) {
    // get buddy alias and icon
    remote = purple_buddy_get_alias(buddy);
    PurpleBuddyIcon *icon = purple_buddy_get_icon(buddy);
    if (icon) {
      size_t len;
      gconstpointer data = purple_buddy_icon_get_data(icon, &len);
      icon_encoded = g_base64_encode(data, len);
    }
  }

  char *argv[2];
  argv[0] = g_strdup(command);
  argv[1] = NULL;

  // prepare child's environment variables
  char **envp = g_get_environ();
  envp = g_environ_setenv(envp, "EVENT_TYPE", "msg", TRUE);
  envp = g_environ_setenv(envp, "EVENT_NETWORK", protocol, TRUE);
  envp = g_environ_setenv(envp, "EVENT_LOCAL_USER", local, TRUE);
  envp = g_environ_setenv(envp, "EVENT_REMOTE_USER", remote, TRUE);
  if (icon_encoded)
    envp = g_environ_setenv(envp, "EVENT_REMOTE_USER_ICON", icon_encoded, TRUE);
  envp = g_environ_setenv(envp, "EVENT_MESSAGE", nohtml, TRUE);
  envp = g_environ_setenv(envp, "EVENT_MESSAGE_HTML", message, TRUE);

  // spawn the command
  GError *err = NULL;
  if (!g_spawn_async(NULL, argv, envp, G_SPAWN_SEARCH_PATH
        | G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL,
        NULL, &err)) {
    purple_debug_error("extaction", "%s", err->message);
    g_clear_error(&err);
  }

  // free all resources
  g_free(argv[0]);
  g_strfreev(envp);

  g_free(local);
  g_free(nohtml);
  g_free(icon_encoded);
}
Example #12
0
static gboolean
on_handle_stream_socket (CockpitWebServer *server,
                         const gchar *path,
                         GIOStream *io_stream,
                         GHashTable *headers,
                         GByteArray *input,
                         gpointer user_data)
{
  CockpitTransport *transport;
  const gchar *query = NULL;
  CockpitCreds *creds;
  int session_stdin = -1;
  int session_stdout = -1;
  GError *error = NULL;
  GPid pid = 0;

  gchar *value;
  gchar **env;
  gchar **argv;

  if (!g_str_has_prefix (path, "/cockpit/socket"))
    return FALSE;

  if (path[15] == '?')
    {
      query = path + 16;
    }
  else if (path[15] != '\0')
    {
      return FALSE;
    }

  if (service)
    {
      g_object_ref (service);
    }
  else
    {
      g_clear_object (&bridge);

      value = g_strdup_printf ("%d", server_port);
      env = g_environ_setenv (g_get_environ (), "COCKPIT_TEST_SERVER_PORT", value, TRUE);

      argv = g_strdupv (bridge_argv);
      if (query)
        argv[g_strv_length (argv) - 1] = g_strdup (query);

      g_spawn_async_with_pipes (NULL, argv, env,
                                G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
                                NULL, NULL, &pid, &session_stdin, &session_stdout, NULL, &error);

      g_strfreev (env);
      g_free (argv);
      g_free (value);

      if (error)
        {
          g_critical ("couldn't run bridge %s: %s", bridge_argv[0], error->message);
          return FALSE;
        }

      bridge = g_object_new (COCKPIT_TYPE_PIPE,
                             "name", "test-server-bridge",
                             "in-fd", session_stdout,
                             "out-fd", session_stdin,
                             "pid", pid,
                             NULL);

      creds = cockpit_creds_new (g_get_user_name (), "test",
                                 COCKPIT_CRED_CSRF_TOKEN, "myspecialtoken",
                                 NULL);

      transport = cockpit_pipe_transport_new (bridge);
      service = cockpit_web_service_new (creds, transport);
      cockpit_creds_unref (creds);
      g_object_unref (transport);

      /* Clear the pointer automatically when service is done */
      g_object_add_weak_pointer (G_OBJECT (service), (gpointer *)&service);
    }

  cockpit_web_service_socket (service, path, io_stream, headers, input);

  /* Keeps ref on itself until it closes */
  g_object_unref (service);

  return TRUE;
}
/* Spawn passwd backend
 * Returns: TRUE on success, FALSE otherwise and sets error appropriately */
static gboolean
spawn_passwd (PasswdHandler *passwd_handler, GError **error)
{
        gchar   *argv[2];
        gchar  **envp;
        gint    my_stdin, my_stdout, my_stderr;

        argv[0] = "/usr/bin/passwd";    /* Is it safe to rely on a hard-coded path? */
        argv[1] = NULL;

        envp = g_get_environ ();
        envp = g_environ_setenv (envp, "LC_ALL", "C", TRUE);

        if (!g_spawn_async_with_pipes (NULL,                            /* Working directory */
                                       argv,                            /* Argument vector */
                                       envp,                            /* Environment */
                                       G_SPAWN_DO_NOT_REAP_CHILD,       /* Flags */
                                       ignore_sigpipe,                  /* Child setup */
                                       NULL,                            /* Data to child setup */
                                       &passwd_handler->backend_pid,    /* PID */
                                       &my_stdin,                       /* Stdin */
                                       &my_stdout,                      /* Stdout */
                                       &my_stderr,                      /* Stderr */
                                       error)) {                        /* GError */

                /* An error occured */
                free_passwd_resources (passwd_handler);

                g_strfreev (envp);

                return FALSE;
        }

        g_strfreev (envp);

        /* 2>&1 */
        if (dup2 (my_stderr, my_stdout) == -1) {
                /* Failed! */
                g_set_error_literal (error,
                                     PASSWD_ERROR,
                                     PASSWD_ERROR_BACKEND,
                                     strerror (errno));

                /* Clean up */
                stop_passwd (passwd_handler);

                return FALSE;
        }

        /* Open IO Channels */
        passwd_handler->backend_stdin = g_io_channel_unix_new (my_stdin);
        passwd_handler->backend_stdout = g_io_channel_unix_new (my_stdout);

        /* Set raw encoding */
        /* Set nonblocking mode */
        if (g_io_channel_set_encoding (passwd_handler->backend_stdin, NULL, error) != G_IO_STATUS_NORMAL ||
                g_io_channel_set_encoding (passwd_handler->backend_stdout, NULL, error) != G_IO_STATUS_NORMAL ||
                g_io_channel_set_flags (passwd_handler->backend_stdin, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ||
                g_io_channel_set_flags (passwd_handler->backend_stdout, G_IO_FLAG_NONBLOCK, error) != G_IO_STATUS_NORMAL ) {

                /* Clean up */
                stop_passwd (passwd_handler);
                return FALSE;
        }

        /* Turn off buffering */
        g_io_channel_set_buffered (passwd_handler->backend_stdin, FALSE);
        g_io_channel_set_buffered (passwd_handler->backend_stdout, FALSE);

        /* Add IO Channel watcher */
        passwd_handler->backend_stdout_watch_id = g_io_add_watch (passwd_handler->backend_stdout,
                                                                  G_IO_IN | G_IO_PRI,
                                                                  (GIOFunc) io_watch_stdout, passwd_handler);

        /* Add child watcher */
        passwd_handler->backend_child_watch_id = g_child_watch_add (passwd_handler->backend_pid, (GChildWatchFunc) child_watch_cb, passwd_handler);

        /* Success! */

        return TRUE;
}
Example #14
0
static GtkWidget*
create_new_window (GtkApplication *application,
                   GVariantDict   *options)
{
    dg_lmem gchar* command = NULL;
    dg_lmem gchar* title = NULL;
    gboolean opt_show_title;
    gboolean opt_update_title;
    gboolean opt_no_headerbar;

    g_object_get (dwt_settings_get_instance (),
                  "show-title", &opt_show_title,
                  "update-title", &opt_update_title,
                  "no-header-bar", &opt_no_headerbar,
                  "command", &command,
                  "title", &title,
                  NULL);

    const gchar *opt_command = command;
    const gchar *opt_title   = title;
    const gchar *opt_workdir = NULL;

    if (options) {
        gboolean opt_no_auto_title = FALSE;
        g_variant_dict_lookup (options, "title-on-maximize", "b", &opt_show_title);
        g_variant_dict_lookup (options, "no-header-bar", "b", &opt_no_headerbar);
        g_variant_dict_lookup (options, "no-auto-title", "b", &opt_no_auto_title);
        g_variant_dict_lookup (options, "workdir", "&s", &opt_workdir);
        g_variant_dict_lookup (options, "command", "&s", &opt_command);
        g_variant_dict_lookup (options, "title",   "&s", &opt_title);
        if (opt_no_auto_title)
            opt_update_title = FALSE;
    }
    if (!opt_workdir) opt_workdir = g_get_home_dir ();
    if (!opt_command) opt_command = guess_shell ();

    /*
     * Title either comes from the default value of the "title" setting,
     * or from the command line flag, but should never be NULL at this
     * point.
     */
    g_assert (opt_title);

    dg_lerr GError *gerror = NULL;
    gint command_argv_len = 0;
    gchar **command_argv = NULL;

    if (!g_shell_parse_argv (opt_command,
                             &command_argv_len,
                             &command_argv,
                             &gerror))
    {
        g_printerr ("%s: coult not parse command: %s\n",
                    __func__, gerror->message);
        return NULL;
    }

    GtkWidget *window = gtk_application_window_new (application);
    gtk_widget_set_visual (window,
                           gdk_screen_get_system_visual (gtk_widget_get_screen (window)));
    gtk_application_window_set_show_menubar (GTK_APPLICATION_WINDOW (window),
                                             FALSE);
    gtk_window_set_title (GTK_WINDOW (window), opt_title);
    gtk_window_set_hide_titlebar_when_maximized (GTK_WINDOW (window),
                                                 !opt_show_title);

    g_action_map_add_action_entries (G_ACTION_MAP (window), win_actions,
                                     G_N_ELEMENTS (win_actions), window);

    VteTerminal *vtterm = VTE_TERMINAL (vte_terminal_new ());
    configure_term_widget (vtterm, options);
    term_char_size_changed (vtterm,
                            vte_terminal_get_char_width (vtterm),
                            vte_terminal_get_char_height (vtterm),
                            window);

    g_signal_connect (G_OBJECT (window), "notify::has-toplevel-focus",
                      G_CALLBACK (window_has_toplevel_focus_notified),
                      vtterm);

    g_signal_connect (G_OBJECT (vtterm), "char-size-changed",
                      G_CALLBACK (term_char_size_changed), window);
    g_signal_connect (G_OBJECT (vtterm), "child-exited",
                      G_CALLBACK (term_child_exited), window);
    g_signal_connect (G_OBJECT (vtterm), "bell",
                      G_CALLBACK (term_beeped), window);
    g_signal_connect (G_OBJECT (vtterm), "button-release-event",
                      G_CALLBACK (term_mouse_button_released),
                      setup_popover (vtterm));

    /*
     * Propagate title changes to the window.
     */
    if (opt_update_title)
        g_object_bind_property (G_OBJECT (vtterm), "window-title",
                                G_OBJECT (window), "title",
                                G_BINDING_DEFAULT);

    if (!opt_no_headerbar)
        setup_header_bar (window, vtterm, opt_show_title);

    gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (vtterm));
    gtk_widget_set_receives_default (GTK_WIDGET (vtterm), TRUE);

    /* We need to realize and show the window for it to have a valid XID */
    gtk_widget_show_all (window);

    gchar **command_env = g_get_environ ();
#ifdef GDK_WINDOWING_X11
    if (GDK_IS_X11_SCREEN (gtk_widget_get_screen (window))) {
        GdkWindow *gdk_window = gtk_widget_get_window (window);
        if (gdk_window) {
            gchar window_id[NDIGITS10(unsigned long)];
            snprintf (window_id,
                      sizeof (window_id),
                      "%lu",
                      GDK_WINDOW_XID (gdk_window));
            command_env = g_environ_setenv (command_env,
                                            "WINDOWID",
                                            window_id,
                                            TRUE);
        } else {
            g_printerr ("No window, cannot set $WINDOWID!\n");
        }
    }
Example #15
0
static gint _main_helper(Options* options) {
    /* start off with some status messages */
#if defined(IGRAPH_VERSION)
    gint igraphMajor = -1, igraphMinor = -1, igraphPatch = -1;
    igraph_version(NULL, &igraphMajor, &igraphMinor, &igraphPatch);

    gchar* startupStr = g_strdup_printf("Starting %s with GLib v%u.%u.%u and IGraph v%i.%i.%i",
            SHADOW_VERSION_STRING,
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
            igraphMajor, igraphMinor, igraphPatch);
#else
    gchar* startupStr = g_strdup_printf("Starting %s with GLib v%u.%u.%u (IGraph version not available)",
            SHADOW_VERSION_STRING,
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
#endif

    message("%s", startupStr);
    /* avoid logging the message to stderr twice (only log if this is not a relaunch) */
    if(g_getenv("SHADOW_SPAWNED") == NULL) {
        g_printerr("** %s\n", startupStr);
    }
    g_free(startupStr);

    message(SHADOW_INFO_STRING);
    message("logging current startup arguments and environment");

    gchar** envlist = g_get_environ();
    gchar** arglist = g_strsplit(options_getArgumentString(options), " ", 0);
    _main_logEnvironment(arglist, envlist);
    g_strfreev(arglist);
    g_strfreev(envlist);

    /* check if we still need to setup our required environment and relaunch */
    if(g_getenv("SHADOW_SPAWNED") == NULL) {
        message("shadow will automatically adjust environment and relaunch");
        message("loading shadow configuration file");

        /* we need to relaunch.
         * first lets load the config file to help us setup the environment */
        const GString* fileName = options_getInputXMLFilename(options);
        if(!fileName) {
            return EXIT_FAILURE;
        }

        GString* file = utility_getFileContents(fileName->str);
        if(!file) {
            critical("unable to read config file contents");
            return EXIT_FAILURE;
        }

        Configuration* config = configuration_new(options, file);
        g_string_free(file, TRUE);
        file = NULL;
        if(!config) {
            critical("there was a problem parsing the Shadow config file, and we can't run without it");
            return EXIT_FAILURE;
        }

        message("shadow configuration file loaded, parsed, and passed validation");

        /* now start to set up the environment */
        gchar** envlist = g_get_environ();
        GString* commandBuffer = g_string_new(options_getArgumentString(options));

        if(!envlist || !commandBuffer) {
            critical("there was a problem loading existing environment");
            configuration_free(config);
            return EXIT_FAILURE;
        }

        message("setting up LD_PRELOAD environment");

        /* compute the proper LD_PRELOAD value, extract the shadow preload file and
         * set it as a command line argument if needed */
        gchar* preloadArgValue = NULL;
        {
            /* before we restart, we should:
             *  -set the shadow preload lib as a command line arg
             *  -make sure it does not exist in LD_PRELOAD, but otherwise leave LD_PRELOAD in place
             * we need to search for our preload lib. our order of preference follows.
             */

            /* 1. existing "--preload=" option value */

            if(_main_isValidPathToPreloadLib(options_getPreloadString(options))) {
                preloadArgValue = g_strdup(options_getPreloadString(options));
            }

            /* 2. the 'preload' attribute value of the 'shadow' element in shadow.config.xml */

            /* we only need to search if we haven't already found a valid path */
            if(!preloadArgValue) {
                ConfigurationShadowElement* element = configuration_getShadowElement(config);
                if(element && element->preloadPath.isSet) {
                    gchar* path = element->preloadPath.string->str;
                    if(_main_isValidPathToPreloadLib(path)) {
                        preloadArgValue = g_strdup(path);
                    }
                }
            }

            /* 3. the LD_PRELOAD value */

            GString* preloadEnvValueBuffer = NULL;
            /* we always search the env variable and remove existing Shadow preload libs */
            if(g_environ_getenv(envlist, "LD_PRELOAD") != NULL) {
                gchar** tokens = g_strsplit(g_environ_getenv(envlist, "LD_PRELOAD"), ":", 0);

                for(gint i = 0; tokens[i] != NULL; i++) {
                    /* each token in the env variable should be an absolute path */
                    if(_main_isValidPathToPreloadLib(tokens[i])) {
                        /* found a valid path, only save it if we don't have one yet (from options or config) */
                        if(!preloadArgValue) {
                            preloadArgValue = g_strdup(tokens[i]);
                        }
                    } else {
                        /* maintain non-shadow entries */
                        if(preloadEnvValueBuffer) {
                            g_string_append_printf(preloadEnvValueBuffer, ":%s", tokens[i]);
                        } else {
                            preloadEnvValueBuffer = g_string_new(tokens[i]);
                        }
                    }
                }

                g_strfreev(tokens);
            }

            /* 4. the 'environment' attribute of the 'shadow' configuration element in shadow.config.xml */

            /* always go through the 'environment' attribute of the 'shadow' element to pull in any keys defined there */
            {
                ConfigurationShadowElement* element = configuration_getShadowElement(config);
                if(element && element->environment.isSet) {
                    /* entries are split by ';' */
                    gchar** envTokens = g_strsplit(element->environment.string->str, ";", 0);

                    for(gint i = 0; envTokens[i] != NULL; i++) {
                        /* each env entry is key=value, get 2 tokens max */
                        gchar** items = g_strsplit(envTokens[i], "=", 2);

                        gchar* key = items[0];
                        gchar* value = items[1];

                        if(key != NULL && value != NULL) {
                            /* check if the key is LD_PRELOAD */
                            if(!g_ascii_strncasecmp(key, "LD_PRELOAD", 10)) {
                                gchar** preloadTokens = g_strsplit(value, ":", 0);

                                for(gint j = 0; preloadTokens[j] != NULL; j++) {
                                    /* each token in the env variable should be an absolute path */
                                    if(_main_isValidPathToPreloadLib(preloadTokens[j])) {
                                        /* found a valid path, only save it if we don't have one yet (from options or config) */
                                        if(!preloadArgValue) {
                                            preloadArgValue = g_strdup(preloadTokens[j]);
                                        }
                                    } else {
                                        /* maintain non-shadow entries */
                                        if(preloadEnvValueBuffer) {
                                            g_string_append_printf(preloadEnvValueBuffer, ":%s", preloadTokens[j]);
                                        } else {
                                            preloadEnvValueBuffer = g_string_new(preloadTokens[j]);
                                        }
                                    }
                                }

                                g_strfreev(preloadTokens);
                            } else {
                                /* set the key=value pair, but don't overwrite any existing settings */
                                envlist = g_environ_setenv(envlist, key, value, 0);
                            }
                        }

                        g_strfreev(items);
                    }

                    g_strfreev(envTokens);
                }
            }

            /* save away the non-shadow preload libs */
            if(preloadEnvValueBuffer) {
                envlist = g_environ_setenv(envlist, "LD_PRELOAD", preloadEnvValueBuffer->str, 1);
                g_string_free(preloadEnvValueBuffer, TRUE);
                preloadEnvValueBuffer = NULL;
            } else {
                envlist = g_environ_unsetenv(envlist, "LD_PRELOAD");
            }

            /* 5. as a last hope, try looking in RPATH since shadow is built with one */

            /* we only need to search if we haven't already found a valid path */
            if(!preloadArgValue) {
                gchar* rpathStr = _main_getRPath();
                if(rpathStr != NULL) {
                    gchar** tokens = g_strsplit(rpathStr, ":", 0);

                    for(gint i = 0; tokens[i] != NULL; i++) {
                        GString* candidateBuffer = g_string_new(NULL);

                        /* rpath specifies directories, so look inside */
                        g_string_printf(candidateBuffer, "%s/%s", tokens[i], INTERPOSELIBSTR);
                        gchar* candidate = g_string_free(candidateBuffer, FALSE);

                        if(_main_isValidPathToPreloadLib(candidate)) {
                            preloadArgValue = candidate;
                            break;
                        } else {
                            g_free(candidate);
                        }
                    }

                    g_strfreev(tokens);
                }
                g_free(rpathStr);
            }

            /* if we still didn't find our preload lib, that is a user error */
            if(!preloadArgValue) {
                critical("can't find path to %s, did you specify an absolute path to an existing readable file?", INTERPOSELIBSTR);
                configuration_free(config);
                return EXIT_FAILURE;
            }

            /* now that we found the correct path to the preload lib, first remove any possibly
             * incomplete path that might exist in the command line args, and then replace it
             * with the path that we found and verified is correct. */

            {
                /* first remove all preload options */
                gchar** tokens = g_strsplit(commandBuffer->str, " ", 0);
                g_string_free(commandBuffer, TRUE);
                commandBuffer = NULL;

                for(gint i = 0; tokens[i] != NULL; i++) {
                    /* use -1 to search the entire string */
                    if(!g_ascii_strncasecmp(tokens[i], "--preload=", 10)) {
                        /* skip this key=value string */
                    } else if(!g_ascii_strncasecmp(tokens[i], "-p", 2)) {
                        /* skip this key, and also the next arg which is the value */
                        i++;
                    } else {
                        if(commandBuffer) {
                            g_string_append_printf(commandBuffer, " %s", tokens[i]);
                        } else {
                            commandBuffer = g_string_new(tokens[i]);
                        }
                    }
                }

                g_strfreev(tokens);

                /* now add back in the preload option */
                g_string_append_printf(commandBuffer, " --preload=%s", preloadArgValue);
            }

        }

        message("setting up LD_STATIC_TLS_EXTRA environment");

        /* compute the proper TLS size we need for dlmopen()ing all of the plugins,
         * but only do this if the user didn't manually specify a size */
        if(g_environ_getenv(envlist, "LD_STATIC_TLS_EXTRA") == NULL) {
            gchar* staticTLSValue = _main_getStaticTLSValue(options, config, preloadArgValue);
            envlist = g_environ_setenv(envlist, "LD_STATIC_TLS_EXTRA", staticTLSValue, 0);
            message("we need %s total bytes of static TLS storage", staticTLSValue);
            g_free(staticTLSValue);
        }

        /* cleanup unused string */
        if(preloadArgValue) {
            g_free(preloadArgValue);
            preloadArgValue = NULL;
        }

        /* are we running valgrind */
        if(options_doRunValgrind(options)) {
            message("setting up environment for valgrind");

            /* make glib friendlier to valgrind */
            envlist = g_environ_setenv(envlist, "G_DEBUG", "gc-friendly", 0);
            envlist = g_environ_setenv(envlist, "G_SLICE", "always-malloc", 0);

            /* add the valgrind command and some default options */
            g_string_prepend(commandBuffer,
                            "valgrind --leak-check=full --show-reachable=yes --track-origins=yes --trace-children=yes --log-file=shadow-valgrind-%p.log --error-limit=no ");
        } else {
            /* The following can be used to add internal GLib memory validation that
             * will abort the program if it finds an error. This is only useful outside
             * of the valgrind context, as otherwise valgrind will complain about
             * the implementation of the GLib validator.
             * e.g. $ G_SLICE=debug-blocks shadow --file
             *
             * envlist = g_environ_setenv(envlist, "G_SLICE", "debug-blocks", 0);
             */
        }

        /* keep track that we are relaunching shadow */
        envlist = g_environ_setenv(envlist, "SHADOW_SPAWNED", "TRUE", 1);

        gchar* command = g_string_free(commandBuffer, FALSE);
        gchar** arglist = g_strsplit(command, " ", 0);
        g_free(command);

        configuration_free(config);

        message("environment was updated; shadow is relaunching now with new environment");

        Logger* logger = logger_getDefault();
        if(logger) {
            logger_setDefault(NULL);
            logger_unref(logger);
        }

        /* execvpe only returns if there is an error, otherwise the current process
         * image is replaced with a new process */
        gint returnValue = execvpe(arglist[0], arglist, envlist);

        /* cleanup */
        if(envlist) {
            g_strfreev(envlist);
        }
        if(arglist) {
            g_strfreev(arglist);
        }

        critical("** Error %i while re-launching shadow process: %s", returnValue, g_strerror(returnValue));
        return EXIT_FAILURE;
    }

    /* we dont need to relaunch, so we can run the simulation */

    /* make sure we have initialized static tls */
    if(!_main_verifyStaticTLS()) {
        critical("** Shadow Setup Check Failed: LD_STATIC_TLS_EXTRA does not contain a nonzero value");
        return EXIT_FAILURE;
    }

    /* make sure we have the shadow preload lib */
    if(!_main_isValidPathToPreloadLib(options_getPreloadString(options))) {
        critical("** Shadow Setup Check Failed: cannot find absolute path to "INTERPOSELIBSTR"");
        return EXIT_FAILURE;
    }

    /* now load the preload library into shadow's namespace */
    if(!_main_loadShadowPreload(options)) {
        critical("** Shadow Setup Check Failed: unable to load preload library");
        return EXIT_FAILURE;
    }

    /* tell the preload lib we are ready for action */
    extern int interposer_setShadowIsLoaded(int);
    int interposerResult = interposer_setShadowIsLoaded(1);

    if(interposerResult != 0) {
        /* it was not intercepted, meaning our preload library is not set up properly */
        critical("** Shadow Setup Check Failed: preload library is not correctly interposing functions");
        return EXIT_FAILURE;
    }

    message("startup checks passed, we are ready to start simulation");

    /* pause for debugger attachment if the option is set */
    if(options_doRunDebug(options)) {
        gint pid = (gint)getpid();
        message("Pausing with SIGTSTP to enable debugger attachment (pid %i)", pid);
        g_printerr("** Pausing with SIGTSTP to enable debugger attachment (pid %i)\n", pid);
        raise(SIGTSTP);
        message("Resuming now");
    }

    /* allocate and initialize our main simulation driver */
    gint returnCode = 0;
    shadowMaster = master_new(options);

    message("log message buffering is enabled for efficiency");
    logger_setEnableBuffering(logger_getDefault(), TRUE);

    if(shadowMaster) {
        /* run the simulation */
        returnCode = master_run(shadowMaster);
        /* cleanup */
        master_free(shadowMaster);
        shadowMaster = NULL;
    }

    message("%s simulation was shut down cleanly, returning code %i", SHADOW_VERSION_STRING, returnCode);
    return returnCode;
}
Example #16
0
static gchar *
spawn_dbus_daemon (const gchar *binary,
    const gchar *configuration,
    const gchar *listen_address,
    TestUser user,
    const gchar *runtime_dir,
    GPid *daemon_pid)
{
  GError *error = NULL;
  GString *address;
  gint address_fd;
  GPtrArray *argv;
  gchar **envp;
#ifdef DBUS_UNIX
  const struct passwd *pwd = NULL;
#endif

  if (user != TEST_USER_ME)
    {
#ifdef DBUS_UNIX
      if (getuid () != 0)
        {
          g_test_skip ("cannot use alternative uid when not uid 0");
          return NULL;
        }

      switch (user)
        {
          case TEST_USER_ROOT:
            break;

          case TEST_USER_MESSAGEBUS:
            pwd = getpwnam (DBUS_USER);

            if (pwd == NULL)
              {
                gchar *message = g_strdup_printf ("user '%s' does not exist",
                    DBUS_USER);

                g_test_skip (message);
                g_free (message);
                return NULL;
              }

            break;

          case TEST_USER_OTHER:
            pwd = getpwnam (DBUS_TEST_USER);

            if (pwd == NULL)
              {
                gchar *message = g_strdup_printf ("user '%s' does not exist",
                    DBUS_TEST_USER);

                g_test_skip (message);
                g_free (message);
                return NULL;
              }

            break;

          case TEST_USER_ME:
            /* cannot get here, fall through */
          default:
            g_assert_not_reached ();
        }
#else
      g_test_skip ("cannot use alternative uid on Windows");
      return NULL;
#endif
    }

  envp = g_get_environ ();

  if (runtime_dir != NULL)
    envp = g_environ_setenv (envp, "XDG_RUNTIME_DIR", runtime_dir, TRUE);

  argv = g_ptr_array_new_with_free_func (g_free);
  g_ptr_array_add (argv, g_strdup (binary));
  g_ptr_array_add (argv, g_strdup (configuration));
  g_ptr_array_add (argv, g_strdup ("--nofork"));
  g_ptr_array_add (argv, g_strdup ("--print-address=1")); /* stdout */

  if (listen_address != NULL)
    g_ptr_array_add (argv, g_strdup (listen_address));

#ifdef DBUS_UNIX
  g_ptr_array_add (argv, g_strdup ("--systemd-activation"));
#endif

  g_ptr_array_add (argv, NULL);

  g_spawn_async_with_pipes (NULL, /* working directory */
      (gchar **) argv->pdata,
      envp,
      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
#ifdef DBUS_UNIX
      child_setup, (gpointer) pwd,
#else
      NULL, NULL,
#endif
      daemon_pid,
      NULL, /* child's stdin = /dev/null */
      &address_fd,
      NULL, /* child's stderr = our stderr */
      &error);
  g_assert_no_error (error);

  g_ptr_array_free (argv, TRUE);
  g_strfreev (envp);

  address = g_string_new (NULL);

  /* polling until the dbus-daemon writes out its address is a bit stupid,
   * but at least it's simple, unlike dbus-launch... in principle we could
   * use select() here, but life's too short */
  while (1)
    {
      gssize bytes;
      gchar buf[4096];
      gchar *newline;

      bytes = read (address_fd, buf, sizeof (buf));

      if (bytes > 0)
        g_string_append_len (address, buf, bytes);

      newline = strchr (address->str, '\n');

      if (newline != NULL)
        {
          if ((newline > address->str) && ('\r' == newline[-1]))
            newline -= 1;
          g_string_truncate (address, newline - address->str);
          break;
        }

      g_usleep (G_USEC_PER_SEC / 10);
    }

  g_close (address_fd, NULL);

  return g_string_free (address, FALSE);
}
Example #17
0
gpointer SpiceController::ClientThread(gpointer data)
{
    SpiceController *fake_this = (SpiceController *)data;
    gchar **env = g_get_environ();
    GPid pid;
    gboolean spawned = FALSE;
    GError *error = NULL;
    GStrv client_argv;

    // Setup client environment
    fake_this->SetupControllerPipe(env);
    if (!fake_this->m_proxy.empty())
        env = g_environ_setenv(env, "SPICE_PROXY", fake_this->m_proxy.c_str(), TRUE);

    // Try to spawn main client
    client_argv = fake_this->GetClientPath();
    if (client_argv != NULL) {
        char *argv_str = g_strjoinv(" ", client_argv);
        g_warning("main client cmdline: %s", argv_str);
        g_free(argv_str);

        spawned = g_spawn_async(NULL,
                                client_argv, env,
                                G_SPAWN_DO_NOT_REAP_CHILD,
                                NULL, NULL, /* child_func, child_arg */
                                &pid, &error);
        if (error != NULL) {
            g_warning("failed to start %s: %s", client_argv[0], error->message);
            g_warn_if_fail(spawned == FALSE);
            g_clear_error(&error);
        }
        g_strfreev(client_argv);
    }

    if (!spawned) {
        // Fallback client for backward compatibility
        GStrv fallback_argv;
        char *argv_str;
        fallback_argv = fake_this->GetFallbackClientPath();
        if (fallback_argv == NULL) {
            goto out;
        }

        argv_str = g_strjoinv(" ", fallback_argv);
        g_warning("fallback client cmdline: %s", argv_str);
        g_free(argv_str);

        g_message("failed to run preferred client, running fallback client instead");
        spawned = g_spawn_async(NULL, fallback_argv, env,
                                G_SPAWN_DO_NOT_REAP_CHILD,
                                NULL, NULL, /* child_func, child_arg */
                                &pid, &error);
        if (error != NULL) {
            g_warning("failed to start %s: %s", fallback_argv[0], error->message);
            g_warn_if_fail(spawned == FALSE);
            g_clear_error(&error);
        }
    }

    out:
        g_strfreev(env);

    if (!spawned) {
        g_critical("ERROR failed to run spicec fallback");
        return NULL;
    }

#ifdef XP_UNIX
    fake_this->m_pid_controller = pid;
#endif
    fake_this->WaitForPid(pid);

    return NULL;
}
Example #18
0
static gboolean 
download_spawn_external(const char *uri, const char *filename, WebKitDownload *download) 
{
    char **argv; 
    int argc;
    gboolean ret = true;
    GError *error = NULL;
    char *newcommand = NULL;

    char *command = g_strdup(GET_CHAR("download-external-command"));
    WebKitNetworkRequest *request = webkit_download_get_network_request(download);
    const char *referer = soup_get_header_from_request(request, "Referer");
    const char *user_agent = soup_get_header_from_request(request, "User-Agent");

    char *proxy = GET_CHAR("proxy-url");
    gboolean has_proxy = GET_BOOL("proxy");

    char **envp = g_get_environ();
    envp = g_environ_setenv(envp, "DWB_URI", uri, true);
    envp = g_environ_setenv(envp, "DWB_FILENAME", filename, true);
    envp = g_environ_setenv(envp, "DWB_COOKIES", dwb.files[FILES_COOKIES], true);

    if ( (newcommand = util_string_replace(command, "dwb_uri", uri)) ) 
    {
        g_free(command);
        command = newcommand;
    }
    if ( (newcommand = util_string_replace(command, "dwb_cookies", dwb.files[FILES_COOKIES])) ) 
    {
        g_free(command);
        command = newcommand;
    }
    if ( (newcommand = util_string_replace(command, "dwb_output", filename)) ) 
    {
        g_free(command);
        command = newcommand;
    }
    if (referer != NULL) 
    {
        envp = g_environ_setenv(envp, "DWB_REFERER", referer, true);
    }
    if ( (newcommand = util_string_replace(command, "dwb_referer", referer == NULL ? "" : referer)) ) 
    {
        g_free(command);
        command = newcommand;
    }
    if ( (newcommand = util_string_replace(command, "dwb_proxy", proxy == NULL && has_proxy ? "" : proxy)) ) 
    {
        g_free(command);
        command = newcommand;
    }
    if (user_agent != NULL) 
        envp = g_environ_setenv(envp, "DWB_USER_AGENT", user_agent, true);

    if (dwb.state.mimetype_request)
        envp = g_environ_setenv(envp, "DWB_MIME_TYPE", dwb.state.mimetype_request, true);
    if (proxy != NULL && has_proxy) 
        envp = g_environ_setenv(envp, "DWB_PROXY", proxy, true);
    

    g_shell_parse_argv(command, &argc, &argv, NULL);
    g_free(command);
    if (!g_spawn_async(NULL, argv, envp, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &error)) 
    {
        perror(error->message);
        ret = false;
    }
    g_strfreev(argv);
    g_strfreev(envp);
    return ret;
}
Example #19
0
gint
execute_sync(gchar *cmd, gchar* stdin, gchar** stdout, gchar** stderr) {
  GPid pid;
  gboolean spawned;
  gint exit_status;
  gint stdio[3];
  gint i;

  gchar **env = g_get_environ();
  env = g_environ_setenv(env, "NICE_REMOTE_HOSTNAME", remote_hostname, TRUE);
  gchar** argv;
  gint argc;

  // parse command line to argv array
  if(!g_shell_parse_argv(cmd, &argc, &argv, NULL)) {
    g_critical("Error parsing command line '%s'", cmd);

    exit(1);
  }

  g_debug("Executing '%s'\n", cmd);
  // spawn process
  spawned = g_spawn_async_with_pipes(".", argv, env, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL,
    &pid, &stdio[0], &stdio[1], &stdio[2], NULL);
  g_assert(spawned);

  // write stdin data
  if(stdin)
    write(stdio[0], stdin, strlen(stdin));
  close(stdio[0]);

  // wait for process to finish
  waitpid(pid, &exit_status, 0);
  g_spawn_close_pid(pid);

  gsize max_size = 10240;
  gsize bytes_read;

  // read stdout
  if(stdout) {
    gchar* buf = g_malloc(max_size*sizeof(gchar));

    bytes_read = read(stdio[1], buf, sizeof(gchar)*max_size);
    g_assert(bytes_read != max_size); // let's assume the output won't be larger than max_size-1
    *stdout = g_malloc0(bytes_read);
    memcpy(*stdout, buf, bytes_read);

    g_free(buf);
  }

  // read stderr
  if(stderr) {
    gchar* buf = g_malloc(max_size*sizeof(gchar));

    bytes_read = read(stdio[2], buf, sizeof(gchar)*max_size);
    g_assert(bytes_read != max_size); // let's assume the output won't be larger than max_size-1
    *stderr = g_malloc0(bytes_read);
    memcpy(*stderr, buf, bytes_read);

    g_free(buf);
  }

  close(stdio[1]);
  close(stdio[2]);

  return exit_status;
}
Example #20
0
#endif

    keep_going = TRUE;

    argv = (gchar **) g_malloc0(sizeof(gchar *) * (argc + 2));

#ifdef _WIN32
    /*
     * Make sure executables can find dependent DLLs and that they're *our*
     * DLLs: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682586.aspx
     * Alternatively we could create a simple wrapper exe similar to Create
     * Hidden Process (http://www.commandline.co.uk/chp/).
     */
    dll_search_envp = g_get_environ();
    progfile_dir = g_strdup_printf("%s;%s", get_progfile_dir(), g_environ_getenv(dll_search_envp, "Path"));
    dll_search_envp = g_environ_setenv(dll_search_envp, "Path", progfile_dir, TRUE);
    g_free(progfile_dir);
#endif

    if ((dir = g_dir_open(dirname, 0, NULL)) != NULL) {
        GString *extcap_path = NULL;

        extcap_path = g_string_new("");
        while (keep_going && (file = g_dir_read_name(dir)) != NULL ) {
            gchar *command_output = NULL;
            gboolean status = FALSE;
            gint exit_status = 0;
            GError *error = NULL;
            gchar **envp = NULL;

            /* full path to extcap binary */
Example #21
0
int
main (int argc,
      char **argv)
{
  CockpitTransport *transport;
  gboolean terminated = FALSE;
  gboolean interupted = FALSE;
  gboolean closed = FALSE;
  GError *error = NULL;
  guint sig_term;
  guint sig_int;
  int ret = 0;
  int outfd;

  const gchar *ssh_auth_sock = BUILDDIR "/test-agent.sock";

  int agent = 0;
  gchar *agent_output = NULL;
  gchar *agent_error = NULL;
  gchar *pid_line = NULL;
  gint status = 0;

  const gchar *agent_argv[] = {
      "/usr/bin/ssh-agent",
      "-a", ssh_auth_sock,
      NULL
  };

  signal (SIGPIPE, SIG_IGN);

  g_setenv ("GSETTINGS_BACKEND", "memory", TRUE);
  g_setenv ("GIO_USE_PROXY_RESOLVER", "dummy", TRUE);
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  outfd = dup (1);
  if (outfd < 0 || dup2 (2, 1) < 1)
    {
      g_warning ("bridge couldn't redirect stdout to stderr");
      outfd = 1;
    }

  g_setenv ("SSH_AUTH_SOCK", ssh_auth_sock, TRUE);
  if (!g_spawn_sync (BUILDDIR, (gchar **)agent_argv, NULL,
                G_SPAWN_DEFAULT, NULL, NULL,
                &agent_output, &agent_error,
                &status, &error))
    {
      g_warning ("bridge couldn't spawn agent %s\n", error->message);
      ret = 1;
      goto out;
    }

  if (!g_spawn_check_exit_status (status, &error))
    {
      g_warning ("bridge couldn't spawn agent %s: %s\n", error->message, agent_error);
      ret = 1;
      goto out;
    }

  pid_line = strstr(agent_output, "SSH_AGENT_PID=");
  if (pid_line)
    {
      if (sscanf (pid_line, "SSH_AGENT_PID=%d;", &agent) != 1)
        g_warning ("couldn't find pid in %s", pid_line);
    }

  if (agent < 1)
    {
      g_warning ("couldn't get agent pid: %s", agent_output);
      ret = 1;
      goto out;
    }


  if (argc > 1)
    {
      const gchar *agent_add_argv[] = {
          "/usr/bin/ssh-add", argv[1],
          NULL
      };

      gchar **agent_add_env = g_get_environ ();
      agent_add_env = g_environ_setenv (agent_add_env,
                                        "SSH_AUTH_SOCK",
                                         g_strdup (ssh_auth_sock),
                                         TRUE);

      g_spawn_sync (BUILDDIR, (gchar **)agent_add_argv,
                    agent_add_env, G_SPAWN_DEFAULT,
                    NULL, NULL, NULL, NULL, NULL, &error);

      g_strfreev (agent_add_env);

      if (error)
        {
          g_warning ("couldn't add key %s\n", error->message);
          ret = 1;
          goto out;
        }
    }

  sig_term = g_unix_signal_add (SIGTERM, on_signal_done, &terminated);
  sig_int = g_unix_signal_add (SIGINT, on_signal_done, &interupted);

  g_type_init ();

  transport = cockpit_pipe_transport_new_fds ("stdio", 0, outfd);

  g_signal_connect (transport, "control", G_CALLBACK (on_transport_control), NULL);
  g_signal_connect (transport, "closed", G_CALLBACK (on_closed_set_flag), &closed);

  /* Owns the channels */
  channels = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);

  send_init_command (transport);

  while (!terminated && !closed && !interupted)
    g_main_context_iteration (NULL, TRUE);

  g_object_unref (transport);
  g_hash_table_destroy (channels);

  g_source_remove (sig_term);
  g_source_remove (sig_int);

out:
  g_free (agent_output);
  g_free (agent_error);
  if (error)
    g_error_free (error);

  if (agent)
    kill (agent, SIGTERM);

  /* So the caller gets the right signal */
  if (terminated)
    raise (SIGTERM);

  return ret;
}