/**
 * Load the session from the specified filename.
 *
 * @param ctx The context in which to load the session.
 * @param filename The name of the session file to load.
 * @param session The session to load the file into.
 *
 * @retval SR_OK Success
 * @retval SR_ERR_MALLOC Memory allocation error
 * @retval SR_ERR_DATA Malformed session file
 * @retval SR_ERR This is not a session file
 */
SR_API int sr_session_load(struct sr_context *ctx, const char *filename,
		struct sr_session **session)
{
	GKeyFile *kf;
	GPtrArray *capturefiles;
	struct zip *archive;
	struct zip_file *zf;
	struct zip_stat zs;
	struct sr_dev_inst *sdi;
	struct sr_channel *ch;
	int ret, i, j;
	uint64_t tmp_u64, total_channels, p;
	char **sections, **keys, *metafile, *val;
	char channelname[SR_MAX_CHANNELNAME_LEN + 1];

	if ((ret = sr_sessionfile_check(filename)) != SR_OK)
		return ret;

	if (!(archive = zip_open(filename, 0, &ret)))
		return SR_ERR;

	if (zip_stat(archive, "metadata", 0, &zs) == -1)
		return SR_ERR;

	if (!(metafile = g_try_malloc(zs.size))) {
		sr_err("%s: metafile malloc failed", __func__);
		return SR_ERR_MALLOC;
	}

	zf = zip_fopen_index(archive, zs.index, 0);
	zip_fread(zf, metafile, zs.size);
	zip_fclose(zf);

