/**
 * fo_property_source_document_validate:
 * @datatype: #FoDatatype to be validated against allowed datatypes and
 *            values for current property.
 * @context:  #FoContext object from which to possibly inherit values.
 * @error:    Information about any error that has occurred.
 * 
 * Validates @datatype against allowed values.  Returns @datatype, a
 * replacement datatype value, or NULL if validation failed.
 * 
 * Return value: Valid datatype value or NULL.
 **/
FoDatatype*
fo_property_source_document_validate (FoDatatype *datatype,
                                      FoContext  *context,
                                      GError    **error)
{
  FoDatatype *new_datatype;
  GError     *tmp_error = NULL;
  gchar      *token;

  g_return_val_if_fail (datatype != NULL, NULL);
  g_return_val_if_fail (FO_IS_DATATYPE (datatype), NULL);
  g_return_val_if_fail (context != NULL, NULL);
  g_return_val_if_fail (FO_IS_CONTEXT (context), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  if (FO_IS_URI_SPECIFICATION (datatype))
    {
      return datatype;
    }
  else if (FO_IS_URI_SPECIFICATION (datatype))
    {
      return datatype;
    }
  else if (FO_IS_ENUM (datatype))
    {
      FoEnumEnum value = fo_enum_get_value (datatype);

      if (value == FO_ENUM_ENUM_NONE)
	{
	  return datatype;
	}
      else
	{
	  gchar *datatype_sprintf = fo_object_sprintf (datatype);

	  g_set_error (error,
		       FO_FO_ERROR,
		       FO_FO_ERROR_ENUMERATION_TOKEN,
		       _(fo_fo_error_messages[FO_FO_ERROR_ENUMERATION_TOKEN]),
		       class_name,
		       datatype_sprintf,
		       g_type_name (G_TYPE_FROM_INSTANCE (datatype)));

	  g_object_unref (datatype);

	  g_free (datatype_sprintf);

	  return NULL;
	}
    }
  else if (FO_IS_STRING (datatype))
    {
      token = fo_string_get_value (datatype);

      new_datatype =
        fo_property_source_document_resolve_enum (token, context, &tmp_error);

      g_object_unref (datatype);

      fo_propagate_and_return_val_if_error (error, tmp_error, NULL);

      return new_datatype;
    }
  else if (FO_IS_NAME (datatype))
    {
      token = fo_name_get_value (datatype);

      new_datatype =
        fo_property_source_document_resolve_enum (token, context, &tmp_error);

      g_object_unref (datatype);

      fo_propagate_and_return_val_if_error (error, tmp_error, NULL);

      return new_datatype;
    }
  else
    {
      gchar *datatype_sprintf = fo_object_sprintf (datatype);

      g_set_error (error,
		   FO_FO_ERROR,
		   FO_FO_ERROR_DATATYPE,
		   _(fo_fo_error_messages[FO_FO_ERROR_DATATYPE]),
		   class_name,
		   datatype_sprintf,
		   g_type_name (G_TYPE_FROM_INSTANCE (datatype)));

      g_object_unref (datatype);

      g_free (datatype_sprintf);

      return NULL;
    }
}
Beispiel #2
0
static GSList *
mgr_columns_update_children (GdaTreeManager *manager, GdaTreeNode *node, const GSList *children_nodes,
			     gboolean *out_error, GError **error)
{
	MgrColumns *mgr = MGR_COLUMNS (manager);
	GSList *nodes_list = NULL;
	GHashTable *ehash = NULL;

	if (out_error)
		*out_error = FALSE;

	if (children_nodes)
		ehash = hash_for_existing_nodes (children_nodes);

	GdaMetaStruct *mstruct;
	mstruct = t_connection_get_meta_struct (mgr->priv->tcnc);
	if (!mstruct) {
		g_set_error (error, MGR_COLUMNS_ERROR, MGR_COLUMNS_NO_META_STRUCT,
                             "%s", _("Not ready"));
                if (out_error)
                        *out_error = TRUE;
		return NULL;
	}

	GdaMetaDbObject *dbo;
	GValue *schema_v = NULL, *name_v;
	if (mgr->priv->schema)
		g_value_set_string ((schema_v = gda_value_new (G_TYPE_STRING)), mgr->priv->schema);
	g_value_set_string ((name_v = gda_value_new (G_TYPE_STRING)), mgr->priv->table_name);
	dbo = gda_meta_struct_get_db_object (mstruct, NULL, schema_v, name_v);
	if (schema_v)
		gda_value_free (schema_v);
	gda_value_free (name_v);

	if (!dbo) {
		g_set_error (error, MGR_COLUMNS_ERROR, MGR_COLUMNS_TABLE_NOT_FOUND,
                             "%s", _("Table not found"));
                if (out_error)
                        *out_error = TRUE;
		return NULL;
	}
	if ((dbo->obj_type != GDA_META_DB_TABLE) && (dbo->obj_type != GDA_META_DB_VIEW)) {
		g_set_error (error, MGR_COLUMNS_ERROR, MGR_COLUMNS_WRONG_OBJ_TYPE,
                             "%s", _("Requested object is not a table or view"));
                if (out_error)
                        *out_error = TRUE;
		return NULL;
	}
	
	GdaMetaTable *dbotable;
	GSList *columns;
	gint index;
	dbotable = GDA_META_TABLE (dbo);
	
	for (columns = dbotable->columns, index = 0;
	     columns;
	     columns = columns->next, index ++) {
		GdaMetaTableColumn *col;
		col = GDA_META_TABLE_COLUMN (columns->data);
		GdaTreeNode* snode = NULL;
		GValue *av;

		if (ehash)
			snode = g_hash_table_lookup (ehash, col->column_name);
		if (snode) {
			/* use the same node */
			g_object_ref (G_OBJECT (snode));
		}
		else {
			/* column's name */
			snode = gda_tree_manager_create_node (manager, node, NULL);
			if (col->pkey)
				g_value_take_string ((av = gda_value_new (G_TYPE_STRING)),
						     g_strdup_printf ("<b>%s</b>", col->column_name));
			else
				g_value_set_string ((av = gda_value_new (G_TYPE_STRING)), col->column_name);
			gda_tree_node_set_node_attribute (snode, MGR_COLUMNS_COL_NAME_ATT_NAME, av, NULL);
			gda_value_free (av);
		}
			
		/* column's type */
		g_value_set_string ((av = gda_value_new (G_TYPE_STRING)), col->column_type);
		gda_tree_node_set_node_attribute (snode, MGR_COLUMNS_COL_TYPE_ATT_NAME, av, NULL);
		gda_value_free (av);
		
		/* NOT NULL */
		g_value_set_boolean ((av = gda_value_new (G_TYPE_BOOLEAN)), !col->nullok);
		gda_tree_node_set_node_attribute (snode, MGR_COLUMNS_COL_NOTNULL_ATT_NAME, av, NULL);
		gda_value_free (av);
		
		/* default value */
		g_value_set_string ((av = gda_value_new (G_TYPE_STRING)), col->default_value);
		gda_tree_node_set_node_attribute (snode, MGR_COLUMNS_COL_DEFAULT_ATT_NAME, av, NULL);
		gda_value_free (av);
		
		/* icon */
		UiIconType type = UI_ICON_COLUMN;
		GdkPixbuf *pixbuf;
		gboolean is_fk = column_is_fk_part (dbo, index);
		if (col->pkey)
			type = UI_ICON_COLUMN_PK;
		else if (!col->nullok) {
			if (is_fk)
				type = UI_ICON_COLUMN_FK_NN;
			else
				type = UI_ICON_COLUMN_NN;
		}
		else if (is_fk)
			type = UI_ICON_COLUMN_FK;
		
		pixbuf = ui_get_pixbuf_icon (type);
		av = gda_value_new (G_TYPE_OBJECT);
		g_value_set_object (av, pixbuf);
		gda_tree_node_set_node_attribute (snode, "icon", av, NULL);
		gda_value_free (av);

		/* details */
		GString *details = NULL;
		if (col->pkey)
			details = g_string_new (_("Primary key"));
		if (is_fk) {
			if (details)
				g_string_append (details, ", ");
			else
				details = g_string_new ("");
			g_string_append (details, _("Foreign key"));
		}
		const GValue *autoinc;
		autoinc = gda_meta_table_column_get_attribute (col, GDA_ATTRIBUTE_AUTO_INCREMENT);
		if (autoinc) {
			if (details)
				g_string_append (details, ", ");
			else
				details = g_string_new ("");
			g_string_append (details, _("Auto incremented"));
		}
		if (details) {
			g_value_set_string ((av = gda_value_new (G_TYPE_STRING)), details->str);
			gda_tree_node_set_node_attribute (snode, MGR_COLUMNS_COL_DETAILS, av, NULL);
			gda_value_free (av);
			g_string_free (details, TRUE);
		}

		nodes_list = g_slist_prepend (nodes_list, snode);		
	}

	if (ehash)
		g_hash_table_destroy (ehash);

	return g_slist_reverse (nodes_list);
}
Beispiel #3
0
static gboolean
brasero_cdrecord_write_inf (BraseroCDRecord *cdrecord,
			    GPtrArray *argv,
			    BraseroTrack *track,
			    const gchar *tmpdir,
			    const gchar *album,
			    gint index,
			    gint start,
			    gboolean last_track,
			    GError **error)
{
	gint fd;
        int errsv;
	gint size;
	gchar *path;
	guint64 length;
	gchar *string;
	gint b_written;
	gint64 sectors;
	const gchar *info;
	gchar buffer [128];
	BraseroCDRecordPrivate *priv;

	priv = BRASERO_CD_RECORD_PRIVATE (cdrecord);

	/* NOTE: about the .inf files: they should have the exact same path
	 * but the ending suffix file is replaced by inf:
	 * example : /path/to/file.mp3 => /path/to/file.inf */
	if (brasero_job_get_fd_in (BRASERO_JOB (cdrecord), NULL) != BRASERO_BURN_OK) {
		gchar *dot, *separator;

		path = brasero_track_stream_get_source (BRASERO_TRACK_STREAM (track), FALSE);

		dot = strrchr (path, '.');
		separator = strrchr (path, G_DIR_SEPARATOR);

		if (dot && dot > separator)
			path = g_strdup_printf ("%.*s.inf",
						(int) (dot - path),
						path);
		else
			path = g_strdup_printf ("%s.inf",
						path);

		/* since this file was not returned by brasero_job_get_tmp_file
		 * it won't be erased when session is unrefed so we have to do 
		 * it ourselves */
		priv->infs = g_slist_prepend (priv->infs, g_strdup (path));
	}
	else {
		BraseroBurnResult result;

		/* in this case don't care about the name since stdin is used */
		result = brasero_job_get_tmp_file (BRASERO_JOB (cdrecord),
						   ".inf",
						   &path,
						   error);
		if (result != BRASERO_BURN_OK)
			return result;
	}

	fd = open (path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
	if (fd < 0)
		goto error;

	BRASERO_JOB_LOG (cdrecord, "writing inf (%s)", path);

	/* The problem here is that when writing CD-TEXT from .inf files, wodim
	 * uses only one charset (and don't let us specify which one) which is
	 * ISO-8859-1. (NOTE: don't believe the doc claiming it requires ASCII
	 * and see cdrecord/cdtext.c line 309).
	 * So we have to convert our UTF-8 input into such a charset.
	 * NOTE: according to docs ASCII should be used for text packs other
	 * than disc/track title.
	 * It might be good in the end to write and pack CD-TEXT pack data 
	 * ourselves so we can set a different charset from English like 
	 * Chinese for example. */
	strcpy (buffer, "# created by brasero\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	strcpy (buffer, "MCN=\t\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	/* ISRC */
	info = brasero_track_tag_lookup_string (BRASERO_TRACK (track), BRASERO_TRACK_STREAM_ISRC_TAG);
	if (info)
		string = g_strdup_printf ("ISRC=\t%s\n", info);
	else
		string = g_strdup ("ISRC=\t\n");
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	strcpy (buffer, "Albumperformer=\t\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	if (album) {
		gchar *encoded;

		encoded = g_convert_with_fallback (album,
						   -1,
						   "ISO-8859-1",
						   "UTF-8",
						   "_",	/* Fallback for non convertible characters */
						   NULL,
						   NULL,
						   NULL);
		string = g_strdup_printf ("Albumtitle=\t%s\n", encoded);
		g_free (encoded);
	}
	else
		string = strdup ("Albumtitle=\t\n");
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	/* ARTIST */
	info = brasero_track_tag_lookup_string (BRASERO_TRACK (track),
						BRASERO_TRACK_STREAM_ARTIST_TAG);
	if (info) {
		gchar *encoded;

		encoded = g_convert_with_fallback (info,
						   -1,
						   "ISO-8859-1",
						   "UTF-8",
						   "_",	/* Fallback for non convertible characters */
						   NULL,
						   NULL,
						   NULL);
		string = g_strdup_printf ("Performer=\t%s\n", encoded);
		g_free (encoded);
	}
	else
		string = strdup ("Performer=\t\n");
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	/* COMPOSER */
	info = brasero_track_tag_lookup_string (BRASERO_TRACK (track),
						BRASERO_TRACK_STREAM_COMPOSER_TAG);
	if (info) {
		gchar *encoded;

		encoded = g_convert_with_fallback (info,
						   -1,
						   "ISO-8859-1",
						   "UTF-8",
						   "_",	/* Fallback for non convertible characters */
						   NULL,
						   NULL,
						   NULL);
		string = g_strdup_printf ("Composer=\t%s\n", encoded);
		g_free (encoded);
	}
	else
		string = strdup ("Composer=\t\n");
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	/* TITLE */
	info = brasero_track_tag_lookup_string (BRASERO_TRACK (track),
						BRASERO_TRACK_STREAM_TITLE_TAG);
	if (info) {
		gchar *encoded;

		encoded = g_convert_with_fallback (info,
						   -1,
						   "ISO-8859-1",
						   "UTF-8",
						   "_",	/* Fallback for non convertible characters */
						   NULL,
						   NULL,
						   NULL);
		string = g_strdup_printf ("Tracktitle=\t%s\n", encoded);
		g_free (encoded);
	}
	else
		string = strdup ("Tracktitle=\t\n");
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	string = g_strdup_printf ("Tracknumber=\t%i\n", index);
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	string = g_strdup_printf ("Trackstart=\t%i\n", start);
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	length = 0;
	brasero_track_stream_get_length (BRASERO_TRACK_STREAM (track), &length);
	sectors = BRASERO_DURATION_TO_SECTORS (length);

	BRASERO_JOB_LOG (cdrecord, "got track length %lli", length);
	string = g_strdup_printf ("Tracklength=\t%"G_GINT64_FORMAT", 0\n", sectors);
	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	strcpy (buffer, "Pre-emphasis=\tno\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	strcpy (buffer, "Channels=\t2\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	strcpy (buffer, "Copy_permitted=\tyes\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	strcpy (buffer, "Endianess=\tlittle\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	strcpy (buffer, "Index=\t\t0\n");
	size = strlen (buffer);
	b_written = write (fd, buffer, size);
	if (b_written != size)
		goto error;

	/* NOTE: -1 here means no pregap */
	if (!last_track) {
		/* K3b does this (possibly to remove silence) */
		string = g_strdup_printf ("Index0=\t\t%"G_GINT64_FORMAT"\n",
					  sectors - 150);
	}
	else
		string = g_strdup_printf ("Index0=\t\t-1\n");

	size = strlen (string);
	b_written = write (fd, string, size);
	g_free (string);
	if (b_written != size)
		goto error;

	close (fd);

	if (argv)
		g_ptr_array_add (argv, path);
	else
		g_free (path);

	return BRASERO_BURN_OK;


error:
        errsv = errno;

	g_remove (path);
	g_free (path);

	g_set_error (error,
		     BRASERO_BURN_ERROR,
		     BRASERO_BURN_ERROR_GENERAL,
		     _("An internal error occurred (%s)"), 
		     g_strerror (errsv));

	return BRASERO_BURN_ERR;
}
Beispiel #4
0
/**
 * g_filename_from_uri:
 * @uri: a uri describing a filename (escaped, encoded in UTF-8).
 * @hostname: Location to store hostname for the URI, or %NULL.
 *            If there is no hostname in the URI, %NULL will be
 *            stored in this location.
 * @error: location to store the error occuring, or %NULL to ignore
 *         errors. Any of the errors in #GConvertError may occur.
 *
 * Converts an escaped UTF-8 encoded URI to a local filename in the
 * encoding used for filenames.
 *
 * Return value: a newly-allocated string holding the resulting
 *               filename, or %NULL on an error.
 **/
gchar *
filename_from_uri (const char *uri,
		   char      **hostname,
		   GError    **error)
{
  const char *path_part;
  const char *host_part;
  char *unescaped_hostname;
  char *result;
  char *filename;
  int offs;
#ifdef G_OS_WIN32
  char *p, *slash;
#endif

  if (hostname)
    *hostname = NULL;

  if (!has_case_prefix (uri, "file:/"))
    {
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		   _("The URI '%s' is not an absolute URI using the file scheme"),
		   uri);
      return NULL;
    }

  path_part = uri + strlen ("file:");

  if (strchr (path_part, '#') != NULL)
    {
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		   _("The local file URI '%s' may not include a '#'"),
		   uri);
      return NULL;
    }

  if (has_case_prefix (path_part, "///"))
    path_part += 2;
  else if (has_case_prefix (path_part, "//"))
    {
      path_part += 2;
      host_part = path_part;

      path_part = strchr (path_part, '/');

      if (path_part == NULL)
	{
	  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		       _("The URI '%s' is invalid"),
		       uri);
	  return NULL;
	}

      unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);

      if (unescaped_hostname == NULL ||
	  !hostname_validate (unescaped_hostname))
	{
	  g_free (unescaped_hostname);
	  g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		       _("The hostname of the URI '%s' is invalid"),
		       uri);
	  return NULL;
	}

      if (hostname)
	*hostname = unescaped_hostname;
      else
	g_free (unescaped_hostname);
    }

  filename = g_unescape_uri_string (path_part, -1, "/", FALSE);

  if (filename == NULL)
    {
      g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
		   _("The URI '%s' contains invalidly escaped characters"),
		   uri);
      return NULL;
    }

  offs = 0;
