示例#1
0
void wxDBusConnection::Flush()
{
	dbus_connection_flush(m_connection);
	m_thread->Wakeup();
}
示例#2
0
int
main (int argc, char *argv[])
{
  DBusConnection *connection;
  DBusError error;
  DBusMessage *message;
  dbus_bool_t print_reply;
  dbus_bool_t print_reply_literal;
  int reply_timeout;
  DBusMessageIter iter;
  int i;
  DBusBusType type = DBUS_BUS_SESSION;
  const char *dest = NULL;
  const char *name = NULL;
  const char *path = NULL;
  int message_type = DBUS_MESSAGE_TYPE_SIGNAL;
  const char *type_str = NULL;
  const char *address = NULL;
  int is_bus = FALSE;
  int session_or_system = FALSE;

  appname = argv[0];
  
  if (argc < 3)
    usage (1);

  print_reply = FALSE;
  print_reply_literal = FALSE;
  reply_timeout = -1;
  
  for (i = 1; i < argc && name == NULL; i++)
    {
      char *arg = argv[i];

      if (strcmp (arg, "--system") == 0)
        {
	  type = DBUS_BUS_SYSTEM;
          session_or_system = TRUE;
        }
      else if (strcmp (arg, "--session") == 0)
        {
	  type = DBUS_BUS_SESSION;
          session_or_system = TRUE;
        }
      else if ((strstr (arg, "--bus=") == arg) || (strstr (arg, "--peer=") == arg) || (strstr (arg, "--address=") == arg))
        {
          if (arg[2] == 'b') /* bus */
            {
              is_bus = TRUE;
            }
          else if (arg[2] == 'p') /* peer */
            {
              is_bus = FALSE;
            }
          else /* address; keeping backwards compatibility */
            {
              is_bus = FALSE;
            }

          address = strchr (arg, '=') + 1;

          if (address[0] == '\0')
            {
              fprintf (stderr, "\"--peer=\" and \"--bus=\" require an ADDRESS\n");
              usage (1);
            }
        }
      else if (strncmp (arg, "--print-reply", 13) == 0)
	{
	  print_reply = TRUE;
	  message_type = DBUS_MESSAGE_TYPE_METHOD_CALL;
	  if (strcmp (arg + 13, "=literal") == 0)
	    print_reply_literal = TRUE;
	  else if (*(arg + 13) != '\0')
	    {
	      fprintf (stderr, "invalid value (%s) of \"--print-reply\"\n", arg + 13);
	      usage (1);
	    }
	}
      else if (strstr (arg, "--reply-timeout=") == arg)
	{
	  if (*(strchr (arg, '=') + 1) == '\0')
	    {
	      fprintf (stderr, "\"--reply-timeout=\" requires an MSEC\n");
	      usage (1);
	    }
	  reply_timeout = strtol (strchr (arg, '=') + 1,
				  NULL, 10);
	  if (reply_timeout <= 0)
	    {
	      fprintf (stderr, "invalid value (%s) of \"--reply-timeout\"\n",
	               strchr (arg, '=') + 1);
	      usage (1);
	    }
	}
      else if (strstr (arg, "--dest=") == arg)
	{
	  if (*(strchr (arg, '=') + 1) == '\0')
	    {
	      fprintf (stderr, "\"--dest=\" requires an NAME\n");
	      usage (1);
	    }
	  dest = strchr (arg, '=') + 1;
	}
      else if (strstr (arg, "--type=") == arg)
	type_str = strchr (arg, '=') + 1;
      else if (!strcmp(arg, "--help"))
	usage (0);
      else if (arg[0] == '-')
	usage (1);
      else if (path == NULL)
        path = arg;
      else /* name == NULL guaranteed by the 'while' loop */
        name = arg;
    }

  if (name == NULL)
    usage (1);

  if (session_or_system &&
      (address != NULL))
    {
      fprintf (stderr, "\"--peer\" and \"--bus\" may not be used with \"--system\" or \"--session\"\n");
      usage (1);
    }

  if (type_str != NULL)
    {
      message_type = dbus_message_type_from_string (type_str);
      if (!(message_type == DBUS_MESSAGE_TYPE_METHOD_CALL ||
            message_type == DBUS_MESSAGE_TYPE_SIGNAL))
        {
          fprintf (stderr, "Message type \"%s\" is not supported\n",
                   type_str);
          exit (1);
        }
    }
  
  dbus_error_init (&error);

  if (dest && !dbus_validate_bus_name (dest, &error))
    {
      fprintf (stderr, "invalid value (%s) of \"--dest\"\n", dest);
      usage (1);
    }

  if (address != NULL)
    {
      connection = dbus_connection_open (address, &error);
    }
  else
    {
      connection = dbus_bus_get (type, &error);
    }

  if (connection == NULL)
    {
      fprintf (stderr, "Failed to open connection to \"%s\" message bus: %s\n",
               (address != NULL) ? address :
                 ((type == DBUS_BUS_SYSTEM) ? "system" : "session"),
               error.message);
      dbus_error_free (&error);
      exit (1);
    }
  else if ((address != NULL) && is_bus)
    {
      if (!dbus_bus_register (connection, &error))
        {
          fprintf (stderr, "Failed to register on connection to \"%s\" message bus: %s\n",
                   address, error.message);
          dbus_error_free (&error);
          exit (1);
        }
    }

  if (message_type == DBUS_MESSAGE_TYPE_METHOD_CALL)
    {
      char *last_dot;

      last_dot = strrchr (name, '.');
      if (last_dot == NULL)
        {
          fprintf (stderr, "Must use org.mydomain.Interface.Method notation, no dot in \"%s\"\n",
                   name);
          exit (1);
        }
      *last_dot = '\0';
      
      message = dbus_message_new_method_call (NULL,
                                              path,
                                              name,
                                              last_dot + 1);
      dbus_message_set_auto_start (message, TRUE);
    }
  else if (message_type == DBUS_MESSAGE_TYPE_SIGNAL)
    {
      char *last_dot;

      last_dot = strrchr (name, '.');
      if (last_dot == NULL)
        {
          fprintf (stderr, "Must use org.mydomain.Interface.Signal notation, no dot in \"%s\"\n",
                   name);
          exit (1);
        }
      *last_dot = '\0';
      
      message = dbus_message_new_signal (path, name, last_dot + 1);
    }
  else
    {
      fprintf (stderr, "Internal error, unknown message type\n");
      exit (1);
    }

  if (message == NULL)
    {
      fprintf (stderr, "Couldn't allocate D-Bus message\n");
      exit (1);
    }

  if (dest && !dbus_message_set_destination (message, dest))
    {
      fprintf (stderr, "Not enough memory\n");
      exit (1);
    }
  
  dbus_message_iter_init_append (message, &iter);

  while (i < argc)
    {
      char *arg;
      char *c;
      int type;
      int secondary_type;
      int container_type;
      DBusMessageIter *target_iter;
      DBusMessageIter container_iter;

      type = DBUS_TYPE_INVALID;
      arg = argv[i++];
      c = strchr (arg, ':');

      if (c == NULL)
	{
	  fprintf (stderr, "%s: Data item \"%s\" is badly formed\n", argv[0], arg);
	  exit (1);
	}

      *(c++) = 0;

      container_type = DBUS_TYPE_INVALID;

      if (strcmp (arg, "variant") == 0)
	container_type = DBUS_TYPE_VARIANT;
      else if (strcmp (arg, "array") == 0)
	container_type = DBUS_TYPE_ARRAY;
      else if (strcmp (arg, "dict") == 0)
	container_type = DBUS_TYPE_DICT_ENTRY;

      if (container_type != DBUS_TYPE_INVALID)
	{
	  arg = c;
	  c = strchr (arg, ':');
	  if (c == NULL)
	    {
	      fprintf (stderr, "%s: Data item \"%s\" is badly formed\n", argv[0], arg);
	      exit (1);
	    }
	  *(c++) = 0;
	}

      if (arg[0] == 0)
	type = DBUS_TYPE_STRING;
      else
	type = type_from_name (arg);

      if (container_type == DBUS_TYPE_DICT_ENTRY)
	{
	  char sig[5];
	  arg = c;
	  c = strchr (c, ':');
	  if (c == NULL)
	    {
	      fprintf (stderr, "%s: Data item \"%s\" is badly formed\n", argv[0], arg);
	      exit (1);
	    }
	  *(c++) = 0;
	  secondary_type = type_from_name (arg);
	  sig[0] = DBUS_DICT_ENTRY_BEGIN_CHAR;
	  sig[1] = type;
	  sig[2] = secondary_type;
	  sig[3] = DBUS_DICT_ENTRY_END_CHAR;
	  sig[4] = '\0';
	  dbus_message_iter_open_container (&iter,
					    DBUS_TYPE_ARRAY,
					    sig,
					    &container_iter);
	  target_iter = &container_iter;
	}
      else if (container_type != DBUS_TYPE_INVALID)
	{
	  char sig[2];
	  sig[0] = type;
	  sig[1] = '\0';
	  dbus_message_iter_open_container (&iter,
					    container_type,
					    sig,
					    &container_iter);
	  target_iter = &container_iter;
	}
      else
	target_iter = &iter;

      if (container_type == DBUS_TYPE_ARRAY)
	{
	  append_array (target_iter, type, c);
	}
      else if (container_type == DBUS_TYPE_DICT_ENTRY)
	{
	  append_dict (target_iter, type, secondary_type, c);
	}
      else
	append_arg (target_iter, type, c);

      if (container_type != DBUS_TYPE_INVALID)
	{
	  dbus_message_iter_close_container (&iter,
					     &container_iter);
	}
    }

  if (print_reply)
    {
      DBusMessage *reply;

      dbus_error_init (&error);
      reply = dbus_connection_send_with_reply_and_block (connection,
                                                         message, reply_timeout,
                                                         &error);
      if (dbus_error_is_set (&error))
        {
          fprintf (stderr, "Error %s: %s\n",
		   error.name,
                   error.message);
          exit (1);
        }

      if (reply)
        {
          long sec, usec;

          _dbus_get_real_time (&sec, &usec);
          print_message (reply, print_reply_literal, sec, usec);
          dbus_message_unref (reply);
        }
    }
  else
    {
      dbus_connection_send (connection, message, NULL);
      dbus_connection_flush (connection);
    }

  dbus_message_unref (message);

  dbus_connection_unref (connection);

  exit (0);
}
示例#3
0
int indicator_music_init(Indicator *indicator) {
	DBusMessage* msg;
	DBusMessageIter args, element;
	DBusPendingCall* pending;
	char *player;
	int current_type;
	
	if(!dbus.session.connection)
		return -1;
	
	if(!(msg=dbus_message_new_method_call(dbus.interface, dbus.object, dbus.interface, "ListNames")))
		return -1;
	
	if(!dbus_connection_send_with_reply(dbus.session.connection, msg, &pending, -1)) {
		dbus_connection_unref(dbus.session.connection);
		return -1;
	}
	if(!pending) {
		dbus_message_unref(msg);
		dbus_connection_unref(dbus.session.connection);
		return -1;
	}
	dbus_connection_flush(dbus.session.connection);
	dbus_message_unref(msg);
	dbus_pending_call_block(pending);

	if(!(msg=dbus_pending_call_steal_reply(pending))) {
		dbus_connection_unref(dbus.session.connection);
		return -1;
	}
	dbus_pending_call_unref(pending);

	if(!(dbus_message_iter_init(msg, &args)&&dbus_message_iter_get_arg_type(&args)==DBUS_TYPE_ARRAY)) {
		dbus_message_unref(msg);
		dbus_connection_unref(dbus.session.connection);
		return -1;
	}
	
	for(dbus_message_iter_recurse(&args, &element); (current_type=dbus_message_iter_get_arg_type(&element))!=DBUS_TYPE_INVALID; dbus_message_iter_next(&element)) {
		if(current_type!=DBUS_TYPE_STRING)
			continue;
		dbus_message_iter_get_basic(&element, &player);
		if(!strncmp(player, mpris.base, strlen(mpris.base))) {
			mediaplayer_register(player+strlen(mpris.base));
		}
	}
	dbus_message_unref(msg);
	
	dbus_bus_add_match(dbus.session.connection, "type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged'", &dbus.session.error);
	dbus_connection_flush(dbus.session.connection);
	if(dbus_error_is_set(&dbus.session.error)) { 
		dbus_connection_unref(dbus.session.connection);
		mediaplayer_deregister_all();
		return -1;
	}
	
	/*init alsa*/
	snd_mixer_selem_id_alloca(&alsa.sid);
	snd_mixer_selem_id_set_index(alsa.sid, alsa.mix_index);
	snd_mixer_selem_id_set_name(alsa.sid, alsa.mix_name);
	
	if((snd_mixer_open(&alsa.handle, 0))<0)
		return -1;
	if((snd_mixer_attach(alsa.handle, alsa.card))<0) {
		snd_mixer_close(alsa.handle);
		return -1;
	}
	if((snd_mixer_selem_register(alsa.handle, NULL, NULL))<0) {
		snd_mixer_close(alsa.handle);
		return -1;
	}
	if(snd_mixer_load(alsa.handle)<0) {
		snd_mixer_close(alsa.handle);
		return -1;
	}
	if(!(alsa.elem=snd_mixer_find_selem(alsa.handle, alsa.sid))) {
		snd_mixer_close(alsa.handle);
		return -1;
	}
	
	snd_mixer_selem_get_playback_volume_range (alsa.elem, &alsa.minv, &alsa.maxv);
	return 0;
}
示例#4
0
/*****************************************************************************
 * SendToTelepathy
 *****************************************************************************/