	kf = g_key_file_new();
	if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, NULL)) {
		sr_dbg("Failed to parse metadata.");
		return SR_ERR;
	}

	if ((ret = sr_session_new(ctx, session)) != SR_OK)
		return ret;

	ret = SR_OK;
	capturefiles = g_ptr_array_new_with_free_func(g_free);
	sections = g_key_file_get_groups(kf, NULL);
	for (i = 0; sections[i] && ret == SR_OK; i++) {
		if (!strcmp(sections[i], "global"))
			/* nothing really interesting in here yet */
			continue;
		if (!strncmp(sections[i], "device ", 7)) {
			/* device section */
			sdi = NULL;
			keys = g_key_file_get_keys(kf, sections[i], NULL, NULL);
			for (j = 0; keys[j]; j++) {
				val = g_key_file_get_string(kf, sections[i], keys[j], NULL);
				if (!strcmp(keys[j], "capturefile")) {
					sdi = g_malloc0(sizeof(struct sr_dev_inst));
					sdi->driver = &session_driver;
					sdi->status = SR_ST_ACTIVE;
					if (!session_driver_initialized) {
						/* first device, init the driver */
						session_driver_initialized = 1;
						sdi->driver->init(sdi->driver, NULL);
					}
					sr_dev_open(sdi);
					sr_session_dev_add(*session, sdi);
					(*session)->owned_devs = g_slist_append(
							(*session)->owned_devs, sdi);
					sdi->driver->config_set(SR_CONF_SESSIONFILE,
							g_variant_new_string(filename), sdi, NULL);
					sdi->driver->config_set(SR_CONF_CAPTUREFILE,
							g_variant_new_string(val), sdi, NULL);
					g_ptr_array_add(capturefiles, val);
				} else if (!strcmp(keys[j], "samplerate")) {
					if (!sdi) {
						ret = SR_ERR_DATA;
						break;
					}
					sr_parse_sizestring(val, &tmp_u64);
					sdi->driver->config_set(SR_CONF_SAMPLERATE,
							g_variant_new_uint64(tmp_u64), sdi, NULL);
				} else if (!strcmp(keys[j], "unitsize")) {
					if (!sdi) {
						ret = SR_ERR_DATA;
						break;
					}
					tmp_u64 = strtoull(val, NULL, 10);
					sdi->driver->config_set(SR_CONF_CAPTURE_UNITSIZE,
							g_variant_new_uint64(tmp_u64), sdi, NULL);
				} else if (!strcmp(keys[j], "total probes")) {
					if (!sdi) {
						ret = SR_ERR_DATA;
						break;
					}
					total_channels = strtoull(val, NULL, 10);
					sdi->driver->config_set(SR_CONF_NUM_LOGIC_CHANNELS,
							g_variant_new_uint64(total_channels), sdi, NULL);
					for (p = 0; p < total_channels; p++) {
						snprintf(channelname, SR_MAX_CHANNELNAME_LEN, "%" PRIu64, p);
						sr_channel_new(sdi, p, SR_CHANNEL_LOGIC, FALSE,
								channelname);
					}
				} else if (!strncmp(keys[j], "probe", 5)) {
					if (!sdi) {
						ret = SR_ERR_DATA;
						break;
					}
					tmp_u64 = strtoul(keys[j]+5, NULL, 10) - 1;
					ch = g_slist_nth_data(sdi->channels, tmp_u64);
					/* sr_session_save() */
					sr_dev_channel_name_set(ch, val);
					sr_dev_channel_enable(ch, TRUE);
				}
			}
			g_strfreev(keys);
		}
	}
	g_strfreev(sections);
	g_key_file_free(kf);

	return ret;
}
Exemple #2
0
void
test_key_names (void)
{
  GError *error = NULL;
  const gchar *data;

  /* [ in key name */
  data = "[a]\n"
         "key[=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* empty key name */
  data = "[a]\n"
         " =123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* empty key name */
  data = "[a]\n"
         " [de] =123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* bad locale suffix */
  data = "[a]\n"
         "foo[@#!&%]=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* initial space */
  data = "[a]\n"
         " foo=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  check_no_error (error);
  check_string_value (keyfile, "a", "foo", "123");
  g_key_file_free (keyfile);  

  /* final space */
  data = "[a]\n"
         "foo =123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  check_no_error (error);
  check_string_value (keyfile, "a", "foo", "123");
  g_key_file_free (keyfile);  

  /* inner space */
  data = "[a]\n"
         "foo bar=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  check_no_error (error);
  check_string_value (keyfile, "a", "foo bar", "123");
  g_key_file_free (keyfile);  

  /* inner space */
  data = "[a]\n"
         "foo [de] =123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);
  g_key_file_free (keyfile);  

  /* control char in key name */
  data = "[a]\n"
         "key\tfoo=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_no_error (error);

  /* Unicode in key name */
  data = "[a]\n"
         "\xc2\xbd=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_no_error (error); 

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a", "x", "123");
  g_key_file_set_string (keyfile, "a", "key=", "123");
  g_key_file_get_string (keyfile, "a", "key=", &error);
  check_error (&error, 
               G_KEY_FILE_ERROR,
               G_KEY_FILE_ERROR_KEY_NOT_FOUND);  
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a", "x", "123");
  g_key_file_set_string (keyfile, "a", "key[", "123");
  g_key_file_get_string (keyfile, "a", "key[", &error);
  check_error (&error, 
               G_KEY_FILE_ERROR,
               G_KEY_FILE_ERROR_KEY_NOT_FOUND);  
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a", "x", "123");
  g_key_file_set_string (keyfile, "a", "key\tfoo", "123");
  g_key_file_get_string (keyfile, "a", "key\tfoo", &error);
  check_no_error (error);
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a", "x", "123");
  g_key_file_set_string (keyfile, "a", " key", "123");
  g_key_file_get_string (keyfile, "a", " key", &error);
  check_error (&error, 
               G_KEY_FILE_ERROR,
               G_KEY_FILE_ERROR_KEY_NOT_FOUND);  
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a", "x", "123");

  /* Unicode key */
  g_key_file_set_string (keyfile, "a", "\xc2\xbd", "123");
  check_string_value (keyfile, "a", "\xc2\xbd", "123");

  /* Keys with / + . (as used by the gnome-vfs mime cache) */
  g_key_file_set_string (keyfile, "a", "foo/bar", "/");
  check_string_value (keyfile, "a", "foo/bar", "/");
  g_key_file_set_string (keyfile, "a", "foo+bar", "+");
  check_string_value (keyfile, "a", "foo+bar", "+");
  g_key_file_set_string (keyfile, "a", "foo.bar", ".");
  check_string_value (keyfile, "a", "foo.bar", ".");

  g_key_file_free (keyfile);  
  keyfile = NULL;
}
Exemple #3
0
static int zip_append(const struct sr_output *o, unsigned char *buf,
		int unitsize, int length)
{
	struct out_context *outc;
	struct zip *archive;
	struct zip_source *logicsrc;
	zip_int64_t num_files;
	struct zip_file *zf;
	struct zip_stat zs;
	struct zip_source *metasrc;
	GKeyFile *kf;
	GError *error;
	gsize len;
	int chunk_num, next_chunk_num, tmpfile, ret, i;
	const char *entry_name;
	char *metafile, tmpname[32], chunkname[16];

	outc = o->priv;
	if (!(archive = zip_open(outc->filename, 0, &ret)))
		return SR_ERR;

	if (zip_stat(archive, "metadata", 0, &zs) == -1)
		return SR_ERR;

	metafile = g_malloc(zs.size);
	zf = zip_fopen_index(archive, zs.index, 0);
	zip_fread(zf, metafile, zs.size);
	zip_fclose(zf);

	/*
	 * If the file was only initialized but doesn't yet have any
	 * data it in, it won't have a unitsize field in metadata yet.
	 */
	error = NULL;
	kf = g_key_file_new();
	if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, &error)) {
		sr_err("Failed to parse metadata: %s.", error->message);
		return SR_ERR;
	}
	g_free(metafile);
	tmpname[0] = '\0';
	if (!g_key_file_has_key(kf, "device 1", "unitsize", &error)) {
		if (error && error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND) {
			sr_err("Failed to check unitsize key: %s", error ? error->message : "?");
			return SR_ERR;
		}
		/* Add unitsize field. */
		g_key_file_set_integer(kf, "device 1", "unitsize", unitsize);
		metafile = g_key_file_to_data(kf, &len, &error);
		strcpy(tmpname, "sigrok-meta-XXXXXX");
		if ((tmpfile = g_mkstemp(tmpname)) == -1)
			return SR_ERR;
		if (write(tmpfile, metafile, len) < 0) {
			sr_dbg("Failed to create new metadata: %s", strerror(errno));
			g_free(metafile);
			unlink(tmpname);
			return SR_ERR;
		}
		close(tmpfile);
		if (!(metasrc = zip_source_file(archive, tmpname, 0, -1))) {
			sr_err("Failed to create zip source for metadata.");
			g_free(metafile);
			unlink(tmpname);
			return SR_ERR;
		}
		if (zip_replace(archive, zs.index, metasrc) == -1) {
			sr_err("Failed to replace metadata file.");
			g_free(metafile);
			unlink(tmpname);
			return SR_ERR;
		}
		g_free(metafile);
	}
	g_key_file_free(kf);

	next_chunk_num = 1;
	num_files = zip_get_num_entries(archive, 0);
	for (i = 0; i < num_files; i++) {
		entry_name = zip_get_name(archive, i, 0);
		if (strncmp(entry_name, "logic-1", 7))
			continue;
		if (strlen(entry_name) == 7) {
			/* This file has no extra chunks, just a single "logic-1".
			 * Rename it to "logic-1-1" * and continue with chunk 2. */
			if (zip_rename(archive, i, "logic-1-1") == -1) {
				sr_err("Failed to rename 'logic-1' to 'logic-1-1'.");
				unlink(tmpname);
				return SR_ERR;
			}
			next_chunk_num = 2;
			break;
		} else if (strlen(entry_name) > 8 && entry_name[7] == '-') {
			chunk_num = strtoull(entry_name + 8, NULL, 10);
			if (chunk_num >= next_chunk_num)
				next_chunk_num = chunk_num + 1;
		}
	}
	snprintf(chunkname, 15, "logic-1-%d", next_chunk_num);
	if (!(logicsrc = zip_source_buffer(archive, buf, length, FALSE))) {
		unlink(tmpname);
		return SR_ERR;
	}
	if (zip_add(archive, chunkname, logicsrc) == -1) {
		unlink(tmpname);
		return SR_ERR;
	}
	if ((ret = zip_close(archive)) == -1) {
		sr_info("error saving session file: %s", zip_strerror(archive));
		unlink(tmpname);
		return SR_ERR;
	}
	unlink(tmpname);

	return SR_OK;
}
Exemple #4
0
/* http://bugzilla.gnome.org/show_bug.cgi?id=420686 */
void
test_reload_idempotency (void)
{
  static const gchar *original_data=""
    "# Top comment\n"
    "\n"
    "# First comment\n"
    "[first]\n"
    "key=value\n"
    "# A random comment in the first group\n"
    "anotherkey=anothervalue\n"
    "# Second comment - one line\n"
    "[second]\n"
    "# Third comment - two lines\n"
    "# Third comment - two lines\n"
    "[third]\n"
    "blank_line=1\n"
    "\n"
    "blank_lines=2\n"
    "\n\n"
    "[fourth]\n"
    "[fifth]\n";
  GError *error = NULL;
  gchar *data1, *data2;
  gsize len1, len2;

  /* check that we only insert a single new line between groups */
  keyfile = g_key_file_new ();
  if (!g_key_file_load_from_data (keyfile,
	                          original_data, strlen(original_data),
	                          G_KEY_FILE_KEEP_COMMENTS,
	                          &error))
    gcut_assert_error (error, cut_message ("Failed to parse keyfile[1]"));

  data1 = g_key_file_to_data (keyfile, &len1, &error);
  if (!data1)
    gcut_assert_error (error, cut_message ("Failed to extract keyfile[1]"));
  g_key_file_free (keyfile);

  keyfile = g_key_file_new ();
  if (!g_key_file_load_from_data (keyfile,
	                          data1, len1,
				  G_KEY_FILE_KEEP_COMMENTS,
				  &error))
    gcut_assert_error (error, cut_message ("Failed to parse keyfile[2]"));

  data2 = g_key_file_to_data (keyfile, &len2, &error);
  if (!data2)
    gcut_assert_error (error, cut_message ("Failed to extract keyfile[2]"));

  g_key_file_free (keyfile);
  keyfile = NULL;

  cut_assert_equal_string (data1, data2,
                           cut_message ("Reloading GKeyFile is not idempotent.\n"
                                        "original:\n"
                                        "%s\n"
                                        "---\n"
                                        "pass1:\n"
                                        "%s\n"
                                        "---\n"
                                        "pass2:\n"
                                        "%s\n"
                                        "---\n",
                                        original_data, data1, data2));

  g_free (data2);
  g_free (data1);
}
Exemple #5
0
/* check parsing of integer and double values */
void
test_number (void)
{
  GError *error = NULL;

  const gchar *data = 
    "[valid]\n"
    "key1=0\n"
    "key2=1\n"
    "key3=-1\n"
    "key4=2324431\n"
    "key5=-2324431\n"
    "key6=000111\n"
    "dkey1=000111\n"
    "dkey2=145.45\n"
    "dkey3=-3453.7\n"
    "[invalid]\n"
    "key1=0xffff\n"
    "key2=0.5\n"
    "key3=1e37\n"
    "key4=ten\n"
    "key5=\n"
    "key6=1.0.0\n"
    "key7=2x2\n"
    "key8=abc\n";
  
  cut_assert (g_key_file_load_from_data (keyfile, data, -1, 0, NULL));

  check_integer_value (keyfile, "valid", "key1", 0);
  check_integer_value (keyfile, "valid", "key2", 1);
  check_integer_value (keyfile, "valid", "key3", -1);
  check_integer_value (keyfile, "valid", "key4", 2324431);
  check_integer_value (keyfile, "valid", "key5", -2324431);
  check_integer_value (keyfile, "valid", "key6", 111);
  check_double_value (keyfile, "valid", "dkey1", 111.0);
  check_double_value (keyfile, "valid", "dkey2", 145.45);
  check_double_value (keyfile, "valid", "dkey3", -3453.7);

  g_key_file_get_integer (keyfile, "invalid", "key1", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_integer (keyfile, "invalid", "key2", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_integer (keyfile, "invalid", "key3", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_integer (keyfile, "invalid", "key4", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_double (keyfile, "invalid", "key5", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_double (keyfile, "invalid", "key6", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_double (keyfile, "invalid", "key7", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);

  g_key_file_get_double (keyfile, "invalid", "key8", &error);
  check_error (&error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE);
}
Exemple #6
0
void
configrc_load(struct data *data)
{
    gchar       *dir_uri;
    gchar       *configrc_file;
    guchar      *configrc_data;
    gsize       configrc_data_len;
    GKeyFile    *keyfile;

    g_assert(data != NULL);

    /* check that the proper directories exist */
    dir_uri = g_strdup_printf("file://%s/%s",
                              g_get_home_dir(), PWGALLERY_CONFIGRC_DIR);
    if (vfs_is_dir(data, dir_uri) == FALSE)
        vfs_mkdir(data, dir_uri);
    g_free(dir_uri);

    dir_uri = g_strdup_printf("file://%s/%s/%s",
                              g_get_home_dir(), PWGALLERY_CONFIGRC_DIR,
                              PWGALLERY_DEFAULT_GAL_DIR);
    if (vfs_is_dir(data, dir_uri) == FALSE)
        vfs_mkdir(data, dir_uri);
    g_free(dir_uri);

    dir_uri = g_strdup_printf("file://%s/%s/%s",
                              g_get_home_dir(), PWGALLERY_CONFIGRC_DIR,
                              PWGALLERY_DEFAULT_TEMPL_DIR);
    if (vfs_is_dir(data, dir_uri) == FALSE)
    {
        char *src;
        char *dst;

        /* make template dir */
        vfs_mkdir(data, dir_uri);

        /* copy index template */
        src = g_strdup_printf("%s/%s",
                              PWGALLERY_SYSTEM_TEMPLATE_DIR,
                              PWGALLERY_DEFAULT_TEMPL_INDEX);
        dst = g_strdup_printf("%s/%s",
                              dir_uri, PWGALLERY_DEFAULT_TEMPL_INDEX);
        vfs_copy(data, src, dst);
        g_free(dst);
        g_free(src);

        /* copy index image template */
        src = g_strdup_printf("%s/%s",
                              PWGALLERY_SYSTEM_TEMPLATE_DIR,
                              PWGALLERY_DEFAULT_TEMPL_INDEXIMG);
        dst = g_strdup_printf("%s/%s",
                              dir_uri, PWGALLERY_DEFAULT_TEMPL_INDEXIMG);
        vfs_copy(data, src, dst);
        g_free(dst);
        g_free(src);

        /* copy index generic template */
        src = g_strdup_printf("%s/%s",
                              PWGALLERY_SYSTEM_TEMPLATE_DIR,
                              PWGALLERY_DEFAULT_TEMPL_INDEXGEN);
        dst = g_strdup_printf("%s/%s",
                              dir_uri, PWGALLERY_DEFAULT_TEMPL_INDEXGEN);
        vfs_copy(data, src, dst);
        g_free(dst);
        g_free(src);

        /* copy image template */
        src = g_strdup_printf("%s/%s",
                              PWGALLERY_SYSTEM_TEMPLATE_DIR,
                              PWGALLERY_DEFAULT_TEMPL_IMAGE);
        dst = g_strdup_printf("%s/%s",
                              dir_uri, PWGALLERY_DEFAULT_TEMPL_IMAGE);
        vfs_copy(data, src, dst);
        g_free(dst);
        g_free(src);

        /* copy generic template */
        src = g_strdup_printf("%s/%s",
                              PWGALLERY_SYSTEM_TEMPLATE_DIR,
                              PWGALLERY_DEFAULT_TEMPL_GEN);
        dst = g_strdup_printf("%s/%s",
                              dir_uri, PWGALLERY_DEFAULT_TEMPL_GEN);
        vfs_copy(data, src, dst);
        g_free(dst);
        g_free(src);
    }
    g_free(dir_uri);


    /* construct path for configrc file */
    configrc_file = g_strdup_printf("file://%s/%s/%s", g_get_home_dir(),
                                    PWGALLERY_CONFIGRC_DIR,
                                    PWGALLERY_CONFIGRC_FILE);

    keyfile = g_key_file_new();

    /* Try to load configrc values if the file exists */
    if (vfs_is_file(data, configrc_file) == TRUE)
    {
        gboolean ok;

        /* read values from configrc file */
        vfs_read_file(data, configrc_file, &configrc_data, &configrc_data_len);

        ok = g_key_file_load_from_data(keyfile,
                                       (gchar*)configrc_data, configrc_data_len,
                                       G_KEY_FILE_KEEP_COMMENTS |
                                       G_KEY_FILE_KEEP_TRANSLATIONS ,
                                       NULL);
        g_assert(ok == TRUE);
        g_free(configrc_data);
        configrc_data = NULL;
    }

    /* set defaults for those keys that are missing */
    set_defaults(keyfile);

    /* save configrc file to disk (maybe if didn't exists or maybe new
     * keys are introduced in a new version. ie. just be sure) */
    configrc_data =
        (guchar*)g_key_file_to_data(keyfile, &configrc_data_len, NULL);
    vfs_write_file(data, configrc_file, configrc_data, configrc_data_len);

    set_rc_values(data, keyfile);

    g_free(configrc_data);
    g_free(configrc_file);
    g_key_file_free(keyfile);
}
void report_table(ReportContext * ctx, gchar * text)
{
    GKeyFile *key_file = g_key_file_new();
    gchar **groups;
    gint i;

    g_key_file_load_from_data(key_file, text, strlen(text), 0, NULL);
    groups = g_key_file_get_groups(key_file, NULL);

    for (i = 0; groups[i]; i++) {
        gchar *group, *tmpgroup;
        gchar **keys;
        gint j;

        if (groups[i][0] == '$') {
            report_context_configure(ctx, key_file);
            continue;
        }

        group = groups[i];

        tmpgroup = g_strdup(group);
        strend(group, '#');

        report_subsubtitle(ctx, group);

#if 0
        if (ctx->is_image_enabled) {
            report_embed_image(ctx, key_file, group);
        } else {
#endif
            keys = g_key_file_get_keys(key_file, tmpgroup, NULL, NULL);
            for (j = 0; keys[j]; j++) {
                gchar *key = keys[j];
                gchar *value;

                value =
                    g_key_file_get_value(key_file, tmpgroup, key, NULL);

                if (g_utf8_validate(key, -1, NULL)
                        && g_utf8_validate(value, -1, NULL)) {
                    strend(key, '#');

                    if (g_str_equal(value, "...")) {
                        g_free(value);
                        if (!(value = ctx->entry->fieldfunc(key))) {
                            value = g_strdup("...");
                        }
                    }

                    if (*key == '$') {
                        report_key_value(ctx, strchr(key + 1, '$') + 1,
                                         value);
                    } else {
                        report_key_value(ctx, key, value);
                    }

                }

                g_free(value);
            }

            g_strfreev(keys);
#if 0
        }
#endif
        g_free(tmpgroup);
    }

    g_strfreev(groups);
    g_key_file_free(key_file);
}
static void
load_options (const char *filename,
              GBytes    **gpg_data)
{
  g_autoptr(GError) error = NULL;
  g_autoptr(GKeyFile) keyfile = g_key_file_new ();
  char *str;
  gboolean nodeps;
  g_autoptr(GBytes) bytes = NULL;
  g_autofree char *version = NULL;

  if (g_str_has_prefix (filename, "http:") ||
      g_str_has_prefix (filename, "https:"))
    {
      const char *options_data;
      gsize options_size;
      g_autoptr(SoupSession) soup_session = NULL;

      soup_session = flatpak_create_soup_session (PACKAGE_STRING);
      bytes = flatpak_load_http_uri (soup_session, filename, 0, NULL, NULL, NULL, &error);

      if (bytes == NULL)
        {
          g_printerr (_("Can't load uri %s: %s\n"), filename, error->message);
          exit (1);
        }

      options_data = g_bytes_get_data (bytes, &options_size);
      if (!g_key_file_load_from_data (keyfile, options_data, options_size, 0, &error))
        {
          g_printerr (_("Can't load uri %s: %s\n"), filename, error->message);
          exit (1);
        }
    }
  else
    {
      if (!g_key_file_load_from_file (keyfile, filename, 0, &error))
        {
          g_printerr (_("Can't load file %s: %s\n"), filename, error->message);
          exit (1);
        }
    }


  if (!g_key_file_has_group (keyfile, FLATPAK_REPO_GROUP))
    {
      g_printerr (_("Invalid file format"));
      exit (1);
    }

  version = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                                   FLATPAK_REPO_VERSION_KEY, NULL);
  if (version != NULL && strcmp (version, "1") != 0)
    {
      g_printerr (_("Invalid version %s, only 1 supported"), version);
      exit (1);
    }

  str = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                               FLATPAK_REPO_URL_KEY, NULL);
  if (str != NULL)
    opt_url = str;

  str = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP, FLATPAK_REPO_DEPLOY_COLLECTION_ID_KEY, NULL);
  if (str != NULL && *str != '\0')
    opt_collection_id = str;
  else
    {
      str = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP, FLATPAK_REPO_COLLECTION_ID_KEY, NULL);
      if (str != NULL && *str != '\0')
        opt_collection_id = str;
    }

  str = g_key_file_get_locale_string (keyfile, FLATPAK_REPO_GROUP,
                                      FLATPAK_REPO_TITLE_KEY, NULL, NULL);
  if (str != NULL)
    opt_title = str;

  str = g_key_file_get_locale_string (keyfile, FLATPAK_REPO_GROUP,
                                      FLATPAK_REPO_DEFAULT_BRANCH_KEY, NULL, NULL);
  if (str != NULL)
    opt_default_branch = str;

  nodeps = g_key_file_get_boolean (keyfile, FLATPAK_REPO_GROUP,
                                   FLATPAK_REPO_NODEPS_KEY, NULL);
  if (nodeps)
    {
      opt_no_deps = TRUE;
      opt_do_deps = FALSE;
    }

  str = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                               FLATPAK_REPO_GPGKEY_KEY, NULL);
  if (str != NULL)
    {
      guchar *decoded;
      gsize decoded_len;

      str = g_strstrip (str);
      decoded = g_base64_decode (str, &decoded_len);
      if (decoded_len < 10) /* Check some minimal size so we don't get crap */
        {
          g_printerr (_("Invalid gpg key"));
          exit (1);
        }

      *gpg_data = g_bytes_new_take (decoded, decoded_len);
      if (!opt_no_gpg_verify)
        opt_do_gpg_verify = TRUE;
    }

  comment = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                                   FLATPAK_REPO_COMMENT_KEY, NULL);

  description = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                                       FLATPAK_REPO_DESCRIPTION_KEY, NULL);

  icon = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                                FLATPAK_REPO_ICON_KEY, NULL);

  homepage  = g_key_file_get_string (keyfile, FLATPAK_REPO_GROUP,
                                     FLATPAK_REPO_HOMEPAGE_KEY, NULL);
}
gboolean
open_file_with_filemanager (GtkWidget * window,
                            const gchar * file)
{
	GDesktopAppInfo * d_app_info;
	GKeyFile * key_file;
	GdkAppLaunchContext * ctx = NULL;
	GList * list = NULL;
	GAppInfo * g_app_info;
	GFile * g_file;
	gchar * command;
	gchar * contents;
	gchar * uri;
	gboolean result = TRUE;

	uri = g_filename_to_uri (file, NULL, NULL);
	list = g_list_prepend (list, uri);

	g_file = g_file_new_for_path (file);
	g_app_info = g_file_query_default_handler (g_file, NULL, NULL);

	if (strcmp (g_app_info_get_executable (g_app_info), "nautilus") == 0) {
		command = g_strconcat ("nautilus ",
		                       "--sm-disable ",
		                       "--no-desktop ",
		                       "--no-default-window ",
		                       NULL);
	}
	else {
		command = g_strconcat (g_app_info_get_executable (g_app_info),
		                       " ", NULL);
	}

	contents = g_strdup_printf ("[Desktop Entry]\n"
				    "Name=Nautilus\n"
				    "Icon=file-manager\n"
				    "Exec=%s\n"
				    "Terminal=false\n"
				    "StartupNotify=true\n"
				    "Type=Application\n",
				    command);
	key_file = g_key_file_new ();
	g_key_file_load_from_data (key_file, contents, strlen(contents), G_KEY_FILE_NONE, NULL);
	d_app_info = g_desktop_app_info_new_from_keyfile (key_file);
	
	if (d_app_info != NULL) {
		ctx = gdk_app_launch_context_new ();
		gdk_app_launch_context_set_screen (ctx, gtk_widget_get_screen (window));

		result = g_app_info_launch_uris (G_APP_INFO (d_app_info), list,  G_APP_LAUNCH_CONTEXT (ctx), NULL);
	}
	else {
		result = FALSE;
	}

	g_object_unref (g_app_info);
	g_object_unref (d_app_info);
	g_object_unref (g_file);
	g_object_unref (ctx);
	g_key_file_free (key_file);
	g_list_free (list);
	g_free (contents);
	g_free (command);
	g_free (uri);

	return result;
}
static gboolean
on_manager_handle_add_account (GoaManager             *manager,
                               GDBusMethodInvocation  *invocation,
                               const gchar            *provider,
                               const gchar            *identity,
                               const gchar            *presentation_identity,
                               GVariant               *details,
                               gpointer                user_data)
{
  GoaDaemon *daemon = GOA_DAEMON (user_data);
  GKeyFile *key_file;
  GError *error;
  gchar *path;
  gchar *id;
  gchar *group;
  gchar *data;
  gsize length;
  gchar *object_path;
  GVariantIter iter;
  const gchar *key;
  const gchar *value;

  /* TODO: could check for @type */

  key_file = NULL;
  path = NULL;
  id = NULL;
  group = NULL;
  data = NULL;
  object_path = NULL;

  key_file = g_key_file_new ();
  path = g_strdup_printf ("%s/goa-1.0/accounts.conf", g_get_user_config_dir ());
  error = NULL;
  if (!g_file_get_contents (path,
                            &data,
                            &length,
                            &error))
    {
      if (error->domain == G_FILE_ERROR && error->code == G_FILE_ERROR_NOENT)
        {
          g_error_free (error);
        }
      else
        {
          g_prefix_error (&error, "Error loading file %s: ", path);
          g_dbus_method_invocation_return_gerror (invocation, error);
          goto out;
        }
    }
  else
    {
      if (length > 0)
        {
          error = NULL;
          if (!g_key_file_load_from_data (key_file, data, length, G_KEY_FILE_KEEP_COMMENTS, &error))
            {
              g_prefix_error (&error, "Error parsing key-value-file %s: ", path);
              g_dbus_method_invocation_return_gerror (invocation, error);
              goto out;
            }
        }
    }

  id = generate_new_id (daemon);
  group = g_strdup_printf ("Account %s", id);
  g_key_file_set_string (key_file, group, "Provider", provider);
  g_key_file_set_string (key_file, group, "Identity", identity);
  g_key_file_set_string (key_file, group, "PresentationIdentity", presentation_identity);

  g_variant_iter_init (&iter, details);
  while (g_variant_iter_next (&iter, "{&s&s}", &key, &value))
    {
      g_key_file_set_string (key_file, group, key, value);
    }

  g_free (data);
  error = NULL;
  data = g_key_file_to_data (key_file,
                             &length,
                             &error);
  if (data == NULL)
    {
      g_prefix_error (&error, "Error generating key-value-file: ");
      g_dbus_method_invocation_return_gerror (invocation, error);
      goto out;
    }

  error = NULL;
  if (!g_file_set_contents (path,
                            data,
                            length,
                            &error))
    {
      g_prefix_error (&error, "Error writing key-value-file %s: ", path);
      g_dbus_method_invocation_return_gerror (invocation, error);
      goto out;
    }

  goa_daemon_reload_configuration (daemon);

  object_path = g_strdup_printf ("/org/gnome/OnlineAccounts/Accounts/%s", id);
  goa_manager_complete_add_account (manager, invocation, object_path);

 out:
  g_free (object_path);
  g_free (data);
  g_free (group);
  g_free (id);
  g_free (path);
  if (key_file != NULL)
    g_key_file_free (key_file);

  return TRUE; /* invocation was handled */
}
Exemple #11
0
static gboolean
net_usershare_run (int argc, char **argv, GKeyFile **ret_key_file, GError **error)
{
	int real_argc;
	int i;
	char **real_argv;
	gboolean retval;
	char *stdout_contents;
	char *stderr_contents;
	int exit_status;
	int exit_code;
	GKeyFile *key_file;
	GError *real_error;

	g_assert (argc > 0);
	g_assert (argv != NULL);
	g_assert (error == NULL || *error == NULL);

	if (ret_key_file)
		*ret_key_file = NULL;

	/* Build command line */

	real_argc = 2 + argc + 1; /* "net" "usershare" [argv] NULL */
	real_argv = g_new (char *, real_argc);

	real_argv[0] = NET_USERSHARE_ARGV0;
	real_argv[1] = "usershare";

	for (i = 0; i < argc; i++) {
		g_assert (argv[i] != NULL);
		real_argv[i + 2] = argv[i];
	}

	real_argv[real_argc - 1] = NULL;

	/* Launch */

	stdout_contents = NULL;
	stderr_contents = NULL;
	/*
	{
		char **p;

		g_message ("------------------------------------------");

		for (p = real_argv; *p; p++)
			g_message ("spawn arg \"%s\"", *p);

		g_message ("end of spawn args; SPAWNING\n");
	}
	*/
	real_error = NULL;
	retval = g_spawn_sync (NULL,			/* cwd */
			       real_argv,
			       NULL, 			/* envp */
			       G_SPAWN_SEARCH_PATH,
			       NULL, 			/* GSpawnChildSetupFunc */
			       NULL,			/* user_data */
			       &stdout_contents,
			       &stderr_contents,
			       &exit_status,
			       &real_error);

	/* g_message ("returned from spawn: %s: %s", retval ? "SUCCESS" : "FAIL", retval ? "" : real_error->message); */

	if (!retval) {
		g_propagate_error (error, real_error);
		goto out;
	}

	if (!WIFEXITED (exit_status)) {
		g_message ("WIFEXITED(%d) was false!", exit_status);
		retval = FALSE;

		if (WIFSIGNALED (exit_status)) {
			int signal_num;

			signal_num = WTERMSIG (exit_status);
			g_message ("Child got signal %d", signal_num);

			g_set_error (error,
				     SHARES_ERROR,
				     SHARES_ERROR_FAILED,
				     _("%s %s %s returned with signal %d"),
				     real_argv[0],
				     real_argv[1],
				     real_argv[2],
				     signal_num);
		} else
			g_set_error (error,
				     SHARES_ERROR,
				     SHARES_ERROR_FAILED,
				     _("%s %s %s failed for an unknown reason"),
				     real_argv[0],
				     real_argv[1],
				     real_argv[2]);

		goto out;
	}

	exit_code = WEXITSTATUS (exit_status);

	/* g_message ("exit code %d", exit_code); */
	if (exit_code != 0) {
		char *str;
		char *message;

		/* stderr_contents is in the system locale encoding, not UTF-8 */

		str = g_locale_to_utf8 (stderr_contents, -1, NULL, NULL, NULL);

		if (str && str[0])
			message = g_strdup_printf (_("'net usershare' returned error %d: %s"), exit_code, str);
		else
			message = g_strdup_printf (_("'net usershare' returned error %d"), exit_code);

		g_free (str);

		g_set_error (error,
			     G_SPAWN_ERROR,
			     G_SPAWN_ERROR_FAILED,
			     "%s",
			     message);

		g_free (message);

		retval = FALSE;
		goto out;
	}

	if (ret_key_file) {
	  /* g_message ("caller wants GKeyFile"); */

		*ret_key_file = NULL;

		/* FIXME: [email protected] says the output of "net usershare" is nearly always
		 * in UTF-8, but that it can be configured in the master smb.conf.  We assume
		 * UTF-8 for now.
		 */

		if (!g_utf8_validate (stdout_contents, -1, NULL)) {
			g_message ("stdout of net usershare was not in valid UTF-8");
			g_set_error (error,
				     G_SPAWN_ERROR,
				     G_SPAWN_ERROR_FAILED,
				     _("the output of 'net usershare' is not in valid UTF-8 encoding"));
			retval = FALSE;
			goto out;
		}

		key_file = g_key_file_new ();

		real_error = NULL;
		if (!g_key_file_load_from_data (key_file, stdout_contents, -1, 0, &real_error)) {
			g_message ("Error when parsing key file {\n%s\n}: %s", stdout_contents, real_error->message);
			g_propagate_error (error, real_error);
			g_key_file_free (key_file);
			retval = FALSE;
			goto out;
		}

		retval = TRUE;
		*ret_key_file = key_file;
	} else
		retval = TRUE;

	/* g_message ("success from calling net usershare and parsing its output"); */

 out:
	g_free (real_argv);
	g_free (stdout_contents);
	g_free (stderr_contents);

	/* g_message ("------------------------------------------"); */

	return retval;
}
/**
 * main:
 * @argc:
 * @argv[]: Sent to gtk_init
 *
 * Prompt for GnuPG and SSH. Communicates using stdin/stdout. Communication data
 * is in ini-file structures
 *
 * Returns: 0
 */
