Exemple #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;
}
/**
 * terminal_client_append_exec_options:
 * @builder: a #GVariantBuilder of #GVariantType "a{sv}"
 * @working_directory: (allow-none): the cwd, or %NULL
 * @shell:
 *
 * Appends the environment and the working directory to @builder.
 */
void 
terminal_client_append_exec_options (GVariantBuilder *builder,
                                     const char      *working_directory,
                                     gboolean         shell)
{
  gs_strfreev char **envv;

  envv = g_get_environ ();
  envv = g_environ_unsetenv (envv, "COLORTERM");
  envv = g_environ_unsetenv (envv, "COLUMNS");
  envv = g_environ_unsetenv (envv, "DESKTOP_STARTUP_ID");
  envv = g_environ_unsetenv (envv, "DISPLAY");
  envv = g_environ_unsetenv (envv, "GIO_LAUNCHED_DESKTOP_FILE_PID");
  envv = g_environ_unsetenv (envv, "GIO_LAUNCHED_DESKTOP_FILE");
  envv = g_environ_unsetenv (envv, "GNOME_DESKTOP_ICON");
  envv = g_environ_unsetenv (envv, "LINES");
  envv = g_environ_unsetenv (envv, "PWD");
  envv = g_environ_unsetenv (envv, "TERM");
  envv = g_environ_unsetenv (envv, "WINDOWID");

  g_variant_builder_add (builder, "{sv}",
                         "environ",
                         g_variant_new_bytestring_array ((const char * const *) envv, -1));

  if (working_directory)
    g_variant_builder_add (builder, "{sv}", 
                           "cwd", g_variant_new_bytestring (working_directory));

  if (shell)
    g_variant_builder_add (builder, "{sv}",
                           "shell",
                           g_variant_new_boolean (TRUE));
}
Exemple #3
0
gchar const * const desktop_from_env ()
{
   gchar const * admin = NULL;

    gchar ** env = g_get_environ ();

    gchar const * const current = g_environ_getenv (env, "XDG_CURRENT_DESKTOP");

    g_assert (current != NULL);

    if (! g_strcmp0 (current, "MATE"))
    {
        admin = admin_list (MATE)->name;
    } 
    else if (! g_strcmp0 (current, "XFCE"))
    {
        admin = admin_list (XFCE)->name;
    }
    else if (! g_strcmp0 (current, "GNOME"))
    {
        admin = admin_list (GNOME)->name;
    }
    else 
    {
        admin = admin_list (UKNOWN)->name;
    }

    g_strfreev (env);

    g_assert (admin != NULL);

    return admin;
}
Exemple #4
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;
}
Exemple #5
0
/**
 * g_app_launch_context_unsetenv:
 * @context: a #GAppLaunchContext
 * @variable: the environment variable to remove
 *
 * Arranges for @variable to be unset in the child's environment
 * when @context is used to launch an application.
 *
 * Since: 2.32
 */
