EXPORT_C
dbus_bool_t
_dbus_server_test (void)
{
  const char *valid_addresses[] = {
    "tcp:port=1234",
   // #ifndef __SYMBIAN32__
    "unix:path=./boogie",
 //   #endif
    "tcp:host=localhost,port=1234",
    "tcp:host=localhost,port=1234;tcp:port=5678",
    "tcp:port=1234;unix:path=./boogie",
  };

  DBusServer *server;
  int i;
  
  for (i = 0; i < _DBUS_N_ELEMENTS (valid_addresses); i++)
    {
      DBusError error;

      /* FIXME um, how are the two tests here different? */
      
      dbus_error_init (&error);
      server = dbus_server_listen (valid_addresses[i], &error);
      if (server == NULL)
        {
          _dbus_warn ("server listen error: %s: %s\n", error.name, error.message);
          dbus_error_free (&error);
          _dbus_assert_not_reached ("Failed to listen for valid address.");
        }
	 #ifdef __SYMBIAN32__	
	  if(server!=NULL)	
	  {
	  dbus_server_disconnect (server);
      dbus_server_unref (server);
	  }
	 #else
	 dbus_server_disconnect (server);
     dbus_server_unref (server); 
	 #endif 
      /* Try disconnecting before unreffing */
      server = dbus_server_listen (valid_addresses[i], &error);
      if (server == NULL)
        {
          _dbus_warn ("server listen error: %s: %s\n", error.name, error.message);
          dbus_error_free (&error);          
          _dbus_assert_not_reached ("Failed to listen for valid address.");
        }
      #ifdef __SYMBIAN32__  
      if(server!=NULL)   
      {
      dbus_server_disconnect (server);
      dbus_server_unref (server);
      }
      #else
      dbus_server_disconnect (server);
      dbus_server_unref (server);
      #endif
    }

  return TRUE;
}
void method_AddService(char *path)
{
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    dbus_error_init(&err);
    DBusPendingCall* pending;
    dbus_int32_t interface = -1;
    dbus_int32_t protocol = -1;
    dbus_uint32_t flags = 0;
    char *name = "xifei";
    char *type = "_http._tcp";
    char *domain = "local";
    char *host = "192.168.160.3";
    dbus_uint16_t port = 500;
    char *txt1 = "xifei";
    char *txt2 = "password of xifei";
 /*
    <arg name="interface" type="i" direction="in"/>
    <arg name="protocol" type="i" direction="in"/>
    <arg name="flags" type="u" direction="in"/>
    <arg name="name" type="s" direction="in"/>
    <arg name="type" type="s" direction="in"/>
    <arg name="domain" type="s" direction="in"/>
    <arg name="host" type="s" direction="in"/>
    <arg name="port" type="q" direction="in"/>
    <arg name="txt" type="aay" direction="in"/>
 */
   // initialiset the errors
    printf("Calling remote method: %s\n", "org.freedesktop.Avahi.EntryGroup");

   // 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);
    }

    msg = dbus_message_new_method_call("org.freedesktop.Avahi",// target for the method call
                                        path, 							// object to call on
                                        "org.freedesktop.Avahi.EntryGroup",    // interface to call on
                                        "AddService");             // method nameResolveHostName
    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_INT32, &interface))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_INT32, &protocol))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &flags))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &name))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &type))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &domain))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &host))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT16, &port))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    /*
	DBusMessageIter iter_ay, iter_y;
	// Open dict entry container
	if (!dbus_message_iter_open_container(&args, DBUS_TYPE_ARRAY, "ay", &iter_ay)) {
			printf("Can't open container for iter_ay\n");
			exit(1);
	}
	if (!dbus_message_iter_open_container(&iter_ay, DBUS_TYPE_ARRAY, "y", &iter_y)) {
			printf("Can't open container for iter_y\n");
			exit(1);
	}
	dbus_uint16_t  bb=98;
	dbus_uint16_t  cc=97;
	dbus_message_iter_append_basic(&iter_y, DBUS_TYPE_BYTE, &bb);
	dbus_message_iter_append_basic(&iter_y, DBUS_TYPE_BYTE, &cc);
	dbus_message_iter_close_container(&iter_ay, &iter_y);
	dbus_message_iter_close_container(&args, &iter_ay);
	g_message("signature of iter_ay: %s", dbus_message_iter_get_signature(&iter_ay));
	g_message("signature of args: %s", dbus_message_iter_get_signature(&args));
*/

	 DBusMessageIter iter_ay, iter_y;
  if (!dbus_message_iter_open_container(&args, DBUS_TYPE_ARRAY, "ay", &iter_ay))
      {
		printf("Can't open container for iter_ay\n");
      exit(1);
      }
	if (!dbus_message_iter_open_container(&iter_ay, DBUS_TYPE_ARRAY, "y", &iter_y)) {
			printf("Can't open container for iter_y\n");
			exit(1);
	}
	if (!dbus_message_iter_append_fixed_array (&iter_y, DBUS_TYPE_BYTE, &txt1, sizeof(txt1)))
	 {
	     fprintf (stderr, "No memory!\n");
	}
	dbus_message_iter_close_container(&iter_ay, &iter_y);
	dbus_message_iter_close_container(&args, &iter_ay);
	g_message("arrive here1.");
	g_message("signature of msg: %s", dbus_message_get_signature(msg));
//	g_message("signature of iter_ay: %s", dbus_message_iter_get_signature(&iter_ay));
//	g_message("signature of args: %s", dbus_message_iter_get_signature(&args));
	
  // send message and get a handle for a reply
  if (!dbus_connection_send (conn, msg, NULL)) { // -1 is default timeout
     fprintf(stderr, "Out Of Memory!\n"); 
     exit(1);
     }

    dbus_connection_flush(conn);
   
    printf("Request Sent\n");
   
    // free message
    dbus_message_unref(msg);
}
/**
 * Connects to the D-Bus system bus daemon and issues the method call
 * OpenSession on the ConsoleKit manager interface. The
 * connection to the bus is private.
 *
 * Returns FALSE on OOM, if the system bus daemon is not running, if
 * the ConsoleKit daemon is not running or if the caller doesn't have
 * sufficient privileges.
 *
 * @returns #TRUE if the operation succeeds
 */
dbus_bool_t
ck_connector_open_session (CkConnector *connector,
                           DBusError   *error)
{
        DBusError    local_error;
        DBusMessage *message;
        DBusMessage *reply;
        dbus_bool_t  ret;
        char        *cookie;

        _ck_return_val_if_fail (connector != NULL, FALSE);
        _ck_return_val_if_fail ((error) == NULL || !dbus_error_is_set ((error)), FALSE);

        reply = NULL;
        message = NULL;
        ret = FALSE;

        dbus_error_init (&local_error);
        connector->connection = dbus_bus_get_private (DBUS_BUS_SYSTEM, &local_error);
        if (connector->connection == NULL) {
                if (dbus_error_is_set (&local_error)) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unable to open session: %s",
                                        local_error.message);
                        dbus_error_free (&local_error);
                }

                goto out;
        }

        dbus_connection_set_exit_on_disconnect (connector->connection, FALSE);

        message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit",
                                                "/org/freedesktop/ConsoleKit/Manager",
                                                "org.freedesktop.ConsoleKit.Manager",
                                                "OpenSession");
        if (message == NULL) {
                goto out;
        }

        dbus_error_init (&local_error);
        reply = dbus_connection_send_with_reply_and_block (connector->connection,
                                                           message,
                                                           -1,
                                                           &local_error);
        if (reply == NULL) {
                if (dbus_error_is_set (&local_error)) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unable to open session: %s",
                                        local_error.message);
                        dbus_error_free (&local_error);
                        goto out;
                }
        }

        dbus_error_init (&local_error);
        if (! dbus_message_get_args (reply,
                                     &local_error,
                                     DBUS_TYPE_STRING, &cookie,
                                     DBUS_TYPE_INVALID)) {
                if (dbus_error_is_set (&local_error)) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unable to open session: %s",
                                        local_error.message);
                        dbus_error_free (&local_error);
                        goto out;
                }
        }

        connector->cookie = strdup (cookie);
        if (connector->cookie == NULL) {
                goto out;
        }

        connector->session_created = TRUE;
        ret = TRUE;

out:
        if (reply != NULL) {
                dbus_message_unref (reply);
        }

        if (message != NULL) {
                dbus_message_unref (message);
        }

        return ret;
}
char* get_service_browser_path()
{
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    dbus_error_init(&err);
    DBusPendingCall* pending;
    dbus_int32_t interface = -1;
    dbus_int32_t protocol = -1;
    char *type = "_http._tcp";
    char *domain = "local";
    dbus_uint32_t flags = 0;
    char *service_browser_path;

   // initialiset the errors
    printf("Calling remote method: %s\n", "org.freedesktop.Avahi");

   // 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);
    }

    msg = dbus_message_new_method_call("org.freedesktop.Avahi",// target for the method call
                                        "/", 							// object to call on
                                        "org.freedesktop.Avahi.Server",    // interface to call on
                                        "ServiceBrowserNew");             // method nameResolveHostName
    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_INT32, &interface))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_INT32, &protocol))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &type))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &domain))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &flags))
    {
        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_OBJECT_PATH != dbus_message_iter_get_arg_type(&args)) 
        fprintf(stderr, "Argument is not boolean!\n"); 
    else
        dbus_message_iter_get_basic(&args, &service_browser_path);


    printf("Got Reply: %s\n", service_browser_path);
    dbus_message_unref(msg);  
    return service_browser_path;
}
void signal_ServiceBrowser_item(char *path){
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    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);
    }

    gchar* filter_itemnew = g_new(gchar, strlen("type='signal',interface='org.freedesktop.Avahi.ServiceBrowser',member='ItemNew', path=''") + strlen(path) + 2);
    sprintf(filter_itemnew, "type='signal',interface='org.freedesktop.Avahi.ServiceBrowser',member='ItemNew', path='%s'", path);
    gchar* filter_itemremove = g_new(gchar, strlen("type='signal',interface='org.freedesktop.Avahi.ServiceBrowser',member='ItemRemove', path=''") + strlen(path) + 2);
    sprintf(filter_itemremove, "type='signal',interface='org.freedesktop.Avahi.ServiceBrowser',member='ItemRemove', path='%s'", path);
    //printf("signal_filter:%s", signal_filter);
    // add a rule for which messages we want to see
    dbus_bus_add_match(conn, filter_itemnew, &err);
    dbus_bus_add_match(conn, filter_itemremove, &err);

    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");

    int interface;
    int protocol;
    char *name;
    char *stype;
    char *domain;
    unsigned int flags;
//int cnt = 0;
   // 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) { 
