Пример #1
0
	int
conf_drp_show_domain_ip(DBusConnection *connection,
		domain_cst *domain_configs_ret)
{
	DBusMessage *query, *reply;
	DBusError err;
	DBusMessageIter  iter;
	DBusMessageIter  iter_array;
	int iRet=0;
	int i = 0, ip_num = 0;
	char *domain_name = NULL;
	int index = 0;
	unsigned long ipaddr = 0;

	query = dbus_message_new_method_call(
			DRP_DBUS_BUSNAME,
			DRP_DBUS_OBJPATH,
			DRP_DBUS_INTERFACE, 
			DRP_DBUS_METHOD_SHOW_DOMAIN_IP );
	dbus_error_init(&err);
	dbus_message_append_args( query,
					DBUS_TYPE_INVALID );

	reply = dbus_connection_send_with_reply_and_block (
			connection, query, -1, &err );

	dbus_message_unref(query);
	if ( NULL == reply ){	
		if (dbus_error_is_set(&err)){
			dbus_error_free(&err);
		}
		return DRP_ERR_DBUS_FAILED;
	}else{
		dbus_message_iter_init(reply,&iter);
		//dbus_message_iter_next(&iter);
		dbus_message_iter_get_basic(&iter, &iRet);
		if( DRP_RETURN_OK == iRet ){
			memset (domain_configs_ret, 0, sizeof(domain_configs_ret));
			dbus_message_iter_next(&iter);
			dbus_message_iter_get_basic(&iter, &ip_num);
			if( ip_num > MAX_DOMAIN_CONFIG_NUM*MAX_DOMAIN_IPADDR ){
				ip_num = MAX_DOMAIN_CONFIG_NUM*MAX_DOMAIN_IPADDR;
			}
			domain_configs_ret->num = ip_num;
			if( ip_num > 0 ){
				dbus_message_iter_next(&iter);	
				dbus_message_iter_recurse(&iter,&iter_array);			
				for( i=0; i<ip_num; i++ ){
					DBusMessageIter iter_struct;
					dbus_message_iter_recurse(&iter_array,&iter_struct);
					dbus_message_iter_get_basic(&iter_struct, &domain_name);
					strncpy((domain_configs_ret->domain[i].domain_name), domain_name,\
							sizeof(domain_configs_ret->domain[i].domain_name));
					dbus_message_iter_next(&iter_struct);
					dbus_message_iter_get_basic(&iter_struct,	\
							&(index));
					domain_configs_ret->domain[i].index = index;
					dbus_message_iter_next(&iter_struct);
					dbus_message_iter_get_basic(&iter_struct, \
							&(ipaddr));
					domain_configs_ret->domain[i].ipaddr = ipaddr;
					dbus_message_iter_next(&iter_array);
#ifdef drp_test_interface	
					printf("domain %s ip index %d ipaddr %lu\n",\
							(domain_configs_ret->domain[i].domain_name),\
							(domain_configs_ret->domain[i].index),\
							(domain_configs_ret->domain[i].ipaddr));
#endif
				}
			}
		}
	}

	dbus_message_unref(reply);

	return iRet;
}
Пример #2
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	guint signal;

#ifdef NEED_THREADS
	if (g_thread_supported() == FALSE)
		g_thread_init(NULL);