#ifdef G_OS_WIN32
  /* Drop localhost */
  if (hostname && *hostname != NULL &&
      g_ascii_strcasecmp (*hostname, "localhost") == 0)
    {
      g_free (*hostname);
      *hostname = NULL;
    }

  /* Turn slashes into backslashes, because that's the canonical spelling */
  p = filename;
  while ((slash = strchr (p, '/')) != NULL)
    {
      *slash = '\\';
      p = slash + 1;
    }

  /* Windows URIs with a drive letter can be like "file://host/c:/foo"
   * or "file://host/c|/foo" (some Netscape versions). In those cases, start
   * the filename from the drive letter.
   */
  if (g_ascii_isalpha (filename[1]))
    {
      if (filename[2] == ':')
	offs = 1;
      else if (filename[2] == '|')
	{
	  filename[2] = ':';
	  offs = 1;
	}
    }
#endif

  /* This is where we differ from glib2.0.6: we use
     gtkpod's charset_from_utf8() instead of glib's
     g_filename_from_utf8() */
  result = charset_from_utf8 (filename + offs);
  g_free (filename);

  return result;
}
static gchar *
generate_temp_cert (GError **error)
{
  const gchar *dir = PACKAGE_SYSCONF_DIR "/cockpit/ws-certs.d";
  gchar *cert_path = NULL;
  gchar *tmp_key = NULL;
  gchar *tmp_pem = NULL;
  gchar *cert_data = NULL;
  gchar *pem_data = NULL;
  gchar *key_data = NULL;
  gchar *ret = NULL;

  cert_path = g_strdup_printf ("%s/0-self-signed.cert", dir);

  /* Generate self-signed cert, if it does not exist */
  if (g_file_test (cert_path, G_FILE_TEST_EXISTS))
    {
      ret = cert_path;
      cert_path = NULL;
      goto out;
    }

  if (g_mkdir_with_parents (dir, 0700) != 0)
    {
      g_set_error (error,
                   G_IO_ERROR,
                   G_IO_ERROR_FAILED,
                   "Error creating directory `%s': %m",
                   dir);
      goto out;
    }

  tmp_key = create_temp_file (dir, "0-self-signed.XXXXXX.tmp", error);
  if (!tmp_key)
    goto out;
  tmp_pem = create_temp_file (dir, "0-self-signed.XXXXXX.tmp", error);
  if (!tmp_pem)
    goto out;
  if (!openssl_make_dummy_cert (tmp_key, tmp_pem, error))
    goto out;
  if (!g_file_get_contents (tmp_key, &key_data, NULL, error))
    goto out;
  if (!g_file_get_contents (tmp_pem, &pem_data, NULL, error))
    goto out;

  cert_data = g_strdup_printf ("%s\n%s\n", pem_data, key_data);
  if (!g_file_set_contents (cert_path, cert_data, -1, error))
    goto out;

  ret = cert_path;
  cert_path = NULL;

out:
  g_free (cert_path);
  cockpit_secclear (key_data, -1);
  g_free (key_data);
  g_free (pem_data);
  cockpit_secclear (cert_data, -1);
  g_free (cert_data);
  if (tmp_key)
    g_unlink (tmp_key);
  if (tmp_pem)
    g_unlink (tmp_pem);
  g_free (tmp_key);
  g_free (tmp_pem);
  return ret;
}
static gint
nm_openconnect_start_openconnect_binary (NMOPENCONNECTPlugin *plugin,
                                         NMSettingVPN *s_vpn,
                                         GError **error)
{
	NMOPENCONNECTPluginPrivate *priv = NM_OPENCONNECT_PLUGIN_GET_PRIVATE (plugin);
	GPid	pid;
	const char **openconnect_binary = NULL;
	GPtrArray *openconnect_argv;
	GSource *openconnect_watch;
	gint	stdin_fd;
	const char *props_vpn_gw, *props_cookie, *props_cacert, *props_mtu, *props_gwcert, *props_proxy;
	
	/* Find openconnect */
	openconnect_binary = openconnect_binary_paths;
	while (*openconnect_binary != NULL) {
		if (g_file_test (*openconnect_binary, G_FILE_TEST_EXISTS))
			break;
		openconnect_binary++;
	}

	if (!*openconnect_binary) {
		g_set_error (error,
		             NM_VPN_PLUGIN_ERROR,
		             NM_VPN_PLUGIN_ERROR_LAUNCH_FAILED,
		             "%s",
		             _("Could not find openconnect binary."));
		return -1;
	}

	/* The actual gateway to use (after redirection) comes from the auth
	   dialog, so it's in the secrets hash not the properties */
	props_vpn_gw = nm_setting_vpn_get_secret (s_vpn, NM_OPENCONNECT_KEY_GATEWAY);
	if (!props_vpn_gw || !strlen (props_vpn_gw) ) {
		g_set_error (error,
		             NM_VPN_PLUGIN_ERROR,
		             NM_VPN_PLUGIN_ERROR_LAUNCH_FAILED,
		             "%s",
		             _("No VPN gateway specified."));
		return -1;
	}

	props_cookie = nm_setting_vpn_get_secret (s_vpn, NM_OPENCONNECT_KEY_COOKIE);
	if (!props_cookie || !strlen (props_cookie)) {
		g_set_error (error,
		             NM_VPN_PLUGIN_ERROR,
		             NM_VPN_PLUGIN_ERROR_LAUNCH_FAILED,
		             "%s",
		             _("No WebVPN cookie provided."));
		return -1;
	}
	props_gwcert = nm_setting_vpn_get_secret (s_vpn, NM_OPENCONNECT_KEY_GWCERT);

	props_cacert = nm_setting_vpn_get_data_item (s_vpn, NM_OPENCONNECT_KEY_CACERT);
	props_mtu = nm_setting_vpn_get_data_item (s_vpn, NM_OPENCONNECT_KEY_MTU);

	props_proxy = nm_setting_vpn_get_data_item (s_vpn, NM_OPENCONNECT_KEY_PROXY);

	openconnect_argv = g_ptr_array_new ();
	g_ptr_array_add (openconnect_argv, (gpointer) (*openconnect_binary));

	if (props_gwcert && strlen(props_gwcert)) {
		g_ptr_array_add (openconnect_argv, (gpointer) "--servercert");
		g_ptr_array_add (openconnect_argv, (gpointer) props_gwcert);
	} else if (props_cacert && strlen(props_cacert)) {
		g_ptr_array_add (openconnect_argv, (gpointer) "--cafile");
		g_ptr_array_add (openconnect_argv, (gpointer) props_cacert);
	}

	if (props_mtu && strlen(props_mtu)) {
		g_ptr_array_add (openconnect_argv, (gpointer) "--mtu");
		g_ptr_array_add (openconnect_argv, (gpointer) props_mtu);
	}

	if (props_proxy && strlen(props_proxy)) {
		g_ptr_array_add (openconnect_argv, (gpointer) "--proxy");
		g_ptr_array_add (openconnect_argv, (gpointer) props_proxy);
	}
		
	g_ptr_array_add (openconnect_argv, (gpointer) "--syslog");
	g_ptr_array_add (openconnect_argv, (gpointer) "--cookie-on-stdin");

	g_ptr_array_add (openconnect_argv, (gpointer) "--script");
	g_ptr_array_add (openconnect_argv, (gpointer) NM_OPENCONNECT_HELPER_PATH);

	priv->tun_name = create_persistent_tundev ();
	if (priv->tun_name) {
		g_ptr_array_add (openconnect_argv, (gpointer) "--interface");
		g_ptr_array_add (openconnect_argv, (gpointer) priv->tun_name);
	}

	g_ptr_array_add (openconnect_argv, (gpointer) props_vpn_gw);

	if (debug)
		g_ptr_array_add (openconnect_argv, (gpointer) "--verbose");

	g_ptr_array_add (openconnect_argv, NULL);

	if (!g_spawn_async_with_pipes (NULL, (char **) openconnect_argv->pdata, NULL,
	                               G_SPAWN_DO_NOT_REAP_CHILD,
	                               openconnect_drop_child_privs, priv->tun_name,
	                               &pid, &stdin_fd, NULL, NULL, error)) {
		g_ptr_array_free (openconnect_argv, TRUE);
		g_warning ("openconnect failed to start.  error: '%s'", (*error)->message);
		return -1;
	}
	g_ptr_array_free (openconnect_argv, TRUE);

	g_message ("openconnect started with pid %d", pid);

	if (write(stdin_fd, props_cookie, strlen(props_cookie)) != strlen(props_cookie) ||
	    write(stdin_fd, "\n", 1) != 1) {
		g_warning ("openconnect didn't eat the cookie we fed it");
		return -1;
	}

	close(stdin_fd);

	NM_OPENCONNECT_PLUGIN_GET_PRIVATE (plugin)->pid = pid;
	openconnect_watch = g_child_watch_source_new (pid);
	g_source_set_callback (openconnect_watch, (GSourceFunc) openconnect_watch_cb, plugin, NULL);
	g_source_attach (openconnect_watch, NULL);
	g_source_unref (openconnect_watch);

	return 0;
}
Beispiel #7
0
static MMModem *
grab_port (MMPluginBase *base,
           MMModem *existing,
           MMPluginBaseSupportsTask *task,
           GError **error)
{
    GUdevDevice *port = NULL;
    MMModem *modem = NULL;
    const char *name, *subsys, *sysfs_path;
    guint32 caps;
    MMPortType ptype;
    MMAtPortFlags pflags = MM_AT_PORT_FLAG_NONE;
    guint16 vendor = 0, product = 0;

    port = mm_plugin_base_supports_task_get_port (task);
    g_assert (port);

    /* Look for port type hints */
    if (g_udev_device_get_property_as_boolean (port, "ID_MM_ZTE_PORT_TYPE_MODEM"))
        pflags = MM_AT_PORT_FLAG_PRIMARY;
    else if (g_udev_device_get_property_as_boolean (port, "ID_MM_ZTE_PORT_TYPE_AUX"))
        pflags = MM_AT_PORT_FLAG_SECONDARY;

    subsys = g_udev_device_get_subsystem (port);
    name = g_udev_device_get_name (port);

    if (!mm_plugin_base_get_device_ids (base, subsys, name, &vendor, &product)) {
        g_set_error (error, 0, 0, "Could not get modem product ID.");
        return NULL;
    }

    caps = mm_plugin_base_supports_task_get_probed_capabilities (task);
    sysfs_path = mm_plugin_base_supports_task_get_physdev_path (task);
    ptype = mm_plugin_base_probed_capabilities_to_port_type (caps);
    if (!existing) {
        if (caps & MM_PLUGIN_BASE_PORT_CAP_GSM) {
            modem = mm_modem_zte_new (sysfs_path,
                                      mm_plugin_base_supports_task_get_driver (task),
                                      mm_plugin_get_name (MM_PLUGIN (base)),
                                      vendor,
                                      product);
        } else if (caps & CAP_CDMA) {
            modem = mm_generic_cdma_new (sysfs_path,
                                         mm_plugin_base_supports_task_get_driver (task),
                                         mm_plugin_get_name (MM_PLUGIN (base)),
                                         !!(caps & MM_PLUGIN_BASE_PORT_CAP_IS856),
                                         !!(caps & MM_PLUGIN_BASE_PORT_CAP_IS856_A),
                                         vendor,
                                         product);
        }

        if (modem) {
            if (!mm_modem_grab_port (modem, subsys, name, ptype, pflags, NULL, error)) {
                g_object_unref (modem);
                return NULL;
            }
        }
    } else if (get_level_for_capabilities (caps) || (!strcmp (subsys, "net"))) {
        modem = existing;
        if (!mm_modem_grab_port (modem, subsys, name, ptype, pflags, NULL, error))
            return NULL;
    }

    return modem;
}
Beispiel #8
0
static GString *
glpk_create_program (GnmSubSolver *ssol, GOIOContext *io_context, GError **err)
{
    GnmSolver *sol = GNM_SOLVER (ssol);
    GnmSolverParameters *sp = sol->params;
    GString *prg = NULL;
    GString *constraints = g_string_new (NULL);
    GString *bounds = g_string_new (NULL);
    GString *binaries = g_string_new (NULL);
    GString *integers = g_string_new (NULL);
    GString *objfunc = g_string_new (NULL);
    GSList *l;
    GnmCell *target_cell = gnm_solver_param_get_target_cell (sp);
    GPtrArray *input_cells = sol->input_cells;
    gsize progress;
    GPtrArray *old = NULL;
    gnm_float *x1 = NULL, *x2 = NULL;
    int cidx = 0;

    /* ---------------------------------------- */

    if (sp->options.model_type != GNM_SOLVER_LP) {
        g_set_error (err,
                     go_error_invalid (),
                     0,
                     _("Only linear programs are handled."));
        goto fail;
    }

    /* ---------------------------------------- */

    if (ssol) {
        unsigned ui;

        for (ui = 0; ui < input_cells->len; ui++) {
            GnmCell *cell = g_ptr_array_index (input_cells, ui);
            char *name = g_strdup_printf ("X_%u", ui + 1);
            gnm_sub_solver_name_cell (ssol, cell, name);
            g_free (name);
        }
    }

    /* ---------------------------------------- */

    progress = 3;
    /* assume_non_negative */ progress++;
    if (sp->options.assume_discrete) progress++;
    progress += g_slist_length (sp->constraints);

    go_io_count_progress_set (io_context, progress, 1);

    /* ---------------------------------------- */

    old = gnm_solver_save_vars (sol);

    gnm_solver_pick_lp_coords (sol, &x1, &x2);
    go_io_count_progress_update (io_context, 1);

    /* ---------------------------------------- */

    switch (sp->problem_type) {
    case GNM_SOLVER_MINIMIZE:
        g_string_append (objfunc, "Minimize\n");
        break;
    case GNM_SOLVER_MAXIMIZE:
        g_string_append (objfunc, "Maximize\n");
        break;
    default:
        g_assert_not_reached ();
    }
    go_io_count_progress_update (io_context, 1);

    g_string_append (objfunc, " obj: ");
    if (!glpk_affine_func (objfunc, target_cell, ssol, x1, x2,
                           TRUE, 0, err))
        goto fail;
    g_string_append (objfunc, "\n");
    go_io_count_progress_update (io_context, 1);

    /* ---------------------------------------- */

    {
        unsigned ui;
        for (ui = 0; ui < input_cells->len; ui++) {
            GnmCell *cell = g_ptr_array_index (input_cells, ui);
            const char *name = glpk_var_name (ssol, cell);
            if (sp->options.assume_non_negative)
                g_string_append_printf (bounds, " %s >= 0\n", name);
            else
                g_string_append_printf (bounds, " %s free\n", name);
        }
        go_io_count_progress_update (io_context, 1);
    }

    if (sp->options.assume_discrete) {
        unsigned ui;
        for (ui = 0; ui < input_cells->len; ui++) {
            GnmCell *cell = g_ptr_array_index (input_cells, ui);
            g_string_append_printf (integers, " %s\n",
                                    glpk_var_name (ssol, cell));
        }
        go_io_count_progress_update (io_context, 1);
    }

    for (l = sp->constraints; l; l = l->next) {
        GnmSolverConstraint *c = l->data;
        const char *op = NULL;
        int i;
        gnm_float cl, cr;
        GnmCell *lhs, *rhs;
        GString *type = NULL;

        switch (c->type) {
        case GNM_SOLVER_LE:
            op = "<=";
            break;
        case GNM_SOLVER_GE:
            op = ">=";
            break;
        case GNM_SOLVER_EQ:
            op = "=";
            break;
        case GNM_SOLVER_INTEGER:
            type = integers;
            break;
        case GNM_SOLVER_BOOLEAN:
            type = binaries;
            break;
        default:
            g_assert_not_reached ();
        }

        for (i = 0;
                gnm_solver_constraint_get_part (c, sp, i,
                                                &lhs, &cl,
                                                &rhs, &cr);
                i++, cidx++) {
            if (type) {
                g_string_append_printf
                (type, " %s\n",
                 glpk_var_name (ssol, lhs));
            } else {
                gboolean ok;
                char *name;

                g_string_append_c (constraints, ' ');

                name = g_strdup_printf ("C_%d", cidx);
                gnm_sub_solver_name_constraint (ssol, cidx, name);
                g_string_append (constraints, name);
                g_string_append (constraints, ": ");
                g_free (name);

                ok = glpk_affine_func
                     (constraints, lhs, ssol,
                      x1, x2,
                      FALSE, cl, err);
                if (!ok)
                    goto fail;

                g_string_append_c (constraints, ' ');
                g_string_append (constraints, op);
                g_string_append_c (constraints, ' ');

                ok = glpk_affine_func
                     (constraints, rhs, ssol,
                      x1, x2,
                      FALSE, cr, err);
                if (!ok)
                    goto fail;

                g_string_append (constraints, "\n");
            }
        }

        go_io_count_progress_update (io_context, 1);
    }

    /* ---------------------------------------- */

    prg = g_string_new (NULL);
    g_string_append_printf (prg,
                            "\\ Created by Gnumeric %s\n\n",
                            GNM_VERSION_FULL);
    go_string_append_gstring (prg, objfunc);

    g_string_append (prg, "\nSubject to\n");
    go_string_append_gstring (prg, constraints);

    g_string_append (prg, "\nBounds\n");
    go_string_append_gstring (prg, bounds);

    if (integers->len > 0) {
        g_string_append (prg, "\nGeneral\n");
        go_string_append_gstring (prg, integers);
    }
    if (binaries->len > 0) {
        g_string_append (prg, "\nBinary\n");
        go_string_append_gstring (prg, binaries);
    }
    g_string_append (prg, "\nEnd\n");

fail:
    g_string_free (objfunc, TRUE);
    g_string_free (constraints, TRUE);
    g_string_free (bounds, TRUE);
    g_string_free (integers, TRUE);
    g_string_free (binaries, TRUE);
    g_free (x1);
    g_free (x2);

    if (old)
        gnm_solver_restore_vars (sol, old);

    return prg;
}
Beispiel #9
0
int
ostree_run (int    argc,
            char **argv,
            OstreeCommand *commands,
            GError **res_error)
{
  OstreeCommand *command;
  GError *error = NULL;
  GCancellable *cancellable = NULL;
#ifndef BUILDOPT_TSAN
  g_autofree char *prgname = NULL;
#endif
  const char *command_name = NULL;
  gboolean success = FALSE;
  int in, out;

  /* avoid gvfs (http://bugzilla.gnome.org/show_bug.cgi?id=526454) */
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, message_handler, NULL);

  /*
   * Parse the global options. We rearrange the options as
   * necessary, in order to pass relevant options through
   * to the commands, but also have them take effect globally.
   */

  for (in = 1, out = 1; in < argc; in++, out++)
    {
      /* The non-option is the command, take it out of the arguments */
      if (argv[in][0] != '-')
        {
          if (command_name == NULL)
            {
              command_name = argv[in];
              out--;
              continue;
            }
        }

      else if (g_str_equal (argv[in], "--"))
        {
          break;
        }

      argv[out] = argv[in];
    }

  argc = out;

  command = commands;
  while (command->name)
    {
      if (g_strcmp0 (command_name, command->name) == 0)
        break;
      command++;
    }

  if (!command->fn)
    {
      g_autoptr(GOptionContext) context = NULL;
      g_autofree char *help = NULL;

      context = ostree_option_context_new_with_commands (commands);

      /* This will not return for some options (e.g. --version). */
      if (ostree_option_context_parse (context, NULL, &argc, &argv, OSTREE_BUILTIN_FLAG_NO_REPO, NULL, cancellable, &error))
        {
          if (command_name == NULL)
            {
              g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "No command specified");
            }
          else
            {
              g_set_error (&error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Unknown command '%s'", command_name);
              ostree_usage (commands, TRUE);
            }
        }

      help = g_option_context_get_help (context, FALSE, NULL);
      g_printerr ("%s", help);

      goto out;
    }