void
g_app_launch_context_unsetenv (GAppLaunchContext *context,
                               const char        *variable)
{
  if (!context->priv->envp)
    context->priv->envp = g_get_environ ();

  context->priv->envp =
    g_environ_unsetenv (context->priv->envp, variable);
}
Exemple #6
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;
}
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;
    }
}
static void
g_application_command_line_constructed (GObject *object)
{
    GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);

    if (IS_REMOTE (cmdline))
        return;

    /* In the local case, set cmd and environ */
    if (!cmdline->priv->cwd)
        cmdline->priv->cwd = g_get_current_dir ();

    if (!cmdline->priv->environ)
        cmdline->priv->environ = g_get_environ ();
}
Exemple #9
0
static int
env_mode (int argc, char **argv)
{
  char **env;
  int i;

  env = g_get_environ ();

  for (i = 0; env[i]; i++)
    g_print ("%s\n", env[i]);

  g_strfreev (env);

  return 0;
}
Exemple #10
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;
}
Exemple #11
0
int
main (G_GNUC_UNUSED int argc, G_GNUC_UNUSED char **argv)
{
	int number_failed = 0;
	gchar **env;
	const gchar *cnc_string;
	GError *error = NULL;

	env = g_get_environ ();
	cnc_string = g_environ_getenv (env, "MYSQL_CNC_PARAMS");
	if (cnc_string == NULL) {
		g_message ("No enviroment variable MYSQL_CNC_PARAMS was set. No PostgreSQL provider tests will be performed."
		          "Set this environment variable in order to get access to your server. Example: export MYSQL_CNC_PARAMS=\"DB_NAME=$MYSQL_DB;HOST=$MYSQL_HOST;USERNAME=$MYSQL_USER;PASSWORD=$MYSQL_PASSWORD\"");
		g_strfreev (env);
		return EXIT_SUCCESS;
	}

	gda_init ();

	pinfo = gda_config_get_provider_info (PROVIDER);
	if (!pinfo) {
		g_warning ("Could not find provider information for %s", PROVIDER);
		return EXIT_SUCCESS;
	}
	g_print ("Provider now tested: %s\n", pinfo->id);

	cnc = gda_connection_open_from_string (pinfo->id, cnc_string, NULL, GDA_CONNECTION_OPTIONS_NONE, &error);
	if (cnc == NULL) {
		g_warning ("Error opening connection: %s",
			         error && error->message ? error->message : "No error was set");
		return EXIT_FAILURE;
	}
	if (cnc) {
		number_failed += prov_test_common_check_timestamp ();
		number_failed += prov_test_common_check_meta_full ();
		number_failed += prov_test_common_check_meta_partial ();
		number_failed += prov_test_common_check_meta_partial2 ();
		number_failed += prov_test_common_check_meta_partial3 ();
		number_failed += prov_test_common_clean ();
	}

	if (! params_provided)
		return EXIT_SUCCESS;
	else {
		g_print ("Test %s\n", (number_failed == 0) ? "Ok" : "failed");
		return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
	}
}
static IdeSubprocessLauncher *
ide_runtime_real_create_launcher (IdeRuntime  *self,
                                  GError     **error)
{
  IdeSubprocessLauncher *ret;
  g_auto(GStrv) env = NULL;

  g_assert (IDE_IS_RUNTIME (self));

  env = g_get_environ ();

  ret = ide_subprocess_launcher_new (G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_PIPE);
  ide_subprocess_launcher_set_environ (ret, (const gchar * const *)env);

  return ret;
}
Exemple #13
0
void playing_env_dump( void )
{
    gchar **envp = g_listenv();
    size_t i = 0;
    while( envp[i] != NULL )
    {
        printf( "g_listenv[%2zu]  %s => %s\n", i, envp[i], g_getenv( envp[i] ) );
        i++;
    }
    envp = g_get_environ();
    i = 0;
    while( envp[i] != NULL )
    {
        printf( "g_get_environ[%zu] = %s\n", i, envp[i] );
        i++;
    }
}
Exemple #14
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;
}
Exemple #15
0
static void
setup_child()
{
    /* io需要在降权之前设置,因为需要打开一个输出文件 */
    setup_io();

    /* 关闭所有继承的附加组id, 设置有gid,uid */
    if (setgroups(0, NULL) != 0 ||
            setresgid(pwd->pw_gid, pwd->pw_gid, pwd->pw_gid) != 0 ||
            setresuid(pwd->pw_uid, pwd->pw_uid, pwd->pw_uid) != 0)
        exit(0);

    chdir(workdir);
    /*
    g_slist_foreach(resource_rule, foreach_resource, NULL);
    g_slist_foreach(environ_rule, foreach_environ, &env);
    */
    setup_resource();
    ptrace(PTRACE_TRACEME, 0, NULL, NULL);

    execvpe(command[0], command, (char * const *)g_get_environ());
    exit(1);
}
static void
gbp_gcc_toolchain_provider_search_init (GbpGccToolchainProvider *self,
                                        GCancellable            *cancellable,
                                        GAsyncReadyCallback      callback,
                                        gpointer                 user_data)
{
  g_autoptr(IdeTask) task = NULL;
  g_auto(GStrv) environ_ = NULL;
  g_auto(GStrv) paths = NULL;
  const gchar *path_env;
  FileSearching *fs;
  GList *folders = NULL;

  g_assert (GBP_IS_GCC_TOOLCHAIN_PROVIDER (self));

  environ_ = g_get_environ ();
  path_env = g_environ_getenv (environ_, "PATH");
  paths = g_strsplit (path_env, ":", -1);
  for (guint i = 0; paths[i] != NULL; i++)
    folders = g_list_append (folders, g_file_new_for_path (paths[i]));

  task = ide_task_new (self, cancellable, callback, user_data);
  ide_task_set_source_tag (task, gbp_gcc_toolchain_provider_search_init);
  ide_task_set_priority (task, G_PRIORITY_LOW);

  fs = g_slice_new0 (FileSearching);
  fs->found_files = g_ptr_array_new_with_free_func (g_object_unref);
  fs->folders = g_steal_pointer (&folders);
  ide_task_set_task_data (task, fs, file_searching_free);

  /* GCC */
  ide_g_file_find_async (fs->folders->data,
                         "*-gcc",
                         cancellable,
                         gbp_gcc_toolchain_provider_search_iterate,
                         g_steal_pointer (&task));
}
int
main (G_GNUC_UNUSED int argc, G_GNUC_UNUSED char **argv)
{
	int number_failed = 0;
	fork_tests = FALSE;
	gchar **env;
	const gchar *cnc_string;

	env = g_get_environ ();
	cnc_string = g_environ_getenv (env, "POSTGRESQL_DBCREATE_PARAMS");
	if (cnc_string == NULL) {
		g_message ("No enviroment variable POSTGRESQL_DBCREATE_PARAMS was set. No PostgreSQL provider tests will be performed."
		          "Set this environment variable in order to get access to your server. Example: export POSTGRESQL_DBCREATE_PARAMS=\"HOST=postgres;ADM_LOGIN=$POSTGRES_USER;ADM_PASSWORD=$POSTGRES_PASSWORD\"");
		g_strfreev (env);
		return EXIT_SUCCESS;
	}

	gda_init ();

	pinfo = gda_config_get_provider_info (PROVIDER);
	if (!pinfo) {
		g_warning ("Could not find provider information for %s", PROVIDER);
		return EXIT_SUCCESS;
	}
	g_print ("============= Provider Meta Partial 1 Update now testing: %s =============\n", pinfo->id);

	number_failed = prov_test_common_setup ();

	if (cnc) {
		number_failed += prov_test_common_check_meta_partial ();
		number_failed += prov_test_common_clean ();
	}

	g_print ("Test %s\n", (number_failed == 0) ? "Ok" : "failed");
	return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
/* Returns the fd to write in the subprocess stdin or -1 on error */
static gint
start_decoder (gchar *audio_socket_path,
               gchar *video_socket_path,
               GError **error)
{
    gint subprocess_stdin;
    char **env;
    char *args[] = {
        SANDBOXME_PATH,
        "-P",
        "-u1",
        "--",
        DECODER_PATH,
        video_socket_path,
        audio_socket_path,
        NULL
    };

    env = g_get_environ ();
    if (!g_spawn_async_with_pipes (NULL, /* working_directory */
                                   args,
                                   env,
                                   0, /* flags */
                                   NULL, /* child_setup */
                                   NULL, /* user_data */
                                   NULL, /* child pid */
                                   &subprocess_stdin,
                                   NULL, /* standard_output */
                                   NULL, /* standard_error */
                                   error)) {
        subprocess_stdin = -1;
    }
    g_strfreev (env);

    return subprocess_stdin;
}
Exemple #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;
}
Exemple #20
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;
}
Exemple #21
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);
}
Exemple #22
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;
}
Exemple #23
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");
        }
    }