#endif

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
		if (error != NULL) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version == TRUE) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach == TRUE) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			exit(1);
		}
	}

	if (mkdir(STATEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create state directory");
	}

	if (mkdir(STORAGEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create storage directory");
	}

	umask(0077);

	main_loop = g_main_loop_new(NULL, FALSE);

#ifdef NEED_THREADS
	if (dbus_threads_init_default() == FALSE) {
		fprintf(stderr, "Can't init usage of threads\n");
		exit(1);
	}
#endif

	signal = setup_signalfd();

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, CONNMAN_SERVICE, &err);
	if (conn == NULL) {
		if (dbus_error_is_set(&err) == TRUE) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	__connman_log_init(argv[0], option_debug, option_detach,
			option_backtrace, "Connection Manager", VERSION);

	__connman_dbus_init(conn);

	if (option_config == NULL)
		config_init(CONFIGMAINFILE);
	else
		config_init(option_config);

	__connman_inotify_init();
	__connman_technology_init();
	__connman_notifier_init();
	__connman_agent_init();
	__connman_service_init();
	__connman_provider_init();
	__connman_network_init();
	__connman_device_init(option_device, option_nodevice);

	__connman_ippool_init();
	__connman_iptables_init();
	__connman_firewall_init();
	__connman_nat_init();
	__connman_tethering_init();
	__connman_counter_init();
	__connman_manager_init();
	__connman_config_init();
	__connman_stats_init();
	__connman_clock_init();

	__connman_resolver_init(option_dnsproxy);
	__connman_ipconfig_init();
	__connman_rtnl_init();
	__connman_task_init();
	__connman_proxy_init();
	__connman_detect_init();
	__connman_session_init();
	__connman_timeserver_init();
	__connman_connection_init();

	__connman_plugin_init(option_plugin, option_noplugin);

	__connman_rtnl_start();
	__connman_dhcp_init();
	__connman_dhcpv6_init();
	__connman_wpad_init();
	__connman_wispr_init();
	__connman_rfkill_init();

	g_free(option_config);
	g_free(option_device);
	g_free(option_plugin);
	g_free(option_nodevice);
	g_free(option_noplugin);

#ifdef SYSTEMD
	/* Tell systemd that we have started up */
	if( option_systemd )
		sd_notify(0, "READY=1");
#endif

	g_main_loop_run(main_loop);

	g_source_remove(signal);

	__connman_rfkill_cleanup();
	__connman_wispr_cleanup();
	__connman_wpad_cleanup();
	__connman_dhcpv6_cleanup();
	__connman_dhcp_cleanup();
	__connman_session_cleanup();
	__connman_plugin_cleanup();
	__connman_provider_cleanup();
	__connman_connection_cleanup();
	__connman_timeserver_cleanup();
	__connman_detect_cleanup();
	__connman_proxy_cleanup();
	__connman_task_cleanup();
	__connman_rtnl_cleanup();
	__connman_resolver_cleanup();

	__connman_clock_cleanup();
	__connman_stats_cleanup();
	__connman_config_cleanup();
	__connman_manager_cleanup();
	__connman_counter_cleanup();
	__connman_tethering_cleanup();
	__connman_nat_cleanup();
	__connman_firewall_cleanup();
	__connman_iptables_cleanup();
	__connman_ippool_cleanup();
	__connman_device_cleanup();
	__connman_network_cleanup();
	__connman_service_cleanup();
	__connman_agent_cleanup();
	__connman_ipconfig_cleanup();
	__connman_notifier_cleanup();
	__connman_technology_cleanup();
	__connman_inotify_cleanup();

	__connman_dbus_cleanup();

	__connman_log_cleanup(option_backtrace);

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	if (connman_settings.pref_timeservers != NULL)
		g_strfreev(connman_settings.pref_timeservers);

	g_free(connman_settings.auto_connect);
	g_free(connman_settings.preferred_techs);
	g_strfreev(connman_settings.fallback_nameservers);
	g_strfreev(connman_settings.blacklisted_interfaces);
	g_strfreev(connman_settings.tethering_technologies);

	g_free(option_debug);

	return 0;
}
/**
 * @ingroup DBusMessageInternals
 * Unit test for DBusMessage.
 *
 * @returns #TRUE on success.
 */
dbus_bool_t
_dbus_message_test (const char *test_data_dir)
{
  DBusMessage *message, *message_without_unix_fds;
  DBusMessageLoader *loader;
  int i;
  const char *data;
  DBusMessage *copy;
  const char *name1;
  const char *name2;
  const dbus_uint32_t our_uint32_array[] =
    { 0x12345678, 0x23456781, 0x34567812, 0x45678123 };
  const dbus_int32_t our_int32_array[] =
    { 0x12345678, -0x23456781, 0x34567812, -0x45678123 };
  const dbus_uint32_t *v_ARRAY_UINT32 = our_uint32_array;
  const dbus_int32_t *v_ARRAY_INT32 = our_int32_array;
#ifdef DBUS_HAVE_INT64
  const dbus_uint64_t our_uint64_array[] =
    { 0x12345678, 0x23456781, 0x34567812, 0x45678123 };
  const dbus_int64_t our_int64_array[] =
    { 0x12345678, -0x23456781, 0x34567812, -0x45678123 };
  const dbus_uint64_t *v_ARRAY_UINT64 = our_uint64_array;
  const dbus_int64_t *v_ARRAY_INT64 = our_int64_array;
#endif
  const char *our_string_array[] = { "Foo", "bar", "", "woo woo woo woo" };
  const char **v_ARRAY_STRING = our_string_array;
  const double our_double_array[] = { 0.1234, 9876.54321, -300.0 };
  const double *v_ARRAY_DOUBLE = our_double_array;
  const unsigned char our_byte_array[] = { 'a', 'b', 'c', 234 };
  const unsigned char *v_ARRAY_BYTE = our_byte_array;
  const dbus_bool_t our_boolean_array[] = { TRUE, FALSE, TRUE, TRUE, FALSE };
  const dbus_bool_t *v_ARRAY_BOOLEAN = our_boolean_array;
  char sig[64];
  const char *s;
  const char *v_STRING;
  double v_DOUBLE;
  dbus_int16_t v_INT16;
  dbus_uint16_t v_UINT16;
  dbus_int32_t v_INT32;
  dbus_uint32_t v_UINT32;
#ifdef DBUS_HAVE_INT64
  dbus_int64_t v_INT64;
  dbus_uint64_t v_UINT64;
#endif
  unsigned char v_BYTE;
  unsigned char v2_BYTE;
  dbus_bool_t v_BOOLEAN;
  DBusMessageIter iter, array_iter, struct_iter;
#ifdef HAVE_UNIX_FD_PASSING
  int v_UNIX_FD;
#endif
  char **decomposed;
  DBusInitialFDs *initial_fds;

  initial_fds = _dbus_check_fdleaks_enter ();

  message = dbus_message_new_method_call ("org.freedesktop.DBus.TestService",
                                          "/org/freedesktop/TestPath",
                                          "Foo.TestInterface",
                                          "TestMethod");
  _dbus_assert (dbus_message_has_destination (message, "org.freedesktop.DBus.TestService"));
  _dbus_assert (dbus_message_is_method_call (message, "Foo.TestInterface",
                                             "TestMethod"));
  _dbus_assert (strcmp (dbus_message_get_path (message),
                        "/org/freedesktop/TestPath") == 0);
  dbus_message_set_serial (message, 1234);

  /* string length including nul byte not a multiple of 4 */
  if (!dbus_message_set_sender (message, "org.foo.bar1"))
    _dbus_assert_not_reached ("out of memory");

  _dbus_assert (dbus_message_has_sender (message, "org.foo.bar1"));
  dbus_message_set_reply_serial (message, 5678);

  _dbus_verbose_bytes_of_string (&message->header.data, 0,
                                 _dbus_string_get_length (&message->header.data));
  _dbus_verbose_bytes_of_string (&message->body, 0,
                                 _dbus_string_get_length (&message->body));

  if (!dbus_message_set_sender (message, NULL))
    _dbus_assert_not_reached ("out of memory");


  _dbus_verbose_bytes_of_string (&message->header.data, 0,
                                 _dbus_string_get_length (&message->header.data));
  _dbus_verbose_bytes_of_string (&message->body, 0,
                                 _dbus_string_get_length (&message->body));


  _dbus_assert (!dbus_message_has_sender (message, "org.foo.bar1"));
  _dbus_assert (dbus_message_get_serial (message) == 1234);
  _dbus_assert (dbus_message_get_reply_serial (message) == 5678);
  _dbus_assert (dbus_message_has_destination (message, "org.freedesktop.DBus.TestService"));

  _dbus_assert (dbus_message_get_no_reply (message) == FALSE);
  dbus_message_set_no_reply (message, TRUE);
  _dbus_assert (dbus_message_get_no_reply (message) == TRUE);
  dbus_message_set_no_reply (message, FALSE);
  _dbus_assert (dbus_message_get_no_reply (message) == FALSE);

  /* Set/get some header fields */

  if (!dbus_message_set_path (message, "/foo"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_path (message),
                        "/foo") == 0);

  if (!dbus_message_set_interface (message, "org.Foo"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_interface (message),
                        "org.Foo") == 0);

  if (!dbus_message_set_member (message, "Bar"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_member (message),
                        "Bar") == 0);

  /* Set/get them with longer values */
  if (!dbus_message_set_path (message, "/foo/bar"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_path (message),
                        "/foo/bar") == 0);

  if (!dbus_message_set_interface (message, "org.Foo.Bar"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_interface (message),
                        "org.Foo.Bar") == 0);

  if (!dbus_message_set_member (message, "BarFoo"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_member (message),
                        "BarFoo") == 0);

  /* Realloc shorter again */

  if (!dbus_message_set_path (message, "/foo"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_path (message),
                        "/foo") == 0);

  if (!dbus_message_set_interface (message, "org.Foo"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_interface (message),
                        "org.Foo") == 0);

  if (!dbus_message_set_member (message, "Bar"))
    _dbus_assert_not_reached ("out of memory");
  _dbus_assert (strcmp (dbus_message_get_member (message),
                        "Bar") == 0);

  /* Path decomposing */
  dbus_message_set_path (message, NULL);
  dbus_message_get_path_decomposed (message, &decomposed);
  _dbus_assert (decomposed == NULL);
  dbus_free_string_array (decomposed);

  dbus_message_set_path (message, "/");
  dbus_message_get_path_decomposed (message, &decomposed);
  _dbus_assert (decomposed != NULL);
  _dbus_assert (decomposed[0] == NULL);
  dbus_free_string_array (decomposed);

  dbus_message_set_path (message, "/a/b");
  dbus_message_get_path_decomposed (message, &decomposed);
  _dbus_assert (decomposed != NULL);
  _dbus_assert (strcmp (decomposed[0], "a") == 0);
  _dbus_assert (strcmp (decomposed[1], "b") == 0);
  _dbus_assert (decomposed[2] == NULL);
  dbus_free_string_array (decomposed);

  dbus_message_set_path (message, "/spam/eggs");
  dbus_message_get_path_decomposed (message, &decomposed);
  _dbus_assert (decomposed != NULL);
  _dbus_assert (strcmp (decomposed[0], "spam") == 0);
  _dbus_assert (strcmp (decomposed[1], "eggs") == 0);
  _dbus_assert (decomposed[2] == NULL);
  dbus_free_string_array (decomposed);

  dbus_message_unref (message);

  /* Test the vararg functions */
  message = dbus_message_new_method_call ("org.freedesktop.DBus.TestService",
                                          "/org/freedesktop/TestPath",
                                          "Foo.TestInterface",
                                          "TestMethod");
  dbus_message_set_serial (message, 1);
  dbus_message_set_reply_serial (message, 5678);

  v_INT16 = -0x123;
  v_UINT16 = 0x123;
  v_INT32 = -0x12345678;
  v_UINT32 = 0x12300042;
#ifdef DBUS_HAVE_INT64
  v_INT64 = DBUS_INT64_CONSTANT (-0x123456789abcd);
  v_UINT64 = DBUS_UINT64_CONSTANT (0x123456789abcd);
#endif
  v_STRING = "Test string";
  v_DOUBLE = 3.14159;
  v_BOOLEAN = TRUE;
  v_BYTE = 42;
  v2_BYTE = 24;
#ifdef HAVE_UNIX_FD_PASSING
  v_UNIX_FD = 1;
#endif

  dbus_message_append_args (message,
                            DBUS_TYPE_INT16, &v_INT16,
                            DBUS_TYPE_UINT16, &v_UINT16,
			    DBUS_TYPE_INT32, &v_INT32,
                            DBUS_TYPE_UINT32, &v_UINT32,
#ifdef DBUS_HAVE_INT64
                            DBUS_TYPE_INT64, &v_INT64,
                            DBUS_TYPE_UINT64, &v_UINT64,
#endif
			    DBUS_TYPE_STRING, &v_STRING,
			    DBUS_TYPE_DOUBLE, &v_DOUBLE,
			    DBUS_TYPE_BOOLEAN, &v_BOOLEAN,
			    DBUS_TYPE_BYTE, &v_BYTE,
			    DBUS_TYPE_BYTE, &v2_BYTE,
			    DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32, &v_ARRAY_UINT32,
                            _DBUS_N_ELEMENTS (our_uint32_array),
                            DBUS_TYPE_ARRAY, DBUS_TYPE_INT32, &v_ARRAY_INT32,
                            _DBUS_N_ELEMENTS (our_int32_array),
#ifdef DBUS_HAVE_INT64
                            DBUS_TYPE_ARRAY, DBUS_TYPE_UINT64, &v_ARRAY_UINT64,
                            _DBUS_N_ELEMENTS (our_uint64_array),
                            DBUS_TYPE_ARRAY, DBUS_TYPE_INT64, &v_ARRAY_INT64,
                            _DBUS_N_ELEMENTS (our_int64_array),
#endif
                            DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE, &v_ARRAY_DOUBLE,
                            _DBUS_N_ELEMENTS (our_double_array),
                            DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &v_ARRAY_BYTE,
                            _DBUS_N_ELEMENTS (our_byte_array),
                            DBUS_TYPE_ARRAY, DBUS_TYPE_BOOLEAN, &v_ARRAY_BOOLEAN,
                            _DBUS_N_ELEMENTS (our_boolean_array),
                            DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &v_ARRAY_STRING,
                            _DBUS_N_ELEMENTS (our_string_array),

			    DBUS_TYPE_INVALID);

  i = 0;
  sig[i++] = DBUS_TYPE_INT16;
  sig[i++] = DBUS_TYPE_UINT16;
  sig[i++] = DBUS_TYPE_INT32;
  sig[i++] = DBUS_TYPE_UINT32;
#ifdef DBUS_HAVE_INT64
  sig[i++] = DBUS_TYPE_INT64;
  sig[i++] = DBUS_TYPE_UINT64;
#endif
  sig[i++] = DBUS_TYPE_STRING;
  sig[i++] = DBUS_TYPE_DOUBLE;
  sig[i++] = DBUS_TYPE_BOOLEAN;
  sig[i++] = DBUS_TYPE_BYTE;
  sig[i++] = DBUS_TYPE_BYTE;
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_UINT32;
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_INT32;
#ifdef DBUS_HAVE_INT64
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_UINT64;
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_INT64;
#endif
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_DOUBLE;
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_BYTE;
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_BOOLEAN;
  sig[i++] = DBUS_TYPE_ARRAY;
  sig[i++] = DBUS_TYPE_STRING;

  message_without_unix_fds = dbus_message_copy(message);
  _dbus_assert(message_without_unix_fds);
#ifdef HAVE_UNIX_FD_PASSING
  dbus_message_append_args (message,
                            DBUS_TYPE_UNIX_FD, &v_UNIX_FD,
			    DBUS_TYPE_INVALID);
  sig[i++] = DBUS_TYPE_UNIX_FD;
#endif
  sig[i++] = DBUS_TYPE_INVALID;

  _dbus_assert (i < (int) _DBUS_N_ELEMENTS (sig));

  _dbus_verbose ("HEADER\n");
  _dbus_verbose_bytes_of_string (&message->header.data, 0,
                                 _dbus_string_get_length (&message->header.data));
  _dbus_verbose ("BODY\n");
  _dbus_verbose_bytes_of_string (&message->body, 0,
                                 _dbus_string_get_length (&message->body));

  _dbus_verbose ("Signature expected \"%s\" actual \"%s\"\n",
                 sig, dbus_message_get_signature (message));

  s = dbus_message_get_signature (message);

  _dbus_assert (dbus_message_has_signature (message, sig));
  _dbus_assert (strcmp (s, sig) == 0);

  verify_test_message (message);

  copy = dbus_message_copy (message);

  _dbus_assert (dbus_message_get_reply_serial (message) ==
                dbus_message_get_reply_serial (copy));
  _dbus_assert (message->header.padding == copy->header.padding);

  _dbus_assert (_dbus_string_get_length (&message->header.data) ==
                _dbus_string_get_length (&copy->header.data));

  _dbus_assert (_dbus_string_get_length (&message->body) ==
                _dbus_string_get_length (&copy->body));

  verify_test_message (copy);

  name1 = dbus_message_get_interface (message);
  name2 = dbus_message_get_interface (copy);

  _dbus_assert (strcmp (name1, name2) == 0);

  name1 = dbus_message_get_member (message);
  name2 = dbus_message_get_member (copy);

  _dbus_assert (strcmp (name1, name2) == 0);

  dbus_message_unref (copy);

  /* Message loader test */
  dbus_message_lock (message);
  loader = _dbus_message_loader_new ();
  
  /* check ref/unref */
  _dbus_message_loader_ref (loader);
  _dbus_message_loader_unref (loader);

  /* Write the header data one byte at a time */
  data = _dbus_string_get_const_data (&message->header.data);
  for (i = 0; i < _dbus_string_get_length (&message->header.data); i++)
    {
      DBusString *buffer;

      _dbus_message_loader_get_buffer (loader, &buffer);
      _dbus_string_append_byte (buffer, data[i]);
      _dbus_message_loader_return_buffer (loader, buffer, 1);
    }

  /* Write the body data one byte at a time */
  data = _dbus_string_get_const_data (&message->body);
  for (i = 0; i < _dbus_string_get_length (&message->body); i++)
    {
      DBusString *buffer;

      _dbus_message_loader_get_buffer (loader, &buffer);
      _dbus_string_append_byte (buffer, data[i]);
      _dbus_message_loader_return_buffer (loader, buffer, 1);
    }

#ifdef HAVE_UNIX_FD_PASSING
  {
    int *unix_fds;
    unsigned n_unix_fds;
    /* Write unix fd */
    _dbus_message_loader_get_unix_fds(loader, &unix_fds, &n_unix_fds);
    _dbus_assert(n_unix_fds > 0);
    _dbus_assert(message->n_unix_fds == 1);
    unix_fds[0] = _dbus_dup(message->unix_fds[0], NULL);
    _dbus_assert(unix_fds[0] >= 0);
    _dbus_message_loader_return_unix_fds(loader, unix_fds, 1);
  }
#endif

  dbus_message_unref (message);

  /* Now pop back the message */
  if (!_dbus_message_loader_queue_messages (loader))
    _dbus_assert_not_reached ("no memory to queue messages");

  if (_dbus_message_loader_get_is_corrupted (loader))
    _dbus_assert_not_reached ("message loader corrupted");

  message = _dbus_message_loader_pop_message (loader);
  if (!message)
    _dbus_assert_not_reached ("received a NULL message");

  if (dbus_message_get_reply_serial (message) != 5678)
    _dbus_assert_not_reached ("reply serial fields differ");

  dbus_message_unref (message);

  /* ovveride the serial, since it was reset by dbus_message_copy() */
  dbus_message_set_serial(message_without_unix_fds, 8901);

  dbus_message_lock (message_without_unix_fds);

  verify_test_message (message_without_unix_fds);

    {
      /* Marshal and demarshal the message. */

      DBusMessage *message2;
      DBusError error = DBUS_ERROR_INIT;
      char *marshalled = NULL;
      int len = 0;
      char garbage_header[DBUS_MINIMUM_HEADER_SIZE] = "xxx";

      if (!dbus_message_marshal (message_without_unix_fds, &marshalled, &len))
        _dbus_assert_not_reached ("failed to marshal message");

      _dbus_assert (len != 0);
      _dbus_assert (marshalled != NULL);

      _dbus_assert (dbus_message_demarshal_bytes_needed (marshalled, len) == len);
      message2 = dbus_message_demarshal (marshalled, len, &error);

      _dbus_assert (message2 != NULL);
      _dbus_assert (!dbus_error_is_set (&error));
      verify_test_message (message2);

      dbus_message_unref (message2);
      dbus_free (marshalled);

      /* Demarshal invalid message. */

      message2 = dbus_message_demarshal ("invalid", 7, &error);
      _dbus_assert (message2 == NULL);
      _dbus_assert (dbus_error_is_set (&error));
      dbus_error_free (&error);

      /* Demarshal invalid (empty) message. */

      message2 = dbus_message_demarshal ("", 0, &error);
      _dbus_assert (message2 == NULL);
      _dbus_assert (dbus_error_is_set (&error));
      dbus_error_free (&error);

      /* Bytes needed to demarshal empty message: 0 (more) */

      _dbus_assert (dbus_message_demarshal_bytes_needed ("", 0) == 0);
      
      /* Bytes needed to demarshal invalid message: -1 (error). */

      _dbus_assert (dbus_message_demarshal_bytes_needed (garbage_header, DBUS_MINIMUM_HEADER_SIZE) == -1);
    }

  dbus_message_unref (message_without_unix_fds);
  _dbus_message_loader_unref (loader);

  check_memleaks ();
  _dbus_check_fdleaks_leave (initial_fds);
  initial_fds = _dbus_check_fdleaks_enter ();

  /* Check that we can abandon a container */
  message = dbus_message_new_method_call ("org.freedesktop.DBus.TestService",
		  			  "/org/freedesktop/TestPath",
					  "Foo.TestInterface",
					  "Method");

  dbus_message_iter_init_append (message, &iter);

  _dbus_assert (dbus_message_iter_open_container (&iter, DBUS_TYPE_ARRAY,
			  			  (DBUS_STRUCT_BEGIN_CHAR_AS_STRING
						   DBUS_TYPE_STRING_AS_STRING
						   DBUS_TYPE_STRING_AS_STRING
						   DBUS_STRUCT_END_CHAR_AS_STRING),
						  &array_iter));
  _dbus_assert (dbus_message_iter_open_container (&array_iter, DBUS_TYPE_STRUCT,
			  			  NULL, &struct_iter));

  s = "peaches";
  _dbus_assert (dbus_message_iter_append_basic (&struct_iter, DBUS_TYPE_STRING,
			  			&s));

  /* uh-oh, error, try and unwind */

  dbus_message_iter_abandon_container (&array_iter, &struct_iter);
  dbus_message_iter_abandon_container (&array_iter, &iter);

  dbus_message_unref (message);

  /* Load all the sample messages from the message factory */
  {
    DBusMessageDataIter diter;
    DBusMessageData mdata;
    int count;

    reset_validities_seen ();
    
    count = 0;
    _dbus_message_data_iter_init (&diter);
    
    while (_dbus_message_data_iter_get_and_next (&diter,
                                                 &mdata))
      {
        if (!dbus_internal_do_not_use_try_message_data (&mdata.data,
                                                        mdata.expected_validity))
          {
            _dbus_warn ("expected validity %d and did not get it\n",
                        mdata.expected_validity);
            _dbus_assert_not_reached ("message data failed");
          }

        _dbus_message_data_free (&mdata);

        count += 1;
      }

    printf ("%d sample messages tested\n", count);

    print_validities_seen (FALSE);
    print_validities_seen (TRUE);
  }

  check_memleaks ();
  _dbus_check_fdleaks_leave (initial_fds);

  /* Now load every message in test_data_dir if we have one */
  if (test_data_dir == NULL)
    return TRUE;

  initial_fds = _dbus_check_fdleaks_enter ();

  if (!dbus_internal_do_not_use_foreach_message_file (test_data_dir,
                                                        (DBusForeachMessageFileFunc)
                                                        dbus_internal_do_not_use_try_message_file,
                                                        NULL))
    _dbus_assert_not_reached ("foreach_message_file test failed");

  _dbus_check_fdleaks_leave (initial_fds);

  return TRUE;
}
Пример #4
0
/**
 * Initialize D-Bus connection.
 */
bool
cdbus_init(session_t *ps) {
  DBusError err = { };

  // Initialize
  dbus_error_init(&err);

  // Connect to D-Bus
  // Use dbus_bus_get_private() so we can fully recycle it ourselves
  ps->dbus_conn = dbus_bus_get_private(DBUS_BUS_SESSION, &err);
  if (dbus_error_is_set(&err)) {
    printf_errf("(): D-Bus connection failed (%s).", err.message);
    dbus_error_free(&err);
    return false;
  }

  if (!ps->dbus_conn) {
    printf_errf("(): D-Bus connection failed for unknown reason.");
    return false;
  }

  // Avoid exiting on disconnect
  dbus_connection_set_exit_on_disconnect(ps->dbus_conn, false);

  // Request service name
  {
    // Build service name
    char *service = mstrjoin3(CDBUS_SERVICE_NAME, ".", ps->o.display_repr);
    ps->dbus_service = service;

    // Request for the name
    int ret = dbus_bus_request_name(ps->dbus_conn, service,
        DBUS_NAME_FLAG_DO_NOT_QUEUE, &err);

    if (dbus_error_is_set(&err)) {
      printf_errf("(): Failed to obtain D-Bus name (%s).", err.message);
      dbus_error_free(&err);
    }

    if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret
        && DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER != ret) {
      printf_errf("(): Failed to become the primary owner of requested "
          "D-Bus name (%d).", ret);
    }
  }


  // Add watch handlers
  if (!dbus_connection_set_watch_functions(ps->dbus_conn,
        cdbus_callback_add_watch, cdbus_callback_remove_watch,
        cdbus_callback_watch_toggled, ps, NULL)) {
    printf_errf("(): Failed to add D-Bus watch functions.");
    return false;
  }

  // Add timeout handlers
  if (!dbus_connection_set_timeout_functions(ps->dbus_conn,
        cdbus_callback_add_timeout, cdbus_callback_remove_timeout,
        cdbus_callback_timeout_toggled, ps, NULL)) {
    printf_errf("(): Failed to add D-Bus timeout functions.");
    return false;
  }

  // Add match
  dbus_bus_add_match(ps->dbus_conn,
      "type='method_call',interface='" CDBUS_INTERFACE_NAME "'", &err);
  if (dbus_error_is_set(&err)) {
    printf_errf("(): Failed to add D-Bus match.");
    dbus_error_free(&err);
    return false;
  }

  return true;
}
Пример #5
0
static dbus_bool_t
match_name_owner_changed_signal (DBusConnection *conn, const char *bus_name, const char *lost_name, const char *acquired_name)
{
  int tries;
  DBusMessage *msg;
 
  for (tries = 0; tries < NUM_TRIES_TIL_FAIL; tries++)
    {
      _dbus_connection_lock (conn);
      _dbus_connection_do_iteration_unlocked (conn,
                                              DBUS_ITERATION_DO_READING |
                                              DBUS_ITERATION_DO_WRITING |
                                              DBUS_ITERATION_BLOCK,
                                              0);
      _dbus_connection_unlock (conn);
      msg = dbus_connection_pop_message (conn);
    
      if (msg != NULL)
        {
          if (dbus_message_is_signal (msg, 
              "org.freedesktop.DBus",
              "NameOwnerChanged"))
            {
              const char *n;
              const char *ln;
              const char *an;
              DBusError error;
              dbus_error_init (&error);

              dbus_message_get_args (msg, &error, DBUS_TYPE_STRING, &n, DBUS_TYPE_STRING, &ln, DBUS_TYPE_STRING, &an, DBUS_TYPE_INVALID);

              if (dbus_error_is_set (&error))
                {
                  fprintf (stderr, "Error getting args: %s\n", error.message);
                  dbus_error_free (&error);
                  dbus_message_unref (msg);
                  return FALSE;
                }

              if (strcmp (n, bus_name) == 0)
                {
                  if ((lost_name == NULL && strcmp (ln, "") == 0)
                        || strcmp (lost_name, ln) == 0)
                    {
                      if ((acquired_name == NULL && strcmp (an, "") == 0)
                            || strcmp (acquired_name, an) == 0)
                        {
                          dbus_message_unref (msg); 
                          break;
                        }
                      else
                        {
                          fprintf (stderr, "Error: name %s was expected to be acquired but we got %s instead\n", acquired_name, an);
                          dbus_message_unref (msg);
                          return FALSE;
                        }
                    }
                  else
                    {
                      fprintf (stderr, "Error: name %s was expected to be lost but we got %s instead\n", lost_name, ln);
                      dbus_message_unref (msg);
                      return FALSE;
                    }
                }
            }
          dbus_message_unref (msg);
        }
    }

  if (tries == NUM_TRIES_TIL_FAIL)
    {
      fprintf (stderr, "Did not recive the expected NameOwnerChanged signal!!!\n");
      return FALSE;
    }
  
  return TRUE;
}
Пример #6
0
/**
 * Try to open a new transport for the given address entry.  (This
 * opens a client-side-of-the-connection transport.)
 * 
 * @param entry the address entry
 * @param error location to store reason for failure.
 * @returns new transport of #NULL on failure.
 */