static int SendToTelepathy( intf_thread_t *p_intf, const char *psz_msg )
{
    DBusConnection *p_conn;
    DBusMessage *p_msg;
    DBusMessage *p_reply;
    DBusMessageIter args;
    DBusError error;
    dbus_error_init( &error );
    dbus_uint32_t i_status;

    p_conn = p_intf->p_sys->p_conn;

    /* first we need to get the actual status */
    p_msg = dbus_message_new_method_call(
            "org.freedesktop.Telepathy.MissionControl",
           "/org/freedesktop/Telepathy/MissionControl",
            "org.freedesktop.Telepathy.MissionControl",
            "GetPresence" );
    if( !p_msg )
        return VLC_ENOMEM;

    p_reply = dbus_connection_send_with_reply_and_block( p_conn, p_msg,
        50, &error ); /* blocks 50ms maximum */

    dbus_message_unref( p_msg );
    if( p_reply == NULL )
    {   /* MC is not active, or too slow. Better luck next time? */
        return VLC_SUCCESS;
    }

    /* extract the status from the reply */
    if( dbus_message_get_args( p_reply, &error,
            DBUS_TYPE_UINT32, &i_status,
            DBUS_TYPE_INVALID ) == FALSE )
    {
        return VLC_ENOMEM;
    }

    p_msg = dbus_message_new_method_call(
            "org.freedesktop.Telepathy.MissionControl",
           "/org/freedesktop/Telepathy/MissionControl",
            "org.freedesktop.Telepathy.MissionControl",
            "SetPresence" );
    if( !p_msg )
        return VLC_ENOMEM;

    dbus_message_iter_init_append( p_msg, &args );

    /* first argument is the status */
    if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_UINT32, &i_status ) )
    {
        dbus_message_unref( p_msg );
        return VLC_ENOMEM;
    }
    /* second argument is the message */
    if( !dbus_message_iter_append_basic( &args, DBUS_TYPE_STRING, &psz_msg ) )
    {
        dbus_message_unref( p_msg );
        return VLC_ENOMEM;
    }


    if( !dbus_connection_send( p_conn, p_msg, NULL ) )
        return VLC_ENOMEM;

    dbus_connection_flush( p_conn );
    dbus_message_unref( p_msg );

    return VLC_SUCCESS;
}
示例#5
0
static int get_all_properties_by_unit_path(DBusConnection *conn, const char *unit_path, int(*callback)(const char *name, const char *value, void *arg), void *cbarg)
{
	int ret = 1;
	DBusMessage *msg = NULL;
	DBusPendingCall *pending = NULL;

	msg = dbus_message_new_method_call(
		"org.freedesktop.systemd1",
		unit_path,
		"org.freedesktop.DBus.Properties",
		"GetAll"
	);
	if (msg == NULL) {
		dI("Failed to create dbus_message via dbus_message_new_method_call!\n");
		goto cleanup;
	}

	DBusMessageIter args, property_iter;

	const char *interface = "org.freedesktop.systemd1.Unit";

	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &interface)) {
		dI("Failed to append interface '%s' string parameter to dbus message!\n", interface);
		goto cleanup;
	}

	if (!dbus_connection_send_with_reply(conn, msg, &pending, -1)) {
		dI("Failed to send message via dbus!\n");
		goto cleanup;
	}
	if (pending == NULL) {
		dI("Invalid dbus pending call!\n");
		goto cleanup;
	}

	dbus_connection_flush(conn);
	dbus_message_unref(msg); msg = NULL;

	dbus_pending_call_block(pending);
	msg = dbus_pending_call_steal_reply(pending);
	if (msg == NULL) {
		dI("Failed to steal dbus pending call reply.\n");
		goto cleanup;
	}
	dbus_pending_call_unref(pending); pending = NULL;

	if (!dbus_message_iter_init(msg, &args)) {
		dI("Failed to initialize iterator over received dbus message.\n");
		goto cleanup;
	}

	if (dbus_message_iter_get_arg_type(&args) != DBUS_TYPE_ARRAY && dbus_message_iter_get_element_type(&args) != DBUS_TYPE_DICT_ENTRY) {
		dI("Expected array of dict_entry argument in reply. Instead received: %s.\n", dbus_message_type_to_string(dbus_message_iter_get_arg_type(&args)));
		goto cleanup;
	}

	dbus_message_iter_recurse(&args, &property_iter);
	do {
		DBusMessageIter dict_entry, value_variant;
		dbus_message_iter_recurse(&property_iter, &dict_entry);

		if (dbus_message_iter_get_arg_type(&dict_entry) != DBUS_TYPE_STRING) {
			dI("Expected string as key in dict_entry. Instead received: %s.\n", dbus_message_type_to_string(dbus_message_iter_get_arg_type(&dict_entry)));
			goto cleanup;
		}

		_DBusBasicValue value;
		dbus_message_iter_get_basic(&dict_entry, &value);
		char *property_name = oscap_strdup(value.str);

		if (dbus_message_iter_next(&dict_entry) == false) {
			dW("Expected another field in dict_entry.");
			oscap_free(property_name);
			goto cleanup;
		}

		if (dbus_message_iter_get_arg_type(&dict_entry) != DBUS_TYPE_VARIANT) {
			dI("Expected variant as value in dict_entry. Instead received: %s.\n", dbus_message_type_to_string(dbus_message_iter_get_arg_type(&dict_entry)));
			oscap_free(property_name);
			goto cleanup;
		}

		dbus_message_iter_recurse(&dict_entry, &value_variant);

		int cbret = 0;
		const int arg_type = dbus_message_iter_get_arg_type(&value_variant);
		// DBUS_TYPE_ARRAY is a special case, we report each element as one value entry
		if (arg_type == DBUS_TYPE_ARRAY) {
			DBusMessageIter array;
			dbus_message_iter_recurse(&value_variant, &array);

			do {
				char *element = dbus_value_to_string(&array);
				if (element == NULL)
					continue;

				const int elementcbret = callback(property_name, element, cbarg);
				if (elementcbret > cbret)
					cbret = elementcbret;

				oscap_free(element);
			}
			while (dbus_message_iter_next(&array));
		}
		else {
			char *property_value = dbus_value_to_string(&value_variant);
			cbret = callback(property_name, property_value, cbarg);
			oscap_free(property_value);
		}

		oscap_free(property_name);
		if (cbret != 0) {
			goto cleanup;
		}
	}
	while (dbus_message_iter_next(&property_iter));

	dbus_message_unref(msg); msg = NULL;
	ret = 0;

