Ejemplo n.º 1
0
static VALUE
rg_set_name(VALUE self, VALUE name)
{
    _SELF(self)->name = g_strdup(RVAL2CSTR(name));
    return self;
}
Ejemplo n.º 2
0
void
ags_recall_ladspa_set_property(GObject *gobject,
			       guint prop_id,
			       const GValue *value,
			       GParamSpec *param_spec)
{
  AgsRecallLadspa *recall_ladspa;

  recall_ladspa = AGS_RECALL_LADSPA(gobject);

  switch(prop_id){
  case PROP_FILENAME:
    {
      gchar *filename;

      filename = g_value_get_string(value);

      if(filename == recall_ladspa->filename){
	return;
      }

      if(recall_ladspa->filename != NULL){
	g_free(recall_ladspa->filename);
      }

      recall_ladspa->filename = g_strdup(filename);
    }
    break;
  case PROP_EFFECT:
    {
      gchar *effect;
      
      effect = g_value_get_string(value);

      if(effect == recall_ladspa->effect){
	return;
      }

      if(recall_ladspa->effect != NULL){
	g_free(recall_ladspa->effect);
      }

      recall_ladspa->effect = g_strdup(effect);
    }
    break;
  case PROP_INDEX:
    {
      unsigned long *effect_index;
      
      effect_index = g_value_get_ulong(value);

      if(effect_index == recall_ladspa->effect_index){
	return;
      }

      recall_ladspa->effect_index = effect_index;
    }
    break;
  default:
    G_OBJECT_WARN_INVALID_PROPERTY_ID(gobject, prop_id, param_spec);
    break;
  };
}
Ejemplo n.º 3
0
/**
 * ags_recall_ladspa_load_ports:
 * @recall_ladspa: an #AgsRecallLadspa
 *
 * Set up LADSPA ports.
 *
 * Returns: a #GList containing #AgsPort.
 * 
 * Since: 0.4.2
 */
GList*
ags_recall_ladspa_load_ports(AgsRecallLadspa *recall_ladspa)
{
  AgsLadspaPlugin *ladspa_plugin;
  AgsPort *current;
  GList *port;
  unsigned long port_count;
  unsigned long i;

  void *plugin_so;
  LADSPA_Descriptor_Function ladspa_descriptor;
  LADSPA_Descriptor *plugin_descriptor;
  LADSPA_PortDescriptor *port_descriptor;
  LADSPA_PortRangeHintDescriptor hint_descriptor;

  ags_ladspa_manager_load_file(recall_ladspa->filename);
  ladspa_plugin = ags_ladspa_manager_find_ladspa_plugin(recall_ladspa->filename);
  port = NULL;
  
  plugin_so = ladspa_plugin->plugin_so;

  if(plugin_so != NULL){
    ladspa_descriptor = (LADSPA_Descriptor_Function) dlsym(plugin_so,
							   "ladspa_descriptor\0");

    if(dlerror() == NULL && ladspa_descriptor){
      recall_ladspa->plugin_descriptor = 
	plugin_descriptor = ladspa_descriptor(recall_ladspa->effect_index);

      port_count = plugin_descriptor->PortCount;
      port_descriptor = plugin_descriptor->PortDescriptors;

      for(i = 0; i < port_count; i++){
	if(LADSPA_IS_PORT_CONTROL(port_descriptor[i])){
	  if(LADSPA_IS_PORT_INPUT(port_descriptor[i]) ||
	     LADSPA_IS_PORT_OUTPUT(port_descriptor[i])){
	    gchar *plugin_name;
	    gchar *specifier;

	    hint_descriptor = plugin_descriptor->PortRangeHints[i].HintDescriptor;

	    plugin_name = g_strdup_printf("ladspa-%lu\0", plugin_descriptor->UniqueID);
	    specifier = g_strdup(plugin_descriptor->PortNames[i]);

	    current = g_object_new(AGS_TYPE_PORT,
				   "plugin-name\0", plugin_name,
				   "specifier\0", specifier,
				   "control-port\0", g_strdup_printf("%d/%d\0",
								     i,
								     port_count),
				   "port-value-is-pointer\0", FALSE,
				   "port-value-type\0", G_TYPE_FLOAT,
				   NULL);
	    current->port_value.ags_port_float = plugin_descriptor->PortRangeHints[i].LowerBound;

	    g_message("connecting port: %d/%d\0", i, port_count);

	    port = g_list_prepend(port,
				  current);
	  }
	}else if(LADSPA_IS_PORT_AUDIO(port_descriptor[i])){
	  if(LADSPA_IS_PORT_INPUT(port_descriptor[i])){
	    if(recall_ladspa->input_port == NULL){
	      recall_ladspa->input_port = (unsigned long *) malloc(sizeof(unsigned long));
	      recall_ladspa->input_port[0] = i;
	    }else{
	      recall_ladspa->input_port = (unsigned long *) realloc(recall_ladspa->input_port,
								    (recall_ladspa->input_lines + 1) * sizeof(unsigned long));
	      recall_ladspa->input_port[recall_ladspa->input_lines] = i;
	    }

	    recall_ladspa->input_lines += 1;
	  }else if(LADSPA_IS_PORT_OUTPUT(port_descriptor[i])){
	    if(recall_ladspa->output_port == NULL){
	      recall_ladspa->output_port = (unsigned long *) malloc(sizeof(unsigned long));
	      recall_ladspa->output_port[0] = i;
	    }else{
	      recall_ladspa->output_port = (unsigned long *) realloc(recall_ladspa->output_port,
								     (recall_ladspa->output_lines + 1) * sizeof(unsigned long));
	      recall_ladspa->output_port[recall_ladspa->output_lines] = i;
	    }

	    recall_ladspa->output_lines += 1;
	  }
	}
      }

      AGS_RECALL(recall_ladspa)->port = g_list_reverse(port);
    }
  }

  return(AGS_RECALL(recall_ladspa)->port);
}
Ejemplo n.º 4
0
/*
 * query object, about the contact list for each account
 * and fill all available contacts in the contacts table
 */