int
main (int argc, char *argv[])
{
	GError *err = NULL;
	gchar *data;
	gboolean ret;
	gsize length;

	/* Exit on HUP signal */
	signal(SIGINT,  hup_handler);

	prepare_logging ();

	egg_libgcrypt_initialize ();

	input_data = g_key_file_new ();
	output_data = g_key_file_new ();

	gtk_init (&argc, &argv);

#ifdef HAVE_LOCALE_H
	/* internationalisation */
	setlocale (LC_ALL, "");
#endif

#ifdef HAVE_GETTEXT
	bindtextdomain (GETTEXT_PACKAGE, MATELOCALEDIR);
	textdomain (GETTEXT_PACKAGE);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

	data = read_all_input ();
	g_assert (data);

	if (!data[0])
		fatal ("no auth dialog instructions", NULL);

	ret = g_key_file_load_from_data (input_data, data, strlen (data), G_KEY_FILE_NONE, &err);
	g_free (data);

	if (!ret)
		fatal ("couldn't parse auth dialog instructions", egg_error_message (err));

	run_dialog ();

	/* Cleanup after any key */
	if (the_key) {
		egg_secure_clear (the_key, n_the_key);
		egg_secure_free (the_key);
		the_key = NULL;
		n_the_key = 0;
	}

	g_key_file_free (input_data);
	data = g_key_file_to_data (output_data, &length, &err);
	g_key_file_free (output_data);

	if (!data)
		fatal ("couldn't format auth dialog response: %s", egg_error_message (err));

	write_all_output (data, length);
	g_free (data);

	return 0;
}
Exemple #13
0
VinagreConnection *
vinagre_connection_new_from_file (const gchar *uri, gchar **error_msg, gboolean use_bookmarks)
{
  GKeyFile          *file;
  GError            *error;
  gboolean           loaded;
  VinagreConnection *conn;
  gchar             *host, *actual_host, *data;
  gint               port;
  int                file_size;
  GFile             *file_a;

  *error_msg = NULL;
  host = NULL;
  data = NULL;
  conn = NULL;
  error = NULL;
  file = NULL;
  conn = NULL;

  file_a = g_file_new_for_commandline_arg (uri);
  loaded = g_file_load_contents (file_a,
				 NULL,
				 &data,
				 &file_size,
				 NULL,
				 &error);
  if (!loaded)
    {
      if (error)
	{
	  *error_msg = g_strdup (error->message);
	  g_error_free (error);
	}
      else
	*error_msg = g_strdup (_("Could not open the file."));

      goto the_end;
    }

  file = g_key_file_new ();
  loaded = g_key_file_load_from_data (file,
				      data,
				      file_size,
				      0,
				      &error);
  if (!loaded)
    {
      if (error)
	{
	  *error_msg = g_strdup (error->message);
	  g_error_free (error);
	}
      else
	*error_msg = g_strdup (_("Could not parse the file."));

      goto the_end;
    }

  host = g_key_file_get_string (file, "connection", "host", NULL);
  port = g_key_file_get_integer (file, "connection", "port", NULL);
  if (host)
    {
      if (!port)
	{
	  if (!vinagre_connection_split_string (host, &actual_host, &port, error_msg))
	    goto the_end;

	  g_free (host);
	  host = actual_host;
	}

      if (use_bookmarks)
        conn = vinagre_bookmarks_exists (vinagre_bookmarks_get_default (), host, port);
      if (!conn)
	{
	  gchar *username, *password;
	  gint shared;
	  GError *e = NULL;

	  conn = vinagre_connection_new ();
	  vinagre_connection_set_host (conn, host);
	  vinagre_connection_set_port (conn, port);

	  username = g_key_file_get_string  (file, "connection", "username", NULL);
	  vinagre_connection_set_username (conn, username);
	  g_free (username);

	  password = g_key_file_get_string  (file, "connection", "password", NULL);
	  vinagre_connection_set_password (conn, password);
	  g_free (password);

	  shared = g_key_file_get_integer (file, "options", "shared", &e);
	  if (e)
	    g_error_free (e);
	  else
	    if (shared == 0 || shared == 1)
	      vinagre_connection_set_shared (conn, shared);
	    else
	      g_message (_("Bad value for 'shared' flag: %d. It is supposed to be 0 or 1. Ignoring it."), shared);
	}

      g_free (host);
    }
  else
    *error_msg = g_strdup (_("Could not find the host address in the file."));

the_end:
  g_free (data);
  g_object_unref (file_a);
  if (file)
    g_key_file_free (file);

  return conn;
}
Exemple #14
0
static void
lbc_init(LibBalsaConf * conf, const gchar * filename,
         const gchar * old_dir)
{
    struct stat buf;
    GError *error = NULL;
    gint rc;

    if (!conf->path)
        conf->path =
            g_build_filename(g_get_home_dir(), ".balsa", filename, NULL);
    rc = stat(conf->path, &buf);
    if (conf->key_file) {
        if (rc >= 0 && buf.st_mtime <= conf->mtime)
            /* found the config file, and it hasn't been touched since
             * we loaded it */
            return;
    } else {
        conf->key_file = g_key_file_new();
        if (rc < 0)
            /* no config file--must be first time startup */
            return;
    }
    conf->mtime = buf.st_mtime;

    libbalsa_assure_balsa_dir();
    if (!g_key_file_load_from_file
        (conf->key_file, conf->path, G_KEY_FILE_NONE, &error)) {
        gchar *old_path;
        gchar *buf;
        static gboolean warn = TRUE;

        old_path =
            g_build_filename(g_get_home_dir(), old_dir, "balsa", NULL);
#if DEBUG
        g_message("Could not load config from \"%s\":\n %s\n"
                  " trying \"%s\"", conf->path, error->message, old_path);
#endif                          /* DEBUG */
        g_clear_error(&error);

        buf = lbc_readfile(old_path);
        if (buf) {
            /* GnomeConfig used ' ' as the list separator... */
            g_key_file_set_list_separator(conf->key_file, ' ');
            g_key_file_load_from_data(conf->key_file, buf, -1,
                                      G_KEY_FILE_KEEP_COMMENTS, &error);
            g_free(buf);
            /* ...but GKeyFile doesn't handle it properly, so we'll
             * revert to the default ';'. */
            g_key_file_set_list_separator(conf->key_file, ';');
        }
        if (!buf || error) {
#if DEBUG
            g_message("Could not load key file from file \"%s\": %s",
                      old_path,
                      error ? error->message : g_strerror(errno));
#endif                          /* DEBUG */
            g_clear_error(&error);
            warn = FALSE;
        }
        g_free(old_path);
        if (warn)
            libbalsa_information(LIBBALSA_INFORMATION_WARNING,
                                 _("Your Balsa configuration "
                                   "is now stored in "
                                   "\"~/.balsa/config\"."));
    }
}
Exemple #15
0
/* This function updates the connection_c contexts.  */
gboolean
read_connections (tclient_c *tclient)
{
    GKeyFile *keys = 0;
    gint i = 0;
    gchar *buf = 0;
    gint buf_size = 0;

    tclient->connection = 0;

    buf = (gchar *)load_remote_file(tclient, "connections.conf");
    if (!buf)
    {
        start_error_dialog(tclient, __FUNCTION__, "Couldn't read connections\n");
        return FALSE;
    }
    buf_size = strlen(buf);

    /* Parse the keys */
    keys = g_key_file_new();
    if(g_key_file_load_from_data(keys, buf, buf_size, G_KEY_FILE_NONE, NULL))
    {
        gchar **group = 0;
        gsize group_size = 0;

        group = g_key_file_get_groups(keys, &group_size);

        /* Go through the groups and create connections for them */
        for (i = 0; i < group_size; i++)
        {
            connection_c *connection;
            connection = g_malloc0 (sizeof (connection_c));

			/* conf file reads like this
			 * [connection alias]
			 * host=127.0.0.1 #any resolvable IP/DNS
			 * icon=windows.png #Loaded from %server%/tclient/icons/
			 * type=RDP # Type of conneciton, must be defined in connections
			 * description=Test Station # This will show as a tooltip
			 * username=root #This is the default username to try
			 * retry=false #retry the connection or not
			 * hidden=true #Whether or not it shows up in the list */

            connection->alias = g_strdup(group[i]);
			
			/* Get the hostname/ip.  Verify that there is text there.  Fail
			 * if this is not there */
			if(!(connection->host = g_key_file_get_value(keys, group[i], "host", NULL)))
			{
				gchar *error_str = 0;
					
				error_str = g_strdup_printf("Malformed connection.conf: Error in group \"%s\".  You must provide a valid host to connect to.", group[i]);
				start_error_dialog(tclient, __FUNCTION__, error_str);
				
				g_free(error_str);
				g_free(connection);
				continue;
			}
			if (strlen(connection->host) <= 0)
			{
				gchar *error_str = 0;
				
				error_str = g_strdup_printf("Malformed connection.conf: Error in group \"%s\".  You must provide a valid host to connect to.", group[i]);
				start_error_dialog(tclient, __FUNCTION__, error_str);
				
				g_free(error_str);
				g_free(connection);
				continue;
			}
			
			/* Default username.  This can be empty */
			connection->username = g_key_file_get_value(keys, group[i], "username", NULL);
			
			/* Type to use.  This must exist in the types.conf file.  Fail if this
			 * entry is blank */
			if (!(connection->type = g_key_file_get_value(keys, group[i], "type", NULL)))
			{
				gchar *error_str = 0;
				
				error_str = g_strdup_printf("Malformed connection.conf: Error in group \"%s\".  \"%s\" must be set in types.conf", group[i], connection->type);
				start_error_dialog(tclient, __FUNCTION__, error_str);
				
				g_free(error_str);
				g_free(connection);
				continue;
			}
			if (connection->type == NULL)
			{
				gchar *error_str = 0;
				
				error_str = g_strdup_printf("Malformed connection.conf: Error in group \"%s\".  Type must be set", group[i]);
				start_error_dialog(tclient, __FUNCTION__, error_str);
				
				g_free(error_str);
				g_free(connection);
				continue;
			}
			
			/* Set retry setting.  If nothing else, say true */
			if (g_ascii_strncasecmp(g_key_file_get_value(keys, group[i], "retry", NULL), "true", strlen("true")) == 0)
			{
				connection->retry = TRUE;
			} 
			else if (g_ascii_strncasecmp(g_key_file_get_value(keys, group[i], "retry", NULL), "false", strlen("false")) == 0)
			{
				connection->retry = FALSE;
			} 
			else
			{
				connection->retry = TRUE;
			}
			
			/* Get this hidden setting.  Set to false by default */
			if(g_key_file_get_value(keys, group[i], "hidden", NULL) != NULL)
			{
				if (g_ascii_strncasecmp(g_key_file_get_value(keys, group[i], "hidden", NULL), "true", strlen("true")) == 0)
				{
					connection->hidden = TRUE;
				} 
				else if (g_ascii_strncasecmp(g_key_file_get_value(keys, group[i], "hidden", NULL), "false", strlen("false")) == 0)
				{
					connection->hidden = FALSE;
				}
			}
			else
			{
				connection->hidden = FALSE;
			}
			
			/* Get the icon name, this is optional */
            connection->icon = g_key_file_get_value(keys, group[i], "icon", NULL);
			
			/* Get the description, this is optional */
            connection->description = g_key_file_get_value(keys, group[i], "description", NULL);
			
            tclient->connection = g_list_append(tclient->connection, connection);
        }

        g_strfreev(group);
    }

    g_key_file_free(keys);

    return TRUE;
}
gboolean
exchanges_load_config ( void )
{
  GMappedFile *f;
  GKeyFile *kf;
  GError *error = NULL;
  gsize flen, len_config;
  gchar *config;
  gchar *finput;
  gchar *exch_name_str;
  gchar **exch_name_str_list;
  gchar *exch_desc_str;
  gchar **exch_desc_str_list;
  gint i;

  /* read configuration file */
  f = g_mapped_file_new ( CONFIG_FILENAME, FALSE, &error );

  if ( f == NULL )
    {
      log_print ( "error: exchanges_load_config(): file \'%s\' cannot be read: %s\n", CONFIG_FILENAME, error->message  );
      g_error_free ( error );
      return TRUE;
    }

  flen = g_mapped_file_get_length ( f );
  len_config = strlen(CONFIG_HEADER) + flen + 1;

  /* copy configuration in a buffer after prepending a key-file group name to make GLib happy */
  config = (gchar *) g_malloc ( sizeof(gchar) * len_config );
  strcpy ( config, CONFIG_HEADER );
  finput = g_mapped_file_get_contents ( f );
  memcpy ( config+strlen(CONFIG_HEADER), finput, flen );
  g_mapped_file_unref ( f );
  config[len_config-1] = '\0';

  /* parse configuration file to get exchanges list */
  kf = g_key_file_new ( );
  g_key_file_load_from_data ( kf, config, len_config, G_KEY_FILE_NONE, &error );

  if ( error != NULL )
    {
      log_print ( "error: exchanges_load_config(): unable to parse config file \'%s\': %s\n", CONFIG_FILENAME, error->message  );
      g_error_free ( error );
      return TRUE;
    }

  exch_name_str = g_key_file_get_string ( kf, "markets", "EXCHANGES", &error );

  if ( exch_name_str == NULL )
    {
      log_print ( "error: exchanges_load_config(): unable to find \'EXCHANGES\' key\n"  );
      return TRUE;
    }

  if ( exch_name_str[0] == '\"' )
    exch_name_str[0] = ' '; /* remove \" characters */
  if ( exch_name_str[strlen(exch_name_str)-1] == '\"' )
    exch_name_str[strlen(exch_name_str)-1] = ' ';

  exch_desc_str = g_key_file_get_string ( kf, "markets", "EXCHANGES_DESC", &error );

  if ( exch_desc_str == NULL )
    {
      log_print ( "error: exchanges_load_config(): unable to find \'EXCHANGES_DESC\' key\n"  );
      return TRUE;
    }

  if ( exch_desc_str[0] == '\"' )
    exch_desc_str[0] = ' '; /* remove \" characters */
  if ( exch_desc_str[strlen(exch_desc_str)-1] == '\"' )
    exch_desc_str[strlen(exch_desc_str)-1] = ' ';

  /* build EXCH_DESC array */
  exch_name_str_list = g_strsplit_set ( exch_name_str, " ", 0 );
  exch_desc_str_list = g_strsplit_set ( exch_desc_str, " ", 0 );

  for ( i=0; i<EXCH_NB_MAX; ++i )
    {
      if ( exch_name_str_list[i] == NULL )
        break;

      if ( strlen(exch_name_str_list[i]) == 0 )
        continue;

      /* log_print ( "core: adding exchange \'%s\'\n", exch_name_str_list[i] ); */
      EXCH_DESC[nb_exchanges].name = g_strdup ( exch_name_str_list[i] );

      if ( ( exch_desc_str_list[i] != NULL ) && ( strlen(exch_desc_str_list[i]) > 0 ) )
        EXCH_DESC[nb_exchanges].desc = g_strdup ( exch_desc_str_list[i] );
      else
        EXCH_DESC[nb_exchanges].desc = g_strdup ( exch_name_str_list[i] );

      ++nb_exchanges;
    }

  /* clean up */
  g_key_file_free ( kf );
  g_free ( config );
  g_free ( exch_name_str );
  g_free ( exch_desc_str );
  g_strfreev ( exch_name_str_list );
  g_strfreev ( exch_desc_str_list );

  return FALSE;
}
gboolean
flatpak_builtin_build (int argc, char **argv, GCancellable *cancellable, GError **error)
{
  g_autoptr(GOptionContext) context = NULL;
  g_autoptr(FlatpakDeploy) runtime_deploy = NULL;
  g_autoptr(GVariant) runtime_deploy_data = NULL;
  g_autoptr(FlatpakDeploy) extensionof_deploy = NULL;
  g_autoptr(GFile) var = NULL;
  g_autoptr(GFile) var_tmp = NULL;
  g_autoptr(GFile) var_lib = NULL;
  g_autoptr(GFile) usr = NULL;
  g_autoptr(GFile) res_deploy = NULL;
  g_autoptr(GFile) res_files = NULL;
  g_autoptr(GFile) app_files = NULL;
  gboolean app_files_ro = FALSE;
  g_autoptr(GFile) runtime_files = NULL;
  g_autoptr(GFile) metadata = NULL;
  g_autofree char *metadata_contents = NULL;
  g_autofree char *runtime = NULL;
  g_autofree char *runtime_ref = NULL;
  g_autofree char *extensionof_ref = NULL;
  g_autofree char *extensionof_tag = NULL;
  g_autofree char *extension_point = NULL;
  g_autofree char *extension_tmpfs_point = NULL;
  g_autoptr(GKeyFile) metakey = NULL;
  g_autoptr(GKeyFile) runtime_metakey = NULL;
  g_autoptr(FlatpakBwrap) bwrap = NULL;
  g_auto(GStrv) minimal_envp = NULL;
  gsize metadata_size;
  const char *directory = NULL;
  const char *command = "/bin/sh";
  g_autofree char *id = NULL;
  int i;
  int rest_argv_start, rest_argc;
  g_autoptr(FlatpakContext) arg_context = NULL;
  g_autoptr(FlatpakContext) app_context = NULL;
  gboolean custom_usr;
  g_auto(GStrv) runtime_ref_parts = NULL;
  FlatpakRunFlags run_flags;
  const char *group = NULL;
  const char *runtime_key = NULL;
  const char *dest = NULL;
  gboolean is_app = FALSE;
  gboolean is_extension = FALSE;
  gboolean is_app_extension = FALSE;
  g_autofree char *app_info_path = NULL;
  g_autofree char *app_extensions = NULL;
  g_autofree char *runtime_extensions = NULL;
  g_autofree char *instance_id_host_dir = NULL;
  char pid_str[64];
  g_autofree char *pid_path = NULL;
  g_autoptr(GFile) app_id_dir = NULL;

  context = g_option_context_new (_("DIRECTORY [COMMAND [ARGUMENT…]] - Build in directory"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);

  rest_argc = 0;
  for (i = 1; i < argc; i++)
    {
      /* The non-option is the directory, take it out of the arguments */
      if (argv[i][0] != '-')
        {
          rest_argv_start = i;
          rest_argc = argc - i;
          argc = i;
          break;
        }
    }

  arg_context = flatpak_context_new ();
  g_option_context_add_group (context, flatpak_context_get_options (arg_context));

  if (!flatpak_option_context_parse (context, options, &argc, &argv, FLATPAK_BUILTIN_FLAG_NO_DIR, NULL, cancellable, error))
    return FALSE;

  if (rest_argc == 0)
    return usage_error (context, _("DIRECTORY must be specified"), error);

  directory = argv[rest_argv_start];
  if (rest_argc >= 2)
    command = argv[rest_argv_start + 1];

  res_deploy = g_file_new_for_commandline_arg (directory);
  metadata = g_file_get_child (res_deploy, opt_metadata ? opt_metadata : "metadata");

  if (!g_file_query_exists (res_deploy, NULL) ||
      !g_file_query_exists (metadata, NULL))
    return flatpak_fail (error, _("Build directory %s not initialized, use flatpak build-init"), directory);

  if (!g_file_load_contents (metadata, cancellable, &metadata_contents, &metadata_size, NULL, error))
    return FALSE;

  metakey = g_key_file_new ();
  if (!g_key_file_load_from_data (metakey, metadata_contents, metadata_size, 0, error))
    return FALSE;

  if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_APPLICATION))
    {
      group = FLATPAK_METADATA_GROUP_APPLICATION;
      is_app = TRUE;
    }
  else if (g_key_file_has_group (metakey, FLATPAK_METADATA_GROUP_RUNTIME))
    {
      group = FLATPAK_METADATA_GROUP_RUNTIME;
    }
  else
    return flatpak_fail (error, _("metadata invalid, not application or runtime"));

  extensionof_ref = g_key_file_get_string (metakey,
                                           FLATPAK_METADATA_GROUP_EXTENSION_OF,
                                           FLATPAK_METADATA_KEY_REF, NULL);
  if (extensionof_ref != NULL)
    {
      is_extension = TRUE;
      if (g_str_has_prefix (extensionof_ref, "app/"))
        is_app_extension = TRUE;
    }

  extensionof_tag = g_key_file_get_string (metakey,
                                           FLATPAK_METADATA_GROUP_EXTENSION_OF,
                                           FLATPAK_METADATA_KEY_TAG, NULL);

  id = g_key_file_get_string (metakey, group, FLATPAK_METADATA_KEY_NAME, error);
  if (id == NULL)
    return FALSE;

  if (opt_runtime)
    runtime_key = FLATPAK_METADATA_KEY_RUNTIME;
  else
    runtime_key = FLATPAK_METADATA_KEY_SDK;

  runtime = g_key_file_get_string (metakey, group, runtime_key, error);
  if (runtime == NULL)
    return FALSE;

  runtime_ref = g_build_filename ("runtime", runtime, NULL);

  runtime_ref_parts = flatpak_decompose_ref (runtime_ref, error);
  if (runtime_ref_parts == NULL)
    return FALSE;

  custom_usr = FALSE;
  usr = g_file_get_child (res_deploy,  opt_sdk_dir ? opt_sdk_dir : "usr");
  if (g_file_query_exists (usr, cancellable))
    {
      custom_usr = TRUE;
      runtime_files = g_object_ref (usr);
    }
  else
    {
      runtime_deploy = flatpak_find_deploy_for_ref (runtime_ref, NULL, cancellable, error);
      if (runtime_deploy == NULL)
        return FALSE;

      runtime_deploy_data = flatpak_deploy_get_deploy_data (runtime_deploy, FLATPAK_DEPLOY_VERSION_ANY, cancellable, error);
      if (runtime_deploy_data == NULL)
        return FALSE;

      runtime_metakey = flatpak_deploy_get_metadata (runtime_deploy);

      runtime_files = flatpak_deploy_get_files (runtime_deploy);
    }

  var = g_file_get_child (res_deploy, "var");
  var_tmp = g_file_get_child (var, "tmp");
  if (!flatpak_mkdir_p (var_tmp, cancellable, error))
    return FALSE;
  var_lib = g_file_get_child (var, "lib");
  if (!flatpak_mkdir_p (var_lib, cancellable, error))
    return FALSE;

  res_files = g_file_get_child (res_deploy, "files");

  if (is_app)
    {
      app_files = g_object_ref (res_files);
      if (opt_with_appdir)
        app_id_dir = flatpak_ensure_data_dir (id, cancellable, NULL);
    }
  else if (is_extension)
    {
      g_autoptr(GKeyFile) x_metakey = NULL;
      g_autofree char *x_group = NULL;
      g_autofree char *x_dir = NULL;
      g_autofree char *x_subdir_suffix = NULL;
      char *x_subdir = NULL;
      g_autofree char *bare_extension_point = NULL;

      extensionof_deploy = flatpak_find_deploy_for_ref (extensionof_ref, NULL, cancellable, error);
      if (extensionof_deploy == NULL)
        return FALSE;

      x_metakey = flatpak_deploy_get_metadata (extensionof_deploy);

      /* Since we have tagged extensions, it is possible that an extension could
       * be listed more than once in the "parent" flatpak. In that case, we should
       * try and disambiguate using the following rules:
       *
       * 1. Use the 'tag=' key in the ExtensionOfSection and if not found:
       * 2. Use the only extension point available if there is only one.
       * 3. If there are no matching groups, return NULL.
       * 4. In all other cases, error out.
       */
      if (!find_matching_extension_group_in_metakey (x_metakey,
                                                     id,
                                                     extensionof_tag,
                                                     &x_group,
                                                     error))
        return FALSE;

      if (x_group == NULL)
        {
          /* Failed, look for subdirectories=true parent */
          char *last_dot = strrchr (id, '.');

          if (last_dot != NULL)
            {
              char *parent_id = g_strndup (id, last_dot - id);
              if (!find_matching_extension_group_in_metakey (x_metakey,
                                                             parent_id,
                                                             extensionof_tag,
                                                             &x_group,
                                                             error))
                return FALSE;

              if (x_group != NULL &&
                  g_key_file_get_boolean (x_metakey, x_group,
                                          FLATPAK_METADATA_KEY_SUBDIRECTORIES,
                                          NULL))
                x_subdir = last_dot + 1;
            }

          if (x_subdir == NULL)
            return flatpak_fail (error, _("No extension point matching %s in %s"), id, extensionof_ref);
        }

      x_dir = g_key_file_get_string (x_metakey, x_group,
                                     FLATPAK_METADATA_KEY_DIRECTORY, error);
      if (x_dir == NULL)
        return FALSE;

      x_subdir_suffix = g_key_file_get_string (x_metakey, x_group,
                                               FLATPAK_METADATA_KEY_SUBDIRECTORY_SUFFIX,
                                               NULL);

      if (is_app_extension)
        {
          app_files = flatpak_deploy_get_files (extensionof_deploy);
          app_files_ro = TRUE;
          if (x_subdir != NULL)
            extension_tmpfs_point = g_build_filename ("/app", x_dir, NULL);
          bare_extension_point = g_build_filename ("/app", x_dir, x_subdir, NULL);
        }
      else
        {
          if (x_subdir != NULL)
            extension_tmpfs_point = g_build_filename ("/usr", x_dir, NULL);
          bare_extension_point = g_build_filename ("/usr", x_dir, x_subdir, NULL);
        }

      extension_point = g_build_filename (bare_extension_point, x_subdir_suffix, NULL);
    }

  app_context = flatpak_app_compute_permissions (metakey,
                                                 runtime_metakey,
                                                 error);
  if (app_context == NULL)
    return FALSE;

  flatpak_context_allow_host_fs (app_context);
  flatpak_context_merge (app_context, arg_context);

  minimal_envp = flatpak_run_get_minimal_env (TRUE, FALSE);
  bwrap = flatpak_bwrap_new (minimal_envp);
  flatpak_bwrap_add_args (bwrap, flatpak_get_bwrap (), NULL);

  run_flags =
    FLATPAK_RUN_FLAG_DEVEL | FLATPAK_RUN_FLAG_MULTIARCH | FLATPAK_RUN_FLAG_NO_SESSION_HELPER |
    FLATPAK_RUN_FLAG_SET_PERSONALITY | FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY;
  if (opt_die_with_parent)
    run_flags |= FLATPAK_RUN_FLAG_DIE_WITH_PARENT;
  if (custom_usr)
    run_flags |= FLATPAK_RUN_FLAG_WRITABLE_ETC;

  run_flags |= flatpak_context_get_run_flags (app_context);

  /* Unless manually specified, we disable dbus proxy */
  if (!flatpak_context_get_needs_session_bus_proxy (arg_context))
    run_flags |= FLATPAK_RUN_FLAG_NO_SESSION_BUS_PROXY;

  if (!flatpak_context_get_needs_system_bus_proxy (arg_context))
    run_flags |= FLATPAK_RUN_FLAG_NO_SYSTEM_BUS_PROXY;

  if (opt_log_session_bus)
    run_flags |= FLATPAK_RUN_FLAG_LOG_SESSION_BUS;

  if (opt_log_system_bus)
    run_flags |= FLATPAK_RUN_FLAG_LOG_SYSTEM_BUS;

  /* Never set up an a11y bus for builds */
  run_flags |= FLATPAK_RUN_FLAG_NO_A11Y_BUS_PROXY;

  if (!flatpak_run_setup_base_argv (bwrap, runtime_files, app_id_dir, runtime_ref_parts[2],
                                    run_flags, error))
    return FALSE;

  flatpak_bwrap_add_args (bwrap,
                          (custom_usr && !opt_readonly)  ? "--bind" : "--ro-bind", flatpak_file_get_path_cached (runtime_files), "/usr",
                          NULL);

  if (!custom_usr)
    flatpak_bwrap_add_args (bwrap,
                            "--lock-file", "/usr/.ref",
                            NULL);

  if (app_files)
    flatpak_bwrap_add_args (bwrap,
                            (app_files_ro || opt_readonly) ? "--ro-bind" : "--bind", flatpak_file_get_path_cached (app_files), "/app",
                            NULL);
  else
    flatpak_bwrap_add_args (bwrap,
                            "--dir", "/app",
                            NULL);

  if (extension_tmpfs_point)
    flatpak_bwrap_add_args (bwrap,
                            "--tmpfs", extension_tmpfs_point,
                            NULL);

  /* We add the actual bind below so that we're not shadowed by other extensions or their tmpfs */

  if (extension_point)
    dest = extension_point;
  else if (is_app)
    dest = g_strdup ("/app");
  else
    dest = g_strdup ("/usr");

  flatpak_bwrap_add_args (bwrap,
                          "--setenv", "FLATPAK_DEST", dest,
                          "--setenv", "FLATPAK_ID", id,
                          "--setenv", "FLATPAK_ARCH", runtime_ref_parts[2],
                          NULL);

  /* Persist some stuff in /var. We can't persist everything because  that breaks /var things
   * from the host to work. For example the /home -> /var/home on atomic.
   * The interesting things to contain during the build is /var/tmp (for tempfiles shared during builds)
   * and things like /var/lib/rpm, if the installation uses packages.
   */
  flatpak_bwrap_add_args (bwrap,
                          "--bind", flatpak_file_get_path_cached (var_lib), "/var/lib",
                          NULL);
  flatpak_bwrap_add_args (bwrap,
                          "--bind", flatpak_file_get_path_cached (var_tmp), "/var/tmp",
                          NULL);

  flatpak_run_apply_env_vars (bwrap, app_context);

  if (is_app)
    {
      /* We don't actually know the final branchname yet, so use "nobranch" as fallback to avoid unexpected matches.
         This means any extension point used at build time must have explicit versions to work. */
      g_autofree char *fake_ref = g_strdup_printf ("app/%s/%s/nobranch", id, runtime_ref_parts[2]);
      if (!flatpak_run_add_extension_args (bwrap, metakey, fake_ref, FALSE, &app_extensions, cancellable, error))
        return FALSE;
    }

  if (!custom_usr &&
      !flatpak_run_add_extension_args (bwrap, runtime_metakey, runtime_ref, FALSE, &runtime_extensions, cancellable, error))
    return FALSE;

  /* Mount this after the above extensions so we always win */
  if (extension_point)
    flatpak_bwrap_add_args (bwrap,
                            "--bind", flatpak_file_get_path_cached (res_files), extension_point,
                            NULL);

  if (!flatpak_run_add_app_info_args (bwrap,
                                      app_files, NULL, app_extensions,
                                      runtime_files, runtime_deploy_data, runtime_extensions,
                                      id, NULL,
                                      runtime_ref,
                                      app_id_dir, app_context, NULL,
                                      FALSE, TRUE, TRUE,
                                      &app_info_path,
                                      &instance_id_host_dir,
                                      error))
    return FALSE;

  if (!flatpak_run_add_environment_args (bwrap, app_info_path, run_flags, id,
                                         app_context, app_id_dir, NULL, cancellable, error))
    return FALSE;

  for (i = 0; opt_bind_mounts != NULL && opt_bind_mounts[i] != NULL; i++)
    {
      char *split = strchr (opt_bind_mounts[i], '=');
      if (split == NULL)
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                       _("Missing '=' in bind mount option '%s'"), opt_bind_mounts[i]);
          return FALSE;
        }

      *split++ = 0;
      flatpak_bwrap_add_args (bwrap,
                              "--bind", split, opt_bind_mounts[i],
                              NULL);
    }

  if (opt_build_dir != NULL)
    {
      flatpak_bwrap_add_args (bwrap,
                              "--chdir", opt_build_dir,
                              NULL);
    }

  if (!flatpak_bwrap_bundle_args (bwrap, 1, -1, FALSE, error))
    return FALSE;

  flatpak_bwrap_add_args (bwrap, command, NULL);
  flatpak_bwrap_append_argsv (bwrap,
                              &argv[rest_argv_start + 2],
                              rest_argc - 2);

  g_ptr_array_add (bwrap->argv, NULL);

  g_snprintf (pid_str, sizeof (pid_str), "%d", getpid ());
  pid_path = g_build_filename (instance_id_host_dir, "pid", NULL);
  g_file_set_contents (pid_path, pid_str, -1, NULL);

  /* Ensure we unset O_CLOEXEC */
  child_setup (bwrap->fds);
  if (execvpe (flatpak_get_bwrap (), (char **) bwrap->argv->pdata, bwrap->envp) == -1)
    {
      g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errno),
                   _("Unable to start app"));
      return FALSE;
    }

  /* Not actually reached... */
  return TRUE;
}
Exemple #18
0
/**
 * facq_stream_save:
 * @stream: A closed #FacqStream object, see facq_stream_is_closed() for
 * more details.
 * @filename: filename of the file where you want to store stream details.
 * @err: (allow-none): A #GError, it will be set in case of error.
 *
 * Saves the closed #FacqStream, @stream, to the plain text file pointed by
 * @filename, creating it if necessary. You can create a #FacqStream from this
 * file later using facq_stream_load().
 *
 * Returns: %TRUE if successful, %FALSE in other case.
 */