DBusTransport*
_dbus_transport_open (DBusAddressEntry *entry,
                      DBusError        *error)
{
  DBusTransport *transport;
  const char *expected_guid_orig;
  char *expected_guid;
  int i;
  DBusError tmp_error = DBUS_ERROR_INIT;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
  transport = NULL;
  expected_guid_orig = dbus_address_entry_get_value (entry, "guid");
  expected_guid = _dbus_strdup (expected_guid_orig);

  if (expected_guid_orig != NULL && expected_guid == NULL)
    {
      _DBUS_SET_OOM (error);
      return NULL;
    }

  for (i = 0; i < (int) _DBUS_N_ELEMENTS (open_funcs); ++i)
    {
      DBusTransportOpenResult result;

      _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
      result = (* open_funcs[i].func) (entry, &transport, &tmp_error);

      switch (result)
        {
        case DBUS_TRANSPORT_OPEN_OK:
          _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
          goto out;
          break;
        case DBUS_TRANSPORT_OPEN_NOT_HANDLED:
          _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
          /* keep going through the loop of open funcs */
          break;
        case DBUS_TRANSPORT_OPEN_BAD_ADDRESS:
          _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
          goto out;
          break;
        case DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT:
          _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
          goto out;
          break;
        }
    }

 out:
  
  if (transport == NULL)
    {
      if (!dbus_error_is_set (&tmp_error))
        _dbus_set_bad_address (&tmp_error,
                               NULL, NULL,
                               "Unknown address type (examples of valid types are \"tcp\" and on UNIX \"unix\")");
      
      _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
      dbus_move_error(&tmp_error, error);
      dbus_free (expected_guid);
    }
  else
    {
      _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);

      /* In the case of autostart the initial guid is NULL
       * and the autostart transport recursively calls
       * _dbus_open_transport wich returns a transport
       * with a guid.  That guid is the definitive one.
       *
       * FIXME: if more transports are added they may have
       * an effect on the expected_guid semantics (i.e. 
       * expected_guid and transport->expected_guid may
       * both have values).  This is very unlikely though
       * we should either throw asserts here for those 
       * corner cases or refactor the code so it is 
       * clearer on what is expected and what is not
       */
      if(expected_guid)
        transport->expected_guid = expected_guid;
    }

  return transport;
}
Пример #7
0
int main(int argc, char *argv[])
{
	GOptionContext *context;
	GError *error = NULL;
	DBusConnection *conn;
	DBusError err;
	guint signal;

	context = g_option_context_new(NULL);
	g_option_context_add_main_entries(context, options, NULL);

	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		if (error) {
			g_printerr("%s\n", error->message);
			g_error_free(error);
		} else
			g_printerr("An unknown error occurred\n");
		exit(1);
	}

	g_option_context_free(context);

	if (option_version) {
		printf("%s\n", VERSION);
		exit(0);
	}

	if (option_detach) {
		if (daemon(0, 0)) {
			perror("Can't start daemon");
			exit(1);
		}
	}

	if (mkdir(STATEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create state directory");
	}

	/*
	 * At some point the VPN stuff is migrated into VPN_STORAGEDIR
	 * and this mkdir() call can be removed.
	 */
	if (mkdir(STORAGEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create storage directory");
	}

	if (mkdir(VPN_STORAGEDIR, S_IRUSR | S_IWUSR | S_IXUSR |
				S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0) {
		if (errno != EEXIST)
			perror("Failed to create VPN storage directory");
	}

	umask(0077);

	main_loop = g_main_loop_new(NULL, FALSE);

	signal = setup_signalfd();

	dbus_error_init(&err);

	conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, VPN_SERVICE, &err);
	if (!conn) {
		if (dbus_error_is_set(&err)) {
			fprintf(stderr, "%s\n", err.message);
			dbus_error_free(&err);
		} else
			fprintf(stderr, "Can't register with system bus\n");
		exit(1);
	}

	g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);

	__connman_log_init(argv[0], option_debug, option_detach, false,
			"Connection Manager VPN daemon", VERSION);
	__connman_dbus_init(conn);

	if (!option_config)
		config_init(CONFIGMAINFILE);
	else
		config_init(option_config);

	__connman_inotify_init();
	__connman_agent_init();
	__vpn_provider_init(option_routes);
	__vpn_manager_init();
	__vpn_ipconfig_init();
	__vpn_rtnl_init();
	__connman_task_init();
	__connman_plugin_init(option_plugin, option_noplugin);
	__vpn_config_init();

	__vpn_rtnl_start();

	g_free(option_plugin);
	g_free(option_noplugin);

	g_main_loop_run(main_loop);

	g_source_remove(signal);

	__vpn_config_cleanup();
	__connman_plugin_cleanup();
	__connman_task_cleanup();
	__vpn_rtnl_cleanup();
	__vpn_ipconfig_cleanup();
	__vpn_manager_cleanup();
	__vpn_provider_cleanup();
	__connman_agent_cleanup();
	__connman_inotify_cleanup();
	__connman_dbus_cleanup();
	__connman_log_cleanup(false);

	dbus_connection_unref(conn);

	g_main_loop_unref(main_loop);

	g_free(option_debug);

	return 0;
}
Пример #8
0
    virtual int showNotify(const char *pcHeader, const char *pcBody)
    {
        int rc;
# ifdef VBOX_WITH_DBUS
        DBusConnection *conn;
        DBusMessage* msg = NULL;
        conn = dbus_bus_get (DBUS_BUS_SESSON, NULL);
        if (conn == NULL)
        {
            LogRelFlowFunc(("Could not retrieve D-BUS session bus!\n"));
            rc = VERR_INVALID_HANDLE;
        }
        else
        {
            msg = dbus_message_new_method_call("org.freedesktop.Notifications",
                                               "/org/freedesktop/Notifications",
                                               "org.freedesktop.Notifications",
                                               "Notify");
            if (msg == NULL)
            {
                LogRel(("Could not create D-BUS message!\n"));
                rc = VERR_INVALID_HANDLE;
            }
            else
                rc = VINF_SUCCESS;
        }
        if (RT_SUCCESS(rc))
        {
            uint32_t msg_replace_id = 0;
            const char *msg_app = "VBoxClient";
            const char *msg_icon = "";
            const char *msg_summary = pcHeader;
            const char *msg_body = pcBody;
            int32_t msg_timeout = -1;           /* Let the notification server decide */

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

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

            DBusError err;
            dbus_error_init(&err);

            DBusMessage *reply;
            reply = dbus_connection_send_with_reply_and_block(conn, msg,
                30 * 1000 /* 30 seconds timeout */, &err);
            if (dbus_error_is_set(&err))
            {
                LogRel(("D-BUS returned an error while sending the notification: %s", err.message));
            }
            else if (reply)
            {
                dbus_connection_flush(conn);
                dbus_message_unref(reply);
            }
            if (dbus_error_is_set(&err))
                dbus_error_free(&err);
        }
        if (msg != NULL)
            dbus_message_unref(msg);
# else
        /* TODO: Implement me */
        rc = VINF_SUCCESS;
# endif /* VBOX_WITH_DBUS */
        return rc;
    }