cleanup:
	if (pending != NULL)
		dbus_pending_call_unref(pending);

	if (msg != NULL)
		dbus_message_unref(msg);

	return ret;
}
示例#6
0
文件: dbus.c 项目: shanewfx/vlc-arib
static int Open( vlc_object_t *p_this )
{ /* initialisation of the connection */
    intf_thread_t   *p_intf = (intf_thread_t*)p_this;
    intf_sys_t      *p_sys  = malloc( sizeof( intf_sys_t ) );
    playlist_t      *p_playlist;
    DBusConnection  *p_conn;
    DBusError       error;

    if( !p_sys )
        return VLC_ENOMEM;

    p_sys->b_meta_read = false;
    p_sys->i_caps = CAPS_NONE;
    p_sys->b_dead = false;

    dbus_error_init( &error );

    /* connect to the session bus */
    p_conn = dbus_bus_get( DBUS_BUS_SESSION, &error );
    if( !p_conn )
    {
        msg_Err( p_this, "Failed to connect to the D-Bus session daemon: %s",
                error.message );
        dbus_error_free( &error );
        free( p_sys );
        return VLC_EGENERIC;
    }

    /* register a well-known name on the bus */
    dbus_bus_request_name( p_conn, VLC_MPRIS_DBUS_SERVICE, 0, &error );
    if( dbus_error_is_set( &error ) )
    {
        msg_Err( p_this, "Error requesting service " VLC_MPRIS_DBUS_SERVICE
                 ": %s", error.message );
        dbus_error_free( &error );
        free( p_sys );
        return VLC_EGENERIC;
    }

    /* we register the objects */
    dbus_connection_register_object_path( p_conn, MPRIS_DBUS_ROOT_PATH,
            &vlc_dbus_root_vtable, p_this );
    dbus_connection_register_object_path( p_conn, MPRIS_DBUS_PLAYER_PATH,
            &vlc_dbus_player_vtable, p_this );
    dbus_connection_register_object_path( p_conn, MPRIS_DBUS_TRACKLIST_PATH,
            &vlc_dbus_tracklist_vtable, p_this );

    dbus_connection_flush( p_conn );

    p_intf->pf_run = Run;
    p_intf->p_sys = p_sys;
    p_sys->p_conn = p_conn;
    p_sys->p_events = vlc_array_new();
    vlc_mutex_init( &p_sys->lock );

    p_playlist = pl_Hold( p_intf );
    PL_LOCK;
    var_AddCallback( p_playlist, "item-current", AllCallback, p_intf );
    var_AddCallback( p_playlist, "intf-change", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-append", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-deleted", AllCallback, p_intf );
    var_AddCallback( p_playlist, "random", AllCallback, p_intf );
    var_AddCallback( p_playlist, "repeat", AllCallback, p_intf );
    var_AddCallback( p_playlist, "loop", AllCallback, p_intf );
    PL_UNLOCK;
    pl_Release( p_intf );

    UpdateCaps( p_intf );

    return VLC_SUCCESS;
}
int main(int argc, char *argv[])
{
  DBusError err;
  DBusConnection *conn;
  DBusMessage *msg;
  DBusMessageIter args;
  DBusPendingCall *pending;
  char **hosts;
  int num_hosts;
  int ret;
  int i;

  dbus_error_init(&err);
  conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
  if (dbus_error_is_set(&err)) {
     fprintf(stderr, "Connection Error (%s)\n", err.message);
     dbus_error_free(&err);
     }
  if (NULL == conn)
     exit(1); 

  msg = dbus_message_new_method_call("de.yavdr.hostwakeup", "/Hosts", "de.yavdr.hostwakeup", "List");
  if (NULL == msg) {
     fprintf(stderr, "Message Null\n");
     exit(1);
     }

  if (!dbus_connection_send_with_reply(conn, msg, &pending, -1)) {
     fprintf(stderr, "Out Of Memory!\n");
     exit(1);
     }
  if (NULL == pending) {
     fprintf(stderr, "Pending Call Null\n");
     exit(1);
     }
  dbus_connection_flush(conn);
  dbus_message_unref(msg);

  dbus_pending_call_block(pending);
  msg = dbus_pending_call_steal_reply(pending);
  if (NULL == msg) {
     fprintf(stderr, "Reply Null\n");
     exit(1);
     }
  dbus_pending_call_unref(pending);
  if (!dbus_message_iter_init(msg, &args))
     fprintf(stderr, "Message has no arguments!\n");
  else if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &hosts, &num_hosts, DBUS_TYPE_INVALID)) {
     if (hosts != NULL)
        dbus_free_string_array(hosts);
     fprintf(stderr, "Argument is not a string array!\n");
     exit(1);
     }
  if (hosts != NULL) {
     printf("found %d host%s\n", num_hosts, (num_hosts == 1 ? "" : "s"));
     for (i = 0; i < num_hosts; i++)
         printf("host %d: %s\n", i + 1, hosts[i]);
     dbus_free_string_array(hosts);
     }
  dbus_message_unref(msg);
  return 0;
}
示例#8
0
int main(int argc, char *argv[])
{
    int camera = 0;
    SDL_Joystick *joy = NULL;

    if (!fs_init(argv[0]))
    {
        fprintf(stderr, "Failure to initialize virtual file system (%s)\n",
                fs_error());
        return 1;
    }

    srand((int) time(NULL));

    opt_parse(argc, argv);

    config_paths(opt_data);
    log_init("Neverputt", "neverputt.log");
    fs_mkdir("Screenshots");

    /* Request backlight stay on (ubuntu touch) */

    int dispreq = -1;

    DBusError err;
    dbus_error_init(&err);
    DBusConnection *conn = dbus_bus_get_private(DBUS_BUS_SYSTEM, &err);
    if (dbus_error_is_set(&err)) {
        log_printf("Failed to get system bus\n");
        dbus_error_free(&err);
        if (conn) {
            dbus_connection_unref(conn);
            conn = NULL;
        }
    } else {
        dbus_connection_set_exit_on_disconnect(conn, 0);

        DBusMessage *msg = dbus_message_new_method_call("com.canonical.Unity.Screen", "/com/canonical/Unity/Screen", "com.canonical.Unity.Screen", "keepDisplayOn");
        if (msg != NULL) {
            DBusMessage *reply = dbus_connection_send_with_reply_and_block(conn, msg, 300, NULL);
            if (reply) {
                if (!dbus_message_get_args(reply, NULL, DBUS_TYPE_INT32, &dispreq, DBUS_TYPE_INVALID)) dispreq = -1;
                dbus_message_unref(reply);
            }
            dbus_message_unref(msg);
        }

        if (dispreq == -1) log_printf("Failed to request backlight stay on\n");
    }

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == 0)
    {
        config_init();
        config_load();

        /* Initialize localization. */

        lang_init();

        /* Cache Neverball's camera setting. */

        camera = config_get_d(CONFIG_CAMERA);

        /* Initialize the joystick. */

        if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
        {
            joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
            if (joy)
            {
                SDL_JoystickEventState(SDL_ENABLE);
                set_joystick(joy);
            }
        }

        /* Initialize the audio. */

        audio_init();

        /* Initialize the video. */

        if (video_init())
        {
            int t1, t0 = SDL_GetTicks();

            /* Material system. */

            mtrl_init();

            /* Run the main game loop. */

            init_state(&st_null);

            if (opt_hole)
            {
                const char *path = fs_resolve(opt_hole);
                int loaded = 0;

                if (path)
                {
                    hole_init(NULL);

                    if (hole_load(0, path) &&
                            hole_load(1, path) &&
                            hole_goto(1, 1))
                    {
                        goto_state(&st_next);
                        loaded = 1;
                    }
                }

                if (!loaded)
                    goto_state(&st_title);
            }
            else
                goto_state(&st_title);

            while (loop())
                if ((t1 = SDL_GetTicks()) > t0)
                {
                    st_timer((t1 - t0) / 1000.f);
                    hmd_step();
                    st_paint(0.001f * t1);
                    video_swap();

                    t0 = t1;

                    if (config_get_d(CONFIG_NICE))
                        SDL_Delay(1);
                }

            mtrl_quit();
        }

        /* Restore Neverball's camera setting. */

        config_set_d(CONFIG_CAMERA, camera);
        config_save();

        /* Remove backlight request (ubuntu touch) */

        if (conn) {
            if (dispreq != -1) {
                DBusMessage *msg = dbus_message_new_method_call("com.canonical.Unity.Screen", "/com/canonical/Unity/Screen", "com.canonical.Unity.Screen", "removeDisplayOnRequest");
                dbus_message_append_args(msg, DBUS_TYPE_INT32, &dispreq, DBUS_TYPE_INVALID);
                if (msg != NULL) {
                    if (dbus_connection_send(conn, msg, NULL)) dbus_connection_flush(conn);
                    dbus_message_unref(msg);
                }
            }
            dbus_connection_close(conn);
            dbus_connection_unref(conn);
            dbus_shutdown();
        }

        SDL_Quit();
    }
    else log_printf("Failure to initialize SDL (%s)\n", SDL_GetError());

    return 0;
}
static void
cupsd_send_dbus(cupsd_eventmask_t event,/* I - Event to send */
                cupsd_printer_t   *dest,/* I - Destination, if any */
                cupsd_job_t       *job)	/* I - Job, if any */
{
  DBusError		error;		/* Error, if any */
  DBusMessage		*message;	/* Message to send */
  DBusMessageIter	iter;		/* Iterator for message data */
  const char		*what;		/* What to send */
  static DBusConnection	*con = NULL;	/* Connection to DBUS server */


 /*
  * Figure out what to send, if anything...
  */

  if (event & CUPSD_EVENT_PRINTER_ADDED)
    what = "PrinterAdded";
  else if (event & CUPSD_EVENT_PRINTER_DELETED)
    what = "PrinterRemoved";
  else if (event & CUPSD_EVENT_PRINTER_CHANGED)
    what = "QueueChanged";
  else if (event & CUPSD_EVENT_JOB_CREATED)
    what = "JobQueuedLocal";
  else if ((event & CUPSD_EVENT_JOB_STATE) && job &&
           job->state_value == IPP_JOB_PROCESSING)
    what = "JobStartedLocal";
  else
    return;

 /*
  * Verify connection to DBUS server...
  */

  if (con && !dbus_connection_get_is_connected(con))
  {
    dbus_connection_unref(con);
    con = NULL;
  }

  if (!con)
  {
    dbus_error_init(&error);

    con = dbus_bus_get(getuid() ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error);
    if (!con)
    {
      dbus_error_free(&error);
      return;
    }
  }

 /*
  * Create and send the new message...
  */

  message = dbus_message_new_signal("/com/redhat/PrinterSpooler",
				    "com.redhat.PrinterSpooler", what);

  dbus_message_append_iter_init(message, &iter);
  if (dest)
    dbus_message_iter_append_string(&iter, dest->name);
  if (job)
  {
    dbus_message_iter_append_uint32(&iter, job->id);
    dbus_message_iter_append_string(&iter, job->username);
  }

  dbus_connection_send(con, message, NULL);
  dbus_connection_flush(con);
  dbus_message_unref(message);
}
示例#10
0
文件: cneod.c 项目: fgau/cneo
void
reply_to_set_brightness(DBusMessage* msg, DBusConnection* conn)
{
	DBusMessage* reply;
	DBusMessageIter args;
	dbus_int32_t level = 0;
	char path[128];
	FILE* f;

	if (!dbus_message_iter_init(msg, &args))
		fprintf(stderr, "Message has no arguments!\n");
	else if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args))
		fprintf(stderr, "Argument is not int32!\n");
	else {
		dbus_message_iter_get_basic(&args, &level);

		reply = dbus_message_new_method_return(msg);

		dbus_message_iter_init_append(reply, &args);

		if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_INT32, &level)) {
			fprintf(stderr, "Out Of Memory!\n");
			return;
		}

		if (strcmp(DBUS_PATH, "/org/cneo/Netbook") == 0) {
			f = fopen(NETBOOK_BRIGHTNESS_FILE, "w");

			if (!f) {
				fprintf(stderr, "Unable to open path for writing\n");
				return;
			}

			snprintf(path, sizeof(path), "%d\n",
				get_sys_path_value(NETBOOK_MAX_BRIGHTNESS_FILE) * level / 100);
		}

		else if (strcmp(DBUS_PATH, "/org/cneo/GTA02") == 0) {
			f = fopen(GTA02_BRIGHTNESS_FILE, "w");

			if (!f) {
				fprintf(stderr, "Unable to open path for writing\n");
				return;
			}

			snprintf(path, sizeof(path), "%d\n",
				get_sys_path_value(GTA02_MAX_BRIGHTNESS_FILE) * level / 100);
		}

		fprintf(f, path);
		fclose(f);

		if (!dbus_connection_send(conn, reply, NULL)) {
			fprintf(stderr, "Out Of Memory!\n");
			return;
		}

	}

	dbus_connection_flush(conn);
	dbus_message_unref(reply);
}
static void cb_Notify(DBusConnection *connection, DBusMessage *message)
{
	DBusMessage *message_reply = NULL;
	DBusMessageIter arguments;
	int current_type = DBUS_TYPE_INVALID;
	unsigned int argument_count = 0;
	char *notification_app_name = NULL;
	unsigned long int notification_replaces_id = 0;
	char *notification_summary = NULL;
	char *notification_body = NULL;
	long int notification_expire_timeout = 0;
	
	if(!dbus_message_iter_init(message, &arguments))
	{
		fprintf(stderr, "Failed to read notify arguments.\n");
		return;
	}
	
	while((current_type = dbus_message_iter_get_arg_type(&arguments)) != DBUS_TYPE_INVALID)
	{
		if(argument_count == 0 && current_type == DBUS_TYPE_STRING)
		{
			dbus_message_iter_get_basic(&arguments, &notification_app_name);
		}
		else if(argument_count == 1 && current_type == DBUS_TYPE_UINT32)
		{
			dbus_message_iter_get_basic(&arguments, &notification_replaces_id);
		}
		else if(argument_count == 3 && current_type == DBUS_TYPE_STRING)
		{
			dbus_message_iter_get_basic(&arguments, &notification_body);
		}
		else if(argument_count == 4 && current_type == DBUS_TYPE_STRING)
		{
			dbus_message_iter_get_basic(&arguments, &notification_summary);
		}
		else if(argument_count == 7 && current_type == DBUS_TYPE_INT32)
		{
			dbus_message_iter_get_basic(&arguments, &notification_expire_timeout);
		}
		
		argument_count++;
		dbus_message_iter_next(&arguments);
	}
	
	printf("{\"app_name\":\"");
	print_json_string(notification_app_name);
	printf("\",\"body\":\"");
	print_json_string(notification_body);
	printf("\",\"summary\":\"");
	print_json_string(notification_summary);
	printf("\",\"expire_timeout\":%li}\n", notification_expire_timeout);
	
	message_reply = dbus_message_new_method_return(message);
	
	dbus_message_iter_init_append(message_reply, &arguments);
	if(!dbus_message_iter_append_basic(&arguments, DBUS_TYPE_UINT32, &notification_replaces_id))
	{
		fprintf(stderr, "Failed to append notify.\n");
		return;
	}
	
	if(!dbus_connection_send(connection, message_reply, NULL))
	{
		fprintf(stderr, "Failed to send notify.\n");
	}
	
	dbus_connection_flush(connection);
	
	dbus_message_unref(message_reply);
}
示例#12
0
    virtual int showNotify(const char *pcHeader, const char *pcBody)
    {
        int rc;
# ifdef VBOX_WITH_DBUS
        DBusConnection *conn;
        DBusMessage* msg = NULL;
        conn = dbus_bus_get (DBUS_BUS_SESSON, NULL);
        if (conn == NULL)
        {
            LogRelFlowFunc(("Could not retrieve D-BUS session bus!\n"));
            rc = VERR_INVALID_HANDLE;
        }
        else
        {
            msg = dbus_message_new_method_call("org.freedesktop.Notifications",
                                               "/org/freedesktop/Notifications",
                                               "org.freedesktop.Notifications",
                                               "Notify");
            if (msg == NULL)
            {
                LogRel(("Could not create D-BUS message!\n"));
                rc = VERR_INVALID_HANDLE;
            }
            else
                rc = VINF_SUCCESS;
        }
        if (RT_SUCCESS(rc))
        {
            uint32_t msg_replace_id = 0;
            const char *msg_app = "VBoxClient";
            const char *msg_icon = "";
            const char *msg_summary = pcHeader;
            const char *msg_body = pcBody;
            int32_t msg_timeout = -1;           /* Let the notification server decide */

            DBusMessageIter iter;
            DBusMessageIter array;
            DBusMessageIter dict;
            DBusMessageIter value;
            DBusMessageIter variant;
            DBusMessageIter data;

            /* Format: UINT32 org.freedesktop.Notifications.Notify
             *         (STRING app_name, UINT32 replaces_id, STRING app_icon, STRING summary, STRING body,
             *          ARRAY actions, DICT hints, INT32 expire_timeout)
             */
            dbus_message_iter_init_append(msg,&iter);
            dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_app);
            dbus_message_iter_append_basic(&iter,DBUS_TYPE_UINT32,&msg_replace_id);
            dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_icon);
            dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_summary);
            dbus_message_iter_append_basic(&iter,DBUS_TYPE_STRING,&msg_body);
            dbus_message_iter_open_container(&iter,DBUS_TYPE_ARRAY,DBUS_TYPE_STRING_AS_STRING,&array);
            dbus_message_iter_close_container(&iter,&array);
            dbus_message_iter_open_container(&iter,DBUS_TYPE_ARRAY,"{sv}",&array);
            dbus_message_iter_close_container(&iter,&array);
            dbus_message_iter_append_basic(&iter,DBUS_TYPE_INT32,&msg_timeout);

            DBusError err;
            dbus_error_init(&err);

            DBusMessage *reply;
            reply = dbus_connection_send_with_reply_and_block(conn, msg,
                30 * 1000 /* 30 seconds timeout */, &err);
            if (dbus_error_is_set(&err))
            {
                LogRel(("D-BUS returned an error while sending the notification: %s", err.message));
            }
            else if (reply)
            {
                dbus_connection_flush(conn);
                dbus_message_unref(reply);
            }
            if (dbus_error_is_set(&err))
                dbus_error_free(&err);
        }
        if (msg != NULL)
            dbus_message_unref(msg);