#ifndef BUILDOPT_TSAN
  prgname = g_strdup_printf ("%s %s", g_get_prgname (), command_name);
  g_set_prgname (prgname);
#endif

  if (!command->fn (argc, argv, cancellable, &error))
    goto out;

  success = TRUE;
 out:
  g_assert (success || error);

  if (error)
    {
      g_propagate_error (res_error, error);
      return 1;
    }
  return 0;
}
/**
 * egg_desktop_file_new_from_key_file:
 * @key_file: a #GKeyFile representing a desktop file
 * @source: the path or URI that @key_file was loaded from, or %NULL
 * @error: error pointer
 *
 * Creates a new #EggDesktopFile for @key_file. Assumes ownership of
 * @key_file (on success or failure); you should consider @key_file to
 * be freed after calling this function.
 *
 * Return value: the new #EggDesktopFile, or %NULL on error.
 **/
EggDesktopFile* egg_desktop_file_new_from_key_file(GKeyFile* key_file, const char* source, GError** error)
{
	EggDesktopFile* desktop_file;
	char* version;
	char* type;

	if (!g_key_file_has_group(key_file, EGG_DESKTOP_FILE_GROUP))
	{
		g_set_error(error, EGG_DESKTOP_FILE_ERROR, EGG_DESKTOP_FILE_ERROR_INVALID, _("File is not a valid .desktop file"));
		g_key_file_free(key_file);
		return NULL;
	}

	version = g_key_file_get_value(key_file, EGG_DESKTOP_FILE_GROUP, EGG_DESKTOP_FILE_KEY_VERSION, NULL);

	if (version)
	{
		double version_num;
		char* end;

		version_num = g_ascii_strtod(version, &end);

		if (*end)
		{
			g_warning("Invalid Version string '%s' in %s", version, source ? source : "(unknown)");
		}
		else if (version_num > 1.0)
		{
			g_set_error(error, EGG_DESKTOP_FILE_ERROR, EGG_DESKTOP_FILE_ERROR_INVALID, _("Unrecognized desktop file Version '%s'"), version);
			g_free(version);
			g_key_file_free(key_file);
			return NULL;
		}

		g_free (version);
	}

	desktop_file = g_new0(EggDesktopFile, 1);
	desktop_file->key_file = key_file;

	if (g_path_is_absolute(source))
	{
		desktop_file->source = g_filename_to_uri(source, NULL, NULL);
	}
	else
	{
		desktop_file->source = g_strdup(source);
	}

	desktop_file->name = g_key_file_get_string(key_file, EGG_DESKTOP_FILE_GROUP, EGG_DESKTOP_FILE_KEY_NAME, error);

	if (!desktop_file->name)
	{
		egg_desktop_file_free(desktop_file);
		return NULL;
	}

	type = g_key_file_get_string(key_file, EGG_DESKTOP_FILE_GROUP, EGG_DESKTOP_FILE_KEY_TYPE, error);

	if (!type)
	{
		egg_desktop_file_free(desktop_file);
		return NULL;
	}

	if (!strcmp (type, "Application"))
	{
	  char *exec, *p;

	  desktop_file->type = EGG_DESKTOP_FILE_TYPE_APPLICATION;

	  exec = g_key_file_get_string (key_file,
					EGG_DESKTOP_FILE_GROUP,
					EGG_DESKTOP_FILE_KEY_EXEC,
					error);
	  if (!exec)
	{
	  egg_desktop_file_free (desktop_file);
	  g_free (type);
	  return NULL;
	}

	  /* See if it takes paths or URIs or neither */
	  for (p = exec; *p; p++)
	{
	  if (*p == '%')
		{
		  if (p[1] == '\0' || strchr ("FfUu", p[1]))
		{
		  desktop_file->document_code = p[1];
		  break;
		}
		  p++;
		}
	}

	  g_free (exec);
	}
	else if (!strcmp (type, "Link"))
	{
	  char *url;

	  desktop_file->type = EGG_DESKTOP_FILE_TYPE_LINK;

	  url = g_key_file_get_string (key_file,
				   EGG_DESKTOP_FILE_GROUP,
				   EGG_DESKTOP_FILE_KEY_URL,
				   error);
	  if (!url)
	{
	  egg_desktop_file_free (desktop_file);
	  g_free (type);
	  return NULL;
	}
	  g_free (url);
	}
	else if (!strcmp (type, "Directory"))
	desktop_file->type = EGG_DESKTOP_FILE_TYPE_DIRECTORY;
	else
	desktop_file->type = EGG_DESKTOP_FILE_TYPE_UNRECOGNIZED;

	g_free (type);

	/* Check the Icon key */
	desktop_file->icon = g_key_file_get_string (key_file,
						  EGG_DESKTOP_FILE_GROUP,
						  EGG_DESKTOP_FILE_KEY_ICON,
						  NULL);
	if (desktop_file->icon && !g_path_is_absolute (desktop_file->icon))
	{
	  char *ext;

	  /* Lots of .desktop files still get this wrong */
	  ext = strrchr (desktop_file->icon, '.');
	  if (ext && (!strcmp (ext, ".png") ||
		  !strcmp (ext, ".xpm") ||
		  !strcmp (ext, ".svg")))
	{
	  g_warning ("Desktop file '%s' has malformed Icon key '%s'"
			 "(should not include extension)",
			 source ? source : "(unknown)",
			 desktop_file->icon);
	  *ext = '\0';
	}
	}

	return desktop_file;
}
Beispiel #11
0
NMConnection *
nm_keyfile_plugin_connection_from_file (const char *filename, GError **error)
{
	GKeyFile *key_file;
	struct stat statbuf;
	gboolean bad_permissions;
	NMConnection *connection = NULL;
	NMSettingConnection *s_con;
	NMSetting *setting;
	gchar **groups;
	gsize length;
	int i;
	gboolean vpn_secrets = FALSE;
	const char *ctype;
	GError *verify_error = NULL;

	if (stat (filename, &statbuf) != 0 || !S_ISREG (statbuf.st_mode)) {
		g_set_error_literal (error, KEYFILE_PLUGIN_ERROR, 0,
		                     "File did not exist or was not a regular file");
		return NULL;
	}

	bad_permissions = statbuf.st_mode & 0077;

	if (bad_permissions) {
		g_set_error (error, KEYFILE_PLUGIN_ERROR, 0,
		             "File permissions (%o) were insecure",
		             statbuf.st_mode);
		return NULL;
	}

	key_file = g_key_file_new ();
	if (!g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, error))
		goto out;

	connection = nm_connection_new ();

	groups = g_key_file_get_groups (key_file, &length);
	for (i = 0; i < length; i++) {
		/* Only read out secrets when needed */
		if (!strcmp (groups[i], VPN_SECRETS_GROUP)) {
			vpn_secrets = TRUE;
			continue;
		}

		setting = read_setting (key_file, filename, groups[i]);
		if (setting)
			nm_connection_add_setting (connection, setting);
	}

	/* Make sure that we have the base device type and slave type settings
	 * even if the keyfile didn't include it, which can happen when the
	 * setting in question is all default values (like ethernet where
	 * the MAC address isn't given, or VLAN when the VLAN ID is zero, or
	 * bridge port with all default settings).
	 */
	s_con = nm_connection_get_setting_connection (connection);
	if (s_con) {
		ctype = nm_setting_connection_get_connection_type (s_con);
		setting = nm_connection_get_setting_by_name (connection, ctype);
		if (ctype && !setting) {
			NMSetting *base_setting;
			GType base_setting_type;

			base_setting_type = nm_connection_lookup_setting_type (ctype);
			if (base_setting_type != G_TYPE_INVALID) {
				base_setting = (NMSetting *) g_object_new (base_setting_type, NULL);
				g_assert (base_setting);
				nm_connection_add_setting (connection, base_setting);
			}
		}

		ensure_slave_setting (connection);
	}

	/* Handle vpn secrets after the 'vpn' setting was read */
	if (vpn_secrets) {
		NMSettingVPN *s_vpn;

		s_vpn = nm_connection_get_setting_vpn (connection);
		if (s_vpn)
			read_vpn_secrets (key_file, s_vpn);
	}

	g_strfreev (groups);

	/* Verify the connection */
	if (!nm_connection_verify (connection, &verify_error)) {
		g_set_error (error, KEYFILE_PLUGIN_ERROR, 0,
			         "invalid or missing connection property '%s/%s'",
			         verify_error ? g_type_name (nm_connection_lookup_setting_type_by_quark (verify_error->domain)) : "(unknown)",
			         (verify_error && verify_error->message) ? verify_error->message : "(unknown)");
		g_clear_error (&verify_error);
		g_object_unref (connection);
		connection = NULL;
		g_warning ("Connection failed to verify: %s",
			verify_error ? g_type_name (nm_connection_lookup_setting_type_by_quark (verify_error->domain)) : "(unknown)");
	}