gboolean facq_stream_save(FacqStream *stream,const gchar *filename,GError **err)
{
	GString *key_file_content = NULL;
	GKeyFile *key_file = NULL;
	gchar *txt_key_file_content = NULL;
	gboolean ret = FALSE;
	GError *local_err = NULL;
	guint i = 0, n_operations = 0;
	gpointer item = NULL;

	g_return_val_if_fail(FACQ_IS_STREAM(stream),FALSE);
	g_return_val_if_fail(filename,FALSE);
	g_return_val_if_fail(facq_stream_is_closed(stream),FALSE);

	key_file_content = facq_stream_save_get_group_names(stream);
	key_file = g_key_file_new();
	ret = g_key_file_load_from_data(key_file,
					key_file_content->str,
					-1,
					G_KEY_FILE_NONE,
					&local_err);
	g_string_free(key_file_content,TRUE);
	if(!ret)
		goto error;

	/* save the stream name */
	g_key_file_set_string(key_file,"Stream","name",stream->priv->name);
	
	/* save the source */
	item = stream->priv->src;
	facq_stream_save_item(key_file,item,i);
	i++;

	/* save the operations */
	n_operations = facq_stream_get_operation_num(stream);
	if(n_operations){
		for(i = 0;i < n_operations;i++){
			item = facq_operation_list_get(stream->priv->oplist,i);
			facq_stream_save_item(key_file,item,i+1);
		}
	}

	/* save the sink */
	i = 1 + n_operations;
	item = stream->priv->sink;
	facq_stream_save_item(key_file,item,i);

	txt_key_file_content = g_key_file_to_data(key_file,NULL,NULL);
	facq_log_write_v(FACQ_LOG_MSG_TYPE_DEBUG,"FILE:\n%s\n",txt_key_file_content);
	facq_stream_save_to_file(filename,txt_key_file_content,&local_err);
	g_free(txt_key_file_content);
	g_key_file_free(key_file);

	facq_log_write_v(FACQ_LOG_MSG_TYPE_INFO,"%s","Stream saved without errors");
	return TRUE;

	error:
	if(local_err){
		facq_log_write_v(FACQ_LOG_MSG_TYPE_ERROR,"%s",
						local_err->message);
		g_clear_error(&local_err);
	}
	if(err)
		g_set_error_literal(err,FACQ_STREAM_ERROR,
					FACQ_STREAM_ERROR_FAILED,
					"Error saving stream");
	return FALSE;
}
static gboolean
handle_configure_remote (FlatpakSystemHelper *object,
                         GDBusMethodInvocation *invocation,
                         guint arg_flags,
                         const gchar *arg_remote,
                         const gchar *arg_config,
                         GVariant *arg_gpg_key)
{
  g_autoptr(FlatpakDir) system = dir_get_system ();
  g_autoptr(GError) error = NULL;
  g_autoptr(GKeyFile) config = g_key_file_new ();
  g_autofree char *group = g_strdup_printf ("remote \"%s\"", arg_remote);
  g_autoptr(GBytes) gpg_data = NULL;
  gboolean force_remove;

  g_debug ("ConfigureRemote %u %s", arg_flags, arg_remote);

  if (*arg_remote == 0 || strchr (arg_remote, '/') != NULL)
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                                             "Invalid remote name: %s", arg_remote);
      return TRUE;
    }

  if ((arg_flags & ~FLATPAK_HELPER_CONFIGURE_REMOTE_FLAGS_ALL) != 0)
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                                             "Unsupported flags enabled: 0x%x", (arg_flags & ~FLATPAK_HELPER_CONFIGURE_REMOTE_FLAGS_ALL));
      return TRUE;
    }

  if (!g_key_file_load_from_data (config, arg_config, strlen (arg_config),
                                  G_KEY_FILE_NONE, &error))
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                                             "Invalid config: %s\n", error->message);
      return TRUE;
    }

  if (!flatpak_dir_ensure_repo (system, NULL, &error))
    {
      g_dbus_method_invocation_return_gerror  (invocation, error);
      return TRUE;
    }

  if (g_variant_get_size (arg_gpg_key) > 0)
    gpg_data = g_variant_get_data_as_bytes (arg_gpg_key);

  force_remove = (arg_flags & FLATPAK_HELPER_CONFIGURE_REMOTE_FLAGS_FORCE_REMOVE) != 0;

  if (g_key_file_has_group (config, group))
    {
      /* Add/Modify */
      if (!flatpak_dir_modify_remote (system, arg_remote, config,
                                      gpg_data, NULL, &error))
        {
          g_dbus_method_invocation_return_gerror  (invocation, error);
          return TRUE;
        }
    }
  else
    {
      /* Remove */
      if (!flatpak_dir_remove_remote (system,
                                      force_remove,
                                      arg_remote,
                                      NULL, &error))
        {
          g_dbus_method_invocation_return_gerror  (invocation, error);
          return TRUE;
        }
    }

  flatpak_system_helper_complete_configure_remote (object, invocation);

  return TRUE;
}
static void
get_all_providers_cb (GObject      *source,
                      GAsyncResult *res,
                      gpointer      user_data)
{
  AddAccountData *data = user_data;
  GoaProvider *provider;
  GKeyFile *key_file;
  GError *error;
  GList *providers;
  GList *l;
  gchar *path;
  gchar *id;
  gchar *group;
  gchar *key_file_data;
  gsize length;
  gchar *object_path;
  GVariantIter iter;
  const gchar *key;
  const gchar *value;

  /* TODO: could check for @type */

  provider = NULL;
  key_file = NULL;
  providers = NULL;
  path = NULL;
  id = NULL;
  group = NULL;
  key_file_data = NULL;
  object_path = NULL;

  if (!goa_provider_get_all_finish (&providers, res, NULL))
    goto out;

  for (l = providers; l != NULL; l = l->next)
    {
      GoaProvider *p;
      const gchar *type;

      p = GOA_PROVIDER (l->data);
      type = goa_provider_get_provider_type (p);
      if (g_strcmp0 (type, data->provider_type) == 0)
        {
          provider = p;
          break;
        }
    }

  if (provider == NULL)
    {
      error= NULL;
      g_set_error (&error,
                   GOA_ERROR,
                   GOA_ERROR_FAILED, /* TODO: more specific */
                   _("Failed to find a provider for: %s"),
                   data->provider_type);
      g_dbus_method_invocation_return_gerror (data->invocation, error);
      goto out;
    }

  key_file = g_key_file_new ();
  path = g_strdup_printf ("%s/goa-1.0/accounts.conf", g_get_user_config_dir ());
  error = NULL;
  if (!g_file_get_contents (path,
                            &key_file_data,
                            &length,
                            &error))
    {
      if (error->domain == G_FILE_ERROR && error->code == G_FILE_ERROR_NOENT)
        {
          g_error_free (error);
        }
      else
        {
          g_prefix_error (&error, "Error loading file %s: ", path);
          g_dbus_method_invocation_return_gerror (data->invocation, error);
          goto out;
        }
    }
  else
    {
      if (length > 0)
        {
          error = NULL;
          if (!g_key_file_load_from_data (key_file, key_file_data, length, G_KEY_FILE_KEEP_COMMENTS, &error))
            {
              g_prefix_error (&error, "Error parsing key-value-file %s: ", path);
              g_dbus_method_invocation_return_gerror (data->invocation, error);
              goto out;
            }
        }
    }

  id = generate_new_id (data->daemon);
  group = g_strdup_printf ("Account %s", id);
  g_key_file_set_string (key_file, group, "Provider", data->provider_type);
  g_key_file_set_string (key_file, group, "Identity", data->identity);
  g_key_file_set_string (key_file, group, "PresentationIdentity", data->presentation_identity);

  g_variant_iter_init (&iter, data->details);
  while (g_variant_iter_next (&iter, "{&s&s}", &key, &value))
    {
      /* We treat IsTemporary special.  If it's true we add in
       * the current session guid, so it can be ignored after
       * the session is over.
       */
      if (g_strcmp0 (key, "IsTemporary") == 0)
        {
          if (g_strcmp0 (value, "true") == 0)
            {
              const char *guid;

              guid = g_dbus_connection_get_guid (data->daemon->connection);
              g_key_file_set_string (key_file, group, "SessionId", guid);
            }
        }

      g_key_file_set_string (key_file, group, key, value);
    }

  g_free (key_file_data);
  error = NULL;
  key_file_data = g_key_file_to_data (key_file,
                                      &length,
                                      &error);
  if (key_file_data == NULL)
    {
      g_prefix_error (&error, "Error generating key-value-file: ");
      g_dbus_method_invocation_return_gerror (data->invocation, error);
      goto out;
    }

  error = NULL;
  if (!g_file_set_contents (path,
                            key_file_data,
                            length,
                            &error))
    {
      g_prefix_error (&error, "Error writing key-value-file %s: ", path);
      g_dbus_method_invocation_return_gerror (data->invocation, error);
      goto out;
    }

  /* We don't want to fail AddAccount if we could not store the
   * credentials in the keyring.
   */
  goa_utils_store_credentials_for_id_sync (provider,
                                           id,
                                           data->credentials,
                                           NULL, /* GCancellable */
                                           NULL);

  goa_daemon_reload_configuration (data->daemon);

  object_path = g_strdup_printf ("/org/gnome/OnlineAccounts/Accounts/%s", id);
  goa_manager_complete_add_account (data->manager, data->invocation, object_path);

 out:
  g_free (object_path);
  if (providers != NULL)
    g_list_free_full (providers, g_object_unref);
  g_free (key_file_data);
  g_free (group);
  g_free (id);
  g_free (path);
  if (key_file != NULL)
    g_key_file_free (key_file);

  g_object_unref (data->daemon);
  g_object_unref (data->manager);
  g_object_unref (data->invocation);
  g_free (data->provider_type);
  g_free (data->identity);
  g_free (data->presentation_identity);
  g_variant_unref (data->credentials);
  g_variant_unref (data->details);
  g_slice_free (AddAccountData, data);
}
static VinagreConnection *
impl_new_connection_from_file (VinagreProtocol *plugin,
			       const gchar   *data,
			       gboolean	      use_bookmarks,
			       gchar	    **error_msg)
{
  GKeyFile	    *file;
  GError	    *error;
  gboolean	     loaded;
  gchar		    *host, *actual_host, *protocol;
  gint		     port;
  VinagreConnection *conn;

  *error_msg = NULL;
  conn = NULL;
  host = NULL;
  protocol = NULL;
  error = NULL;

  file = g_key_file_new ();
  loaded = g_key_file_load_from_data (file,
				      data,
				      -1,
				      0,
				      &error);
  if (!loaded)
    {
      if (error)
	{
	  *error_msg = g_strdup (error->message);
	  g_error_free (error);
	}
      else
	*error_msg = g_strdup (_("Could not parse the file."));

      goto the_end;
    }
  if (!g_key_file_has_group (file, "connection"))
    {
      /* Translators: Do not translate "connection". It's the name of a group in the .spice (.ini like) file. */
      *error_msg = g_strdup (_("The file is not a Spice one: Missing the group \"connection\"."));
      goto the_end;
    }

  if (!g_key_file_has_key (file, "connection", "host", NULL))
    {
      /* Translators: Do not translate "host". It's the name of a key in the .spice (.ini like) file. */
      *error_msg = g_strdup (_("The file is not a Spice one: Missing the key \"host\"."));
      goto the_end;
    }

  host = g_key_file_get_string (file, "connection", "host", NULL);
  port = g_key_file_get_integer (file, "connection", "port", NULL);
  if (!port)
    {
      if (!vinagre_connection_split_string (host, "spice", &protocol, &actual_host, &port, error_msg))
	goto the_end;

      g_free (host);
      host = actual_host;
    }

  if (use_bookmarks)
    conn = vinagre_bookmarks_exists (vinagre_bookmarks_get_default (), "spice", host, port);
  if (!conn)
    {
      gchar *s_value;

      conn = vinagre_spice_connection_new ();
      vinagre_connection_set_host (conn, host);
      vinagre_connection_set_port (conn, port);

      s_value = g_key_file_get_string  (file, "connection", "password", NULL);
      vinagre_connection_set_password (conn, s_value);
      g_free (s_value);
    }

 the_end:

  g_free (host);
  g_free (protocol);
  g_key_file_free (file);
  return conn;

}
Exemple #22
0
static void
on_xdg_volume_info_loaded (GObject      *source_object,
                           GAsyncResult *res,
                           gpointer      user_data)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
  GFile *xdg_volume_info_file;
  gchar *content;
  gsize content_length;
  GError *error;
  GKeyFile *key_file;
  gchar *name;
  gchar *icon_name;
  gchar *icon_file;
  GIcon *icon;

  content = NULL;
  key_file = NULL;
  name = NULL;
  icon_name = NULL;
  icon_file = NULL;

  xdg_volume_info_file = G_FILE (source_object);

  error = NULL;
  if (g_file_load_contents_finish (xdg_volume_info_file,
                                   res,
                                   &content,
                                   &content_length,
                                   NULL,
                                   &error))
    {
      key_file = g_key_file_new ();
      if (!g_key_file_load_from_data (key_file,
                                      content,
                                      content_length,
                                      G_KEY_FILE_NONE,
                                      &error))
        goto out;


      name = g_key_file_get_locale_string (key_file,
                                           VOLUME_INFO_GROUP,
                                           "Name",
                                           NULL,
                                           NULL);

      icon_name = g_key_file_get_string (key_file,
                                         VOLUME_INFO_GROUP,
                                         "Icon",
                                         NULL);
      
      icon_file = g_key_file_get_string (key_file,
                                         VOLUME_INFO_GROUP,
                                         "IconFile",
                                         NULL);

      icon = NULL;
      
      if (icon_file != NULL)
        {
          GFile *dir, *f;

          dir = g_file_get_parent (xdg_volume_info_file);
          if (dir)
            {
              f = g_file_resolve_relative_path (dir, icon_file);
              if (f)
                {
                  icon = g_file_icon_new (f);
                  g_object_unref (f);
                }
              
              g_object_unref (dir);
            }
        }
            
      if (icon == NULL && icon_name != NULL)
        {
          icon = g_themed_icon_new (icon_name);
          g_themed_icon_append_name (G_THEMED_ICON (icon), "drive-removable-media");
          g_themed_icon_append_name (G_THEMED_ICON (icon), "drive-removable");
          g_themed_icon_append_name (G_THEMED_ICON (icon), "drive");
        }

      g_simple_async_result_set_op_res_gpointer (simple, icon, NULL);
      g_object_set_data_full (G_OBJECT (simple), "name", name, g_free);
      name = NULL; /* steals name */
      g_simple_async_result_complete_in_idle (simple);
      g_object_unref (simple);
    }

 out:

  if (key_file != NULL)
    g_key_file_free (key_file);

  if (error != NULL)
    {
      g_simple_async_result_set_from_error (simple, error);
      g_simple_async_result_complete_in_idle (simple);
      g_object_unref (simple);
      g_error_free (error);
    }

  g_free (name);
  g_free (icon_name);
  g_free (icon_file);
  g_free (content);
}
Exemple #23
0
/* check handling of comments
 */