# else
        /* TODO: Implement me */
        rc = VINF_SUCCESS;
# endif /* VBOX_WITH_DBUS */
        return rc;
    }
示例#13
0
int main(int argc, char *argv[]) {
  
    DBusConnection *connection;
	DBusMessage *msg;
	DBusMessage *reply;
	DBusMessageIter args;
	DBusError err;
	char* sigvalue;
    int ret;

	dbus_error_init(&err);
	
	connection = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
	if (connection == NULL){
		printf("Failed to open connection to bus: %s\n", err.message);
		dbus_error_free(&err);
		exit(1);
	}
	
	ret = dbus_bus_request_name(connection, "test.signal.usb", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
	
	if (dbus_error_is_set(&err)){
	    fprintf(stderr, "Name error (%s)\n", err.message); 
	    dbus_error_free(&err);
	}
	if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret){
	    printf("not primary owner!!\n");
	    exit(1);
	}
	
	printf("listening for usb additions\n ");
	//dbus_bus_add_match(connection, "type='signal',interface='test.signal.Type'", &err);
	dbus_bus_add_match(connection, "type='signal',interface='test.signal.Type'", &err);
	dbus_connection_flush(connection);

	if (dbus_error_is_set(&err)){
	    fprintf(stderr, "error (%s)\n", err.message); 
	    exit(1);
	}

	macaddrs = ht_create(100);
	
	while(true){
	    printf("creating dbus connection\n");
	    dbus_connection_read_write(connection,-1); //block, waiting on message
	    printf("seen a message!!\n");
	    while( (msg = dbus_connection_pop_message(connection)) != NULL){
            if (dbus_message_is_signal(msg, "test.signal.Type", "device")){
                printf("seen a signal!!\n");
                if (!dbus_message_iter_init(msg, &args)){
                    fprintf(stderr, "message has no parameters!\n");
                }
                else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)){
                     fprintf(stderr, "arg is not a string!\n");
                }
                else{
                    dbus_message_iter_get_basic(&args, &sigvalue);
                    printf("got signal %s\n", sigvalue);
                    int argc = 0;
                    char *token;
                    char command[7];
                    char device[18];
                    
                    if (sigvalue != NULL){
                        while ((token = strsep(&sigvalue, " ")) != NULL){
                            if (argc == 0){
                                sprintf(command, token, 0, 7);
                            }
                            if (argc == 1){
                                sprintf(device, token, 0, 15);
                            }
                            argc++;
                        }
                    }
                    if (argc == 3){
                        printf("read in %s %s args\n", command, device);
                        if (strcmp(command, "add") == 0){
                            handle_usb_plugged(device);
                        }else if (strcmp(command, "remove") == 0){
                            handle_usb_unplugged(device);
                        }
                    }
                }
                    //split up the parameter and call appropriate method (should this not be done with dbus method??)
            }
            dbus_message_unref(msg);
	    }
	}
}
示例#14
0
void handle_methods(DBusMessage *msg)
{
   DBusMessage* reply;
   DBusMessageIter args;

   dbus_uint32_t serial = 0;
   char* param = "";

   // read the arguments
   if (!dbus_message_iter_init(msg, &args))
      fprintf(stdout, "Message has no arguments!\n"); 
   else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
      fprintf(stdout, "Argument is not string!\n"); 
   else 
      dbus_message_iter_get_basic(&args, &param);

   printf("Method called with %s\n", param);

   // create a reply from the message
   reply = dbus_message_new_method_return(msg);

   // add the arguments to the reply
   dbus_message_iter_init_append(reply, &args);
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map1_val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map2_val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map3_val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map4_val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map5_val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map6_val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map1_r1val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map2_r1val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map2_r2val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map3_r2val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map4_r2val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map4_r3val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map5_r3val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_DOUBLE, &map6_r3val)) { 
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }

   // send the reply && flush the connection
   if (!dbus_connection_send(conn, reply, &serial)) {
      fprintf(stdout, "Out Of Memory!\n"); 
      exit(1);
   }
   dbus_connection_flush(conn);

   // free the reply
   dbus_message_unref(reply);
}
示例#15
0
int main (int argc, char* argv[])
{
    char *servicename = NULL;
    char *address = NULL;
    DBusMessage* message = NULL;
    DBusConnection* conn = NULL;
    int c;
    int ret = 1;
    int messageType = FCITX_DBUS_GET_CURRENT_STATE;
    char *imname = NULL;
    while ((c = getopt(argc, argv, "chortTeam:s:")) != -1) {
        switch (c) {
        case 'o':
            messageType = FCITX_DBUS_ACTIVATE;
            break;

        case 'c':
            messageType = FCITX_DBUS_INACTIVATE;
            break;

        case 'r':
            messageType = FCITX_DBUS_RELOAD_CONFIG;
            break;

        case 't':
        case 'T':
            messageType = FCITX_DBUS_TOGGLE;
            break;

        case 'e':
            messageType = FCITX_DBUS_EXIT;
            break;

        case 'm':
            messageType = FCITX_DBUS_GET_IM_ADDON;
            imname = strdup(optarg);
            break;

        case 's':
            messageType = FCITX_DBUS_SET_CURRENT_IM;
            imname = strdup(optarg);
            break;

        case 'a':
            address = _fcitx_get_address();
            if (address) {
                printf("%s\n", address);
                free(address);
                return 0;
            } else {
                return 1;
            }
        case 'h':
            usage(stdout);
            return 0;
        default:
            usage(stderr);
            return 1;
        }
    }

#define CASE(ENUMNAME, MESSAGENAME) \
        case FCITX_DBUS_##ENUMNAME: \
            message = dbus_message_new_method_call(servicename, FCITX_IM_DBUS_PATH, FCITX_IM_DBUS_INTERFACE, #MESSAGENAME); \
            break;

    asprintf(&servicename, "%s-%d", FCITX_DBUS_SERVICE, fcitx_utils_get_display_number());
    switch(messageType) {
        CASE(ACTIVATE, ActivateIM);
        CASE(INACTIVATE, InactivateIM);
        CASE(RELOAD_CONFIG, ReloadConfig);
        CASE(EXIT, Exit);
        CASE(TOGGLE, ToggleIM);
        CASE(GET_CURRENT_STATE, GetCurrentState);
        CASE(GET_IM_ADDON, GetIMAddon);
        CASE(SET_CURRENT_IM, SetCurrentIM);

        default:
            goto some_error;
    };
    if (!message) {
        goto some_error;
    }
    address = _fcitx_get_address();
    do {
        if (!address)
            break;
        conn = dbus_connection_open(address, NULL);
        if (!conn)
            break;
        if (!dbus_bus_register(conn, NULL)) {
            dbus_connection_unref(conn);
            conn = NULL;
            break;
        }
    } while(0);

    if (!conn) {
        conn = dbus_bus_get(DBUS_BUS_SESSION, NULL);

        if (!conn) {
            goto some_error;
        }

        dbus_connection_set_exit_on_disconnect(conn, FALSE);
    }

    if (messageType == FCITX_DBUS_GET_CURRENT_STATE) {
        DBusMessage* reply = dbus_connection_send_with_reply_and_block(conn, message, 1000, NULL);
        int result = 0;
        if (reply && dbus_message_get_args(reply, NULL, DBUS_TYPE_INT32, &result, DBUS_TYPE_INVALID)) {
            printf("%d\n", result);
            ret = 0;
        } else {
            fprintf(stderr, "Not get reply\n");
        }
    }
    else if (messageType == FCITX_DBUS_GET_IM_ADDON) {
        do {
            if (!fcitx_utf8_check_string(imname))
                break;
            dbus_message_append_args(message, DBUS_TYPE_STRING, &imname, DBUS_TYPE_INVALID);
            DBusMessage* reply = dbus_connection_send_with_reply_and_block(conn, message, 1000, NULL);
            char *result = NULL;
            if (reply && dbus_message_get_args(reply, NULL, DBUS_TYPE_STRING, &result, DBUS_TYPE_INVALID)) {
                printf("%s\n", result);
                ret = 0;
            } else {
                fprintf(stderr, "Not get reply\n");
            }
        } while(0);

    }
    else if (messageType == FCITX_DBUS_SET_CURRENT_IM) {
        do {
            if (!fcitx_utf8_check_string(imname))
                break;
            dbus_message_append_args(message, DBUS_TYPE_STRING, &imname, DBUS_TYPE_INVALID);
            dbus_connection_send(conn, message, NULL);
            dbus_connection_flush(conn);
            ret = 0;
        } while(0);
    } else {
        dbus_connection_send(conn, message, NULL);
        dbus_connection_flush(conn);
        ret = 0;
    }

some_error:
    if (message)
        dbus_message_unref(message);
    if (conn)
        dbus_connection_unref(conn);
    fcitx_utils_free(address);
    fcitx_utils_free(servicename);
    fcitx_utils_free(imname);
    return ret;
}
示例#16
0
文件: test.c 项目: nirmoy/dbus-task
/**
 * Connect to the DBUS bus and send a broadcast signal
 */
void sendsignal(char* sigvalue)
{
   DBusMessage* msg;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   int ret;
   dbus_uint32_t serial = 0;

   printf("Sending signal with value %s\n", sigvalue);

   // initialise the error value
   dbus_error_init(&err);

   // connect to the DBUS system bus, and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Connection Error (%s)\n", err.message); 
      dbus_error_free(&err); 
   }
   if (NULL == conn) { 
      exit(1); 
   }

   // register our name on the bus, and check for errors
   ret = dbus_bus_request_name(conn, "task.signal.source", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Name Error (%s)\n", err.message); 
      dbus_error_free(&err); 
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) { 
      exit(1);
   }

   // create a signal & check for errors 
   msg = dbus_message_new_signal("/task/signal/Object", // object name of the signal
                                 "task.signal.Type", // interface name of the signal
                                 "Test"); // name of the signal
   if (NULL == msg) 
   { 
      fprintf(stderr, "Message Null\n"); 
      exit(1); 
   }

   // append arguments onto signal
   dbus_message_iter_init_append(msg, &args);
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &sigvalue)) {
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   }

   // send the message and flush the connection
   if (!dbus_connection_send(conn, msg, &serial)) {
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   }
   dbus_connection_flush(conn);
   
   printf("Signal Sent\n");
   
   // free the message and close the connection
   dbus_message_unref(msg);
   dbus_connection_close(conn);
}
示例#17
0
void* FcitxNotificationItemCreate(FcitxInstance* instance)
{
    FcitxNotificationItem* notificationitem = fcitx_utils_new(FcitxNotificationItem);
    notificationitem->owner = instance;
    DBusError err;
    dbus_error_init(&err);
    do {
        DBusConnection *conn = FcitxDBusGetConnection(instance);
        if (conn == NULL) {
            FcitxLog(ERROR, "DBus Not initialized");
            break;
        }

        notificationitem->conn = conn;

        DBusObjectPathVTable fcitxIPCVTable = {NULL, &FcitxNotificationItemEventHandler, NULL, NULL, NULL, NULL };
        if (!dbus_connection_register_object_path(notificationitem->conn, NOTIFICATION_ITEM_DEFAULT_OBJ, &fcitxIPCVTable, notificationitem)) {
            FcitxLog(ERROR, "No memory");
            break;
        }

        if (!FcitxDBusMenuCreate(notificationitem)) {
            FcitxLog(ERROR, "No memory");
            break;
        }


        int id = FcitxDBusWatchName(instance,
                                    NOTIFICATION_WATCHER_DBUS_ADDR,
                                    notificationitem,
                                    FcitxNotificationItemOwnerChanged,
                                    NULL,
                                    NULL);

        if (id == 0) {
            break;
        }

        const char* notificationWatcher = NOTIFICATION_WATCHER_DBUS_ADDR;
        DBusMessage* message = dbus_message_new_method_call(DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "NameHasOwner");
        dbus_message_append_args(message, DBUS_TYPE_STRING, &notificationWatcher, DBUS_TYPE_INVALID);

        DBusPendingCall* call = NULL;
        dbus_bool_t reply =
            dbus_connection_send_with_reply(notificationitem->conn, message,
                                            &call, DBUS_TIMEOUT_USE_DEFAULT);
        if (reply == TRUE) {
            dbus_pending_call_set_notify(call,
                                         NotificationWatcherServiceExistCallback,
                                         notificationitem,
                                         NULL);
            dbus_pending_call_unref(call);
        }
        dbus_connection_flush(notificationitem->conn);
        dbus_message_unref(message);

        FcitxIMEventHook hk;
        hk.arg = notificationitem;
        hk.func = FcitxNotificationItemIMChanged;
        FcitxInstanceRegisterIMChangedHook(instance, hk);
        FcitxInstanceRegisterInputFocusHook(instance, hk);
        FcitxInstanceRegisterInputUnFocusHook(instance, hk);

        hk.func = FcitxNotificationItemUpdateIMList;
        FcitxInstanceRegisterUpdateIMListHook(instance, hk);

        dbus_error_free(&err);

        FcitxNotificationItemAddFunctions(instance);

        return notificationitem;
    } while(0);

    dbus_error_free(&err);
    FcitxNotificationItemDestroy(notificationitem);

    return NULL;
}
示例#18
0
文件: test.c 项目: nirmoy/dbus-task
/**
 * Listens for signals on the bus
 */