out:
	g_key_file_free (key_file);
	return connection;
}
static gboolean
egg_desktop_file_launchv (EggDesktopFile *desktop_file,
			  GSList *documents, va_list args,
			  GError **error)
{
  EggDesktopFileLaunchOption option;
  GSList *translated_documents = NULL, *docs = NULL;
  char *command, **argv;
  int argc, i, screen_num;
  gboolean success, current_success;
  GdkDisplay *display;
  char *startup_id;

  GPtrArray   *env = NULL;
  char       **variables = NULL;
  GdkScreen   *screen = NULL;
  int          workspace = -1;
  const char  *directory = NULL;
  guint32      launch_time = (guint32)-1;
  GSpawnFlags  flags = G_SPAWN_SEARCH_PATH;
  GSpawnChildSetupFunc setup_func = NULL;
  gpointer     setup_data = NULL;

  GPid        *ret_pid = NULL;
  int         *ret_stdin = NULL, *ret_stdout = NULL, *ret_stderr = NULL;
  char       **ret_startup_id = NULL;

  if (documents && desktop_file->document_code == 0)
    {
      g_set_error (error, EGG_DESKTOP_FILE_ERROR,
		   EGG_DESKTOP_FILE_ERROR_NOT_LAUNCHABLE,
		   _("Application does not accept documents on command line"));
      return FALSE;
    }

  /* Read the options: technically it's incorrect for the caller to
   * NULL-terminate the list of options (rather than 0-terminating
   * it), but NULL-terminating lets us use G_GNUC_NULL_TERMINATED,
   * it's more consistent with other glib/gtk methods, and it will
   * work as long as sizeof (int) <= sizeof (NULL), and NULL is
   * represented as 0. (Which is true everywhere we care about.)
   */
  while ((option = va_arg (args, EggDesktopFileLaunchOption)))
    {
      switch (option)
	{
	case EGG_DESKTOP_FILE_LAUNCH_CLEARENV:
	  if (env)
	    g_ptr_array_free (env, TRUE);
	  env = g_ptr_array_new ();
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_PUTENV:
	  variables = va_arg (args, char **);
	  for (i = 0; variables[i]; i++)
	    env = array_putenv (env, variables[i]);
	  break;

	case EGG_DESKTOP_FILE_LAUNCH_SCREEN:
	  screen = va_arg (args, GdkScreen *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_WORKSPACE:
	  workspace = va_arg (args, int);
	  break;

	case EGG_DESKTOP_FILE_LAUNCH_DIRECTORY:
	  directory = va_arg (args, const char *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_TIME:
	  launch_time = va_arg (args, guint32);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_FLAGS:
	  flags |= va_arg (args, GSpawnFlags);
	  /* Make sure they didn't set any flags that don't make sense. */
	  flags &= ~G_SPAWN_FILE_AND_ARGV_ZERO;
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_SETUP_FUNC:
	  setup_func = va_arg (args, GSpawnChildSetupFunc);
	  setup_data = va_arg (args, gpointer);
	  break;

	case EGG_DESKTOP_FILE_LAUNCH_RETURN_PID:
	  ret_pid = va_arg (args, GPid *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STDIN_PIPE:
	  ret_stdin = va_arg (args, int *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STDOUT_PIPE:
	  ret_stdout = va_arg (args, int *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STDERR_PIPE:
	  ret_stderr = va_arg (args, int *);
	  break;
	case EGG_DESKTOP_FILE_LAUNCH_RETURN_STARTUP_ID:
	  ret_startup_id = va_arg (args, char **);
	  break;

	default:
	  g_set_error (error, EGG_DESKTOP_FILE_ERROR,
		       EGG_DESKTOP_FILE_ERROR_UNRECOGNIZED_OPTION,
		       _("Unrecognized launch option: %d"),
		       GPOINTER_TO_INT (option));
	  success = FALSE;
	  goto out;
	}
    }

  if (screen)
    {
      char *display_name = gdk_screen_make_display_name (screen);
      char *display_env = g_strdup_printf ("DISPLAY=%s", display_name);
      env = array_putenv (env, display_env);
      g_free (display_name);
      g_free (display_env);

      display = gdk_screen_get_display (screen);
    }
  else
    {
      display = gdk_display_get_default ();
      screen = gdk_display_get_default_screen (display);
    }
  screen_num = gdk_screen_get_number (screen);

  translated_documents = translate_document_list (desktop_file, documents);
  docs = translated_documents;

  success = FALSE;

  do
    {
      command = parse_exec (desktop_file, &docs, error);
      if (!command)
	goto out;

      if (!g_shell_parse_argv (command, &argc, &argv, error))
	{
	  g_free (command);
	  goto out;
	}
      g_free (command);

      startup_id = start_startup_notification (display, desktop_file,
					       argv[0], screen_num,
					       workspace, launch_time);
      if (startup_id)
	{
	  char *startup_id_env = g_strdup_printf ("DESKTOP_STARTUP_ID=%s",
						  startup_id);
	  env = array_putenv (env, startup_id_env);
	  g_free (startup_id_env);
	}

      if (env != NULL)
	g_ptr_array_add (env, NULL);

      current_success =
	g_spawn_async_with_pipes (directory,
				  argv,
				  env ? (char **)(env->pdata) : NULL,
				  flags,
				  setup_func, setup_data,
				  ret_pid,
				  ret_stdin, ret_stdout, ret_stderr,
				  error);
      g_strfreev (argv);

      if (startup_id)
	{
	  if (current_success)
	    {
	      set_startup_notification_timeout (display, startup_id);

	      if (ret_startup_id)
		*ret_startup_id = startup_id;
	      else
		g_free (startup_id);
	    }
	  else
	    g_free (startup_id);
	}
      else if (ret_startup_id)
	*ret_startup_id = NULL;

      if (current_success)
	{
	  /* If we successfully launch any instances of the app, make
	   * sure we return TRUE and don't set @error.
	   */
	  success = TRUE;
	  error = NULL;

	  /* Also, only set the output params on the first one */
	  ret_pid = NULL;
	  ret_stdin = ret_stdout = ret_stderr = NULL;
	  ret_startup_id = NULL;
	}
    }
  while (docs && current_success);

 out:
  if (env)
    {
      g_ptr_array_foreach (env, (GFunc)g_free, NULL);
      g_ptr_array_free (env, TRUE);
    }
  free_document_list (translated_documents);

  return success;
}
gboolean
ot_admin_builtin_instutil (int argc, char **argv, OstreeSysroot *sysroot, GCancellable *cancellable, GError **error)
{
  gboolean ret = FALSE;
  OstreeAdminInstUtilCommand *subcommand;
  const char *subcommand_name = NULL;
  gboolean want_help = FALSE;
  int in, out, i;
  gboolean skip;

  for (in = 1, out = 1; in < argc; in++, out++)
    {
      /* The non-option is the command, take it out of the arguments */
      if (argv[in][0] != '-')
        {
          skip = (subcommand_name == NULL);
          if (subcommand_name == NULL)
            subcommand_name = argv[in];
        }

      /* The global long options */
      else if (argv[in][1] == '-')
        {
          skip = FALSE;

          if (g_str_equal (argv[in], "--"))
            {
              break;
            }
          else if (g_str_equal (argv[in], "--help"))
            {
              want_help = TRUE;
            }
          else if (subcommand_name == NULL)
            {
              g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                           "Unknown or invalid admin instutil option: %s", argv[in]);
              goto out;
            }
        }

      /* The global short options */
      else
        {
          skip = FALSE;
          for (i = 1; argv[in][i] != '\0'; i++)
            {
              switch (argv[in][i])
              {
                case 'h':
                  want_help = TRUE;
                  break;

                default:
                  if (subcommand_name == NULL)
                    {
                      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                   "Unknown or invalid admin instutil option: %s", argv[in]);
                      goto out;
                    }
                  break;
              }
            }
        }

      /* Skipping this argument? */
      if (skip)
        out--;
      else
        argv[out] = argv[in];
    }

  argc = out;

  if (subcommand_name == NULL)
    {
      void (*print_func) (const gchar *format, ...) = want_help ? g_print : g_printerr;

      subcommand = admin_instutil_subcommands;
      print_func ("usage: ostree admin instutil COMMAND [options]\n");
      print_func ("Builtin commands:\n");
      while (subcommand->name)
        {
          print_func ("  %s\n", subcommand->name);
          subcommand++;
        }

      if (want_help)
        ret = TRUE;
      else
        g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                             "No command specified");
      goto out;
    }

  subcommand = admin_instutil_subcommands;
  while (subcommand->name)
    {
      if (g_strcmp0 (subcommand_name, subcommand->name) == 0)
        break;
      subcommand++;
    }

  if (!subcommand->name)
    {
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
                   "Unknown admin instutil command '%s'", subcommand_name);
      goto out;
    }

  g_set_prgname (g_strdup_printf ("ostree admin instutil %s", subcommand_name));

  if (!subcommand->fn (argc, argv, sysroot, cancellable, error))
    goto out;
 
  ret = TRUE;
 out:
  return ret;
}
Beispiel #14
0
bool
audio_output_init(struct audio_output *ao, const struct config_param *param,
		  struct player_control *pc,
		  GError **error_r)
{
	assert(ao != NULL);
	assert(pc != NULL);

	const struct audio_output_plugin *plugin = NULL;
	GError *error = NULL;

	if (param) {
		const char *p;

		p = config_get_block_string(param, AUDIO_OUTPUT_TYPE, NULL);
		if (p == NULL) {
			g_set_error(error_r, audio_output_quark(), 0,
				    "Missing \"type\" configuration");
			return false;
		}

		plugin = audio_output_plugin_get(p);
		if (plugin == NULL) {
			g_set_error(error_r, audio_output_quark(), 0,
				    "No such audio output plugin: %s", p);
			return false;
		}

		ao->name = config_get_block_string(param, AUDIO_OUTPUT_NAME,
						   NULL);
		if (ao->name == NULL) {
			g_set_error(error_r, audio_output_quark(), 0,
				    "Missing \"name\" configuration");
			return false;
		}

		p = config_get_block_string(param, AUDIO_OUTPUT_FORMAT,
						 NULL);
		if (p != NULL) {
			bool success =
				audio_format_parse(&ao->config_audio_format,
						   p, true, error_r);
			if (!success)
				return false;
		} else
			audio_format_clear(&ao->config_audio_format);
	} else {
		g_warning("No \"%s\" defined in config file\n",
			  CONF_AUDIO_OUTPUT);

		plugin = audio_output_detect(error_r);
		if (plugin == NULL)
			return false;

		g_message("Successfully detected a %s audio device",
			  plugin->name);

		ao->name = "default detected output";

		audio_format_clear(&ao->config_audio_format);
	}

	ao->plugin = plugin;
	ao->always_on = config_get_block_bool(param, "always_on", false);
	ao->enabled = config_get_block_bool(param, "enabled", true);
	ao->really_enabled = false;
	ao->open = false;
	ao->pause = false;
	ao->fail_timer = NULL;

	pcm_buffer_init(&ao->cross_fade_buffer);

	/* set up the filter chain */

	ao->filter = filter_chain_new();
	assert(ao->filter != NULL);

	/* create the replay_gain filter */

	const char *replay_gain_handler =
		config_get_block_string(param, "replay_gain_handler",
					"software");

	if (strcmp(replay_gain_handler, "none") != 0) {
		ao->replay_gain_filter = filter_new(&replay_gain_filter_plugin,
						    param, NULL);
		assert(ao->replay_gain_filter != NULL);

		ao->replay_gain_serial = 0;

		ao->other_replay_gain_filter = filter_new(&replay_gain_filter_plugin,
							  param, NULL);
		assert(ao->other_replay_gain_filter != NULL);

		ao->other_replay_gain_serial = 0;
	} else {
		ao->replay_gain_filter = NULL;
		ao->other_replay_gain_filter = NULL;
	}

	/* create the normalization filter (if configured) */

	if (config_get_bool(CONF_VOLUME_NORMALIZATION, false)) {
		struct filter *normalize_filter =
			filter_new(&normalize_filter_plugin, NULL, NULL);
		assert(normalize_filter != NULL);

		filter_chain_append(ao->filter,
				    autoconvert_filter_new(normalize_filter));
	}

	filter_chain_parse(ao->filter,
	                   config_get_block_string(param, AUDIO_FILTERS, ""),
	                   &error
	);

	// It's not really fatal - Part of the filter chain has been set up already
	// and even an empty one will work (if only with unexpected behaviour)
	if (error != NULL) {
		g_warning("Failed to initialize filter chain for '%s': %s",
			  ao->name, error->message);
		g_error_free(error);
	}

	ao->thread = NULL;
	ao->command = AO_COMMAND_NONE;
	ao->mutex = g_mutex_new();
	ao->cond = g_cond_new();
	ao->player_control = pc;

	ao->data = ao_plugin_init(plugin,
				  &ao->config_audio_format,
				  param, error_r);
	if (ao->data == NULL)
		return false;

	ao->mixer = audio_output_load_mixer(ao->data, param,
					    plugin->mixer_plugin,
					    ao->filter, &error);
	if (ao->mixer == NULL && error != NULL) {
		g_warning("Failed to initialize hardware mixer for '%s': %s",
			  ao->name, error->message);
		g_error_free(error);
	}

	/* use the hardware mixer for replay gain? */

	if (strcmp(replay_gain_handler, "mixer") == 0) {
		if (ao->mixer != NULL)
			replay_gain_filter_set_mixer(ao->replay_gain_filter,
						     ao->mixer, 100);
		else
			g_warning("No such mixer for output '%s'", ao->name);
	} else if (strcmp(replay_gain_handler, "software") != 0 &&
		   ao->replay_gain_filter != NULL) {
		g_set_error(error_r, audio_output_quark(), 0,
			    "Invalid \"replay_gain_handler\" value");
		return false;
	}

	/* the "convert" filter must be the last one in the chain */

	ao->convert_filter = filter_new(&convert_filter_plugin, NULL, NULL);
	assert(ao->convert_filter != NULL);

	filter_chain_append(ao->filter, ao->convert_filter);

	/* done */

	return true;
}
Beispiel #15
0
static gssize
g_unix_input_stream_read (GInputStream  *stream,
			  void          *buffer,
			  gsize          count,
			  GCancellable  *cancellable,
			  GError       **error)
{
  GUnixInputStream *unix_stream;
  gssize res = -1;
  GPollFD poll_fds[2];
  int nfds;
  int poll_ret;

  unix_stream = G_UNIX_INPUT_STREAM (stream);

  poll_fds[0].fd = unix_stream->priv->fd;
  poll_fds[0].events = G_IO_IN;
  if (unix_stream->priv->is_pipe_or_socket &&
      g_cancellable_make_pollfd (cancellable, &poll_fds[1]))
    nfds = 2;
  else
    nfds = 1;

  while (1)
    {
      poll_fds[0].revents = poll_fds[1].revents = 0;
      do
	poll_ret = g_poll (poll_fds, nfds, -1);
      while (poll_ret == -1 && errno == EINTR);

      if (poll_ret == -1)
	{
          int errsv = errno;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error reading from file descriptor: %s"),
		       g_strerror (errsv));
	  break;
	}

      if (g_cancellable_set_error_if_cancelled (cancellable, error))
	break;

      if (!poll_fds[0].revents)
	continue;

      res = read (unix_stream->priv->fd, buffer, count);
      if (res == -1)
	{
          int errsv = errno;

	  if (errsv == EINTR || errsv == EAGAIN)
	    continue;

	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error reading from file descriptor: %s"),
		       g_strerror (errsv));
	}

      break;
    }

  g_cancellable_release_fd (cancellable);
  return res;
}
Beispiel #16
0
gboolean
ostree_admin_option_context_parse (GOptionContext *context,
                                   const GOptionEntry *main_entries,
                                   int *argc,
                                   char ***argv,
                                   OstreeAdminBuiltinFlags flags,
                                   OstreeSysroot **out_sysroot,
                                   GCancellable *cancellable,
                                   GError **error)
{
  /* Entries are listed in --help output in the order added.  We add the
   * main entries ourselves so that we can add the --sysroot entry first. */

  g_option_context_add_main_entries (context, global_admin_entries, NULL);

  if (!ostree_option_context_parse (context, main_entries, argc, argv, OSTREE_BUILTIN_FLAG_NO_REPO, NULL, cancellable, error))
    return FALSE;

  g_autoptr(GFile) sysroot_path = NULL;
  if (opt_sysroot != NULL)
    sysroot_path = g_file_new_for_path (opt_sysroot);

  g_autoptr(OstreeSysroot) sysroot = ostree_sysroot_new (sysroot_path);

  if (flags & OSTREE_ADMIN_BUILTIN_FLAG_SUPERUSER)
    {
      GFile *path = ostree_sysroot_get_path (sysroot);

      /* If sysroot path is "/" then user must be root. */
      if (!g_file_has_parent (path, NULL) && getuid () != 0)
        {
          g_set_error (error, G_IO_ERROR, G_IO_ERROR_PERMISSION_DENIED,
                       "You must be root to perform this command");
          return FALSE;
        }
    }

  if (opt_print_current_dir)
    {
      g_autoptr(GPtrArray) deployments = NULL;
      OstreeDeployment *first_deployment;
      g_autoptr(GFile) deployment_file = NULL;
      g_autofree char *deployment_path = NULL;

      if (!ostree_sysroot_load (sysroot, cancellable, error))
        return FALSE;

      deployments = ostree_sysroot_get_deployments (sysroot);
      if (deployments->len == 0)
        return glnx_throw (error, "Unable to find a deployment in sysroot");
      first_deployment = deployments->pdata[0];
      deployment_file = ostree_sysroot_get_deployment_directory (sysroot, first_deployment);
      deployment_path = g_file_get_path (deployment_file);

      g_print ("%s\n", deployment_path);

      /* The g_autoptr, g_autofree etc. don't happen when we explicitly
       * exit, making valgrind complain about leaks */
      g_clear_object (&sysroot);
      g_clear_object (&sysroot_path);
      g_clear_object (&deployment_file);
      g_clear_pointer (&deployments, g_ptr_array_unref);
      g_clear_pointer (&deployment_path, g_free);
      exit (EXIT_SUCCESS);
    }

  if ((flags & OSTREE_ADMIN_BUILTIN_FLAG_UNLOCKED) == 0)
    {
      /* Released when sysroot is finalized, or on process exit */
      if (!ot_admin_sysroot_lock (sysroot, error))
        return FALSE;
    }

  if (out_sysroot)
    *out_sysroot = g_steal_pointer (&sysroot);

  return TRUE;
}
static void
validate_one_property (const char *key, const char *value, gpointer user_data)
{
	ValidateInfo *info = (ValidateInfo *) user_data;
	int i;

	if (*(info->error))
		return;

	info->have_items = TRUE;

	/* 'name' is the setting name; always allowed but unused */
	if (!strcmp (key, NM_SETTING_NAME))
		return;

	for (i = 0; info->table[i].name; i++) {
		ValidProperty prop = info->table[i];
		long int tmp;

		if (strcmp (prop.name, key))
			continue;

		switch (prop.type) {
		case G_TYPE_STRING:
			return; /* valid */
		case G_TYPE_INT:
			errno = 0;
			tmp = strtol (value, NULL, 10);
			if (errno == 0 && tmp >= prop.int_min && tmp <= prop.int_max)
				return; /* valid */

			g_set_error (info->error,
			             NM_VPN_PLUGIN_ERROR,
			             NM_VPN_PLUGIN_ERROR_BAD_ARGUMENTS,
			             _("invalid integer property '%s' or out of range [%d -> %d]"),
			             key, prop.int_min, prop.int_max);
			break;
		case G_TYPE_BOOLEAN:
			if (!strcmp (value, "yes") || !strcmp (value, "no"))
				return; /* valid */

			g_set_error (info->error,
			             NM_VPN_PLUGIN_ERROR,
			             NM_VPN_PLUGIN_ERROR_BAD_ARGUMENTS,
			             _("invalid boolean property '%s' (not yes or no)"),
			             key);
			break;
		default:
			g_set_error (info->error,
			             NM_VPN_PLUGIN_ERROR,
			             NM_VPN_PLUGIN_ERROR_BAD_ARGUMENTS,
			             _("unhandled property '%s' type %s"),
			             key, g_type_name (prop.type));
			break;
		}
	}

	/* Did not find the property from valid_properties or the type did not match */
	if (!info->table[i].name && strncmp(key, "form:", 5)) {
		g_warning ("property '%s' unknown", key);
		if (0)
		g_set_error (info->error,
		             NM_VPN_PLUGIN_ERROR,
		             NM_VPN_PLUGIN_ERROR_BAD_ARGUMENTS,
		             _("property '%s' invalid or not supported"),
		             key);
	}
}
Beispiel #18
0
static gboolean
complete_connection (NMDevice *device,
                     NMConnection *connection,
                     const char *specific_object,
                     const GSList *existing_connections,
                     GError **error)
{
	NMDeviceWimax *self = NM_DEVICE_WIMAX (device);
	NMDeviceWimaxPrivate *priv = NM_DEVICE_WIMAX_GET_PRIVATE (self);
	NMSettingWimax *s_wimax;
	const GByteArray *setting_mac;
	const guint8 *hw_address;
	char *format;
	const char *nsp_name = NULL;
	NMWimaxNsp *nsp = NULL;
	GSList *iter;

	s_wimax = nm_connection_get_setting_wimax (connection);

	if (!specific_object) {
		/* If not given a specific object, we need at minimum an NSP name */
		if (!s_wimax) {
			g_set_error_literal (error,
			                     NM_WIMAX_ERROR,
			                     NM_WIMAX_ERROR_CONNECTION_INVALID,
			                     "A 'wimax' setting is required if no NSP path was given.");
			return FALSE;
		}

		nsp_name = nm_setting_wimax_get_network_name (s_wimax);
		if (!nsp_name || !strlen (nsp_name)) {
			g_set_error_literal (error,
			                     NM_WIMAX_ERROR,
			                     NM_WIMAX_ERROR_CONNECTION_INVALID,
			                     "A 'wimax' setting with a valid network name is required if no NSP path was given.");
			return FALSE;
		}

		/* Find a compatible NSP in the list */
		nsp = get_nsp_by_name (self, nsp_name);

		/* If we still don't have an NSP, then the WiMAX settings needs to be
		 * fully specified by the client.  Might not be able to find the NSP
		 * if the scan didn't find the NSP yet.
		 */
		if (!nsp) {
			if (!nm_setting_verify (NM_SETTING (s_wimax), NULL, error))
				return FALSE;
		}
	} else {
		/* Find a compatible NSP in the list */
		for (iter = priv->nsp_list; iter; iter = g_slist_next (iter)) {
			if (!strcmp (specific_object, nm_wimax_nsp_get_dbus_path (NM_WIMAX_NSP (iter->data)))) {
				nsp = NM_WIMAX_NSP (iter->data);
				break;
			}
		}

		if (!nsp) {
			g_set_error (error,
			             NM_WIMAX_ERROR,
			             NM_WIMAX_ERROR_NSP_NOT_FOUND,
			             "The NSP %s was not in the scan list.",
			             specific_object);
			return FALSE;
		}

		nsp_name = nm_wimax_nsp_get_name (nsp);
	}

	/* Add a WiMAX setting if one doesn't exist */
	if (!s_wimax) {
		s_wimax = (NMSettingWimax *) nm_setting_wimax_new ();
		nm_connection_add_setting (connection, NM_SETTING (s_wimax));
	}

	g_assert (nsp_name);
	format = g_strdup_printf ("%s %%d", nsp_name);
	nm_utils_complete_generic (connection,
	                           NM_SETTING_WIMAX_SETTING_NAME,
	                           existing_connections,
	                           format,
	                           nsp_name,
	                           TRUE);
	g_free (format);
	g_object_set (G_OBJECT (s_wimax), NM_SETTING_WIMAX_NETWORK_NAME, nsp_name, NULL);

	setting_mac = nm_setting_wimax_get_mac_address (s_wimax);
	hw_address = nm_device_get_hw_address (device, NULL);
	if (setting_mac) {
		/* Make sure the setting MAC (if any) matches the device's permanent MAC */
		if (memcmp (setting_mac->data, hw_address, ETH_ALEN)) {
			g_set_error (error,
				         NM_SETTING_WIMAX_ERROR,
				         NM_SETTING_WIMAX_ERROR_INVALID_PROPERTY,
				         NM_SETTING_WIMAX_MAC_ADDRESS);
			return FALSE;
		}
	} else {
		GByteArray *mac;
		const guint8 null_mac[ETH_ALEN] = { 0, 0, 0, 0, 0, 0 };

		/* Lock the connection to this device by default */
		if (memcmp (hw_address, null_mac, ETH_ALEN)) {
			mac = g_byte_array_sized_new (ETH_ALEN);
			g_byte_array_append (mac, hw_address, ETH_ALEN);
			g_object_set (G_OBJECT (s_wimax), NM_SETTING_WIMAX_MAC_ADDRESS, mac, NULL);
			g_byte_array_free (mac, TRUE);
		}
	}

	return TRUE;
}
static gboolean
kms_sdp_rtp_avpf_media_handler_rtcp_fb_attrs (KmsSdpMediaHandler * handler,
    GstSDPMedia * media, const gchar * fmt, const gchar * enc, GError ** error)
{
  KmsSdpRtpAvpfMediaHandler *self = KMS_SDP_RTP_AVPF_MEDIA_HANDLER (handler);
  gchar *attr;

  /* Add rtcp-fb attributes */

  if (!self->priv->nack) {
    goto no_nack;
  }

  attr = g_strdup_printf ("%s %s", fmt, SDP_MEDIA_RTCP_FB_NACK);

  if (gst_sdp_media_add_attribute (media, SDP_MEDIA_RTCP_FB,
          attr) != GST_SDP_OK) {
    g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR,
        "Cannot add media attribute 'a=%s'", attr);
    g_free (attr);
    return FALSE;
  }

  g_free (attr);
  attr = g_strdup_printf ("%s %s %s", fmt /* format */ , SDP_MEDIA_RTCP_FB_NACK,
      SDP_MEDIA_RTCP_FB_PLI);

  if (gst_sdp_media_add_attribute (media, SDP_MEDIA_RTCP_FB,
          attr) != GST_SDP_OK) {
    g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR,
        "Can add media attribute a=%s", attr);
    g_free (attr);
    return FALSE;
  }

  g_free (attr);