Exemple #24
0
static void
name_lost_cb (GDBusConnection *connection,
              const char *name,
              gpointer user_data)
{
	OwnData *data = (OwnData *) user_data;
	GError *error = NULL;
	char **envv;
	int i;
	GVariantBuilder builder;
	GVariant *value;
	GString *string;
	char *s;
	gsize len;

	_terminal_debug_print (TERMINAL_DEBUG_FACTORY,
	                       "Lost the name %s on the session bus\n", name);

	/* Couldn't get the connection? No way to continue! */
	if (connection == NULL)
	{
		data->exit_code = EXIT_FAILURE;
		gtk_main_quit ();
		return;
	}

	if (data->options == NULL)
	{
		/* Already handled */
		data->exit_code = EXIT_SUCCESS;
		gtk_main_quit ();
		return;
	}

	_terminal_debug_print (TERMINAL_DEBUG_FACTORY,
	                       "Forwarding arguments to existing instance\n");

    g_variant_builder_init (&builder, G_VARIANT_TYPE ("(ayayayayiay)"));
    
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->default_working_dir));
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->display_name));
	g_variant_builder_add (&builder, "@ay", string_to_ay (data->options->startup_id));

	string = g_string_new (NULL);
	envv = g_get_environ ();
	for (i = 0; envv[i]; ++i)
	{
		if (i > 0)
			g_string_append_c (string, '\0');

		g_string_append (string, envv[i]);
	}
	g_strfreev (envv);

	len = string->len;
	s = g_string_free (string, FALSE);
	g_variant_builder_add (&builder, "@ay",
	                       g_variant_new_from_data (G_VARIANT_TYPE ("ay"), s, len, TRUE, g_free, s));

    g_variant_builder_add (&builder, "@i", g_variant_new_int32 (data->options->initial_workspace));

	string = g_string_new (NULL);

	for (i = 0; i < data->argc; ++i)
	{
		if (i > 0)
			g_string_append_c (string, '\0');
		g_string_append (string, data->argv[i]);
	}

	len = string->len;
	s = g_string_free (string, FALSE);
	g_variant_builder_add (&builder, "@ay",
	                       g_variant_new_from_data (G_VARIANT_TYPE ("ay"), s, len, TRUE, g_free, s));

	value = g_dbus_connection_call_sync (connection,
	                                     data->factory_name,
	                                     TERMINAL_FACTORY_SERVICE_PATH,
	                                     TERMINAL_FACTORY_INTERFACE_NAME,
	                                     "HandleArguments",
	                                     g_variant_builder_end (&builder),
	                                     G_VARIANT_TYPE ("()"),
	                                     G_DBUS_CALL_FLAGS_NONE,
	                                     -1,
	                                     NULL,
	                                     &error);
	if (value == NULL)
	{
		g_printerr ("Failed to forward arguments: %s\n", error->message);
		g_error_free (error);
		data->exit_code = EXIT_FAILURE;
		gtk_main_quit ();
	}
	else
	{
		g_variant_unref (value);
		data->exit_code = EXIT_SUCCESS;
	}

	terminal_options_free (data->options);
	data->options = NULL;

	gtk_main_quit ();
}
/* 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;
}
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;
}
Exemple #27
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;
}
Exemple #28
0
    gchar **dll_search_envp;
    gchar *progfile_dir;
#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;
Exemple #29
0
gint shadow_main(gint argc, gchar* argv[]) {
    /* check the compiled GLib version */
    if (!GLIB_CHECK_VERSION(2, 32, 0)) {
        g_printerr("** GLib version 2.32.0 or above is required but Shadow was compiled against version %u.%u.%u\n",
            (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
        return -1;
    }

    if(GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION == 40) {
        g_printerr("** You compiled against GLib version %u.%u.%u, which has bugs known to break Shadow. Please update to a newer version of GLib.\n",
                    (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION);
        return -1;
    }

    /* check the that run-time GLib matches the compiled version */
    const gchar* mismatch = glib_check_version(GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
    if(mismatch) {
        g_printerr("** The version of the run-time GLib library (%u.%u.%u) is not compatible with the version against which Shadow was compiled (%u.%u.%u). GLib message: '%s'\n",
        glib_major_version, glib_minor_version, glib_micro_version,
        (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
        mismatch);
        return -1;
    }

    /* setup configuration - this fails and aborts if invalid */
    gchar* cmds = g_strjoinv(" ", argv);
    gchar** cmdv = g_strsplit(cmds, " ", 0);
    Configuration* config = configuration_new(argc, cmdv);
    g_free(cmds);
    g_strfreev(cmdv);
    if(!config) {
        /* incorrect options given */
        return -1;
    } else if(config->printSoftwareVersion) {
        g_printerr("%s running GLib v%u.%u.%u and IGraph v%s\n%s\n",
                SHADOW_VERSION_STRING,
                (guint)GLIB_MAJOR_VERSION, (guint)GLIB_MINOR_VERSION, (guint)GLIB_MICRO_VERSION,
#if defined(IGRAPH_VERSION)
                IGRAPH_VERSION,
#else
                "(n/a)",
#endif
                SHADOW_INFO_STRING);
        configuration_free(config);
        return 0;
    }

    /* check environment for LD_PRELOAD */
    gchar** envlist = g_get_environ();
    gboolean preloadSuccess = _main_checkPreloadEnvironment(envlist);
    g_strfreev(envlist);
    gboolean respawned = g_getenv("SHADOW_SPAWNED") != NULL ? TRUE : FALSE;

    if(respawned) {
        /* if shadow already respawned once and LD_PRELOAD still isnt correct,
         * then the user will need to provide the correct path */
        if(!preloadSuccess) {
            g_printerr("** Environment Check Failed: LD_PRELOAD does not contain an absolute path to "INTERPOSELIBSTR"\n");
            return -1;
        }
        /* NOTE: we ignore valgrind and preload options during the respawn */
    } else {
        /* if preload is not set, or the user added a preload library,
         * or we are going to run valgrind, we need to respawn */
        if(config->preloads || config->runValgrind || !preloadSuccess) {
            gchar** envlist = _main_getSpawnEnviroment(config->preloads, config->runValgrind);
            gchar* cmds = g_strjoinv(" ", argv);
            gchar** cmdv = g_strsplit(cmds, " ", 0);
            GError* error = NULL;
            gint exitStatus = 0;

            gboolean spawnSuccess = config->runValgrind ?
                    _main_spawnShadowWithValgrind(cmdv, envlist, &exitStatus, &error) :
                    _main_spawnShadow(cmdv, envlist, &exitStatus, &error);

            g_free(cmds);
            g_strfreev(cmdv);
            g_strfreev(envlist);

            if(!spawnSuccess) {
                g_printerr("** Error %i while re-spawning shadow process: %s\n", error->code, error->message);
                return -1;
            }

            /* child was run */
            return (exitStatus == 0) ? 0 : -1;
        }
    }

    utility_assert(preloadSuccess);

    /* tell the preaload lib we are ready for action */
    extern void interposer_setShadowIsLoaded();
    interposer_setShadowIsLoaded();

    /* allocate and initialize our main simulation driver */
    gint returnCode = 0;
    shadowMaster = master_new(config);
    if(shadowMaster) {
        /* run the simulation */
        returnCode = master_run(shadowMaster);
        /* cleanup */
        master_free(shadowMaster);
        shadowMaster = NULL;
    }

    configuration_free(config);
    g_printerr("** shadow returning code %i (%s)\n", returnCode, (returnCode == 0) ? "success" : "error");
    return returnCode;
}
Exemple #30
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);
}