Пример #9
0
static DBusGProxy *dbus_connect (MoonshotError **error)
{
    DBusConnection  *dbconnection;
    DBusError        dbus_error;
    DBusGConnection *connection;
    DBusGProxy      *g_proxy;
    GError          *g_error = NULL;
    dbus_bool_t      name_has_owner;

    g_return_val_if_fail (*error == NULL, NULL);

    dbus_error_init (&dbus_error);

    /* Check for moonshot server and start the service if possible. We use
     * libdbus here because dbus-glib doesn't handle autostarting the service.
     * If/when we move to GDBus this code can become a one-liner.
     */

    if (is_setid()) {
        *error = moonshot_error_new (MOONSHOT_ERROR_IPC_ERROR,
	                             "Cannot use IPC while setid");
        return NULL;
    }
#ifdef IPC_DBUS_GLIB
    if (getenv("DISPLAY")==NULL) {
        connection = dbus_launch_moonshot();
        if (connection == NULL) {
            *error = moonshot_error_new (MOONSHOT_ERROR_IPC_ERROR,
                                         "Headless dbus launch failed");
            return NULL;
        }
    } else
#endif
    {
        connection = dbus_g_bus_get (DBUS_BUS_SESSION, &g_error);

        if (g_error_matches(g_error, DBUS_GERROR, DBUS_GERROR_NOT_SUPPORTED)) {
            /*Generally this means autolaunch failed because probably DISPLAY is unset*/
            connection = dbus_launch_moonshot();
            if (connection != NULL) {
                g_error_free(g_error);
                g_error = NULL;
            }
        }
        if (g_error != NULL) {
            *error = moonshot_error_new (MOONSHOT_ERROR_IPC_ERROR,
                                         "DBus error: %s",
                                         g_error->message);
            g_error_free (g_error);
            return NULL;
        }
    }


    dbconnection = dbus_g_connection_get_connection(connection);
    name_has_owner  = dbus_bus_name_has_owner (dbconnection,
                                               MOONSHOT_DBUS_NAME,
                                               &dbus_error);

    if (dbus_error_is_set (&dbus_error)) {
        *error = moonshot_error_new (MOONSHOT_ERROR_IPC_ERROR,
                                     "DBus error: %s",
                                     dbus_error.message);
        dbus_error_free (&dbus_error);
        return NULL;
    }

    if (! name_has_owner) {
        dbus_bus_start_service_by_name (dbconnection,
                                        MOONSHOT_DBUS_NAME,
                                        0,
                                        NULL,
                                        &dbus_error);

        if (dbus_error_is_set (&dbus_error)) {
            if (strcmp (dbus_error.name + 27, "ServiceUnknown") == 0) {
                /* Missing .service file; the moonshot-ui install is broken */
                *error = moonshot_error_new (MOONSHOT_ERROR_UNABLE_TO_START_SERVICE,
                                             "The Moonshot service was not found. "
                                             "Please make sure that moonshot-ui is "
                                             "correctly installed.");
            } else {
                *error = moonshot_error_new (MOONSHOT_ERROR_IPC_ERROR,
                                             "DBus error: %s",
                                             dbus_error.message);
            }
            dbus_error_free (&dbus_error);
            return NULL;
        }
    }

    /* Now the service should be running */
    g_error = NULL;

    g_proxy = dbus_g_proxy_new_for_name_owner (connection,
                                               MOONSHOT_DBUS_NAME,
                                               MOONSHOT_DBUS_PATH,
                                               MOONSHOT_DBUS_NAME,
                                               &g_error);

    if (g_error != NULL) {
        *error = moonshot_error_new (MOONSHOT_ERROR_IPC_ERROR,
                                     "DBus error: %s",
                                     g_error->message);
        g_error_free (g_error);
        return NULL;
    }

    return g_proxy; 
}
Пример #10
0
static DBusHandlerResult
message_filter(DBusConnection * connection, DBusMessage * message, void *data)
{
    struct systemd_logind_info *info = data;
    struct xf86_platform_device *pdev = NULL;
    InputInfoPtr pInfo = NULL;
    int ack = 0, pause = 0, fd = -1;
    DBusError error;
    dbus_int32_t major, minor;
    char *pause_str;

    dbus_error_init(&error);

    if (dbus_message_is_signal(message,
                               "org.freedesktop.DBus", "NameOwnerChanged")) {
        char *name, *old_owner, *new_owner;

        dbus_message_get_args(message, &error,
                              DBUS_TYPE_STRING, &name,
                              DBUS_TYPE_STRING, &old_owner,
                              DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID);
        if (dbus_error_is_set(&error)) {
            LogMessage(X_ERROR, "systemd-logind: NameOwnerChanged: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        if (name && strcmp(name, "org.freedesktop.login1") == 0)
            FatalError("systemd-logind disappeared (stopped/restarted?)\n");

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (strcmp(dbus_message_get_path(message), info->session) != 0)
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    if (dbus_message_is_signal(message, "org.freedesktop.login1.Session",
                               "PauseDevice")) {
        if (!dbus_message_get_args(message, &error,
                               DBUS_TYPE_UINT32, &major,
                               DBUS_TYPE_UINT32, &minor,
                               DBUS_TYPE_STRING, &pause_str,
                               DBUS_TYPE_INVALID)) {
            LogMessage(X_ERROR, "systemd-logind: PauseDevice: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }

        if (strcmp(pause_str, "pause") == 0) {
            pause = 1;
            ack = 1;
        }
        else if (strcmp(pause_str, "force") == 0) {
            pause = 1;
        }
        else if (strcmp(pause_str, "gone") == 0) {
            /* Device removal is handled through udev */
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
        else {
            LogMessage(X_WARNING, "systemd-logind: unknown pause type: %s\n",
                       pause_str);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
    }
    else if (dbus_message_is_signal(message, "org.freedesktop.login1.Session",
                                    "ResumeDevice")) {
        if (!dbus_message_get_args(message, &error,
                                   DBUS_TYPE_UINT32, &major,
                                   DBUS_TYPE_UINT32, &minor,
                                   DBUS_TYPE_UNIX_FD, &fd,
                                   DBUS_TYPE_INVALID)) {
            LogMessage(X_ERROR, "systemd-logind: ResumeDevice: %s\n",
                       error.message);
            dbus_error_free(&error);
            return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
        }
    } else
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;

    LogMessage(X_INFO, "systemd-logind: got %s for %u:%u\n",
               pause ? "pause" : "resume", major, minor);

    pdev = xf86_find_platform_device_by_devnum(major, minor);        
    if (!pdev)
        pInfo = systemd_logind_find_info_ptr_by_devnum(xf86InputDevs,
                                                       major, minor);
    if (!pdev && !pInfo) {
        LogMessage(X_WARNING, "systemd-logind: could not find dev %u:%u\n",
                   major, minor);
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (pause) {
        /* Our VT_PROCESS usage guarantees we've already given up the vt */
        info->active = info->vt_active = FALSE;
        /* Note the actual vtleave has already been handled by xf86Events.c */
        if (pdev)
            pdev->flags |= XF86_PDEV_PAUSED;
        else {
            close(pInfo->fd);
            systemd_logind_set_input_fd_for_all_devs(major, minor, -1, FALSE);
        }
        if (ack)
            systemd_logind_ack_pause(info, major, minor);
    }
    else {
        /* info->vt_active gets set by systemd_logind_vtenter() */
        info->active = TRUE;

        if (pdev)
            pdev->flags &= ~XF86_PDEV_PAUSED;
        else
            systemd_logind_set_input_fd_for_all_devs(major, minor, fd,
                                                     info->vt_active);

        /* Always call vtenter(), in case there are only legacy video devs */
        systemd_logind_vtenter();
    }
    return DBUS_HANDLER_RESULT_HANDLED;
}
Пример #11
0
static void
connect_hook(DBusConnection *connection, void *data)
{
    struct systemd_logind_info *info = data;
    DBusError error;
    DBusMessage *msg = NULL;
    DBusMessage *reply = NULL;
    dbus_int32_t arg;
    char *session = NULL;

    dbus_error_init(&error);

    msg = dbus_message_new_method_call("org.freedesktop.login1",
            "/org/freedesktop/login1", "org.freedesktop.login1.Manager",
            "GetSessionByPID");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    arg = getpid();
    if (!dbus_message_append_args(msg, DBUS_TYPE_UINT32, &arg,
                                  DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg,
                                                      DBUS_TIMEOUT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: failed to get session: %s\n",
                   error.message);
        goto cleanup;
    }
    dbus_message_unref(msg);

    if (!dbus_message_get_args(reply, &error, DBUS_TYPE_OBJECT_PATH, &session,
                               DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: GetSessionByPID: %s\n",
                   error.message);
        goto cleanup;
    }
    session = XNFstrdup(session);

    dbus_message_unref(reply);
    reply = NULL;


    msg = dbus_message_new_method_call("org.freedesktop.login1",
            session, "org.freedesktop.login1.Session", "TakeControl");
    if (!msg) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    arg = FALSE; /* Don't forcibly take over over the session */
    if (!dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &arg,
                                  DBUS_TYPE_INVALID)) {
        LogMessage(X_ERROR, "systemd-logind: out of memory\n");
        goto cleanup;
    }

    reply = dbus_connection_send_with_reply_and_block(connection, msg,
                                                      DBUS_TIMEOUT, &error);
    if (!reply) {
        LogMessage(X_ERROR, "systemd-logind: TakeControl failed: %s\n",
                   error.message);
        goto cleanup;
    }

    dbus_bus_add_match(connection,
        "type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus'",
        &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }

    /*
     * HdG: This is not useful with systemd <= 208 since the signal only
     * contains invalidated property names there, rather than property, val
     * pairs as it should.  Instead we just use the first resume / pause now.
     */
#if 0
    snprintf(match, sizeof(match),
        "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='%s'",
        session);
    dbus_bus_add_match(connection, match, &error);
    if (dbus_error_is_set(&error)) {
        LogMessage(X_ERROR, "systemd-logind: could not add match: %s\n",
                   error.message);
        goto cleanup;
    }
#endif

    if (!dbus_connection_add_filter(connection, message_filter, info, NULL)) {
        LogMessage(X_ERROR, "systemd-logind: could not add filter: %s\n",
                   error.message);
        goto cleanup;
    }

    LogMessage(X_INFO, "systemd-logind: took control of session %s\n",
               session);
    info->conn = connection;
    info->session = session;
    info->vt_active = info->active = TRUE; /* The server owns the vt during init */
    session = NULL;

cleanup:
    free(session);
    if (msg)
        dbus_message_unref(msg);
    if (reply)
        dbus_message_unref(reply);
    dbus_error_free(&error);
}
Пример #12
0
void* DBusCreate(FcitxInstance* instance)
{
    FcitxDBus *dbusmodule = (FcitxDBus*) fcitx_utils_malloc0(sizeof(FcitxDBus));
    FcitxAddon* dbusaddon = FcitxAddonsGetAddonByName(FcitxInstanceGetAddons(instance), FCITX_DBUS_NAME);
    dbusmodule->owner = instance;

    DBusError err;

    if (FcitxInstanceIsTryReplace(instance)) {
        fcitx_utils_launch_tool("fcitx-remote", "-e");
        sleep(1);
    }

    dbus_threads_init_default();

    // first init dbus
    dbus_error_init(&err);

    int retry = 0;
    DBusConnection* conn = NULL;
    char* servicename = NULL;
    asprintf(&servicename, "%s-%d", FCITX_DBUS_SERVICE,
             fcitx_utils_get_display_number());

    /* do session dbus initialize */
    do {
        if (!getenv("DISPLAY") && !getenv("DBUS_SESSION_BUS_ADDRESS")) {
            FcitxLog(WARNING, "Without DISPLAY or DBUS_SESSION_BUS_ADDRESS session bus will not work");
            break;
        }
        /* try to get session dbus */
        while (1) {
            conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
            if (dbus_error_is_set(&err)) {
                FcitxLog(WARNING, "Connection Error (%s)", err.message);
                dbus_error_free(&err);
                dbus_error_init(&err);
            }

            if (NULL == conn && retry < MAX_RETRY_TIMES) {
                retry ++;
                sleep(RETRY_INTERVAL * retry);
            } else {
                break;
            }
        }

        if (NULL == conn) {
            break;
        }

        if (!dbus_connection_add_filter(conn, DBusModuleFilter, dbusmodule, NULL))
            break;

        if (!dbus_connection_set_watch_functions(conn, DBusAddWatch, DBusRemoveWatch,
                NULL, &dbusmodule->watches, NULL)) {
            FcitxLog(WARNING, "Add Watch Function Error");
            dbus_error_free(&err);
            dbus_error_init(&err);
            dbus_connection_unref(conn);
            conn = NULL;
            break;
        }

        /* from here we know dbus connection is successful, now we need to register the service */
        dbus_connection_set_exit_on_disconnect(conn, FALSE);
        dbusmodule->conn = conn;

        boolean request_retry = false;

        int replaceCountdown = FcitxInstanceIsTryReplace(instance) ? 3 : 0;
        FcitxInstanceResetTryReplace(instance);
        do {
            request_retry = false;

            // request a name on the bus
            int ret = dbus_bus_request_name(conn, servicename,
                                            DBUS_NAME_FLAG_DO_NOT_QUEUE,
                                            &err);
            if (dbus_error_is_set(&err)) {
                FcitxLog(WARNING, "Name Error (%s)", err.message);
                goto dbus_init_failed;
            }
            if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
                FcitxLog(WARNING, "DBus Service Already Exists");

                if (replaceCountdown > 0) {
                    replaceCountdown --;
                    fcitx_utils_launch_tool("fcitx-remote", "-e");

                    /* sleep for a while and retry */
                    sleep(1);

                    request_retry = true;
                    continue;
                }

                /* if we know fcitx exists, we should exit. */
                dbus_error_free(&err);
                free(servicename);
                free(dbusmodule);

                FcitxInstanceEnd(instance);
                return NULL;
            }
        } while (request_retry);

        dbus_connection_flush(dbusmodule->conn);
    } while(0);

    DBusConnection* privconn = NULL;
    do {
        int noPrivateDBus = fcitx_utils_get_boolean_env("FCITX_NO_PRIVATE_DBUS", false);
        if (noPrivateDBus)
            break;

        char* file;
        FILE* dbusfp = FcitxXDGGetFileWithPrefix("dbus", "daemon.conf", "r", &file);
        if (dbusfp) {
            fclose(dbusfp);
        }
        else {
            free(file);
            file = NULL;
        }

        dbusmodule->daemon = DBusLaunch(file);
        fcitx_utils_free(file);
        if (dbusmodule->daemon.pid == 0)
            break;

        privconn = dbus_connection_open(dbusmodule->daemon.address, &err);

        if (dbus_error_is_set(&err)) {
            FcitxLog(ERROR, "Private dbus daemon connection error (%s)",
                     err.message);
            break;
        }

        dbus_bus_register(privconn, &err);

        if (dbus_error_is_set(&err)) {
            FcitxLog(ERROR, "Private dbus bus register error (%s)", err.message);
            break;
        }

        int ret = dbus_bus_request_name(privconn, servicename,
                                        DBUS_NAME_FLAG_DO_NOT_QUEUE,
                                        &err);

        if (dbus_error_is_set(&err)) {
            FcitxLog(WARNING, "Private Name Error (%s)", err.message);
            break;
        }
        if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
            FcitxLog(ERROR, "Private DBus Service Already Exists, fcitx being hacked?");
            break;
        }

        if (!dbus_connection_add_filter(privconn, DBusModuleFilter, dbusmodule, NULL))
            break;

        if (!dbus_connection_set_watch_functions(privconn, DBusAddWatch, DBusRemoveWatch,
                NULL, &dbusmodule->watches, NULL)) {
            FcitxLog(WARNING, "Add Watch Function Error");
            break;
        }

        char* addressFile = NULL;
        char* localMachineId = dbus_get_local_machine_id();
        asprintf(&addressFile, "%s-%d", localMachineId,
                 fcitx_utils_get_display_number());
        dbus_free(localMachineId);

        FILE* fp = FcitxXDGGetFileUserWithPrefix("dbus", addressFile, "w", NULL);
        free(addressFile);
        if (!fp)
            break;

        fprintf(fp, "%s", dbusmodule->daemon.address);
        fwrite("\0", sizeof(char), 1, fp);
        pid_t curPid = getpid();
        fwrite(&dbusmodule->daemon.pid, sizeof(pid_t), 1, fp);
        fwrite(&curPid, sizeof(pid_t), 1, fp);
        fclose(fp);

        dbusmodule->privconn = privconn;

        char* command = fcitx_utils_get_fcitx_path_with_filename("bindir", "/fcitx-dbus-watcher");
        char* pidstring = NULL;
        asprintf(&pidstring, "%d", dbusmodule->daemon.pid);
        char* args[] = {
            command,
            dbusmodule->daemon.address,
            pidstring,
            NULL
        };
        fcitx_utils_start_process(args);
        free(command);
        free(pidstring);

    } while(0);

    if (!dbusmodule->privconn) {
        if (privconn) {
            dbus_connection_unref(privconn);
            DBusKill(&dbusmodule->daemon);
        }
    }

    FcitxModuleAddFunction(dbusaddon, DBusGetConnection);
    FcitxModuleAddFunction(dbusaddon, DBusGetPrivateConnection);
    dbus_error_free(&err);

    dbusmodule->serviceName = servicename;

    return dbusmodule;

dbus_init_failed:
    dbus_error_free(&err);
    fcitx_utils_free(servicename);
    if (conn)
        dbus_connection_unref(conn);
    DBusKill(&dbusmodule->daemon);
    fcitx_utils_free(dbusmodule);
    return NULL;
}
Пример #13
0
void listen_signal()
{
    DBusMessage *msg;
    DBusMessageIter arg;
    DBusConnection *connection;
    DBusError err;
    int ret;
    char *sigvalue;

    //step 1. connect DBus
    dbus_error_init(&err);
    connection = dbus_bus_get(DBUS_BUS_SESSION, &err);
    if (dbus_error_is_set(&err)) {
        fprintf(stderr, "Connection Error %s\n", err.message);
        dbus_error_free(&err);
    }
    if (connection == NULL) {
        return;
    }

    //step 2. [OPTION] Assign a known name for connection
    ret = dbus_bus_request_name(connection, "test.singal.dest", DBUS_NAME_FLAG_REPLACE_EXISTING, &err);
    if (dbus_error_is_set(&err)) {
        fprintf(stderr, "Name Error %s\n", err.message);
        dbus_error_free(&err);
    }
    if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
        return ;
    }

    //step 3. Notify DBus daemon, listen test.signal.Type signal
    dbus_bus_add_match(connection, "type='signal', interface='test.signal.Type'", &err);
    dbus_connection_flush(connection);
    if (dbus_error_is_set(&err)) {
        fprintf(stderr, "Match Error %s\n", err.message);
        dbus_error_free(&err);
    }

    //step 4. listen in loop per 1s.
    while (1) {
        dbus_connection_read_write(connection, 0);
        msg = dbus_connection_pop_message(connection);
        if (msg == NULL) {
            sleep(1);
            continue;
        }

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

    }//End of while
}
Пример #14
0
int
add_network_printer(LibHalContext *ctx, char *base, char *hostaddr,
		char *device, char *community)
{
	DBusError error;
	int rc = -1;
	char udi[128];
	char *tmp_udi = NULL;
	static char *parent = NULL;
	char *manufacturer = NULL, *model = NULL, *description = NULL,
	     *uri = NULL, *sn, *serial;

	sn = serial = pseudo_serialno_from_addr(hostaddr);

	if (parent == NULL)
		parent = getenv("UDI");

	dbus_error_init(&error);

	network_device_name_to_udi(udi, sizeof (udi), base, serial, NULL);

	if (libhal_device_exists(ctx, udi, &error) == TRUE)
		goto out;

	if ((tmp_udi = libhal_new_device(ctx, &error)) == NULL)
		goto out;

	snmp_printer_info(hostaddr, community, &manufacturer, &model,
			&description, &serial, NULL, &uri);

	libhal_device_set_property_string(ctx, tmp_udi,
			"info.parent", parent, &error);

	libhal_device_set_property_string(ctx, tmp_udi,
			"info.category", "printer", &error);

	libhal_device_property_strlist_append(ctx, tmp_udi,
				"info.capabilities", "printer", &error);
	libhal_device_property_strlist_append(ctx, tmp_udi,
				"info.capabilities", "network_device", &error);

	libhal_device_set_property_string(ctx, tmp_udi,
			"network_device.address", hostaddr, &error);

	if ((community != NULL) && (strcasecmp(community, "public") != 0))
		libhal_device_set_property_string(ctx, tmp_udi,
			"network_device.snmp_community", community, &error);

	if ((uri != NULL) || (device != NULL))
		libhal_device_set_property_string(ctx, tmp_udi,
			"printer.device", (uri ? uri : device), &error);

	if (serial != NULL)
		libhal_device_set_property_string(ctx, tmp_udi,
			"printer.serial", serial, &error);

	if (manufacturer != NULL)
		libhal_device_set_property_string(ctx, tmp_udi,
			"printer.vendor", manufacturer, &error);

	if (model != NULL)
		libhal_device_set_property_string(ctx, tmp_udi,
			"printer.product", model, &error);

	if (description != NULL)
		libhal_device_set_property_string(ctx, tmp_udi,
			"printer.description", description, &error);

	/* commit the changes to the new UDI */
	rc = libhal_device_commit_to_gdl(ctx, tmp_udi, udi, &error);

out:
	HAL_DEBUG(("result: %s (%s): %s, %s, %s, %s, %s", hostaddr, udi,
		NP(manufacturer), NP(model), NP(description), NP(serial),
		NP(uri)));

	if (tmp_udi != NULL)
		free(tmp_udi);
	if (manufacturer != NULL)
		free(manufacturer);
	if (model != NULL)
		free(model);
	if (description != NULL)
		free(description);
	if (uri != NULL)
		free(uri);
	if (sn != NULL)
		free(sn);

	if (dbus_error_is_set(&error)) {
		HAL_WARNING(("%s: %s", error.name, error.message));
		dbus_error_free(&error);
	}

	HAL_DEBUG(("add: %s (%s)", hostaddr, udi));

	return (rc);
}
Пример #15
0
static void track_pulseaudio_on_dbus(pa_context *c, DBusBusType type, pa_dbus_wrap_connection **conn) {
    DBusError error;

    pa_assert(c);
    pa_assert(conn);

    dbus_error_init(&error);

    if (!(*conn = pa_dbus_wrap_connection_new(c->mainloop, c->use_rtclock, type, &error)) || dbus_error_is_set(&error)) {
        pa_log_warn("Unable to contact DBUS: %s: %s", error.name, error.message);
        goto fail;
    }

    if (!dbus_connection_add_filter(pa_dbus_wrap_connection_get(*conn), filter_cb, c, NULL)) {
        pa_log_warn("Failed to add filter function");
        goto fail;
    }
    c->filter_added = TRUE;

    if (pa_dbus_add_matches(
                pa_dbus_wrap_connection_get(*conn), &error,
                "type='signal',sender='" DBUS_SERVICE_DBUS "',interface='" DBUS_INTERFACE_DBUS "',member='NameOwnerChanged',arg0='org.pulseaudio.Server',arg1=''", NULL) < 0) {

        pa_log_warn("Unable to track org.pulseaudio.Server: %s: %s", error.name, error.message);
        goto fail;
    }

    return;

fail:
    if (*conn) {
        pa_dbus_wrap_connection_free(*conn);
        *conn = NULL;
    }

    dbus_error_free(&error);
}
Пример #16
0
static    DBusMessage *
rdc_dbus_method_add_radius(
					DBusConnection *conn, 
					DBusMessage *msg, 
					void *user_data )
{
		rdc_ins_t *rdcins = NULL;
		DBusMessage* reply = NULL;
		DBusMessageIter iter = {0};
		DBusError		err = {0};
		struct radius_srv_coa *radius_srv = NULL;
		
		unsigned long auth_ip=0;
		unsigned short auth_port=0;
		char *auth_secret=NULL;
		
		int ret = -1;
	
		reply = dbus_message_new_method_return(msg);
		if (NULL == reply) {
			eag_log_err("rdc_dbus_method_add_radius "\
						"DBUS new reply message error!\n");
			return NULL;
		}
	
		rdcins = (rdc_ins_t *)user_data;
		if (NULL == rdcins){
			eag_log_err("rdc_dbus_method_add_radius user_data error!");
			//return reply;
			ret = EAG_ERR_UNKNOWN;
			goto replyx;
		}
		
		dbus_error_init(&err);
		if (!(dbus_message_get_args(msg ,&err,
									DBUS_TYPE_UINT32, &auth_ip,
									DBUS_TYPE_UINT16, &auth_port,
									DBUS_TYPE_STRING, &auth_secret,							
									DBUS_TYPE_INVALID))){
			eag_log_err("rdc_dbus_method_add_radius "\
						"unable to get input args\n");
			if (dbus_error_is_set(&err)) {
				eag_log_err("rdc_dbus_method_add_radius %s raised:%s\n",
								err.name, err.message);
				dbus_error_free(&err);
			}
			ret = EAG_ERR_DBUS_FAILED;
			goto replyx;
		}
	
		radius_srv = rdc_coa_check_radius_srv(&(rdcins->radius_conf),auth_ip,auth_port,auth_secret);
		if( NULL != radius_srv ){
			ret = EAG_ERR_RADIUS_DOAMIN_AREADY_EXIST;
			eag_log_err("eag_dbus_method_add_radius domain already exist!");
		}
		else if( MAX_RADIUS_SRV_NUM == rdcins->radius_conf.current_num ){
			ret = EAG_ERR_RADIUS_MAX_NUM_LIMITE;
			eag_log_err("eag_dbus_method_add_radius failed because max num limite!");
		}
		else{
			radius_srv = rdc_coa_conf_radius_srv(&(rdcins->radius_conf));
			rdc_coa_set_radius_srv(radius_srv,auth_ip,auth_port,
								auth_secret,strlen(auth_secret));
			ret = EAG_RETURN_OK;
		}
	
	replyx:
		dbus_message_iter_init_append(reply, &iter);
		dbus_message_iter_append_basic(&iter,
										DBUS_TYPE_INT32, &ret);
		return reply;
}
Пример #17
0
/*
 * Receive the signals from the bus
 */
void receive()
{
	DBusMessage *msg;
	DBusMessageIter iter;
	DBusConnection *conn;
	DBusError err;
	int ret;

	Item *item = (Item *)malloc(sizeof(Item));
	if (item == NULL)
	{
		exit(1);
	}
	char *s = (char *)malloc(512 * sizeof(char));
	if (s == NULL)
	{
		exit(1);
	}

	printf("Listening for signals\n");

	// initialize the errors
	dbus_error_init(&err);

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

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

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

	// loop listening for signals being emmitted
	while (1)
	{
		// 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 (msg == NULL)
		{
			sleep(1);
			continue;
		}

		// signals for adding
		// check if the message is a signal from the correct interface and with the correct name
		if (dbus_message_is_signal(msg, "queue.msg.Handler", "Add"))
		{

			// read the parameters
			if (!dbus_message_iter_init(msg, &iter))
			{
				fprintf(stderr, "Message Has No Parameters\n");
			}
			else
			{
				dbus_uint32_t v;
				dbus_message_iter_get_basic(&iter, &s);
				strcpy(item->name, s);
				dbus_message_iter_next(&iter);  // moves the iter to read next param
				dbus_message_iter_get_basic(&iter, &v);
				item->value = v;
			}

			int n = random_add_items(queue, item);
			if (n != -1)
			{
				printf("Added an item with name \"%s\" valued (%d) at position (%d)\n", 
				       item->name, item->value, n);
			}
			else
			{
				exit(1);
			}
		}

		// methods for removing
		// check if the message is a method call from the correct interface and with the correct name
		else if (dbus_message_is_method_call(msg, "queue.msg.Handler", "Remove"))
		{
			int n = random_remove_items(queue);
			if (n != -1)
			{
				printf("Removed an item from position (%d)\n", n);
			}
			else
			{
				exit(1);
			}
		}

		// free the message
		dbus_message_unref(msg);
	}

	// free the item
	free(item);
	item = NULL;
	// free the s
	free(s);
	s = NULL;
}
Пример #18
0
DBusMessage *
rdc_dbus_method_delete_radius(
			    DBusConnection *conn, 
			    DBusMessage *msg, 
			    void *user_data )
{
	rdc_ins_t *rdcins = NULL;
	DBusMessage* reply = NULL;
	DBusMessageIter iter = {0};
	DBusError		err = {0};
	struct radius_srv_coa *radius_srv = NULL;
	
	unsigned long auth_ip=0;
	unsigned short auth_port=0;
	char *auth_secret=NULL;
	
	int ret = -1;

	reply = dbus_message_new_method_return(msg);
	if (NULL == reply) {
		eag_log_err("rdc_dbus_method_set_portal_port "\
					"DBUS new reply message error!\n");
		return NULL;
	}

	rdcins = ( rdc_ins_t *)user_data;
	if( NULL == rdcins ){
		eag_log_err("rdc_dbus_method_add_radius  user_data  error!");
		//return reply;
		ret = EAG_ERR_UNKNOWN;
		goto replyx;
	}
	
	dbus_error_init(&err);
	if (!(dbus_message_get_args(msg ,&err,
									DBUS_TYPE_UINT32, &auth_ip,
									DBUS_TYPE_UINT16, &auth_port,
									DBUS_TYPE_STRING, &auth_secret,							
									DBUS_TYPE_INVALID))){
		eag_log_err("rdc_dbus_method_del_radius "\
					"unable to get input args\n");
		if (dbus_error_is_set(&err)) {
			eag_log_err("rdc_dbus_method_del_radius %s raised:%s\n",
							err.name, err.message);
			dbus_error_free(&err);
		}
		ret = EAG_ERR_DBUS_FAILED;
		goto replyx;
	}

	radius_srv = rdc_coa_check_radius_srv(&(rdcins->radius_conf),auth_ip,auth_port,auth_secret);
	if( NULL == radius_srv ){
		ret = EAG_ERR_RADIUS_DOAMIN_NOT_EXIST;
		eag_log_err("rdc_dbus_method_del_radius ip,port,secret not exist!");
	}
	else{
		ret = rdc_coa_del_radius_srv( &(rdcins->radius_conf),auth_ip,auth_port,auth_secret);
	}

replyx:
	dbus_message_iter_init_append(reply, &iter);
	dbus_message_iter_append_basic(&iter,
									DBUS_TYPE_INT32, &ret);
	return reply;
}
Пример #19
0
void listen_signal()
{
    DBusMessage * msg;
    DBusMessageIter arg;
    DBusConnection * connection;
    DBusError err;
    int ret;
    char * sigvalue;

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

   //步骤2:给连接名分配一个可记忆名字test.singal.dest作为Bus name,这个步骤不是必须的,但推荐这样处理 
/*
    ret = dbus_bus_request_name(connection,"test.singal.dest",DBUS_NAME_FLAG_REPLACE_EXISTING,&err);
    if(dbus_error_is_set(&err)){
        fprintf(stderr,"Name Error %s/n",err.message);
        dbus_error_free(&err);
    }
    if(ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER){
        printf("dbus request name is not primary owner.\n");
        return;
    }
*/
    //步骤3:通知D-Bus daemon,希望监听来行接口test.signal.Type的信号 
    dbus_bus_add_match(connection,"type='signal',interface='test.signal.Type'",&err); 
    //实际需要发送东西给daemon来通知希望监听的内容,所以需要flush 
    dbus_connection_flush(connection); 
    if(dbus_error_is_set(&err)){
        fprintf(stderr,"Match Error %s/n",err.message);
        dbus_error_free(&err);
    }
    
    //步骤4:在循环中监听,每隔开1秒,就去试图自己的连接中获取这个信号。这里给出的是中连接中获取任何消息的方式,所以获取后去检查一下这个消息是否我们期望的信号,并获取内容。我们也可以通过这个方式来获取method call消息。 
    gint cnt = 0;
    while(1){
        dbus_connection_read_write(connection,0); 
        msg = dbus_connection_pop_message (connection);
        if(msg == NULL){
            sleep(1);
            //printf("cnt:%d\n", cnt++);
            continue;
        }
    printf("message type: %d\n", dbus_message_get_type(msg));
    printf("message member: %s\n", dbus_message_get_member(msg));

        if(dbus_message_is_signal(msg,"test.signal.Type","Test") ){
            if(!dbus_message_iter_init(msg,&arg) )
                fprintf(stderr,"Message Has no Param");
            else if(dbus_message_iter_get_arg_type(&arg) != DBUS_TYPE_STRING) 
                g_printerr("Param is not string");
            else
                dbus_message_iter_get_basic(&arg,&sigvalue); 
            printf("Got Singal with value : %s\n",sigvalue);
        }
        dbus_message_unref(msg);
    }//End of while
    printf("end of receiver.");
}
Пример #20
0
static DBusMessage *
rdc_dbus_method_get_radius_conf(
			    DBusConnection *conn, 
			    DBusMessage *msg, 
			    void *user_data )
{
	rdc_ins_t *rdcins = NULL;
	DBusMessage* reply = NULL;
	DBusMessageIter iter = {0};
	DBusError  err = {0};
	struct  radius_srv_coa * radius_srv = NULL;
	int num=0;
	
	char *domain=NULL;
	char *auth_secret=NULL;
	int ret = -1;

	reply = dbus_message_new_method_return(msg);
	if (NULL == reply) {
		eag_log_err("rdc_dbus_method_get_radius_conf "\
					"DBUS new reply message error!\n");
		return NULL;
	}

	rdcins = ( rdc_ins_t *)user_data;
	if( NULL == rdcins ){
		eag_log_err("rdc_dbus_method_get_radius_conf user_data error!");
		//return reply;
		ret = EAG_ERR_UNKNOWN;
		goto replyx;
	}
	
	dbus_error_init(&err);
	if (!(dbus_message_get_args(msg ,&err,
								DBUS_TYPE_STRING, &domain,						
								DBUS_TYPE_INVALID))){
		eag_log_err("rdc_dbus_method_get_radius_conf "\
					"unable to get input args\n");
		if (dbus_error_is_set(&err)) {
			eag_log_err("rdc_dbus_method_get_radius_conf %s raised:%s\n",
							err.name, err.message);
			dbus_error_free(&err);
		}
		ret = EAG_ERR_DBUS_FAILED;
		goto replyx;
	}

	eag_log_info("rdc_dbus_method_get_radius_conf domain=%s,end", domain );
	if( 0 == strlen(domain)){
		/*get all radius configuration*/
		num = rdcins->radius_conf.current_num;
		ret = EAG_RETURN_OK;
		radius_srv = &(rdcins->radius_conf.radius_srv[0]);
	}

replyx:
	dbus_message_iter_init_append(reply, &iter);
	dbus_message_iter_append_basic(&iter,
									DBUS_TYPE_INT32, &ret);

	if( EAG_RETURN_OK == ret ){
		dbus_message_iter_append_basic(&iter,
									DBUS_TYPE_UINT32, &num);
	}
	if( EAG_RETURN_OK == ret && num > 0 ){
		int i;
		DBusMessageIter  iter_array;
		
		dbus_message_iter_open_container (&iter,
									DBUS_TYPE_ARRAY,
										DBUS_STRUCT_BEGIN_CHAR_AS_STRING											
											 DBUS_TYPE_UINT32_AS_STRING	
											 DBUS_TYPE_UINT16_AS_STRING
											 DBUS_TYPE_STRING_AS_STRING																
										DBUS_STRUCT_END_CHAR_AS_STRING,
									&iter_array);

		for( i=0; i<num; i++ ){
			DBusMessageIter iter_struct;
			dbus_message_iter_open_container (&iter_array,
										DBUS_TYPE_STRUCT,
										NULL,
										&iter_struct);
			/*domain = radius_srv[i].domain;
			eag_log_info("eag_dbus_method_get_radius_conf add domain %s", domain );
			dbus_message_iter_append_basic(&iter_struct,
											DBUS_TYPE_STRING, &domain);
			*/
			/*auth*/
			dbus_message_iter_append_basic(&iter_struct,
											DBUS_TYPE_UINT32, &radius_srv[i].auth_ip);			
			dbus_message_iter_append_basic(&iter_struct,
											DBUS_TYPE_UINT16, &radius_srv[i].auth_port);
			auth_secret = radius_srv[i].auth_secret;
			dbus_message_iter_append_basic(&iter_struct,
											DBUS_TYPE_STRING, &auth_secret);

			dbus_message_iter_close_container (&iter_array, &iter_struct);

		}
		dbus_message_iter_close_container (&iter, &iter_array);
	}
	
	return reply;
}
int main(int argc, char **argv)
{

    DBusMessage *l_msg;
    DBusConnection *l_conn;
    DBusError l_err;
    int l_ret;

    printf("Listening for method calls!%s","\n");

    // initialise the error
    dbus_error_init(&l_err);

    // connect to the bus and check for errors
    l_conn = dbus_bus_get(DBUS_BUS_SYSTEM, &l_err);
    if (dbus_error_is_set(&l_err)) {
        printf("Connection Error (%s)\n",l_err.message);
        dbus_error_free(&l_err);
    }
    if (NULL == l_conn) {
        printf("Connection Null!\n");
        exit(1);
    }

    // request our name on the bus and check for errors
    l_ret = dbus_bus_request_name(l_conn,
                                  "org.GENIVI.std_intf_test",
                                  DBUS_NAME_FLAG_REPLACE_EXISTING,
                                  &l_err);
    if (dbus_error_is_set(&l_err)) {
        printf("Name Error (%s)\n",l_err.message);
        dbus_error_free(&l_err);
    }
    if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != l_ret) {
        printf("Not Primary Owner (%d)\n", l_ret);
        exit(1);
    }


    // infinite loop, testing for new messages
    while (1) {
        dbus_connection_read_write(l_conn, 0);
        // non blocking read of the next available message
        l_msg = dbus_connection_pop_message(l_conn);

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

        // Exposing standard interface and methods
        if (dbus_message_is_method_call(l_msg,
                                        "org.freedesktop.DBus.Introspectable",
                                        "Introspect")) {
            ReplyToIntrospect(l_msg, l_conn);
        }
        else if (dbus_message_is_method_call(l_msg,
                                        "org.freedesktop.DBus.Peer",
                                        "Ping")) {
            if (gReplyToPing < 3){
                gReplyToPing ++;
                ReplyToPing(l_msg, l_conn);
            }else{
                syslog(LOG_INFO,"[_DBUS_PING_TIMEOUT_] Closing app %s with pid %d...\n", argv[0], getpid());
                          }
        }
        else {
            printf ("Unknown method called\n");
        }

        // free the message
        dbus_message_unref(l_msg);


    }
    dbus_connection_flush(l_conn);
    return 0;
}
Пример #22
0
static void id_callback(DBusPendingCall *pending, void *ptr)
{
    DBusMessage *reply;
    DBusError dbus_error;
    dbus_bool_t ret;
    dbus_uint16_t mon_ver;
    int type;

    dbus_error_init(&dbus_error);

    reply = dbus_pending_call_steal_reply(pending);
    if (!reply) {
        /* reply should never be null. This function shouldn't be called
         * until reply is valid or timeout has occurred. If reply is NULL
         * here, something is seriously wrong and we should bail out.
         */
        DEBUG(SSSDBG_FATAL_FAILURE,
              "Severe error. A reply callback was called but no"
                  " reply was received and no timeout occurred\n");

        /* FIXME: Destroy this connection ? */
        goto done;
    }

    type = dbus_message_get_type(reply);
    switch (type) {
    case DBUS_MESSAGE_TYPE_METHOD_RETURN:
        ret = dbus_message_get_args(reply, &dbus_error,
                                    DBUS_TYPE_UINT16, &mon_ver,
                                    DBUS_TYPE_INVALID);
        if (!ret) {
            DEBUG(SSSDBG_CRIT_FAILURE, "Failed to parse message\n");
            if (dbus_error_is_set(&dbus_error)) dbus_error_free(&dbus_error);
            /* FIXME: Destroy this connection ? */
            goto done;
        }

        DEBUG(SSSDBG_CONF_SETTINGS,
              "Got id ack and version (%d) from Monitor\n", mon_ver);

        break;

    case DBUS_MESSAGE_TYPE_ERROR:
        DEBUG(SSSDBG_FATAL_FAILURE,"The Monitor returned an error [%s]\n",
                 dbus_message_get_error_name(reply));
        /* Falling through to default intentionally*/
    default:
        /*
         * Timeout or other error occurred or something
         * unexpected happened.
         * It doesn't matter which, because either way we
         * know that this connection isn't trustworthy.
         * We'll destroy it now.
         */

        /* FIXME: Destroy this connection ? */
        break;
    }

done:
    dbus_pending_call_unref(pending);
    dbus_message_unref(reply);
}
Пример #23
0
int
main(int argc, char **argv)
{
	DBusError error;
	DBusConnection *conn;
	LibHalContext *hal_ctx;
	int err;
	int	c;
	int	all = 0;
	int	list = 0;
	int	dev = 0;
	char 	*dev_name;

	if (argc < 2) {
		return (0);
	}

	while ((c = getopt(argc, argv, "ald:")) != EOF) {
		switch (c) {
		case 'a':
			all = 1;
			break;
		case 'l':
			list = 1;
			break;
		case 'd':
			dev = 1;
			dev_name = optarg;
			break;
		default:
			exit(1);
		}
	}

	dbus_error_init(&error);

	if (!(conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) {
		fprintf(stderr, "error: dbus_bus_get: %s: %s\n",
			error.name, error.message);
		LIBHAL_FREE_DBUS_ERROR(&error);
		return (2);
	}

	if (!(hal_ctx = libhal_ctx_new())) {
		return (3);
	}

	if (!libhal_ctx_set_dbus_connection(hal_ctx, conn)) {
		return (4);
	}

	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 (5);
	}

	err = 0;

	if (list) {
		err = list_battery_devices(hal_ctx);
	}

	if (all) {
		err = dump_all_devices(hal_ctx);
	}

	if (dev) {
		err = dump_device(hal_ctx, dev_name);
	}

	libhal_ctx_shutdown(hal_ctx, &error);
	libhal_ctx_free(hal_ctx);
	dbus_connection_unref(conn);
	dbus_error_free(&error);

	return (err);
}
Пример #24
0
VIR_MOCK_WRAP_RET_ARGS(dbus_connection_send_with_reply_and_block,
                       DBusMessage *,
                       DBusConnection *, connection,
                       DBusMessage *, message,
                       int, timeout_milliseconds,
                       DBusError *, error)
{
    DBusMessage *reply = NULL;
    const char *service = dbus_message_get_destination(message);
    const char *member = dbus_message_get_member(message);
    size_t i;
    size_t nargs = 0;
    char **args = NULL;
    char *type = NULL;

    VIR_MOCK_REAL_INIT(dbus_connection_send_with_reply_and_block);

    if (STREQ(service, "org.freedesktop.DBus") &&
        STREQ(member, "ListNames")) {
        const char *svc1 = "org.foo.bar.wizz";
        const char *svc2 = VIR_FIREWALL_FIREWALLD_SERVICE;
        DBusMessageIter iter;
        DBusMessageIter sub;
        reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN);
        dbus_message_iter_init_append(reply, &iter);
        dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
                                         "s", &sub);

        if (!dbus_message_iter_append_basic(&sub,
                                            DBUS_TYPE_STRING,
                                            &svc1))
            goto error;
        if (!fwDisabled &&
            !dbus_message_iter_append_basic(&sub,
                                            DBUS_TYPE_STRING,
                                            &svc2))
            goto error;
        dbus_message_iter_close_container(&iter, &sub);
    } else if (STREQ(service, VIR_FIREWALL_FIREWALLD_SERVICE) &&
               STREQ(member, "passthrough")) {
        bool isAdd = false;
        bool doError = false;

        if (virDBusMessageDecode(message,
                                 "sa&s",
                                 &type,
                                 &nargs,
                                 &args) < 0)
            goto error;

        for (i = 0; i < nargs; i++) {
            /* Fake failure on the command with this IP addr */
            if (STREQ(args[i], "-A")) {
                isAdd = true;
            } else if (isAdd && STREQ(args[i], "192.168.122.255")) {
                doError = true;
            }
        }

        if (fwBuf) {
            if (STREQ(type, "ipv4"))
                virBufferAddLit(fwBuf, IPTABLES_PATH);
            else if (STREQ(type, "ipv4"))
                virBufferAddLit(fwBuf, IP6TABLES_PATH);
            else
                virBufferAddLit(fwBuf, EBTABLES_PATH);
        }
        for (i = 0; i < nargs; i++) {
            if (fwBuf) {
                virBufferAddLit(fwBuf, " ");
                virBufferEscapeShell(fwBuf, args[i]);
            }
        }
        if (fwBuf)
            virBufferAddLit(fwBuf, "\n");
        if (doError) {
            dbus_set_error_const(error,
                                 "org.firewalld.error",
                                 "something bad happened");
        } else {
            if (nargs == 1 &&
                STREQ(type, "ipv4") &&
                STREQ(args[0], "-L")) {
                if (virDBusCreateReply(&reply,
                                       "s", TEST_FILTER_TABLE_LIST) < 0)
                    goto error;
            } else if (nargs == 3 &&
                       STREQ(type, "ipv4") &&
                       STREQ(args[0], "-t") &&
                       STREQ(args[1], "nat") &&
                       STREQ(args[2], "-L")) {
                if (virDBusCreateReply(&reply,
                                       "s", TEST_NAT_TABLE_LIST) < 0)
                    goto error;
            } else {
                if (virDBusCreateReply(&reply,
                                       "s", "success") < 0)
                    goto error;
            }
        }
    } else {
        reply = dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_RETURN);
    }

 cleanup:
    VIR_FREE(type);
    for (i = 0; i < nargs; i++)
        VIR_FREE(args[i]);
    VIR_FREE(args);
    return reply;

 error:
    virDBusMessageUnref(reply);
    reply = NULL;
    if (error && !dbus_error_is_set(error))
        dbus_set_error_const(error,
                             "org.firewalld.error",
                             "something unexpected happened");

    goto cleanup;
}
Пример #25
0
int
main (int argc, char *argv[])
{
  DBusConnection *conn[NUM_CONN];
  DBusConnection *monitor;
  DBusError error;
  int i;
  int test_data_len;

  test_data_len = sizeof (test_data) / sizeof (CommandAndResult);
  
  dbus_error_init (&error);

  conn[0] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 0 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }
  
  if (!match_acquired_or_lost_signal (conn[0],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[0])))
    return 1;
  
  conn[1] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 1 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (conn[1],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[1])))
    return 1;


  conn[2] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 2 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (conn[2],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[2])))
    return 1;


  conn[3] = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open connection 3 to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (conn[3],
                                "NameAcquired",
                                dbus_bus_get_unique_name (conn[3])))
    return 1;


  monitor = dbus_bus_get (DBUS_BUS_SESSION, &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to open monitoring connection to session bus: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }

  if (!match_acquired_or_lost_signal (monitor,
                                "NameAcquired",
                                dbus_bus_get_unique_name (monitor)))
    return 1;

  dbus_bus_add_match (monitor, "", &error);
  if (dbus_error_is_set (&error))
    {
      fprintf (stderr, "*** Failed to set filter on monitoring connection: %s\n",
               error.message);
      dbus_error_free (&error);
      return 1;
    }


  for (i = 0; i < NUM_CONN; i++) 
    dbus_connection_set_exit_on_disconnect (conn[i], FALSE);

  for (i = 0; i < test_data_len; i++)
    {
      dbus_uint32_t result;
      result = 0;

      if (test_data[i].command == ADD_CONNECTION)
        {
          result = dbus_bus_request_name (conn[test_data[i].connection_number], 
                                          TEST_NAME, 
                                          test_data[i].flags,
                                          &error);

          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "Error on addition in iteration %i: %s\n", i, error.message);
              dbus_error_free (&error);
              return 1;
            }
        } 
      else if (test_data[i].command == REMOVE_CONNECTION)
        {
          result = dbus_bus_release_name (conn[test_data[i].connection_number], 
                                          TEST_NAME, 
                                          &error);  
          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "*** Failed to remove connection %i in iteration %i: %s\n",
                       test_data[i].connection_number,
                       i,
                       error.message);
              dbus_error_free (&error);
              return 1;
            }
        }
      else
        {
          fprintf (stderr, "Command #%i not a valid command!\n", test_data[i].command);
          return 1;
        }


      if (result != test_data[i].expected_result)
        {
          fprintf (stderr, "Results recived (%i) are not the expected results (%i) in iteration %i\n",
                   result,
                   test_data[i].expected_result,
                   i);
          return 1;
        }

      if (!check_connection (monitor, i, conn))
        {
          fprintf (stderr, "Failed at iteration %i\n", i);
          return 1;
        }

      if (!check_signals (monitor, i, conn))
        {
          fprintf (stderr, "Failed at iteration %i\n", i);
          return 1;
        }
    }

    return 0;
}
Пример #26
0
static dbus_bool_t
process_test_subdir (const DBusString          *test_base_dir,
                     const char                *subdir)
{
  DBusString test_directory;
  DBusString filename;
  DBusDirIter *dir;
  dbus_bool_t retval;
  DBusError error;

  retval = FALSE;
  dir = NULL;
  
  if (!_dbus_string_init (&test_directory))
    _dbus_assert_not_reached ("didn't allocate test_directory\n");

  _dbus_string_init_const (&filename, subdir);
  
  if (!_dbus_string_copy (test_base_dir, 0,
                          &test_directory, 0))
    _dbus_assert_not_reached ("couldn't copy test_base_dir to test_directory");
  
  if (!_dbus_concat_dir_and_file (&test_directory, &filename))    
    _dbus_assert_not_reached ("couldn't allocate full path");

  _dbus_string_free (&filename);
  if (!_dbus_string_init (&filename))
    _dbus_assert_not_reached ("didn't allocate filename string\n");

  dbus_error_init (&error);
  dir = _dbus_directory_open (&test_directory, &error);
  if (dir == NULL)
    {
      _dbus_warn ("Could not open %s: %s\n",
                  _dbus_string_get_const_data (&test_directory),
                  error.message);
      dbus_error_free (&error);
      goto failed;
    }

  printf ("Testing %s:\n", subdir);
  
 next:
  while (_dbus_directory_get_next_file (dir, &filename, &error))
    {
      DBusString full_path;
      
      if (!_dbus_string_init (&full_path))
        _dbus_assert_not_reached ("couldn't init string");

      if (!_dbus_string_copy (&test_directory, 0, &full_path, 0))
        _dbus_assert_not_reached ("couldn't copy dir to full_path");

      if (!_dbus_concat_dir_and_file (&full_path, &filename))
        _dbus_assert_not_reached ("couldn't concat file to dir");

      if (!_dbus_string_ends_with_c_str (&filename, ".auth-script"))
        {
          _dbus_verbose ("Skipping non-.auth-script file %s\n",
                         _dbus_string_get_const_data (&filename));
	  _dbus_string_free (&full_path);
          goto next;
        }

      printf ("    %s\n", _dbus_string_get_const_data (&filename));
      
      if (!_dbus_auth_script_run (&full_path))
        {
          _dbus_string_free (&full_path);
          goto failed;
        }
      else
        _dbus_string_free (&full_path);
    }

  if (dbus_error_is_set (&error))
    {
      _dbus_warn ("Could not get next file in %s: %s\n",
                  _dbus_string_get_const_data (&test_directory), error.message);
      dbus_error_free (&error);
      goto failed;
    }
    
  retval = TRUE;
  
 failed:

  if (dir)
    _dbus_directory_close (dir);
  _dbus_string_free (&test_directory);
  _dbus_string_free (&filename);

  return retval;
}
Пример #27
0
static int Open( vlc_object_t *p_this )
{ /* initialisation of the connection */
    intf_thread_t   *p_intf = (intf_thread_t*)p_this;
    intf_sys_t      *p_sys  = malloc( sizeof( intf_sys_t ) );
    playlist_t      *p_playlist;
    DBusConnection  *p_conn;
    DBusError       error;
    char            *psz_service_name = NULL;

    if( !p_sys || !dbus_threads_init_default())
        return VLC_ENOMEM;

    p_sys->b_meta_read = false;
    p_sys->i_caps = CAPS_NONE;
    p_sys->b_dead = false;
    p_sys->p_input = NULL;
    p_sys->i_playing_state = -1;

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

    p_sys->b_unique = var_CreateGetBool( p_intf, "dbus-unique-service-id" );
    if( p_sys->b_unique )
    {
        if( asprintf( &psz_service_name, "%s-%d",
            DBUS_MPRIS_BUS_NAME, getpid() ) < 0 )
        {
            free( p_sys );
            return VLC_ENOMEM;
        }
    }
    else
    {
        psz_service_name = strdup(DBUS_MPRIS_BUS_NAME);
    }

    dbus_error_init( &error );

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

    dbus_connection_set_exit_on_disconnect( p_conn, FALSE );

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

    /* we register the objects */
    dbus_connection_register_object_path( p_conn, DBUS_MPRIS_ROOT_PATH,
            &dbus_mpris_root_vtable, p_this );
    dbus_connection_register_object_path( p_conn, DBUS_MPRIS_PLAYER_PATH,
            &dbus_mpris_player_vtable, p_this );
    dbus_connection_register_object_path( p_conn, DBUS_MPRIS_TRACKLIST_PATH,
            &dbus_mpris_tracklist_vtable, p_this );

    dbus_connection_flush( p_conn );

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

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

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

    dbus_connection_set_dispatch_status_function( p_conn,
                                                  dispatch_status_cb,
                                                  p_intf, NULL );

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

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

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

    UpdateCaps( p_intf );

    return VLC_SUCCESS;
}
Пример #28
0
/**
 * wrapper_export:
 * @comp:    the component to export (source or renderer)
 *
 * Exports a component on D-Bus, if it is not already exported, which means:
 * 1. registering an appropriate service name for it
 *    -- in case of sources: MAFW_SOURCE_SERVICE "." plugin "." uuid
 *    -- in case of renderers: MAFW_RENDERER_SERVICE "." plugin "." uuid
 * 2. attaching the appropriate D-Bus message handlers:
 *    -- common one for all #MafwExtensions
 *    -- a specific one for either #MafwSource or #MafwRenderer
 * 3. registering all this information in the Exports list.
 */