no_nack:
  if (!self->priv->remb) {
    goto no_remb;
  }

  if (g_str_has_prefix (enc, "VP8")) {
    /* Chrome adds goog-remb attribute */
    attr = g_strdup_printf ("%s %s", fmt, SDP_MEDIA_RTCP_FB_GOOG_REMB);

    if (gst_sdp_media_add_attribute (media, SDP_MEDIA_RTCP_FB,
            attr) != GST_SDP_OK) {
      g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR,
          "Cannot add media attribute 'a=%s'", attr);
      g_free (attr);
      return FALSE;
    }

    g_free (attr);
  }

no_remb:
  attr =
      g_strdup_printf ("%s %s %s", fmt, SDP_MEDIA_RTCP_FB_CCM,
      SDP_MEDIA_RTCP_FB_FIR);
  if (gst_sdp_media_add_attribute (media, SDP_MEDIA_RTCP_FB,
          attr) != GST_SDP_OK) {
    g_set_error (error, KMS_SDP_AGENT_ERROR, SDP_AGENT_UNEXPECTED_ERROR,
        "Cannot add media attribute 'a=%s'", attr);
    g_free (attr);
    return FALSE;
  }

  g_free (attr);

  return TRUE;
}
Beispiel #20
0
/** Parses a file into cells. This requires having an encoding that
 * works (see gnc_csv_convert_encoding). parse_data->options should be
 * set according to how the user wants before calling this
 * function. (Note: this function must be called with guessColTypes as
 * TRUE before it is ever called with it as FALSE.) (Note: if
 * guessColTypes is TRUE, all the column types will be GNC_CSV_NONE
 * right now.)
 * @param parse_data Data that is being parsed
 * @param guessColTypes TRUE to guess what the types of columns are based on the cell contents
 * @param error Will contain an error if there is a failure
 * @return 0 on success, 1 on failure
 */