void receive()
{
   DBusMessage* msg;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   int ret;
   char* sigvalue;

   printf("Listening for signals\n");

   // initialise the errors
   dbus_error_init(&err);
   
   // connect to the bus and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Connection Error (%s)\n", err.message);
      dbus_error_free(&err); 
   }
   if (NULL == conn) { 
      exit(1);
   }
   
   // request our name on the bus and check for errors
   ret = dbus_bus_request_name(conn, "task.signal.sink", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Name Error (%s)\n", err.message);
      dbus_error_free(&err); 
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
      exit(1);
   }

   // add a rule for which messages we want to see
   dbus_bus_add_match(conn, "type='signal',interface='task.signal.Type'", &err); // see signals from the given interface
   dbus_connection_flush(conn);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Match Error (%s)\n", err.message);
      exit(1); 
   }
   printf("Match rule sent\n");

   // loop listening for signals being emmitted
   while (true) {

      // non blocking read of the next available message
      dbus_connection_read_write(conn, 0);
      msg = dbus_connection_pop_message(conn);

      // loop again if we haven't read a message
      if (NULL == msg) { 
         sleep(1);
         continue;
      }

      // check if the message is a signal from the correct interface and with the correct name
      if (dbus_message_is_signal(msg, "task.signal.Type", "Test")) {
         
         // read the parameters
         if (!dbus_message_iter_init(msg, &args))
            fprintf(stderr, "Message Has No Parameters\n");
         else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
            fprintf(stderr, "Argument is not string!\n"); 
         else
            dbus_message_iter_get_basic(&args, &sigvalue);
         
         printf("Got Signal with value %s\n", sigvalue);
      }

      // free the message
      dbus_message_unref(msg);
   }
   // close the connection
   dbus_connection_close(conn);
}
示例#19
0
文件: sbus_sync.c 项目: SSSD/sssd
errno_t
sbus_sync_message_send(TALLOC_CTX *mem_ctx,
                       struct sbus_sync_connection *conn,
                       DBusMessage *msg,
                       int timeout_ms,
                       DBusMessage **_reply)
{
    DBusError dbus_error;
    DBusMessage *reply;
    errno_t ret;

    if (msg == NULL) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Bug: message is empty!\n");
        return EINVAL;
    }

    if (conn->disconnecting) {
        DEBUG(SSSDBG_TRACE_FUNC, "Connection is being disconnected\n");
        return ERR_TERMINATED;
    }

    if (_reply == NULL) {
        dbus_connection_send(conn->connection, msg, NULL);
        dbus_connection_flush(conn->connection);
        return EOK;
    }

    dbus_error_init(&dbus_error);
    reply = dbus_connection_send_with_reply_and_block(conn->connection, msg,
                                                      timeout_ms, &dbus_error);
    if (dbus_error_is_set(&dbus_error)) {
        ret = sbus_error_to_errno(&dbus_error);
        goto done;
    } else if (reply == NULL) {
        ret = ERR_SBUS_NO_REPLY;
        goto done;
    }

    ret = sbus_reply_check(reply);
    if (ret != EOK) {
        goto done;
    }

    if (mem_ctx != NULL) {
        ret = sbus_message_bound(mem_ctx, reply);
        if (ret != EOK) {
            goto done;
        }
    }

    *_reply = reply;