//g_message("cnt: %d", cnt++);
           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, "org.freedesktop.Avahi.ServiceBrowser", "ItemNew")) {
        // read the parameters
//g_message("is the message we need.%d", cnt++);
//g_message("Message Has No Parameters\n");

        if (!dbus_message_iter_init(msg, &args))
            g_message("dbus_message_iter_init fail\n");
        else
        { 
            if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
               g_message( "Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &interface);

            if (!dbus_message_iter_next(&args))
                g_message( "Message has too few arguments!\n"); 
            else if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
                dbus_message_iter_get_basic(&args, &protocol);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &name);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &stype);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &domain);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
                dbus_message_iter_get_basic(&args, &flags);
            printf("\n");
            printf("discovered:%d, %d, %s, %s, %s, %d.\n", interface, protocol, name, stype, domain, flags);
            resolve_service(interface, protocol, name, stype, domain);
        //printf("Got Signal with value %s\n", sigvalue);
        }
    }else if(dbus_message_is_signal(msg, "org.freedesktop.Avahi.ServiceBrowser", "ItemRemove")){
        if (!dbus_message_iter_init(msg, &args))
            g_message("dbus_message_iter_init fail\n");
        else
        { 
            if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
               g_message( "Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &interface);

            if (!dbus_message_iter_next(&args))
                g_message( "Message has too few arguments!\n"); 
            else if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
                dbus_message_iter_get_basic(&args, &protocol);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &name);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &stype);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
               dbus_message_iter_get_basic(&args, &domain);

            if (!dbus_message_iter_next(&args))
                g_message("Message has too few arguments!\n"); 
            else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) 
                g_message("Argument is not error!\n"); 
            else
                dbus_message_iter_get_basic(&args, &flags);
            printf("\n");
            printf("removed:%d, %d, %s, %s, %s, %d.\n", interface, protocol, name, stype, domain, flags);
            //resolve_service(interface, protocol, name, stype, domain);
        //printf("Got Signal with value %s\n", sigvalue);
        }
            }
    // free the message
    dbus_message_unref(msg);
    }
}
Exemple #6
0
static ReadStatus
read_data (DBusBabysitter *sitter,
           int             fd)
{
    int what;
    int got;
    DBusError error = DBUS_ERROR_INIT;
    ReadStatus r;

    r = read_ints (fd, &what, 1, &got, &error);

    switch (r)
    {
    case READ_STATUS_ERROR:
        _dbus_warn ("Failed to read data from fd %d: %s\n", fd, error.message);
        dbus_error_free (&error);
        return r;

    case READ_STATUS_EOF:
        return r;

    case READ_STATUS_OK:
        break;
    }

    if (got == 1)
    {
        switch (what)
        {
        case CHILD_EXITED:
        case CHILD_FORK_FAILED:
        case CHILD_EXEC_FAILED:
        {
            int arg;

            r = read_ints (fd, &arg, 1, &got, &error);

            switch (r)
            {
            case READ_STATUS_ERROR:
                _dbus_warn ("Failed to read arg from fd %d: %s\n", fd, error.message);
                dbus_error_free (&error);
                return r;
            case READ_STATUS_EOF:
                return r;
            case READ_STATUS_OK:
                break;
            }

            if (got == 1)
            {
                if (what == CHILD_EXITED)
                {
                    sitter->have_child_status = TRUE;
                    sitter->status = arg;
                    sitter->errnum = 0;
                    _dbus_verbose ("recorded child status exited = %d signaled = %d exitstatus = %d termsig = %d\n",
                                   WIFEXITED (sitter->status), WIFSIGNALED (sitter->status),
                                   WEXITSTATUS (sitter->status), WTERMSIG (sitter->status));
                }
                else if (what == CHILD_FORK_FAILED)
                {
                    sitter->have_fork_errnum = TRUE;
                    sitter->errnum = arg;
                    _dbus_verbose ("recorded fork errnum %d\n", sitter->errnum);
                }
                else if (what == CHILD_EXEC_FAILED)
                {
                    sitter->have_exec_errnum = TRUE;
                    sitter->errnum = arg;
                    _dbus_verbose ("recorded exec errnum %d\n", sitter->errnum);
                }
            }
        }
        break;
        case CHILD_PID:
        {
            pid_t pid = -1;

            r = read_pid (fd, &pid, &error);

            switch (r)
            {
            case READ_STATUS_ERROR:
                _dbus_warn ("Failed to read PID from fd %d: %s\n", fd, error.message);
                dbus_error_free (&error);
                return r;
            case READ_STATUS_EOF:
                return r;
            case READ_STATUS_OK:
                break;
            }

            sitter->grandchild_pid = pid;

            _dbus_verbose ("recorded grandchild pid %d\n", sitter->grandchild_pid);
        }
        break;
        default:
            _dbus_warn ("Unknown message received from babysitter process\n");
            break;
        }
    }

    return r;
}
static void 
force_unmount (LibHalContext *ctx, const char *udi)
{
	DBusError error;
	DBusMessage *msg = NULL;
	DBusMessage *reply = NULL;
	char **options = NULL;
	unsigned int num_options = 0;
	DBusConnection *dbus_connection;
	char *device_file;

	dbus_connection = libhal_ctx_get_dbus_connection (ctx);

	msg = dbus_message_new_method_call ("org.freedesktop.Hal", udi,
					    "org.freedesktop.Hal.Device.Volume",
					    "Unmount");
	if (msg == NULL) {
		HAL_ERROR (("Could not create dbus message for %s", udi));
		goto out;
	}


	options = calloc (1, sizeof (char *));
	if (options == NULL) {
		HAL_ERROR (("Could not allocate options array"));
		goto out;
	}

	options[0] = "lazy";
	num_options = 1;

	device_file = libhal_device_get_property_string (ctx, udi, "block.device", NULL);
	if (device_file != NULL) {
		HAL_INFO(("forcibly attempting to lazy unmount %s as media was removed", device_file));
		libhal_free_string (device_file);
	}

	if (!dbus_message_append_args (msg, 
				       DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &options, num_options,
				       DBUS_TYPE_INVALID)) {
		HAL_ERROR (("Could not append args to dbus message for %s", udi));
		goto out;
	}
	
	dbus_error_init (&error);
	if (!(reply = dbus_connection_send_with_reply_and_block (dbus_connection, msg, -1, &error))) {
		HAL_ERROR (("Unmount failed for %s: %s : %s\n", udi, error.name, error.message));
		dbus_error_free (&error);
		goto out;
	}

	if (dbus_error_is_set (&error)) {
		HAL_ERROR (("Unmount failed for %s\n%s : %s\n", udi, error.name, error.message));
		dbus_error_free (&error);
		goto out;
	}

	HAL_DEBUG (("Succesfully unmounted udi '%s'", udi));

out:
	if (options != NULL)
		free (options);
	if (msg != NULL)
		dbus_message_unref (msg);
	if (reply != NULL)
		dbus_message_unref (reply);
}
Exemple #8
0
/** 
 *  main:
 *  @argc:                Number of arguments given to program
 *  @argv:                Arguments given to program
 *
 *  Returns:              Return code
 *
 *  Main entry point 
 */
int
main (int argc, char *argv[])
{
	dbus_bool_t rc = 0;
	char *udi = NULL;
	char *key = NULL;
	char *str_value = NULL;
	dbus_int32_t int_value = 0;
	dbus_uint64_t uint64_value = 0;
	double double_value = 0.0f;
	dbus_bool_t bool_value = TRUE;
	dbus_bool_t remove = FALSE;
	dbus_bool_t is_version = FALSE;
	int type = PROP_INVALID;
	DBusError error;
	dbus_bool_t direct = FALSE;

	if (argc <= 1) {
		usage (argc, argv);
		return 1;
	}

	while (1) {
		int c;
		int option_index = 0;
		const char *opt;
		static struct option long_options[] = {
			{"udi", 1, NULL, 0},
			{"key", 1, NULL, 0},
			{"int", 1, NULL, 0},
			{"uint64", 1, NULL, 0},
			{"string", 1, NULL, 0},
			{"double", 1, NULL, 0},
			{"bool", 1, NULL, 0},
			{"strlist-pre", 1, NULL, 0},
			{"strlist-post", 1, NULL, 0},
			{"strlist-rem", 1, NULL, 0},
			{"direct", 0, NULL, 0},
			{"remove", 0, NULL, 0},
			{"version", 0, NULL, 0},
			{"help", 0, NULL, 0},
			{NULL, 0, NULL, 0}
		};
		
		c = getopt_long (argc, argv, "",
				 long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
		case 0:
			opt = long_options[option_index].name;

			if (strcmp (opt, "help") == 0) {
				usage (argc, argv);
				return 0;
			} else if (strcmp (opt, "key") == 0) {
				key = strdup (optarg);
			} else if (strcmp (opt, "string") == 0) {
				str_value = strdup (optarg);
				type = PROP_STRING;
			} else if (strcmp (opt, "int") == 0) {
				int_value = strtol (optarg, NULL, 0);
				type = PROP_INT;
			} else if (strcmp (opt, "uint64") == 0) {
				uint64_value = strtoull (optarg, NULL, 0);
				type = PROP_UINT64;
			} else if (strcmp (opt, "double") == 0) {
				double_value = (double) atof (optarg);
				type = PROP_DOUBLE;
			} else if (strcmp (opt, "bool") == 0) {
				if (strcmp (optarg, "true") == 0)
					bool_value = TRUE;
				else if (strcmp (optarg, "false") == 0)
					bool_value = FALSE;
				else {
					usage (argc, argv);
					return 1;
				}
				type = PROP_BOOL;
			} else if (strcmp (opt, "strlist-pre") == 0) {
				str_value = strdup (optarg);
				type = PROP_STRLIST_PRE;
			} else if (strcmp (opt, "strlist-post") == 0) {
				str_value = strdup (optarg);
				type = PROP_STRLIST_POST;
			} else if (strcmp (opt, "strlist-rem") == 0) {
				str_value = strdup (optarg);
				type = PROP_STRLIST_REM;
			} else if (strcmp (opt, "remove") == 0) {
				remove = TRUE;
			} else if (strcmp (opt, "direct") == 0) {
				direct = TRUE;
			} else if (strcmp (opt, "udi") == 0) {
				udi = strdup (optarg);
			} else if (strcmp (opt, "version") == 0) {
				is_version = TRUE;
			}
			break;

		default:
			usage (argc, argv);
			return 1;
			break;
		}
	}

	if (is_version) {
		printf ("hal-set-property " PACKAGE_VERSION "\n");
		return 0;
	}

	/* must have at least one, but not neither or both */
	if ((remove && type != PROP_INVALID) || ((!remove) && type == PROP_INVALID)) {
		usage (argc, argv);
		return 1;
	}
	
	fprintf (stderr, "\n");
	
	dbus_error_init (&error);
	if (direct) {
		if ((hal_ctx = libhal_ctx_init_direct (&error)) == NULL) {
			fprintf (stderr, "error: libhal_ctx_init_direct\n");
			LIBHAL_FREE_DBUS_ERROR (&error);
			return 1;
		}
	} else {
		if ((hal_ctx = libhal_ctx_new ()) == NULL) {
			fprintf (stderr, "error: libhal_ctx_new\n");
			return 1;
		}
		if (!libhal_ctx_set_dbus_connection (hal_ctx, dbus_bus_get (DBUS_BUS_SYSTEM, &error))) {
			fprintf (stderr, "error: libhal_ctx_set_dbus_connection: %s: %s\n", error.name, error.message);
			LIBHAL_FREE_DBUS_ERROR (&error);
			return 1;
		}
		if (!libhal_ctx_init (hal_ctx, &error)) {
			if (dbus_error_is_set(&error)) {
				fprintf (stderr, "error: libhal_ctx_init: %s: %s\n", error.name, error.message);
				dbus_error_free (&error);
			}
			fprintf (stderr, "Could not initialise connection to hald.\n"
					"Normally this means the HAL daemon (hald) is not running or not ready.\n");
			return 1;
		}
	}

	if (remove) {
		rc = libhal_device_remove_property (hal_ctx, udi, key, &error);
		if (!rc) {
			fprintf (stderr, "error: libhal_device_remove_property: %s: %s\n", error.name, error.message);
			LIBHAL_FREE_DBUS_ERROR (&error);
			return 1;
		}
	} else {
		switch (type) {
		case PROP_STRING:
			rc = libhal_device_set_property_string (hal_ctx, udi, key, str_value, &error);
			break;
		case PROP_INT:
			rc = libhal_device_set_property_int (hal_ctx, udi, key, int_value, &error);
			break;
		case PROP_UINT64:
			rc = libhal_device_set_property_uint64 (hal_ctx, udi, key, uint64_value, &error);
			break;
		case PROP_DOUBLE:
			rc = libhal_device_set_property_double (hal_ctx, udi, key, double_value, &error);
			break;
		case PROP_BOOL:
			rc = libhal_device_set_property_bool (hal_ctx, udi, key, bool_value, &error);
			break;
		case PROP_STRLIST_PRE:
			rc = libhal_device_property_strlist_prepend (hal_ctx, udi, key, str_value, &error);
			break;
		case PROP_STRLIST_POST:
			rc = libhal_device_property_strlist_append (hal_ctx, udi, key, str_value, &error);
			break;
		case PROP_STRLIST_REM:
			rc = libhal_device_property_strlist_remove (hal_ctx, udi, key, str_value, &error);
			break;
		}
		if (!rc) {
			fprintf (stderr, "error: libhal_device_set_property: %s: %s\n", error.name, error.message);
			dbus_error_free (&error);
			return 1;
		}
	}
	    
	return rc ? 0 : 1;
}
Exemple #9
0
static char *
session_ck_open_session (DBusConnection *connection,
			 const char     *username,
			 int            display)
{
    DBusError       error;
    DBusMessage     *message;
    DBusMessage     *reply;
    DBusMessageIter iter;
    DBusMessageIter iter_array;
    dbus_bool_t     res;
    char            *ret;
    char            *cookie;
    dbus_bool_t     is_local = FALSE;
    dbus_bool_t     active = TRUE;
    int             uid;
    char            display_str[256];
    const char      *x11_display = display_str;
    const char      *session_type = "rdp";

    reply = NULL;
    message = NULL;
    ret = NULL;

    g_sprintf(display_str, ":%d", display);

    if (g_getuser_info(username, 0, &uid, 0, 0, 0))
	goto out;

    message =
	dbus_message_new_method_call ("org.freedesktop.ConsoleKit",
				      "/org/freedesktop/ConsoleKit/Manager",
				      "org.freedesktop.ConsoleKit.Manager",
				      "OpenSessionWithParameters");
    if (message == NULL) {
	goto out;
    }

    dbus_message_iter_init_append (message, &iter);
    if (! dbus_message_iter_open_container (&iter,
					    DBUS_TYPE_ARRAY,
					    "(sv)",
					    &iter_array)) {
	goto out;
    }

    if (!add_param_basic (&iter_array,
			  "unix-user",
			  DBUS_TYPE_INT32,
			  &uid) ||
	!add_param_basic (&iter_array,
			  "x11-display",
			  DBUS_TYPE_STRING,
			  &x11_display) ||
	!add_param_basic (&iter_array,
			  "is-local",
			  DBUS_TYPE_BOOLEAN,
			  &is_local) ||
	!add_param_basic (&iter_array,
			  "active",
			  DBUS_TYPE_BOOLEAN,
			  &active) ||
	!add_param_basic (&iter_array,
			  "session-type",
			  DBUS_TYPE_STRING,
			  &session_type)) {
	log_message(&(g_cfg->log), LOG_LEVEL_ALWAYS,
		    "Error adding ck session parameter");
	goto out;
    }

    if (! dbus_message_iter_close_container (&iter, &iter_array)) {
	goto out;
    }

    dbus_error_init (&error);
    reply = dbus_connection_send_with_reply_and_block (connection,
						       message,
						       -1,
						       &error);
    if (reply == NULL) {
	if (dbus_error_is_set (&error)) {
	    log_message(&(g_cfg->log), LOG_LEVEL_ALWAYS,
			"Unable to open session: %s",
			error.message);
	    dbus_error_free (&error);
	    goto out;
	}
    }

    dbus_error_init (&error);
    if (! dbus_message_get_args (reply,
				 &error,
				 DBUS_TYPE_STRING, &cookie,
				 DBUS_TYPE_INVALID)) {
	if (dbus_error_is_set (&error)) {
	    log_message(&(g_cfg->log), LOG_LEVEL_ALWAYS,
			"Unable to open session: %s",
			error.message);
	    dbus_error_free (&error);
	    goto out;
	}
    }

    ret = g_strdup (cookie);

out:
    if (reply != NULL) {
	dbus_message_unref (reply);
    }

    if (message != NULL) {
	dbus_message_unref (message);
    }

    return ret;
}
/**
 * wpa_supplicant_dbus_ctrl_iface_init - Initialize dbus control interface
 * @global: Pointer to global data from wpa_supplicant_init()
 * Returns: Pointer to dbus_ctrl_iface date or %NULL on failure
 *
 * Initialize the dbus control interface and start receiving commands from
 * external programs over the bus.
 */