int gnc_csv_parse(GncCsvParseData* parse_data, gboolean guessColTypes, GError** error)
{
    /* max_cols is the number of columns in the row with the most columns. */
    int i, max_cols = 0;

    if (parse_data->orig_lines != NULL)
    {
        stf_parse_general_free(parse_data->orig_lines);
    }

    /* If everything is fine ... */
    if (parse_data->file_str.begin != NULL)
    {
        /* Do the actual parsing. */
        parse_data->orig_lines = stf_parse_general(parse_data->options, parse_data->chunk,
        parse_data->file_str.begin,
        parse_data->file_str.end);
    }
    /* If we couldn't get the encoding right, we just want an empty array. */
    else
    {
        parse_data->orig_lines = g_ptr_array_new();
    }

    /* Record the original row lengths of parse_data->orig_lines. */
    if (parse_data->orig_row_lengths != NULL)
        g_array_free(parse_data->orig_row_lengths, FALSE);

    parse_data->orig_row_lengths =
    g_array_sized_new(FALSE, FALSE, sizeof(int), parse_data->orig_lines->len);
    g_array_set_size(parse_data->orig_row_lengths, parse_data->orig_lines->len);
    parse_data->orig_max_row = 0;
    for (i = 0; i < parse_data->orig_lines->len; i++)
    {
        int length = ((GPtrArray*)parse_data->orig_lines->pdata[i])->len;
        parse_data->orig_row_lengths->data[i] = length;
        if (length > parse_data->orig_max_row)
            parse_data->orig_max_row = length;
    }

    /* If it failed, generate an error. */
    if (parse_data->orig_lines == NULL)
    {
        g_set_error(error, 0, 0, "Parsing failed.");
        return 1;
    }

    /* Now that we have data, let's set max_cols. */
    for (i = 0; i < parse_data->orig_lines->len; i++)
    {
        if (max_cols < ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len)
            max_cols = ((GPtrArray*)(parse_data->orig_lines->pdata[i]))->len;
    }

    if (guessColTypes)
    {
        /* Free parse_data->column_types if it's already been created. */
        if (parse_data->column_types != NULL)
            g_array_free(parse_data->column_types, TRUE);

        /* Create parse_data->column_types and fill it with guesses based
         * on the contents of each column. */
        parse_data->column_types = g_array_sized_new(FALSE, FALSE, sizeof(int),
        max_cols);
        g_array_set_size(parse_data->column_types, max_cols);
        /* TODO Make it actually guess. */
        for (i = 0; i < parse_data->column_types->len; i++)
        {
            parse_data->column_types->data[i] = GNC_CSV_NONE;
        }
    }
    else
    {
        /* If we don't need to guess column types, we will simply set any
         * new columns that are created that didn't exist before to "None"
         * since we don't want gibberish to appear. Note:
         * parse_data->column_types should have already been
         * initialized, so we don't check for it being NULL. */
        int i = parse_data->column_types->len;
        g_array_set_size(parse_data->column_types, max_cols);
        for (; i < parse_data->column_types->len; i++)
        {
            parse_data->column_types->data[i] = GNC_CSV_NONE;
        }
    }

    return 0;
}
static gboolean
verify (NMSetting *setting, GSList *all_settings, GError **error)
{
	NMSettingGsmPrivate *priv = NM_SETTING_GSM_GET_PRIVATE (setting);

	if (priv->number && !priv->number[0]) {
		g_set_error (error,
		             NM_SETTING_GSM_ERROR,
		             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
		             NM_SETTING_GSM_NUMBER);
		return FALSE;
	}

	if (priv->apn) {
		guint32 apn_len = strlen (priv->apn);
		guint32 i;

		if (apn_len < 1 || apn_len > 64) {
			g_set_error (error,
			             NM_SETTING_GSM_ERROR,
			             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
			             NM_SETTING_GSM_APN);
			return FALSE;
		}

		/* APNs roughly follow the same rules as DNS domain names.  Allowed
		 * characters are a-z, 0-9, . and -.  GSM 03.03 Section 9.1 states:
		 *
		 *   The syntax of the APN shall follow the Name Syntax defined in
		 *   RFC 2181 [14] and RFC 1035 [15]. The APN consists of one or
		 *   more labels. Each label is coded as one octet length field
		 *   followed by that number of octets coded as 8 bit ASCII characters.
		 *   Following RFC 1035 [15] the labels should consist only of the
		 *   alphabetic characters (A-Z and a-z), digits (0-9) and the
		 *   dash (-). The case of alphabetic characters is not significant.
		 *
		 * A dot (.) is commonly used to separate parts of the APN, and
		 * apparently the underscore (_) is used as well.  RFC 2181 indicates
		 * that no restrictions of any kind are placed on DNS labels, and thus
		 * it would appear that none are placed on APNs either, but many modems
		 * and networks will fail to accept APNs that include odd characters
		 * like space ( ) and such.
		 */
		for (i = 0; i < apn_len; i++) {
			if (   !isalnum (priv->apn[i])
			    && (priv->apn[i] != '.')
			    && (priv->apn[i] != '_')
			    && (priv->apn[i] != '-')) {
				g_set_error (error,
				             NM_SETTING_GSM_ERROR,
				             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
				             NM_SETTING_GSM_APN);
				return FALSE;
			}
		}
	}

	if (priv->username && !strlen (priv->username)) {
		g_set_error (error,
		             NM_SETTING_GSM_ERROR,
		             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
		             NM_SETTING_GSM_USERNAME);
		return FALSE;
	}

	if (priv->password && !strlen (priv->password)) {
		g_set_error (error,
		             NM_SETTING_GSM_ERROR,
		             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
		             NM_SETTING_GSM_USERNAME);
		return FALSE;
	}

	if (priv->network_id) {
		guint32 nid_len = strlen (priv->network_id);
		guint32 i;

		/* Accept both 5 and 6 digit MCC/MNC codes */
		if ((nid_len < 5) || (nid_len > 6)) {
			g_set_error (error,
			             NM_SETTING_GSM_ERROR,
			             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
			             NM_SETTING_GSM_NETWORK_ID);
			return FALSE;
		}

		for (i = 0; i < nid_len; i++) {
			if (!isdigit (priv->network_id[i])) {
				g_set_error (error,
				             NM_SETTING_GSM_ERROR,
				             NM_SETTING_GSM_ERROR_INVALID_PROPERTY,
				             NM_SETTING_GSM_NETWORK_ID);
				return FALSE;
			}
		}
	}

	return TRUE;
}
Beispiel #22
0
/**
 * as_markup_convert_full:
 * @markup: the text to copy.
 * @format: the #AsMarkupConvertFormat, e.g. %AS_MARKUP_CONVERT_FORMAT_MARKDOWN
 * @flags: the #AsMarkupConvertFlag, e.g. %AS_MARKUP_CONVERT_FLAG_IGNORE_ERRORS
 * @error: A #GError or %NULL
 *
 * Converts an XML description into a printable form.
 *
 * Returns: (transfer full): a newly allocated %NULL terminated string
 *
 * Since: 0.3.5
 **/
gchar *
as_markup_convert_full (const gchar *markup,
			AsMarkupConvertFormat format,
			AsMarkupConvertFlag flags,
			GError **error)
{
	GNode *tmp;
	GNode *tmp_c;
	const gchar *tag;
	const gchar *tag_c;
	g_autoptr(AsNode) root = NULL;
	g_autoptr(GError) error_local = NULL;
	g_autoptr(GString) str = NULL;

	/* is this actually markup */
	if (g_strstr_len (markup, -1, "<") == NULL)
		return g_strdup (markup);

	/* load */
	root = as_node_from_xml (markup, AS_NODE_FROM_XML_FLAG_NONE, &error_local);
	if (root == NULL) {

		/* truncate to the last tag and try again */
		if (flags & AS_MARKUP_CONVERT_FLAG_IGNORE_ERRORS) {
			gchar *found;
			g_autofree gchar *markup_new = NULL;
			markup_new = g_strdup (markup);
			found = g_strrstr (markup_new, "<");
			g_assert (found != NULL);
			*found = '\0';
			return as_markup_convert_full (markup_new, format, flags, error);
		}

		/* just return error */
		g_propagate_error (error, error_local);
		error_local = NULL;
		return NULL;
	}

	/* format */
	str = g_string_new ("");
	for (tmp = root->children; tmp != NULL; tmp = tmp->next) {

		tag = as_node_get_name (tmp);
		if (g_strcmp0 (tag, "unknown") == 0)
			continue;
		if (g_strcmp0 (tag, "p") == 0) {
			as_markup_render_para (str, format, as_node_get_data (tmp));
			continue;
		}

		/* loop on the children */
		if (g_strcmp0 (tag, "ul") == 0 ||
		    g_strcmp0 (tag, "ol") == 0) {
			as_markup_render_ul_start (str, format);
			for (tmp_c = tmp->children; tmp_c != NULL; tmp_c = tmp_c->next) {
				tag_c = as_node_get_name (tmp_c);
				if (g_strcmp0 (tag_c, "unknown") == 0)
					continue;
				if (g_strcmp0 (tag_c, "li") == 0) {
					as_markup_render_li (str, format,
							     as_node_get_data (tmp_c));
					continue;
				}

				/* just abort the list */
				if (flags & AS_MARKUP_CONVERT_FLAG_IGNORE_ERRORS)
					break;

				/* only <li> is valid in lists */
				g_set_error (error,
					     AS_NODE_ERROR,
					     AS_NODE_ERROR_FAILED,
					     "Tag %s in %s invalid",
					     tag_c, tag);
				return NULL;
			}
			as_markup_render_ul_end (str, format);
			continue;
		}

		/* just try again */
		if (flags & AS_MARKUP_CONVERT_FLAG_IGNORE_ERRORS)
			continue;

		/* only <p>, <ul> and <ol> is valid here */
		g_set_error (error,
			     AS_NODE_ERROR,
			     AS_NODE_ERROR_FAILED,
			     "Unknown tag '%s'", tag);
		return NULL;
	}

	/* success */
	switch (format) {
	case AS_MARKUP_CONVERT_FORMAT_SIMPLE:
	case AS_MARKUP_CONVERT_FORMAT_MARKDOWN:
		if (str->len > 0)
			g_string_truncate (str, str->len - 1);
		break;
	default:
		break;
	}
	return g_strdup (str->str);
}
static gboolean
verify (NMSetting *setting, GSList *all_settings, GError **error)
{
	NMSettingVlanPrivate *priv = NM_SETTING_VLAN_GET_PRIVATE (setting);
	NMSettingConnection *s_con = NULL;
	NMSettingWired *s_wired = NULL;
	GSList *iter;

	for (iter = all_settings; iter; iter = iter->next) {
		if (NM_IS_SETTING_CONNECTION (iter->data))
			s_con = iter->data;
		else if (NM_IS_SETTING_WIRED (iter->data))
			s_wired = iter->data;
	}

	/* If iface_name is specified, it must be a valid interface name. We
	 * don't check that it matches parent and/or id, because we allowing
	 * renaming vlans to arbitrary names.
	 */
	if (priv->iface_name && !nm_utils_iface_valid_name (priv->iface_name)) {
		g_set_error (error,
		             NM_SETTING_VLAN_ERROR,
		             NM_SETTING_VLAN_ERROR_INVALID_PROPERTY,
		             NM_SETTING_VLAN_INTERFACE_NAME);
		return FALSE;
	}

	if (priv->parent) {
		if (nm_utils_is_uuid (priv->parent)) {
			/* If we have an NMSettingConnection:master with slave-type="vlan",
			 * then it must be the same UUID.
			 */
			if (s_con) {
				const char *master = NULL, *slave_type = NULL;

				slave_type = nm_setting_connection_get_slave_type (s_con);
				if (!g_strcmp0 (slave_type, NM_SETTING_VLAN_SETTING_NAME))
					master = nm_setting_connection_get_master (s_con);

				if (master && g_strcmp0 (priv->parent, master) != 0) {
					g_set_error (error,
					             NM_SETTING_VLAN_ERROR,
					             NM_SETTING_VLAN_ERROR_INVALID_PARENT,
					             NM_SETTING_CONNECTION_MASTER);
					return FALSE;
				}
			}
		} else if (!nm_utils_iface_valid_name (priv->parent)) {
			/* parent must be either a UUID or an interface name */
			g_set_error (error,
			             NM_SETTING_VLAN_ERROR,
			             NM_SETTING_VLAN_ERROR_INVALID_PROPERTY,
			             NM_SETTING_VLAN_PARENT);
			return FALSE;
		} 
	} else {
		/* If parent is NULL, the parent must be specified via
		 * NMSettingWired:mac-address.
		 */
		if (!s_wired || !nm_setting_wired_get_mac_address (s_wired)) {
			g_set_error (error,
			             NM_SETTING_VLAN_ERROR,
			             NM_SETTING_VLAN_ERROR_MISSING_PROPERTY,
			             NM_SETTING_VLAN_PARENT);
			return FALSE;
		}
	}

	if (priv->flags & ~(NM_VLAN_FLAG_REORDER_HEADERS |
	                    NM_VLAN_FLAG_GVRP |
	                    NM_VLAN_FLAG_LOOSE_BINDING)) {
		g_set_error (error,
		             NM_SETTING_VLAN_ERROR,
		             NM_SETTING_VLAN_ERROR_INVALID_PROPERTY,
		             NM_SETTING_VLAN_FLAGS);
		return FALSE;
	}

	return TRUE;
}
static gboolean
verify (NMSetting *setting, NMConnection *connection, GError **error)
{
	NMSettingVlanPrivate *priv = NM_SETTING_VLAN_GET_PRIVATE (setting);
	NMSettingConnection *s_con;
	NMSettingWired *s_wired;

	if (connection) {
		s_con = nm_connection_get_setting_connection (connection);
		s_wired = nm_connection_get_setting_wired (connection);
	} else {
		s_con = NULL;
		s_wired = NULL;
	}

	if (priv->parent) {
		if (nm_utils_is_uuid (priv->parent)) {
			/* If we have an NMSettingConnection:master with slave-type="vlan",
			 * then it must be the same UUID.
			 */
			if (s_con) {
				const char *master = NULL, *slave_type = NULL;

				slave_type = nm_setting_connection_get_slave_type (s_con);
				if (!g_strcmp0 (slave_type, NM_SETTING_VLAN_SETTING_NAME))
					master = nm_setting_connection_get_master (s_con);

				if (master && g_strcmp0 (priv->parent, master) != 0) {
					g_set_error (error,
					             NM_CONNECTION_ERROR,
					             NM_CONNECTION_ERROR_INVALID_PROPERTY,
					             _("'%s' value doesn't match '%s=%s'"),
					             priv->parent, NM_SETTING_CONNECTION_MASTER, master);
					g_prefix_error (error, "%s.%s: ", NM_SETTING_VLAN_SETTING_NAME, NM_SETTING_VLAN_PARENT);
					return FALSE;
				}
			}
		} else if (!nm_utils_iface_valid_name (priv->parent)) {
			/* parent must be either a UUID or an interface name */
			g_set_error (error,
			             NM_CONNECTION_ERROR,
			             NM_CONNECTION_ERROR_INVALID_PROPERTY,
			             _("'%s' is neither an UUID nor an interface name"),
			             priv->parent);
			g_prefix_error (error, "%s.%s: ", NM_SETTING_VLAN_SETTING_NAME, NM_SETTING_VLAN_PARENT);
			return FALSE;
		}
	} else {
		/* If parent is NULL, the parent must be specified via
		 * NMSettingWired:mac-address.
		 */
		if (   connection
		    && (!s_wired || !nm_setting_wired_get_mac_address (s_wired))) {
			g_set_error (error,
			             NM_CONNECTION_ERROR,
			             NM_CONNECTION_ERROR_MISSING_PROPERTY,
			             _("property is not specified and neither is '%s:%s'"),
			             NM_SETTING_WIRED_SETTING_NAME, NM_SETTING_WIRED_MAC_ADDRESS);
			g_prefix_error (error, "%s.%s: ", NM_SETTING_VLAN_SETTING_NAME, NM_SETTING_VLAN_PARENT);
			return FALSE;
		}
	}

	if (priv->id >= 4095) {
		g_set_error (error,
		             NM_CONNECTION_ERROR,
		             NM_CONNECTION_ERROR_INVALID_PROPERTY,
		             _("the vlan id must be in range 0-4094 but is %u"),
		             priv->id);
		g_prefix_error (error, "%s.%s: ", NM_SETTING_VLAN_SETTING_NAME, NM_SETTING_VLAN_ID);
	}

	if (priv->flags & ~NM_VLAN_FLAGS_ALL) {
		g_set_error_literal (error,
		                     NM_CONNECTION_ERROR,
		                     NM_CONNECTION_ERROR_INVALID_PROPERTY,
		                     _("flags are invalid"));
		g_prefix_error (error, "%s.%s: ", NM_SETTING_VLAN_SETTING_NAME, NM_SETTING_VLAN_FLAGS);
		return FALSE;
	}

	return TRUE;
}
/*! \brief Create picture OBJECT from character string.
 *  \par Function Description
 *  Parses \a first_line and subsequent lines from \a tb, and returns
 *  a newly-created picture #OBJECT.
 *
 *  \param [in]  toplevel       The TOPLEVEL object.
 *  \param [in]  first_line      Character string with picture description.
 *  \param [in]  tb              Text buffer to load embedded data from.
 *  \param [in]  release_ver     libgeda release version number.
 *  \param [in]  fileformat_ver  libgeda file format version number.
 *  \return A pointer to the new picture object, or NULL on error.
 */
