Example #1
0
static void
clean_old_logs()
{
#if !defined(_WIN32)
    const gchar *file;
    gchar *config;

    config = ghb_get_user_config_dir(NULL);

    if (g_file_test(config, G_FILE_TEST_IS_DIR))
    {
        GDir *gdir = g_dir_open(config, 0, NULL);
        file = g_dir_read_name(gdir);
        while (file)
        {
            if (strncmp(file, "Activity.log.", 13) == 0)
            {
                gchar *path;
                int fd, lock = 1;
                int pid;

                sscanf(file, "Activity.log.%d", &pid);

                path = g_strdup_printf("%s/ghb.pid.%d", config, pid);
                if (g_file_test(path, G_FILE_TEST_EXISTS))
                {
                    fd = open(path, O_RDWR);
                    if (fd >= 0)
                    {
                        lock = lockf(fd, F_TLOCK, 0);
                    }
                    g_free(path);
                    close(fd);
                    if (lock == 0)
                    {
                        path = g_strdup_printf("%s/%s", config, file);
                        g_unlink(path);
                        g_free(path);
                    }
                }
                else
                {
                    g_free(path);
                    path = g_strdup_printf("%s/%s", config, file);
                    g_unlink(path);
                    g_free(path);
                }
            }
            file = g_dir_read_name(gdir);
        }
        g_dir_close(gdir);
    }
    g_free(config);
#else
    const gchar *file;
    gchar *config;

    config = ghb_get_user_config_dir(NULL);

    if (g_file_test(config, G_FILE_TEST_IS_DIR))
    {
        GDir *gdir = g_dir_open(config, 0, NULL);
        file = g_dir_read_name(gdir);
        while (file)
        {
            if (strncmp(file, "Activity.log.", 13) == 0)
            {
                gchar *path;
                int pid;

                sscanf(file, "Activity.log.%d", &pid);

#if 0
                int fd, lock = 1;

                path = g_strdup_printf("%s/ghb.pid.%d", config, pid);
                if (g_file_test(path, G_FILE_TEST_EXISTS))
                {
                    fd = open(path, O_RDWR);
                    if (fd >= 0)
                    {
                        lock = lockf(fd, F_TLOCK, 0);
                    }
                    g_free(path);
                    close(fd);
                    if (lock == 0)
                    {
                        path = g_strdup_printf("%s/%s", config, file);
                        g_unlink(path);
                        g_free(path);
                    }
                }
                else
#endif
                {
                    //g_free(path);
                    path = g_strdup_printf("%s/%s", config, file);
                    g_unlink(path);
                    g_free(path);
                }
            }
            file = g_dir_read_name(gdir);
        }
        g_dir_close(gdir);
    }
    g_free(config);
#endif
}
static int
generate_os(const int nOS, const int fHeader,
            const int fCompress, const int fGammon, const int nHashSize, bearoffcontext * pbc, FILE * output)
{

    int i;
    int n;
    unsigned short int aus[64];
    xhash h;
    FILE *pfTmp = NULL;
    unsigned int npos;
    char *tmpfile;
    int fTTY = isatty(STDERR_FILENO);

    /* initialise xhash */

    if (XhashCreate(&h, nHashSize / (fGammon ? 128 : 64))) {
        fprintf(stderr, _("Error creating xhash with %d elements\n"), nHashSize / (fGammon ? 128 : 64));
        exit(2);
    }

    XhashStatus(&h);

    /* write header */

    if (fHeader) {
        char sz[41];
        sprintf(sz, "gnubg-OS-%02d-15-%1d-%1d-0xxxxxxxxxxxxxxxxxxx\n", nOS, fGammon, fCompress);
        fputs(sz, output);
    }

    if (fCompress) {
        pfTmp = GetTemporaryFile(NULL, &tmpfile);
        if (pfTmp == NULL)
            exit(2);
    }


    /* loop trough bearoff positions */

    n = Combination(nOS + 15, nOS);
    npos = 0;


    for (i = 0; i < n; ++i) {

        if (i)
            BearOff(i, nOS, aus, fGammon, &h, pbc, fCompress, output, pfTmp);
        else {
            memset(aus, 0, 128);
            aus[0] = 0xFFFF;
            aus[32] = 0xFFFF;
        }
        if (!(i % 100) && fTTY)
            fprintf(stderr, "1:%d/%d        \r", i, n);

        WriteOS(aus, fCompress, fCompress ? pfTmp : output);
        if (fGammon)
            WriteOS(aus + 32, fCompress, fCompress ? pfTmp : output);

        XhashAdd(&h, i, aus, fGammon ? 128 : 64);

        if (fCompress)
            WriteIndex(&npos, aus, fGammon, output);

    }

    if (fCompress) {

        char ac[256];
        size_t n;
        /* write contents of pfTmp to output */

        rewind(pfTmp);

        while (!feof(pfTmp) && (n = fread(ac, 1, sizeof(ac), pfTmp))) {
            if (fwrite(ac, 1, n, output) != n) {
                fprintf(stderr, "failed writing to '%s'\n", tmpfile);
                exit(3);
            }
        }

        if (ferror(pfTmp))
            exit(3);

        fclose(pfTmp);

        g_unlink(tmpfile);

    }
    putc('\n', stderr);

    XhashStatus(&h);

    XhashDestroy(&h);

    return 0;

}
Example #3
0
int
main (int argc, char **argv)
{
  gboolean byteswap = G_BYTE_ORDER != G_LITTLE_ENDIAN;
  GError *error;
  GHashTable *table;
  GDir *dir;
  const gchar *file;
  gchar *srcdir;
  gchar *targetdir = NULL;
  gchar *target;
  gboolean uninstall = FALSE;
  gboolean dry_run = FALSE;
  gchar **schema_files = NULL;
  GOptionContext *context;
  GOptionEntry entries[] = {
    { "targetdir", 0, 0, G_OPTION_ARG_FILENAME, &targetdir, N_("where to store the gschemas.compiled file"), N_("DIRECTORY") },
    { "dry-run", 0, 0, G_OPTION_ARG_NONE, &dry_run, N_("Do not write the gschema.compiled file"), NULL },
    { "uninstall", 0, 0, G_OPTION_ARG_NONE, &uninstall, N_("Do not give error for empty directory"), NULL },
    { "allow-any-name", 0, 0, G_OPTION_ARG_NONE, &allow_any_name, N_("Do not enforce key name restrictions") },

    /* These options are only for use in the gschema-compile tests */
    { "schema-file", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_FILENAME_ARRAY, &schema_files, NULL, NULL },
    { NULL }
  };

  setlocale (LC_ALL, "");

  context = g_option_context_new (N_("DIRECTORY"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
  g_option_context_set_summary (context,
    N_("Compile all GSettings schema files into a schema cache.\n"
       "Schema files are required to have the extension .gschema.xml,\n"
       "and the cache file is called gschemas.compiled."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

  error = NULL;
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      fprintf (stderr, "%s", error->message);
      return 1;
    }

  g_option_context_free (context);

  if (!schema_files && argc != 2)
    {
      fprintf (stderr, _("You should give exactly one directory name\n"));
      return 1;
    }

  srcdir = argv[1];

  if (targetdir == NULL)
    targetdir = srcdir;

  target = g_build_filename (targetdir, "gschemas.compiled", NULL);

  if (!schema_files)
    {
      GPtrArray *files;

      files = g_ptr_array_new ();

      dir = g_dir_open (srcdir, 0, &error);
      if (dir == NULL)
        {
          fprintf (stderr, "%s\n", error->message);
          return 1;
        }

      while ((file = g_dir_read_name (dir)) != NULL)
        {
          if (g_str_has_suffix (file, ".gschema.xml"))
            g_ptr_array_add (files, g_build_filename (srcdir, file, NULL));
        }

      if (files->len == 0)
        {
          if (uninstall)
            {
              g_unlink (target);
              return 0;
            }
          else
            {
              fprintf (stderr, _("No schema files found\n"));
              return 1;
            }
        }
      g_ptr_array_add (files, NULL);

      schema_files = (char **) g_ptr_array_free (files, FALSE);
    }


  if (!(table = parse_gschema_files (schema_files, byteswap, &error)) ||
      (!dry_run && !gvdb_table_write_contents (table, target, byteswap, &error)))
    {
      fprintf (stderr, "%s\n", error->message);
      return 1;
    }

  g_free (target);

  return 0;
}
Example #4
0
static void
install_selected_file_cb(gpointer handle, const char *filename)
{
	/* Try to init the selected file.
	 * If it succeeds, try to make a copy of the file in $USERDIR/plugins/.
	 * If the copy succeeds, unload and destroy the plugin in the original
	 *  location and init+load the new one.
	 * Select the plugin in the plugin list.
	 */
	char *path;
	PurplePlugin *plugin;

	g_return_if_fail(plugins.window);

	plugin = purple_plugin_probe(filename);
	if (!plugin) {
		purple_notify_error(handle, _("Error loading plugin"),
				_("The selected file is not a valid plugin."),
				_("Please open the debug window and try again to see the exact error message."), NULL);
		return;
	}
	if (g_list_find(gnt_tree_get_rows(GNT_TREE(plugins.tree)), plugin)) {
		purple_plugin_load(plugin);
		gnt_tree_set_choice(GNT_TREE(plugins.tree), plugin, purple_plugin_is_loaded(plugin));
		gnt_tree_set_selected(GNT_TREE(plugins.tree), plugin);
		return;
	}

	path = g_build_filename(purple_user_dir(), "plugins", NULL);
	if (purple_build_dir(path, S_IRUSR | S_IWUSR | S_IXUSR) == 0) {
		char *content = NULL;
		gsize length = 0;

		if (g_file_get_contents(filename, &content, &length, NULL)) {
			char *file = g_path_get_basename(filename);
			g_free(path);
			path = g_build_filename(purple_user_dir(), "plugins", file, NULL);
			if (purple_util_write_data_to_file_absolute(path, content, length)) {
				purple_plugin_destroy(plugin);
				plugin = purple_plugin_probe(path);
				if (!plugin) {
					purple_debug_warning("gntplugin", "This is really strange. %s can be loaded, but %s can't!\n",
							filename, path);
					g_unlink(path);
					plugin = purple_plugin_probe(filename);
				}
			} else {
			}
		}
		g_free(content);
	}
	g_free(path);

	purple_plugin_load(plugin);

	if (plugin->info->type == PURPLE_PLUGIN_LOADER) {
		GList *cur;
		for (cur = PURPLE_PLUGIN_LOADER_INFO(plugin)->exts; cur != NULL;
				cur = cur->next)
			purple_plugins_probe(cur->data);
		return;
	}

	if (plugin->info->type != PURPLE_PLUGIN_STANDARD ||
			(plugin->info->flags & PURPLE_PLUGIN_FLAG_INVISIBLE) ||
			plugin->error)
		return;

	gnt_tree_add_choice(GNT_TREE(plugins.tree), plugin,
			gnt_tree_create_row(GNT_TREE(plugins.tree), plugin->info->name), NULL, NULL);
	gnt_tree_set_choice(GNT_TREE(plugins.tree), plugin, purple_plugin_is_loaded(plugin));
	gnt_tree_set_row_flags(GNT_TREE(plugins.tree), plugin, GNT_TEXT_FLAG_BOLD);
	gnt_tree_set_selected(GNT_TREE(plugins.tree), plugin);
}
static void
query_dir (const char *dirname)
{
  GString *data;
  GDir *dir;
  const char *name;
  char *cachename;
  char **(* query)  (void);
  GError *error;
  int i;

  if (!g_module_supported ())
    return;

  error = NULL;
  dir = g_dir_open (dirname, 0, &error);
  if (!dir)
    {
      g_printerr ("Unable to open directory %s: %s\n", dirname, error->message);
      g_error_free (error);
      return;
    }

  data = g_string_new ("");

  while ((name = g_dir_read_name (dir)))
    {
      GModule *module;
      gchar     *path;
      char **extension_points;

      if (!is_valid_module_name (name))
	continue;

      path = g_build_filename (dirname, name, NULL);
      module = g_module_open (path, G_MODULE_BIND_LAZY | G_MODULE_BIND_LOCAL);
      g_free (path);

      if (module)
	{
	  g_module_symbol (module, "g_io_module_query", (gpointer) &query);

	  if (query)
	    {
	      extension_points = query ();

	      if (extension_points)
		{
		  g_string_append_printf (data, "%s: ", name);

		  for (i = 0; extension_points[i] != NULL; i++)
		    g_string_append_printf (data, "%s%s", i == 0 ? "" : ",", extension_points[i]);

		  g_string_append (data, "\n");
		  g_strfreev (extension_points);
		}
	    }

	  g_module_close (module);
	}
    }

  g_dir_close (dir);

  cachename = g_build_filename (dirname, "giomodule.cache", NULL);

  if (data->len > 0)
    {
      error = NULL;

      if (!g_file_set_contents (cachename, data->str, data->len, &error))
        {
          g_printerr ("Unable to create %s: %s\n", cachename, error->message);
          g_error_free (error);
        }
    }
  else
    {
      if (g_unlink (cachename) != 0 && errno != ENOENT)
        g_printerr ("Unable to unlink %s: %s\n", cachename, g_strerror (errno));
    }

  g_string_free (data, TRUE);
}
Example #6
0
// FIXME: we can't rely on darktable to avoid file overwriting -- it doesn't know the filename (extension).
int write_image (dt_imageio_module_data_t *ppm, const char *filename, const void *in, void *exif, int exif_len, int imgid)
{
  int status = 1;
  char *sourcefile = NULL;
  char *targetfile = NULL;
  char *xmpfile = NULL;
  char *content = NULL;
  FILE *fin = NULL;
  FILE *fout = NULL;
  sqlite3_stmt *stmt;

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select folder, filename from images, film_rolls where images.id = ?1 and film_id = film_rolls.id;", -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid);

  if(sqlite3_step(stmt) != SQLITE_ROW)
    goto END;

  char *sfolder    = (char*)sqlite3_column_text(stmt, 0);
  char *sfilename  = (char*)sqlite3_column_text(stmt, 1);
  sourcefile = g_build_filename(sfolder, sfilename, NULL);
  char *extension  = g_strrstr(sourcefile, ".");
  if(extension == NULL)
    goto END;
  targetfile = g_strconcat(filename, ++extension, NULL);

  if(!strcmp(sourcefile, targetfile))
    goto END;

  fin = fopen(sourcefile, "rb");
  fout = fopen(targetfile, "wb");
  if(fin == NULL || fout == NULL)
    goto END;

  fseek(fin,0,SEEK_END);
  size_t end = ftell(fin);
  rewind(fin);

  content = (char *)g_malloc_n(end, sizeof(char));
  if(content == NULL)
    goto END;
  if(fread(content,sizeof(char),end,fin) != end)
    goto END;
  if(fwrite(content,sizeof(char),end,fout) != end)
    goto END;

  // we got a copy of the file, now write the xmp data
  xmpfile = g_strconcat(targetfile, ".xmp", NULL);
  if(dt_exif_xmp_write (imgid, xmpfile) != 0)
  {
    // something went wrong, unlink the copied image.
    g_unlink(targetfile);
    goto END;
  }

  status = 0;
END:
  g_free(sourcefile);
  g_free(targetfile);
  g_free(xmpfile);
  g_free(content);
  if(fin)
    fclose(fin);
  if(fout)
    fclose(fout);
  return status;
}
static void
populate_options_real (PpOptionsDialog *dialog)
{
  GtkTreeSelection *selection;
  GtkTreeModel     *model;
  GtkTreeView      *treeview;
  GtkTreeIter       iter;
  ppd_file_t       *ppd_file;
  GtkWidget        *notebook;
  GtkWidget        *grid;
  GtkWidget        *general_tab_grid = tab_grid_new ();
  GtkWidget        *page_setup_tab_grid = tab_grid_new ();
  GtkWidget        *installable_options_tab_grid = tab_grid_new ();
  GtkWidget        *job_tab_grid = tab_grid_new ();
  GtkWidget        *image_quality_tab_grid = tab_grid_new ();
  GtkWidget        *color_tab_grid = tab_grid_new ();
  GtkWidget        *finishing_tab_grid = tab_grid_new ();
  GtkWidget        *advanced_tab_grid = tab_grid_new ();
  GtkWidget        *widget;
  gint              i, j;

  widget = (GtkWidget*)
    gtk_builder_get_object (dialog->builder, "options-spinner");
  gtk_widget_hide (widget);
  gtk_spinner_stop (GTK_SPINNER (widget));

  widget = (GtkWidget*)
    gtk_builder_get_object (dialog->builder, "progress-label");
  gtk_widget_hide (widget);

  treeview = (GtkTreeView *)
    gtk_builder_get_object (dialog->builder, "options-categories-treeview");

  notebook = (GtkWidget *)
    gtk_builder_get_object (dialog->builder, "options-notebook");

  if (dialog->ipp_attributes)
    {
      /* Add number-up option to Page Setup tab */
      ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes,
                                           "number-up-supported"),
                      g_hash_table_lookup (dialog->ipp_attributes,
                                           "number-up-default"),
                      "number-up",
                      /* Translators: This option sets number of pages printed on one sheet */
                      _("Pages per side"),
                      dialog->printer_name,
                      page_setup_tab_grid,
                      dialog->sensitive);

      /* Add sides option to Page Setup tab */
      ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes,
                                           "sides-supported"),
                      g_hash_table_lookup (dialog->ipp_attributes,
                                           "sides-default"),
                      "sides",
                      /* Translators: This option sets whether to print on both sides of paper */
                      _("Two-sided"),
                      dialog->printer_name,
                      page_setup_tab_grid,
                      dialog->sensitive);

      /* Add orientation-requested option to Page Setup tab */
      ipp_option_add (g_hash_table_lookup (dialog->ipp_attributes,
                                           "orientation-requested-supported"),
                      g_hash_table_lookup (dialog->ipp_attributes,
                                           "orientation-requested-default"),
                      "orientation-requested",
                      /* Translators: This option sets orientation of print (portrait, landscape...) */
                      _("Orientation"),
                      dialog->printer_name,
                      page_setup_tab_grid,
                      dialog->sensitive);
    }

  if (dialog->destination && dialog->ppd_filename)
    {
      ppd_file = ppdOpenFile (dialog->ppd_filename);
      ppdLocalize (ppd_file);

      if (ppd_file)
        {
          ppdMarkDefaults (ppd_file);
          cupsMarkOptions (ppd_file,
                           dialog->destination->num_options,
                           dialog->destination->options);

          for (i = 0; i < ppd_file->num_groups; i++)
            {
              for (j = 0; j < ppd_file->groups[i].num_options; j++)
                {
                  grid = NULL;

                  if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                       color_group_whitelist))
                    grid = color_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            image_quality_group_whitelist))
                    grid = image_quality_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            job_group_whitelist))
                    grid = job_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            finishing_group_whitelist))
                    grid = finishing_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            installable_options_group_whitelist))
                    grid = installable_options_tab_grid;
                  else if (STRING_IN_TABLE (ppd_file->groups[i].name,
                                            page_setup_group_whitelist))
                    grid = page_setup_tab_grid;

                  if (!STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                        ppd_option_blacklist))
                    {
                      if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                    color_option_whitelist))
                        grid = color_tab_grid;
                      else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                         image_quality_option_whitelist))
                        grid = image_quality_tab_grid;
                      else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                         finishing_option_whitelist))
                        grid = finishing_tab_grid;
                      else if (!grid && STRING_IN_TABLE (ppd_file->groups[i].options[j].keyword,
                                                         page_setup_option_whitelist))
                        grid = page_setup_tab_grid;

                      if (!grid)
                        grid = advanced_tab_grid;

                      ppd_option_add (ppd_file->groups[i].options[j],
                                      dialog->printer_name,
                                      grid,
                                      dialog->sensitive);
                    }
                }
            }

          ppdClose (ppd_file);
        }
    }

  dialog->ppd_filename_set = FALSE;
  if (dialog->ppd_filename)
    {
      g_unlink (dialog->ppd_filename);
      g_free (dialog->ppd_filename);
      dialog->ppd_filename = NULL;
    }

  dialog->destination_set = FALSE;
  if (dialog->destination)
    {
      cupsFreeDests (1, dialog->destination);
      dialog->destination = NULL;
    }

  dialog->ipp_attributes_set = FALSE;
  if (dialog->ipp_attributes)
    {
      g_hash_table_unref (dialog->ipp_attributes);
      dialog->ipp_attributes = NULL;
    }

  /* Translators: "General" tab contains general printer options */
  tab_add (C_("Printer Option Group", "General"), notebook, treeview, general_tab_grid);

  /* Translators: "Page Setup" tab contains settings related to pages (page size, paper source, etc.) */
  tab_add (C_("Printer Option Group", "Page Setup"), notebook, treeview, page_setup_tab_grid);

  /* Translators: "Installable Options" tab contains settings of presence of installed options (amount of RAM, duplex unit, etc.) */
  tab_add (C_("Printer Option Group", "Installable Options"), notebook, treeview, installable_options_tab_grid);

  /* Translators: "Job" tab contains settings for jobs */
  tab_add (C_("Printer Option Group", "Job"), notebook, treeview, job_tab_grid);

  /* Translators: "Image Quality" tab contains settings for quality of output print (e.g. resolution) */
  tab_add (C_("Printer Option Group", "Image Quality"), notebook, treeview, image_quality_tab_grid);

  /* Translators: "Color" tab contains color settings (e.g. color printing) */
  tab_add (C_("Printer Option Group", "Color"), notebook, treeview, color_tab_grid);

  /* Translators: "Finishing" tab contains finishing settings (e.g. booklet printing) */
  tab_add (C_("Printer Option Group", "Finishing"), notebook, treeview, finishing_tab_grid);

  /* Translators: "Advanced" tab contains all others settings */
  tab_add (C_("Printer Option Group", "Advanced"), notebook, treeview, advanced_tab_grid);

  gtk_widget_show_all (GTK_WIDGET (notebook));

  /* Select the first option group */
  if ((selection = gtk_tree_view_get_selection (treeview)) != NULL)
    {
      g_signal_connect (selection,
                        "changed",
                        G_CALLBACK (category_selection_changed_cb), dialog);

      if ((model = gtk_tree_view_get_model (treeview)) != NULL &&
          gtk_tree_model_get_iter_first (model, &iter))
        gtk_tree_selection_select_iter (selection, &iter);
    }

  dialog->populating_dialog = FALSE;
  if (dialog->response != GTK_RESPONSE_NONE)
    {
      dialog->user_callback (GTK_DIALOG (dialog->dialog), dialog->response, dialog->user_data);
    }
}
gboolean
ews_oab_decompress_patch (const gchar *filename, const gchar *orig_filename,
			  const gchar *output_filename, GError **error)
{
	LzxPatchHeader *lzx_h = NULL;
	guint total_decomp_size = 0;
	FILE *input = NULL, *output = NULL, *orig_input = NULL;
	gboolean ret = TRUE;
	GError *err = NULL;

	input = fopen (filename, "rb");
	if (!input) {
		g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "unable to open the input file");
		ret = FALSE;
		goto exit;
	}

	orig_input = fopen (orig_filename, "rb");
	if (!orig_input) {
		g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "unable to open the reference input file");
		ret = FALSE;
		goto exit;
	}

	output = fopen (output_filename, "wb");
	if (!output) {
		g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "unable to open the output file");
		ret = FALSE;
		goto exit;
	}

	lzx_h = read_patch_headers (input, &err);
	if (!lzx_h) {
		ret = FALSE;
		goto exit;
	}

	/* TODO decompressing multiple lzx_blocks has not been tested yet. Will need to get a setup and test it. */
	do {
		LzxPatchBlockHeader *lzx_b;
		struct lzxd_stream *lzs;
		goffset offset;
		guint ref_size, window_bits;

		lzx_b = read_patch_block_header (input, &err);
		if (err) {
			printf("err block header\n");
			ret = FALSE;
			goto exit;
		}

		/* note the file offset */
		offset = ftell(input);

		/* The window size should be the smallest power of two
		   between 2^17 and 2^25 that is greater than or equal
		   to the sum of the size of the reference data
		   rounded up to a multiple of 32768 and the size of
		   the subject data. */
		ref_size = (lzx_b->source_size + 32767) & ~32767;
		window_bits = g_bit_nth_msf(ref_size + lzx_b->target_size - 1, -1) + 1;

		if (window_bits < 17)
			window_bits = 17;
		else if (window_bits > 25)
			window_bits = 25;

		lzs = ews_lzxd_init (input, output, window_bits,
				 0, 4096, lzx_b->target_size, 1);
		if (!lzs) {
			g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "decompression failed (lzxd_init)");
			ret = FALSE;
			goto exit;
		}
		if (ews_lzxd_set_reference_data(lzs, orig_input, lzx_b->source_size)) {
			g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "decompression failed (lzxd_set_reference_data)");
			ret = FALSE;
			goto exit;
		}
		if (ews_lzxd_decompress (lzs, lzs->length) != LZX_ERR_OK) {
			g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "decompression failed (lzxd_decompress)");
			ret = FALSE;
			goto exit;
		}

		/* Set the fp to beggining of next block. This is a HACK, looks like decompress reads beyond the block.
		 * Since we can identify the next block start from block header, we just reset the offset */
		offset += lzx_b->patch_size;
		fseek (input, offset, SEEK_SET);

		total_decomp_size += lzx_b->target_size;
		g_free (lzx_b);
	} while (total_decomp_size < lzx_h->target_size);