void
test_comments (void)
{
  gchar **names;
  gsize len;
  GError *error = NULL;
  gchar *comment;

  const gchar *data = 
    "# top comment\n"
    "# top comment, continued\n"
    "[group1]\n"
    "key1 = value1\n"
    "# key comment\n"
    "# key comment, continued\n"
    "key2 = value2\n"
    "# line end check\r\n"
    "key3 = value3\n"
    "key4 = value4\n"
    "# group comment\n"
    "# group comment, continued\n"
    "[group2]\n";

  const gchar *top_comment= " top comment\n top comment, continued\n";
  const gchar *group_comment= " group comment\n group comment, continued\n";
  const gchar *key_comment= " key comment\n key comment, continued\n";
  
  cut_assert (g_key_file_load_from_data (keyfile, data, -1, 0, NULL));

  check_string_value (keyfile, "group1", "key1", "value1");
  check_string_value (keyfile, "group1", "key2", "value2");
  check_string_value (keyfile, "group1", "key3", "value3");
  check_string_value (keyfile, "group1", "key4", "value4");

  names = g_key_file_get_keys (keyfile, "group1", &len, &error);
  check_no_error (error);

  check_length ("keys", g_strv_length (names), len, 4);
  check_name ("key", names[0], "key1", 0);
  check_name ("key", names[1], "key2", 1);
  check_name ("key", names[2], "key3", 2);
  check_name ("key", names[3], "key4", 3);

  g_strfreev (names);

  g_key_file_free (keyfile);

  keyfile = g_key_file_new ();
  cut_assert (g_key_file_load_from_data (keyfile, data, -1, G_KEY_FILE_KEEP_COMMENTS, NULL));

  names = g_key_file_get_keys (keyfile, "group1", &len, &error);
  check_no_error (error);

  check_length ("keys", g_strv_length (names), len, 4);
  check_name ("key", names[0], "key1", 0);
  check_name ("key", names[1], "key2", 1);
  check_name ("key", names[2], "key3", 2);
  check_name ("key", names[3], "key4", 3);

  g_strfreev (names);

  comment = g_key_file_get_comment (keyfile, NULL, NULL, &error);
  check_no_error (error);
  check_name ("top comment", comment, top_comment, 0);
  g_free (comment);

  comment = g_key_file_get_comment (keyfile, "group1", "key2", &error);
  check_no_error (error);
  check_name ("key comment", comment, key_comment, 0);
  g_free (comment);

  comment = g_key_file_get_comment (keyfile, "group2", NULL, &error);
  check_no_error (error);
  check_name ("group comment", comment, group_comment, 0);
  g_free (comment);

  comment = g_key_file_get_comment (keyfile, "group3", NULL, &error);
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_GROUP_NOT_FOUND);
  cut_assert_null (comment);
}
Exemple #24
0
/**
 * Load the session from the specified filename.
 *
 * @param filename The name of the session file to load. Must not be NULL.
 *
 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
 *         SR_ERR_MALLOC upon memory allocation errors, or SR_ERR upon
 *         other errors.
 */