struct ctrl_iface_dbus_priv *
wpa_supplicant_dbus_ctrl_iface_init(struct wpa_global *global)
{
	struct ctrl_iface_dbus_priv *iface;
	DBusError error;
	int ret = -1;
	DBusObjectPathVTable wpas_vtable = {
		NULL, &wpas_message_handler, NULL, NULL, NULL, NULL
	};

	iface = wpa_zalloc(sizeof(struct ctrl_iface_dbus_priv));
	if (iface == NULL)
		return NULL;

	iface->global = global;

	/* Get a reference to the system bus */
	dbus_error_init(&error);
	iface->con = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	dbus_error_free(&error);
	if (!iface->con) {
		perror("dbus_bus_get[ctrl_iface_dbus]");
		wpa_printf(MSG_ERROR, "Could not acquire the system bus.");
		goto fail;
	}

	/* Tell dbus about our mainloop integration functions */
	if (integrate_with_eloop(iface->con, iface))
		goto fail;

	/* Register the message handler for the global dbus interface */
	if (!dbus_connection_register_object_path(iface->con,
						  WPAS_DBUS_PATH, &wpas_vtable,
						  iface)) {
		perror("dbus_connection_register_object_path[dbus]");
		wpa_printf(MSG_ERROR, "Could not set up DBus message "
			   "handler.");
		goto fail;
	}

	/* Register our service with the message bus */
	dbus_error_init(&error);
	switch (dbus_bus_request_name(iface->con, WPAS_DBUS_SERVICE,
				      0, &error)) {
	case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER:
		ret = 0;
		break;
	case DBUS_REQUEST_NAME_REPLY_EXISTS:
	case DBUS_REQUEST_NAME_REPLY_IN_QUEUE:
	case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER:
		perror("dbus_bus_request_name[dbus]");
		wpa_printf(MSG_ERROR, "Could not request DBus service name: "
			   "already registered.");
		break;
	default:
		perror("dbus_bus_request_name[dbus]");
		wpa_printf(MSG_ERROR, "Could not request DBus service name: "
			   "%s %s.", error.name, error.message);
		break;
	}
	dbus_error_free(&error);

	if (ret != 0)
		goto fail;

	wpa_printf(MSG_DEBUG, "Providing DBus service '" WPAS_DBUS_SERVICE
		   "'.");

	/*
	 * Dispatch initial DBus messages that may have come in since the bus
	 * name was claimed above. Happens when clients are quick to notice the
	 * wpa_supplicant service.
	 *
	 * FIXME: is there a better solution to this problem?
	 */
	eloop_register_timeout(0, 50, dispatch_initial_dbus_messages,
	                       iface->con, NULL);

	return iface;

fail:
	wpa_supplicant_dbus_ctrl_iface_deinit(iface);
	return NULL;
}
Exemple #11
0
int verify_polkit(
                DBusConnection *c,
                DBusMessage *request,
                const char *action,
                bool interactive,
                bool *_challenge,
                DBusError *error) {


#ifdef ENABLE_POLKIT
        DBusMessage *m = NULL, *reply = NULL;
        const char *unix_process = "unix-process", *pid = "pid", *starttime = "start-time", *cancel_id = "";
        uint32_t flags = interactive ? 1 : 0;
        pid_t pid_raw;
        uint32_t pid_u32;
        unsigned long long starttime_raw;
        uint64_t starttime_u64;
        DBusMessageIter iter_msg, iter_struct, iter_array, iter_dict, iter_variant;
        int r;
        dbus_bool_t authorized = FALSE, challenge = FALSE;
#endif
        const char *sender;
        unsigned long ul;

        assert(c);
        assert(request);

        sender = dbus_message_get_sender(request);
        if (!sender)
                return -EINVAL;

        ul = dbus_bus_get_unix_user(c, sender, error);
        if (ul == (unsigned long) -1)
                return -EINVAL;

        /* Shortcut things for root, to avoid the PK roundtrip and dependency */
        if (ul == 0)
                return 1;

#ifdef ENABLE_POLKIT

        pid_raw = bus_get_unix_process_id(c, sender, error);
        if (pid_raw == 0)
                return -EINVAL;

        r = get_starttime_of_pid(pid_raw, &starttime_raw);
        if (r < 0)
                return r;

        m = dbus_message_new_method_call(
                        "org.freedesktop.PolicyKit1",
                        "/org/freedesktop/PolicyKit1/Authority",
                        "org.freedesktop.PolicyKit1.Authority",
                        "CheckAuthorization");
        if (!m)
                return -ENOMEM;

        dbus_message_iter_init_append(m, &iter_msg);

        pid_u32 = (uint32_t) pid_raw;
        starttime_u64 = (uint64_t) starttime_raw;

        if (!dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_STRUCT, NULL, &iter_struct) ||
            !dbus_message_iter_append_basic(&iter_struct, DBUS_TYPE_STRING, &unix_process) ||
            !dbus_message_iter_open_container(&iter_struct, DBUS_TYPE_ARRAY, "{sv}", &iter_array) ||
            !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
            !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &pid) ||
            !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "u", &iter_variant) ||
            !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT32, &pid_u32) ||
            !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
            !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
            !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
            !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &starttime) ||
            !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "t", &iter_variant) ||
            !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT64, &starttime_u64) ||
            !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
            !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
            !dbus_message_iter_close_container(&iter_struct, &iter_array) ||
            !dbus_message_iter_close_container(&iter_msg, &iter_struct) ||
            !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &action) ||
            !dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_ARRAY, "{ss}", &iter_array) ||
            !dbus_message_iter_close_container(&iter_msg, &iter_array) ||
            !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_UINT32, &flags) ||
            !dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &cancel_id)) {
                r = -ENOMEM;
                goto finish;
        }

        reply = dbus_connection_send_with_reply_and_block(c, m, -1, error);
        if (!reply) {

                /* Treat no PK available as access denied */
                if (dbus_error_has_name(error, DBUS_ERROR_SERVICE_UNKNOWN)) {
                        r = -EACCES;
                        dbus_error_free(error);
                        goto finish;
                }

                r = -EIO;
                goto finish;
        }

        if (!dbus_message_iter_init(reply, &iter_msg) ||
            dbus_message_iter_get_arg_type(&iter_msg) != DBUS_TYPE_STRUCT) {
                r = -EIO;
                goto finish;
        }

        dbus_message_iter_recurse(&iter_msg, &iter_struct);

        if (dbus_message_iter_get_arg_type(&iter_struct) != DBUS_TYPE_BOOLEAN) {
                r = -EIO;
                goto finish;
        }

        dbus_message_iter_get_basic(&iter_struct, &authorized);

        if (!dbus_message_iter_next(&iter_struct) ||
            dbus_message_iter_get_arg_type(&iter_struct) != DBUS_TYPE_BOOLEAN) {
                r = -EIO;
                goto finish;
        }

        dbus_message_iter_get_basic(&iter_struct, &challenge);

        if (authorized)
                r = 1;
        else if (_challenge) {
                *_challenge = !!challenge;
                r = 0;
        } else
                r = -EPERM;

finish:
        if (m)
                dbus_message_unref(m);

        if (reply)
                dbus_message_unref(reply);

        return r;
#else
        return -EPERM;
#endif
}
Exemple #12
0
int list_controllers_main (void *parent, char ***output)
{
	DBusMessage *message = NULL, *reply = NULL;
	char **         output_local = NULL;
	DBusError       error;
	DBusMessageIter iter;
	int		ret = -1;
	DBusMessageIter output_local_iter;
	size_t          output_local_size;

	*output = NULL;
	message = dbus_message_new_method_call(dbus_bus_get_unique_name(server_conn),
			"/org/linuxcontainers/cgmanager",
			"org.linuxcontainers.cgmanager0_0", "ListControllers");

	dbus_error_init (&error);

	reply = dbus_connection_send_with_reply_and_block (server_conn, message, -1, &error);
	if (! reply) {
		dbus_message_unref (message);

		nih_error("%s: error completing dbus request: %s %s", __func__,
			error.name, error.message);

		dbus_error_free (&error);
		return -1;
	}
	dbus_message_unref (message);

	dbus_message_iter_init (reply, &iter);

	if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_ARRAY)
		goto out;

	dbus_message_iter_recurse (&iter, &output_local_iter);

	output_local_size = 0;
	output_local = NULL;

	output_local = NIH_MUST( nih_alloc (parent, sizeof (char *)) );

	output_local[output_local_size] = NULL;

	while (dbus_message_iter_get_arg_type (&output_local_iter) != DBUS_TYPE_INVALID) {
		const char *output_local_element_dbus;
		char **     output_local_tmp;
		char *      output_local_element;

		if (dbus_message_iter_get_arg_type (&output_local_iter) != DBUS_TYPE_STRING)
			goto out;

		dbus_message_iter_get_basic (&output_local_iter, &output_local_element_dbus);

		output_local_element = NIH_MUST( nih_strdup (output_local, output_local_element_dbus) );

		dbus_message_iter_next (&output_local_iter);

		output_local_tmp = NIH_MUST( nih_realloc (output_local, parent, sizeof (char *) * (output_local_size + 2)) );

		output_local = output_local_tmp;
		output_local[output_local_size] = output_local_element;
		output_local[output_local_size + 1] = NULL;

		output_local_size++;
	}

	dbus_message_iter_next (&iter);

	if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_INVALID)
		goto out;

	*output = output_local;

	ret = 0;