OBJECT *o_picture_read (TOPLEVEL *toplevel,
                        const char *first_line,
                        TextBuffer *tb,
                        unsigned int release_ver,
                        unsigned int fileformat_ver,
                        GError **err)
{
  OBJECT *new_obj;
  int x1, y1;
  int width, height, angle;
  int mirrored, embedded;
  int num_conv;
  gchar type;
  const gchar *line = NULL;
  gchar *filename;
  gchar *file_content = NULL;
  guint file_length = 0;

  num_conv = sscanf(first_line, "%c %d %d %d %d %d %d %d\n",
                    &type, &x1, &y1, &width, &height, &angle, &mirrored, &embedded);

  if (num_conv != 8) {
    g_set_error(err, EDA_ERROR, EDA_ERROR_PARSE, _("Failed to parse picture definition"));
    return NULL;
  }

  if (width == 0 || height == 0) {
    s_log_message(_("Found a zero width/height picture "
                    "[ %1$c %2$d %3$d %4$d %5$d ]"),
                  type, x1, y1, width, height);
  }

  if ( (mirrored > 1) || (mirrored < 0)) {
    s_log_message(_("Found a picture with a wrong 'mirrored' parameter: %1$d."),
                  mirrored);
    s_log_message(_("Setting mirrored to 0."));
    mirrored = 0;
  }

  if ( (embedded > 1) || (embedded < 0)) {
    s_log_message(_("Found a picture with a wrong 'embedded' parameter: %1$d."),
                  embedded);
    s_log_message(_("Setting embedded to 0."));
    embedded = 0;
  }

  switch(angle) {

    case(0):
    case(90):
    case(180):
    case(270):
    break;

    default:
      s_log_message(_("Found an unsupported picture angle [ %1$d ]"), angle);
      s_log_message(_("Setting angle to 0."));
      angle=0;
      break;

  }

  filename = g_strdup(s_textbuffer_next_line(tb));
  filename = geda_string_remove_ending_newline (filename);

  /* Handle empty filenames */
  if (strlen (filename) == 0) {
    s_log_message (_("Found an image with no filename."));
    g_free (filename);
    filename = NULL;
  }

  if (embedded == 1) {
    GString *encoded_picture=g_string_new("");
    char finished = 0;

    /* Read the encoded picture */
    do {

      line = s_textbuffer_next_line(tb);
      if (line == NULL) break;

      if (strcmp (line, ".\n") != 0) {
        encoded_picture = g_string_append (encoded_picture, line);
      } else {
        finished = 1;
      }
    } while (finished == 0);

    /* Decode the picture */
    if (encoded_picture != NULL) {
      file_content = s_encoding_base64_decode(encoded_picture->str,
                                              encoded_picture->len,
                                              &file_length);
      g_string_free (encoded_picture, TRUE);
    }

    if (file_content == NULL) {
      s_log_message (_("Failed to load image from embedded data [%1$s]: %2$s"),
                     filename, _("Base64 decoding failed."));
      s_log_message (_("Falling back to file loading. Picture unembedded."));
      embedded = 0;
    }
  }

  /* create the picture */
  /* The picture is described by its upper left and lower right corner */
  new_obj = o_picture_new (toplevel, file_content, file_length, filename,
                           type,
                           x1, y1+height, x1+width, y1,
                           angle, mirrored, embedded);

  g_free (file_content);
  g_free (filename);

  return new_obj;
}
Beispiel #26
0
static gboolean
fu_altos_device_write_firmware (FuDevice *device, GBytes *fw, GError **error)
{
	FuAltosDevice *self = FU_ALTOS_DEVICE (device);
	GBytes *fw_blob;
	const gchar *data;
	const gsize data_len;
	guint flash_len;
	g_autoptr(FuAltosFirmware) altos_firmware = NULL;
	g_autoptr(FuDeviceLocker) locker  = NULL;
	g_autoptr(GString) buf = g_string_new (NULL);

	/* check kind */
	if (self->kind != FU_ALTOS_DEVICE_KIND_BOOTLOADER) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_NOT_SUPPORTED,
				     "verification only supported in bootloader");
		return FALSE;
	}

	/* check sizes */
	if (self->addr_base == 0x0 || self->addr_bound == 0x0) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_NOT_SUPPORTED,
				     "address base and bound are unset");
		return FALSE;
	}

	/* read in blocks of 256 bytes */
	flash_len = self->addr_bound - self->addr_base;
	if (flash_len == 0x0 || flash_len > 0x100000) {
		g_set_error_literal (error,
				     FWUPD_ERROR,
				     FWUPD_ERROR_NOT_SUPPORTED,
				     "address range was icorrect");
		return FALSE;
	}

	/* load ihex blob */
	altos_firmware = fu_altos_firmware_new ();
	if (!fu_altos_firmware_parse (altos_firmware, fw, error))
		return FALSE;

	/* check the start address */
	if (fu_altos_firmware_get_address (altos_firmware) != self->addr_base) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_INVALID_FILE,
			     "start address not correct %" G_GUINT64_FORMAT ":"
			     "%" G_GUINT64_FORMAT,
			     fu_altos_firmware_get_address (altos_firmware),
			     self->addr_base);
		return FALSE;
	}

	/* check firmware will fit */
	fw_blob = fu_altos_firmware_get_data (altos_firmware);
	data = g_bytes_get_data (fw_blob, (gsize *) &data_len);
	if (data_len > flash_len) {
		g_set_error (error,
			     FWUPD_ERROR,
			     FWUPD_ERROR_INVALID_FILE,
			     "firmware too large for device %" G_GSIZE_FORMAT ":%u",
			     data_len, flash_len);
		return FALSE;
	}

	/* open tty for download */
	locker = fu_device_locker_new_full (device,
					    (FuDeviceLockerFunc) fu_altos_device_tty_open,
					    (FuDeviceLockerFunc) fu_altos_device_tty_close,
					    error);
	if (locker == NULL)
		return FALSE;
	for (guint i = 0; i < flash_len; i+= 0x100) {
		g_autoptr(GString) str = NULL;
		guint8 buf_tmp[0x100];

		/* copy remaining data into buf if required */
		memset (buf_tmp, 0xff, sizeof (buf));
		if (i < data_len) {
			gsize chunk_len = 0x100;
			if (i + 0x100 > data_len)
				chunk_len = data_len - i;
			memcpy (buf_tmp, data + i, chunk_len);
		}

		/* verify data from device */
		if (!fu_altos_device_write_page (self,
						 self->addr_base + i,
						 buf_tmp,
						 0x100,
						 error))
			return FALSE;

		/* verify data written on device */
		str = fu_altos_device_read_page (self,
						 self->addr_base + i,
						 error);
		if (str == NULL)
			return FALSE;
		if (str->len != 0x100) {
			g_set_error (error,
					     FWUPD_ERROR,
					     FWUPD_ERROR_WRITE,
					     "failed to verify @%x, "
					     "not enough data returned",
					     (guint) (self->addr_base + i));
			return FALSE;
		}
		if (memcmp (str->str, buf_tmp, 0x100) != 0) {
			g_set_error (error,
					     FWUPD_ERROR,
					     FWUPD_ERROR_WRITE,
					     "failed to verify @%x",
					     (guint) (self->addr_base + i));
			return FALSE;
		}

		/* progress */
		fu_device_set_progress_full (device, i, flash_len);
		g_string_append_len (buf, str->str, str->len);
	}

	/* go to application mode */
	if (!fu_altos_device_tty_write (self, "a\n", -1, error))
		return FALSE;

	/* progress complete */
	fu_device_set_progress_full (device, flash_len, flash_len);

	/* success */
	return TRUE;
}
Beispiel #27
0
GMountSpec *
g_mount_spec_new_from_string (const gchar     *str,
                              GError         **error)
{
  GArray *items;
  GMountSpec *mount_spec;
  char **kv_pairs;
  char *mount_prefix;
  const char *colon;
  GMountSpecItem item;
  int i;

  g_return_val_if_fail (str != NULL, NULL);

  mount_spec = NULL;
  mount_prefix = NULL;
  items = g_array_new (FALSE, TRUE, sizeof (GMountSpecItem));

  colon = strchr (str, ':');
  if (colon)
    {
      item.key = g_strdup ("type");
      item.value = g_strndup (str, colon - str);
      g_array_append_val (items, item);
      str = colon + 1;
    }

  kv_pairs = g_strsplit (str, ",", 0);
  for (i = 0; kv_pairs[i] != NULL; i++)
    {
      char **tokens;

      tokens = g_strsplit (kv_pairs[i], "=", 0);
      if (g_strv_length (tokens) != 2)
        {
          g_set_error (error,
                       G_IO_ERROR,
                       G_IO_ERROR_INVALID_ARGUMENT,
                       "Encountered invalid key/value pair '%s' while decoding GMountSpec",
                       kv_pairs[i]);
          g_strfreev (tokens);
          g_strfreev (kv_pairs);
          goto fail;
        }

      item.value = g_uri_unescape_string (tokens[1], NULL);
      if (strcmp (tokens[0], "prefix") == 0)
        {
          g_free (mount_prefix);
          mount_prefix = item.value;
        }
      else
        {
	  item.key = g_strdup (tokens[0]);
          g_array_append_val (items, item);
        }

      g_strfreev (tokens);
    }
  g_strfreev (kv_pairs);

  if (mount_prefix == NULL)
    mount_prefix = g_strdup ("/");

  /* this constructor takes ownership of the data we pass in */
  mount_spec = g_mount_spec_new_from_data (items,
                                           mount_prefix);

  return mount_spec;

 fail:
  for (i = 0; i < items->len; i++)
    {
      GMountSpecItem *item = &g_array_index (items, GMountSpecItem, i);
      g_free (item->key);
      g_free (item->value);
    }
  g_array_free (items, TRUE);
  g_free (mount_prefix);
  return NULL;
}
Beispiel #28
0
/**
 * gda_data_model_array_copy_model_ext:
 * @src: a #GdaDataModel to copy data from
 * @ncols: size of @cols
 * @cols: (array length=ncols): array of @src's columns to copy into the new array, not %NULL
 * @error: a place to store errors, or %NULL
 *
 * Like gda_data_model_array_copy_model(), makes a copy of @src, but copies only some
 * columns.
 *
 * Returns: (transfer full) (allow-none): a new data model, or %NULL if an error occurred
 *
 * Since: 5.2.0
 */