SR_API int sr_session_load(const char *filename)
{
	GKeyFile *kf;
	GPtrArray *capturefiles;
	struct zip *archive;
	struct zip_file *zf;
	struct zip_stat zs;
	struct sr_dev_inst *sdi;
	struct sr_channel *probe;
    int ret, devcnt, i, j, k;
    uint16_t probenum;
    uint64_t tmp_u64, total_probes, enabled_probes;
    uint16_t p;
	char **sections, **keys, *metafile, *val, s[11];
	char probename[SR_MAX_PROBENAME_LEN + 1];
    int mode = LOGIC;
    int channel_type = SR_CHANNEL_LOGIC;
    double tmp_double;

	if (!filename) {
		sr_err("%s: filename was NULL", __func__);
		return SR_ERR_ARG;
	}

	if (!(archive = zip_open(filename, 0, &ret))) {
		sr_dbg("Failed to open session file: zip error %d", ret);
		return SR_ERR;
	}

	/* read "metadata" */
    if (zip_stat(archive, "header", 0, &zs) == -1) {
        sr_dbg("Not a valid DSView data file.");
		return SR_ERR;
	}

	if (!(metafile = g_try_malloc(zs.size))) {
		sr_err("%s: metafile malloc failed", __func__);
		return SR_ERR_MALLOC;
	}

	zf = zip_fopen_index(archive, zs.index, 0);
	zip_fread(zf, metafile, zs.size);
	zip_fclose(zf);

	kf = g_key_file_new();
	if (!g_key_file_load_from_data(kf, metafile, zs.size, 0, NULL)) {
		sr_dbg("Failed to parse metadata.");
		return SR_ERR;
	}

	sr_session_new();

	devcnt = 0;
	capturefiles = g_ptr_array_new_with_free_func(g_free);
	sections = g_key_file_get_groups(kf, NULL);
	for (i = 0; sections[i]; i++) {
        if (!strcmp(sections[i], "version"))
			/* nothing really interesting in here yet */
			continue;
        if (!strncmp(sections[i], "header", 6)) {
			/* device section */
			sdi = NULL;
			enabled_probes = total_probes = 0;
			keys = g_key_file_get_keys(kf, sections[i], NULL, NULL);
			for (j = 0; keys[j]; j++) {
				val = g_key_file_get_string(kf, sections[i], keys[j], NULL);
                if (!strcmp(keys[j], "device mode")) {
                    mode = strtoull(val, NULL, 10);
                } else if (!strcmp(keys[j], "capturefile")) {
                    sdi = sr_dev_inst_new(mode, devcnt, SR_ST_ACTIVE, NULL, NULL, NULL);
					sdi->driver = &session_driver;
					if (devcnt == 0)
						/* first device, init the driver */
						sdi->driver->init(NULL);
					sr_dev_open(sdi);
					sr_session_dev_add(sdi);
					sdi->driver->config_set(SR_CONF_SESSIONFILE,
                            g_variant_new_bytestring(filename), sdi, NULL, NULL);
					sdi->driver->config_set(SR_CONF_CAPTUREFILE,
                            g_variant_new_bytestring(val), sdi, NULL, NULL);
					g_ptr_array_add(capturefiles, val);
				} else if (!strcmp(keys[j], "samplerate")) {
					sr_parse_sizestring(val, &tmp_u64);
					sdi->driver->config_set(SR_CONF_SAMPLERATE,
                            g_variant_new_uint64(tmp_u64), sdi, NULL, NULL);
				} else if (!strcmp(keys[j], "unitsize")) {
					tmp_u64 = strtoull(val, NULL, 10);
					sdi->driver->config_set(SR_CONF_CAPTURE_UNITSIZE,
                            g_variant_new_uint64(tmp_u64), sdi, NULL, NULL);
                } else if (!strcmp(keys[j], "total samples")) {
                    tmp_u64 = strtoull(val, NULL, 10);
                    sdi->driver->config_set(SR_CONF_LIMIT_SAMPLES,
                            g_variant_new_uint64(tmp_u64), sdi, NULL, NULL);
                }  else if (!strcmp(keys[j], "hDiv")) {
                    tmp_u64 = strtoull(val, NULL, 10);
                    sdi->driver->config_set(SR_CONF_TIMEBASE,
                            g_variant_new_uint64(tmp_u64), sdi, NULL, NULL);
                } else if (!strcmp(keys[j], "total probes")) {
					total_probes = strtoull(val, NULL, 10);
					sdi->driver->config_set(SR_CONF_CAPTURE_NUM_PROBES,
                            g_variant_new_uint64(total_probes), sdi, NULL, NULL);
                    channel_type = (mode == DSO) ? SR_CHANNEL_DSO :
                                   (mode == ANALOG) ? SR_CHANNEL_ANALOG : SR_CHANNEL_LOGIC;
					for (p = 0; p < total_probes; p++) {
						snprintf(probename, SR_MAX_PROBENAME_LEN, "%" PRIu64, p);
                        if (!(probe = sr_channel_new(p, channel_type, FALSE,
								probename)))
							return SR_ERR;
                        sdi->channels = g_slist_append(sdi->channels, probe);
					}
				} else if (!strncmp(keys[j], "probe", 5)) {
					if (!sdi)
						continue;
					enabled_probes++;
					tmp_u64 = strtoul(keys[j]+5, NULL, 10);
					/* sr_session_save() */
                    sr_dev_probe_name_set(sdi, tmp_u64, val);
                    sr_dev_probe_enable(sdi, tmp_u64, TRUE);
				} else if (!strncmp(keys[j], "trigger", 7)) {
					probenum = strtoul(keys[j]+7, NULL, 10);
					sr_dev_trigger_set(sdi, probenum, val);
                } else if (!strncmp(keys[j], "enable", 6)) {
                    probenum = strtoul(keys[j]+6, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_EN_CH,
                            g_variant_new_boolean(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "coupling", 8)) {
                    probenum = strtoul(keys[j]+8, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_COUPLING,
                            g_variant_new_byte(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "vDiv", 4)) {
                    probenum = strtoul(keys[j]+4, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_VDIV,
                            g_variant_new_uint64(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "vFactor", 7)) {
                    probenum = strtoul(keys[j]+7, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_FACTOR,
                            g_variant_new_uint64(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "vPos", 4)) {
                    probenum = strtoul(keys[j]+4, NULL, 10);
                    tmp_double = strtod(val, NULL);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_VPOS,
                            g_variant_new_double(tmp_double), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "period", 6)) {
                    probenum = strtoul(keys[j]+6, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_STATUS_PERIOD,
                            g_variant_new_uint64(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "pcnt", 4)) {
                    probenum = strtoul(keys[j]+4, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_STATUS_PCNT,
                            g_variant_new_uint64(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "max", 3)) {
                    probenum = strtoul(keys[j]+3, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_STATUS_MAX,
                            g_variant_new_uint64(tmp_u64), sdi, probe, NULL);
                    }
                } else if (!strncmp(keys[j], "min", 3)) {
                    probenum = strtoul(keys[j]+3, NULL, 10);
                    tmp_u64 = strtoull(val, NULL, 10);
                    if (probenum < g_slist_length(sdi->channels)) {
                        probe = g_slist_nth(sdi->channels, probenum)->data;
                        sdi->driver->config_set(SR_CONF_STATUS_MIN,
                            g_variant_new_uint64(tmp_u64), sdi, probe, NULL);
                    }
                }
			}
			g_strfreev(keys);
		}
		devcnt++;
	}
	g_strfreev(sections);
	g_key_file_free(kf);

	return SR_OK;
}
Exemple #25
0
void
test_group_names (void)
{
  const gchar *data;
  GError *error = NULL;

  /* [ in group name */
  data = "[a[b]\n"
         "key1=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* ] in group name */
  data = "[a]b]\n"
         "key1=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* control char in group name */
  data = "[a\tb]\n"
         "key1=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* empty group name */
  data = "[]\n"
         "key1=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_error (&error, 
	       G_KEY_FILE_ERROR,
	       G_KEY_FILE_ERROR_PARSE);

  /* Unicode in group name */
  data = "[\xc2\xbd]\n"
         "key1=123\n";
  keyfile = g_key_file_new ();
  g_key_file_load_from_data (keyfile, data, -1, 0, &error);
  g_key_file_free (keyfile);  
  check_no_error (error);

  keyfile = g_key_file_new ();
  cut_assert (keyfile);
  g_key_file_set_string (keyfile, "a[b", "key1", "123");
  g_key_file_get_string (keyfile, "a[b", "key1", &error);
  check_error (&error, 
               G_KEY_FILE_ERROR,
               G_KEY_FILE_ERROR_GROUP_NOT_FOUND);  
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a]b", "key1", "123");
  g_key_file_get_string (keyfile, "a]b", "key1", &error);
  check_error (&error, 
               G_KEY_FILE_ERROR,
               G_KEY_FILE_ERROR_GROUP_NOT_FOUND);  
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "a\tb", "key1", "123");
  g_key_file_get_string (keyfile, "a\tb", "key1", &error);
  check_error (&error, 
               G_KEY_FILE_ERROR,
               G_KEY_FILE_ERROR_GROUP_NOT_FOUND);  
  g_key_file_free (keyfile);  

  keyfile = g_key_file_new ();
  g_key_file_set_string (keyfile, "\xc2\xbd", "key1", "123");
  check_string_value (keyfile, "\xc2\xbd", "key1", "123");
  g_key_file_free (keyfile);
  keyfile = NULL;
}
Exemple #26
0
/* This function is taken from libhif
 * Original author: Richard Hughes <richard at hughsie dot com>
 */
static GKeyFile *
lr_load_multiline_key_file(const char *filename,
                           GError **err)
{
    GKeyFile *file = NULL;
    gboolean ret;
    gsize len;
    guint i;
    _cleanup_error_free_ GError *tmp_err = NULL;
    _cleanup_free_ gchar *data = NULL;
    _cleanup_string_free_ GString *string = NULL;
    _cleanup_strv_free_ gchar **lines = NULL;

    // load file
    if (!g_file_get_contents (filename, &data, &len, &tmp_err)) {
        g_set_error(err, LR_REPOCONF_ERROR, LRE_FILE,
                    "Cannot load content of %s: %s",
                    filename, tmp_err->message);
        return NULL;
    }

    // split into lines
    string = g_string_new ("");
    lines = g_strsplit (data, "\n", -1);
    for (i = 0; lines[i] != NULL; i++) {

        // convert tabs to spaces
        g_strdelimit (lines[i], "\t", ' ');

        // if a line starts with whitespace, then append it on
        // the previous line
        if (lines[i][0] == ' ' && string->len > 0) {

            // remove old newline from previous line
            g_string_set_size (string, string->len - 1);

            // whitespace strip this new line
            g_strchug (lines[i]);

            // only add a ';' if we have anything after the '='
            if (string->str[string->len - 1] == '=') {
                g_string_append_printf (string, "%s\n", lines[i]);
            } else {
                g_string_append_printf (string, ";%s\n", lines[i]);
            }
        } else {
            g_string_append_printf (string, "%s\n", lines[i]);
        }
    }

    // remove final newline
    if (string->len > 0)
        g_string_set_size (string, string->len - 1);

    // load modified lines
    file = g_key_file_new ();
    ret = g_key_file_load_from_data (file,
                                     string->str,
                                     -1,
                                     G_KEY_FILE_KEEP_COMMENTS,
                                     &tmp_err);
    if (!ret) {
        g_key_file_free (file);
        g_set_error(err, LR_REPOCONF_ERROR, LRE_KEYFILE,
                    "Cannot parse key file %s: %s", filename, tmp_err->message);
        return NULL;
    }
    return file;
}
Exemple #27
0
static GKeyFile *
_eventd_config_process_config_file(GHashTable *config_files, const gchar *id, GKeyFile *config_file)
{
    gchar *parent_id;

    switch ( libeventd_config_key_file_get_string(config_file, "Event", "Extends", &parent_id) )
    {
    case 1:
        return config_file;
    case -1:
        return NULL;
    case 0:
    break;
    }

    GError *error = NULL;
    if ( ! g_key_file_remove_key(config_file, "Event", "Extends", &error) )
    {
        g_warning("Couldn't clean event file '%s': %s", id, error->message);
        g_clear_error(&error);
        goto fail;
    }

    GKeyFile *parent;
    parent = g_hash_table_lookup(config_files, parent_id);
    if ( parent == NULL )
    {
        g_warning("Event file '%s' has no parent file '%s'", id, parent_id);
        goto fail;
    }

    if ( ( parent = _eventd_config_process_config_file(config_files, parent_id, parent) ) == NULL )
        goto fail;

    GString *merged_data;
    gchar *data;

    data = g_key_file_to_data(parent, NULL, NULL);
    merged_data = g_string_new(data);
    g_free(data);

    data = g_key_file_to_data(config_file, NULL, NULL);
    g_string_append(merged_data, data);
    g_free(data);

    GKeyFile *new_config_file;

    new_config_file = g_key_file_new();
    if ( g_key_file_load_from_data(new_config_file, merged_data->str, -1, G_KEY_FILE_NONE, &error) )
        g_hash_table_insert(config_files, g_strdup(id), new_config_file);
    else
    {
        g_warning("Couldn't merge '%s' and '%s': %s", id, parent_id, error->message);
        g_clear_error(&error);
        g_key_file_free(new_config_file);
        new_config_file = NULL;
    }

    g_string_free(merged_data, TRUE);
    g_free(parent_id);

    return new_config_file;

fail:
    g_free(parent_id);
    return NULL;
}
static GIcon *
xfdesktop_load_icon_from_desktop_file(XfdesktopRegularFileIcon *regular_icon)
{
    gchar *contents, *icon_name;
    gsize length;
    GIcon *gicon = NULL;
    gchar *p;
    GKeyFile *key_file;

    /* try to load the file into memory */
    if(!g_file_load_contents(regular_icon->priv->file, NULL, &contents, &length, NULL, NULL))
        return NULL;

    /* allocate a new key file */
    key_file = g_key_file_new();

    /* try to parse the key file from the contents of the file */
    if(!g_key_file_load_from_data(key_file, contents, length, 0, NULL)) {
        g_free(contents);
        return NULL;
    }

    /* try to determine the custom icon name */
    icon_name = g_key_file_get_string(key_file,
                                      G_KEY_FILE_DESKTOP_GROUP,
                                      G_KEY_FILE_DESKTOP_KEY_ICON,
                                      NULL);

    /* No icon name in the desktop file */
    if(icon_name == NULL) {
        /* free key file and in-memory data */
        g_key_file_free(key_file);
        g_free(contents);
        return NULL;
    }

    /* icon_name is an absolute path, create it as a file icon */
    if(g_file_test(icon_name, G_FILE_TEST_IS_REGULAR)) {
        gicon = g_file_icon_new(g_file_new_for_path(icon_name));
    }

    /* check if the icon theme includes the icon name as-is */
    if(gicon == NULL) {
        if(gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), icon_name)) {
            /* load it */
            gicon = g_themed_icon_new(icon_name);
        }
    }

    /* drop any suffix (e.g. '.png') from themed icons and try to laod that */
    if(gicon == NULL) {
        gchar *tmp_name = NULL;

        p = strrchr(icon_name, '.');
        if(p != NULL)
            tmp_name = g_strndup(icon_name, p - icon_name);

        /* check if the icon theme includes the icon name */
        if(tmp_name && gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), tmp_name)) {
            /* load it */
            gicon = g_themed_icon_new(tmp_name);
        }
        g_free(tmp_name);
    }

    /* maybe it points to a file in the pixmaps folder */
    if(gicon == NULL) {
        gchar *filename = g_build_filename("pixmaps", icon_name, NULL);
        gchar *tmp_name = NULL;

        if(filename)
            tmp_name = xfce_resource_lookup(XFCE_RESOURCE_DATA, filename);

        if(tmp_name)
            gicon = g_file_icon_new(g_file_new_for_path(tmp_name));

        g_free(filename);
        g_free(tmp_name);
    }

    /* free key file and in-memory data */
    g_key_file_free(key_file);
    g_free(contents);
    g_free(icon_name);

    return gicon;
}
Exemple #29
0
static gboolean
prefsFromData (PrettyPrintingOptions* ppo,
               const gchar* contents,
               gssize size,
               GError** error)
{
    GKeyFile *kf;

    g_return_val_if_fail (contents != NULL, FALSE);

    kf = g_key_file_new ();

    if (!g_key_file_load_from_data (kf, contents, size,
             G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS,
             error))
    {
        g_key_file_free (kf);
        return FALSE;
    }

    if (g_key_file_has_key (kf, "pretty-printer", "newLineChars", NULL))
    {
        g_free ((gpointer)ppo->newLineChars);
        ppo->newLineChars = g_key_file_get_string (kf, "pretty-printer", "newLineChars", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "indentChar", NULL))
    {
        ppo->indentChar = (char)g_key_file_get_integer (kf, "pretty-printer", "indentChar", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "indentLength", NULL))
    {
        ppo->indentLength = g_key_file_get_integer (kf, "pretty-printer", "indentLength", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "oneLineText", NULL))
    {
        ppo->oneLineText = g_key_file_get_boolean (kf, "pretty-printer", "oneLineText", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "inlineText", NULL))
    {
        ppo->inlineText = g_key_file_get_boolean (kf, "pretty-printer", "inlineText", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "oneLineComment", NULL))
    {
        ppo->oneLineComment = g_key_file_get_boolean (kf, "pretty-printer", "oneLineComment", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "inlineComment", NULL))
    {
        ppo->inlineComment = g_key_file_get_boolean (kf, "pretty-printer", "inlineComment", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "oneLineCdata", NULL))
    {
        ppo->oneLineCdata = g_key_file_get_boolean (kf, "pretty-printer", "oneLineCdata", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "inlineCdata", NULL))
    {
        ppo->inlineCdata = g_key_file_get_boolean (kf, "pretty-printer", "inlineCdata", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "emptyNodeStripping", NULL))
    {
        ppo->emptyNodeStripping = g_key_file_get_boolean (kf, "pretty-printer", "emptyNodeStripping", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "emptyNodeStrippingSpace", NULL))
    {
        ppo->emptyNodeStrippingSpace = g_key_file_get_boolean (kf, "pretty-printer", "emptyNodeStrippingSpace", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "forceEmptyNodeSplit", NULL))
    {
        ppo->forceEmptyNodeSplit = g_key_file_get_boolean (kf, "pretty-printer", "forceEmptyNodeSplit", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "trimLeadingWhites", NULL))
    {
        ppo->trimLeadingWhites = g_key_file_get_boolean (kf, "pretty-printer", "trimLeadingWhites", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "trimTrailingWhites", NULL))
    {
        ppo->trimTrailingWhites = g_key_file_get_boolean (kf, "pretty-printer", "trimTrailingWhites", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "alignComment", NULL))
    {
        ppo->alignComment = g_key_file_get_boolean (kf, "pretty-printer", "alignComment", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "alignText", NULL))
    {
        ppo->alignText = g_key_file_get_boolean (kf, "pretty-printer", "alignText", error);
    }
    if (g_key_file_has_key (kf, "pretty-printer", "alignCdata", NULL))
    {
        ppo->alignCdata = g_key_file_get_boolean (kf, "pretty-printer", "alignCdata", error);
    }

    g_key_file_free (kf);
    return TRUE;
}
Exemple #30
0
/**
 * ephy_web_application_get_application_list:
 *
 * Gets a list of the currently installed web applications.
 * Free the returned GList with
 * ephy_web_application_free_application_list.
 *
 * Returns: (transfer-full): a #GList of #EphyWebApplication objects
 **/