exit:
	if (input)
		fclose (input);

	if (orig_input)
		fclose (orig_input);

	if (output)
		fclose (output);

	if (err) {
		ret = FALSE;
		g_propagate_error (error, err);
		g_unlink (output_filename);
	}

	g_free (lzx_h);

	return ret;
}
Example #9
0
GList *
e_composer_find_orphans (GQueue *registry,
                         GError **error)
{
	GDir *dir;
	const gchar *dirname;
	const gchar *basename;
	GList *orphans = NULL;

	g_return_val_if_fail (registry != NULL, NULL);

	dirname = e_get_user_data_dir ();
	dir = g_dir_open (dirname, 0, error);
	if (dir == NULL)
		return NULL;

	/* Scan the user data directory for snapshot files. */
	while ((basename = g_dir_read_name (dir)) != NULL) {
		const gchar *errmsg;
		gchar *filename;
		struct stat st;

		/* Is this a snapshot file? */
		if (!g_str_has_prefix (basename, SNAPSHOT_FILE_PREFIX))
			continue;

		/* Is this an orphaned snapshot file? */
		if (composer_registry_lookup (registry, basename) != NULL)
			continue;

		filename = g_build_filename (dirname, basename, NULL);

		/* Try to examine the snapshot file.  Failure here
		 * is non-fatal; just emit a warning and move on. */
		errno = 0;
		if (g_stat (filename, &st) < 0) {
			errmsg = g_strerror (errno);
			g_warning ("%s: %s", filename, errmsg);
			g_free (filename);
			continue;
		}

		/* If the file is empty, delete it.  Failure here
		 * is non-fatal; just emit a warning and move on. */
		if (st.st_size == 0) {
			errno = 0;
			if (g_unlink (filename) < 0) {
				errmsg = g_strerror (errno);
				g_warning ("%s: %s", filename, errmsg);
			}
			g_free (filename);
			continue;
		}

		orphans = g_list_prepend (
			orphans, g_file_new_for_path (filename));

		g_free (filename);
	}

	g_dir_close (dir);

	return g_list_reverse (orphans);
}
Example #10
0
int
e_xml_save_file (const char *filename, xmlDocPtr doc)
{
	char *filesave;
	xmlChar *xmlbuf;
	size_t n, written = 0;
	int ret, fd, size;
	int errnosave;
	ssize_t w;
	gchar *dirname = g_path_get_dirname (filename);
	gchar *basename = g_path_get_basename (filename);
	gchar *savebasename = g_strconcat (".#", basename, NULL);

	g_free (basename);
	filesave = g_build_filename (dirname, savebasename, NULL);
	g_free (savebasename);
	g_free (dirname);

	fd = g_open (filesave, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
	if (fd == -1) {
		g_free (filesave);
		return -1;
	}

	xmlDocDumpFormatMemory (doc, &xmlbuf, &size, TRUE);
	if (size <= 0) {
		close (fd);
		g_unlink (filesave);
		g_free (filesave);
		errno = ENOMEM;
		return -1;
	}

	n = (size_t) size;
	do {
		do {
			w = write (fd, xmlbuf + written, n - written);
		} while (w == -1 && errno == EINTR);

		if (w > 0)
			written += w;
	} while (w != -1 && written < n);

	xmlFree (xmlbuf);

	if (written < n || fsync (fd) == -1) {
		errnosave = errno;
		close (fd);
		g_unlink (filesave);
		g_free (filesave);
		errno = errnosave;
		return -1;
	}

	while ((ret = close (fd)) == -1 && errno == EINTR)
		;

	if (ret == -1) {
		g_free (filesave);
		return -1;
	}

	if (g_rename (filesave, filename) == -1) {
		errnosave = errno;
		g_unlink (filesave);
		g_free (filesave);
		errno = errnosave;
		return -1;
	}
	g_free (filesave);

	return 0;
}
Example #11
0
gboolean
ews_oab_decompress_full (const gchar *filename, const gchar *output_filename,
			 GError **error)
{
	LzxHeader *lzx_h = NULL;
	guint total_decomp_size = 0;
	FILE *input, *output = NULL;
	gboolean ret = TRUE;
	GError *err = NULL;

	input = fopen (filename, "rb");
	if (!input) {
		g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "unable to open the input file");
		ret = FALSE;
		goto exit;
	}

	output = fopen (output_filename, "wb");
	if (!output) {
		g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "unable to open the output file");
		ret = FALSE;
		goto exit;
	}

	lzx_h = read_headers (input, &err);
	if (!lzx_h) {
		ret = FALSE;
		goto exit;
	}

	/* TODO decompressing multiple lzx_blocks has not been tested yet. Will need to get a setup and test it. */
	do {
		LzxBlockHeader *lzx_b;
		struct lzxd_stream *lzs;
		goffset offset;

		lzx_b = read_block_header (input, &err);
		if (err) {
			ret = FALSE;
			goto exit;
		}

		/* note the file offset */
		offset = ftell (input);

		/* lzx_b points to 1, write it directly to file */
		if (lzx_b->flags == 0) {
			gchar *buffer = g_malloc0 (lzx_b->ucomp_size);

			if (!(fread (buffer, 1, lzx_b->ucomp_size, input) == lzx_b->ucomp_size &&
				fwrite (buffer, 1, lzx_b->ucomp_size, output) == lzx_b->ucomp_size)) {
				g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "failed to write data in output file");
				g_free (buffer);
				ret = FALSE;
				goto exit;
			}
			g_free (buffer);
		} else {
			/* The window size should be the smallest power of two between 2^17 and 2^25 that is
			   greater than or equal to the sum of the size of the reference data rounded up to
			   a multiple of 32768 and the size of the subject data. Since we have no reference
			   data, forget that and the rounding. Just the smallest power of two which is large
			   enough to cover the subject data (lzx_b->ucomp_size). */

			guint window_bits = g_bit_nth_msf(lzx_b->ucomp_size - 1, -1) + 1;

			if (window_bits < 17)
				window_bits = 17;
			else if (window_bits > 25)
				window_bits = 25;

			lzs = ews_lzxd_init (input, output, window_bits,
					 0, 4096, lzx_b->ucomp_size, 1);
			if (!lzs) {
				g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "decompression failed (lzxd_init)");
				ret = FALSE;
				goto exit;
			}
			if (ews_lzxd_decompress (lzs, lzx_b->ucomp_size) != LZX_ERR_OK) {
				g_set_error_literal (&err, g_quark_from_string ("lzx"), 1, "decompression failed (lzxd_decompress)");
				ret = FALSE;
				goto exit;
			}
		}

		/* Set the fp to beggining of next block. This is a HACK, looks like decompress reads beyond the block.
		 * Since we can identify the next block start from block header, we just reset the offset */
		offset += lzx_b->comp_size;
		fseek (input, offset, SEEK_SET);

		total_decomp_size += lzx_b->ucomp_size;
		g_free (lzx_b);
	} while (total_decomp_size < lzx_h->target_size);