static gboolean
_get_contacts (void)
{
	GError *error;
	GSList *contacts_list;
	GHashTable *prefs_map;
	gchar **accounts;
	gchar **account_iter;
	gchar *account;
	
	error = NULL;

	if (proxy == NULL) {
		g_warning("[Gajim] unable to connect to session bus");
		return FALSE;
	}
	/* get gajim prefs and lookup for iconset */
	if (!dbus_g_proxy_call(proxy, "prefs_list", &error, G_TYPE_INVALID,
			dbus_g_type_get_map ("GHashTable", G_TYPE_STRING, G_TYPE_STRING),
			&prefs_map, G_TYPE_INVALID))
	{
		_handle_dbus_exception(error, TRUE);
		return FALSE;
	}
	gpointer iconset_ptr = g_hash_table_lookup(prefs_map, "iconset");
	if (iconset_ptr != NULL) {
		iconset = g_strdup((gchar *)iconset_ptr);
	} else {
		g_warning("[Gajim] unable to get prefs value for iconset");
		return FALSE;
	}
	g_hash_table_destroy(prefs_map);
	/* END get gajim prefs */
	error= NULL;
	if (!dbus_g_proxy_call (proxy, "list_accounts", &error, G_TYPE_INVALID,
			G_TYPE_STRV,
			&accounts, G_TYPE_INVALID))
	{
		_handle_dbus_exception(error, TRUE);
		return FALSE;
	}
	for(account_iter = accounts; *account_iter ; account_iter++) {
		account = g_strdup(*account_iter);
		error = NULL;	
		/* query gajim remote object and put results in 'contacts_list' */
		if (!dbus_g_proxy_call (proxy, "list_contacts", &error,
				G_TYPE_STRING, account, /* call arguments */
				G_TYPE_INVALID, /* delimiter */
				/* return value is collection of maps */
				dbus_g_type_get_collection ("GSList",
					dbus_g_type_get_map ("GHashTable",
						G_TYPE_STRING, G_TYPE_VALUE)),
				&contacts_list, G_TYPE_INVALID))
		{
			_handle_dbus_exception(error, FALSE);
			error = NULL;
			continue;
		}
		g_slist_foreach (contacts_list, _foreach_contact, account);
		g_slist_free(contacts_list);
	}
	g_strfreev (accounts);
	return TRUE;
}
Ejemplo n.º 5
0
int stonithd_list_stonith_types(GList ** types)
{
	int rc = ST_FAIL;
	struct ha_msg * request, * reply;
	const char * tmpstr;

	if ( !signed_on(chan) ) {
		stdlib_log(LOG_ERR, "not signed on");
		return ST_FAIL;
	}

	if ( (request = create_basic_reqmsg_fields(ST_LTYPES)) == NULL) {
		return ST_FAIL;
	}

	/* Send the request message */
	if (msg2ipcchan(request, chan) != HA_OK) {
		ZAPMSG(request);
		stdlib_log(LOG_ERR, "can't send stonithRA message to IPC");
		return ST_FAIL;
	}

	/*  waiting for the output to finish */
	chan_waitout_timeout(chan, DEFAULT_TIMEOUT);
	ZAPMSG(request);
	
	/* Read the reply... */
	stdlib_log(LOG_DEBUG, "waiting for the reply to list stonith types.");
        if ( IPC_OK != chan_waitin_timeout(chan, DEFAULT_TIMEOUT) ) {
		stdlib_log(LOG_ERR, "%s:%d: chan_waitin failed."
			   , __FUNCTION__, __LINE__);
		return ST_FAIL;
	}

	if ( (reply = msgfromIPC_noauth(chan)) == NULL ) {
		stdlib_log(LOG_ERR, "stonithd_list_stonith_types: "
			   "failed to fetch reply.");
		return ST_FAIL;
	}
	
	*types = NULL;
	if ( TRUE == is_expected_msg(reply, F_STONITHD_TYPE, ST_APIRPL, 
			     F_STONITHD_APIRPL, ST_RLTYPES, TRUE) ) {
		if ( ((tmpstr = cl_get_string(reply, F_STONITHD_APIRET)) != NULL) 
	   	    && (STRNCMP_CONST(tmpstr, ST_APIOK) == 0) ) {
			int i;
			int len=cl_msg_list_length(reply, F_STONITHD_STTYPES);
			if ( len < 0 ) {
				stdlib_log(LOG_ERR, "Not field to list stonith "
					  "types.");
			} else {
				for (i = 0; i < len; i++) {
					tmpstr = cl_msg_list_nth_data(reply,
							F_STONITHD_STTYPES, i);
					if( tmpstr ) {
						*types = g_list_append(*types,
							       g_strdup(tmpstr));
					}
				}
				stdlib_log(LOG_DEBUG, "got stonith types.");
				rc = ST_OK;
			}
		} else {
			stdlib_log(LOG_DEBUG, "failed to get stonith types.");
		}
	} else {
		stdlib_log(LOG_DEBUG, "stonithd_list_stonith_types: "
			   "Got an unexpected message.");
	}

	ZAPMSG(reply);
	return rc;
}
Ejemplo n.º 6
0
static void
add_group_to_hashtable (struct group *gr,
                       gpointer user_data)
{
  g_hash_table_add (user_data, g_strdup (gr->gr_name));
}
static void
protocol_choosers_add_cm (EmpathyProtocolChooser *chooser,
    TpConnectionManager *cm)
{
  EmpathyProtocolChooserPriv *priv = GET_PRIV (chooser);
  const TpConnectionManagerProtocol * const *iter;

  for (iter = cm->protocols; iter != NULL && *iter != NULL; iter++)
    {
      const TpConnectionManagerProtocol *proto = *iter;
      gchar *icon_name;
      const gchar *display_name;
      const gchar *saved_cm_name;

      saved_cm_name = g_hash_table_lookup (priv->protocols, proto->name);

      if (!tp_strdiff (cm->name, "haze") && saved_cm_name != NULL &&
          tp_strdiff (saved_cm_name, "haze"))
        /* the CM we're adding is a haze implementation of something we already
         * have; drop it.
         */
        continue;

      if (!tp_strdiff (cm->name, "haze") &&
          !tp_strdiff (proto->name, "facebook"))
        /* Facebook now supports XMPP so drop the purple facebook plugin; user
         * should use Gabble */
        continue;

      if (!tp_strdiff (cm->name, "haze") &&
          !tp_strdiff (proto->name, "sip"))
        /* Haze's SIP implementation is pretty useless (bgo #629736) */
        continue;

      if (!tp_strdiff (cm->name, "butterfly"))
        /* Butterfly isn't supported any more */
        continue;

      if (tp_strdiff (cm->name, "haze") && !tp_strdiff (saved_cm_name, "haze"))
        {
          GtkTreeIter titer;
          gboolean valid;
          TpConnectionManager *haze_cm;

          /* let's this CM replace the haze implementation */
          valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->store),
              &titer);

          while (valid)
            {
              gchar *haze_proto_name = NULL;

              gtk_tree_model_get (GTK_TREE_MODEL (priv->store), &titer,
                  COL_PROTOCOL_NAME, &haze_proto_name,
                  COL_CM, &haze_cm, -1);

              if (haze_cm == NULL)
                continue;

              if (!tp_strdiff (haze_cm->name, "haze") &&
                  !tp_strdiff (haze_proto_name, proto->name))
                {
                  gtk_list_store_remove (priv->store, &titer);
                  g_object_unref (haze_cm);
                  g_free (haze_proto_name);
                  break;
                }

              g_object_unref (haze_cm);
              g_free (haze_proto_name);
              valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (priv->store),
                  &titer);
            }
        }

      g_hash_table_insert (priv->protocols,
          g_strdup (proto->name), g_strdup (cm->name));

      icon_name = empathy_protocol_icon_name (proto->name);

      display_name = empathy_protocol_name_to_display_name (proto->name);

      gtk_list_store_insert_with_values (priv->store,
          NULL, 0,
          COL_ICON, icon_name,
          COL_LABEL, display_name,
          COL_CM, cm,
          COL_PROTOCOL_NAME, proto->name,
          -1);

      if (!tp_strdiff (proto->name, "jabber") &&
          !tp_strdiff (cm->name, "gabble"))
        {
          display_name = empathy_service_name_to_display_name ("google-talk");
          gtk_list_store_insert_with_values (priv->store,
             NULL, 0,
             COL_ICON, "im-google-talk",
             COL_LABEL, display_name,
             COL_CM, cm,
             COL_PROTOCOL_NAME, proto->name,
             COL_SERVICE, "google-talk",
             -1);

          display_name = empathy_service_name_to_display_name ("facebook");
          gtk_list_store_insert_with_values (priv->store,
             NULL, 0,
             COL_ICON, "im-facebook",
             COL_LABEL, display_name,
             COL_CM, cm,
             COL_PROTOCOL_NAME, proto->name,
             COL_SERVICE, "facebook",
             -1);
        }

      g_free (icon_name);
    }
}
Ejemplo n.º 8
0
static void
cockpit_polkit_agent_initiate_authentication (PolkitAgentListener *listener,
                                              const gchar *action_id,
                                              const gchar *message,
                                              const gchar *icon_name,
                                              PolkitDetails *details,
                                              const gchar *cookie,
                                              GList *identities,
                                              GCancellable *cancellable,
                                              GAsyncReadyCallback callback,
                                              gpointer user_data)
{
  CockpitPolkitAgent *self = COCKPIT_POLKIT_AGENT (listener);
  PolkitIdentity *identity = NULL;
  GSimpleAsyncResult *result = NULL;
  GString *unsupported = NULL;
  ReauthorizeCaller *caller;
  gchar *string;
  uid_t uid;
  GList *l;

  const gchar *argv[] = {
    PACKAGE_LIBEXEC_DIR "/cockpit-polkit",
    cookie,
    NULL,
  };

  g_debug ("polkit is requesting authentication");

  result = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
                                      cockpit_polkit_agent_initiate_authentication);

  uid = getuid ();

  unsupported = g_string_new ("");
  for (l = identities; l != NULL; l = g_list_next (l))
    {
      if (POLKIT_IS_UNIX_USER (l->data))
        {
          if (polkit_unix_user_get_uid (l->data) == uid)
            {
              identity = g_object_ref (l->data);
              break;
            }
        }

      string = polkit_identity_to_string (l->data);
      g_string_append_printf (unsupported, "%s ", string);
      g_free (string);
    }

  if (!identity)
    {
      g_message ("cannot reauthorize identity(s): %s", unsupported->str);
      g_simple_async_result_set_error (result, POLKIT_ERROR, POLKIT_ERROR_FAILED,
                                       "Reauthorization not supported for identity");
      g_simple_async_result_complete_in_idle (result);
      goto out;
    }

  string = polkit_identity_to_string (identity);
  g_message ("Reauthorizing %s", string);
  g_free (string);

  caller = g_new0 (ReauthorizeCaller, 1);
  caller->cookie = g_strdup (cookie);
  caller->helper = cockpit_pipe_spawn (argv, NULL, NULL, COCKPIT_PIPE_FLAGS_NONE);
  caller->read_sig = g_signal_connect (caller->helper, "read", G_CALLBACK (on_helper_read), caller);
  caller->close_sig = g_signal_connect (caller->helper, "close", G_CALLBACK (on_helper_close), caller);

  caller->cancellable = g_object_ref (cancellable);
  caller->cancel_sig = g_cancellable_connect (cancellable, G_CALLBACK (on_cancelled), caller, NULL);

  caller->result = g_object_ref (result);
  caller->self = self;

  g_hash_table_replace (self->callers, caller->cookie, caller);

  g_debug ("cockpit-polkit helper starting");

out:
  if (unsupported)
    g_string_free (unsupported, TRUE);
  g_object_unref (result);
  if (identity)
    g_object_unref (identity);
}
Ejemplo n.º 9
0
static GSocketConnectable *
parse_address (CockpitChannel *self,
               gchar **possible_name,
               gboolean *local_address)
{
  GSocketConnectable *connectable = NULL;
  const gchar *unix_path;
  const gchar *internal;
  const gchar *address;
  JsonObject *options;
  gboolean local = FALSE;
  GError *error = NULL;
  const gchar *host;
  gint64 port;
  gchar *name = NULL;
  gboolean open = FALSE;

  options = self->priv->open_options;
  if (!cockpit_json_get_string (options, "unix", NULL, &unix_path))
    {
      cockpit_channel_fail (self, "protocol-error", "invalid \"unix\" option in channel");
      goto out;
    }
  if (!cockpit_json_get_int (options, "port", G_MAXINT64, &port))
    {
      cockpit_channel_fail (self, "protocol-error", "invalid \"port\" option in channel");
      goto out;
    }
  if (!cockpit_json_get_string (options, "internal", NULL, &internal))
    {
      cockpit_channel_fail (self, "protocol-error", "invalid \"internal\" option in channel");
      goto out;
    }
  if (!cockpit_json_get_string (options, "address", NULL, &address))
    {
      cockpit_channel_fail (self, "protocol-error", "invalid \"address\" option in channel");
      goto out;
    }

  if (port != G_MAXINT64 && unix_path)
    {
      cockpit_channel_fail (self, "protocol-error", "cannot specify both \"port\" and \"unix\" options");
      goto out;
    }
  else if (port != G_MAXINT64)
    {
      if (port <= 0 || port > 65535)
        {
          cockpit_channel_fail (self, "protocol-error", "received invalid \"port\" option");
          goto out;
        }

      if (address)
        {
          connectable = g_network_address_new (address, port);
          host = address;

          /* This isn't perfect, but matches the use case. Specify address => non-local */
          local = FALSE;
        }
      else if (cockpit_bridge_local_address)
        {
          connectable = g_network_address_parse (cockpit_bridge_local_address, port, &error);
          host = cockpit_bridge_local_address;
          local = TRUE;
        }
      else
        {
          connectable = cockpit_loopback_new (port);
          host = "localhost";
          local = TRUE;
        }

      if (error != NULL)
        {
          cockpit_channel_fail (self, "internal-error",
                                "couldn't parse local address: %s: %s", host, error->message);
          goto out;
        }
      else
        {
          name = g_strdup_printf ("%s:%d", host, (gint)port);
        }
    }
  else if (unix_path)
    {
      name = g_strdup (unix_path);
      connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (unix_path));
      local = FALSE;
    }
  else if (internal)
    {
      gboolean reg = lookup_internal (internal, &connectable);

      if (!connectable)
        {
          if (reg)
            cockpit_channel_close (self, "not-found");
          else
            cockpit_channel_fail (self, "not-found", "couldn't find internal address: %s", internal);
          goto out;
        }

      name = g_strdup (internal);
      connectable = g_object_ref (connectable);
      local = FALSE;
    }
  else
    {
      cockpit_channel_fail (self, "protocol-error",
                            "no \"port\" or \"unix\" or other address option for channel");
      goto out;
    }

  open = TRUE;

out:
  g_clear_error (&error);
  if (open)
    {
      if (possible_name)
          *possible_name = g_strdup (name);
      if (local_address)
        *local_address = local;
    }
  else
    {
      if (connectable)
        g_object_unref (connectable);
      connectable = NULL;
    }

  g_free (name);
  return connectable;
}
Ejemplo n.º 10
0
/**
 * msg_queue_check:
 *
 * checks the queue for any messages
 * this is called by the master program, usually by gtk_timeout_add()
 * the messages it will listen to are the types:
 * - MSG_QUEUE_ASK_ALIVE - we should respond with a type MSG_QUEUE_SEND_ALIVE
 * - MSG_QUEUE_OPENFILE - open a filename
 * - MSG_QUEUE_OPENPROJECT - open a filename as project
 * - MSG_QUEUE_OPENNEWWIN - open a new window
 */