out:
	if (reply)
		dbus_message_unref (reply);
	if (ret)
		nih_free (output_local);
	return ret;
}
Exemple #13
0
static void get_properties(DBusConnection *conn)
{
    DBusError err;
    DBusMessage *msg;
    DBusMessageIter iter, dict, dict_key, dict_value;
    dbus_bool_t bValue;
    dbus_uint32_t iValue;

    char key[255];
    char value[255];
    char *ckey;
    char *cValue;
    // int i = 0;

    dbus_error_init(&err);

    msg = dbus_message_new_method_call(DBUS_NAME,DBUS_PATH, DBUS_INTERFACE_APAPTER,
                                       "GetProperties");
    if (msg == NULL)
    {
        printf("%s %d msg is null\n", __func__, __LINE__);
        exit(1);
    }

    msg = excute_method_a(conn, msg);

    dbus_message_iter_init(msg, &iter);
    dbus_message_iter_recurse(&iter, &dict);

    do
    {
        memset(key, 0, 255);
        memset(value, 0, 255);

        dbus_message_iter_recurse(&dict, &dict_key);
        dbus_message_iter_get_basic(&dict_key, &ckey);

        strcpy(key, ckey);

        // printf("%s %d key:%s\n", __func__, __LINE__, key);

        if (!strcmp(key, "Name"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &cValue);
            strcpy(value, cValue);
            printf("%s:  %s\n", key, value);
        }
        else if(!strcmp(key, "Address"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &cValue);
            strcpy(value, cValue);
            printf("%s:  %s\n", key, value);
        }
        //Discoverable
        else if(!strcmp(key, "Discoverable"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &bValue);
            printf("%s:  %d\n", key, bValue);
        }
        //DiscoverableTimeout
        else if(!strcmp(key, "DiscoverableTimeout"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &iValue);
            printf("%s:  %d\n", key, iValue);
        }
        //Discovering
        else if(!strcmp(key, "Discovering"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &bValue);
            printf("%s:  %d\n", key, bValue);
        }
        //Pairable
        else if(!strcmp(key, "Pairable"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &bValue);
            printf("%s:  %d\n", key, bValue);
        }
        //PairableTimeout
        else if(!strcmp(key, "PairableTimeout"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &iValue);
            printf("%s:  %d\n", key, iValue);
        }
        //Powerd
        else if(!strcmp(key, "Powered"))
        {
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_get_basic(&dict_value, &bValue);
            printf("%s:  %d\n", key, bValue);
        }
        //Devices
        else if(!strcmp(key, "Devices"))
        {
            DBusMessageIter device_array;
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_recurse(&dict_value, &device_array);

            if (dbus_message_iter_get_arg_type(&device_array) != DBUS_TYPE_OBJECT_PATH)
            {
                printf("%s:  0\n", key);
                continue;
            }

            // i = 0;
            do
            {
                dbus_message_iter_get_basic(&device_array, &cValue);
                strcpy(value, cValue);
                // printf("%s %d %s %d: %s\n", __func__, __LINE__, key, ++i, value);
            } while (dbus_message_iter_next(&device_array));

        }
        //UUIDs
        else if(!strcmp(key, "UUIDs"))
        {
            DBusMessageIter device_array;
            dbus_message_iter_next(&dict_key);
            dbus_message_iter_recurse(&dict_key, &dict_value);
            dbus_message_iter_recurse(&dict_value, &device_array);

            do
            {
                dbus_message_iter_get_basic(&device_array, &cValue);
            } while(dbus_message_iter_next(&device_array));
        }
        else
        {
            printf("%s: Not to supported \n",key);
        }

    } while (dbus_message_iter_next(&dict));

    dbus_error_free(&err);
}
Exemple #14
0
static void set_property(DBusConnection *conn, const char *name, struct ADAPTER_PROPERTIES *p)
{
    DBusError err;
    DBusMessage *msg;
    DBusMessageIter iter;
    char s[255];

    memset(&s, 0, 255);
    dbus_error_init(&err);

    msg = dbus_message_new_method_call(DBUS_NAME,DBUS_PATH, DBUS_INTERFACE_APAPTER,
                                       "SetProperty");
    if (msg == NULL)
    {
        printf("%s %d msg is null\n", __func__, __LINE__);
        exit(1);
    }

    /* append data */
    dbus_message_iter_init_append(msg, &iter);
    dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &name);

    // printf("%s %d\n", __func__, __LINE__);

    if (!strcmp(name, "Name"))
    {
        // printf("SynergyDBusAdapter::SetProperty('%s', %s)\n", name, p->Name);
        strcpy(s, p->Name);
        append_variant(&iter, DBUS_TYPE_STRING, &s);
    }
    else if (!strcmp(name, "Powered"))
    {
        // printf("SynergyDBusAdapter::SetProperty('%s', %d)\n", name, p->Powered);
        append_variant(&iter, DBUS_TYPE_BOOLEAN, &p->Powered);
    }
    else if (!strcmp(name, "DiscoverableTimeout"))
    {
        // printf("SynergyDBusAdapter::SetProperty('%s', %d)\n", name, p->DiscoverableTimeout);
        append_variant(&iter, DBUS_TYPE_UINT32, &p->DiscoverableTimeout);
    }
    else if (!strcmp(name, "Discoverable"))
    {
        // printf("SynergyDBusAdapter::SetProperty('%s', %d)\n", name, p->Discoverable);
        append_variant(&iter, DBUS_TYPE_BOOLEAN, &p->Discoverable);
    }
    else if (!strcmp(name, "PairableTimeout"))
    {
        // printf("SynergyDBusAdapter::SetProperty('%s', %d)\n", name, p->PairableTimeout);
        append_variant(&iter, DBUS_TYPE_UINT32, &p->PairableTimeout);
    }
    else if (!strcmp(name, "Pairable"))
    {
        // printf("SynergyDBusAdapter::SetProperty('%s', %d)\n", name, p->Pairable);
        append_variant(&iter, DBUS_TYPE_BOOLEAN, &p->Pairable);
    }
    else
    {
        printf("SynergyDBusAdapter::SetProperty('%s') is not supported)\n", name);
        dbus_connection_flush(conn);
        dbus_message_unref(msg);
        exit(1);
    }

    msg = excute_method_a(conn, msg);

    dbus_message_unref(msg);

    dbus_error_free(&err);
}
Exemple #15
0
pa_reserve_wrapper* pa_reserve_wrapper_get(pa_core *c, const char *device_name) {
    pa_reserve_wrapper *r;
    int k;
    char *t;
#ifdef HAVE_DBUS
    DBusError error;

    dbus_error_init(&error);
#endif

    pa_assert(c);
    pa_assert(device_name);

    t = pa_sprintf_malloc("[email protected]%s", device_name);

    if ((r = pa_shared_get(c, t))) {
        pa_xfree(t);

        pa_assert(PA_REFCNT_VALUE(r) >= 1);
        PA_REFCNT_INC(r);

        return r;
    }

    r = pa_xnew0(pa_reserve_wrapper, 1);
    PA_REFCNT_INIT(r);
    r->core = c;
    pa_hook_init(&r->hook, r);
    r->shared_name = t;

    pa_assert_se(pa_shared_set(c, r->shared_name, r) >= 0);

#ifdef HAVE_DBUS
    if (!(r->connection = pa_dbus_bus_get(c, DBUS_BUS_SESSION, &error)) || dbus_error_is_set(&error)) {
        pa_log_debug("Unable to contact D-Bus session bus: %s: %s", error.name, error.message);

        /* We don't treat this as error here because we want allow PA
         * to run even when no session bus is available. */
        return r;
    }

    if ((k = rd_acquire(
                 &r->device,
                 pa_dbus_connection_get(r->connection),
                 device_name,
                 _("PulseAudio Sound Server"),
                 0,
                 request_cb,
                 NULL)) < 0) {

        if (k == -EBUSY) {
            pa_log_debug("Device '%s' already locked.", device_name);
            goto fail;
        } else {
            pa_log_debug("Failed to acquire reservation lock on device '%s': %s", device_name, pa_cstrerror(-k));
            return r;
        }
    }

    pa_log_debug("Successfully acquired reservation lock on device '%s'", device_name);

    rd_set_userdata(r->device, r);

    return r;
fail:
    dbus_error_free(&error);

    reserve_wrapper_free(r);

    return NULL;
#else
    return r;
#endif
}
Exemple #16
0
Fichier : dbus.c Projet : aosm/cups
int					/* O - Exit status */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
  ipp_t			*msg;		/* Event message from scheduler */
  ipp_state_t		state;		/* IPP event state */
  struct sigaction	action;		/* POSIX sigaction data */
  DBusConnection	*con = NULL;	/* Connection to DBUS server */
  DBusError		error;		/* Error, if any */
  DBusMessage		*message;	/* Message to send */
  DBusMessageIter	iter;		/* Iterator for message data */
  int			lock_fd = -1;	/* Lock file descriptor */


 /*
  * Don't buffer stderr...
  */

  setbuf(stderr, NULL);

 /*
  * Ignore SIGPIPE signals...
  */

  memset(&action, 0, sizeof(action));
  action.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &action, NULL);

 /*
  * Validate command-line options...
  */

  if (argc != 3)
  {
    fputs("Usage: dbus dbus:/// notify-user-data\n", stderr);
    return (1);
  }

  if (strncmp(argv[1], "dbus:", 5))
  {
    fprintf(stderr, "ERROR: Bad URI \"%s\"!\n", argv[1]);
    return (1);
  }

 /*
  * Loop forever until we run out of events...
  */

  for (;;)
  {
    ipp_attribute_t	*attr;		/* Current attribute */
    const char		*event;		/* Event name */
    const char		*signame = NULL;/* DBUS signal name */
    char		*printer_reasons = NULL;
					/* Printer reasons string */
    char		*job_reasons = NULL;
					/* Job reasons string */
    const char		*nul = "";	/* Empty string value */
    int			no = 0;		/* Boolean "no" value */
    int			params = PARAMS_NONE;
					/* What parameters to include? */


   /*
    * Get the next event...
    */

    msg = ippNew();
    while ((state = ippReadFile(0, msg)) != IPP_DATA)
    {
      if (state <= IPP_IDLE)
        break;
    }

    fprintf(stderr, "DEBUG: state=%d\n", state);

    if (state == IPP_ERROR)
      fputs("DEBUG: ippReadFile() returned IPP_ERROR!\n", stderr);

    if (state <= IPP_IDLE)
    {
     /*
      * Out of messages, free memory and then exit...
      */

      ippDelete(msg);
      break;
    }

   /*
    * 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(DBUS_BUS_SYSTEM, &error);
      if (!con)
	dbus_error_free(&error);
      else
	fputs("DEBUG: Connected to D-BUS\n", stderr);
    }

    if (!con)
      continue;

    if (lock_fd == -1 &&
        acquire_lock(&lock_fd, lock_filename, sizeof(lock_filename)))
      continue;

    attr = ippFindAttribute(msg, "notify-subscribed-event",
			    IPP_TAG_KEYWORD);
    if (!attr)
      continue;

    event = ippGetString(attr, 0, NULL);
    if (!strncmp(event, "server-", 7))
    {
      const char *word2 = event + 7;	/* Second word */

      if (!strcmp(word2, "restarted"))
	signame = "ServerRestarted";
      else if (!strcmp(word2, "started"))
	signame = "ServerStarted";
      else if (!strcmp(word2, "stopped"))
	signame = "ServerStopped";
      else if (!strcmp(word2, "audit"))
	signame = "ServerAudit";
      else
	continue;
    }
    else if (!strncmp(event, "printer-", 8))
    {
      const char *word2 = event + 8;	/* Second word */

      params = PARAMS_PRINTER;
      if (!strcmp(word2, "restarted"))
	signame = "PrinterRestarted";
      else if (!strcmp(word2, "shutdown"))
	signame = "PrinterShutdown";
      else if (!strcmp(word2, "stopped"))
	signame = "PrinterStopped";
      else if (!strcmp(word2, "state-changed"))
	signame = "PrinterStateChanged";
      else if (!strcmp(word2, "finishings-changed"))
	signame = "PrinterFinishingsChanged";
      else if (!strcmp(word2, "media-changed"))
	signame = "PrinterMediaChanged";
      else if (!strcmp(word2, "added"))
	signame = "PrinterAdded";
      else if (!strcmp(word2, "deleted"))
	signame = "PrinterDeleted";
      else if (!strcmp(word2, "modified"))
	signame = "PrinterModified";
      else
	continue;
    }
    else if (!strncmp(event, "job-", 4))
    {
      const char *word2 = event + 4;	/* Second word */

      params = PARAMS_JOB;
      if (!strcmp(word2, "state-changed"))
	signame = "JobState";
      else if (!strcmp(word2, "created"))
	signame = "JobCreated";
      else if (!strcmp(word2, "completed"))
	signame = "JobCompleted";
      else if (!strcmp(word2, "stopped"))
	signame = "JobStopped";
      else if (!strcmp(word2, "config-changed"))
	signame = "JobConfigChanged";
      else if (!strcmp(word2, "progress"))
	signame = "JobProgress";
      else
	continue;
    }
    else
      continue;

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

    fprintf(stderr, "DEBUG: %s\n", signame);
    message = dbus_message_new_signal("/org/cups/cupsd/Notifier",
				      "org.cups.cupsd.Notifier",
				      signame);

    dbus_message_append_iter_init(message, &iter);
    attr = ippFindAttribute(msg, "notify-text", IPP_TAG_TEXT);
    if (attr)
    {
      const char *val = ippGetString(attr, 0, NULL);
      if (!dbus_message_iter_append_string(&iter, &val))
        goto bail;
    }
    else
      goto bail;

    if (params >= PARAMS_PRINTER)
    {
      char	*p;			/* Pointer into printer_reasons */
      size_t	reasons_length;		/* Required size of printer_reasons */
      int	i;			/* Looping var */
      int	have_printer_params = 1;/* Do we have printer URI? */

      /* STRING printer-uri or "" */
      attr = ippFindAttribute(msg, "notify-printer-uri", IPP_TAG_URI);
      if (attr)
      {
        const char *val = ippGetString(attr, 0, NULL);
        if (!dbus_message_iter_append_string(&iter, &val))
	  goto bail;
      }
      else
      {
	have_printer_params = 0;
	dbus_message_iter_append_string(&iter, &nul);
      }

      /* STRING printer-name */
      if (have_printer_params)
      {
	attr = ippFindAttribute(msg, "printer-name", IPP_TAG_NAME);
        if (attr)
        {
          const char *val = ippGetString(attr, 0, NULL);
          if (!dbus_message_iter_append_string(&iter, &val))
            goto bail;
        }
        else
          goto bail;
      }
      else
	dbus_message_iter_append_string(&iter, &nul);

      /* UINT32 printer-state */
      if (have_printer_params)
      {
	attr = ippFindAttribute(msg, "printer-state", IPP_TAG_ENUM);
	if (attr)
	{
	  dbus_uint32_t val = (dbus_uint32_t)ippGetInteger(attr, 0);
	  dbus_message_iter_append_uint32(&iter, &val);
	}
	else
	  goto bail;
      }
      else
	dbus_message_iter_append_uint32(&iter, &no);

      /* STRING printer-state-reasons */
      if (have_printer_params)
      {
	attr = ippFindAttribute(msg, "printer-state-reasons",
				IPP_TAG_KEYWORD);
	if (attr)
	{
	  int num_values = ippGetCount(attr);
	  for (reasons_length = 0, i = 0; i < num_values; i++)
	    /* All need commas except the last, which needs a nul byte. */
	    reasons_length += 1 + strlen(ippGetString(attr, i, NULL));
	  printer_reasons = malloc(reasons_length);
	  if (!printer_reasons)
	    goto bail;
	  p = printer_reasons;
	  for (i = 0; i < num_values; i++)
	  {
	    if (i)
	      *p++ = ',';

	    strlcpy(p, ippGetString(attr, i, NULL), reasons_length - (size_t)(p - printer_reasons));
	    p += strlen(p);
	  }
	  if (!dbus_message_iter_append_string(&iter, &printer_reasons))
	    goto bail;
	}
	else
	  goto bail;
      }
      else
	dbus_message_iter_append_string(&iter, &nul);

      /* BOOL printer-is-accepting-jobs */
      if (have_printer_params)
      {
	attr = ippFindAttribute(msg, "printer-is-accepting-jobs",
				IPP_TAG_BOOLEAN);
	if (attr)
	{
	  dbus_bool_t val = (dbus_bool_t)ippGetBoolean(attr, 0);
	  dbus_message_iter_append_boolean(&iter, &val);
	}
	else
	  goto bail;
      }
      else
	dbus_message_iter_append_boolean(&iter, &no);
    }

    if (params >= PARAMS_JOB)
    {
      char	*p;			/* Pointer into job_reasons */
      size_t	reasons_length;		/* Required size of job_reasons */
      int	i;			/* Looping var */

      /* UINT32 job-id */
      attr = ippFindAttribute(msg, "notify-job-id", IPP_TAG_INTEGER);
      if (attr)
      {
        dbus_uint32_t val = (dbus_uint32_t)ippGetInteger(attr, 0);
        dbus_message_iter_append_uint32(&iter, &val);
      }
      else
	goto bail;

      /* UINT32 job-state */
      attr = ippFindAttribute(msg, "job-state", IPP_TAG_ENUM);
      if (attr)
      {
        dbus_uint32_t val = (dbus_uint32_t)ippGetInteger(attr, 0);
        dbus_message_iter_append_uint32(&iter, &val);
      }
      else
	goto bail;

      /* STRING job-state-reasons */
      attr = ippFindAttribute(msg, "job-state-reasons", IPP_TAG_KEYWORD);
      if (attr)
      {
	int num_values = ippGetCount(attr);
	for (reasons_length = 0, i = 0; i < num_values; i++)
	  /* All need commas except the last, which needs a nul byte. */
	  reasons_length += 1 + strlen(ippGetString(attr, i, NULL));
	job_reasons = malloc(reasons_length);
	if (!job_reasons)
	  goto bail;
	p = job_reasons;
	for (i = 0; i < num_values; i++)
	{
	  if (i)
	    *p++ = ',';

	  strlcpy(p, ippGetString(attr, i, NULL), reasons_length - (size_t)(p - job_reasons));
	  p += strlen(p);
	}
	if (!dbus_message_iter_append_string(&iter, &job_reasons))
	  goto bail;
      }
      else
	goto bail;

      /* STRING job-name or "" */
      attr = ippFindAttribute(msg, "job-name", IPP_TAG_NAME);
      if (attr)
      {
        const char *val = ippGetString(attr, 0, NULL);
        if (!dbus_message_iter_append_string(&iter, &val))
          goto bail;
      }
      else
	dbus_message_iter_append_string(&iter, &nul);

      /* UINT32 job-impressions-completed */
      attr = ippFindAttribute(msg, "job-impressions-completed",
			      IPP_TAG_INTEGER);
      if (attr)
      {
        dbus_uint32_t val = (dbus_uint32_t)ippGetInteger(attr, 0);
        dbus_message_iter_append_uint32(&iter, &val);
      }
      else
	goto bail;
    }

    dbus_connection_send(con, message, NULL);
    dbus_connection_flush(con);

   /*
    * Cleanup...
    */

    bail:

    dbus_message_unref(message);

    if (printer_reasons)
      free(printer_reasons);

    if (job_reasons)
      free(job_reasons);

    ippDelete(msg);
  }

 /*
  * Remove lock file...
  */

  if (lock_fd >= 0)
  {
    close(lock_fd);
    release_lock();
  }

  return (0);
}
Exemple #17
0
pa_reserve_monitor_wrapper* pa_reserve_monitor_wrapper_get(pa_core *c, const char *device_name) {
    pa_reserve_monitor_wrapper *w;
    int k;
    char *t;
#ifdef HAVE_DBUS
    DBusError error;

    dbus_error_init(&error);
#endif

    pa_assert(c);
    pa_assert(device_name);

    t = pa_sprintf_malloc("[email protected]%s", device_name);

    if ((w = pa_shared_get(c, t))) {
        pa_xfree(t);

        pa_assert(PA_REFCNT_VALUE(w) >= 1);
        PA_REFCNT_INC(w);

        return w;
    }

    w = pa_xnew0(pa_reserve_monitor_wrapper, 1);
    PA_REFCNT_INIT(w);
    w->core = c;
    pa_hook_init(&w->hook, w);
    w->shared_name = t;

    pa_assert_se(pa_shared_set(c, w->shared_name, w) >= 0);

#ifdef HAVE_DBUS
    if (!(w->connection = pa_dbus_bus_get(c, DBUS_BUS_SESSION, &error)) || dbus_error_is_set(&error)) {
        pa_log_debug("Unable to contact D-Bus session bus: %s: %s", error.name, error.message);

        /* We don't treat this as error here because we want allow PA
         * to run even when no session bus is available. */
        return w;
    }

    if ((k = rm_watch(
                 &w->monitor,
                 pa_dbus_connection_get(w->connection),
                 device_name,
                 change_cb,
                 NULL)) < 0) {

        pa_log_debug("Failed to create watch on device '%s': %s", device_name, pa_cstrerror(-k));
        goto fail;
    }

    pa_log_debug("Successfully create reservation lock monitor for device '%s'", device_name);

    rm_set_userdata(w->monitor, w);
    return w;

fail:
    dbus_error_free(&error);

    reserve_monitor_wrapper_free(w);

    return NULL;
#else
    return w;
#endif
}
Exemple #18
0
static DBusHandlerResult
_libnm_glib_dbus_filter (DBusConnection *connection,
                         DBusMessage *message,
                         void *user_data)
{
	libnm_glib_ctx		*ctx = (libnm_glib_ctx *)user_data;
	gboolean		 handled = TRUE;
	DBusError	 	 error;

	g_return_val_if_fail (ctx != NULL, DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
	g_return_val_if_fail (connection != NULL, DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
	g_return_val_if_fail (message != NULL, DBUS_HANDLER_RESULT_NOT_YET_HANDLED);

	dbus_error_init (&error);
	if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, "Disconnected"))
	{
		/* Try to reactivate our connection to dbus on the next pass through the event loop */
		ctx->nm_state = LIBNM_NO_DBUS;
		dbus_connection_close (ctx->dbus_con);
		dbus_connection_unref (ctx->dbus_con);
		ctx->dbus_con = NULL;
		_libnm_glib_schedule_dbus_watcher (ctx);
	}
	else if (dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, "NameOwnerChanged"))
	{
		/* New signal for dbus 0.23... */
		char 	*service;
		char		*old_owner;
		char		*new_owner;

		if (    dbus_message_get_args (message, &error,
									DBUS_TYPE_STRING, &service,
									DBUS_TYPE_STRING, &old_owner,
									DBUS_TYPE_STRING, &new_owner,
									DBUS_TYPE_INVALID))
		{
			if (strcmp (service, NM_DBUS_SERVICE) == 0)
			{
				gboolean old_owner_good = (old_owner && (strlen (old_owner) > 0));
				gboolean new_owner_good = (new_owner && (strlen (new_owner) > 0));

				if (!old_owner_good && new_owner_good)	/* Equivalent to old ServiceCreated signal */
					_libnm_glib_get_nm_state (ctx);
				else if (old_owner_good && !new_owner_good)	/* Equivalent to old ServiceDeleted signal */
					ctx->nm_state = LIBNM_NO_NETWORKMANAGER;
			}
		}
	}
	else if (    dbus_message_is_signal (message, NM_DBUS_INTERFACE, "DeviceNowActive")
			|| dbus_message_is_signal (message, NM_DBUS_INTERFACE, "DeviceNoLongerActive")
			|| dbus_message_is_signal (message, NM_DBUS_INTERFACE, "DeviceActivating")
			|| dbus_message_is_signal (message, NM_DBUS_INTERFACE, "DevicesChanged"))
	{
		_libnm_glib_get_nm_state (ctx);
	}
	else if (dbus_message_is_signal (message, NM_DBUS_INTERFACE, "StateChanged"))
	{
		NMState	state = NM_STATE_UNKNOWN;

		dbus_message_get_args (message, &error, DBUS_TYPE_UINT32, &state, DBUS_TYPE_INVALID);
		_libnm_glib_update_state (ctx, state);
	}
	else
		handled = FALSE;

	if (dbus_error_is_set (&error))
		dbus_error_free (&error);

	return (handled ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
}
static void 
unmount_childs (LibHalContext *ctx, const char *udi)
{
	int num_volumes;
	char **volumes;
	DBusError error;

	/* need to force unmount all partitions */
	dbus_error_init (&error);
	if ((volumes = libhal_manager_find_device_string_match (ctx, "block.storage_device", udi, &num_volumes, &error)) != NULL) {
		int i;

		for (i = 0; i < num_volumes; i++) {
			char *vol_udi;

			vol_udi = volumes[i];
			LIBHAL_FREE_DBUS_ERROR (&error);

			if (libhal_device_get_property_bool (ctx, vol_udi, "block.is_volume", &error)) {
				dbus_bool_t is_crypto;

				/* unmount all cleartext devices associated with us */
				is_crypto = unmount_cleartext_devices (ctx, vol_udi);

				LIBHAL_FREE_DBUS_ERROR (&error);
				if (libhal_device_get_property_bool (ctx, vol_udi, "volume.is_mounted", &error)) {
					HAL_DEBUG (("Forcing unmount of child '%s'", vol_udi));
					force_unmount (ctx, vol_udi);
				}

				/* teardown crypto */
				if (is_crypto) {
					DBusMessage *msg = NULL;
					DBusMessage *reply = NULL;

					/* tear down mapping */
					HAL_DEBUG (("Teardown crypto for '%s'", vol_udi));

					msg = dbus_message_new_method_call ("org.freedesktop.Hal", vol_udi,
									    "org.freedesktop.Hal.Device.Volume.Crypto",
									    "Teardown");
					if (msg == NULL) {
						HAL_ERROR (("Could not create dbus message for %s", vol_udi));
						goto teardown_failed;
					}

					LIBHAL_FREE_DBUS_ERROR (&error);

					if (!(reply = dbus_connection_send_with_reply_and_block (
						      libhal_ctx_get_dbus_connection (ctx), msg, -1, &error)) || 
					    dbus_error_is_set (&error)) {
						HAL_DEBUG (("Teardown failed for %s: %s : %s\n", udi, error.name, error.message));
						dbus_error_free (&error);
					}

				teardown_failed:
					if (msg != NULL)
						dbus_message_unref (msg);
					if (reply != NULL)
						dbus_message_unref (reply);
				}

			}

		}
		libhal_free_string_array (volumes);
	}
	LIBHAL_FREE_DBUS_ERROR (&error);
}
Exemple #20
0
/** Entry point
 *
 *  @param  argc                Number of arguments given to program
 *  @param  argv                Arguments given to program
 *  @return                     Return code
 */