static void wrapper_export(gpointer comp)
{
	DBusError err;
	ExportedComponent *ecomp;
	const gchar *plugin, *name, *uuid;
	gchar *service_name;
	gchar *object_path;
	GList *t;
	DBusObjectPathVTable path_vtable;

	/* Export a component only once. */
	for (t = Exports; t; t = t->next)
		if (((ExportedComponent *)t->data)->comp == comp)
			return;

	plugin = mafw_extension_get_plugin(comp);
	name = mafw_extension_get_name(comp);
	uuid = mafw_extension_get_uuid(comp);
	g_assert(plugin);
	g_assert(name);
	g_assert(uuid);

	if (MAFW_IS_SOURCE(comp)) {
		service_name = g_strconcat(MAFW_SOURCE_SERVICE ".",
					   plugin, ".", uuid, NULL);
		object_path = g_strconcat(MAFW_SOURCE_OBJECT "/",
					  uuid, NULL);
	} else if (MAFW_IS_RENDERER(comp)) {
		service_name = g_strconcat(MAFW_RENDERER_SERVICE ".",
					   plugin, ".", uuid, NULL);
		object_path = g_strconcat(MAFW_RENDERER_OBJECT "/",
					  uuid, NULL);
	} else {
		service_name = NULL;
		object_path = NULL;
		g_critical("wrapper_export(): Neither source nor renderer, "
			   "someone is putting strange things "
			   "in your registry.");
		goto err1;
	}

	dbus_error_init(&err);
	switch (dbus_bus_request_name(Session_bus, service_name,
				      DBUS_NAME_FLAG_DO_NOT_QUEUE, &err)) {
	case DBUS_REQUEST_NAME_REPLY_EXISTS:
		g_warning("dbus_bus_request_name(): service already exists: "
			  "%s", service_name);
		goto err1;
	default:
		if (dbus_error_is_set(&err)) {
			g_warning("dbus_bus_request_name() an error was set: "
				  "%s", err.message);
			dbus_error_free(&err);
			goto err1;
		}
	}
	mafw_dbus_send(Session_bus,
			mafw_dbus_signal_full(
					NULL,
					MAFW_REGISTRY_PATH,
					MAFW_REGISTRY_INTERFACE,
					MAFW_REGISTRY_SIGNAL_HELLO,
					MAFW_DBUS_STRING(service_name)));
	ecomp = g_new0(ExportedComponent, 1);
	ecomp->comp = comp;
	ecomp->connection = Session_bus;
	ecomp->name = g_strdup(name);
	ecomp->uuid = g_strdup(uuid);
	ecomp->service_name = service_name;
	ecomp->object_path = object_path;
	ecomp->sighandlers = g_array_sized_new(FALSE, FALSE, sizeof(gulong),
					       13);

	if (MAFW_IS_SOURCE(comp))
		ecomp->handler = handle_source_msg;
	else if (MAFW_IS_RENDERER(comp))
		ecomp->handler = handle_renderer_msg;
	g_assert(ecomp->handler);

	memset(&path_vtable, 0, sizeof(DBusObjectPathVTable));
	path_vtable.message_function =
		(DBusObjectPathMessageFunction)ecomp->handler;

	if (!dbus_connection_register_object_path(Session_bus,
                                                  ecomp->object_path,
                                                  &path_vtable,
                                                  ecomp))
		goto err2;

	Exports = g_list_prepend(Exports, ecomp);

	if (MAFW_IS_SOURCE(comp))
		connect_to_source_signals(ecomp);
	if (MAFW_IS_RENDERER(comp))
		connect_to_renderer_signals(ecomp);
	if (MAFW_IS_EXTENSION(comp))
		connect_to_extension_signals(ecomp);

	return;

err2:   g_free(ecomp->name);
	g_free(ecomp->uuid);
	g_free(ecomp);
err1:   g_free(service_name);
	g_free(object_path);
}
static dbus_bool_t
process_test_subdir (const DBusString          *test_base_dir,
                     const char                *subdir,
                     DBusValidity               expected_validity,
                     DBusForeachMessageFileFunc function,
                     void                      *user_data)
{
  DBusString test_directory;
  DBusString filename;
  DBusDirIter *dir;
  dbus_bool_t retval;
  DBusError error = DBUS_ERROR_INIT;

  retval = FALSE;
  dir = NULL;

  if (!_dbus_string_init (&test_directory))
    _dbus_assert_not_reached ("didn't allocate test_directory\n");

  _dbus_string_init_const (&filename, subdir);

  if (!_dbus_string_copy (test_base_dir, 0,
                          &test_directory, 0))
    _dbus_assert_not_reached ("couldn't copy test_base_dir to test_directory");

  if (!_dbus_concat_dir_and_file (&test_directory, &filename))
    _dbus_assert_not_reached ("couldn't allocate full path");

  _dbus_string_free (&filename);
  if (!_dbus_string_init (&filename))
    _dbus_assert_not_reached ("didn't allocate filename string\n");

  dir = _dbus_directory_open (&test_directory, &error);
  if (dir == NULL)
    {
      _dbus_warn ("Could not open %s: %s\n",
                  _dbus_string_get_const_data (&test_directory),
                  error.message);
      dbus_error_free (&error);
      goto failed;
    }

  printf ("Testing %s:\n", subdir);

 next:
  while (_dbus_directory_get_next_file (dir, &filename, &error))
    {
      DBusString full_path;

      if (!_dbus_string_init (&full_path))
        _dbus_assert_not_reached ("couldn't init string");

      if (!_dbus_string_copy (&test_directory, 0, &full_path, 0))
        _dbus_assert_not_reached ("couldn't copy dir to full_path");

      if (!_dbus_concat_dir_and_file (&full_path, &filename))
        _dbus_assert_not_reached ("couldn't concat file to dir");

      if (_dbus_string_ends_with_c_str (&filename, ".message-raw"))
        ;
      else
        {
          if (_dbus_string_ends_with_c_str (&filename, ".message"))
            {
              printf ("SKIP: Could not load %s, message builder language no longer supported\n",
                      _dbus_string_get_const_data (&filename));
            }
          
          _dbus_verbose ("Skipping non-.message file %s\n",
                         _dbus_string_get_const_data (&filename));
	  _dbus_string_free (&full_path);
          goto next;
        }

      printf ("    %s\n",
              _dbus_string_get_const_data (&filename));

      if (! (*function) (&full_path,
                         expected_validity, user_data))
        {
          _dbus_string_free (&full_path);
          goto failed;
        }
      else
        _dbus_string_free (&full_path);
    }

  if (dbus_error_is_set (&error))
    {
      _dbus_warn ("Could not get next file in %s: %s\n",
                  _dbus_string_get_const_data (&test_directory),
                  error.message);
      dbus_error_free (&error);
      goto failed;
    }

  retval = TRUE;

 failed:

  if (dir)
    _dbus_directory_close (dir);
  _dbus_string_free (&test_directory);
  _dbus_string_free (&filename);

  return retval;
}
Пример #30
0
	int