done:
    if (ret != EOK) {
        DEBUG(SSSDBG_CRIT_FAILURE, "Error received [%d]: %s!\n",
              ret, sss_strerror(ret));
    }

    dbus_error_free(&dbus_error);

    return ret;
}
示例#20
0
文件: test.c 项目: nirmoy/dbus-task
/**
 * Call a method on a remote object
 */
void query(char* param) 
{
   DBusMessage* msg;
   DBusMessageIter args;
   DBusConnection* conn;
   DBusError err;
   DBusPendingCall* pending;
   int ret;
   bool stat;
   dbus_uint32_t level;

   printf("Calling remote method with %s\n", param);

   // initialiset the errors
   dbus_error_init(&err);

   // connect to the system bus and check for errors
   conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Connection Error (%s)\n", err.message); 
      dbus_error_free(&err);
   }
   if (NULL == conn) { 
      exit(1); 
   }

   // request our name on the bus
   ret = dbus_bus_request_name(conn, "task.method.caller", DBUS_NAME_FLAG_REPLACE_EXISTING , &err);
   if (dbus_error_is_set(&err)) { 
      fprintf(stderr, "Name Error (%s)\n", err.message); 
      dbus_error_free(&err);
   }
   if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) { 
      exit(1);
   }

   // create a new method call and check for errors
   msg = dbus_message_new_method_call("task.method.server", // target for the method call
                                      "/task/method/Object", // object to call on
                                      "task.method.Type", // interface to call on
                                      "Method"); // method name
   if (NULL == msg) { 
      fprintf(stderr, "Message Null\n");
      exit(1);
   }

   // append arguments
   dbus_message_iter_init_append(msg, &args);
   if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &param)) {
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   }
   
   // send message and get a handle for a reply
   if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
      fprintf(stderr, "Out Of Memory!\n"); 
      exit(1);
   }
   if (NULL == pending) { 
      fprintf(stderr, "Pending Call Null\n"); 
      exit(1); 
   }
   dbus_connection_flush(conn);
   
   printf("Request Sent\n");
   
   // free message
   dbus_message_unref(msg);
   
   // block until we recieve a reply
   dbus_pending_call_block(pending);

   // get the reply message
   msg = dbus_pending_call_steal_reply(pending);
   if (NULL == msg) {
      fprintf(stderr, "Reply Null\n"); 
      exit(1); 
   }
   // free the pending message handle
   dbus_pending_call_unref(pending);

   // read the parameters
   if (!dbus_message_iter_init(msg, &args))
      fprintf(stderr, "Message has no arguments!\n"); 
   else if (DBUS_TYPE_BOOLEAN != dbus_message_iter_get_arg_type(&args)) 
      fprintf(stderr, "Argument is not boolean!\n"); 
   else
      dbus_message_iter_get_basic(&args, &stat);

   if (!dbus_message_iter_next(&args))
      fprintf(stderr, "Message has too few arguments!\n"); 
   else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) 
      fprintf(stderr, "Argument is not int!\n"); 
   else
      dbus_message_iter_get_basic(&args, &level);

   printf("Got Reply: %d, %d\n", stat, level);
   
   // free reply and close connection
   dbus_message_unref(msg);   
   dbus_connection_close(conn);
}
static int send_dbus_signal(DBusConnection *conn,
			const char *msg_name,
			const char *value) {
	DBusMessage *msg;
	DBusMessageIter args;
	DBusPendingCall *pending;
	int result = 0;

	/* create a signal and check for errors */
	msg = dbus_message_new_method_call(STE_MAD_DBUS_SERVICE,
					STE_MAD_DBUS_OBJECT_NAME,
					STE_MAD_DBUS_TXBO_IF_NAME,
					msg_name);

	if (msg == NULL) {
		ERR("failed to allocate memory\n");
		return -1;
	}

	/* append arguments onto signal */
	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &value)) {
		ERR("failed to allocate memory\n");
		result = -1;
		goto exit;
	}

	/* send the message and flush the connection */
	if (!dbus_connection_send_with_reply(conn, msg, &pending, -1)) {
		ERR("DBUS message sending failed\n");
		result = -1;
		goto exit;
	}

	/* send request */
	dbus_connection_flush(conn);
	dbus_message_unref(msg);

	/* wait for ACK from MAD */
	dbus_pending_call_block(pending);
	msg = dbus_pending_call_steal_reply(pending);
	dbus_pending_call_unref(pending);

	if (msg == NULL) {
		ERR("failed to receive MAD's ACK\n");
		goto exit;
	}

	if (dbus_message_get_type(msg) == DBUS_MESSAGE_TYPE_ERROR) {
		DBusError err;

		dbus_error_init(&err);
		dbus_set_error_from_message(&err, msg);
		ERR("MAD ACK failed: %s\n", err.message);
		dbus_error_free(&err);
		goto exit;
	}

exit:
	if (msg) {
		dbus_message_unref(msg);
	}
	return result;
}
int main(int argc, char *argv[])
{
	DBusConnection *conn;
	DBusError error;
	DBusMessage *msg;
	DBusMessageIter iter, dict;
	char **envp, *busname, *interface, *path, *reason;
	int ret = 0;

	openlog(basename(argv[0]), LOG_NDELAY | LOG_PID, LOG_DAEMON);

	busname = getenv("CONNMAN_BUSNAME");
	interface = getenv("CONNMAN_INTERFACE");
	path = getenv("CONNMAN_PATH");

	reason = getenv("script_type");

	if (!busname || !interface || !path || !reason) {
		print("Required environment variables not set");
		ret = 1;
		goto out;
	}
	dbus_error_init(&error);

	conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	if (conn == NULL) {
		if (dbus_error_is_set(&error) == TRUE) {
			print("%s", error.message);
			dbus_error_free(&error);
		} else
			print("Failed to get on system bus");

		goto out;
	}

	msg = dbus_message_new_method_call(busname, path,
						interface, "notify");
	if (msg == NULL) {
		dbus_connection_unref(conn);
		print("Failed to allocate method call");
		goto out;
	}

	dbus_message_set_no_reply(msg, TRUE);

	dbus_message_append_args(msg,
				 DBUS_TYPE_STRING, &reason,
				 DBUS_TYPE_INVALID);

	dbus_message_iter_init_append(msg, &iter);

	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_STRING_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);

	for (envp = environ; envp && *envp; envp++)
		append(&dict, *envp);

	dbus_message_iter_close_container(&iter, &dict);

	if (dbus_connection_send(conn, msg, NULL) == FALSE) {
		print("Failed to send message");
		goto out;
	}

	dbus_connection_flush(conn);

	dbus_message_unref(msg);

	dbus_connection_unref(conn);

out:
	closelog();

	return ret;
}
示例#23
0
int main(int argc, char *argv[]) {
        DBusError error;
        DBusConnection *bus = NULL;
        DBusMessage *m = NULL;
        int r = EXIT_FAILURE;

        dbus_error_init(&error);

        if (argc != 2) {
                log_error("Incorrect number of arguments.");
                goto finish;
        }

        log_set_target(LOG_TARGET_AUTO);
        log_parse_environment();
        log_open();

        /* We send this event to the private D-Bus socket and then the
         * system instance will forward this to the system bus. We do
         * this to avoid an activation loop when we start dbus when we
         * are called when the dbus service is shut down. */

        bus = dbus_connection_open_private("unix:path=/run/systemd/private", &error);
        if (!bus) {
                log_warning("Failed to get D-Bus connection: %s", bus_error_message(&error));
                goto finish;
        }

        if (bus_check_peercred(bus) < 0) {
                log_error("Bus owner not root.");
                goto finish;
        }

        m = dbus_message_new_signal("/org/freedesktop/systemd1/agent", "org.freedesktop.systemd1.Agent", "Released");
        if (!m) {
                log_error("Could not allocate signal message.");
                goto finish;
        }

        if (!dbus_message_append_args(m,
                                      DBUS_TYPE_STRING, &argv[1],
                                      DBUS_TYPE_INVALID)) {
                log_error("Could not attach group information to signal message.");
                goto finish;
        }

        if (!dbus_connection_send(bus, m, NULL)) {
                log_error("Failed to send signal message on private connection.");
                goto finish;
        }

        r = EXIT_SUCCESS;

finish:
        if (bus) {
                dbus_connection_flush(bus);
                dbus_connection_close(bus);
                dbus_connection_unref(bus);
        }

        if (m)
                dbus_message_unref(m);

        dbus_error_free(&error);
        return r;
}
示例#24
0
void listen_signal()
{
    DBusMessage * msg;
    DBusMessageIter arg;
    DBusConnection * connection;
    DBusError err;
    int ret;
    char * sigvalue;

    //步骤1:建立与D-Bus后台的连接
    dbus_error_init(&err);
    connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
    if(dbus_error_is_set(&err)) {
        fprintf(stderr,"Connection Error %s\n",err.message);
        dbus_error_free(&err);
    }
    if(connection == NULL) {
        return;
    }

    //步骤2:给连接名分配一个可记忆名字test.singal.dest作为Bus name,这个步骤不是必须的,但推荐这样处理
    ret = dbus_bus_request_name(connection,"test.singal.dest",DBUS_NAME_FLAG_REPLACE_EXISTING,&err);
    if(dbus_error_is_set(&err)) {
        fprintf(stderr,"Name Error %s\n",err.message);
        dbus_error_free(&err);
    }
    if(ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
        return;
    }

    //步骤3:通知D-Bus daemon,希望监听来行接口test.signal.Type的信号
    dbus_bus_add_match(connection,"type='signal',interface='test.signal.Type'",&err);
    //实际需要发送东西给daemon来通知希望监听的内容,所以需要flush
    dbus_connection_flush(connection);
    if(dbus_error_is_set(&err)) {
        fprintf(stderr,"Match Error %s\n",err.message);
        dbus_error_free(&err);
    }

    //步骤4:在循环中监听,每隔开1秒,就去试图自己的连接中获取这个信号。这里给出的是从连接中获取任何消息的方式,所以获取后去检查一下这个消息是否我们期望的信号,并获取内容。我们也可以通过这个方式来获取method call消息。
    while(1) {
        dbus_connection_read_write(connection,0);
        msg = dbus_connection_pop_message (connection);
        if(msg == NULL){
            sleep(1);
            continue;
        }

        if(dbus_message_is_signal(msg,"test.signal.Type","Test") ){
            if(!dbus_message_iter_init(msg,&arg)) {
                fprintf(stderr,"Message Has no Param");
            } else if(dbus_message_iter_get_arg_type(&arg) != DBUS_TYPE_STRING) {
                g_printerr("Param is not string");
            } else {
                dbus_message_iter_get_basic(&arg,&sigvalue);
                printf("Got Singal with value : %s\n",sigvalue);
            }
        }
        dbus_message_unref(msg);
    }//End of while

    return ;
}
示例#25
0
/**
 * Listens for signals on the bus
 */