int
main (int argc, char *argv[])
{
	char *udi = NULL;
	char *key = NULL;
	int type;
	dbus_bool_t is_hex = FALSE;
	dbus_bool_t is_verbose = FALSE;
	dbus_bool_t is_version = FALSE;
	char *str;
	DBusError error;

	if (argc <= 1) {
		usage (argc, argv);
		return 1;
	}

	while (1) {
		int c;
		int option_index = 0;
		const char *opt;
		static struct option long_options[] = {
			{"udi", 1, NULL, 0},
			{"key", 1, NULL, 0},
			{"hex", 0, NULL, 0},
			{"verbose", 0, NULL, 0},
			{"version", 0, NULL, 0},
			{"help", 0, NULL, 0},
			{NULL, 0, NULL, 0}
		};

		c = getopt_long (argc, argv, "",
				 long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
		case 0:
			opt = long_options[option_index].name;

			if (strcmp (opt, "help") == 0) {
				usage (argc, argv);
				return 0;
			} else if (strcmp (opt, "hex") == 0) {
				is_hex = TRUE;
			} else if (strcmp (opt, "verbose") == 0) {
				is_verbose = TRUE;
			} else if (strcmp (opt, "version") == 0) {
				is_version = TRUE;
			} else if (strcmp (opt, "key") == 0) {
				key = strdup (optarg);
			} else if (strcmp (opt, "udi") == 0) {
				udi = strdup (optarg);
			}
			break;

		default:
			usage (argc, argv);
			return 1;
			break;
		}
	}

	if (is_version) {
		printf ("hal-get-property " PACKAGE_VERSION "\n");
		return 0;
	}

	if (udi == NULL || key == NULL) {
		usage (argc, argv);
		return 1;
	}

	dbus_error_init (&error);	
	if ((hal_ctx = libhal_ctx_new ()) == NULL) {
		fprintf (stderr, "error: libhal_ctx_new\n");
		return 1;
	}
	if (!libhal_ctx_set_dbus_connection (hal_ctx, dbus_bus_get (DBUS_BUS_SYSTEM, &error))) {
		fprintf (stderr, "error: libhal_ctx_set_dbus_connection: %s: %s\n", error.name, error.message);
		LIBHAL_FREE_DBUS_ERROR (&error);
		return 1;
	}
	if (!libhal_ctx_init (hal_ctx, &error)) {
		if (dbus_error_is_set(&error)) {
			fprintf (stderr, "error: libhal_ctx_init: %s: %s\n", error.name, error.message);
			LIBHAL_FREE_DBUS_ERROR (&error);
		}
		fprintf (stderr, "Could not initialise connection to hald.\n"
				 "Normally this means the HAL daemon (hald) is not running or not ready.\n");
		return 1;
	}

	type = libhal_device_get_property_type (hal_ctx, udi, key, &error);
	if (type == LIBHAL_PROPERTY_TYPE_INVALID) {
		fprintf (stderr, "error: libhal_device_get_property_type: %s: %s\n", error.name, error.message);
		LIBHAL_FREE_DBUS_ERROR (&error);
		return 1;
	}
	/* emit the value to stdout */
	switch (type) {
	case LIBHAL_PROPERTY_TYPE_STRING:
		str = libhal_device_get_property_string (hal_ctx, udi, key, &error);
		if (is_verbose)
			printf ("Type is string\n");
		printf ("%s\n", str);
		libhal_free_string (str);
		break;
	case LIBHAL_PROPERTY_TYPE_INT32:
		if (is_verbose)
			printf ("Type is integer (shown in %s)\n",
				(is_hex ? "hexadecimal" : "decimal"));
		printf ((is_hex ? "%x\n" : "%d\n"),
			libhal_device_get_property_int (hal_ctx, udi, key, &error));
		break;
	case LIBHAL_PROPERTY_TYPE_UINT64:
		if (is_verbose)
			printf ("Type is uint64 (shown in %s)\n",
				(is_hex ? "hexadecimal" : "decimal"));
		printf ((is_hex ? "%llx\n" : "%llu\n"),
			(long long unsigned int) libhal_device_get_property_uint64 (hal_ctx, udi, key, &error));
		break;
	case LIBHAL_PROPERTY_TYPE_DOUBLE:
		if (is_verbose)
			printf ("Type is double\n");
		printf ("%f\n",
			libhal_device_get_property_double (hal_ctx, udi, key, &error));
		break;
	case LIBHAL_PROPERTY_TYPE_BOOLEAN:
		if (is_verbose)
			printf ("Type is boolean\n");
		printf ("%s\n",
			libhal_device_get_property_bool (hal_ctx, udi, key, &error) ? "true" : "false");
		break;

	case LIBHAL_PROPERTY_TYPE_STRLIST:
	{
		unsigned int i;
		char **strlist;
		
		if ((strlist = libhal_device_get_property_strlist (hal_ctx, udi, key, &error)) != NULL) {
			
			for (i = 0; strlist[i] != 0; i++) {
				printf ("%s", strlist[i]);
				if (strlist[i+1] != NULL)
					printf (" ");
			}
		} 
		break;
	}
	default:
		printf ("Unknown type %d='%c'\n", type, type);
		return 1;
		break;
	}

	if (dbus_error_is_set (&error)) {
		fprintf (stderr, "error: %s: %s\n", error.name, error.message);
		dbus_error_free (&error);
		return 1;
	}


	return 0;
}
Exemple #21
0
/**
 * Listens for new connections on the given address.  If there are
 * multiple semicolon-separated address entries in the address, tries
 * each one and listens on the first one that works.
 *
 * Returns #NULL and sets error if listening fails for any reason.
 * Otherwise returns a new #DBusServer.
 * dbus_server_set_new_connection_function(),
 * dbus_server_set_watch_functions(), and
 * dbus_server_set_timeout_functions() should be called immediately to
 * render the server fully functional.
 *
 * To free the server, applications must call first
 * dbus_server_disconnect() and then dbus_server_unref().
 *
 * @param address the address of this server.
 * @param error location to store reason for failure.
 * @returns a new #DBusServer, or #NULL on failure.
 *
 */