GdaDataModelArray *
gda_data_model_array_copy_model_ext (GdaDataModel *src, gint ncols, gint *cols, GError **error)
{
	GdaDataModel *model;
	gint nbfields, i;

	g_return_val_if_fail (GDA_IS_DATA_MODEL (src), NULL);
	g_return_val_if_fail (cols, NULL);
	g_return_val_if_fail (ncols > 0, NULL);

	/* check columns' validity */
	nbfields = gda_data_model_get_n_columns (src);
	for (i = 0; i < ncols; i++) {
		if ((cols[i] < 0) || (cols[i] >= nbfields)) {
			g_set_error (error, GDA_DATA_MODEL_ERROR,
				     GDA_DATA_MODEL_COLUMN_OUT_OF_RANGE_ERROR,
                                     _("Column %d out of range (0-%d)"), cols[i], nbfields - 1);
			return NULL;
		}
	}

	/* initialize new model */
	model = gda_data_model_array_new (ncols);
	if (g_object_get_data (G_OBJECT (src), "name"))
		g_object_set_data_full (G_OBJECT (model), "name", g_strdup (g_object_get_data (G_OBJECT (src), "name")), g_free);
	if (g_object_get_data (G_OBJECT (src), "descr"))
		g_object_set_data_full (G_OBJECT (model), "descr", g_strdup (g_object_get_data (G_OBJECT (src), "descr")), g_free);


	/* map new columns */
	GHashTable *hash;
	hash = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, NULL);
	for (i = 0; i < ncols; i++) {
		gint *ptr;
		ptr = g_new (gint, 1);
		*ptr = i;
		g_hash_table_insert (hash, ptr, GINT_TO_POINTER (cols[i]));

		GdaColumn *copycol, *srccol;
		gchar *colid;

		srccol = gda_data_model_describe_column (src, cols[i]);
		copycol = gda_data_model_describe_column (model, i);

		g_object_get (G_OBJECT (srccol), "id", &colid, NULL);
		g_object_set (G_OBJECT (copycol), "id", colid, NULL);
		g_free (colid);
		gda_column_set_description (copycol, gda_column_get_description (srccol));
		gda_column_set_name (copycol, gda_column_get_name (srccol));
		gda_column_set_dbms_type (copycol, gda_column_get_dbms_type (srccol));
		gda_column_set_g_type (copycol, gda_column_get_g_type (srccol));
		gda_column_set_position (copycol, gda_column_get_position (srccol));
		gda_column_set_allow_null (copycol, gda_column_get_allow_null (srccol));
	}

	if (! gda_data_model_import_from_model (model, src, FALSE, hash, error)) {
		g_hash_table_destroy (hash);
		g_object_unref (model);
		model = NULL;
	}
	/*else
	  gda_data_model_dump (model, stdout);*/

	g_hash_table_destroy (hash);
	return (GdaDataModelArray*) model;
}
Beispiel #29
0
static BraseroBurnResult
brasero_cdrecord_set_argv_record (BraseroCDRecord *cdrecord,
				  GPtrArray *argv, 
				  GError **error)
{
	guint speed;
	BraseroBurnFlag flags;
	BraseroCDRecordPrivate *priv;
	BraseroTrackType *type = NULL;

	priv = BRASERO_CD_RECORD_PRIVATE (cdrecord);

	if (priv->immediate) {
		g_ptr_array_add (argv, g_strdup ("-immed"));
		g_ptr_array_add (argv, g_strdup_printf ("minbuf=%i", priv->minbuf));
	}

	if (brasero_job_get_speed (BRASERO_JOB (cdrecord), &speed) == BRASERO_BURN_OK) {
		gchar *speed_str;

		speed_str = g_strdup_printf ("speed=%d", speed);
		g_ptr_array_add (argv, speed_str);
	}

	brasero_job_get_flags (BRASERO_JOB (cdrecord), &flags);
	if (flags & BRASERO_BURN_FLAG_OVERBURN)
		g_ptr_array_add (argv, g_strdup ("-overburn"));
	if (flags & BRASERO_BURN_FLAG_BURNPROOF)
		g_ptr_array_add (argv, g_strdup ("driveropts=burnfree"));
	if (flags & BRASERO_BURN_FLAG_MULTI)
		g_ptr_array_add (argv, g_strdup ("-multi"));

	/* NOTE: This write mode is necessary for all CLONE images burning */
	if (flags & BRASERO_BURN_FLAG_RAW)
		g_ptr_array_add (argv, g_strdup ("-raw96r"));

	/* NOTE1: DAO can't be used if we're appending to a disc */
	/* NOTE2: CD-text cannot be written in tao mode (which is the default)
	 * NOTE3: when we don't want wodim to use stdin then we give the audio
	 * file on the command line. Otherwise we use the .inf */
	if (flags & BRASERO_BURN_FLAG_DAO)
		g_ptr_array_add (argv, g_strdup ("-dao"));

	type = brasero_track_type_new ();
	brasero_job_get_input_type (BRASERO_JOB (cdrecord), type);

	if (brasero_job_get_fd_in (BRASERO_JOB (cdrecord), NULL) == BRASERO_BURN_OK) {
		BraseroBurnResult result;
		int buffer_size;
		goffset sectors;
		
		/* we need to know what is the type of the track (audio / data) */
		result = brasero_job_get_input_type (BRASERO_JOB (cdrecord), type);
		if (result != BRASERO_BURN_OK) {
			brasero_track_type_free (type);

			BRASERO_JOB_LOG (cdrecord, "Imager doesn't seem to be ready")
			g_set_error (error,
				     BRASERO_BURN_ERROR,
				     BRASERO_BURN_ERROR_GENERAL,
				     _("An internal error occurred"));
			return BRASERO_BURN_ERR;
		}
		
		/* ask the size */
		result = brasero_job_get_session_output_size (BRASERO_JOB (cdrecord),
							      &sectors,
							      NULL);
		if (result != BRASERO_BURN_OK) {
			brasero_track_type_free (type);

			BRASERO_JOB_LOG (cdrecord, "The size of the session cannot be retrieved")
			g_set_error (error,
				     BRASERO_BURN_ERROR,
				     BRASERO_BURN_ERROR_GENERAL,
				     _("An internal error occurred"));
			return BRASERO_BURN_ERR;
		}

		/* we create a buffer depending on the size 
		 * buffer 4m> < 64m and is 1/25th of size otherwise */
		buffer_size = sectors * 2352 / 1024 / 1024 / 25;
		if (buffer_size > 32)
			buffer_size = 32;
		else if (buffer_size < 4)
			buffer_size = 4;

		g_ptr_array_add (argv, g_strdup_printf ("fs=%im", buffer_size));
		if (brasero_track_type_get_has_image (type)) {
			BraseroImageFormat format;

			format = brasero_track_type_get_image_format (type);
			if (format == BRASERO_IMAGE_FORMAT_BIN) {
				g_ptr_array_add (argv, g_strdup_printf ("tsize=%"G_GINT64_FORMAT"s", sectors));
				g_ptr_array_add (argv, g_strdup ("-data"));
				g_ptr_array_add (argv, g_strdup ("-nopad"));
				g_ptr_array_add (argv, g_strdup ("-"));
			}
			else {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_SUPPORTED (cdrecord);
			}
		}
		else if (brasero_track_type_get_has_stream (type)) {
			g_ptr_array_add (argv, g_strdup ("-audio"));
			g_ptr_array_add (argv, g_strdup ("-useinfo"));
			g_ptr_array_add (argv, g_strdup ("-text"));

			result = brasero_cdrecord_write_infs (cdrecord,
							      argv,
							      error);
			if (result != BRASERO_BURN_OK) {
				brasero_track_type_free (type);
				return result;
			}
		}
		else {
			brasero_track_type_free (type);
			BRASERO_JOB_NOT_SUPPORTED (cdrecord);
		}
	}
	else if (brasero_track_type_get_has_stream (type)) {
		BraseroBurnResult result;
		GSList *tracks;

		g_ptr_array_add (argv, g_strdup ("fs=16m"));
		g_ptr_array_add (argv, g_strdup ("-audio"));
		g_ptr_array_add (argv, g_strdup ("-pad"));
	
		g_ptr_array_add (argv, g_strdup ("-useinfo"));
		g_ptr_array_add (argv, g_strdup ("-text"));

		result = brasero_cdrecord_write_infs (cdrecord,
						      NULL,
						      error);
		if (result != BRASERO_BURN_OK) {
			brasero_track_type_free (type);
			return result;
		}

		tracks = NULL;
		brasero_job_get_tracks (BRASERO_JOB (cdrecord), &tracks);
		for (; tracks; tracks = tracks->next) {
			BraseroTrack *track;
			gchar *path;

			track = tracks->data;
			path = brasero_track_stream_get_source (BRASERO_TRACK_STREAM (track), FALSE);
			g_ptr_array_add (argv, path);
		}
	}
	else if (brasero_track_type_get_has_image (type)) {
		BraseroTrack *track = NULL;
		BraseroImageFormat format;

		brasero_job_get_current_track (BRASERO_JOB (cdrecord), &track);
		if (!track) {
			brasero_track_type_free (type);
			BRASERO_JOB_NOT_READY (cdrecord);
		}

		format = brasero_track_type_get_image_format (type);
		if (format == BRASERO_IMAGE_FORMAT_NONE) {
			gchar *image_path;

			image_path = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!image_path) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			g_ptr_array_add (argv, g_strdup ("fs=16m"));
			g_ptr_array_add (argv, g_strdup ("-data"));
			g_ptr_array_add (argv, g_strdup ("-nopad"));
			g_ptr_array_add (argv, image_path);
		}
		else if (format == BRASERO_IMAGE_FORMAT_BIN) {
			gchar *isopath;

			isopath = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!isopath) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			g_ptr_array_add (argv, g_strdup ("fs=16m"));
			g_ptr_array_add (argv, g_strdup ("-data"));
			g_ptr_array_add (argv, g_strdup ("-nopad"));
			g_ptr_array_add (argv, isopath);
		}
		else if (format == BRASERO_IMAGE_FORMAT_CLONE) {
			gchar *rawpath;

			rawpath = brasero_track_image_get_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!rawpath) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			g_ptr_array_add (argv, g_strdup ("fs=16m"));
			g_ptr_array_add (argv, g_strdup ("-clone"));
			g_ptr_array_add (argv, rawpath);
		}
		else if (format == BRASERO_IMAGE_FORMAT_CUE) {
			gchar *cue_str;
			gchar *cuepath;
			gchar *parent;

			cuepath = brasero_track_image_get_toc_source (BRASERO_TRACK_IMAGE (track), FALSE);
			if (!cuepath) {
				brasero_track_type_free (type);
				BRASERO_JOB_NOT_READY (cdrecord);
			}

			parent = g_path_get_dirname (cuepath);
			brasero_process_set_working_directory (BRASERO_PROCESS (cdrecord), parent);
			g_free (parent);

			/* we need to check endianness */
			if (brasero_track_image_need_byte_swap (BRASERO_TRACK_IMAGE (track)))
				g_ptr_array_add (argv, g_strdup ("-swab"));

			g_ptr_array_add (argv, g_strdup ("fs=16m"));

			/* This is to make sure the CD-TEXT stuff gets written */
			g_ptr_array_add (argv, g_strdup ("-text"));

			cue_str = g_strdup_printf ("cuefile=%s", cuepath);
			g_ptr_array_add (argv, cue_str);
			g_free (cuepath);
		}
		else {
			brasero_track_type_free (type);
			BRASERO_JOB_NOT_SUPPORTED (cdrecord);
		}
	}
	else {
		brasero_track_type_free (type);
		BRASERO_JOB_NOT_SUPPORTED (cdrecord);
	}

	brasero_track_type_free (type);

	brasero_job_set_current_action (BRASERO_JOB (cdrecord),
					BRASERO_BURN_ACTION_START_RECORDING,
					NULL,
					FALSE);
	return BRASERO_BURN_OK;
}
Beispiel #30
0
static bool
mvp_set_pcm_params(struct mvp_data *md, struct audio_format *audio_format,
		   GError **error)
{
	unsigned mix[5];

	switch (audio_format->channels) {
	case 1:
		mix[0] = 1;
		break;

	case 2:
		mix[0] = 0;
		break;

	default:
		g_debug("unsupported channel count %u - falling back to stereo",
			audio_format->channels);
		audio_format->channels = 2;
		mix[0] = 0;
		break;
	}

	/* 0,1=24bit(24) , 2,3=16bit */
	switch (audio_format->format) {
	case SAMPLE_FORMAT_S16:
		mix[1] = 2;
		break;

	case SAMPLE_FORMAT_S24_P32:
		mix[1] = 0;
		break;

	default:
		g_debug("unsupported sample format %s - falling back to 16 bit",
			sample_format_to_string(audio_format->format));
		audio_format->format = SAMPLE_FORMAT_S16;
		mix[1] = 2;
		break;
	}

	mix[3] = 0;	/* stream type? */
	mix[4] = G_BYTE_ORDER == G_LITTLE_ENDIAN;

	/*
	 * if there is an exact match for the frequency, use it.
	 */
	mix[2] = mvp_find_sample_rate(audio_format->sample_rate);
	if (mix[2] == (unsigned)-1) {
		g_set_error(error, mvp_output_quark(), 0,
			    "Can not find suitable output frequency for %u",
			    audio_format->sample_rate);
		return false;
	}

	if (ioctl(md->fd, MVP_SET_AUD_FORMAT, &mix) < 0) {
		g_set_error(error, mvp_output_quark(), errno,
			    "Can not set audio format");
		return false;
	}

	if (ioctl(md->fd, MVP_SET_AUD_SYNC, 2) != 0) {
		g_set_error(error, mvp_output_quark(), errno,
			    "Can not set audio sync");
		return false;
	}

	if (ioctl(md->fd, MVP_SET_AUD_PLAY, 0) < 0) {
		g_set_error(error, mvp_output_quark(), errno,
			    "Can not set audio play mode");
		return false;
	}

	return true;
}