static gboolean msg_queue_check(gint started_by_gtk_timeout)
{
	struct msgbuf {
		long mtype;
		char mtext[MSQ_QUEUE_SIZE];
	} msgp;
	gint retval;
	if (main_v->bfwinlist == NULL || BFWIN(main_v->bfwinlist->data)->documentlist == NULL) {
		DEBUG_MSG("msg_queue_check, no documentlist yet, so we do not continue\n");
		return TRUE;
	}

	if (msg_queue.msgid == -1) {
		return FALSE;
	}
	retval = msgrcv(msg_queue.msgid, &msgp, MSQ_QUEUE_SIZE, -MSG_QUEUE_OPENFILE, IPC_NOWAIT);
	if (retval != -1) {
		DEBUG_MSG("msg_queue_check, found type %ld\n", msgp.mtype);
		if (msgp.mtype == MSG_QUEUE_ASK_ALIVE) {
			struct small_msgbuf {
				long mtype;
				char mtext[MSQ_QUEUE_SMALL_SIZE];
			} small_msgp;
			DEBUG_MSG("msg_queue_check, a keepalive is asked from %s, sending!\n", msgp.mtext);
			small_msgp.mtype = MSG_QUEUE_SEND_ALIVE;
			strncpy(small_msgp.mtext, msgp.mtext, MSQ_QUEUE_SMALL_SIZE - 1);
			msgsnd(msg_queue.msgid, (void *) &small_msgp, MSQ_QUEUE_SMALL_SIZE * sizeof(char),
				   IPC_NOWAIT);
		} else if (msgp.mtype == MSG_QUEUE_OPENFILE) {
			GList *lastlist = g_list_last(main_v->bfwinlist);
			DEBUG_MSG("msg_queue_check, a filename %s is received\n", msgp.mtext);
			Tdocument *tmpdoc = doc_new_with_file(BFWIN(lastlist->data),msgp.mtext, FALSE, TRUE);
			if (!tmpdoc) {
				msg_queue.file_error_list = g_list_append(msg_queue.file_error_list, g_strdup(msgp.mtext));
			} else if (msg_queue.linenumber >=0) {
				doc_activate( tmpdoc );
				doc_select_line( tmpdoc, msg_queue.linenumber, TRUE );
				gtk_widget_grab_focus( GTK_WIDGET( tmpdoc->view ) );
			}
			msg_queue_check(0); /* call myself again, there may have been multiple files */
			if (started_by_gtk_timeout) {
				if (msg_queue.file_error_list) {
					gchar *message, *tmp;
					tmp = stringlist_to_string(msg_queue.file_error_list, "\n");
					free_stringlist(msg_queue.file_error_list);
					msg_queue.file_error_list = NULL;
					message = g_strconcat(_("These files were not opened:\n"), tmp, NULL);
					g_free(tmp);
					warning_dialog(BFWIN(main_v->bfwinlist->data)->main_window,_("Unable to open file(s)\n"), message);
					g_free(message);
				}
/*				gtk_notebook_set_page(GTK_NOTEBOOK(main_v->notebook),g_list_length(main_v->documentlist) - 1);
				notebook_changed(-1);*/
			}
		} else if (msgp.mtype == MSG_QUEUE_OPENPROJECT) {
			GList *lastlist = g_list_last(main_v->bfwinlist);
			DEBUG_MSG("msg_queue_check, a project %s is received\n", msgp.mtext);
			project_open_from_file(BFWIN(lastlist->data), msgp.mtext, msg_queue.linenumber);
			msg_queue_check(0);	/* call myself again, there may have been multiple projects */
		} else if (msgp.mtype == MSG_QUEUE_OPENNEWWIN) {
			/* now check if this is indeed send by another process
			if the message queue was dead during the startup of this process,
			it might be started by this very process */
			int otherpid = atoi(msgp.mtext);
			DEBUG_MSG("msg_queue_check, a new window is requested by PID=%d\n",otherpid);
			if (otherpid != (int) getpid()) {
				DEBUG_MSG("msg_queue_check, the PID is not ours, opening new window\n");
				gui_new_window(NULL, NULL);
			}
		} else if (msgp.mtype == MSG_QUEUE_SETLINE) {
			msg_queue.linenumber = strtoul(msgp.mtext, NULL,10);
		}
#ifdef DEBUG
		 else {
		 	DEBUG_MSG("msg_queue_check, unknown message queue type %ld\n", msgp.mtype);
		 }
#endif
		
	} else {
#ifdef MSG_QUEUE_DEBUG
		DEBUG_MSG("msg_queue_check, found errno(%d)=%s\n", errno, g_strerror(errno));
#endif
	/*
	43 = Identifier removed
	*/
		if (errno == 22 || errno == 43) {
			DEBUG_MSG("msg_queue_check, re-opening message queue ?!?!?\n");
			/* the msg_queue was removed !?!?! */
			if (msg_queue_open()) {
				DEBUG_MSG("msg_queue_check, another process has opened the message_queue, stopping server\n");
				msg_queue.server = FALSE;
				return FALSE;
			}
		}
	}
	return TRUE;
}
Ejemplo n.º 11
0
void CddaSongLoader::LoadSongs() {
  QMutexLocker locker(&mutex_load_);
  cdio_ = cdio_open(url_.path().toLocal8Bit().constData(), DRIVER_DEVICE);
  if (cdio_ == nullptr) {
    return;
  }
  // Create gstreamer cdda element
  GError* error = nullptr;
  cdda_ = gst_element_make_from_uri(GST_URI_SRC, "cdda://", nullptr, &error);
  if (error) {
    qLog(Error) << error->code << error->message;
  }
  if (cdda_ == nullptr) {
    return;
  }

  if (!url_.isEmpty()) {
    g_object_set(cdda_, "device", g_strdup(url_.path().toLocal8Bit().constData()),
                 nullptr);
  }
  if (g_object_class_find_property (G_OBJECT_GET_CLASS (cdda_), "paranoia-mode")) {
    g_object_set (cdda_, "paranoia-mode", 0, NULL);
  }

  // Change the element's state to ready and paused, to be able to query it
  if (gst_element_set_state(cdda_, GST_STATE_READY) ==
          GST_STATE_CHANGE_FAILURE ||
      gst_element_set_state(cdda_, GST_STATE_PAUSED) ==
          GST_STATE_CHANGE_FAILURE) {
    gst_element_set_state(cdda_, GST_STATE_NULL);
    gst_object_unref(GST_OBJECT(cdda_));
    return;
  }

  // Get number of tracks
  GstFormat fmt = gst_format_get_by_nick("track");
  GstFormat out_fmt = fmt;
  gint64 num_tracks = 0;
  if (!gst_element_query_duration(cdda_, out_fmt, &num_tracks) ||
      out_fmt != fmt) {
    qLog(Error) << "Error while querying cdda GstElement";
    gst_object_unref(GST_OBJECT(cdda_));
    return;
  }

  SongList songs;
  for (int track_number = 1; track_number <= num_tracks; track_number++) {
    // Init song
    Song song;
    song.set_id(track_number);
    song.set_valid(true);
    song.set_filetype(Song::Type_Cdda);
    song.set_url(
        GetUrlFromTrack(track_number));
    song.set_title(QString("Track %1").arg(track_number));
    song.set_track(track_number);
    songs << song;
  }
  emit SongsLoaded(songs);


  gst_tag_register_musicbrainz_tags();

  GstElement* pipeline = gst_pipeline_new("pipeline");
  GstElement* sink = gst_element_factory_make ("fakesink", NULL);
  gst_bin_add_many (GST_BIN (pipeline), cdda_, sink, NULL);
  gst_element_link (cdda_, sink);
  gst_element_set_state(pipeline, GST_STATE_READY);
  gst_element_set_state(pipeline, GST_STATE_PAUSED);

  // Get TOC and TAG messages
  GstMessage* msg = nullptr;
  GstMessage* msg_toc = nullptr;
  GstMessage* msg_tag = nullptr;
  while ((msg = gst_bus_timed_pop_filtered(GST_ELEMENT_BUS(pipeline),
      GST_SECOND, (GstMessageType)(GST_MESSAGE_TOC | GST_MESSAGE_TAG)))) {
    if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_TOC) {
      if (msg_toc) gst_message_unref(msg_toc); // Shouldn't happen, but just in case
      msg_toc = msg;
    } else if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_TAG) {
      if (msg_tag) gst_message_unref(msg_tag);
      msg_tag = msg;
    }
  }

  // Handle TOC message: get tracks duration
  if (msg_toc) {
    GstToc* toc;
    gst_message_parse_toc (msg_toc, &toc, nullptr);
    if (toc) {
      GList* entries = gst_toc_get_entries(toc);
      if (entries && songs.size() <= g_list_length (entries)) {
        int i = 0;
        for (GList* node = entries; node != nullptr; node = node->next) {
          GstTocEntry *entry = static_cast<GstTocEntry*>(node->data);
          quint64 duration = 0;
          gint64 start, stop;
          if (gst_toc_entry_get_start_stop_times (entry, &start, &stop))
            duration = stop - start;
          songs[i++].set_length_nanosec(duration);
        }
      }
    }
    gst_message_unref(msg_toc);
  }
  emit SongsDurationLoaded(songs);

  // Handle TAG message: generate MusicBrainz DiscId
  if (msg_tag) {
    GstTagList* tags = nullptr;
    gst_message_parse_tag(msg_tag, &tags);
    char* string_mb = nullptr;
    if (gst_tag_list_get_string(tags, GST_TAG_CDDA_MUSICBRAINZ_DISCID,
                                &string_mb)) {
      QString musicbrainz_discid(string_mb);
      qLog(Info) << "MusicBrainz discid: " << musicbrainz_discid;

      MusicBrainzClient* musicbrainz_client = new MusicBrainzClient;
      connect(musicbrainz_client, SIGNAL(Finished(const QString&, const QString&,
                                                  MusicBrainzClient::ResultList)),
              SLOT(AudioCDTagsLoaded(const QString&, const QString&,
                                     MusicBrainzClient::ResultList)));
      musicbrainz_client->StartDiscIdRequest(musicbrainz_discid);
      g_free(string_mb);
      gst_message_unref(msg_tag);
      gst_tag_list_free(tags);
    }
  }

  gst_element_set_state(pipeline, GST_STATE_NULL);
  // This will also cause cdda_ to be unref'd.
  gst_object_unref(pipeline);
}
Ejemplo n.º 12
0
void
set_host(
    const char *	host)
{
    char *cmd = NULL;
    struct hostent *hp;
    char **hostp;
    int found_host = 0;
    char *uqhost;

    if (is_extract_list_nonempty())
    {
	g_printf(_("Must clear extract list before changing host\n"));
	return;
    }

    uqhost = unquote_string(host);
    cmd = g_strconcat("HOST ", uqhost, NULL);
    if (converse(cmd) == -1)
	exit(1);
    if (server_happy())
    {
	found_host = 1;
    }
    else
    {
	/*
	 * Try converting the given host to a fully qualified name
	 * and then try each of the aliases.
	 */
	if ((hp = gethostbyname(uqhost)) != NULL) {
	    host = hp->h_name;
	    g_printf(_("Trying host %s ...\n"), host);
	    g_free(cmd);
	    cmd = g_strconcat("HOST ", host, NULL);
	    if (converse(cmd) == -1)
		exit(1);
	    if(server_happy())
	    {
		found_host = 1;
	    }
	    else
	    {
	        for (hostp = hp->h_aliases; (host = *hostp) != NULL; hostp++)
	        {
		    g_printf(_("Trying host %s ...\n"), host);
		    g_free(cmd);
		    cmd = g_strconcat("HOST ", host, NULL);
		    if (converse(cmd) == -1)
		        exit(1);
		    if(server_happy())
		    {
		        found_host = 1;
		        break;
		    }
		}
	    }
	}
    }
    if(found_host)
    {
	g_free(dump_hostname);
	dump_hostname = g_strdup(host);
	amfree(disk_name);
	amfree(mount_point);
	amfree(disk_path);
	clear_dir_list();
    }
    amfree(cmd);
    amfree(uqhost);
}
Ejemplo n.º 13
0
void
set_directory(
    char *	dir)
{
    char *cmd = NULL;
    char *new_dir = NULL;
    char *dp, *de;
    char *ldir = NULL;

    /* do nothing if "." */
    if(g_str_equal(dir, ".")) {
	show_directory();		/* say where we are */
	return;
	/*NOTREACHED*/
    }

    if (disk_name == NULL) {
	g_printf(_("Must select disk before setting directory\n"));
	return;
	/*NOTREACHED*/
    }

    ldir = g_strdup(dir);
    clean_pathname(ldir);

    /* convert directory into absolute path relative to disk mount point */
    if (ldir[0] == '/')
    {
	/* absolute path specified, must start with mount point */
	if (g_str_equal(mount_point, "/"))
	{
	    new_dir = g_strdup(ldir);
	}
	else
	{
	    if (strncmp(mount_point, ldir, strlen(mount_point)) != 0)
	    {
		g_printf(_("Invalid directory - Can't cd outside mount point \"%s\"\n"),
		       mount_point);
		amfree(ldir);
		return;
		/*NOTREACHED*/
	    }
	    new_dir = g_strdup(ldir+strlen(mount_point));
	    if (strlen(new_dir) == 0) {
		g_free(new_dir);
		new_dir = g_strdup("/");
					/* i.e. ldir == mount_point */
	    }
	}
    }
    else
    {
	new_dir = g_strdup(disk_path);
	dp = ldir;
	/* strip any leading ..s */
	while (g_str_has_prefix(dp, "../"))
	{
	    de = strrchr(new_dir, '/');	/* always at least 1 */
	    if (de == new_dir)
	    {
		/* at top of disk */
		*(de + 1) = '\0';
		dp = dp + 3;
	    }
	    else
	    {
		*de = '\0';
		dp = dp + 3;
	    }
	}
	if (g_str_equal(dp, "..")) {
	    if (g_str_equal(new_dir, "/")) {
		/* at top of disk */
		g_printf(_("Invalid directory - Can't cd outside mount point \"%s\"\n"),
		       mount_point);
		/*@ignore@*/
		amfree(new_dir);
		/*@end@*/
		amfree(ldir);
		return;
		/*NOTREACHED*/
	    }
	    de = strrchr(new_dir, '/');	/* always at least 1 */
	    if (de == new_dir)
	    {
		/* at top of disk */
		*(de+1) = '\0';
	    }
	    else
	    {
		*de = '\0';
 	    }
	} else {
	    /*@ignore@*/
	    if (!g_str_equal(new_dir, "/")) {
		strappend(new_dir, "/");
	    }
	    strappend(new_dir, ldir);
	    /*@end@*/
	}
    }

    cmd = g_strconcat("OISD ", new_dir, NULL);
    if (exchange(cmd) == -1) {
	exit(1);
	/*NOTREACHED*/
    }
    amfree(cmd);

    if (server_happy())
    {
	g_free(disk_path);
	disk_path = g_strdup(new_dir);
	suck_dir_list_from_server();	/* get list of directory contents */
	show_directory();		/* say where we moved to */
    }
    else
    {
	g_printf(_("Invalid directory - %s\n"), dir);
    }

    /*@ignore@*/
    amfree(new_dir);
    amfree(ldir);
    /*@end@*/
}
Ejemplo n.º 14
0
void
set_disk(
    char *	dsk,
    char *	mtpt)
{
    char *cmd = NULL;
    char *uqdsk;
    char *uqmtpt = NULL;

    if (is_extract_list_nonempty())
    {
	g_printf(_("Must clear extract list before changing disk\n"));
	return;
    }

    /* if mount point specified, check it is valid */
    if (mtpt != NULL) {
	uqmtpt = unquote_string(mtpt);
	if (*mtpt != '/') {
	    g_printf(_("Mount point \"%s\" invalid - must start with /\n"), uqmtpt);
	    amfree(uqmtpt);
	    return;
	}
    }

    clear_dir_list();
    uqdsk = unquote_string(dsk);
    cmd = g_strconcat("DISK ", uqdsk, NULL);
    if (converse(cmd) == -1)
	exit(1);
    amfree(cmd);

    if (!server_happy()) {
	amfree(uqdsk);
	amfree(uqmtpt);
	return;
    }

    g_free(disk_name);
    disk_name = g_strdup(uqdsk);
    if (mtpt == NULL)
    {
	/* mount point not specified */
	if (*uqdsk == '/')
	{
	    /* disk specified by mount point, hence use it */
	    g_free(mount_point);
	    mount_point = g_strdup(uqdsk);
	}
	else
	{
	    /* device name given, use '/' because nothing better */
	    g_free(mount_point);
	    mount_point = g_strdup("/");
	}
    }
    else
    {
	/* mount point specified */
	g_free(mount_point);
	mount_point = g_strdup(uqmtpt);
    }

    /* set the working directory to the mount point */
    /* there is the possibility that there are no index records for the
       disk for the given date, hence setting the directory to the
       mount point will fail. Preempt this by checking first so we can write
       a more informative message. */
    if (exchange("OISD /") == -1)
	exit(1);
    if (server_happy())
    {
	g_free(disk_path);
	disk_path = g_strdup("/");
	suck_dir_list_from_server();	/* get list of directory contents */
    }
    else
    {
	g_printf(_("No index records for disk for specified date\n"));
	g_printf(_("If date correct, notify system administrator\n"));
	g_free(disk_path);
	disk_path = g_strdup("/");	/* fake it */
	clear_dir_list();
    }
    amfree(uqmtpt);
    amfree(uqdsk);
}
Ejemplo n.º 15
0
static void
add_group_to_array (struct group *gr,
                    gpointer user_data)
{
  g_ptr_array_add (user_data, g_strdup (gr->gr_name));
}
Ejemplo n.º 16
0
static JsonNode *
builder_options_serialize_property (JsonSerializable *serializable,
                                    const gchar      *property_name,
                                    const GValue     *value,
                                    GParamSpec       *pspec)
{
  if (strcmp (property_name, "arch") == 0)
    {
      BuilderOptions *self = BUILDER_OPTIONS (serializable);
      JsonNode *retval = NULL;

      if (self->arch && g_hash_table_size (self->arch) > 0)
        {
          JsonObject *object;
          GHashTableIter iter;
          gpointer key, value;

          object = json_object_new ();

          g_hash_table_iter_init (&iter, self->arch);
          while (g_hash_table_iter_next (&iter, &key, &value))
            {
              JsonNode *child = json_gobject_serialize (value);
              json_object_set_member (object, (char *) key, child);
            }

          retval = json_node_init_object (json_node_alloc (), object);
          json_object_unref (object);
        }

      return retval;
    }
  else if (strcmp (property_name, "env") == 0)
    {
      BuilderOptions *self = BUILDER_OPTIONS (serializable);
      JsonNode *retval = NULL;

      if (self->env && g_strv_length (self->env) > 0)
        {
          JsonObject *object;
          int i;

          object = json_object_new ();

          for (i = 0; self->env[i] != NULL; i++)
            {
              JsonNode *str = json_node_new (JSON_NODE_VALUE);
              const char *equal;
              g_autofree char *member = NULL;

              equal = strchr (self->env[i], '=');
              if (equal)
                {
                  json_node_set_string (str, equal + 1);
                  member = g_strndup (self->env[i], equal - self->env[i]);
                }
              else
                {
                  json_node_set_string (str, "");
                  member = g_strdup (self->env[i]);
                }

              json_object_set_member (object, member, str);
            }

          retval = json_node_init_object (json_node_alloc (), object);
          json_object_unref (object);
        }

      return retval;
    }
  else
    {
      return json_serializable_default_serialize_property (serializable,
                                                           property_name,
                                                           value,
                                                           pspec);
    }
}
Ejemplo n.º 17
0
static void
add_name_to_hashtable (struct passwd *pw,
                       gpointer user_data)
{
  g_hash_table_add (user_data, g_strdup (pw->pw_name));
}
Ejemplo n.º 18
0
static gboolean
builder_options_deserialize_property (JsonSerializable *serializable,
                                      const gchar      *property_name,
                                      GValue           *value,
                                      GParamSpec       *pspec,
                                      JsonNode         *property_node)
{
  if (strcmp (property_name, "arch") == 0)
    {
      if (JSON_NODE_TYPE (property_node) == JSON_NODE_NULL)
        {
          g_value_set_boxed (value, NULL);
          return TRUE;
        }
      else if (JSON_NODE_TYPE (property_node) == JSON_NODE_OBJECT)
        {
          JsonObject *object = json_node_get_object (property_node);
          g_autoptr(GHashTable) hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
          g_autoptr(GList) members = NULL;
          GList *l;

          members = json_object_get_members (object);
          for (l = members; l != NULL; l = l->next)
            {
              const char *member_name = l->data;
              JsonNode *val;
              GObject *option;

              val = json_object_get_member (object, member_name);
              option = json_gobject_deserialize (BUILDER_TYPE_OPTIONS, val);
              if (option == NULL)
                return FALSE;

              g_hash_table_insert (hash, g_strdup (member_name), option);
            }

          g_value_set_boxed (value, hash);
          return TRUE;
        }

      return FALSE;
    }
  else if (strcmp (property_name, "env") == 0)
    {
      if (JSON_NODE_TYPE (property_node) == JSON_NODE_NULL)
        {
          g_value_set_boxed (value, NULL);
          return TRUE;
        }
      else if (JSON_NODE_TYPE (property_node) == JSON_NODE_OBJECT)
        {
          JsonObject *object = json_node_get_object (property_node);
          g_autoptr(GPtrArray) env = g_ptr_array_new_with_free_func (g_free);
          g_autoptr(GList) members = NULL;
          GList *l;

          members = json_object_get_members (object);
          for (l = members; l != NULL; l = l->next)
            {
              const char *member_name = l->data;
              JsonNode *val;
              const char *val_str;

              val = json_object_get_member (object, member_name);
              val_str = json_node_get_string (val);
              if (val_str == NULL)
                return FALSE;

              g_ptr_array_add (env, g_strdup_printf ("%s=%s", member_name, val_str));
            }

          g_ptr_array_add (env, NULL);
          g_value_take_boxed (value, g_ptr_array_free (g_steal_pointer (&env), FALSE));
          return TRUE;
        }

      return FALSE;
    }
  else
    {
      return json_serializable_default_deserialize_property (serializable,
                                                             property_name,
                                                             value,
                                                             pspec, property_node);
    }
}
Ejemplo n.º 19
0
static void
setup_commit_passwd1 (GVariant *parameters,
                     GDBusMethodInvocation *invocation)
{
  const gchar *mechanism;
  GVariant *transferred = NULL;
  const gchar **lines;
  GHashTable *users = NULL;
  GHashTable *groups = NULL;
  GString *chpasswd = NULL;
  GString *newusers = NULL;
  CommitAdmin1 *context;
  CockpitPipe *pipe;
  gsize length, i, j;
  gchar **parts;
  GBytes *bytes;
  GVariant *pwdata = NULL;
  GVariant *grdata = NULL;
  GHashTable *usermod;
  gchar **memlist;
  GString *string;
  gboolean user_exists;

  /* We are getting crypted passwords so we need to use
   * --crypt-method=NONE with newusers and chpasswd so that the string
   * is installed unchanged.  Unfortunately, newusers might or might
   * not support the --crypt-method option, depending on whether it
   * was compiled with or without PAM.  When the option is missing, we
   * fix up the password afterwards via chpasswd.
   *
   * However, newusers needs some valid password to create new users.
   * Thus, we need a good random string that passes all password
   * quality criteria, and we just use the crpyted password for that.
   */

  const gchar *argv[] = { cockpit_bridge_path_newusers, "--crypt-method=NONE", NULL };
  if (!cockpit_bridge_have_newusers_crypt_method)
    argv[1] = NULL;

  g_variant_get (parameters, "(&sv)", &mechanism, &transferred);

  if (!g_str_equal (mechanism, "passwd1"))
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_NOT_SUPPORTED,
                                             "Unsupported setup mechanism: %s", mechanism);
      goto out;
    }
  if (!g_variant_is_of_type (transferred, G_VARIANT_TYPE ("(asas)")))
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
                                             "Bad data passed for passwd1 mechanism");
      goto out;
    }

  users = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
  groups = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);

  if (!fgetpwent_callback (add_name_to_hashtable, users) ||
      !fgetgrent_callback (add_group_to_hashtable, groups))
    {
      g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
                                             _("Couldn't list local users"));
      goto out;
    }

  g_debug ("starting setup synchronization");

  g_variant_get (transferred, "(@as@as)", &pwdata, &grdata);

  chpasswd = g_string_new ("");
  newusers = g_string_new ("");
  usermod = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, string_free);

  lines = g_variant_get_strv (pwdata, &length);
  for (i = 0; i < length; i++)
    {
      parts = g_strsplit(lines[i], ":", 3);

      user_exists = (g_hash_table_lookup (users, parts[0]) != NULL);

      if (!user_exists)
        {
          g_string_append (newusers, lines[i]);
          g_string_append_c (newusers, '\n');
        }

      if (user_exists || !cockpit_bridge_have_newusers_crypt_method)
        {
          g_string_append_printf (chpasswd, "%s:%s\n", parts[0], parts[1]);
        }

      g_strfreev (parts);
    }

  g_free (lines);

  lines = g_variant_get_strv (grdata, &length);
  for (i = 0; i < length; i++)
    {
      parts = g_strsplit(lines[i], ":", 4);
      if (g_hash_table_lookup (groups, parts[0]))
        {
          memlist = g_strsplit (parts[3], ",", -1);
          for (j = 0; memlist[j] != NULL; j++)
            {
              string = g_hash_table_lookup (usermod, memlist[j]);
              if (!string)
                {
                  string = g_string_new ("");
                  g_hash_table_insert (usermod, g_strdup (memlist[j]), string);
                }
              if (string->len > 0)
                g_string_append_c (string, ',');
              g_string_append (string, parts[0]);
            }
          g_strfreev (memlist);
        }
      g_strfreev (parts);
    }
  g_free (lines);

  context = g_new0 (CommitAdmin1, 1);
  context->invocation = g_object_ref (invocation);
  context->chpasswd = g_string_free_to_bytes (chpasswd);
  context->usermod = usermod;

  g_debug ("batch creating new users");

  bytes = g_string_free_to_bytes (newusers);
  pipe = cockpit_pipe_spawn (argv, NULL, NULL, COCKPIT_PIPE_FLAGS_NONE);
  g_signal_connect (pipe, "close", G_CALLBACK (on_newusers_close), context);
  cockpit_pipe_write (pipe, bytes);
  cockpit_pipe_close (pipe, NULL);
  g_bytes_unref (bytes);