DBusServer*
dbus_server_listen (const char     *address,
                    DBusError      *error)
{
    DBusServer *server;
    DBusAddressEntry **entries;
    int len, i;
    DBusError first_connect_error = DBUS_ERROR_INIT;
    dbus_bool_t handled_once;

    _dbus_return_val_if_fail (address != NULL, NULL);
    _dbus_return_val_if_error_is_set (error, NULL);

    if (!dbus_parse_address (address, &entries, &len, error))
        return NULL;

    server = NULL;
    handled_once = FALSE;

    for (i = 0; i < len; i++)
    {
        int j;

        for (j = 0; j < (int) _DBUS_N_ELEMENTS (listen_funcs); ++j)
        {
            DBusServerListenResult result;
            DBusError tmp_error = DBUS_ERROR_INIT;

            result = (* listen_funcs[j].func) (entries[i],
                                               &server,
                                               &tmp_error);

            if (result == DBUS_SERVER_LISTEN_OK)
            {
                _dbus_assert (server != NULL);
                _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
                handled_once = TRUE;
                goto out;
            }
            else if (result == DBUS_SERVER_LISTEN_ADDRESS_ALREADY_USED)
            {
                _dbus_assert (server == NULL);
                dbus_set_error (error,
                                DBUS_ERROR_ADDRESS_IN_USE,
                                "Address '%s' already used",
                                dbus_address_entry_get_method (entries[0]));
                handled_once = TRUE;
                goto out;
            }
            else if (result == DBUS_SERVER_LISTEN_BAD_ADDRESS)
            {
                _dbus_assert (server == NULL);
                _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
                dbus_move_error (&tmp_error, error);
                handled_once = TRUE;
                goto out;
            }
            else if (result == DBUS_SERVER_LISTEN_NOT_HANDLED)
            {
                _dbus_assert (server == NULL);
                _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);

                /* keep trying addresses */
            }
            else if (result == DBUS_SERVER_LISTEN_DID_NOT_CONNECT)
            {
                _dbus_assert (server == NULL);
                _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
                if (!dbus_error_is_set (&first_connect_error))
                    dbus_move_error (&tmp_error, &first_connect_error);
                else
                    dbus_error_free (&tmp_error);

                handled_once = TRUE;

                /* keep trying addresses */
            }
        }

        _dbus_assert (server == NULL);
        _DBUS_ASSERT_ERROR_IS_CLEAR (error);
    }