exit:
	if (input)
		fclose (input);

	if (output)
		fclose (output);

	if (err) {
		ret = FALSE;
		g_propagate_error (error, err);
		g_unlink (output_filename);
	}

	g_free (lzx_h);

	return ret;
}
Example #12
0
/* make sure our script gets called with the right parameters */
static void
test_pb_utils_install_plugins_do_callout (const gchar * const *details,
    GstInstallPluginsContext * ctx, const gchar * script,
    GstInstallPluginsReturn expected_result)
{
#ifdef G_OS_UNIX
  GstInstallPluginsReturn ret;
  GError *err = NULL;
  gchar *path;

  path = g_strdup_printf ("%s/gst-plugins-base-unit-test-helper.%s.%lu",
      g_get_tmp_dir (), (g_get_user_name ())? g_get_user_name () : "nobody",
      (gulong) getpid ());

  if (!g_file_set_contents (path, script, -1, &err)) {
    GST_DEBUG ("Failed to write test script to %s: %s", path, err->message);
    g_error_free (err);
    goto done;
  }

  if (chmod (path, S_IRUSR | S_IWUSR | S_IXUSR) != 0) {
    GST_DEBUG ("Could not set mode u+rwx on '%s'", path);
    goto done;
  }

  /* test gst_install_plugins_supported() I */
  g_setenv ("GST_INSTALL_PLUGINS_HELPER", "/i/do/not/ex.ist!", 1);
  fail_if (gst_install_plugins_supported ());

  GST_LOG ("setting GST_INSTALL_PLUGINS_HELPER to '%s'", path);
  g_setenv ("GST_INSTALL_PLUGINS_HELPER", path, 1);

  /* test gst_install_plugins_supported() II */
  fail_unless (gst_install_plugins_supported ());

  /* test sync callout */
  ret = gst_install_plugins_sync (details, ctx);
  fail_unless (ret == GST_INSTALL_PLUGINS_HELPER_MISSING ||
      ret == expected_result,
      "gst_install_plugins_sync() failed with unexpected ret %d, which is "
      "neither HELPER_MISSING nor %d", ret, expected_result);

  /* test async callout */
  marker = -333;
  ret = gst_install_plugins_async (details, ctx, result_cb,
      (gpointer) & marker);
  fail_unless (ret == GST_INSTALL_PLUGINS_HELPER_MISSING ||
      ret == GST_INSTALL_PLUGINS_STARTED_OK,
      "gst_install_plugins_async() failed with unexpected ret %d", ret);
  if (ret == GST_INSTALL_PLUGINS_STARTED_OK) {
    while (marker == -333) {
      g_usleep (500);
      g_main_context_iteration (NULL, FALSE);
    }
    /* and check that the callback was called with the expected code */
    fail_unless_equals_int (marker, expected_result);
  }

done:

  g_unlink (path);
  g_free (path);
#endif /* G_OS_UNIX */
}
Example #13
0
/* Creates a list of global tags. Ideally, this should be created once during
 installations so that all users can use the same file. This is because a full
 scale global tag list can occupy several megabytes of disk space.
 @param pre_process The pre-processing command. This is executed via system(),
 so you can pass stuff like 'gcc -E -dD -P `gnome-config --cflags gnome`'.
 @param includes Include files to process. Wildcards such as '/usr/include/a*.h'
 are allowed.
 @param tags_file The file where the tags will be stored.
 @param lang The language to use for the tags file.
 @return TRUE on success, FALSE on failure.
*/
gboolean tm_workspace_create_global_tags(const char *pre_process, const char **includes,
	int includes_count, const char *tags_file, TMParserType lang)
{
#ifdef HAVE_GLOB_H
	glob_t globbuf;
	size_t idx_glob;
#endif
	int idx_inc;
	char *command;
	guint i;
	FILE *fp;
	TMSourceFile *source_file;
	GPtrArray *tags_array;
	GHashTable *includes_files_hash;
	GList *includes_files = NULL;
	gchar *temp_file = create_temp_file("tmp_XXXXXX.cpp");
	gchar *temp_file2 = create_temp_file("tmp_XXXXXX.cpp");

	if (NULL == temp_file || NULL == temp_file2 ||
		NULL == (fp = g_fopen(temp_file, "w")))
	{
		g_free(temp_file);
		g_free(temp_file2);
		return FALSE;
	}

	includes_files_hash = g_hash_table_new_full (tm_file_inode_hash,
												 g_direct_equal,
												 NULL, g_free);

#ifdef HAVE_GLOB_H
	globbuf.gl_offs = 0;

	if (includes[0][0] == '"')	/* leading \" char for glob matching */
	for(idx_inc = 0; idx_inc < includes_count; idx_inc++)
	{
		size_t dirty_len = strlen(includes[idx_inc]);
		char *clean_path = g_malloc(dirty_len - 1);

		strncpy(clean_path, includes[idx_inc] + 1, dirty_len - 1);
		clean_path[dirty_len - 2] = 0;

#ifdef TM_DEBUG
		g_message ("[o][%s]\n", clean_path);
#endif
		glob(clean_path, 0, NULL, &globbuf);

#ifdef TM_DEBUG
		g_message ("matches: %d\n", globbuf.gl_pathc);
#endif

		for(idx_glob = 0; idx_glob < globbuf.gl_pathc; idx_glob++)
		{
#ifdef TM_DEBUG
			g_message (">>> %s\n", globbuf.gl_pathv[idx_glob]);
#endif
			if (!g_hash_table_lookup(includes_files_hash,
									globbuf.gl_pathv[idx_glob]))
			{
				char* file_name_copy = strdup(globbuf.gl_pathv[idx_glob]);
				g_hash_table_insert(includes_files_hash, file_name_copy,
									file_name_copy);
#ifdef TM_DEBUG
				g_message ("Added ...\n");
#endif
			}
		}
		globfree(&globbuf);
		g_free(clean_path);
  	}
  	else
#endif
	/* no glob support or globbing not wanted */
	for(idx_inc = 0; idx_inc < includes_count; idx_inc++)
	{
		if (!g_hash_table_lookup(includes_files_hash,
									includes[idx_inc]))
		{
			char* file_name_copy = strdup(includes[idx_inc]);
			g_hash_table_insert(includes_files_hash, file_name_copy,
								file_name_copy);
		}
  	}

	/* Checks for duplicate file entries which would case trouble */
	g_hash_table_foreach(includes_files_hash, tm_move_entries_to_g_list,
						 &includes_files);

	includes_files = g_list_reverse (includes_files);

#ifdef TM_DEBUG
	g_message ("writing out files to %s\n", temp_file);
#endif
	if (pre_process != NULL)
		write_includes_file(fp, includes_files);
	else
		append_to_temp_file(fp, includes_files);

	g_list_free (includes_files);
	g_hash_table_destroy(includes_files_hash);
	includes_files_hash = NULL;
	includes_files = NULL;
	fclose(fp);

	if (pre_process != NULL)
	{
		gint ret;
		gchar *tmp_errfile = create_temp_file("tmp_XXXXXX");
		gchar *errors = NULL;
		command = g_strdup_printf("%s %s >%s 2>%s",
								pre_process, temp_file, temp_file2, tmp_errfile);
#ifdef TM_DEBUG
		g_message("Executing: %s", command);
#endif
		ret = system(command);
		g_free(command);
		g_unlink(temp_file);
		g_free(temp_file);
		g_file_get_contents(tmp_errfile, &errors, NULL, NULL);
		if (errors && *errors)
			g_printerr("%s", errors);
		g_free(errors);
		g_unlink(tmp_errfile);
		g_free(tmp_errfile);
		if (ret == -1)
		{
			g_unlink(temp_file2);
			return FALSE;
		}
	}
	else
	{
		/* no pre-processing needed, so temp_file2 = temp_file */
		g_unlink(temp_file2);
		g_free(temp_file2);
		temp_file2 = temp_file;
		temp_file = NULL;
	}
	source_file = tm_source_file_new(temp_file2, tm_source_file_get_lang_name(lang));
	update_source_file(source_file, NULL, 0, FALSE, FALSE);
	if (NULL == source_file)
	{
		g_unlink(temp_file2);
		return FALSE;
	}
	g_unlink(temp_file2);
	g_free(temp_file2);
	if (0 == source_file->tags_array->len)
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	tags_array = tm_tags_extract(source_file->tags_array, tm_tag_max_t);
	if ((NULL == tags_array) || (0 == tags_array->len))
	{
		if (tags_array)
			g_ptr_array_free(tags_array, TRUE);
		tm_source_file_free(source_file);
		return FALSE;
	}
	if (FALSE == tm_tags_sort(tags_array, global_tags_sort_attrs, TRUE, FALSE))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	if (NULL == (fp = g_fopen(tags_file, "w")))
	{
		tm_source_file_free(source_file);
		return FALSE;
	}
	fprintf(fp, "# format=tagmanager\n");
	for (i = 0; i < tags_array->len; ++i)
	{
		tm_tag_write(TM_TAG(tags_array->pdata[i]), fp, tm_tag_attr_type_t
		  | tm_tag_attr_scope_t | tm_tag_attr_arglist_t | tm_tag_attr_vartype_t
		  | tm_tag_attr_pointer_t);
	}
	fclose(fp);
	tm_source_file_free(source_file);
	g_ptr_array_free(tags_array, TRUE);
	return TRUE;
}
Example #14
0
static void
gwy_recent_file_update_thumbnail(GwyRecentFile *rf,
                                 GwyContainer *data,
                                 gint hint,
                                 GdkPixbuf *use_this_pixbuf)
{
    GwyDataField *dfield;
    GdkPixbuf *pixbuf;
    GStatBuf st;
    gchar *fnm;
    GwySIUnit *siunit;
    GwySIValueFormat *vf;
    gdouble xreal, yreal;
    gchar str_mtime[22];
    gchar str_size[22];
    gchar str_width[22];
    gchar str_height[22];
    GError *err = NULL;
    GQuark quark;
    gint id;

    g_return_if_fail(GWY_CONTAINER(data));

    if (use_this_pixbuf) {
        /* If we are given a pixbuf, hint must be the ultimate channel id.
         * We also ignore the thnumbnail state then. */
        g_return_if_fail(GDK_IS_PIXBUF(use_this_pixbuf));
        id = hint;
        pixbuf = g_object_ref(use_this_pixbuf);
    }
    else {
        pixbuf = NULL;
        id = gwy_recent_file_find_some_channel(data, hint);

        if (rf->file_state == FILE_STATE_UNKNOWN)
            gwy_app_recent_file_try_load_thumbnail(rf);
    }

    /* Find channel with the lowest id not smaller than hint */
    if (id == G_MAXINT) {
        gwy_debug("There is no channel in the file, cannot make thumbnail.");
        return;
    }

    if (g_stat(rf->file_sys, &st) != 0) {
        g_warning("File <%s> was just loaded or saved, but it doesn't seem to "
                  "exist any more: %s",
                  rf->file_utf8, g_strerror(errno));
        return;
    }

    if ((gulong)rf->file_mtime == (gulong)st.st_mtime)
        return;

    quark = gwy_app_get_data_key_for_id(id);
    dfield = GWY_DATA_FIELD(gwy_container_get_object(data, quark));
    g_return_if_fail(GWY_IS_DATA_FIELD(dfield));
    rf->file_mtime = st.st_mtime;
    rf->file_size = st.st_size;
    rf->image_width = gwy_data_field_get_xres(dfield);
    rf->image_height = gwy_data_field_get_yres(dfield);
    xreal = gwy_data_field_get_xreal(dfield);
    yreal = gwy_data_field_get_yreal(dfield);
    siunit = gwy_data_field_get_si_unit_xy(dfield);
    vf = gwy_si_unit_get_format(siunit, GWY_SI_UNIT_FORMAT_VFMARKUP,
                                sqrt(xreal*yreal), NULL);
    g_free(rf->image_real_size);
    rf->image_real_size
        = g_strdup_printf("%.*f×%.*f%s%s",
                          vf->precision, xreal/vf->magnitude,
                          vf->precision, yreal/vf->magnitude,
                          (vf->units && *vf->units) ? " " : "", vf->units);
    rf->file_state = FILE_STATE_OK;
    gwy_si_unit_value_format_free(vf);

    if (g_str_has_prefix(rf->file_sys, gwy_recent_file_thumbnail_dir())) {
        gchar c;

        c = rf->file_sys[strlen(gwy_recent_file_thumbnail_dir())];
        if (!c || G_IS_DIR_SEPARATOR(c))
            return;
    }

    if (!pixbuf)
        pixbuf = gwy_app_get_channel_thumbnail(data, id,
                                               TMS_NORMAL_THUMB_SIZE,
                                               TMS_NORMAL_THUMB_SIZE);

    g_snprintf(str_mtime, sizeof(str_mtime), "%lu", rf->file_mtime);
    g_snprintf(str_size, sizeof(str_size), "%lu", rf->file_size);
    g_snprintf(str_width, sizeof(str_width), "%d", rf->image_width);
    g_snprintf(str_height, sizeof(str_height), "%d", rf->image_height);

    /* invent an unique temporary name for atomic save
     * FIXME: rough, but works on Win32 */
    fnm = g_strdup_printf("%s.%u", rf->thumb_sys, getpid());
    if (!gdk_pixbuf_save(pixbuf, fnm, "png", &err,
                         KEY_SOFTWARE, PACKAGE_NAME,
                         KEY_THUMB_URI, rf->file_uri,
                         KEY_THUMB_MTIME, str_mtime,
                         KEY_THUMB_FILESIZE, str_size,
                         KEY_THUMB_IMAGE_WIDTH, str_width,
                         KEY_THUMB_IMAGE_HEIGHT, str_height,
                         KEY_THUMB_GWY_REAL_SIZE, rf->image_real_size,
                         NULL)) {
        g_clear_error(&err);
        rf->thumb_state = FILE_STATE_FAILED;
    }
#ifndef G_OS_WIN32
    chmod(fnm, 0600);
#endif
    g_unlink(rf->thumb_sys);
    if (g_rename(fnm, rf->thumb_sys) != 0) {
        g_unlink(fnm);
        rf->thumb_state = FILE_STATE_FAILED;
        rf->thumb_mtime = 0;
    }
    else {
        rf->thumb_state = FILE_STATE_UNKNOWN;  /* force reload */
        rf->thumb_mtime = rf->file_mtime;
    }
    g_free(fnm);

    gwy_object_unref(rf->pixbuf);
    g_object_unref(pixbuf);
}
Example #15
0
static void
run_tests (const gchar* argv0)
{
  GError *err = NULL;
  gchar *output = NULL;
  gchar *erroutput = NULL;
  gchar *dirname = g_path_get_dirname (argv0);
#ifdef G_OS_WIN32
  int pipedown[2], pipeup[2];
  gchar **argv = 0;
  gchar spawn_binary[1000] = {0};
  gchar full_cmdline[1000] = {0};
  g_snprintf (spawn_binary, sizeof (spawn_binary), "%s\\spawn-test-win32-gui.exe", dirname);
#endif
  g_free (dirname);
  
  err = NULL;
  if (!g_spawn_command_line_sync ("nonexistent_application foo 'bar baz' blah blah",
                                  NULL, NULL, NULL,
                                  &err))
    {
      g_error_free (err);
    }
  else
    {
      g_warning ("no error for sync spawn of nonexistent application");
      exit (1);
    }

  err = NULL;
  if (!g_spawn_command_line_async ("nonexistent_application foo bar baz \"blah blah\"",
                                   &err))
    {
      g_error_free (err);
    }
  else
    {
      g_warning ("no error for async spawn of nonexistent application");
      exit (1);
    }

  err = NULL;
#ifdef G_OS_UNIX
  if (!g_spawn_command_line_sync ("/bin/sh -c 'echo hello'",
                                  &output, NULL, NULL,
                                  &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  else
    {
      g_assert (output != NULL);
      
      if (strcmp (output, "hello\n") != 0)
        {
          printf ("output was '%s', should have been 'hello'\n",
                  output);

          exit (1);
        }

      g_free (output);
      output = NULL;
    }
#endif
  /* Running sort synchronously, collecting its output. 'sort' command is selected
   * because it is non-builtin command on both unix and win32 with well-defined stdout behaviour.
   */
  g_file_set_contents ("spawn-test-created-file.txt", "line first\nline 2\nline last\n", -1, &err);
  g_assert_no_error(err);
  if (!g_spawn_command_line_sync ("sort spawn-test-created-file.txt",
                                  &output, &erroutput, NULL,
                                  &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  else
    {
      g_assert (output != NULL);
      g_assert (erroutput != NULL);
      
      if (strstr (output, "\nline first") == 0)
        {
          printf ("output was '%s', should have contained 'line first' in second line\n",
                  output);

          exit (1);
        }
      if (erroutput[0] != '\0')
	{
	  printf ("error output was '%s', should have been empty\n",
		  erroutput);
	  exit (1);
	}

      g_free (output);
      output = NULL;
      g_free (erroutput);
      erroutput = NULL;
      g_unlink ("spawn-test-created-file.txt");
    }

  if (!g_spawn_command_line_sync ("sort non-existing-file.txt",
                                  NULL, &erroutput, NULL,
                                  &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  else
    {
      g_assert (erroutput != NULL);

      if (erroutput[0] == '\0')
        {
          printf ("erroutput was empty, expected contain error message about non-existing-file.txt\n");
          exit (1);
        }
      g_free (erroutput);
      erroutput = NULL;
    }

#ifdef G_OS_WIN32
  printf ("Running spawn-test-win32-gui in various ways.\n");

  printf ("First asynchronously (without wait).\n");
  g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' 1", spawn_binary);
  if (!g_spawn_command_line_async (full_cmdline, &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }

  printf ("Now synchronously, collecting its output.\n");
  g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' 2", spawn_binary);
  if (!g_spawn_command_line_sync (full_cmdline,
				  &output, &erroutput, NULL,
				  &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  else
    {
      g_assert (output != NULL);
      g_assert (erroutput != NULL);
      
      if (strcmp (output, "This is stdout\r\n") != 0)
        {
          printf ("output was '%s', should have been 'This is stdout'\n",
                  g_strescape (output, NULL));

          exit (1);
        }
      if (strcmp (erroutput, "This is stderr\r\n") != 0)
	{
	  printf ("error output was '%s', should have been 'This is stderr'\n",
		  g_strescape (erroutput, NULL));
	  exit (1);
	}

      g_free (output);
      output = NULL;
      g_free (erroutput);
      erroutput = NULL;
    }

  printf ("Now with G_SPAWN_FILE_AND_ARGV_ZERO.\n");
  g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' this-should-be-argv-zero print_argv0", spawn_binary);
  if (!g_shell_parse_argv (full_cmdline, NULL, &argv, &err))
    {
      fprintf (stderr, "Error parsing command line? %s\n", err->message);
      g_error_free (err);
      exit (1);
    }

  if (!g_spawn_sync (NULL, argv, NULL,
		      G_SPAWN_FILE_AND_ARGV_ZERO,
		      NULL, NULL, &output, NULL, NULL,
		      &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  else
    {
      if (strcmp (output, "this-should-be-argv-zero") != 0)
	{
	  printf ("output was '%s', should have been 'this-should-be-argv-zero'\n", output);
	  exit (1);
	}
      g_free (output);
      output = NULL;
    }

  printf ("Now talking to it through pipes.\n");

  if (pipe (pipedown) < 0 ||
      pipe (pipeup) < 0)
    {
      fprintf (stderr, "Could not create pipes\n");
      exit (1);
    }

  g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' pipes %d %d", spawn_binary, pipedown[0], pipeup[1]);
  if (!g_shell_parse_argv (full_cmdline,
                           NULL, &argv,
                           &err))
    {
      fprintf (stderr, "Error parsing command line? %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  
  if (!g_spawn_async (NULL, argv, NULL,
		      G_SPAWN_LEAVE_DESCRIPTORS_OPEN |
		      G_SPAWN_DO_NOT_REAP_CHILD,
		      NULL, NULL, NULL,
		      &err))
    {
      fprintf (stderr, "Error: %s\n", err->message);
      g_error_free (err);
      exit (1);
    }
  else
    {
      int k, n;
      char buf[100];

      if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n))
	{
	  int errsv = errno;
	  if (k == -1)
	    fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
	  else
	    fprintf (stderr, "Wanted to read %d bytes, got %d\n",
		     (int)sizeof (n), k);
	  exit (1);
	}

      if ((k = read (pipeup[0], buf, n)) != n)
	{
	  int errsv = errno;
	  if (k == -1)
	    fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
	  else
	    fprintf (stderr, "Wanted to read %d bytes, got %d\n",
		     n, k);
	  exit (1);
	}

      n = strlen ("Bye then");
      if (write (pipedown[1], &n, sizeof (n)) == -1 ||
	  write (pipedown[1], "Bye then", n) == -1)
	{
	  int errsv = errno;
	  fprintf (stderr, "Write error: %s\n", g_strerror (errsv));
	  exit (1);
	}

      if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n))
	{
	  int errsv = errno;
	  if (k == -1)
	    fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
	  else
	    fprintf (stderr, "Wanted to read %d bytes, got %d\n",
		     (int)sizeof (n), k);
	  exit (1);
	}
      if (n != strlen ("See ya"))
	{
	  printf ("child wrote %d bytes, expected %d", n, (int) strlen ("See ya"));
	  exit (1);
	}

      if ((k = read (pipeup[0], buf, n)) != n)
	{
	  int errsv = errno;
	  if (k == -1)
	    fprintf (stderr, "Read error: %s\n", g_strerror (errsv));
	  else
	    fprintf (stderr, "Wanted to read %d bytes, got %d\n",
		     n, k);
	  exit (1);
	}
      buf[n] = '\0';
      if (strcmp (buf, "See ya") != 0)
	{
	  printf ("output was '%s', should have been 'See ya'\n", buf);
	  exit (1);
	}
    }
#endif
}
Example #16
0
int
save_config (void)
{
	int fh, i;
	char *config, *new_config;

	check_prefs_dir ();

	config = default_file ();
	new_config = g_strconcat (config, ".new", NULL);
	
	fh = g_open (new_config, OFLAGS | O_TRUNC | O_WRONLY | O_CREAT, 0600);
	if (fh == -1)
	{
		g_free (new_config);
		return 0;
	}

	if (!cfg_put_str (fh, "version", PACKAGE_VERSION))
	{
		g_free (new_config);
		return 0;
	}
		
	i = 0;
	do
	{
		switch (vars[i].type)
		{
		case TYPE_STR:
			if (!cfg_put_str (fh, vars[i].name, (char *) &prefs + vars[i].offset))
			{
				g_free (new_config);
				return 0;
			}
			break;
		case TYPE_INT:
		case TYPE_BOOL:
			if (!cfg_put_int (fh, *((int *) &prefs + vars[i].offset), vars[i].name))
			{
				g_free (new_config);
				return 0;
			}
		}
		i++;
	}
	while (vars[i].name);

	if (close (fh) == -1)
	{
		g_free (new_config);
		return 0;
	}

#ifdef WIN32
	g_unlink (config);	/* win32 can't rename to an existing file */
#endif
	if (g_rename (new_config, config) == -1)
	{
		g_free (new_config);
		return 0;
	}
	g_free (new_config);

	return 1;
}
Example #17
0
static int
actual_portaudio_initialize (DenemoPrefs * config)
{
  sample_rate = config->portaudio_sample_rate;

#ifdef _HAVE_FLUIDSYNTH_
  g_message ("Initializing Fluidsynth");
  if (fluidsynth_init (config, sample_rate))
    {
      g_warning ("Initializing Fluidsynth FAILED!");
      return -1;
    }
#endif
#ifdef _HAVE_RUBBERBAND_
  g_message ("Initializing Rubberband");
 if (rubberband_init (config))
    {
      g_warning ("Initializing Rubberband FAILED!");
      return -1;
    }
#endif
  g_unlink (recorded_audio_filename ());

  g_message ("Initializing PortAudio backend");
  g_info("PortAudio version: %s", Pa_GetVersionText());

  PaStreamParameters output_parameters;
  PaError err;

  err = Pa_Initialize ();
  if (err != paNoError)
    {
      g_warning ("Initializing PortAudio failed");
      return -1;
    }

  output_parameters.device = get_portaudio_device_index (config->portaudio_device->str);

  if (output_parameters.device == paNoDevice)
    {
      output_parameters.device =   get_portaudio_device_index ("default");
       if (output_parameters.device == paNoDevice)
        {
            g_warning("No PortAudio device %s and no default either.", config->portaudio_device->str);
            return -1;
        }
    }

  PaDeviceInfo const *info = Pa_GetDeviceInfo (output_parameters.device);

  if (!info)
    {
      g_warning ("Invalid device '%s'", config->portaudio_device->str);
      return -1;
    }

  char const *api_name = Pa_GetHostApiInfo (info->hostApi)->name;
  g_message ("Opening output device '%s: %s'", api_name, info->name);

  output_parameters.channelCount = 2;
  output_parameters.sampleFormat = paFloat32 | paNonInterleaved;
  output_parameters.suggestedLatency = Pa_GetDeviceInfo (output_parameters.device)->defaultLowOutputLatency;
  output_parameters.hostApiSpecificStreamInfo = NULL;
  err = Pa_OpenStream (&stream, NULL, &output_parameters, config->portaudio_sample_rate, config->portaudio_period_size, paNoFlag /* make this a pref??? paClipOff */ , stream_callback, NULL);
  if (err != paNoError)
    {
      g_warning ("Couldn't open output stream");
      return -1;
    }
  err = Pa_StartStream (stream);
  if (err != paNoError)
    {
      g_warning ("Couldn't start output stream");
      return -1;
    }

  return 0;
}
static void
test_account (int i, Account* test_act)
{
    xmlNodePtr test_node;
    gchar* filename1;
    gchar* compare_msg;
    int fd;

    test_node = gnc_account_dom_tree_create (test_act, FALSE, TRUE);

    if (!test_node)
    {
        failure_args ("account_xml", __FILE__, __LINE__,
                      "gnc_account_dom_tree_create returned NULL");
        return;
    }

    if ((compare_msg = node_and_account_equal (test_node, test_act)) != NULL)
    {
        failure_args ("account_xml", __FILE__, __LINE__,
                      "node and account were not equal: %s", compare_msg);
        xmlElemDump (stdout, NULL, test_node);
        fprintf (stdout, "\n");
        xmlFreeNode (test_node);
        g_free (compare_msg);
        return;
    }
    else
    {
        success ("account_xml");
    }

    filename1 = g_strdup_printf ("test_file_XXXXXX");

    fd = g_mkstemp (filename1);

    write_dom_node_to_file (test_node, fd);

    close (fd);

    {
        sixtp* parser;
        act_data data;

        data.act = test_act;
        data.value = i;

        parser = gnc_account_sixtp_parser_create ();

        if (!gnc_xml_parse_file (parser, filename1, test_add_account,
                                 &data, sixbook))
        {
            failure_args ("gnc_xml_parse_file returned FALSE",
                          __FILE__, __LINE__, "%d", i);
        }

        /* no handling of circular data structures.  We'll do that later */
        /* sixtp_destroy(parser); */
    }


    g_unlink (filename1);
    g_free (filename1);
    xmlFreeNode (test_node);
}
static void
_pp_maintenance_command_execute_thread (GSimpleAsyncResult *res,
                                        GObject            *object,
                                        GCancellable       *cancellable)
{
  PpMaintenanceCommand        *command = (PpMaintenanceCommand *) object;
  PpMaintenanceCommandPrivate *priv = command->priv;
  static const char           *attrs[] = {"printer-commands"};
  ipp_attribute_t             *attr = NULL;
  gboolean                     success = FALSE;
  GError                      *error = NULL;
  ipp_t                       *request;
  ipp_t                       *response = NULL;
  gchar                       *printer_uri;
  gchar                       *printer_commands = NULL;
  gchar                       *printer_commands_lowercase = NULL;
  gchar                       *command_lowercase;
  gchar                       *file_name = NULL;
  int                          fd = -1;

  printer_uri = g_strdup_printf ("ipp://localhost/printers/%s",
                                 priv->printer_name);

  request = ippNewRequest (IPP_GET_PRINTER_ATTRIBUTES);
  ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI,
                "printer-uri", NULL, printer_uri);
  ippAddStrings (request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
                 "requested-attributes", 1, NULL, attrs);
  response = cupsDoRequest (CUPS_HTTP_DEFAULT, request, "/");

  if (response)
    {
      if (ippGetStatusCode (response) <= IPP_OK_CONFLICT)
        {
          attr = ippFindAttribute (response, "printer-commands", IPP_TAG_ZERO);
          if (attr && ippGetCount (attr) > 0 && ippGetValueTag (attr) != IPP_TAG_NOVALUE)
            {
              if (ippGetValueTag (attr) == IPP_TAG_KEYWORD)
                {
                  printer_commands = g_strdup (ippGetString (attr, 0, NULL));
                }
            }
          else
            {
              success = TRUE;
            }
        }

      ippDelete (response);
    }

  if (printer_commands)
    {
      command_lowercase = g_ascii_strdown (priv->command, -1);
      printer_commands_lowercase = g_ascii_strdown (printer_commands, -1);

      if (g_strrstr (printer_commands_lowercase, command_lowercase))
        {
          request = ippNewRequest (IPP_PRINT_JOB);

          ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_URI,
                        "printer-uri", NULL, printer_uri);
          ippAddString (request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                        "job-name", NULL, priv->title);
          ippAddString (request, IPP_TAG_JOB, IPP_TAG_MIMETYPE,
                        "document-format", NULL, "application/vnd.cups-command");

          fd = g_file_open_tmp ("ccXXXXXX", &file_name, &error);

          if (fd != -1)
            {
              FILE *file;

              file = fdopen (fd, "w");
              fprintf (file, "#CUPS-COMMAND\n");
              fprintf (file, "%s\n", priv->command);
              fclose (file);

              response = cupsDoFileRequest (CUPS_HTTP_DEFAULT, request, "/", file_name);
              g_unlink (file_name);

              if (response)
                {
                  if (ippGetStatusCode (response) <= IPP_OK_CONFLICT)
                    {
                      success = TRUE;
                    }

                  ippDelete (response);
                }
            }

          g_free (file_name);
        }
      else
        {
          success = TRUE;
        }

      g_free (command_lowercase);
      g_free (printer_commands_lowercase);
      g_free (printer_commands);
    }

  g_free (printer_uri);

  if (!success)
    {
      g_simple_async_result_set_error (res,
                                       G_IO_ERROR,
                                       G_IO_ERROR_FAILED,
                                       "Execution of maintenance command failed.");
    }

  g_simple_async_result_set_op_res_gboolean (res, success);
}
Example #20
0
/* return 0 on success
 * extract a file in tarball to appropriate directory, ignoring any paths in archive
 * note that szDestPath lacks slash at end
 * szFName is the file to extract
 * szWantedFile is the file to extract
 * szDestPath is the path to extract to (without trailing slash) - if NULL, extracted data wont be saved to disk
 * retBuf is a pointer to a bufferpointer - will be g_try_malloc'ed and filled with data if retBuf != NULL
 * retFileSize will be filled with the size of the file, if it's != NULL
 *
 * extraction routines derived from logic in zlib's contrib untgz.c program
 */
int
UT_untgz(const char *szFName, const char *szWantedFile, const char *szDestPath, char **retBuf, int *retFileSize)
{
	gzFile tarball;
	union  tar_buffer buffer;
	int    getheader = 1;
	int    remaining = 0;
	int    len;
	char   fname[TGZ_BLOCKSIZE];
	FILE   *outfile = NULL;
	int    fileSize = 0;
	
	if (retBuf)
		FREEP(*retBuf);

	if ((tarball = gzopen(szFName, "rb")) == NULL)
	{
		UT_DEBUGMSG(("untgz: Error while opening downloaded dictionary archive"));
		return 1;
	}


	bool done = false;
	while (!done)
	{
		if ((len = gzread(tarball, &buffer, TGZ_BLOCKSIZE)) != TGZ_BLOCKSIZE)
		{
			// error (gzerror(in, &err));
			UT_DEBUGMSG(("untgz: gzread failed to read in complete block"));
			gzclose(tarball);
			return 1;
		}
		
		/*
		 * If we have to get a tar header
		 */
		if (getheader == 1)
		{
			/*
			 * if we met the end of the tar
			 * or the end-of-tar block,
			 * we are done
			 */
			if ((len == 0)  || (buffer.header.name[0]== 0)) 
			{ 
				done = true;
				continue; 
			}

			// tartime = static_cast<time_t>(getoct(buffer.header.mtime,12));
			strcpy(fname, buffer.header.name);
			strippath(fname);
	  
			if ((buffer.header.typeflag == '\0')	||	// [A]REGTYPE, ie regular files
				(buffer.header.typeflag == '0') )
			{
				remaining = getoct(buffer.header.size, 12);

				if ((remaining) && (g_ascii_strcasecmp(fname, szWantedFile) == 0))
				{
					fileSize = remaining;
					
					if (retBuf)
					{
						if (!(*retBuf = static_cast<char *>(g_try_malloc(fileSize))))
							*retBuf = NULL;
					}
					
					if (retFileSize)
						*retFileSize = fileSize;
					
					if (szDestPath) {
						UT_String outfilename(szDestPath);
						outfilename += "/";
						outfilename += fname;
						if ((outfile = fopen(outfilename.c_str(), "wb")) == NULL) {
							UT_DEBUGMSG(("untgz: Unable to save %s", outfilename.c_str()));
							}
					}
					else
						outfile = NULL;
				}
				else
					outfile = NULL;

				/*
				 * could have no contents
				 */
				getheader = (remaining) ? 0 : 1;
			}
		}
		else // if (getheader != 1)
		{
			unsigned int bytes = (remaining > TGZ_BLOCKSIZE) ? TGZ_BLOCKSIZE : remaining;
			
			if (retBuf && *retBuf)
			{
				memcpy(retBuf[fileSize - remaining], buffer.buffer, bytes);
			}
			
			if (outfile != NULL)
			{
				if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes)
				{
					UT_DEBUGMSG(("untgz: error writing, skipping %s", fname));
					fclose(outfile);
					g_unlink(fname);
				}
			}
			
			remaining -= bytes;
			if (remaining == 0)
			{
				getheader = 1;
				if (outfile != NULL)
				{
					// TODO: should actually set proper time from archive, oh well
					fclose(outfile);
					outfile = NULL;
				}
			}
		} // if (getheader == 1) else end
	}

	if (tarball != NULL) gzclose(tarball);
	return 0;
}
Example #21
0
static int
hexchat_pluginpref_set_str_real (hexchat_plugin *pl, const char *var, const char *value, int mode) /* mode: 0 = delete, 1 = save */
{
	FILE *fpIn;
	int fhOut;
	int prevSetting;
	char *confname;
	char *confname_tmp;
	char *buffer;
	char *buffer_tmp;
	char line_buffer[512];		/* the same as in cfg_put_str */
	char *line_bufp = line_buffer;
	char *canon;

	canon = g_strdup (pl->name);
	canonalize_key (canon);
	confname = g_strdup_printf ("addon_%s.conf", canon);
	g_free (canon);
	confname_tmp = g_strdup_printf ("%s.new", confname);

	fhOut = hexchat_open_file (confname_tmp, O_TRUNC | O_WRONLY | O_CREAT, 0600, XOF_DOMODE);
	fpIn = hexchat_fopen_file (confname, "r", 0);

	if (fhOut == -1)		/* unable to save, abort */
	{
		g_free (confname);
		g_free (confname_tmp);
		return 0;
	}
	else if (fpIn == NULL)	/* no previous config file, no parsing */
	{
		if (mode)
		{
			buffer = g_strdup_printf ("%s = %s\n", var, value);
			write (fhOut, buffer, strlen (buffer));
			g_free (buffer);
			close (fhOut);

			buffer = g_build_filename (get_xdir (), confname, NULL);
			g_free (confname);
			buffer_tmp = g_build_filename (get_xdir (), confname_tmp, NULL);
			g_free (confname_tmp);

#ifdef WIN32
			g_unlink (buffer);
#endif

			if (g_rename (buffer_tmp, buffer) == 0)
			{
				g_free (buffer);
				g_free (buffer_tmp);
				return 1;
			}
			else
			{
				g_free (buffer);
				g_free (buffer_tmp);
				return 0;
			}
		}
		else
		{
			/* mode = 0, we want to delete but the config file and thus the given setting does not exist, we're ready */
			close (fhOut);
			g_free (confname);
			g_free (confname_tmp);
			return 1;
		}
	}
	else	/* existing config file, preserve settings and find & replace current var value if any */
	{
		prevSetting = 0;

		while (fscanf (fpIn, " %[^\n]", line_bufp) != EOF)	/* read whole lines including whitespaces */
		{
			buffer_tmp = g_strdup_printf ("%s ", var);	/* add one space, this way it works against var - var2 checks too */

			if (strncmp (buffer_tmp, line_buffer, strlen (var) + 1) == 0)	/* given setting already exists */
			{
				if (mode)									/* overwrite the existing matching setting if we are in save mode */
				{
					buffer = g_strdup_printf ("%s = %s\n", var, value);
				}
				else										/* erase the setting in delete mode */
				{
					buffer = g_strdup ("");
				}

				prevSetting = 1;
			}
			else
			{
				buffer = g_strdup_printf ("%s\n", line_buffer);	/* preserve the existing different settings */
			}

			write (fhOut, buffer, strlen (buffer));

			g_free (buffer);
			g_free (buffer_tmp);
		}

		fclose (fpIn);

		if (!prevSetting && mode)	/* var doesn't exist currently, append if we're in save mode */
		{
			buffer = g_strdup_printf ("%s = %s\n", var, value);
			write (fhOut, buffer, strlen (buffer));
			g_free (buffer);
		}

		close (fhOut);

		buffer = g_build_filename (get_xdir (), confname, NULL);
		g_free (confname);
		buffer_tmp = g_build_filename (get_xdir (), confname_tmp, NULL);
		g_free (confname_tmp);

#ifdef WIN32
		g_unlink (buffer);
#endif

		if (g_rename (buffer_tmp, buffer) == 0)
		{
			g_free (buffer);
			g_free (buffer_tmp);
			return 1;
		}
		else
		{
			g_free (buffer);
			g_free (buffer_tmp);
			return 0;
		}
	}
}
Example #22
0
/*
 * Creates an SQLite .db file from the definitions in @sqlfile
 */
gboolean
create_sqlite_db (const gchar *dir, const gchar *dbname, const gchar *sqlfile, GError **error)
{
	GdaBatch *batch;
	GdaSqlParser *parser;
	GdaServerProvider *prov;
	GdaConnection *cnc;

	/* create batch */
	prov = gda_config_get_provider ("SQLite", NULL);
	if (!prov) {
		g_set_error (error, TEST_ERROR, TEST_ERROR_GENERIC, "%s", 
			     "Cannot find the SQLite provider");
		return FALSE;
	}
	parser = gda_server_provider_create_parser (prov, NULL);
	if (!parser)
		parser = gda_sql_parser_new ();
	
	batch = gda_sql_parser_parse_file_as_batch (parser, sqlfile, error);
	g_object_unref (parser);
	if (!batch)
		return FALSE;

	/* clean any previous DB file */
	gchar *fname, *tmp;
	tmp = g_strdup_printf ("%s.db", dbname);
	fname = g_build_filename (dir, tmp, NULL);
	g_free (tmp);
	g_unlink (fname);
	g_free (fname);

	/* open a connection */
	gchar *cnc_string;
	gchar *edir, *edbname;

	edir = gda_rfc1738_encode (dir);
	edbname = gda_rfc1738_encode (dbname);
	cnc_string = g_strdup_printf ("DB_DIR=%s;DB_NAME=%s", edir, edbname);
	g_free (edir);
	g_free (edbname);
	cnc = gda_connection_open_from_string ("SQLite", cnc_string, NULL, 
					       GDA_CONNECTION_OPTIONS_NONE, error);
	g_free (cnc_string);
	if (!cnc) {
		g_object_unref (batch);
		return FALSE;
	}

	/* execute batch */
	GSList *list;
	const GSList *stmt_list;
	gboolean retval = TRUE;
	list = gda_connection_batch_execute (cnc, batch, NULL, GDA_STATEMENT_MODEL_RANDOM_ACCESS, error);
	stmt_list = gda_batch_get_statements (batch);
	if (g_slist_length (list) != g_slist_length ((GSList *) stmt_list))
		retval = FALSE;

	g_slist_foreach (list, (GFunc) g_object_unref, NULL);
	g_slist_free (list);

	g_assert (gda_connection_close (cnc, NULL));
	g_object_unref (cnc);
	g_object_unref (batch);
	return retval;
}
Example #23
0
GimpPDBStatusType
screenshot_osx_shoot (ScreenshotValues  *shootvals,
                      GdkScreen         *screen,
                      gint32            *image_ID,
                      GError           **error)
{
  const gchar *mode    = " ";
  const gchar *cursor  = " ";
  gchar       *delay   = NULL;
  gchar       *filename;
  gchar       *quoted;
  gchar       *command = NULL;

  switch (shootvals->shoot_type)
    {
    case SHOOT_REGION:
      mode = "-is";
      break;

    case SHOOT_WINDOW:
      if (shootvals->decorate)
        mode = "-iwo";
      else
        mode = "-iw";
      break;

    case SHOOT_ROOT:
      mode = " ";
      if (shootvals->show_cursor)
        cursor = "-C";
      break;

    default:
      g_return_val_if_reached (GIMP_PDB_CALLING_ERROR);
      break;
    }

  delay = g_strdup_printf ("-T %i", shootvals->select_delay);

  filename = gimp_temp_name ("png");
  quoted   = g_shell_quote (filename);

  command = g_strjoin (" ",
                       "/usr/sbin/screencapture",
                       mode,
                       cursor,
                       delay,
                       quoted,
                       NULL);

  g_free (quoted);
  g_free (delay);

  if (system ((const char *) command) == EXIT_SUCCESS)
    {
      *image_ID = gimp_file_load (GIMP_RUN_NONINTERACTIVE,
                                  filename, filename);
      gimp_image_set_filename (*image_ID, "screenshot.png");

      g_unlink (filename);
      g_free (filename);
      g_free (command);

      return GIMP_PDB_SUCCESS;
   }

  g_free (command);
  g_free (filename);

  return GIMP_PDB_EXECUTION_ERROR;
}
Example #24
0
/**
 * main:
 **/
int
main (int argc, char *argv[])
{
	PkOfflineAction action = PK_OFFLINE_ACTION_UNKNOWN;
	gint retval;
	_cleanup_error_free_ GError *error = NULL;
	_cleanup_main_loop_unref_ GMainLoop *loop = NULL;
	_cleanup_object_unref_ GFile *file = NULL;
	_cleanup_object_unref_ PkProgressBar *progressbar = NULL;
	_cleanup_object_unref_ PkResults *results = NULL;
	_cleanup_object_unref_ PkTask *task = NULL;
	_cleanup_strv_free_ gchar **package_ids = NULL;

#if (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 35)
	g_type_init ();
#endif

	/* ensure root user */
	if (getuid () != 0 || geteuid () != 0) {
		retval = EXIT_FAILURE;
		g_print ("This program can only be used using root\n");
		sd_journal_print (LOG_WARNING, "not called with the root user");
		goto out;
	}

	/* get the action, and then delete the file */
	action = pk_offline_update_get_action ();
	g_unlink (PK_OFFLINE_ACTION_FILENAME);

	/* always do this first to avoid a loop if this tool segfaults */
	g_unlink (PK_OFFLINE_TRIGGER_FILENAME);

	/* do stuff on ctrl-c */
	g_unix_signal_add_full (G_PRIORITY_DEFAULT,
				SIGINT,
				pk_offline_update_sigint_cb,
				NULL,
				NULL);

	/* get the list of packages to update */
	package_ids = pk_offline_get_prepared_ids (&error);
	if (package_ids == NULL) {
		retval = EXIT_FAILURE;
		sd_journal_print (LOG_WARNING,
				  "failed to read %s: %s",
				  PK_OFFLINE_PREPARED_FILENAME,
				  error->message);
		goto out;
	}

	/* use a progress bar when the user presses <esc> in plymouth */
	progressbar = pk_progress_bar_new ();
	pk_progress_bar_set_size (progressbar, 25);
	pk_progress_bar_set_padding (progressbar, 30);

	/* just update the system */
	task = pk_task_new ();
	pk_client_set_interactive (PK_CLIENT (task), FALSE);
	pk_offline_update_set_plymouth_mode ("updates");
	/* TRANSLATORS: we've started doing offline updates */
	pk_offline_update_set_plymouth_msg (_("Installing updates, this could take a while..."));
	pk_offline_update_write_dummy_results (package_ids);
	results = pk_client_update_packages (PK_CLIENT (task),
					     0,
					     package_ids,
					     NULL, /* GCancellable */
					     pk_offline_update_progress_cb,
					     progressbar, /* user_data */
					     &error);
	if (results == NULL) {
		retval = EXIT_FAILURE;
		pk_offline_update_write_error (error);
		sd_journal_print (LOG_WARNING,
				  "failed to update system: %s",
				  error->message);
		goto out;
	}
	pk_progress_bar_end (progressbar);
	pk_offline_update_write_results (results);

	/* delete prepared-update file if it's not already been done by the
	 * pk-plugin-systemd-update daemon plugin */
	if (!pk_offline_auth_invalidate (&error)) {
		retval = EXIT_FAILURE;
		sd_journal_print (LOG_WARNING,
				  "failed to delete %s: %s",
				  PK_OFFLINE_PREPARED_FILENAME,
				  error->message);
		goto out;
	}

	retval = EXIT_SUCCESS;
out:
	/* if we failed, we pause to show any error on the screen */
	if (retval != EXIT_SUCCESS) {
		loop = g_main_loop_new (NULL, FALSE);
		g_timeout_add_seconds (10, pk_offline_update_loop_quit_cb, loop);
		g_main_loop_run (loop);
	}
	/* we have to manually either restart or shutdown */
	if (action == PK_OFFLINE_ACTION_REBOOT)
		pk_offline_update_reboot ();
	else if (action == PK_OFFLINE_ACTION_POWER_OFF)
		pk_offline_update_power_off ();
	return retval;
}
static void
generate_ts(const int nTSP, const int nTSC,
            const int fHeader, const int fCubeful, const int nHashSize, bearoffcontext * pbc, FILE * output)
{

    int i, j, k;
    int iPos;
    int n;
    short int asiEquity[4];
    xhash h;
    FILE *pfTmp;
    unsigned char ac[8];
    char *tmpfile;
    int fTTY = isatty(STDERR_FILENO);

    pfTmp = GetTemporaryFile(NULL, &tmpfile);
    if (pfTmp == NULL)
        exit(2);

    /* initialise xhash */

    if (XhashCreate(&h, nHashSize / (fCubeful ? 8 : 2))) {
        fprintf(stderr, _("Error creating xhash with %d elements\n"), nHashSize / (fCubeful ? 8 : 2));
        exit(2);
    }

    XhashStatus(&h);

    /* write header information */

    if (fHeader) {
        char sz[41];
        sprintf(sz, "gnubg-TS-%02d-%02d-%1dxxxxxxxxxxxxxxxxxxxxxxx\n", nTSP, nTSC, fCubeful);
        fputs(sz, output);
    }


    /* generate bearoff database */

    n = Combination(nTSP + nTSC, nTSC);
    iPos = 0;


    /* positions above diagonal */

    for (i = 0; i < n; i++) {
        for (j = 0; j <= i; j++, ++iPos) {

            BearOff2(i - j, j, nTSP, nTSC, asiEquity, n, fCubeful, &h, pbc, pfTmp);

            for (k = 0; k < (fCubeful ? 4 : 1); ++k)
                WriteEquity(pfTmp, asiEquity[k]);

            XhashAdd(&h, (i - j) * n + j, asiEquity, fCubeful ? 8 : 2);

        }
        if (fTTY)
            fprintf(stderr, "%d/%d     \r", iPos, n * n);
    }

    /* positions below diagonal */

    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++, ++iPos) {

            BearOff2(i + n - j, j, nTSP, nTSC, asiEquity, n, fCubeful, &h, pbc, pfTmp);

            for (k = 0; k < (fCubeful ? 4 : 1); ++k)
                WriteEquity(pfTmp, asiEquity[k]);

            XhashAdd(&h, (i + n - j) * n + j, asiEquity, fCubeful ? 8 : 2);

        }
        if (fTTY)
            fprintf(stderr, "%d/%d     \r", iPos, n * n);
    }

    putc('\n', stderr);
    XhashStatus(&h);

    XhashDestroy(&h);

    /* sort file from ordering:
     * 
     * 136       123
     * 258  to   456 
     * 479       789 
     * 
     */

    for (i = 0; i < n; ++i) {
        for (j = 0; j < n; ++j) {
            unsigned int count = fCubeful ? 8 : 2;

            k = CalcPosition(i, j, n);

            fseek(pfTmp, count * k, SEEK_SET);
            if (fread(ac, 1, count, pfTmp) != count || fwrite(ac, 1, count, output) != count) {
                fprintf(stderr, "failed to read from or write to database file\n");
                exit(3);
            }
        }

    }

    fclose(pfTmp);

    g_unlink(tmpfile);

}
Example #26
0
int32_t dt_control_delete_images_job_run(dt_job_t *job)
{
  long int imgid = -1;
  dt_control_image_enumerator_t *t1 = (dt_control_image_enumerator_t *)job->param;
  GList *t = t1->index;
  int total = g_list_length(t);
  char message[512]= {0};
  double fraction=0;
  snprintf(message, 512, ngettext ("deleting %d image", "deleting %d images", total), total );
  const guint *jid = dt_control_backgroundjobs_create(darktable.control, 0, message);

  sqlite3_stmt *stmt;

  char query[1024];
  sprintf(query, "update images set flags = (flags | %d) where id in (select imgid from selected_images)",DT_IMAGE_REMOVE);
  DT_DEBUG_SQLITE3_EXEC(dt_database_get(darktable.db), query, NULL, NULL, NULL);

  dt_collection_update(darktable.collection);

  // We need a list of files to regenerate .xmp files if there are duplicates
  GList *list = NULL;

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select distinct folder || '/' || filename from images, film_rolls where images.film_id = film_rolls.id and images.id in (select imgid from selected_images)", -1, &stmt, NULL);

  if(sqlite3_step(stmt) == SQLITE_ROW)
  {
    list = g_list_append(list, g_strdup((const gchar *)sqlite3_column_text(stmt, 0)));
  }
  sqlite3_finalize(stmt);

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select count(id) from images where filename in (select filename from images where id = ?1) and film_id in (select film_id from images where id = ?1)", -1, &stmt, NULL);
  while(t)
  {
    imgid = (long int)t->data;
    char filename[DT_MAX_PATH_LEN];
    dt_image_full_path(imgid, filename, DT_MAX_PATH_LEN);

    int duplicates = 0;
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid);
    if(sqlite3_step(stmt) == SQLITE_ROW)
      duplicates = sqlite3_column_int(stmt, 0);
    sqlite3_reset(stmt);
    sqlite3_clear_bindings(stmt);

    // remove from disk:
    if(duplicates == 1) // don't remove the actual data if there are (other) duplicates using it
      (void)g_unlink(filename);
    dt_image_path_append_version(imgid, filename, DT_MAX_PATH_LEN);
    char *c = filename + strlen(filename);
    sprintf(c, ".xmp");
    (void)g_unlink(filename);

    dt_image_remove(imgid);

    t = g_list_delete_link(t, t);
    fraction=1.0/total;
    dt_control_backgroundjobs_progress(darktable.control, jid, fraction);
  }
  sqlite3_finalize(stmt);

  char *imgname;
  while(list)
  {
    imgname = (char *)list->data;
    dt_image_synch_all_xmp(imgname);
    list = g_list_delete_link(list, list);
  }
  g_list_free(list);
  dt_control_backgroundjobs_destroy(darktable.control, jid);
  dt_film_remove_empty();
  dt_control_queue_redraw_center();
  return 0;
}
Example #27
0
gboolean
rs_external_editor_gimp(RS_PHOTO *photo, RSFilter *prior_to_resample, guint snapshot)
{
#ifdef WIN32
	return FALSE;
#else
	RSOutput *output = NULL;
	g_assert(RS_IS_PHOTO(photo));

	// We need at least GIMP 2.4.0 to export photo
	if (!rs_has_gimp(2,4,0)) {
		return FALSE;
	}

	DBusConnection *bus;
	DBusMessage *message, *reply;
	GString *filename;

	bus = dbus_bus_get (DBUS_BUS_SESSION, NULL);

	gchar* org_name = g_path_get_basename(photo->filename);
	gchar* org_name_noext = g_utf8_strchr(org_name, -1, '.');

	/* Terminate string there */
	if (NULL != org_name_noext)
		org_name_noext[0] = 0;

	filename = g_string_new("");
        g_string_printf(filename, "%s/%s-rawstudio_%.0f.png",g_get_tmp_dir(), org_name, g_random_double()*10000);

	g_free(org_name);

	/* Setup our filter chain for saving */
				RSFilter *ftransform_input = rs_filter_new("RSColorspaceTransform", prior_to_resample);
        RSFilter *fdcp = rs_filter_new("RSDcp", ftransform_input);
        RSFilter *fdenoise= rs_filter_new("RSDenoise", fdcp);
        RSFilter *ftransform_display = rs_filter_new("RSColorspaceTransform", fdenoise);
        RSFilter *fend = ftransform_display;

			GList *filters = g_list_append(NULL, fend);
			rs_photo_apply_to_filters(photo, filters, snapshot);
			g_list_free(filters);


	output = rs_output_new("RSPngfile");
	g_object_set(output, "filename", filename->str, NULL);
	g_object_set(output, "save16bit", FALSE, NULL);
	g_object_set(output, "copy-metadata", TRUE, NULL);
	rs_output_execute(output, fend);
	g_object_unref(output);
	g_object_unref(ftransform_input);
	g_object_unref(ftransform_display);
	g_object_unref(fdenoise);
	g_object_unref(fdcp);

	message = dbus_message_new_method_call("org.gimp.GIMP.UI",
                                                "/org/gimp/GIMP/UI",
                                                "org.gimp.GIMP.UI",
                                                "OpenAsNew");
	dbus_message_append_args (message,
                                        DBUS_TYPE_STRING, &filename->str,
					DBUS_TYPE_INVALID);

	/* Send DBus message to GIMP */
	reply = dbus_connection_send_with_reply_and_block (bus, message, -1, NULL);

	/* If we didn't get a reply from GIMP - we try to start it and resend the message */
	if (!reply) {
		gint retval = system("gimp &");
		if (retval != 0) {
			g_warning("system(\"gimp &\") returned: %d\n", retval);
			g_unlink(filename->str);
			g_string_free(filename, TRUE);
			dbus_message_unref (message);
			return FALSE;
		}
	}

	/* Allow GIMP to start - we send the message every one second */
	while (!reply) {
		gint i = 0;
		if (i > EXPORT_TO_GIMP_TIMEOUT_SECONDS) {
			g_warning("Never got a reply from GIMP - deleting temporary file");
			g_unlink(filename->str);
			g_string_free(filename, TRUE);
			dbus_message_unref (message);
			return FALSE;
		}
		sleep(1);
		i++;
		reply = dbus_connection_send_with_reply_and_block (bus, message, -1, NULL);
	}

	dbus_message_unref (message);

	/* Depends on GIMP DBus signal: 'Opened' */
	if (rs_has_gimp(2,6,2)) {
		/* Connect to GIMP and listen for "Opened" signal */
		dbus_bus_add_match (bus, "type='signal',interface='org.gimp.GIMP.UI'", NULL);
		dbus_connection_add_filter(bus, dbus_gimp_opened, filename->str , NULL);
		g_string_free(filename, FALSE);
	} else {
		/* Old sad way - GIMP doesn't let us know that it has opened the photo */
		g_warning("You have an old version of GIMP and we suggest that you upgrade to at least 2.6.2");
		g_warning("Rawstudio will stop responding for 10 seconds while it waits for GIMP to open the file");
		sleep(10);
		g_unlink(filename->str);
		g_string_free(filename, TRUE);
	}

	return TRUE;
#endif
}
Example #28
0
/**
 * bt_edit_application_save_song:
 * @self: the application instance to save a song from
 * @file_name: the song filename to save
 * @err: where to store the error message in case of an error, or %NULL
 *
 * Saves a song.
 *
 * Returns: true for success
 */
gboolean
bt_edit_application_save_song (const BtEditApplication * self,
    const char *file_name, GError ** err)
{
  gboolean res = FALSE;
  BtSongIO *saver;

  g_return_val_if_fail (BT_IS_EDIT_APPLICATION (self), FALSE);

  GST_INFO ("song name = %s", file_name);

  if ((saver = bt_song_io_from_file (file_name, err))) {
    gchar *old_file_name = NULL, *bak_file_name = NULL;

    bt_edit_application_ui_lock (self);
    g_signal_connect (saver, "notify::status",
        G_CALLBACK (on_songio_status_changed), (gpointer) self);

    // update the time-stamp
    bt_child_proxy_set (self->priv->song, "song-info::change-dts", NULL, NULL);

    bt_child_proxy_get (self->priv->song, "song-info::file-name",
        &old_file_name, NULL);

    /* save file saving (bak files)
     * save
     *   new file (!old_file_name)
     *     chosen file-name already exist
     *       - move to <existing>.bak
     *       - save newfile
     *       - if saving failed, move <existing>.bak back
     *       - if saving worked, delete <existing>.bak
     *     chosen file-name does not exist
     *       - save newfile
     *   existing file
     *     - move to <existing>.bak
     *       - save newfile
     *       - if saving failed, move <existing>.bak back
     * save-as
     *   new file (!old_file_name)
     *     like save of a new-file
     *   existing file
     *     chosen file-name already exist
     *       - like save of an existing file
     *     chosen file-name does not exist
     *       - save newfile
     *
     * - check how other apps do it (check if inodes change if various scenarios)
     * - when loading a file, should we keep the file-handle open, so then when
     *   saving, we can just update it?
     *   - this can help with the wavetable (only updated changed wavetable slots)
     *   - if we can't update it, we can use gsf_input_copy() for external files
     *     (if unchanged)
     * - if the user deletes the file that is currently open -> user error
     */
    if (g_file_test (file_name, G_FILE_TEST_EXISTS)) {
      bak_file_name = g_strconcat (file_name, ".bak", NULL);
      g_rename (file_name, bak_file_name);
    }
    if (bt_song_io_save (saver, self->priv->song, err)) {
      res = TRUE;
      if (!old_file_name || strcmp (old_file_name, file_name)) {
        // saving worked, we remove the bak file as
        // - there was no old_file_name and/or
        // - user has chosen to overwrite this file
        g_unlink (bak_file_name);
      }
    } else {
      GST_WARNING ("could not save song \"%s\"", file_name);
      if (bak_file_name) {
        // saving failed, so move a file we renamed to .bak back
        g_rename (bak_file_name, file_name);
      }
    }
    GST_INFO ("saving done");
    self->priv->unsaved = FALSE;
    g_object_notify (G_OBJECT (self), "unsaved");
    self->priv->need_dts_reset = TRUE;

    bt_edit_application_ui_unlock (self);

    g_free (old_file_name);
    g_free (bak_file_name);
    g_object_unref (saver);
  } else {
    GST_WARNING ("Unknown extension \"%s\"", file_name);
  }
  return res;
}
static gboolean
inf_test_certificate_validate_run(const InfTestCertificateValidateDesc* desc,
                                  GError** error)
{
  InfIo* io;
  InfdXmppServer* server;

  InfXmppManager* xmpp_manager;
  InfCertificateVerify* verify;
  InfXmppConnection* client;
  gchar* pinned_file;

  InfXmlConnectionStatus status;
  InfTestCertificateValidateCheckCertificateData check_certificate_data;
  gboolean result;

  GError* conn_error;
  GHashTable* pinned;
  gnutls_x509_crt_t pinned_cert;
  InfCertificateChain* current_cert;
  gboolean cert_equal;

  /* Setup server */
  io = INF_IO(inf_standalone_io_new());

  server = inf_test_certificate_setup_server(
    io,
    desc->key_file,
    desc->cert_file,
    error
  );

  if(server == NULL)
  {
    g_object_unref(io);
    return FALSE;
  }

  /* Create client */
  pinned_file = inf_test_validate_setup_pin(
    desc->hostname,
    desc->pinned_certificate,
    error
  );

  if(pinned_file == NULL)
  {
    g_object_unref(server);
    g_object_unref(io);
    return FALSE;
  }

  xmpp_manager = inf_xmpp_manager_new();
  verify = inf_certificate_verify_new(xmpp_manager, pinned_file);

  check_certificate_data.did_query = FALSE;
  check_certificate_data.accept_query = desc->accept_query;
  g_signal_connect(
    G_OBJECT(verify),
    "check-certificate",
    G_CALLBACK(inf_test_certificate_validate_check_certificate),
    &check_certificate_data
  );

  client = inf_test_certificate_validate_setup_client(
    io,
    desc->ca_file,
    desc->hostname,
    error
  );

  if(client == NULL)
  {
    g_unlink(pinned_file);
    g_free(pinned_file);
    g_object_unref(io);
    g_object_unref(xmpp_manager);
    g_object_unref(verify);
    g_object_unref(server);
    return FALSE;
  }

  inf_xmpp_manager_add_connection(xmpp_manager, client);

  /* Okay, now watch for status changes on the client or whether a dialog
   * appears. */
  g_signal_connect(
    G_OBJECT(client),
    "notify::status",
    G_CALLBACK(inf_test_validate_certificate_notify_status_cb),
    io
  );

  conn_error = NULL;
  g_signal_connect(
    G_OBJECT(client),
    "error",
    G_CALLBACK(inf_test_validate_certificate_error_cb),
    &conn_error
  );

  inf_standalone_io_loop(INF_STANDALONE_IO(io));
  g_object_unref(io);

  /* Evaluate result */
  result = TRUE;
  g_object_get(G_OBJECT(client), "status", &status, NULL);
  if(status == INF_XML_CONNECTION_OPEN)
  {
    g_assert(conn_error == NULL);

    if(check_certificate_data.did_query == TRUE &&
       desc->expectation != INF_TEST_CERTIFICATE_VALIDATE_EXPECT_QUERY_ACCEPT)
    {
      g_set_error(
        error,
        inf_test_certificate_validate_error(),
        3,
        "Certificate queried and accepted but not expected to"
      );

      result = FALSE;
    }
    else if(check_certificate_data.did_query == FALSE &&
            desc->expectation != INF_TEST_CERTIFICATE_VALIDATE_EXPECT_ACCEPT)
    {
      g_set_error(
        error,
        inf_test_certificate_validate_error(),
        0,
        "Certificate accepted but not expected to"
      );

      result = FALSE;
    }
  }
  else
  {
    g_assert(check_certificate_data.did_query || conn_error != NULL);

    /* TODO: The certificate verification result is not preserved at
     * the moment. We could change this in
     * inf_xmpp_connection_certificate_verify_cancel such that the existing
     * error is used if any, or otherwise our own is created. */
    if(conn_error != NULL &&
       conn_error->domain != inf_xmpp_connection_error_quark() &&
       conn_error->code != INF_XMPP_CONNECTION_ERROR_CERTIFICATE_NOT_TRUSTED)
    {
      g_propagate_error(error, conn_error);
      conn_error = NULL;
      result = FALSE;
    }
    else if(check_certificate_data.did_query == TRUE &&
            desc->expectation != INF_TEST_CERTIFICATE_VALIDATE_EXPECT_QUERY_REJECT)
    {
      g_set_error(
        error,
        inf_test_certificate_validate_error(),
        2,
        "Certificate queried and rejected but not expected to"
      );

      result = FALSE;
    }
    else if(check_certificate_data.did_query == FALSE &&
            desc->expectation != INF_TEST_CERTIFICATE_VALIDATE_EXPECT_REJECT)
    {
      g_set_error(
        error,
        inf_test_certificate_validate_error(),
        1,
        "Certificate rejected but not expected to"
      );

      result = FALSE;
    }

    if(conn_error != NULL)
    {
      g_error_free(conn_error);
      conn_error = NULL;
    }
  }

  /* If we got the expected result, check whether the host was correctly
   * pinned or not. */
  if(result == TRUE)
  {
    pinned = inf_cert_util_read_certificate_map(pinned_file, error);
    if(pinned == NULL)
    {
      result = FALSE;
    }
    else
    {
      pinned_cert = g_hash_table_lookup(pinned, desc->hostname);

      cert_equal = FALSE;
      if(pinned_cert != NULL)
      {
        g_object_get(
          G_OBJECT(client),
          "remote-certificate", &current_cert,
          NULL
        );

        cert_equal = inf_cert_util_compare_fingerprint(
          pinned_cert,
          inf_certificate_chain_get_own_certificate(current_cert),
          &conn_error
        );

        inf_certificate_chain_unref(current_cert);
      }

      if(conn_error != NULL)
      {
        g_propagate_error(error, conn_error);
        conn_error = NULL;
      }
      else if(cert_equal == TRUE && desc->expect_pinned == FALSE)
      {
        g_set_error(
          error,
          inf_test_certificate_validate_error(),
          4,
          "Certificate was pinned but not expected to"
        );

        result = FALSE;
      }
      else if(pinned_cert == NULL && desc->expect_pinned == TRUE)
      {
        g_set_error(
          error,
          inf_test_certificate_validate_error(),
          5,
          "Certificate was not pinned but expected to"
        );

        result = FALSE;
      }

      g_hash_table_destroy(pinned);
    }
  }

  g_unlink(pinned_file);
  g_free(pinned_file);
  g_object_unref(xmpp_manager);
  g_object_unref(verify);
  g_object_unref(server);
  g_object_unref(client);
  return result;
}
Example #30
0
static GsApp *
gs_plugin_fwupd_new_app (GsPlugin *plugin, FwupdDevice *dev, GError **error)
{
	FwupdRelease *rel = fwupd_device_get_release_default (dev);
	GPtrArray *checksums;
	const gchar *update_uri;
	g_autofree gchar *basename = NULL;
	g_autofree gchar *filename_cache = NULL;
	g_autoptr(GFile) file = NULL;
	g_autoptr(GsApp) app = NULL;

	/* update unsupported */
	app = gs_plugin_fwupd_new_app_from_device (plugin, dev);
	if (gs_app_get_state (app) != AS_APP_STATE_UPDATABLE_LIVE) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_NOT_SUPPORTED,
			     "%s [%s] cannot be updated",
			     gs_app_get_name (app), gs_app_get_id (app));
		return NULL;
	}

	/* some missing */
	if (gs_app_get_id (app) == NULL) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_NOT_SUPPORTED,
			     "fwupd: No id for firmware");
		return NULL;
	}
	if (gs_app_get_version (app) == NULL) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_NOT_SUPPORTED,
			     "fwupd: No version! for %s!", gs_app_get_id (app));
		return NULL;
	}
	if (gs_app_get_update_version (app) == NULL) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_NOT_SUPPORTED,
			     "fwupd: No update-version! for %s!", gs_app_get_id (app));
		return NULL;
	}
	checksums = fwupd_release_get_checksums (rel);
	if (checksums->len == 0) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_NO_SECURITY,
			     "%s [%s] (%s) has no checksums, ignoring as unsafe",
			     gs_app_get_name (app),
			     gs_app_get_id (app),
			     gs_app_get_update_version (app));
		return NULL;
	}
	update_uri = fwupd_release_get_uri (rel);
	if (update_uri == NULL) {
		g_set_error (error,
			     GS_PLUGIN_ERROR,
			     GS_PLUGIN_ERROR_INVALID_FORMAT,
			     "no location available for %s [%s]",
			     gs_app_get_name (app), gs_app_get_id (app));
		return NULL;
	}

	/* does the firmware already exist in the cache? */
	basename = g_path_get_basename (update_uri);
	filename_cache = gs_utils_get_cache_filename ("fwupd",
						      basename,
						      GS_UTILS_CACHE_FLAG_NONE,
						      error);
	if (filename_cache == NULL)
		return NULL;

	/* delete the file if the checksum does not match */
	if (g_file_test (filename_cache, G_FILE_TEST_EXISTS)) {
		const gchar *checksum_tmp = NULL;
		g_autofree gchar *checksum = NULL;

		/* we can migrate to something better than SHA1 when the LVFS
		 * starts producing metadata with multiple hash types */
		checksum_tmp = fwupd_checksum_get_by_kind (checksums,
							   G_CHECKSUM_SHA1);
		if (checksum_tmp == NULL) {
			g_set_error (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_INVALID_FORMAT,
				     "No valid checksum for %s",
				     filename_cache);
		}
		checksum = gs_plugin_fwupd_get_file_checksum (filename_cache,
							      G_CHECKSUM_SHA1,
							      error);
		if (checksum == NULL)
			return NULL;
		if (g_strcmp0 (checksum_tmp, checksum) != 0) {
			g_set_error (error,
				     GS_PLUGIN_ERROR,
				     GS_PLUGIN_ERROR_INVALID_FORMAT,
				     "%s does not match checksum, expected %s got %s",
				     filename_cache, checksum_tmp, checksum);
			g_unlink (filename_cache);
			return NULL;
		}
	}

	/* already downloaded, so overwrite */
	if (g_file_test (filename_cache, G_FILE_TEST_EXISTS))
		gs_app_set_size_download (app, 0);

	/* actually add the application */
	file = g_file_new_for_path (filename_cache);
	gs_app_set_local_file (app, file);
	return g_steal_pointer (&app);
}