conf_drp_get_domain_ip(DBusConnection *connection,
							int local_slot_id, int hansitype, int insid, 
							domain_pt *domain, domain_ct *domain_ret)
{
	DBusMessage *query, *reply;
	DBusError err;
	DBusMessageIter  iter;
	DBusMessageIter  iter_array;
	int iRet=0;
	int i = 0, num = 0;
	static int distributed = 0;
	static int active_master_slot_id = 0;
	int active_master_slot_id_tmp = 0;
	static DBusConnection *remote_dbus_conn = NULL;
	DBusConnection *remote_dbus_conn_tmp = NULL;
	DBusConnection *connection_real = NULL;
		

	query = dbus_message_new_method_call(
			DRP_DBUS_BUSNAME,
			DRP_DBUS_OBJPATH,
			DRP_DBUS_INTERFACE, 
			DRP_DBUS_METHOD_GET_DOMAIN_IP );
	dbus_error_init(&err);
	dbus_message_append_args( query,
			DBUS_TYPE_STRING, &(domain->domain_name),
			DBUS_TYPE_INVALID );

/*init remote dbus connection*/
	distributed = init_distributed_flag();
	if (distributed == 1){
		active_master_slot_id_tmp = get_product_info(ACTIVE_MASTER_SLOT_FILE);
		if (0 == active_master_slot_id || active_master_slot_id_tmp != active_master_slot_id){
			if (NULL == remote_dbus_conn){
				remote_dbus_conn_tmp = dbus_get_tipc_connection(active_master_slot_id_tmp,local_slot_id, hansitype, insid);
				if (NULL == remote_dbus_conn_tmp){
					syslog(LOG_ERR,"connect to drp dbus_get_tipc_connection error!");
					dbus_message_unref(query);
					iRet = DRP_ERR_REMOTE_DBUS_CONNECT_FAILED;
					goto error;
				}
			}else{
				dbus_connection_close(remote_dbus_conn);
				remote_dbus_conn = NULL;
				remote_dbus_conn_tmp = dbus_get_tipc_connection(active_master_slot_id_tmp,local_slot_id, hansitype, insid);
				if (NULL == remote_dbus_conn_tmp){
					syslog(LOG_ERR,"connect to drp dbus_get_tipc_connection error!");
					dbus_message_unref(query);
					iRet = DRP_ERR_REMOTE_DBUS_CONNECT_FAILED;
					goto error;
				}
			}
		}
		active_master_slot_id = active_master_slot_id_tmp;
		remote_dbus_conn = remote_dbus_conn_tmp;
		connection_real = remote_dbus_conn;
		syslog(LOG_INFO,"connect to drp remote active_master_slot_id is %d ",active_master_slot_id);
	}else if( 0 == distributed ){
		connection_real = connection;
	}else{
		syslog(LOG_ERR, "connect to drp error distributed state wrong! flag = %d \n use local dbus connection to drp!",distributed);
		connection_real = connection;
	}
	
	reply = dbus_connection_send_with_reply_and_block (
										connection_real, query, -1, &err );
	dbus_message_unref(query);

	if ( NULL == reply ){	
		if (dbus_error_is_set(&err)){
			dbus_error_free(&err);
		}
		return DRP_ERR_DBUS_FAILED;
	}else{
		memset (domain_ret, 0, sizeof(domain_ret));
		dbus_message_iter_init(reply,&iter);
		dbus_message_iter_get_basic(&iter, &iRet);

		if( DRP_RETURN_OK == iRet ){
			dbus_message_iter_next(&iter);
			dbus_message_iter_get_basic(&iter, &num);
			if( num > MAX_DOMAIN_IPADDR ){
				num = MAX_DOMAIN_IPADDR;
			}

			strncpy(domain_ret->domain_name, domain->domain_name,\
					sizeof(domain_ret->domain_name));
			domain_ret->num = num;

			if( num > 0 ){
				dbus_message_iter_next(&iter);	
				dbus_message_iter_recurse(&iter,&iter_array);			

				for( i=0; i<num; i++ ){
					DBusMessageIter iter_struct;
					dbus_message_iter_recurse(&iter_array,&iter_struct);
					dbus_message_iter_get_basic(&iter_struct, &(domain_ret->domain_ip[i].index));
					dbus_message_iter_get_basic(&iter_struct, &(domain_ret->domain_ip[i].ipaddr));
					dbus_message_iter_next(&iter_array);
				}
			}
		}
	}


	dbus_message_unref(reply);
error:

	return iRet;
}