out:

    if (!handled_once)
    {
        _DBUS_ASSERT_ERROR_IS_CLEAR (error);
        if (len > 0)
            dbus_set_error (error,
                            DBUS_ERROR_BAD_ADDRESS,
                            "Unknown address type '%s'",
                            dbus_address_entry_get_method (entries[0]));
        else
            dbus_set_error (error,
                            DBUS_ERROR_BAD_ADDRESS,
                            "Empty address '%s'",
                            address);
    }

    dbus_address_entries_free (entries);

    if (server == NULL)
    {
        _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error) ||
                      dbus_error_is_set (error));

        if (error && dbus_error_is_set (error))
        {
            /* already set the error */
        }
        else
        {
            /* didn't set the error but either error should be
             * NULL or first_connect_error should be set.
             */
            _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error));
            dbus_move_error (&first_connect_error, error);
        }

        _DBUS_ASSERT_ERROR_IS_CLEAR (&first_connect_error); /* be sure we freed it */
        _DBUS_ASSERT_ERROR_IS_SET (error);

        return NULL;
    }
    else
    {
        _DBUS_ASSERT_ERROR_IS_CLEAR (error);
        return server;
    }
}
Exemple #22
0
static DBusHandlerResult object_handler(
	DBusConnection *c,
	DBusMessage *m,
	void *userdata) {

	rd_device *d;
	DBusError error;
	DBusMessage *reply = NULL;

	dbus_error_init(&error);

	d = userdata;
	assert(d->ref >= 1);

	if (dbus_message_is_method_call(
		    m,
		    "org.freedesktop.ReserveDevice1",
		    "RequestRelease")) {

		int32_t priority;
		dbus_bool_t ret;

		if (!dbus_message_get_args(
			    m,
			    &error,
			    DBUS_TYPE_INT32, &priority,
			    DBUS_TYPE_INVALID))
			goto invalid;

		ret = FALSE;

		if (priority > d->priority && d->request_cb) {
			d->ref++;

			if (d->request_cb(d, 0) > 0) {
				ret = TRUE;
				d->gave_up = 1;
			}

			rd_release(d);
		}

		if (!(reply = dbus_message_new_method_return(m)))
			goto oom;

		if (!dbus_message_append_args(
			    reply,
			    DBUS_TYPE_BOOLEAN, &ret,
			    DBUS_TYPE_INVALID))
			goto oom;

		if (!dbus_connection_send(c, reply, NULL))
			goto oom;

		dbus_message_unref(reply);

		return DBUS_HANDLER_RESULT_HANDLED;

	} else if (dbus_message_is_method_call(
			   m,
			   "org.freedesktop.DBus.Properties",
			   "Get")) {

		const char *interface, *property;

		if (!dbus_message_get_args(
			    m,
			    &error,
			    DBUS_TYPE_STRING, &interface,
			    DBUS_TYPE_STRING, &property,
			    DBUS_TYPE_INVALID))
			goto invalid;

		if (strcmp(interface, "org.freedesktop.ReserveDevice1") == 0) {
			const char *empty = "";

			if (strcmp(property, "ApplicationName") == 0 && d->application_name) {
				if (!(reply = dbus_message_new_method_return(m)))
					goto oom;

				if (!add_variant(
					    reply,
					    DBUS_TYPE_STRING,
					    d->application_name ? (const char * const *) &d->application_name : &empty))
					goto oom;

			} else if (strcmp(property, "ApplicationDeviceName") == 0) {
				if (!(reply = dbus_message_new_method_return(m)))
					goto oom;

				if (!add_variant(
					    reply,
					    DBUS_TYPE_STRING,
					    d->application_device_name ? (const char * const *) &d->application_device_name : &empty))
					goto oom;

			} else if (strcmp(property, "Priority") == 0) {
				if (!(reply = dbus_message_new_method_return(m)))
					goto oom;

				if (!add_variant(
					    reply,
					    DBUS_TYPE_INT32,
					    &d->priority))
					goto oom;
			} else {
				if (!(reply = dbus_message_new_error_printf(
					      m,
					      DBUS_ERROR_UNKNOWN_METHOD,
					      "Unknown property %s",
					      property)))
					goto oom;
			}

			if (!dbus_connection_send(c, reply, NULL))
				goto oom;

			dbus_message_unref(reply);

			return DBUS_HANDLER_RESULT_HANDLED;
		}

	} else if (dbus_message_is_method_call(
			   m,
			   "org.freedesktop.DBus.Introspectable",
			   "Introspect")) {
			    const char *i = introspection;

		if (!(reply = dbus_message_new_method_return(m)))
			goto oom;

		if (!dbus_message_append_args(
			    reply,
			    DBUS_TYPE_STRING,
			    &i,
			    DBUS_TYPE_INVALID))
			goto oom;

		if (!dbus_connection_send(c, reply, NULL))
			goto oom;

		dbus_message_unref(reply);

		return DBUS_HANDLER_RESULT_HANDLED;
	}

	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

invalid:
	if (reply)
		dbus_message_unref(reply);

	if (!(reply = dbus_message_new_error(
		      m,
		      DBUS_ERROR_INVALID_ARGS,
		      "Invalid arguments")))
		goto oom;

	if (!dbus_connection_send(c, reply, NULL))
		goto oom;

	dbus_message_unref(reply);

	dbus_error_free(&error);

	return DBUS_HANDLER_RESULT_HANDLED;

oom:
	if (reply)
		dbus_message_unref(reply);

	dbus_error_free(&error);

	return DBUS_HANDLER_RESULT_NEED_MEMORY;
}
char* resolve_service(int interface, int protocol, char *name, char *type, char *domain)
{
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    dbus_error_init(&err);
    DBusPendingCall* pending;
    //dbus_int32_t interface = 2;
    //dbus_int32_t protocol = 1;
    //char *name = "TestService";
    //char *type = "_http._tcp";
    //char *domain = "local";
    dbus_int32_t aprotocol = -1;
    dbus_uint32_t flags = 0;
    printf ("parameter for ResolvesService:%d, %d, %s, %s, %s, %d, %d.\n", interface, protocol, name, type, domain, aprotocol, flags);

   // initialiset the errors
    printf("Calling remote method: %s\n", "org.freedesktop.Avahi");

   // 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);
    }

    msg = dbus_message_new_method_call("org.freedesktop.Avahi",// target for the method call
                                        "/", 							// object to call on
                                        "org.freedesktop.Avahi.Server",    // interface to call on
                                        "ResolveService");             // method nameResolveHostName
    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_INT32, &interface))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_INT32, &protocol))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &name))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &type))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &domain))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_INT32, &aprotocol))
    {
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
    }
    if (!dbus_message_iter_append_basic(&args, DBUS_TYPE_UINT32, &flags))
    {
        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);


    char *address;
    char *host;
    dbus_uint16_t port;//gint16
    GPtrArray *byte_arraies;
    dbus_uint32_t m_flags;
    if (!dbus_message_iter_init(msg, &args))
        g_message("dbus_message_iter_init fail\n");
    else
    { 
//g_message("signature of container args: %s", dbus_message_iter_get_signature(&args));
//g_message("first type: %d", dbus_message_iter_get_arg_type(&args));
//g_message("DBUS_TYPE_INT32: %d", DBUS_TYPE_INT32);
//g_message("DBUS_TYPE_STRING: %d", DBUS_TYPE_STRING);
//char *value;
//dbus_message_iter_get_basic(&args, &value);
//g_message("DBUS_TYPE_STRING: %s", value);

        if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
            g_message( "Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &interface);
            printf("interface : %d\n", interface); 
        }

        if (!dbus_message_iter_next(&args))
            g_message( "Message has too few arguments!\n"); 
        else if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &protocol);
            printf("protocol : %d\n", protocol); 
        }

        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
           dbus_message_iter_get_basic(&args, &name);
            printf("name : %s\n", name); 
        }

        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
           dbus_message_iter_get_basic(&args, &type);
            printf("type : %s\n", type); 
        }

        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &domain);
            printf("domain : %s\n", domain); 
        }

        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &host);
            printf("host : %s\n", host); 
        }

        if (!dbus_message_iter_next(&args))
            g_message( "Message has too few arguments!\n"); 
        else if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &aprotocol);
            printf("aprotocol : %d\n", aprotocol); 
        }

        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
           dbus_message_iter_get_basic(&args, &address);
            printf("address : %s\n", address); 
        }

        if (!dbus_message_iter_next(&args))
            g_message( "Message has too few arguments!\n"); 
        else if (DBUS_TYPE_UINT16 != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &port);
            printf("port : %d\n", port); 
        }

        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (strcmp("aay", dbus_message_iter_get_signature(&args))) 
            g_message("Argument is not error!\n"); 
        else{
            DBusMessageIter container_ay, container_y;
            unsigned char *values;int size;
            //dbus_message_iter_get_basic(&args, &flags);
            //dbus_message_iter_open_container(&args, DBUS_TYPE_ARRAY, "ay", &container_ay);
            //dbus_message_iter_open_container(&container_ay, DBUS_TYPE_BYTE, "y", &container_y);

            dbus_message_iter_recurse(&args, &container_ay);

            dbus_message_iter_recurse(&container_ay, &container_y);
            dbus_message_iter_get_fixed_array(&container_y, &values, &size);
            g_message("size: %d, %s", size, values);
/*
g_message("container args: %s", dbus_message_iter_get_signature(&args));
g_message("container_ay: %s", dbus_message_iter_get_signature(&container_ay));
g_message("container_y: %s", dbus_message_iter_get_signature(&container_y));
g_message("type of container_y: %d", dbus_message_iter_get_arg_type(&container_y));
g_message("value of DBUS_TYPE_BYTE: %d", DBUS_TYPE_BYTE);
*/
// && strcmp("ay", dbus_message_iter_get_signature(&container_ay))
            while(dbus_message_iter_next(&container_ay)){
                dbus_message_iter_recurse(&container_ay, &container_y);
                dbus_message_iter_get_fixed_array(&container_y, &values, &size);
                g_message("size: %d, %s", size, values);
            }
        }
        if (!dbus_message_iter_next(&args))
            g_message( "Message has too few arguments!\n"); 
        else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else{
            dbus_message_iter_get_basic(&args, &m_flags);
            printf("m_flags : %d\n", m_flags); 
        }