int sedbus_send_avc(DBusConnection* conn, char *avc) {

	DBusMessage* msg;
	DBusMessageIter args;
	DBusPendingCall* pending;
	char* reply = NULL;

	msg = dbus_message_new_method_call(BUSNAME, 
					   PATH, 
					   INTERFACE,
					   "avc"); // method name
	if (NULL == msg) { 
		fprintf(stderr, "Can't communicate with setroubleshootd\n");
		return -1;
	}
	// append arguments
	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &avc)) { 
		fprintf(stderr, "Out Of Memory!\n"); 
		return -1;
	}

	// send message and get a handle for a reply
	if ( ! dbus_connection_send_with_reply (conn, msg, &pending, -1)) { 
		// -1 is default timeout
		fprintf(stderr, "Out Of Memory!\n"); 
		return -1;
	}
	if (NULL == pending) { 
		fprintf(stderr, "Pending Call Null\n"); 
		return -1;
	}
	dbus_connection_flush(conn);
	
	// free message
	dbus_message_unref(msg);

	// block until we receive a reply
	dbus_pending_call_block(pending);
   
	// get the reply message
	msg = dbus_pending_call_steal_reply(pending);
	if (NULL == msg) {
		fprintf(stderr, "Reply Null\n"); 
		exit(1); 
	}
	// free the pending message handle
	dbus_pending_call_unref(pending);

	// read the parameters
	if (!dbus_message_iter_init(msg, &args))
		fprintf(stderr, "Message has no arguments!\n"); 
	else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
		fprintf(stderr, "Argument is not boolean!\n"); 
	else
		dbus_message_iter_get_basic(&args, &reply);

	printf("Send: %s\n", avc);
	printf("Got Reply: %s\n", reply);

	// free reply and close connection
	dbus_message_unref(msg);   

	return 0;
}
示例#26
0
int
main (int   argc,
      char *argv[])
{
	char **             args;
	DBusConnection *    conn;
	int fd, optval = 1, exitval = 1, ret;
	DBusMessage *message = NULL, *reply = NULL;
	DBusMessageIter iter;
	dbus_uint32_t serial;;

	nih_main_init (argv[0]);

	nih_option_set_synopsis (_("Control group client"));

	args = nih_option_parser (NULL, argc, argv, options, FALSE);
	if (! args)
		exit (1);

	if (!controller)
		usage(argv[0]);

	if (pid == -1)
		pid = getpid();

	conn = nih_dbus_connect("unix:path=/tmp/cgmanager", NULL);
	nih_assert (conn != NULL);

	message = dbus_message_new_method_call(dbus_bus_get_unique_name(conn),
			"/org/linuxcontainers/cgmanager",
			"org.linuxcontainers.cgmanager0_0", "getPidCgroup");

	if (!dbus_connection_get_socket(conn, &fd)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					"Could not get socket");
		return -1;
	}
	if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &optval, sizeof(optval)) == -1) {
		perror("setsockopt");
		return -1;
	}

	dbus_message_iter_init_append(message, &iter);
        if (! dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING,
                                              &controller)) {
                nih_error_raise_no_memory ();
                return -1;
        }
	dbus_message_iter_init_append(message, &iter);
        if (! dbus_message_iter_append_basic (&iter, DBUS_TYPE_INT32,
                                              &pid)) {
                nih_error_raise_no_memory ();
                return -1;
        }

	if (!dbus_connection_send(conn, message, &serial)) {
		nih_error("failed to send dbus message");
		return -1;
	}
	dbus_connection_flush(conn);

	/* If we're sending our own pid, or if we're root, then
	 * we can send an SCM_CREDENTIAL
	 */
	if (pid == getpid() || geteuid() == 0) {
		if (send_pid(fd, pid)) {
			nih_error("Error sending pid over SCM_CREDENTIAL");
			goto out;
		}
	}

	while (!(reply = dbus_connection_pop_message(conn)))
		dbus_connection_read_write(conn, -1);
	if (dbus_message_get_reply_serial(reply) != serial) {
		nih_error("wrong serial on reply");
		goto out;
	}

	dbus_message_iter_init(reply, &iter);
	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING) {
		nih_error("Got bad reply type: %d", dbus_message_iter_get_arg_type(&iter));
		goto out;
	}
	char *str_value;
	dbus_message_iter_get_basic(&iter, &str_value);
	printf("%s\n", str_value);
	exitval = 0;

out:
	if (message)
		dbus_message_unref(message);
	if (reply)
		dbus_message_unref(reply);
	dbus_connection_unref (conn);
	exit(exitval);
}
示例#27
0
static struct TRACK mediaplayer_get_track(const char *id) {
	int current_type;
	DBusMessage* msg;
	DBusMessageIter args, array, dict, element, var, artist;
	DBusPendingCall* pending;
	static const char *prop="Metadata";
	char player[256];
	struct TRACK track={
		"Unknown",
		"Unknown",
		"Unknown",
	};
	