out:
  if (users)
    g_hash_table_unref (users);
  if (groups)
    g_hash_table_unref (groups);
  if (pwdata)
    g_variant_unref (pwdata);
  if (grdata)
    g_variant_unref (grdata);
  g_variant_unref (transferred);
}
Ejemplo n.º 20
0
static storage_status_t xml_load_real( irc_t *irc, const char *my_nick, const char *password, xml_pass_st action )
{
	GMarkupParseContext *ctx;
	struct xml_parsedata *xd;
	char *fn, buf[512];
	GError *gerr = NULL;
	int fd, st;
	
	xd = g_new0( struct xml_parsedata, 1 );
	xd->irc = irc;
	xd->given_nick = g_strdup( my_nick );
	xd->given_pass = g_strdup( password );
	xd->pass_st = action;
	nick_lc( xd->given_nick );
	
	fn = g_strdup_printf( "%s%s%s", global.conf->configdir, xd->given_nick, ".xml" );
	if( ( fd = open( fn, O_RDONLY ) ) < 0 )
	{
		xml_destroy_xd( xd );
		g_free( fn );
		return STORAGE_NO_SUCH_USER;
	}
	g_free( fn );
	
	ctx = g_markup_parse_context_new( &xml_parser, 0, xd, xml_destroy_xd );
	
	while( ( st = read( fd, buf, sizeof( buf ) ) ) > 0 )
	{
		if( !g_markup_parse_context_parse( ctx, buf, st, &gerr ) || gerr )
		{
			xml_pass_st pass_st = xd->pass_st;
			
			g_markup_parse_context_free( ctx );
			close( fd );
			
			if( pass_st == XML_PASS_WRONG )
			{
				g_clear_error( &gerr );
				return STORAGE_INVALID_PASSWORD;
			}
			else
			{
				if( gerr && irc )
					irc_rootmsg( irc, "Error from XML-parser: %s", gerr->message );
				
				g_clear_error( &gerr );
				return STORAGE_OTHER_ERROR;
			}
		}
	}
	/* Just to be sure... */
	g_clear_error( &gerr );
	
	g_markup_parse_context_free( ctx );
	close( fd );
	
	if( action == XML_PASS_CHECK_ONLY )
		return STORAGE_OK;
	
	return STORAGE_OK;
}
Ejemplo n.º 21
0
Archivo: filegui.c Proyecto: l-4-l/mc
char *
file_mask_dialog (file_op_context_t * ctx, FileOperation operation,
                  gboolean only_one,
                  const char *format, const void *text, const char *def_text, gboolean * do_bg)
{
    size_t fmd_xlen;
    vfs_path_t *vpath;
    int source_easy_patterns = easy_patterns;
    char fmd_buf[BUF_MEDIUM];
    char *dest_dir, *tmp;
    char *def_text_secure;

    if (ctx == NULL)
        return NULL;

    /* unselect checkbox if target filesystem don't support attributes */
    ctx->op_preserve = filegui__check_attrs_on_fs (def_text);
    ctx->stable_symlinks = FALSE;
    *do_bg = FALSE;

    /* filter out a possible password from def_text */
    vpath = vfs_path_from_str_flags (def_text, only_one ? VPF_NO_CANON : VPF_NONE);
    tmp = vfs_path_to_str_flags (vpath, 0, VPF_STRIP_PASSWORD);
    vfs_path_free (vpath);

    if (source_easy_patterns)
        def_text_secure = strutils_glob_escape (tmp);
    else
        def_text_secure = strutils_regex_escape (tmp);
    g_free (tmp);

    if (only_one)
    {
        int format_len, text_len;
        int max_len;

        format_len = str_term_width1 (format);
        text_len = str_term_width1 (text);
        max_len = COLS - 2 - 6;

        if (format_len + text_len <= max_len)
        {
            fmd_xlen = format_len + text_len + 6;
            fmd_xlen = max (fmd_xlen, 68);
        }
        else
        {
            text = str_trunc ((const char *) text, max_len - format_len);
            fmd_xlen = max_len + 6;
        }

        g_snprintf (fmd_buf, sizeof (fmd_buf), format, (const char *) text);
    }
    else
    {
        fmd_xlen = COLS * 2 / 3;
        fmd_xlen = max (fmd_xlen, 68);
        g_snprintf (fmd_buf, sizeof (fmd_buf), format, *(const int *) text);
    }

    {
        char *source_mask, *orig_mask;
        int val;
        struct stat buf;

        quick_widget_t quick_widgets[] = {
            /* *INDENT-OFF* */
            QUICK_LABELED_INPUT (fmd_buf, input_label_above,
                                 easy_patterns ? "*" : "^(.*)$", "input-def", &source_mask,
                                 NULL, FALSE, FALSE, INPUT_COMPLETE_FILENAMES),
            QUICK_START_COLUMNS,
                QUICK_SEPARATOR (FALSE),
            QUICK_NEXT_COLUMN,
                QUICK_CHECKBOX (N_("&Using shell patterns"), &source_easy_patterns, NULL),
            QUICK_STOP_COLUMNS,
            QUICK_LABELED_INPUT (N_("to:"), input_label_above,
                                 def_text_secure, "input2", &dest_dir, NULL, FALSE, FALSE, INPUT_COMPLETE_FILENAMES),
            QUICK_SEPARATOR (TRUE),
            QUICK_START_COLUMNS,
                QUICK_CHECKBOX (N_("Follow &links"), &ctx->follow_links, NULL),
                QUICK_CHECKBOX (N_("Preserve &attributes"), &ctx->op_preserve, NULL),
            QUICK_NEXT_COLUMN,
                QUICK_CHECKBOX (N_("Di&ve into subdir if exists"), &ctx->dive_into_subdirs, NULL),
                QUICK_CHECKBOX (N_("&Stable symlinks"), &ctx->stable_symlinks, NULL),
            QUICK_STOP_COLUMNS,
            QUICK_START_BUTTONS (TRUE, TRUE),
                QUICK_BUTTON (N_("&OK"), B_ENTER, NULL, NULL),
#ifdef ENABLE_BACKGROUND
                QUICK_BUTTON (N_("&Background"), B_USER, NULL, NULL),
#endif /* ENABLE_BACKGROUND */
                QUICK_BUTTON (N_("&Cancel"), B_CANCEL, NULL, NULL),
            QUICK_END
            /* *INDENT-ON* */
        };

        quick_dialog_t qdlg = {
            -1, -1, fmd_xlen,
            op_names[operation], "[Mask Copy/Rename]",
            quick_widgets, NULL, NULL
        };

      ask_file_mask:
        val = quick_dialog_skip (&qdlg, 4);

        if (val == B_CANCEL)
        {
            g_free (def_text_secure);
            return NULL;
        }

        if (ctx->follow_links)
            ctx->stat_func = mc_stat;
        else
            ctx->stat_func = mc_lstat;

        if (ctx->op_preserve)
        {
            ctx->preserve = TRUE;
            ctx->umask_kill = 0777777;
            ctx->preserve_uidgid = (geteuid () == 0);
        }
        else
        {
            int i2;

            ctx->preserve = ctx->preserve_uidgid = FALSE;
            i2 = umask (0);
            umask (i2);
            ctx->umask_kill = i2 ^ 0777777;
        }

        if ((dest_dir == NULL) || (*dest_dir == '\0'))
        {
            g_free (def_text_secure);
            g_free (source_mask);
            return dest_dir;
        }

        ctx->search_handle = mc_search_new (source_mask, -1, NULL);

        if (ctx->search_handle == NULL)
        {
            message (D_ERROR, MSG_ERROR, _("Invalid source pattern '%s'"), source_mask);
            g_free (dest_dir);
            g_free (source_mask);
            goto ask_file_mask;
        }

        g_free (def_text_secure);
        g_free (source_mask);

        ctx->search_handle->is_case_sensitive = TRUE;
        if (source_easy_patterns)
            ctx->search_handle->search_type = MC_SEARCH_T_GLOB;
        else
            ctx->search_handle->search_type = MC_SEARCH_T_REGEX;

        tmp = dest_dir;
        dest_dir = tilde_expand (tmp);
        g_free (tmp);
        vpath = vfs_path_from_str (dest_dir);

        ctx->dest_mask = strrchr (dest_dir, PATH_SEP);
        if (ctx->dest_mask == NULL)
            ctx->dest_mask = dest_dir;
        else
            ctx->dest_mask++;
        orig_mask = ctx->dest_mask;
        if (*ctx->dest_mask == '\0'
            || (!ctx->dive_into_subdirs && !is_wildcarded (ctx->dest_mask)
                && (!only_one
                    || (mc_stat (vpath, &buf) == 0 && S_ISDIR (buf.st_mode))))
            || (ctx->dive_into_subdirs
                && ((!only_one && !is_wildcarded (ctx->dest_mask))
                    || (only_one && mc_stat (vpath, &buf) == 0 && S_ISDIR (buf.st_mode)))))
            ctx->dest_mask = g_strdup ("\\0");
        else
        {
            ctx->dest_mask = g_strdup (ctx->dest_mask);
            *orig_mask = '\0';
        }
        if (*dest_dir == '\0')
        {
            g_free (dest_dir);
            dest_dir = g_strdup ("./");
        }
        vfs_path_free (vpath);
        if (val == B_USER)
            *do_bg = TRUE;
    }

    return dest_dir;
}
Ejemplo n.º 22
0
static storage_status_t xml_save( irc_t *irc, int overwrite )
{
	char path[512], *path2, *pass_buf = NULL;
	set_t *set;
	account_t *acc;
	int fd;
	md5_byte_t pass_md5[21];
	md5_state_t md5_state;
	GSList *l;
	
	path2 = g_strdup( irc->user->nick );
	nick_lc( path2 );
	g_snprintf( path, sizeof( path ) - 2, "%s%s%s", global.conf->configdir, path2, ".xml" );
	g_free( path2 );
	
	if( !overwrite && g_access( path, F_OK ) == 0 )
		return STORAGE_ALREADY_EXISTS;
	
	strcat( path, ".XXXXXX" );
	if( ( fd = mkstemp( path ) ) < 0 )
	{
		irc_rootmsg( irc, "Error while opening configuration file." );
		return STORAGE_OTHER_ERROR;
	}
	
	/* Generate a salted md5sum of the password. Use 5 bytes for the salt
	   (to prevent dictionary lookups of passwords) to end up with a 21-
	   byte password hash, more convenient for base64 encoding. */
	random_bytes( pass_md5 + 16, 5 );
	md5_init( &md5_state );
	md5_append( &md5_state, (md5_byte_t*) irc->password, strlen( irc->password ) );
	md5_append( &md5_state, pass_md5 + 16, 5 ); /* Add the salt. */
	md5_finish( &md5_state, pass_md5 );
	/* Save the hash in base64-encoded form. */
	pass_buf = base64_encode( pass_md5, 21 );
	
	if( !xml_printf( fd, 0, "<user nick=\"%s\" password=\"%s\" version=\"%d\">\n", irc->user->nick, pass_buf, XML_FORMAT_VERSION ) )
		goto write_error;
	
	g_free( pass_buf );
	
	for( set = irc->b->set; set; set = set->next )
		if( set->value && !( set->flags & SET_NOSAVE ) )
			if( !xml_printf( fd, 1, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) )
				goto write_error;
	
	for( acc = irc->b->accounts; acc; acc = acc->next )
	{
		unsigned char *pass_cr;
		char *pass_b64;
		int pass_len;
		
		pass_len = arc_encode( acc->pass, strlen( acc->pass ), (unsigned char**) &pass_cr, irc->password, 12 );
		pass_b64 = base64_encode( pass_cr, pass_len );
		g_free( pass_cr );
		
		if( !xml_printf( fd, 1, "<account protocol=\"%s\" handle=\"%s\" password=\"%s\" "
		                        "autoconnect=\"%d\" tag=\"%s\"", acc->prpl->name, acc->user,
		                        pass_b64, acc->auto_connect, acc->tag ) )
		{
			g_free( pass_b64 );
			goto write_error;
		}
		g_free( pass_b64 );
		
		if( acc->server && acc->server[0] && !xml_printf( fd, 0, " server=\"%s\"", acc->server ) )
			goto write_error;
		if( !xml_printf( fd, 0, ">\n" ) )
			goto write_error;
		
		for( set = acc->set; set; set = set->next )
			if( set->value && !( set->flags & ACC_SET_NOSAVE ) )
				if( !xml_printf( fd, 2, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) )
					goto write_error;
		
		/* This probably looks pretty strange. g_hash_table_foreach
		   is quite a PITA already (but it can't get much better in
		   C without using #define, I'm afraid), and since it
		   doesn't seem to be possible to abort the foreach on write
		   errors, so instead let's use the _find function and
		   return TRUE on write errors. Which means, if we found
		   something, there was an error. :-) */
		if( g_hash_table_find( acc->nicks, xml_save_nick, & fd ) )
			goto write_error;
		
		if( !xml_printf( fd, 1, "</account>\n" ) )
			goto write_error;
	}
	
	for( l = irc->channels; l; l = l->next )
	{
		irc_channel_t *ic = l->data;
		
		if( ic->flags & IRC_CHANNEL_TEMP )
			continue;
		
		if( !xml_printf( fd, 1, "<channel name=\"%s\" type=\"%s\">\n",
		                 ic->name, set_getstr( &ic->set, "type" ) ) )
			goto write_error;
		
		for( set = ic->set; set; set = set->next )
			if( set->value && strcmp( set->key, "type" ) != 0 )
				if( !xml_printf( fd, 2, "<setting name=\"%s\">%s</setting>\n", set->key, set->value ) )
					goto write_error;
		
		if( !xml_printf( fd, 1, "</channel>\n" ) )
			goto write_error;
	}
	
	if( !xml_printf( fd, 0, "</user>\n" ) )
		goto write_error;
	
	fsync( fd );
	close( fd );
	
	path2 = g_strndup( path, strlen( path ) - 7 );
	if( rename( path, path2 ) != 0 )
	{
		irc_rootmsg( irc, "Error while renaming temporary configuration file." );
		
		g_free( path2 );
		unlink( path );
		
		return STORAGE_OTHER_ERROR;
	}
	
	g_free( path2 );
	
	return STORAGE_OK;

write_error:
	g_free( pass_buf );
	
	irc_rootmsg( irc, "Write error. Disk full?" );
	close( fd );
	
	return STORAGE_OTHER_ERROR;
}
Ejemplo n.º 23
0
static void
list_property (IAnjutaProject *project, AnjutaProjectNode *parent, gint indent)
{
	GList *item;
	GString *value;

	value = g_string_new (NULL);

	for (item = anjuta_project_node_get_properties (parent); item != NULL; item = g_list_next (item))
	{
		AnjutaProjectProperty *prop;
		AnjutaProjectPropertyInfo *info;
		GList *list;
		gchar *name;

		prop = (AnjutaProjectProperty *)item->data;
		info = prop->info;

		/* Default property */
		if (info->default_value == prop) continue;

		switch (info->type)
		{
		case ANJUTA_PROJECT_PROPERTY_STRING:
		case ANJUTA_PROJECT_PROPERTY_LIST:
				g_string_assign (value, prop->value == NULL ? "" : prop->value);
				break;
		case ANJUTA_PROJECT_PROPERTY_BOOLEAN:
				g_string_assign (value, (prop->value != NULL) && (*prop->value == '1') ? "true" : "false");
				break;
		case ANJUTA_PROJECT_PROPERTY_MAP:
				g_string_assign (value, "");
				for (list = anjuta_project_node_get_properties (parent); list != NULL; list = g_list_next (list))
				{
					AnjutaProjectProperty *list_prop = (AnjutaProjectProperty *)list->data;

					if (list_prop->info == info)
					{
						if ((value->len == 0) && (list_prop != prop))
						{
							/* This list has already been displayed */
							break;
						}

						if (value->len != 0) g_string_append_c (value, ' ');
						g_string_append_printf (value, "%s = %s", list_prop->name == NULL ? "?" : list_prop->name, list_prop->value == NULL ? "" : list_prop->value);
					}
				}
				if (value->len == 0) continue;
				break;
		}

		name = g_strdup (info->name);
		if (*(name + strlen (name) - 1) == ':')
		{
			*(name + strlen (name) - 1) = '\0';
		}
		print ("%*sPROPERTY (%s): %s", indent * INDENT, "", name, value->str);
		g_free (name);
	}

	g_string_free (value, TRUE);
}
Ejemplo n.º 24
0
static void xml_start_element( GMarkupParseContext *ctx, const gchar *element_name, const gchar **attr_names, const gchar **attr_values, gpointer data, GError **error )
{
	struct xml_parsedata *xd = data;
	irc_t *irc = xd->irc;
	
	if( xd->unknown_tag > 0 )
	{
		xd->unknown_tag ++;
	}
	else if( g_strcasecmp( element_name, "user" ) == 0 )
	{
		char *nick = xml_attr( attr_names, attr_values, "nick" );
		char *pass = xml_attr( attr_names, attr_values, "password" );
		int st;
		
		if( !nick || !pass )
		{
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Missing attributes for %s element", element_name );
		}
		else if( ( st = md5_verify_password( xd->given_pass, pass ) ) == -1 )
		{
			xd->pass_st = XML_PASS_WRONG;
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Error while decoding password attribute" );
		}
		else if( st == 0 )
		{
			if( xd->pass_st != XML_PASS_CHECK_ONLY )
				xd->pass_st = XML_PASS_OK;
		}
		else
		{
			xd->pass_st = XML_PASS_WRONG;
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Password mismatch" );
		}
	}
	else if( xd->pass_st < XML_PASS_OK )
	{
		/* Let's not parse anything else if we only have to check
		   the password. */
	}
	else if( g_strcasecmp( element_name, "account" ) == 0 )
	{
		char *protocol, *handle, *server, *password = NULL, *autoconnect, *tag;
		char *pass_b64 = NULL;
		unsigned char *pass_cr = NULL;
		int pass_len;
		struct prpl *prpl = NULL;
		
		handle = xml_attr( attr_names, attr_values, "handle" );
		pass_b64 = xml_attr( attr_names, attr_values, "password" );
		server = xml_attr( attr_names, attr_values, "server" );
		autoconnect = xml_attr( attr_names, attr_values, "autoconnect" );
		tag = xml_attr( attr_names, attr_values, "tag" );
		
		protocol = xml_attr( attr_names, attr_values, "protocol" );
		if( protocol )
			prpl = find_protocol( protocol );
		
		if( !handle || !pass_b64 || !protocol )
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Missing attributes for %s element", element_name );
		else if( !prpl )
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Unknown protocol: %s", protocol );
		else if( ( pass_len = base64_decode( pass_b64, (unsigned char**) &pass_cr ) ) &&
		         arc_decode( pass_cr, pass_len, &password, xd->given_pass ) >= 0 )
		{
			xd->current_account = account_add( irc->b, prpl, handle, password );
			if( server )
				set_setstr( &xd->current_account->set, "server", server );
			if( autoconnect )
				set_setstr( &xd->current_account->set, "auto_connect", autoconnect );
			if( tag )
				set_setstr( &xd->current_account->set, "tag", tag );
		}
		else
		{
			/* Actually the _decode functions don't even return error codes,
			   but maybe they will later... */
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Error while decrypting account password" );
		}
		
		g_free( pass_cr );
		g_free( password );
	}
	else if( g_strcasecmp( element_name, "setting" ) == 0 )
	{
		char *setting;
		
		if( xd->current_setting )
		{
			g_free( xd->current_setting );
			xd->current_setting = NULL;
		}
		
		if( ( setting = xml_attr( attr_names, attr_values, "name" ) ) )
		{
			if( xd->current_channel != NULL )
				xd->current_set_head = &xd->current_channel->set;
			else if( xd->current_account != NULL )
				xd->current_set_head = &xd->current_account->set;
			else
				xd->current_set_head = &xd->irc->b->set;
			
			xd->current_setting = g_strdup( setting );
		}
		else
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Missing attributes for %s element", element_name );
	}
	else if( g_strcasecmp( element_name, "buddy" ) == 0 )
	{
		char *handle, *nick;
		
		handle = xml_attr( attr_names, attr_values, "handle" );
		nick = xml_attr( attr_names, attr_values, "nick" );
		
		if( xd->current_account && handle && nick )
		{
			nick_set_raw( xd->current_account, handle, nick );
		}
		else
		{
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Missing attributes for %s element", element_name );
		}
	}
	else if( g_strcasecmp( element_name, "channel" ) == 0 )
	{
		char *name, *type;
		
		name = xml_attr( attr_names, attr_values, "name" );
		type = xml_attr( attr_names, attr_values, "type" );
		
		if( !name || !type )
		{
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Missing attributes for %s element", element_name );
			return;
		}
		
		/* The channel may exist already, for example if it's &bitlbee.
		   Also, it's possible that the user just reconnected and the
		   IRC client already rejoined all channels it was in. They
		   should still get the right settings. */
		if( ( xd->current_channel = irc_channel_by_name( irc, name ) ) ||
		    ( xd->current_channel = irc_channel_new( irc, name ) ) )
			set_setstr( &xd->current_channel->set, "type", type );
	}
	/* Backward compatibility: Keep this around for a while for people
	   switching from BitlBee 1.2.4+. */
	else if( g_strcasecmp( element_name, "chat" ) == 0 )
	{
		char *handle, *channel;
		
		handle = xml_attr( attr_names, attr_values, "handle" );
		channel = xml_attr( attr_names, attr_values, "channel" );
		
		if( xd->current_account && handle && channel )
		{
			irc_channel_t *ic;
			
			if( ( ic = irc_channel_new( irc, channel ) ) &&
			    set_setstr( &ic->set, "type", "chat" ) &&
			    set_setstr( &ic->set, "chat_type", "room" ) &&
			    set_setstr( &ic->set, "account", xd->current_account->tag ) &&
			    set_setstr( &ic->set, "room", handle ) )
			{
				/* Try to pick up some settings where possible. */
				xd->current_channel = ic;
			}
			else if( ic )
				irc_channel_free( ic );
		}
		else
		{
			g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT,
			             "Missing attributes for %s element", element_name );
		}
	}
	else
	{
		xd->unknown_tag ++;
		irc_rootmsg( irc, "Warning: Unknown XML tag found in configuration file (%s). "
		                  "This may happen when downgrading BitlBee versions. "
		                  "This tag will be skipped and the information will be lost "
		                  "once you save your settings.", element_name );
		/*
		g_set_error( error, G_MARKUP_ERROR, G_MARKUP_ERROR_UNKNOWN_ELEMENT,
		             "Unkown element: %s", element_name );
		*/
	}
}
Ejemplo n.º 25
0
/**
 * gimp_rc_add_unknown_token:
 * @config: a #GObject.
 * @key: a nul-terminated string to identify the value.
 * @value: a nul-terminated string representing the value.
 *
 * This function allows to add arbitrary key/value pairs to a GObject.
 * It's purpose is to attach additional data to a #GimpConfig object
 * that can be stored along with the object properties when
 * serializing the object to a configuration file. Please note however
 * that the default gimp_config_serialize() implementation does not
 * serialize unknown tokens.
 *
 * If you want to remove a key/value pair from the object, call this
 * function with a %NULL @value.
 **/