/*
dbus_message_iter_next(&args);
g_message("g_message_iter_get_signature: %s", dbus_message_iter_get_signature(&args));
*/
/*
        if (!dbus_message_iter_next(&args))
            g_message("Message has too few arguments!\n"); 
        else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) 
            g_message("Argument is not error!\n"); 
        else
            dbus_message_iter_get_basic(&args, &flags);
*/
  //      printf("discovered:%d, %d, %s, %s, %s, %d.\n", interface, protocol, name, type, domain, flags);
    }
    dbus_message_unref(msg);  
}
Exemple #24
0
static DBusHandlerResult filter_handler(
	DBusConnection *c,
	DBusMessage *m,
	void *userdata) {

	rd_device *d;
	DBusError error;
	char *name_owner = NULL;

	dbus_error_init(&error);

	d = userdata;
	assert(d->ref >= 1);

	if (dbus_message_is_signal(m, "org.freedesktop.DBus", "NameLost")) {
		const char *name;

		if (!dbus_message_get_args(
			    m,
			    &error,
			    DBUS_TYPE_STRING, &name,
			    DBUS_TYPE_INVALID))
			goto invalid;

		if (strcmp(name, d->service_name) == 0 && d->owning) {
			/* Verify the actual owner of the name to avoid leaked NameLost
			 * signals from previous reservations. The D-Bus daemon will send
			 * all messages asynchronously in the correct order, but we could
			 * potentially process them too late due to the pseudo-blocking
			 * call mechanism used during both acquisition and release. This
			 * can happen if we release the device and immediately after
			 * reacquire it before NameLost is processed. */
			if (!d->gave_up) {
				const char *un;

				if ((un = dbus_bus_get_unique_name(c)) && rd_dbus_get_name_owner(c, d->service_name, &name_owner, &error) == 0)
					if (name_owner && strcmp(name_owner, un) == 0)
						goto invalid; /* Name still owned by us */
			}

			d->owning = 0;

			if (!d->gave_up)  {
				d->ref++;

				if (d->request_cb)
					d->request_cb(d, 1);
				d->gave_up = 1;

				rd_release(d);
			}

		}
	}

invalid:
	free(name_owner);
	dbus_error_free(&error);

	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
char* get_entry_group_path()
{
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    dbus_error_init(&err);
    DBusPendingCall* pending;
    char *entry_group_path;

   // initialiset the errors
    printf("Calling remote method: %s\n", "org.freedesktop.Avahi");

   // 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);
    }

    msg = dbus_message_new_method_call("org.freedesktop.Avahi",// target for the method call
                                        "/", 							// object to call on
                                        "org.freedesktop.Avahi.Server",    // interface to call on
                                        "EntryGroupNew");             // method nameResolveHostName
    if (NULL == msg) 
     { 
      fprintf(stderr, "Message Null\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); 
    }
    if (dbus_message_get_type(msg) == DBUS_MESSAGE_TYPE_ERROR) {
			   fprintf("message returned error: %s", dbus_message_get_error_name(msg));
	}
    // 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_OBJECT_PATH != dbus_message_iter_get_arg_type(&args)) 
        fprintf(stderr, "Argument is not DBUS_TYPE_OBJECT_PATH!\n"); 
    else
        dbus_message_iter_get_basic(&args, &entry_group_path);


    printf("Got Reply: %s\n", entry_group_path);
    dbus_message_unref(msg);  
    return entry_group_path;
}
Exemple #26
0
int rd_acquire(
	rd_device **_d,
	DBusConnection *connection,
	const char *device_name,
	const char *application_name,
	int32_t priority,
	rd_request_cb_t request_cb,
	DBusError *error) {

	rd_device *d = NULL;
	int r, k;
	DBusError _error;
	DBusMessage *m = NULL, *reply = NULL;
	dbus_bool_t good;

	if (!error)
		error = &_error;

	dbus_error_init(error);

	if (!_d)
		return -EINVAL;

	if (!connection)
		return -EINVAL;

	if (!device_name)
		return -EINVAL;

	if (!request_cb && priority != INT32_MAX)
		return -EINVAL;

	if (!(d = calloc(sizeof(rd_device), 1)))
		return -ENOMEM;

	d->ref = 1;

	if (!(d->device_name = strdup(device_name))) {
		r = -ENOMEM;
		goto fail;
	}

	if (!(d->application_name = strdup(application_name))) {
		r = -ENOMEM;
		goto fail;
	}

	d->priority = priority;
	d->connection = dbus_connection_ref(connection);
	d->request_cb = request_cb;

	if (!(d->service_name = malloc(sizeof(SERVICE_PREFIX) + strlen(device_name)))) {
		r = -ENOMEM;
		goto fail;
	}
	sprintf(d->service_name, SERVICE_PREFIX "%s", d->device_name);

	if (!(d->object_path = malloc(sizeof(OBJECT_PREFIX) + strlen(device_name)))) {
		r = -ENOMEM;
		goto fail;
	}
	sprintf(d->object_path, OBJECT_PREFIX "%s", d->device_name);

	if ((k = dbus_bus_request_name(
		     d->connection,
		     d->service_name,
		     DBUS_NAME_FLAG_DO_NOT_QUEUE|
		     (priority < INT32_MAX ? DBUS_NAME_FLAG_ALLOW_REPLACEMENT : 0),
		     error)) < 0) {
		r = -EIO;
		goto fail;
	}

	if (k == DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
		goto success;

	if (k != DBUS_REQUEST_NAME_REPLY_EXISTS) {
		r = -EIO;
		goto fail;
	}

	if (priority <= INT32_MIN) {
		r = -EBUSY;
		goto fail;
	}

	if (!(m = dbus_message_new_method_call(
		      d->service_name,
		      d->object_path,
		      "org.freedesktop.ReserveDevice1",
		      "RequestRelease"))) {
		r = -ENOMEM;
		goto fail;
	}

	if (!dbus_message_append_args(
		    m,
		    DBUS_TYPE_INT32, &d->priority,
		    DBUS_TYPE_INVALID)) {
		r = -ENOMEM;
		goto fail;
	}

	if (!(reply = dbus_connection_send_with_reply_and_block(
		      d->connection,
		      m,
		      5000, /* 5s */
		      error))) {

		if (dbus_error_has_name(error, DBUS_ERROR_TIMED_OUT) ||
		    dbus_error_has_name(error, DBUS_ERROR_UNKNOWN_METHOD) ||
		    dbus_error_has_name(error, DBUS_ERROR_NO_REPLY)) {
			/* This must be treated as denied. */
			r = -EBUSY;
			goto fail;
		}

		r = -EIO;
		goto fail;
	}

	if (!dbus_message_get_args(
		    reply,
		    error,
		    DBUS_TYPE_BOOLEAN, &good,
		    DBUS_TYPE_INVALID)) {
		r = -EIO;
		goto fail;
	}

	if (!good) {
		r = -EBUSY;
		goto fail;
	}

	if ((k = dbus_bus_request_name(
		     d->connection,
		     d->service_name,
		     DBUS_NAME_FLAG_DO_NOT_QUEUE|
		     (priority < INT32_MAX ? DBUS_NAME_FLAG_ALLOW_REPLACEMENT : 0)|
		     DBUS_NAME_FLAG_REPLACE_EXISTING,
		     error)) < 0) {
		r = -EIO;
		goto fail;
	}

	if (k != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
		r = -EIO;
		goto fail;
	}

success:
	d->owning = 1;

	if (!(dbus_connection_register_object_path(
		      d->connection,
		      d->object_path,
		      &vtable,
		      d))) {
		r = -ENOMEM;
		goto fail;
	}

	d->registered = 1;

	if (!dbus_connection_add_filter(
		    d->connection,
		    filter_handler,
		    d,
		    NULL)) {
		r = -ENOMEM;
		goto fail;
	}

	d->filtering = 1;

	*_d = d;
	return 0;

fail:
	if (m)
		dbus_message_unref(m);

	if (reply)
		dbus_message_unref(reply);

	if (&_error == error)
		dbus_error_free(&_error);

	if (d)
		rd_release(d);

	return r;
}
void method_GetState(char *path){
    DBusMessage* msg;
    DBusMessageIter args;
    DBusConnection* conn;
    DBusError err;
    dbus_error_init(&err);
    DBusPendingCall* pending;
    // 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);
     }
    //char *path = malloc(sizeof(char) * strlen(mpath));
    //strcpy(path, mpath);
    //printf("*0mpath: %s / %s\n", path, mpath);
    msg = dbus_message_new_method_call("org.freedesktop.Avahi",// target for the method call
                                        path, 							// object to call on
                                        "org.freedesktop.Avahi.EntryGroup",    // interface to call on
                                        "GetState");             // method nameResolveHostName
    //printf("*1mpath: %s / %s\n", path, mpath);
    if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout
        fprintf(stderr, "Out Of Memory!\n"); 
        exit(1);
     }
    //printf("*2mpath: %s / %s\n", path, mpath);
    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);

     dbus_uint32_t m_state;
     if (!dbus_message_iter_init(msg, &args)){
         g_message("dbus_message_iter_init fail\n");
     }
     if(dbus_message_get_type(msg) == DBUS_MESSAGE_TYPE_ERROR){
         char *result;
         g_message("arg type: %d", dbus_message_iter_get_arg_type(&args));
         dbus_message_iter_get_basic(&args, &result);
         g_message("error:  %s", result);    	 
     }else{
         if (DBUS_TYPE_INT32 != dbus_message_iter_get_arg_type(&args)) 
             g_message("Argument is not DBUS_TYPE_INT32!\n"); 
         else{
             dbus_message_iter_get_basic(&args, &m_state);
             printf("m_state : %d\n", m_state);
         }
     }
     dbus_message_unref(msg);
}
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;

        if (!dbus_connection_add_filter(notificationitem->conn, FcitxNotificationItemDBusFilter, notificationitem, NULL)) {
            FcitxLog(ERROR, "No memory");
            break;
        }

        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;
        }

        dbus_bus_add_match(notificationitem->conn,
                           "type='signal',"
                           "interface='" DBUS_INTERFACE_DBUS "',"
                           "path='" DBUS_PATH_DBUS "',"
                           "member='NameOwnerChanged',"
                           "arg0='" NOTIFICATION_WATCHER_DBUS_ADDR "'",
                           &err);
        dbus_connection_flush(notificationitem->conn);
        if (dbus_error_is_set(&err)) {
            FcitxLog(ERROR, "Match Error (%s)", err.message);
            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,
                                                            0);
        if (reply == TRUE) {
            dbus_pending_call_set_notify(call,
                                         NotificationWatcherServiceExistCallback,
                                         notificationitem,
                                         NULL);
        }
        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);

        dbus_error_free(&err);

        FcitxNotificationItemAddFunctions(instance);

        return notificationitem;
    } while(0);

    dbus_error_free(&err);
    FcitxNotificationItemDestroy(notificationitem);

    return NULL;
}
static dbus_bool_t
ck_connector_open_session_with_parameters_valist (CkConnector *connector,
                                                  DBusError   *error,
                                                  const char  *first_parameter_name,
                                                  va_list      var_args)
{
        DBusError       local_error;
        DBusMessage    *message;
        DBusMessage    *reply;
        DBusMessageIter iter;
        DBusMessageIter iter_array;
        dbus_bool_t     ret;
        char           *cookie;
        const char     *name;

        _ck_return_val_if_fail (connector != NULL, FALSE);

        reply = NULL;
        message = NULL;
        ret = FALSE;

        dbus_error_init (&local_error);
        connector->connection = dbus_bus_get_private (DBUS_BUS_SYSTEM, &local_error);
        if (connector->connection == NULL) {
                if (dbus_error_is_set (&local_error)) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unable to open session: %s",
                                        local_error.message);
                        dbus_error_free (&local_error);
                }
                goto out;
        }

        dbus_connection_set_exit_on_disconnect (connector->connection, FALSE);

        message = dbus_message_new_method_call ("org.freedesktop.ConsoleKit",
                                                "/org/freedesktop/ConsoleKit/Manager",
                                                "org.freedesktop.ConsoleKit.Manager",
                                                "OpenSessionWithParameters");
        if (message == NULL) {
                goto out;
        }

        dbus_message_iter_init_append (message, &iter);
        if (! dbus_message_iter_open_container (&iter,
                                                DBUS_TYPE_ARRAY,
                                                "(sv)",
                                                &iter_array)) {
                goto out;
        }

        name = first_parameter_name;
        while (name != NULL) {
                int         type;
                const void *value;
                dbus_bool_t res;

                type = lookup_parameter_type (name);
                value = va_arg (var_args, const void *);

                if (type == DBUS_TYPE_INVALID) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unknown parameter: %s",
                                        name);
                        goto out;
                }

                res = add_param_basic (&iter_array, name, type, value);
                if (! res) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Error adding parameter: %s",
                                        name);
                        goto out;
                }

                name = va_arg (var_args, char *);
        }

        if (! dbus_message_iter_close_container (&iter, &iter_array)) {
                goto out;
        }

        dbus_error_init (&local_error);
        reply = dbus_connection_send_with_reply_and_block (connector->connection,
                                                           message,
                                                           -1,
                                                           &local_error);
        if (reply == NULL) {
                if (dbus_error_is_set (&local_error)) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unable to open session: %s",
                                        local_error.message);
                        dbus_error_free (&local_error);
                        goto out;
                }
        }

        dbus_error_init (&local_error);
        if (! dbus_message_get_args (reply,
                                     &local_error,
                                     DBUS_TYPE_STRING, &cookie,
                                     DBUS_TYPE_INVALID)) {
                if (dbus_error_is_set (&local_error)) {
                        dbus_set_error (error,
                                        CK_CONNECTOR_ERROR,
                                        "Unable to open session: %s",
                                        local_error.message);
                        dbus_error_free (&local_error);
                        goto out;
                }
        }

        connector->cookie = strdup (cookie);
        if (connector->cookie == NULL) {
                goto out;
        }

        connector->session_created = TRUE;
        ret = TRUE;

out:
        if (reply != NULL) {
                dbus_message_unref (reply);
        }

        if (message != NULL) {
                dbus_message_unref (message);
        }

        return ret;
}
Exemple #30
0
static int set_network(struct supplicant_task *task,
				const unsigned char *network, int len,
				const char *address, const char *security,
							const char *passphrase)
{
	DBusMessage *message, *reply;
	DBusMessageIter array, dict;
	DBusError error;
	dbus_uint32_t scan_ssid = 1;

	_DBG_SUPPLICANT("task %p", task);

	if (task->netpath == NULL)
		return -EINVAL;

	message = dbus_message_new_method_call(SUPPLICANT_NAME, task->netpath,
					SUPPLICANT_INTF ".Network", "set");
	if (message == NULL)
		return -ENOMEM;

	dbus_message_set_auto_start(message, FALSE);

	dbus_message_iter_init_append(message, &array);

	dbus_message_iter_open_container(&array, DBUS_TYPE_ARRAY,
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);

	connman_dbus_dict_append_variant(&dict, "scan_ssid",
					 DBUS_TYPE_UINT32, &scan_ssid);
	connman_dbus_dict_append_array(&dict, "ssid",
					DBUS_TYPE_BYTE, &network, len);
	/* NB: do not set the bssid; this allows wpa_supplicant to roam */

	if (g_ascii_strcasecmp(security, "wpa") == 0 ||
				g_ascii_strcasecmp(security, "rsn") == 0) {
		const char *key_mgmt = "WPA-PSK";
		connman_dbus_dict_append_variant(&dict, "key_mgmt",
						DBUS_TYPE_STRING, &key_mgmt);

		if (passphrase && strlen(passphrase) > 0)
			connman_dbus_dict_append_variant(&dict, "psk",
						DBUS_TYPE_STRING, &passphrase);
	} else if (g_ascii_strcasecmp(security, "wep") == 0) {
		const char *key_mgmt = "NONE";
		const char *auth_alg = "OPEN";
		const char *key_index = "0";

		if (task->mac80211 == TRUE)
			auth_alg = "OPEN SHARED";

		connman_dbus_dict_append_variant(&dict, "auth_alg",
						DBUS_TYPE_STRING, &auth_alg);

		connman_dbus_dict_append_variant(&dict, "key_mgmt",
						DBUS_TYPE_STRING, &key_mgmt);

		if (passphrase) {
			int size = strlen(passphrase);
			if (size == 10 || size == 26) {
				unsigned char *key = malloc(13);
				char tmp[3];
				int i;
				memset(tmp, 0, sizeof(tmp));
				if (key == NULL)
					size = 0;
				for (i = 0; i < size / 2; i++) {
					memcpy(tmp, passphrase + (i * 2), 2);
					key[i] = (unsigned char) strtol(tmp,
								NULL, 16);
				}
				connman_dbus_dict_append_array(&dict,
						"wep_key0", DBUS_TYPE_BYTE,
							&key, size / 2);
				free(key);
			} else
				connman_dbus_dict_append_variant(&dict,
						"wep_key0", DBUS_TYPE_STRING,
								&passphrase);

			connman_dbus_dict_append_variant(&dict, "wep_tx_keyidx",
						DBUS_TYPE_STRING, &key_index);
		}
	} else {
		const char *key_mgmt = "NONE";
		connman_dbus_dict_append_variant(&dict, "key_mgmt",
						DBUS_TYPE_STRING, &key_mgmt);
	}

	dbus_message_iter_close_container(&array, &dict);

	dbus_error_init(&error);

	reply = dbus_connection_send_with_reply_and_block(connection,
							message, -1, &error);
	if (reply == NULL) {
		if (dbus_error_is_set(&error) == TRUE) {
			connman_error("%s", error.message);
			dbus_error_free(&error);
		} else
			connman_error("Failed to set network options");
		dbus_message_unref(message);
		return -EIO;
	}

	dbus_message_unref(message);

	dbus_message_unref(reply);

	return 0;
}