	sprintf(player, "%s%s", mpris.base, id);
	if(!(msg=dbus_message_new_method_call(player, mpris.object, dbus.interface_prop, "Get")))
		return track;
	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &mpris.interface_player)) {
		dbus_message_unref(msg);
		return track;
	}
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &prop)) {
		dbus_message_unref(msg);
		return track;
	}
	if(!dbus_connection_send_with_reply(dbus.session.connection, msg, &pending, -1)) {
		dbus_message_unref(msg);
		return track;
	}
	if(!pending) {
		dbus_message_unref(msg);
		return track;
	}
	dbus_connection_flush(dbus.session.connection);
	dbus_message_unref(msg);
	dbus_pending_call_block(pending);
	if(!(msg=dbus_pending_call_steal_reply(pending))) {
		dbus_pending_call_unref(pending);
		return track;
	}
	dbus_pending_call_unref(pending);
	if(!dbus_message_iter_init(msg, &args)) {
		dbus_message_unref(msg);
		return track;
	}
	
	if(dbus_message_iter_get_arg_type(&args)!=DBUS_TYPE_VARIANT) {
		dbus_message_unref(msg);
		return track;
	}
	dbus_message_iter_recurse(&args, &array);
	if(dbus_message_iter_get_arg_type(&array)!=DBUS_TYPE_ARRAY) {
		dbus_message_unref(msg);
		return track;
	}
	
	for(dbus_message_iter_recurse(&array, &dict); (current_type=dbus_message_iter_get_arg_type(&dict))!=DBUS_TYPE_INVALID; dbus_message_iter_next(&dict)) {
		char *element_key, *element_value;
		int element_type;
		dbus_message_iter_recurse(&dict, &element);
		if(dbus_message_iter_get_arg_type(&element)!=DBUS_TYPE_STRING)
			continue;
		
		dbus_message_iter_get_basic(&element, &element_key);
		dbus_message_iter_next(&element);
		if(dbus_message_iter_get_arg_type(&element)!=DBUS_TYPE_VARIANT)
			continue;
		
		dbus_message_iter_recurse(&element, &var);
		element_type=dbus_message_iter_get_arg_type(&var);
		if(element_type==DBUS_TYPE_STRING) {
			dbus_message_iter_get_basic(&var, &element_value);
			if(!strcmp(element_key, "xesam:album"))
				snprintf(track.album, TRACK_ELEMENT_LENGTH, "%s", element_value);
			else if(!strcmp(element_key, "xesam:title"))
				snprintf(track.title, TRACK_ELEMENT_LENGTH, "%s", element_value);
		} else if(element_type==DBUS_TYPE_ARRAY) {
			/*just handle one artist for now*/
			dbus_message_iter_recurse(&var, &artist);
			if(dbus_message_iter_get_arg_type(&artist)!=DBUS_TYPE_STRING)
				continue;
			dbus_message_iter_get_basic(&artist, &element_value);
			if(!strcmp(element_key, "xesam:artist"))
				snprintf(track.artist, TRACK_ELEMENT_LENGTH, "%s", element_value);
		}
	}
	dbus_message_unref(msg);
	return track;
}
示例#28
0
文件: dbus.c 项目: etix/vlc
static int Open( vlc_object_t *p_this )
{
    intf_thread_t   *p_intf = (intf_thread_t*)p_this;

    /* initialisation of the connection */
    if( !dbus_threads_init_default() )
        return VLC_EGENERIC;

    intf_sys_t *p_sys  = calloc( 1, sizeof( intf_sys_t ) );
    if( unlikely(!p_sys) )
        return VLC_ENOMEM;

    playlist_t      *p_playlist;
    DBusConnection  *p_conn;
    p_sys->i_player_caps   = PLAYER_CAPS_NONE;
    p_sys->i_playing_state = PLAYBACK_STATE_INVALID;

    if( vlc_pipe( p_sys->p_pipe_fds ) )
    {
        free( p_sys );
        msg_Err( p_intf, "Could not create pipe" );
        return VLC_EGENERIC;
    }

    DBusError error;
    dbus_error_init( &error );

    /* connect privately to the session bus
     * the connection will not be shared with other vlc modules which use dbus,
     * thus avoiding a whole class of concurrency issues */
    p_conn = dbus_bus_get_private( DBUS_BUS_SESSION, &error );
    if( !p_conn )
    {
        msg_Err( p_this, "Failed to connect to the D-Bus session daemon: %s",
                error.message );
        dbus_error_free( &error );
        vlc_close( p_sys->p_pipe_fds[1] );
        vlc_close( p_sys->p_pipe_fds[0] );
        free( p_sys );
        return VLC_EGENERIC;
    }

    dbus_connection_set_exit_on_disconnect( p_conn, FALSE );

    /* Register the entry point object path */
    dbus_connection_register_object_path( p_conn, DBUS_MPRIS_OBJECT_PATH,
            &dbus_mpris_vtable, p_this );

    /* Try to register org.mpris.MediaPlayer2.vlc */
    dbus_bus_request_name( p_conn, DBUS_MPRIS_BUS_NAME, 0, &error );
    if( dbus_error_is_set( &error ) )
    {
        msg_Dbg( p_this, "Failed to get service name %s: %s",
                 DBUS_MPRIS_BUS_NAME, error.message );
        dbus_error_free( &error );

        /* Register an instance-specific well known name of the form
         * org.mpris.MediaPlayer2.vlc.instanceXXXX where XXXX is the
         * current Process ID */
        char unique_service[sizeof( DBUS_MPRIS_BUS_NAME ) +
                            sizeof( DBUS_INSTANCE_ID_PREFIX ) + 10];

        snprintf( unique_service, sizeof (unique_service),
                  DBUS_MPRIS_BUS_NAME"."DBUS_INSTANCE_ID_PREFIX"%"PRIu32,
                  (uint32_t)getpid() );

        dbus_bus_request_name( p_conn, unique_service, 0, &error );
        if( dbus_error_is_set( &error ) )
        {
            msg_Err( p_this, "Failed to get service name %s: %s",
                     DBUS_MPRIS_BUS_NAME, error.message );
            dbus_error_free( &error );
        }
        else
            msg_Dbg( p_intf, "listening on dbus as: %s", unique_service );
    }
    else
        msg_Dbg( p_intf, "listening on dbus as: %s", DBUS_MPRIS_BUS_NAME );

    dbus_connection_flush( p_conn );

    p_intf->p_sys = p_sys;
    p_sys->p_conn = p_conn;
    p_sys->p_events = vlc_array_new();
    p_sys->p_timeouts = vlc_array_new();
    p_sys->p_watches = vlc_array_new();
    vlc_mutex_init( &p_sys->lock );

    p_playlist = pl_Get( p_intf );
    p_sys->p_playlist = p_playlist;

    var_AddCallback( p_playlist, "input-current", AllCallback, p_intf );
    var_AddCallback( p_playlist, "volume", AllCallback, p_intf );
    var_AddCallback( p_playlist, "mute", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-append", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-deleted", AllCallback, p_intf );
    var_AddCallback( p_playlist, "random", AllCallback, p_intf );
    var_AddCallback( p_playlist, "repeat", AllCallback, p_intf );
    var_AddCallback( p_playlist, "loop", AllCallback, p_intf );
    var_AddCallback( p_playlist, "fullscreen", AllCallback, p_intf );

    if( !dbus_connection_set_timeout_functions( p_conn,
                                                add_timeout,
                                                remove_timeout,
                                                toggle_timeout,
                                                p_intf, NULL ) )
        goto error;

    if( !dbus_connection_set_watch_functions( p_conn,
                                              add_watch,
                                              remove_watch,
                                              watch_toggled,
                                              p_intf, NULL ) )
        goto error;

    if( vlc_clone( &p_sys->thread, Run, p_intf, VLC_THREAD_PRIORITY_LOW ) )
        goto error;

    return VLC_SUCCESS;

error:
    /* The dbus connection is private,
     * so we are responsible for closing it
     * XXX: Does this make sense when OOM ? */
    dbus_connection_close( p_sys->p_conn );
    dbus_connection_unref( p_conn );

    vlc_array_destroy( p_sys->p_events );
    vlc_array_destroy( p_sys->p_timeouts );
    vlc_array_destroy( p_sys->p_watches );

    vlc_mutex_destroy( &p_sys->lock );

    vlc_close( p_sys->p_pipe_fds[1] );
    vlc_close( p_sys->p_pipe_fds[0] );
    free( p_sys );
    return VLC_ENOMEM;
}
示例#29
0
static void mediaplayer_register(const char *id) {
	DBusMessage* msg;
	DBusMessageIter args, element;
	DBusPendingCall* pending;
	char *name=NULL;
	static const char *prop="Identity";
	struct MEDIAPLAYER **mp;
	char player[256];
	
	for(mp=&mediaplayer; *mp; mp=&((*mp)->next)) {
		if(!strcmp(id, (*mp)->id))
			return;
	}
	sprintf(player, "%s.%s", mpris.interface, id);
	if(!(msg=dbus_message_new_method_call(player, mpris.object, dbus.interface_prop, "Get")))
		goto do_register;
	dbus_message_iter_init_append(msg, &args);
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &mpris.interface)) {
		dbus_message_unref(msg);
		goto do_register;
	}
	if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &prop)) {
		dbus_message_unref(msg);
		goto do_register;
	}
	if(!dbus_connection_send_with_reply(dbus.session.connection, msg, &pending, -1)) {
		dbus_message_unref(msg);
		goto do_register;
	}
	if(!pending) {
		dbus_message_unref(msg);
		goto do_register;
	}
	dbus_connection_flush(dbus.session.connection);
	dbus_message_unref(msg);
	dbus_pending_call_block(pending);
	if (!(msg=dbus_pending_call_steal_reply(pending))) {
		dbus_pending_call_unref(pending);
		goto do_register;
	}
	dbus_pending_call_unref(pending);
	if(!dbus_message_iter_init(msg, &args)) {
		dbus_message_unref(msg);
		goto do_register;
	} else if(dbus_message_iter_get_arg_type(&args)!=DBUS_TYPE_VARIANT) {
		dbus_message_unref(msg);
		goto do_register;
	}
	
	dbus_message_iter_recurse(&args, &element);
	dbus_message_iter_get_basic(&element, &name);
	dbus_message_unref(msg);
	
	do_register:
	*mp=malloc(sizeof(struct MEDIAPLAYER));
	(*mp)->id=malloc(strlen(id)+1);
	if(name) {
		(*mp)->name=malloc(strlen(name)+1);
		strcpy((void *) (*mp)->name, name);
	} else
		(*mp)->name=NULL;
	(*mp)->next=NULL;
	strcpy((void *) (*mp)->id, id);
}
示例#30
0
文件: dbus.c 项目: RicoP/vlcfork
static int Open( vlc_object_t *p_this )
{
    intf_thread_t   *p_intf = (intf_thread_t*)p_this;

    /* initialisation of the connection */
    if( !dbus_threads_init_default() )
        return VLC_EGENERIC;

    intf_sys_t *p_sys  = calloc( 1, sizeof( intf_sys_t ) );
    if( unlikely(!p_sys) )
        return VLC_ENOMEM;

    playlist_t      *p_playlist;
    DBusConnection  *p_conn;
    p_sys->i_player_caps   = PLAYER_CAPS_NONE;
    p_sys->i_playing_state = PLAYBACK_STATE_INVALID;

    if( vlc_pipe( p_sys->p_pipe_fds ) )
    {
        free( p_sys );
        msg_Err( p_intf, "Could not create pipe" );
        return VLC_EGENERIC;
    }

    DBusError error;
    dbus_error_init( &error );

    /* connect privately to the session bus
     * the connection will not be shared with other vlc modules which use dbus,
     * thus avoiding a whole class of concurrency issues */
    p_conn = dbus_bus_get_private( DBUS_BUS_SESSION, &error );
    if( !p_conn )
    {
        msg_Err( p_this, "Failed to connect to the D-Bus session daemon: %s",
                error.message );
        dbus_error_free( &error );
        free( p_sys );
        return VLC_EGENERIC;
    }

    dbus_connection_set_exit_on_disconnect( p_conn, FALSE );

    /* register a well-known name on the bus */
    char unique_service[sizeof (DBUS_MPRIS_BUS_NAME) + 10];
    snprintf( unique_service, sizeof (unique_service),
              DBUS_MPRIS_BUS_NAME"-%"PRIu32, (uint32_t)getpid() );
    dbus_bus_request_name( p_conn, unique_service, 0, &error );
    if( dbus_error_is_set( &error ) )
    {
        msg_Err( p_this, "Error requesting service name %s: %s",
                 unique_service, error.message );
        dbus_error_free( &error );
        free( p_sys );
        return VLC_EGENERIC;
    }
    msg_Dbg( p_intf, "listening on dbus as: %s", unique_service );

    dbus_bus_request_name( p_conn, DBUS_MPRIS_BUS_NAME, 0, NULL );

    /* Register the entry point object path */
    dbus_connection_register_object_path( p_conn, DBUS_MPRIS_OBJECT_PATH,
            &dbus_mpris_vtable, p_this );

    dbus_connection_flush( p_conn );

    p_intf->pf_run = Run;
    p_intf->p_sys = p_sys;
    p_sys->p_conn = p_conn;
    p_sys->p_events = vlc_array_new();
    p_sys->p_timeouts = vlc_array_new();
    p_sys->p_watches = vlc_array_new();
    vlc_mutex_init( &p_sys->lock );

    p_playlist = pl_Get( p_intf );
    p_sys->p_playlist = p_playlist;

    var_AddCallback( p_playlist, "item-current", AllCallback, p_intf );
    var_AddCallback( p_playlist, "intf-change", AllCallback, p_intf );
    var_AddCallback( p_playlist, "volume", AllCallback, p_intf );
    var_AddCallback( p_playlist, "mute", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-append", AllCallback, p_intf );
    var_AddCallback( p_playlist, "playlist-item-deleted", AllCallback, p_intf );
    var_AddCallback( p_playlist, "random", AllCallback, p_intf );
    var_AddCallback( p_playlist, "repeat", AllCallback, p_intf );
    var_AddCallback( p_playlist, "loop", AllCallback, p_intf );
    var_AddCallback( p_playlist, "fullscreen", AllCallback, p_intf );

    if( !dbus_connection_set_timeout_functions( p_conn,
                                                add_timeout,
                                                remove_timeout,
                                                timeout_toggled,
                                                p_intf, NULL ) )
    {
        dbus_connection_unref( p_conn );
        free( p_sys );
        return VLC_ENOMEM;
    }

    if( !dbus_connection_set_watch_functions( p_conn,
                                              add_watch,
                                              remove_watch,
                                              watch_toggled,
                                              p_intf, NULL ) )
    {
        dbus_connection_unref( p_conn );
        free( p_sys );
        return VLC_ENOMEM;
    }

/*     dbus_connection_set_wakeup_main_function( p_conn,
                                              wakeup_main_loop,
                                              p_intf, NULL); */

    return VLC_SUCCESS;
}