void
gimp_rc_add_unknown_token (GimpConfig  *config,
                           const gchar *key,
                           const gchar *value)
{
  GimpConfigToken *token;
  GSList          *unknown_tokens;
  GSList          *last;
  GSList          *list;

  g_return_if_fail (GIMP_IS_CONFIG (config));
  g_return_if_fail (key != NULL);

  unknown_tokens = (GSList *) g_object_get_data (G_OBJECT (config),
                                                 GIMP_RC_UNKNOWN_TOKENS);

  for (last = NULL, list = unknown_tokens;
       list;
       last = list, list = g_slist_next (list))
    {
      token = (GimpConfigToken *) list->data;

      if (strcmp (token->key, key) == 0)
        {
          g_free (token->value);

          if (value)
            {
              token->value = g_strdup (value);
            }
          else
            {
              g_free (token->key);

              unknown_tokens = g_slist_remove (unknown_tokens, token);
              g_object_set_data_full (G_OBJECT (config),
                                      GIMP_RC_UNKNOWN_TOKENS,
                                      unknown_tokens,
                     (GDestroyNotify) gimp_rc_destroy_unknown_tokens);
            }

          return;
        }
    }

  if (!value)
    return;

  token = g_slice_new (GimpConfigToken);
  token->key   = g_strdup (key);
  token->value = g_strdup (value);

  if (last)
    {
      last = g_slist_last (g_slist_append (last, token));
    }
  else
    {
      unknown_tokens = g_slist_append (NULL, token);

      g_object_set_data_full (G_OBJECT (config),
                              GIMP_RC_UNKNOWN_TOKENS,
                              unknown_tokens,
                              (GDestroyNotify) gimp_rc_destroy_unknown_tokens);
    }
}
Ejemplo n.º 26
0
gboolean
g_vfs_keyring_lookup_password (const gchar *username,
                               const gchar *host,
                               const gchar *domain,
                               const gchar *protocol,
                               const gchar *object,
                               const gchar *authtype,
                               guint32      port,
                               gchar      **username_out,
                               gchar      **domain_out,
                               gchar      **password_out)
{
#ifdef HAVE_KEYRING
    GHashTable  *attributes;
    SecretItem  *item;
    SecretValue *secret;
    GList       *plist;
    GError      *error = NULL;


    attributes = build_network_attributes (username, host, domain, protocol, object, authtype, port);
    plist = secret_service_search_sync (NULL, SECRET_SCHEMA_COMPAT_NETWORK, attributes,
                                        SECRET_SEARCH_UNLOCK | SECRET_SEARCH_LOAD_SECRETS |
                                        SECRET_SEARCH_ALL,
                                        NULL, &error);
    g_hash_table_unref (attributes);

    if (error != NULL)
    {
        g_error_free (error);
        return FALSE;
    }

    if (plist == NULL)
        return FALSE;

    /* We want the least specific result, so we sort the return values.
       For instance, given both items for ftp://host:port and ftp://host
       in the keyring we always want to use the ftp://host one for
       i.e. ftp://host/some/path. */

    plist = g_list_sort (plist, compare_specificity);

    item = SECRET_ITEM (plist->data);
    secret = secret_item_get_secret (item);
    attributes = secret_item_get_attributes (item);
    g_list_free_full (plist, g_object_unref);

    if (secret == NULL)
    {
        if (attributes)
            g_hash_table_unref (attributes);
        return FALSE;
    }

    *password_out = g_strdup (secret_value_get (secret, NULL));
    secret_value_unref (secret);

    if (username_out)
        *username_out = g_strdup (g_hash_table_lookup (attributes, "user"));

    if (domain_out)
        *domain_out = g_strdup (g_hash_table_lookup (attributes, "domain"));

    g_hash_table_unref (attributes);
    return TRUE;
#else
    return FALSE;
#endif /* HAVE_KEYRING */
}
Ejemplo n.º 27
0
void
ags_recall_ladspa_set_ports(AgsPlugin *plugin, GList *port)
{
  AgsRecallLadspa *recall_ladspa;
  AgsLadspaPlugin *ladspa_plugin;
  AgsPort *current;
  GList *list;
  unsigned long port_count;
  unsigned long i;

  void *plugin_so;
  LADSPA_Descriptor_Function ladspa_descriptor;
  LADSPA_Descriptor *plugin_descriptor;
  LADSPA_PortDescriptor *port_descriptor;
  LADSPA_PortRangeHintDescriptor hint_descriptor;

  recall_ladspa = AGS_RECALL_LADSPA(plugin);

  ags_ladspa_manager_load_file(recall_ladspa->filename);
  ladspa_plugin = ags_ladspa_manager_find_ladspa_plugin(recall_ladspa->filename);
  
  plugin_so = ladspa_plugin->plugin_so;

  if(plugin_so != NULL){
    ladspa_descriptor = (LADSPA_Descriptor_Function) dlsym(plugin_so,
							   "ladspa_descriptor\0");

    if(dlerror() == NULL && ladspa_descriptor){
      recall_ladspa->plugin_descriptor = 
	plugin_descriptor = ladspa_descriptor(recall_ladspa->effect_index);

      port_count = plugin_descriptor->PortCount;
      port_descriptor = plugin_descriptor->PortDescriptors;

      for(i = 0; i < port_count; i++){
	if(LADSPA_IS_PORT_CONTROL(port_descriptor[i])){
	  if(LADSPA_IS_PORT_INPUT(port_descriptor[i]) ||
	     LADSPA_IS_PORT_OUTPUT(port_descriptor[i])){
	    gchar *plugin_name;
	    gchar *specifier;

	    hint_descriptor = plugin_descriptor->PortRangeHints[i].HintDescriptor;

	    plugin_name = g_strdup_printf("ladspa-%lu\0", plugin_descriptor->UniqueID);
	    specifier = g_strdup(plugin_descriptor->PortNames[i]);

	    list = port;
	    current = NULL;

	    while(list != NULL){
	      if(!g_strcmp0(specifier,
			    AGS_PORT(list->data)->specifier)){
		current = list->data;
		break;
	      }

	      list = list->next;
	    }
	    
	    current->port_value.ags_port_float = plugin_descriptor->PortRangeHints[i].LowerBound;

	    g_message("connecting port: %d/%d\0", i, port_count);
	  }
	}else if(LADSPA_IS_PORT_AUDIO(port_descriptor[i])){
	  if(LADSPA_IS_PORT_INPUT(port_descriptor[i])){
	    if(recall_ladspa->input_port == NULL){
	      recall_ladspa->input_port = (unsigned long *) malloc(sizeof(unsigned long));
	      recall_ladspa->input_port[0] = i;
	    }else{
	      recall_ladspa->input_port = (unsigned long *) realloc(recall_ladspa->input_port,
							    (recall_ladspa->input_lines + 1) * sizeof(unsigned long));
	      recall_ladspa->input_port[recall_ladspa->input_lines] = i;
	    }

	    recall_ladspa->input_lines += 1;
	  }else if(LADSPA_IS_PORT_OUTPUT(port_descriptor[i])){
	    if(recall_ladspa->output_port == NULL){
	      recall_ladspa->output_port = (unsigned long *) malloc(sizeof(unsigned long));
	      recall_ladspa->output_port[0] = i;
	    }else{
	      recall_ladspa->output_port = (unsigned long *) realloc(recall_ladspa->output_port,
							    (recall_ladspa->output_lines + 1) * sizeof(unsigned long));
	      recall_ladspa->output_port[recall_ladspa->output_lines] = i;
	    }

	    recall_ladspa->output_lines += 1;
	  }
	}
      }

      AGS_RECALL(recall_ladspa)->port = g_list_reverse(port);
    }
  }
}
Ejemplo n.º 28
0
nsresult
nsIconChannel::InitWithGnome(nsIMozIconURI *aIconURI)
{
  nsresult rv;
  
  if (!gnome_program_get()) {
    // Get the brandShortName from the string bundle to pass to GNOME
    // as the application name.  This may be used for things such as
    // the title of grouped windows in the panel.
    nsCOMPtr<nsIStringBundleService> bundleService = 
      do_GetService(NS_STRINGBUNDLE_CONTRACTID);

    NS_ASSERTION(bundleService, "String bundle service must be present!");

    nsCOMPtr<nsIStringBundle> bundle;
    bundleService->CreateBundle("chrome://branding/locale/brand.properties",
                                getter_AddRefs(bundle));
    nsXPIDLString appName;

    if (bundle) {
      bundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                getter_Copies(appName));
    } else {
      NS_WARNING("brand.properties not present, using default application name");
      appName.AssignLiteral("Gecko");
    }

    char* empty[] = { "" };
    gnome_init(NS_ConvertUTF16toUTF8(appName).get(), "1.0", 1, empty);
  }

  nsCAutoString iconSizeString;
  aIconURI->GetIconSize(iconSizeString);

  PRUint32 iconSize;

  if (iconSizeString.IsEmpty()) {
    rv = aIconURI->GetImageSize(&iconSize);
    NS_ASSERTION(NS_SUCCEEDED(rv), "GetImageSize failed");
  } else {
    int size;
    
    GtkIconSize icon_size = moz_gtk_icon_size(iconSizeString.get());
    gtk_icon_size_lookup(icon_size, &size, NULL);
    iconSize = size;
  }

  nsCAutoString type;
  aIconURI->GetContentType(type);

  GnomeVFSFileInfo fileInfo = {0};
  fileInfo.refcount = 1; // In case some GnomeVFS function addrefs and releases it

  nsCAutoString spec;
  nsCOMPtr<nsIURI> fileURI;
  rv = aIconURI->GetIconFile(getter_AddRefs(fileURI));
  if (fileURI) {
    fileURI->GetAsciiSpec(spec);
    // Only ask gnome-vfs for a GnomeVFSFileInfo for file: uris, to avoid a
    // network request
    PRBool isFile;
    if (NS_SUCCEEDED(fileURI->SchemeIs("file", &isFile)) && isFile) {
      gnome_vfs_get_file_info(spec.get(), &fileInfo, GNOME_VFS_FILE_INFO_DEFAULT);
    }
    else {
      // We have to get a leaf name from our uri...
      nsCOMPtr<nsIURL> url(do_QueryInterface(fileURI));
      if (url) {
        nsCAutoString name;
        // The filename we get is UTF-8-compatible, which matches gnome expectations.
        // See also: http://lists.gnome.org/archives/gnome-vfs-list/2004-March/msg00049.html
        // "Whenever we can detect the charset used for the URI type we try to
        //  convert it to/from utf8 automatically inside gnome-vfs."
        // I'll interpret that as "otherwise, this field is random junk".
        url->GetFileName(name);
        fileInfo.name = g_strdup(name.get());
      }
      // If this is no nsIURL, nothing we can do really.

      if (!type.IsEmpty()) {
        fileInfo.valid_fields = GNOME_VFS_FILE_INFO_FIELDS_MIME_TYPE;
        fileInfo.mime_type = g_strdup(type.get());
      }
    }
  }


  if (type.IsEmpty()) {
    nsCOMPtr<nsIMIMEService> ms(do_GetService("@mozilla.org/mime;1"));
    if (ms) {
      nsCAutoString fileExt;
      aIconURI->GetFileExtension(fileExt);
      ms->GetTypeFromExtension(fileExt, type);
    }
  }

  // Get the icon theme
  if (!gIconTheme) {
    gIconTheme = gnome_icon_theme_new();
    if (!gIconTheme) {
      gnome_vfs_file_info_clear(&fileInfo);
      return NS_ERROR_NOT_AVAILABLE;
    }
  }

  char* name = gnome_icon_lookup(gIconTheme, NULL, spec.get(), NULL, &fileInfo,
                                 type.get(), GNOME_ICON_LOOKUP_FLAGS_NONE,
                                 NULL);
  gnome_vfs_file_info_clear(&fileInfo);
  if (!name) {
    return NS_ERROR_NOT_AVAILABLE;
  }
 
  char* file = gnome_icon_theme_lookup_icon(gIconTheme, name, iconSize,
                                            NULL, NULL);
  g_free(name);
  if (!file)
    return NS_ERROR_NOT_AVAILABLE;

  // Create a GdkPixbuf buffer and scale it
  GError *err = nsnull;
  GdkPixbuf* buf = gdk_pixbuf_new_from_file(file, &err);
  g_free(file);
  if (!buf) {
    if (err)
      g_error_free(err);
    return NS_ERROR_UNEXPECTED;
  }

  GdkPixbuf* scaled = buf;
  if (gdk_pixbuf_get_width(buf)  != iconSize &&
      gdk_pixbuf_get_height(buf) != iconSize) {
    // scale...
    scaled = gdk_pixbuf_scale_simple(buf, iconSize, iconSize,
                                     GDK_INTERP_BILINEAR);
    gdk_pixbuf_unref(buf);
    if (!scaled)
      return NS_ERROR_OUT_OF_MEMORY;
  }

  // XXX Respect icon state
  
  rv = moz_gdk_pixbuf_to_channel(scaled, aIconURI,
                                 getter_AddRefs(mRealChannel));
  gdk_pixbuf_unref(scaled);
  return rv;
}
Ejemplo n.º 29
0
static gboolean
gsf_outfile_open_pkg_close (GsfOutput *output)
{
	GsfOutfileOpenPkg *open_pkg = GSF_OUTFILE_OPEN_PKG (output);
	GsfOutput *dir;
	gboolean res = FALSE;
	char *rels_name;

	if (NULL == open_pkg->sink || gsf_output_is_closed (open_pkg->sink))
		return TRUE;

	/* Generate [Content_types].xml when we close the root dir */
	if (NULL == gsf_output_name (output)) {
		GsfOutput *out = gsf_outfile_new_child (GSF_OUTFILE (open_pkg->sink),
			"[Content_Types].xml", FALSE);
		GsfXMLOut *xml = gsf_xml_out_new (out);

		gsf_xml_out_start_element (xml, "Types");
		gsf_xml_out_add_cstr_unchecked (xml, "xmlns",
			"http://schemas.openxmlformats.org/package/2006/content-types");
		gsf_open_pkg_write_content_default (xml, "rels",
			"application/vnd.openxmlformats-package.relationships+xml");
		gsf_open_pkg_write_content_default (xml, "xlbin",
			"application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings");
		gsf_open_pkg_write_content_default (xml, "xml",
			"application/xml");
		gsf_open_pkg_write_content_override (open_pkg, "/", xml);
		gsf_xml_out_end_element (xml); /* </Types> */
		g_object_unref (xml);

		gsf_output_close (out);
		g_object_unref (out);

		dir = open_pkg->sink;
		rels_name = g_strdup (".rels");
	} else {
		res = gsf_output_close (open_pkg->sink);

		dir = (GsfOutput *)gsf_output_container (open_pkg->sink);
		rels_name = g_strconcat (gsf_output_name (output), ".rels", NULL);
	}

	if (NULL != open_pkg->relations) {
		GsfOutput *rels;
		GsfXMLOut *xml;
		GsfOpenPkgRel *rel;
		GSList *ptr;

		dir = gsf_outfile_new_child (GSF_OUTFILE (dir), "_rels", TRUE);
		rels = gsf_outfile_new_child (GSF_OUTFILE (dir), rels_name, FALSE);
		xml = gsf_xml_out_new (rels);

		gsf_xml_out_start_element (xml, "Relationships");
		gsf_xml_out_add_cstr_unchecked (xml, "xmlns",
			"http://schemas.openxmlformats.org/package/2006/relationships");

		for (ptr = open_pkg->relations ; ptr != NULL ; ptr = ptr->next) {
			rel = ptr->data;
			gsf_xml_out_start_element (xml, "Relationship");
			gsf_xml_out_add_cstr (xml, "Id", rel->id);
			gsf_xml_out_add_cstr (xml, "Type", rel->type);
			gsf_xml_out_add_cstr (xml, "Target", rel->target);
			if (rel->is_extern)
				gsf_xml_out_add_cstr_unchecked (xml, "TargetMode", "External");
			gsf_xml_out_end_element (xml); /* </Relationship> */

			g_free (rel->id);
			g_free (rel->type);
			g_free (rel->target);
			g_free (rel);
		}
		g_slist_free (open_pkg->relations);

		gsf_xml_out_end_element (xml); /* </Relationships> */
		g_object_unref (xml);
		gsf_output_close (rels);
		g_object_unref (rels);
		g_object_unref (dir);
	}
	g_free (rels_name);

	/* close the container */
	if (NULL == gsf_output_name (output))
		return gsf_output_close (open_pkg->sink);
	return res;
}
Ejemplo n.º 30
0
char *
nautilus_file_conflict_dialog_get_new_name (NautilusFileConflictDialog *dialog)
{
	return g_strdup (gtk_entry_get_text
			 (GTK_ENTRY (dialog->details->entry)));
}