GList *
ephy_web_application_get_application_list ()
{
  GFileEnumerator *children = NULL;
  GFileInfo *info;
  GList *applications = NULL;
  GFile *dot_dir;

  dot_dir = g_file_new_for_path (ephy_dot_dir ());
  children = g_file_enumerate_children (dot_dir,
                                        "standard::name",
                                        0, NULL, NULL);
  g_object_unref (dot_dir);

  info = g_file_enumerator_next_file (children, NULL, NULL);
  while (info) {
    EphyWebApplication *app;
    const char *name;
    glong prefix_length = g_utf8_strlen (EPHY_WEB_APP_PREFIX, -1);

    name = g_file_info_get_name (info);
    if (g_str_has_prefix (name, EPHY_WEB_APP_PREFIX)) {
      char *profile_dir;
      guint64 created;
      GDate *date;
      char *desktop_file, *desktop_file_path;
      char *contents;
      GFileInfo *desktop_info;

      app = g_slice_new0 (EphyWebApplication);

      profile_dir = g_build_filename (ephy_dot_dir (), name, NULL);
      app->icon_url = g_build_filename (profile_dir, EPHY_WEB_APP_ICON_NAME, NULL);

      desktop_file = g_strconcat (name + prefix_length, ".desktop", NULL);
      desktop_file_path = g_build_filename (profile_dir, desktop_file, NULL);
      app->desktop_file = g_strdup (desktop_file);

      if (g_file_get_contents (desktop_file_path, &contents, NULL, NULL)) {
        char *exec;
        char **strings;
        GKeyFile *key;
        int i;
        GFile *file;

        key = g_key_file_new ();
        g_key_file_load_from_data (key, contents, -1, 0, NULL);
        app->name = g_key_file_get_string (key, "Desktop Entry", "Name", NULL);
        exec = g_key_file_get_string (key, "Desktop Entry", "Exec", NULL);
        strings = g_strsplit (exec, " ", -1);

        for (i = 0; strings[i]; i++);
        app->url = g_strdup (strings[i - 1]);

        g_strfreev (strings);
        g_free (exec);
        g_key_file_free (key);

        file = g_file_new_for_path (desktop_file_path);

        /* FIXME: this should use TIME_CREATED but it does not seem to be working. */
        desktop_info = g_file_query_info (file, G_FILE_ATTRIBUTE_TIME_MODIFIED, 0, NULL, NULL);
        created = g_file_info_get_attribute_uint64 (desktop_info, G_FILE_ATTRIBUTE_TIME_MODIFIED);

        date = g_date_new ();
        g_date_set_time_t (date, (time_t)created);
        g_date_strftime (app->install_date, 127, "%x", date);

        g_date_free (date);
        g_object_unref (file);
        g_object_unref (desktop_info);

        applications = g_list_append (applications, app);
      }

      g_free (contents);
      g_free (desktop_file);
      g_free (profile_dir);
      g_free (desktop_file_path);
    }

    g_object_unref (info);

    info = g_file_enumerator_next_file (children, NULL, NULL);
  }

  g_object_unref (children);

  return applications;
}