Example #1
0
void dbus_initialize(void) {
	DBusError err;

	dbus_threads_init_default();
	dbus_error_init(&err);

	if (!(service_bus = dbus_connection_open(SERVICE_BUS_ADDRESS, &err))) {
		dbus_error_free(&err);
		errx(1, "failed to connect to service bus: %s: %s", err.name, err.message);
	}

	if (!dbus_bus_register(service_bus, &err)) {
		dbus_error_free(&err);
		errx(1, "failed to register with service bus: %s: %s", err.name, err.message);
	}
	
	dbus_error_free(&err);
	
	service_thread = std::thread([]() {
		// dispatch messages until disconnect
		while (dbus_connection_read_write_dispatch(service_bus, -1));
		dbus_connection_unref(service_bus);
	});

    service_thread.detach();
}
void VolumeBarLogic::openConnection (bool init)
{
    /*
     * Check the connection first, maybe this function
     * only called because of lost connection
     */
    if ((dbus_conn != NULL) && (dbus_connection_get_is_connected (dbus_conn)))
        return;

    DBusError dbus_err;
    char *pa_bus_address = getenv ("PULSE_DBUS_SERVER");

    if (pa_bus_address == NULL)
        pa_bus_address = (char *) DEFAULT_ADDRESS;

    dbus_error_init (&dbus_err);

    dbus_conn = dbus_connection_open (pa_bus_address, &dbus_err);

    DBUS_ERR_CHECK (dbus_err);

    if (dbus_conn != NULL) {
        dbus_connection_setup_with_g_main (dbus_conn, NULL);

        dbus_connection_add_filter (
            dbus_conn,
            (DBusHandleMessageFunction) VolumeBarLogic::stepsUpdatedSignal,
            (void *) this, NULL);

        if (init == true)
            initValues ();
    }
}
Example #3
0
static gboolean
session_new_bus (const char *address)
{
    DBusError error;

    dbus_error_init (&error);

    if (session_bus != NULL) {
        N_DEBUG (LOG_CAT "received session bus address '%s'", address);
        dbus_connection_unref (session_bus);
        session_bus = NULL;
    }
    else
        N_DEBUG (LOG_CAT "received new session bus address '%s'", address);

    if ((session_bus = dbus_connection_open (address, &error)) == NULL ||
        !dbus_bus_register (session_bus, &error))
    {
        if (dbus_error_is_set(&error)) {
            N_WARNING (LOG_CAT "failed to connect to session bus %s (%s)",
                address, error.message);

            dbus_error_free (&error);
        }
        else
            N_WARNING (LOG_CAT "failed to connect to session bus %s", address);

        return FALSE;
    }

    session_reconnect ();

    return TRUE;
}
Example #4
0
static gboolean
connect_peer_to_peer()
{
    DBusError   error;

    dbus_error_init (&error);
    volume_bus = dbus_connection_open (volume_pulse_address, &error);

    if (dbus_error_is_set (&error)) {
        N_WARNING (LOG_CAT "failed to open connection to pulseaudio: %s",
            error.message);
        dbus_error_free (&error);
        return FALSE;
    }

    dbus_connection_setup_with_g_main (volume_bus, NULL);

    if (!dbus_connection_add_filter (volume_bus, filter_cb, NULL, NULL)) {
        N_WARNING (LOG_CAT "failed to add filter");
        return FALSE;
    }

    process_queued_ops();

    return TRUE;
}
Example #5
0
static void
open_destroy_shared_session_bus_connection (void)
{
  DBusError error;
  DBusConnection *connection;
  char *session_addr_no_guid;
  char *comma;
  
  dbus_error_init (&error);

  session_addr_no_guid = strdup (getenv ("DBUS_SESSION_BUS_ADDRESS"));
  comma = strchr (session_addr_no_guid, ',');
  if (comma == NULL)
    die ("Couldn't find GUID in session bus address");
  *comma = '\0';
    
  connection = dbus_connection_open (session_addr_no_guid, &error);
  free (session_addr_no_guid);
  if (connection == NULL)
    die ("Failed to open connection to temp session bus\n");

  loop = _dbus_loop_new ();
  if (loop == NULL)
    die ("No memory\n");
  
  if (!test_connection_setup (loop, connection))
    die ("No memory\n");

  test_connection_shutdown (loop, connection);
 
  _dbus_loop_unref (loop);

  dbus_connection_unref (connection); 
}
Example #6
0
static int
vehicle_gpsd_dbus_open(struct vehicle_priv *priv)
{
	DBusError error;

	dbus_error_init(&error);
	if (priv->address) {
		priv->connection = dbus_connection_open(priv->address, &error);
	} else {
		priv->connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	}
	if (!priv->connection) {
		dbg(0,"Failed to open connection to %s message bus: %s\n", priv->address?priv->address:"session",error.message);
		dbus_error_free(&error);
		return 0;
	}
	dbus_connection_setup_with_g_main(priv->connection, NULL);
	dbus_bus_add_match(priv->connection,"type='signal',interface='org.gpsd'",&error);
	dbus_connection_flush(priv->connection);
	if (dbus_error_is_set(&error)) {
		dbg(0,"Failed to add match to connection: %s\n", error.message);
		vehicle_gpsd_dbus_close(priv);
		return 0;
	}
	if (!dbus_connection_add_filter(priv->connection, vehicle_gpsd_dbus_filter, priv, NULL)) {
		dbg(0,"Failed to add filter to connection\n");
		vehicle_gpsd_dbus_close(priv);
		return 0;
	}
	return 1;
}
Connection::Connection( const char* address, bool priv )
{
	Error e;
	_connection = priv 
			? NULL//dbus_connection_open_private(address, e) //todo:
			: dbus_connection_open(address,e);

	if(e) throw e;

	init();

	cbus_dbg("connected to %s", address);
}
Example #8
0
void initialize_dbus(void)
{
    dbus_threads_init_default();

    DBusError error;
    dbus_error_init(&error);

    // Initialize service bus
    service_bus = dbus_connection_open(SERVICE_BUS_ADDRESS, &error);
    if (!service_bus) {
        errx(1, "failed to connect to service bus: %s: %s\n", error.name, error.message);
    }

    if (!dbus_bus_register(service_bus, &error)) {
        errx(1, "failed to register with service bus: %s: %s\n", error.name, error.message);
    }

    // Initialize HMI bus
    hmi_bus = dbus_connection_open(HMI_BUS_ADDRESS, &error);
    if (!hmi_bus) {
        errx(1, "failed to connect to HMI bus: %s: %s\n", error.name, error.message);
    }

    if (!dbus_bus_register(hmi_bus, &error)) {
        errx(1, "failed to register with HMI bus: %s: %s\n", error.name, error.message);
    }

    std::thread service_thread([]() {
        while (dbus_connection_read_write_dispatch(service_bus, -1));
    });

    std::thread hmi_thread([]() {
        while (dbus_connection_read_write_dispatch(hmi_bus, -1));
    });

    service_thread.detach();
    hmi_thread.detach();
}
Example #9
0
static int ldbus_connection_open(lua_State *L) {
	const char *address = luaL_checkstring(L, 1);

	DBusError *error = new_DBusError(L);
	DBusConnection *connection = dbus_connection_open(address, error);

	if (dbus_error_is_set(error)) {
		lua_pushnil(L);
		lua_pushstring(L, error->message);
		return 2;
	} else {
		push_DBusConnection(L, connection, FALSE);
		return 1;
	}
}
Example #10
0
QDBusConnection QDBusConnection::addConnection(const QString &address,
                    const QString &name)
{
//    Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
//               "Cannot create connection without a Q[Core]Application instance");

    QDBusConnectionPrivate *d = manager()->connection(name);
    if (d)
        return QDBusConnection(name);

    d = new QDBusConnectionPrivate;
    // setConnection does the error handling for us
    d->setConnection(dbus_connection_open(address.utf8().data(), &d->error));

    manager()->setConnection(name, d);

    return QDBusConnection(name);
}
Example #11
0
static void session_bus_init(const char *addr)
{
    DBusError err;
    int       success;

    dbus_error_init(&err);

    if (!addr) {
        if ((sess_conn = dbus_bus_get(DBUS_BUS_SESSION, &err)) != NULL)
            success = TRUE;
        else {
            success = FALSE;

            if (!dbus_error_is_set(&err))
                OHM_ERROR("auth: can't get D-Bus connection");
            else {
                OHM_ERROR("auth: can't get D-Bus connection: %s", err.message);
                dbus_error_free(&err);
            }
        }
    }
    else {
        if ((sess_conn = dbus_connection_open(addr, &err)) != NULL &&
            dbus_bus_register(sess_conn, &err)                        )
            success = TRUE;
        else {
            success = FALSE;
            sess_conn = NULL;

            if (!dbus_error_is_set(&err))
                OHM_ERROR("auth: can't connect to D-Bus %s", addr);
            else {
                OHM_ERROR("auth: can't connect to D-Bus %s (%s)",
                          addr, err.message);
                dbus_error_free(&err);
            }
        }
    }

    if (!success)
        OHM_ERROR("auth: delayed connection to session bus failed");
}
static int init_dbus(DBusConnection **conn) {
	DBusError err;
	char dbus_address[PROPERTY_VALUE_MAX];
	int result = 0;

	dbus_error_init(&err);

	/* get STE specific DBUS port */
	memset(dbus_address, 0, sizeof(dbus_address));
	(void) property_get("ste.dbus.bus.address", dbus_address, NULL);

	/* connect to the bus */
	*conn = dbus_connection_open(dbus_address, &err);

	if (*conn == NULL || dbus_error_is_set(&err)) {
		WRN("failed to connect to DBUS: %s\n", err.message);
		result = -1;
		goto exit;
	}

	if (!dbus_bus_get_unique_name(*conn) &&
		!dbus_bus_register(*conn, &err)) {
		ERR("failed to register with DBUS: %s\n", err.message);
		goto exit;
	}

	dbus_connection_ref(*conn);

exit:
	if (*conn) {
		dbus_connection_unref(*conn);
	}

	dbus_error_free(&err);

	return result;
}
Example #13
0
IBusConnection *
ibus_connection_open (const gchar *address)
{
    g_assert (address != NULL);

    DBusError error;
    DBusConnection *dbus_connection;
    IBusConnection *connection;

    if (_connections == NULL) {
        _connections = g_hash_table_new (g_direct_hash, g_direct_equal);
    }


    dbus_error_init (&error);
    dbus_connection = dbus_connection_open (address, &error);
    if (dbus_connection == NULL) {
        g_warning ("Connect to %s failed: %s.", address, error.message);
        dbus_error_free (&error);
        return NULL;
    }

    connection = g_hash_table_lookup (_connections, dbus_connection);

    if (connection == NULL) {
        connection = ibus_connection_new ();
        g_object_ref_sink (connection);

        ibus_connection_set_connection (connection, dbus_connection, TRUE);
        g_hash_table_insert (_connections, dbus_connection, connection);
        g_signal_connect (connection, "destroy", G_CALLBACK (_connection_destroy_cb), dbus_connection);
    }

    dbus_connection_unref (dbus_connection);
    g_object_ref_sink (connection);
    return connection;
}
void PulseAudioControl::openConnection()
{
    //! If the connection already exists, do nothing
    if ((dbusConnection != NULL) && (dbus_connection_get_is_connected(dbusConnection))) {
        return;
    }

    // Establish a connection to the server
    char *pa_bus_address = getenv("PULSE_DBUS_SERVER");
    QByteArray addressArray;
    if (pa_bus_address == NULL) {
        QDBusMessage message = QDBusMessage::createMethodCall("org.pulseaudio.Server", "/org/pulseaudio/server_lookup1", "org.freedesktop.DBus.Properties", "Get");
        message.setArguments(QVariantList() << "org.PulseAudio.ServerLookup1" << "Address");
        QDBusMessage reply = QDBusConnection::sessionBus().call(message);
        if (reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() > 0) {
            addressArray = reply.arguments().first().value<QDBusVariant>().variant().toString().toAscii();
            pa_bus_address = addressArray.data();
        }
    }

    if (pa_bus_address != NULL) {
        DBusError dbus_err;
        dbus_error_init(&dbus_err);

        dbusConnection = dbus_connection_open(pa_bus_address, &dbus_err);

        DBUS_ERR_CHECK(dbus_err);
    }

    if (dbusConnection != NULL) {
        dbus_connection_setup_with_g_main(dbusConnection, NULL);
        dbus_connection_add_filter(dbusConnection, PulseAudioControl::stepsUpdatedSignalHandler, (void *)this, NULL);

        addSignalMatch();
    }
}
Example #15
0
gboolean commander_poll_event(gpointer data)
{	
	return TRUE;
	
	const struct timespec timeout = { .tv_sec = 0, .tv_nsec = 10000};
	
	struct input_event event[64];
	const size_t ev_size = sizeof(struct input_event);
	const size_t buffer_size = ev_size * 64;
	ssize_t size;
	gst_app_t *app = (gst_app_t *)data;
	struct timespec tp;
	uint8_t *cmd_buf = NULL;
	int cmd_size = 0; 

	sigset_t sigmask;
	struct pollfd fds[1];
	int ret;
	unsigned char* buf = 0;
	int len;

	sigemptyset(&sigmask);

	fds[0].events = POLLIN;
    fds[0].fd = mCommander.fd;
    
    fds[0].revents = 0;

	ret = ppoll(fds, sizeof(fds) / sizeof(struct pollfd), &timeout, &sigmask);

	if (fds[0].revents & POLLIN) {

		size = read(mCommander.fd, &event, buffer_size);
		
		if (size == 0 || size == -1)
			return FALSE;
		
		if (size < ev_size) {
			printf("Error size when reading\n");
			g_main_loop_quit(app->loop);
			return FALSE;
		}
		
		int num_chars = size / ev_size;
		
		int i;
		
		
		for (i=0;i < num_chars;i++) {			
			if (event[i].type == EV_KEY && event[i].value == 1) {
				
				switch (event[i].code) {
					case KEY_UP:
						cmd_buf = cd_up1;
						cmd_size = sizeof(cd_up1);
						break;
							
					case KEY_DOWN:
						cmd_buf = cd_down1;
						cmd_size = sizeof(cd_down1);
						break;
										
					case KEY_LEFT:
						cmd_buf = cd_left1;
						cmd_size = sizeof(cd_left1);
						break;
						
					case KEY_RIGHT:
						cmd_buf = cd_right1;
						cmd_size = sizeof(cd_right1);
						break;
						
					case KEY_N:
						cmd_buf = cd_lefturn;
						cmd_size = sizeof(cd_lefturn);
						break;
						
					case KEY_M:
						cmd_buf = cd_rightturn;
						cmd_size = sizeof(cd_rightturn);
						break;

					case KEY_ENTER:
						cmd_buf = cd_enter1;
						cmd_size = sizeof(cd_enter1);
						break;

					case KEY_BACKSPACE:
						cmd_buf = cd_back1;
						cmd_size = sizeof(cd_back1);
						break;
				}
				
				if (cmd_buf != NULL) {
					clock_gettime(CLOCK_REALTIME, &tp);
					
					uint8_t *buf = (uint8_t *)malloc(cmd_size);

					memcpy(buf, cmd_buf, cmd_size);

					varint_encode(tp.tv_sec * 1000000000 +tp.tv_nsec, buf,3);

					printf("\n { ");
			
					for (i = 0; i < cmd_size; i++)
					{
						
						if (i > 0) printf(",");
						printf("0x%02X", (char) buf[i]);
					}
					
					printf(" } \n");

									
					queueSend(0,AA_CH_TOU, buf, cmd_size, TRUE);
					
				}
				
			}
				
			if (event[i].type == EV_KEY && event[i].value == 0) {
				cmd_buf = NULL;
				
				switch (event[i].code) {
					case KEY_UP:
						cmd_buf = cd_up2;
						cmd_size = sizeof(cd_up2);
						break;
							
					case KEY_DOWN:
						cmd_buf = cd_down2;
						cmd_size = sizeof(cd_down2);
						break;
										
					case KEY_LEFT:
						cmd_buf = cd_left2;
						cmd_size = sizeof(cd_left2);
						break;
						
					case KEY_RIGHT:
						cmd_buf = cd_right2;
						cmd_size = sizeof(cd_right2);
						break;

					case KEY_ENTER:
						cmd_buf = cd_enter2;
						cmd_size = sizeof(cd_enter2);
						break;

					case KEY_BACKSPACE:
						cmd_buf = cd_back2;
						cmd_size = sizeof(cd_back2);
						break;
				}
				
				if (cmd_buf != NULL) {
					clock_gettime(CLOCK_REALTIME, &tp);
					uint8_t *buf = (uint8_t *)malloc(cmd_size);

					memcpy(buf, cmd_buf, cmd_size);

					printf("\n { ");
			
					for (i = 0; i < cmd_size; i++)
					{
						
						if (i > 0) printf(",");
						printf("0x%02X", (char) buf[i]);
					}
					
					printf(" } \n");

					varint_encode(tp.tv_sec * 100000000 +tp.tv_nsec, buf,3);
					
					queueSend(0,AA_CH_TOU, buf, cmd_size, TRUE);
				}
			}
		}
	}
	
	return TRUE;
}


static void * input_thread(void *app) {
	
	while (touch_poll_event(app)) {
		commander_poll_event(app);		
		ms_sleep(100);
	}
}

GMainLoop *mainloop;

#define HMI_BUS_ADDRESS "unix:path=/tmp/dbus_hmi_socket"

 
static void * nightmode_thread(void *app) 
{

	// Initialize HMI bus
	DBusConnection *hmi_bus;
	DBusError error;

	hmi_bus = dbus_connection_open(HMI_BUS_ADDRESS, &error);

	if (!hmi_bus) {
		printf("DBUS: failed to connect to HMI bus: %s: %s\n", error.name, error.message);
	}

	if (!dbus_bus_register(hmi_bus, &error)) {
		printf("DBUS: failed to register with HMI bus: %s: %s\n", error.name, error.message);
	}

	// Wait for mainloop to start
	ms_sleep(100);
		
	while (g_main_loop_is_running (mainloop)) {
		
		DBusMessage *msg = dbus_message_new_method_call("com.jci.BLM_TIME", "/com/jci/BLM_TIME", "com.jci.BLM_TIME", "GetClock");
		DBusPendingCall *pending = NULL;

		if (!msg) {
			printf("DBUS: failed to create message \n");
		}

		if (!dbus_connection_send_with_reply(hmi_bus, msg, &pending, -1)) {
			printf("DBUS: failed to send message \n");
		}

		dbus_connection_flush(hmi_bus);
		dbus_message_unref(msg);

		dbus_pending_call_block(pending);
		msg = dbus_pending_call_steal_reply(pending);
		if (!msg) {
		   printf("DBUS: received null reply \n");
		}

		dbus_uint32_t nm_hour;
		dbus_uint32_t nm_min;
		dbus_uint32_t nm_timestamp;
		dbus_uint64_t nm_calltimestamp;
		if (!dbus_message_get_args(msg, &error, DBUS_TYPE_UINT32, &nm_hour,
											  DBUS_TYPE_UINT32, &nm_min,
											  DBUS_TYPE_UINT32, &nm_timestamp,
											  DBUS_TYPE_UINT64, &nm_calltimestamp,
											  DBUS_TYPE_INVALID)) {
			printf("DBUS: failed to get result %s: %s\n", error.name, error.message);
		}
		
		dbus_message_unref(msg);
		
		int nightmodenow = 1;

		if (nm_hour >= 6 && nm_hour <= 18)
			nightmodenow = 0;

		if (nightmode != nightmodenow) {
			nightmode = nightmodenow;
			byte* rspds = malloc(sizeof(byte) * 6);
			rspds[0] = -128; 
			rspds[1] = 0x03;
		   	rspds[2] = 0x52; 
			rspds[3] = 0x02;
		   	rspds[4] = 0x08;
			if (nightmode == 0)
				rspds[5]= 0x00;
			else
				rspds[5] = 0x01;
			
			queueSend(0,AA_CH_SEN, rspds, sizeof (byte) * 6, TRUE); 	// Send Sensor Night mode
		}
		
		sleep(600);		
	}
}
Example #16
0
int main (int argc, char* argv[])
{
    char *servicename = NULL;
    char *address = NULL;
    DBusMessage* message = NULL;
    DBusConnection* conn = NULL;
    int c;
    int ret = 1;
    int messageType = FCITX_DBUS_GET_CURRENT_STATE;
    char *imname = NULL;
    while ((c = getopt(argc, argv, "chortTeam:")) != -1) {
        switch (c) {
        case 'o':
            messageType = FCITX_DBUS_ACTIVATE;
            break;

        case 'c':
            messageType = FCITX_DBUS_INACTIVATE;
            break;

        case 'r':
            messageType = FCITX_DBUS_RELOAD_CONFIG;
            break;

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

        case 'e':
            messageType = FCITX_DBUS_EXIT;
            break;

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

        case 'a':
            address = _fcitx_get_address();
            if (address) {
                printf("%s\n", address);
                return 0;
            }
            else
                return 1;
            break;

        case 'h':
            usage(stdout);
            return 0;
        default:
            usage(stderr);
            return 1;
            break;
        }
    }

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

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

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

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

        if (!conn) {
            goto some_error;
        }

        dbus_connection_set_exit_on_disconnect(conn, FALSE);
    }

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

some_error:
    if (message)
        dbus_message_unref(message);
    if (conn)
        dbus_connection_unref(conn);
    fcitx_utils_free(address);
    fcitx_utils_free(servicename);
    fcitx_utils_free(imname);
    return ret;
}
Example #17
0
int
main (int argc, char *argv[])
{
  DBusConnection *connection;
  DBusError error;
  DBusBusType type = DBUS_BUS_SESSION;
  DBusHandleMessageFunction filter_func = monitor_filter_func;
  char *address = NULL;
  
  int i = 0, j = 0, numFilters = 0;
  char **filters = NULL;

  /* Set stdout to be unbuffered; this is basically so that if people
   * do dbus-monitor > file, then send SIGINT via Control-C, they
   * don't lose the last chunk of messages.
   */

#ifdef DBUS_WIN
  setvbuf (stdout, NULL, _IONBF, 0);
#else
  setvbuf (stdout, NULL, _IOLBF, 0);
#endif

  for (i = 1; i < argc; i++)
    {
      char *arg = argv[i];

      if (!strcmp (arg, "--system"))
	type = DBUS_BUS_SYSTEM;
      else if (!strcmp (arg, "--session"))
	type = DBUS_BUS_SESSION;
      else if (!strcmp (arg, "--address"))
	{
	  if (i+1 < argc)
	    {
	      address = argv[i+1];
	      i++;
	    }
	  else
	    usage (argv[0], 1);
	}
      else if (!strcmp (arg, "--help"))
	usage (argv[0], 0);
      else if (!strcmp (arg, "--monitor"))
	filter_func = monitor_filter_func;
      else if (!strcmp (arg, "--profile"))
	filter_func = profile_filter_func;
      else if (!strcmp (arg, "--"))
	continue;
      else if (arg[0] == '-')
	usage (argv[0], 1);
      else {
	numFilters++;
       filters = (char **)realloc(filters, numFilters * sizeof(char *));
	filters[j] = (char *)malloc((strlen(arg) + 1) * sizeof(char *));
	snprintf(filters[j], strlen(arg) + 1, "%s", arg);
	j++;
      }
    }

  dbus_error_init (&error);
  
  if (address != NULL)
    {
      connection = dbus_connection_open (address, &error);
      if (connection)
        {
          if (!dbus_bus_register (connection, &error))
      	    {
              fprintf (stderr, "Failed to register connection to bus at %s: %s\n",
      	               address, error.message);
              dbus_error_free (&error);
              exit (1);
      	    }
        }
    }
  else
    connection = dbus_bus_get (type, &error);
  if (connection == NULL)
    {
      const char *where;
      if (address != NULL)
        where = address;
      else
        {
          switch (type)
            {
            case DBUS_BUS_SYSTEM:
              where = "system bus";
              break;
            case DBUS_BUS_SESSION:
              where = "session bus";
              break;
            default:
              where = "";
            }
        }
      fprintf (stderr, "Failed to open connection to %s: %s\n",
               where,
               error.message);
      dbus_error_free (&error);
      exit (1);
    }

  if (numFilters)
    {
      for (i = 0; i < j; i++)
        {
          dbus_bus_add_match (connection, filters[i], &error);
          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "Failed to setup match \"%s\": %s\n",
                       filters[i], error.message);
              dbus_error_free (&error);
              exit (1);
            }
	  free(filters[i]);
        }
    }
  else
    {
      dbus_bus_add_match (connection,
		          "type='signal'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
      dbus_bus_add_match (connection,
		          "type='method_call'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
      dbus_bus_add_match (connection,
		          "type='method_return'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
      dbus_bus_add_match (connection,
		          "type='error'",
		          &error);
      if (dbus_error_is_set (&error))
        goto lose;
    }

  if (!dbus_connection_add_filter (connection, filter_func, NULL, NULL)) {
    fprintf (stderr, "Couldn't add filter!\n");
    exit (1);
  }

  while (dbus_connection_read_write_dispatch(connection, -1))
    ;
  exit (0);
 lose:
  fprintf (stderr, "Error: %s\n", error.message);
  exit (1);
}
Example #18
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;
}
Example #19
0
int
main (int argc, char *argv[])
{
  DBusConnection *connection;
  DBusError error;
  DBusBusType type = DBUS_BUS_SESSION;
  DBusHandleMessageFunction filter_func = monitor_filter_func;
  char *address = NULL;
  dbus_bool_t seen_bus_type = FALSE;
  BinaryMode binary_mode = BINARY_MODE_NOT;
  int i = 0, j = 0, numFilters = 0;
  char **filters = NULL;

  /* Set stdout to be unbuffered; this is basically so that if people
   * do dbus-monitor > file, then send SIGINT via Control-C, they
   * don't lose the last chunk of messages.
   */

#ifdef DBUS_WIN
  setvbuf (stdout, NULL, _IONBF, 0);
#else
  setvbuf (stdout, NULL, _IOLBF, 0);
#endif

  for (i = 1; i < argc; i++)
    {
      char *arg = argv[i];

      if (!strcmp (arg, "--system"))
        {
          only_one_type (&seen_bus_type, argv[0]);
          type = DBUS_BUS_SYSTEM;
        }
      else if (!strcmp (arg, "--session"))
        {
          only_one_type (&seen_bus_type, argv[0]);
          type = DBUS_BUS_SESSION;
        }
      else if (!strcmp (arg, "--address"))
        {
          only_one_type (&seen_bus_type, argv[0]);

          if (i+1 < argc)
            {
              address = argv[i+1];
              i++;
            }
          else
            usage (argv[0], 1);
        }
      else if (!strcmp (arg, "--help"))
        usage (argv[0], 0);
      else if (!strcmp (arg, "--monitor"))
        {
          filter_func = monitor_filter_func;
          binary_mode = BINARY_MODE_NOT;
        }
      else if (!strcmp (arg, "--profile"))
        {
          filter_func = profile_filter_func;
          binary_mode = BINARY_MODE_NOT;
        }
      else if (!strcmp (arg, "--binary"))
        {
          filter_func = binary_filter_func;
          binary_mode = BINARY_MODE_RAW;
        }
      else if (!strcmp (arg, "--pcap"))
        {
          filter_func = binary_filter_func;
          binary_mode = BINARY_MODE_PCAP;
        }
      else if (!strcmp (arg, "--"))
        continue;
      else if (arg[0] == '-')
        usage (argv[0], 1);
      else {
          unsigned int filter_len;
          numFilters++;
          /* Prepend a rule (and a comma) to enable the monitor to eavesdrop.
           * Prepending allows the user to add eavesdrop=false at command line
           * in order to disable eavesdropping when needed */
          filter_len = strlen (EAVESDROPPING_RULE) + 1 + strlen (arg) + 1;

          filters = (char **) realloc (filters, numFilters * sizeof (char *));
          if (filters == NULL)
            tool_oom ("adding a new filter slot");
          filters[j] = (char *) malloc (filter_len);
          if (filters[j] == NULL)
            tool_oom ("adding a new filter");
          snprintf (filters[j], filter_len, "%s,%s", EAVESDROPPING_RULE, arg);
          j++;
      }
    }

  dbus_error_init (&error);
  
  if (address != NULL)
    {
      connection = dbus_connection_open (address, &error);
      if (connection)
        {
          if (!dbus_bus_register (connection, &error))
            {
              fprintf (stderr, "Failed to register connection to bus at %s: %s\n",
                       address, error.message);
              dbus_error_free (&error);
              exit (1);
            }
        }
    }
  else
    connection = dbus_bus_get (type, &error);
  if (connection == NULL)
    {
      const char *where;
      if (address != NULL)
        where = address;
      else
        {
          switch (type)
            {
            case DBUS_BUS_SYSTEM:
              where = "system bus";
              break;
            case DBUS_BUS_SESSION:
              where = "session bus";
              break;
            default:
              where = "";
            }
        }
      fprintf (stderr, "Failed to open connection to %s: %s\n",
               where,
               error.message);
      dbus_error_free (&error);
      exit (1);
    }

  /* Receive o.fd.Peer messages as normal messages, rather than having
   * libdbus handle them internally, which is the wrong thing for
   * a monitor */
  dbus_connection_set_route_peer_messages (connection, TRUE);

  if (!dbus_connection_add_filter (connection, filter_func,
                                   _DBUS_INT_TO_POINTER (binary_mode), NULL))
    {
      fprintf (stderr, "Couldn't add filter!\n");
      exit (1);
    }

  if (become_monitor (connection, numFilters,
                      (const char * const *) filters))
    {
      /* no more preparation needed */
    }
  else if (numFilters)
    {
      size_t offset = 0;
      for (i = 0; i < j; i++)
        {
          dbus_bus_add_match (connection, filters[i] + offset, &error);
          if (dbus_error_is_set (&error) && i == 0 && offset == 0)
            {
              /* We might be talking to a pre-1.5.6 dbus-daemon
              * which wouldn't understand eavesdrop=true.
              * If this works, carry on with offset > 0
              * on the remaining iterations. */
              offset = strlen (EAVESDROPPING_RULE) + 1;
              dbus_error_free (&error);
              dbus_bus_add_match (connection, filters[i] + offset, &error);
            }

          if (dbus_error_is_set (&error))
            {
              fprintf (stderr, "Failed to setup match \"%s\": %s\n",
                       filters[i], error.message);
              dbus_error_free (&error);
              exit (1);
            }
          free(filters[i]);
        }
    }
  else
    {
      dbus_bus_add_match (connection,
                          EAVESDROPPING_RULE,
                          &error);
      if (dbus_error_is_set (&error))
        {
          dbus_error_free (&error);
          dbus_bus_add_match (connection,
                              "",
                              &error);
          if (dbus_error_is_set (&error))
            goto lose;
        }
    }

  switch (binary_mode)
    {
      case BINARY_MODE_NOT:
      case BINARY_MODE_RAW:
        break;

      case BINARY_MODE_PCAP:
          {
            /* We're not using libpcap because the file format is simple
             * enough not to need it.
             * http://wiki.wireshark.org/Development/LibpcapFileFormat */
            struct {
                dbus_uint32_t magic;
                dbus_uint16_t major_version;
                dbus_uint16_t minor_version;
                dbus_int32_t timezone;
                dbus_uint32_t precision;
                dbus_uint32_t max_length;
                dbus_uint32_t link_type;
            } header = {
                0xA1B2C3D4U,  /* magic number */
                2, 4,         /* v2.4 */
                0,            /* capture in GMT */
                0,            /* no opinion on timestamp precision */
                (1 << 27),    /* D-Bus spec says so */
                LINKTYPE_DBUS
            };

            /* Assert that there is no padding */
            _DBUS_STATIC_ASSERT (sizeof (header) == 24);

            if (!tool_write_all (STDOUT_FILENO, &header, sizeof (header)))
              {
                perror ("dbus-monitor: write");
                exit (1);
              }
          }
        break;
    }

  while (dbus_connection_read_write_dispatch(connection, -1))
    ;
  exit (0);
 lose:
  fprintf (stderr, "Error: %s\n", error.message);
  exit (1);
}
Example #20
0
static int
dbus_activate(pcap_t *handle)
{
#define EAVESDROPPING_RULE "eavesdrop=true,"

	static const char *rules[] = {
		EAVESDROPPING_RULE "type='signal'",
		EAVESDROPPING_RULE "type='method_call'",
		EAVESDROPPING_RULE "type='method_return'",
		EAVESDROPPING_RULE "type='error'",
	};

	#define N_RULES sizeof(rules)/sizeof(rules[0])

	struct pcap_dbus *handlep = handle->priv;
	const char *dev = handle->opt.source;

	DBusError error = DBUS_ERROR_INIT;
	int i;

	if (strcmp(dev, "dbus-system") == 0) {
		if (!(handlep->conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) {
			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to get system bus: %s", error.message);
			dbus_error_free(&error);
			return PCAP_ERROR;
		}

	} else if (strcmp(dev, "dbus-session") == 0) {
		if (!(handlep->conn = dbus_bus_get(DBUS_BUS_SESSION, &error))) {
			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to get session bus: %s", error.message);
			dbus_error_free(&error);
			return PCAP_ERROR;
		}

	} else if (strncmp(dev, "dbus://", 7) == 0) {
		const char *addr = dev + 7;

		if (!(handlep->conn = dbus_connection_open(addr, &error))) {
			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to open connection to: %s: %s", addr, error.message);
			dbus_error_free(&error);
			return PCAP_ERROR;
		}

		if (!dbus_bus_register(handlep->conn, &error)) {
			pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to register bus %s: %s\n", addr, error.message);
			dbus_error_free(&error);
			return PCAP_ERROR;
		}

	} else {
		pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't get bus address from %s", handle->opt.source);
		return PCAP_ERROR;
	}

	/* Initialize some components of the pcap structure. */
	handle->bufsize = 0;
	handle->offset = 0;
	handle->linktype = DLT_DBUS;
	handle->read_op = dbus_read;
	handle->inject_op = dbus_write;
	handle->setfilter_op = install_bpf_program; /* XXX, later add support for dbus_bus_add_match() */
	handle->setdirection_op = NULL;
	handle->set_datalink_op = NULL;      /* can't change data link type */
	handle->getnonblock_op = pcap_getnonblock_fd;
	handle->setnonblock_op = pcap_setnonblock_fd;
	handle->stats_op = dbus_stats;

	handle->selectable_fd = handle->fd = -1;

	if (handle->opt.rfmon) {
		/*
		 * Monitor mode doesn't apply to dbus connections.
		 */
		dbus_cleanup(handle);
		return PCAP_ERROR_RFMON_NOTSUP;
	}

	/* dbus_connection_set_max_message_size(handlep->conn, handle->snapshot); */
	if (handle->opt.buffer_size != 0)
		dbus_connection_set_max_received_size(handlep->conn, handle->opt.buffer_size);

	for (i = 0; i < N_RULES; i++) {
		dbus_bus_add_match(handlep->conn, rules[i], &error);
		if (dbus_error_is_set(&error)) {
			dbus_error_free(&error);

			/* try without eavesdrop */
			dbus_bus_add_match(handlep->conn, rules[i] + strlen(EAVESDROPPING_RULE), &error);
			if (dbus_error_is_set(&error)) {
				pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to add bus match: %s\n", error.message);
				dbus_error_free(&error);
				dbus_cleanup(handle);
				return PCAP_ERROR;
			}
		}
	}

	return 0;
}
Example #21
0
/**
 * Connects to a bus daemon and registers the client with it.  If a
 * connection to the bus already exists, then that connection is
 * returned.  Caller owns a reference to the bus.
 *
 * @todo alex thinks we should nullify the connection when we get a disconnect-message.
 *
 * @param type bus type
 * @param error address where an error can be returned.
 * @returns a DBusConnection with new ref
 */
DBusConnection *
dbus_bus_get (DBusBusType  type,
	      DBusError   *error)
{
  const char *address;
  DBusConnection *connection;
  BusData *bd;
  DBusBusType address_type;

  _dbus_return_val_if_fail (type >= 0 && type < N_BUS_TYPES, NULL);
  _dbus_return_val_if_error_is_set (error, NULL);

  _DBUS_LOCK (bus);

  if (!init_connections_unlocked ())
    {
      _DBUS_UNLOCK (bus);
      _DBUS_SET_OOM (error);
      return NULL;
    }

  /* We want to use the activation address even if the
   * activating bus is the session or system bus,
   * per the spec.
   */
  address_type = type;
  
  /* Use the real type of the activation bus for getting its
   * connection, but only if the real type's address is available. (If
   * the activating bus isn't a well-known bus then
   * activation_bus_type == DBUS_BUS_STARTER)
   */
  if (type == DBUS_BUS_STARTER &&
      bus_connection_addresses[activation_bus_type] != NULL)
    type = activation_bus_type;
  
  if (bus_connections[type] != NULL)
    {
      connection = bus_connections[type];
      dbus_connection_ref (connection);
      
      _DBUS_UNLOCK (bus);
      return connection;
    }

  address = bus_connection_addresses[address_type];
  if (address == NULL)
    {
      dbus_set_error (error, DBUS_ERROR_FAILED,
                      "Unable to determine the address of the message bus");
      _DBUS_UNLOCK (bus);
      return NULL;
    }

  connection = dbus_connection_open (address, error);
  
  if (!connection)
    {
      _DBUS_ASSERT_ERROR_IS_SET (error);
      _DBUS_UNLOCK (bus);
      return NULL;
    }

  /* By default we're bound to the lifecycle of
   * the message bus.
   */
  dbus_connection_set_exit_on_disconnect (connection,
                                          TRUE);
  
  if (!dbus_bus_register (connection, error))
    {
      _DBUS_ASSERT_ERROR_IS_SET (error);
      dbus_connection_close (connection);
      dbus_connection_unref (connection);

      _DBUS_UNLOCK (bus);
      return NULL;
    }

  bus_connections[type] = connection;
  bd = ensure_bus_data (connection);
  _dbus_assert (bd != NULL);

  bd->is_well_known = TRUE;

  _DBUS_UNLOCK (bus);
  return connection;
}
Example #22
0
/********************
 * bus_new_session
 ********************/
static DBusHandlerResult
bus_new_session(DBusConnection *c, DBusMessage *msg, void *data)
{
    char      *address;
    DBusError  error;
    
    (void)c;
    (void)data;

    dbus_error_init(&error);
    
    if (!dbus_message_get_args(msg, &error,
                               DBUS_TYPE_STRING, &address,
                               DBUS_TYPE_INVALID)) {
        if (dbus_error_is_set(&error)) {
            OHM_ERROR("Failed to parse session bus notification: %s.",
                      error.message);
            dbus_error_free(&error);
        }
        else
            OHM_ERROR("Failed to parse session bus notification.");
        
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (!strcmp(address, "<failure>")) {
        OHM_INFO("profile: got session bus failure notification");
#ifndef __TEST__
        OHM_INFO("profile: requesting ohm restart");
        ohm_restart(0);
#else
        OHM_INFO("profile: ignoring");
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
#endif
    }

    if (bus_conn != NULL) {
        OHM_INFO("profile: received new session bus address \"%s\".", address);
        dbus_connection_unref(bus_conn);
        bus_conn = NULL;
    }
    else
        OHM_INFO("profile: received session bus address \"%s\".", address);
    
    if ((bus_conn = dbus_connection_open(address, &error)) == NULL ||
        !dbus_bus_register(bus_conn, &error)) {
        if (dbus_error_is_set(&error)) {
            OHM_ERROR("Failed to connect to DBUS %s (%s).", address,
                      error.message);
            dbus_error_free(&error);
        }
        else
            OHM_ERROR("Failed to connect to DBUS %s.", address);
        
        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
    }

    if (profile_plugin_p == NULL) {
        profile_plugin_p = init_profile();

        if (profile_plugin_p != NULL)
            OHM_INFO("profile: initialized with session bus.");
        else
            OHM_ERROR("profile: failed to initialize with session bus.");
    }
    else {
        reconnect_profile();
        OHM_INFO("profile: reinitialized with new session bus.");
    }
    
    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
Example #23
0
int main(int argc, char *argv[])
{
	int i, rc;

	if (argc < 3) {
		usage();
		rc = 1;
		goto out;
	}

	rc = setup_signal_handling();
	if (rc != 0) {
		fprintf(stderr, "FAIL: Couldn't set up signal handler\n");
		rc = 1;
		goto out;
	}

	for (i = 1; i < argc && interface == NULL; i++) {
		char *arg = argv[i];

		if (strcmp(arg, "--system") == 0) {
			type = DBUS_BUS_SYSTEM;
			session_or_system = TRUE;
		} else if (strcmp(arg, "--session") == 0) {
			type = DBUS_BUS_SESSION;
			session_or_system = TRUE;
		} else if (strstr(arg, "--address") == arg) {
			address = strchr(arg, '=');

			if (address == NULL) {
				fprintf(stderr,
					"FAIL: \"--address=\" requires an ADDRESS\n");
				usage();
				rc = 1;
				goto out;
			} else {
				address = address + 1;
			}
		} else if (strstr(arg, "--name=") == arg)
			name = strchr(arg, '=') + 1;
		else if (strstr(arg, "--log=") == arg) {
			char *path = strchr(arg, '=') + 1;

			log_fd = open(path, O_CREAT | O_TRUNC | O_WRONLY,
				      S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
				      S_IROTH | S_IWOTH);
			if (log_fd < 0) {
				fprintf(stderr,
					"FAIL: Couldn't open log file \"%s\"\n",
					path);
				exit(1);
			}
		} else if (strstr(arg, "--lock-fd=") == arg) {
			char *fd = strchr(arg, '=') + 1;

			lock_fd = atoi(fd);
		} else if (!strcmp(arg, "--help")) {
			usage();
			rc = 0;
			goto out;
		} else if (arg[0] == '-') {
			usage();
			rc = 1;
			goto out;
		} else if (path == NULL)
			path = arg;
		else	/* interface == NULL guaranteed by the 'while' loop */
			interface = arg;
	}

	if (name == NULL || path == NULL || interface == NULL || i < argc) {
		usage();
		rc = 1;
		goto out;
	}

	if (session_or_system && (address != NULL)) {
		fprintf(stderr,
			"FAIL: \"--address\" may not be used with \"--system\" or \"--session\"\n");
		usage();
		rc = 1;
		goto out;
	}

	dbus_error_init(&error);

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

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

	rc = do_service();

out:
	if (connection)
		dbus_connection_unref(connection);

	unlock_fd();

	if (rc == 0)
		printf("PASS\n");

	exit(rc);
}
Example #24
0
int
main (int argc, char *argv[])
{
  DBusConnection *connection;
  DBusError error;
  DBusMessage *message;
  dbus_bool_t print_reply;
  dbus_bool_t print_reply_literal;
  int reply_timeout;
  DBusMessageIter iter;
  int i;
  DBusBusType type = DBUS_BUS_SESSION;
  const char *dest = NULL;
  const char *name = NULL;
  const char *path = NULL;
  int message_type = DBUS_MESSAGE_TYPE_SIGNAL;
  const char *type_str = NULL;
  const char *address = NULL;
  int is_bus = FALSE;
  int session_or_system = FALSE;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      *(c++) = 0;

      container_type = DBUS_TYPE_INVALID;

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

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

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

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

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

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

  if (print_reply)
    {
      DBusMessage *reply;

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

      if (reply)
        {
          long sec, usec;

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

  dbus_message_unref (message);

  dbus_connection_unref (connection);

  exit (0);
}
Example #25
0
gboolean
check_libhal (const char *server_addr)
{
	pid_t child_pid;

	child_pid = fork ();
	if (child_pid == -1) {
		printf ("Cannot fork\n");
		exit (1);
	} else if (child_pid == 0) {
		DBusError error;
		DBusConnection *conn;
		LibHalContext *ctx;
		dbus_bool_t passed;

		printf ("server address='%s'\n", server_addr);

		dbus_error_init (&error);
		if ((conn = dbus_connection_open (server_addr, &error)) == NULL) {
			printf ("Error connecting to server: %s\n", error.message);
			goto fail;
		}

		dbus_connection_setup_with_g_main (conn, NULL);

		if ((ctx = libhal_ctx_new ()) == NULL) {
			printf ("Error getting libhal context\n");
			goto fail;
		}

		
		libhal_ctx_set_dbus_connection (ctx, conn);

		libhal_ctx_init (ctx, &error);

		if (dbus_error_is_set (&error)) {
			printf ("FAILED98: %s\n", error.message);			
			goto fail;
		}
		printf ("SUCCESS98\n");

		libhal_device_print (ctx, "/org/freedesktop/Hal/devices/testobj1", &error);


		if (dbus_error_is_set (&error)) {
			printf ("FAILED99: %s\n", error.message);			
			goto fail;
		}
		printf ("SUCCESS99\n");

		passed = FALSE;

		{
			char *val;
			
			val = libhal_device_get_property_string (ctx, "/org/freedesktop/Hal/devices/testobj1", "test.string", &error);

			if (val == NULL || strcmp (val, "fooooobar22") != 0 || dbus_error_is_set (&error)) {
				libhal_free_string (val);
				printf ("FAILED100\n");			
				goto fail;
			}
			printf ("SUCCESS100\n");
			libhal_free_string (val);
		}

		{
			char *val;
			val = libhal_device_get_property_string (ctx, "/org/freedesktop/Hal/devices/testobj1", "test.string2", &error);
			if (val == NULL || strcmp (val, "fooøةמ") != 0 || dbus_error_is_set (&error)) {
				libhal_free_string (val);
				printf ("FAILED101: %s\n", error.message);			
				goto fail;
			}
			libhal_free_string (val);
			printf ("SUCCESS101\n");
		}

		{
			dbus_bool_t b;
			b = libhal_device_get_property_bool (
			    ctx, "/org/freedesktop/Hal/devices/testobj1", 
			    "test.bool", &error);
			    
			if (!b || dbus_error_is_set (&error)) {
				printf ("FAILED102: %s, %i\n", error.message, b);			
				goto fail;
			}
			printf ("SUCCESS102\n");
		}

		{
			double val;
			double expected_val = 0.53434343;

			val = libhal_device_get_property_double (ctx, "/org/freedesktop/Hal/devices/testobj1", 
								 "test.double", &error);
			if ( memcmp (&val, &expected_val, sizeof (double)) != 0 || dbus_error_is_set (&error)) {
				printf ("FAILED103\n");
				goto fail;
			}
			printf ("SUCCESS103\n");
		}

		if (libhal_device_get_property_uint64 (
			    ctx, "/org/freedesktop/Hal/devices/testobj1", "test.uint64", &error) != 
		    ((((dbus_uint64_t)1)<<35) + 5) ||
		    dbus_error_is_set (&error)) {
			printf ("FAILED104: %s\n", error.message);			
			goto fail;
		}
		printf ("SUCCESS104\n");
		
		{
			char **val;
			val = libhal_device_get_property_strlist (ctx, "/org/freedesktop/Hal/devices/testobj1", "test.strlist", &error);
			if (val == NULL ||  dbus_error_is_set (&error)) {
				libhal_free_string_array (val);
				printf ("FAILED105: %s\n", error.message);			
				goto fail;
			}
			printf ("SUCCESS105\n");
			
			if (libhal_string_array_length (val) != 2) {
				libhal_free_string_array (val);
				printf ("FAILED106\n");			
				goto fail;
			}
			printf ("SUCCESS106\n");

			if (strcmp (val[0], "foostrlist2") != 0 ||
			    strcmp (val[1], "foostrlist3") != 0) {
				libhal_free_string_array (val);
				printf ("FAILED107\n");			
				goto fail;
			}
			printf ("SUCCESS107\n");

			libhal_free_string_array (val);
		}

		if (libhal_device_get_property_int (
			    ctx, "/org/freedesktop/Hal/devices/testobj1", "test.int", &error) != 42 ||
		    dbus_error_is_set (&error)) {
			printf ("FAILED108\n");			
			goto fail;
		}
		printf ("SUCCESS108\n");
	
		/* tests for libhal_psi */
		{
			int type;
			char *key;
			LibHalPropertySet *pset;
			LibHalPropertySetIterator it;
			unsigned int psi_num_passed;
			unsigned int psi_num_elems;

			if ((pset = libhal_device_get_all_properties (ctx, "/org/freedesktop/Hal/devices/testobj1", 
								      &error)) == NULL)
				return FALSE;
			printf ("SUCCESS110\n");

			psi_num_passed = 0;
			psi_num_elems = libhal_property_set_get_num_elems (pset);

			for (libhal_psi_init (&it, pset); libhal_psi_has_more (&it); libhal_psi_next (&it)) {
				type = libhal_psi_get_type (&it);
				key = libhal_psi_get_key (&it);

				switch (type) {
				case LIBHAL_PROPERTY_TYPE_STRING:
					if (strcmp (key, "info.udi") == 0) {
						if (strcmp (libhal_psi_get_string (&it), 
							    "/org/freedesktop/Hal/devices/testobj1") == 0) {
							psi_num_passed++;
						} else {
							printf ("fail on %s\n", key);
						}
					} else if (strcmp (key, "test.string") == 0) {
						if (strcmp (libhal_psi_get_string (&it), 
							    "fooooobar22") == 0) {
							psi_num_passed++;
						} else {
							printf ("fail on %s\n", key);
						}
					} else if (strcmp (key, "test.string2") == 0) {
						if (strcmp (libhal_psi_get_string (&it), 
							    "fooøةמ") == 0) {
							psi_num_passed++;
						} else {
							printf ("fail on %s\n", key);
						}
					}
					break;

				case LIBHAL_PROPERTY_TYPE_INT32:
					if (strcmp (key, "test.int") == 0) {
						if (libhal_psi_get_int (&it) == 42)
							psi_num_passed++;
						else
							printf ("fail on %s\n", key);
					}
					break;

				case LIBHAL_PROPERTY_TYPE_UINT64:
					if (strcmp (key, "test.uint64") == 0) {
						if (libhal_psi_get_uint64 (&it) == ((((dbus_uint64_t)1)<<35) + 5))
							psi_num_passed++;
						else
							printf ("fail on %s\n", key);
					}
					break;

				case LIBHAL_PROPERTY_TYPE_BOOLEAN:
					if (strcmp (key, "test.bool") == 0) {
						if (libhal_psi_get_bool (&it) == TRUE)
							psi_num_passed++;
						else
							printf ("fail on %s\n", key);
					}
					break;

				case LIBHAL_PROPERTY_TYPE_DOUBLE:
					if (strcmp (key, "test.double") == 0) {
						double val = 0.53434343;
						double val2;

						val2 = libhal_psi_get_double (&it);
						if (memcmp (&val, &val2, sizeof (double)) == 0)
							psi_num_passed++;
						else
							printf ("fail on %s\n", key);
					}
					break;

				case LIBHAL_PROPERTY_TYPE_STRLIST:
					if (strcmp (key, "test.strlist") == 0) {
						char **val;
					
						val = libhal_psi_get_strlist (&it);
						if (libhal_string_array_length (val) == 2 &&
						    strcmp (val[0], "foostrlist2") == 0 &&
						    strcmp (val[1], "foostrlist3") == 0 &&
						    val[2] == NULL)
							psi_num_passed++;
						else
							printf ("fail on %s\n", key);
					}
					break;

				default:
					printf ("    *** unknown type for key %s\n", key);
					break;
				}
			}
			libhal_free_property_set (pset);

			if (psi_num_passed != psi_num_elems) {
				printf ("FAILED111\n");			
				goto fail;
			}
			printf ("SUCCESS111\n");			


		} /* end libhal_test_psi */

	
		printf ("Passed all libhal tests\n");
		passed = TRUE;
		
	fail:
		if (dbus_error_is_set (&error))
			dbus_error_free (&error);
			
		send_tests_done (conn, passed);
		exit (1);

	} else {
		printf ("child pid=%d\n", child_pid);
	}
	return TRUE;
}
static void
open_shutdown_private_connection (dbus_bool_t use_guid)
{
  DBusError error;
  DBusLoop *loop;
  DBusConnection *session;
  DBusMessage *msg;
  DBusMessage *reply;
  DBusConnection *privconn;
  char *addr;
  dbus_bool_t service_died;
  dbus_bool_t private_conn_lost;

  dbus_error_init (&error);
  service_died = FALSE;
  private_conn_lost = FALSE;

  loop = _dbus_loop_new ();

  session = dbus_bus_get (DBUS_BUS_SESSION, &error);
  if (!session)
    die ("couldn't access session bus\n");
  dbus_connection_set_exit_on_disconnect (session, FALSE);
  test_connection_setup (loop, session);

  dbus_bus_add_match (session, PRIVSERVER_DIED_RULE, &error);
  if (dbus_error_is_set (&error))
    die ("couldn't add match rule \"%s\": %s: %s", PRIVSERVER_DIED_RULE,
         error.name, error.message);

  if (!dbus_connection_add_filter (session, filter_session_message,
                                   &service_died, NULL))
    die ("couldn't add filter to session bus\n");

  msg = dbus_message_new_method_call (PRIVSERVER_SERVICE, "/",
                                      PRIVSERVER_INTERFACE, "GetPrivateAddress");
  if (!(reply = dbus_connection_send_with_reply_and_block (session, msg, -1, &error)))
    die ("couldn't send message: %s\n", error.message);
  dbus_message_unref (msg);
  if (!dbus_message_get_args (reply, &error, DBUS_TYPE_STRING, &addr, DBUS_TYPE_INVALID))
    die ("couldn't parse message replym\n");
  printf ("# got private temp address %s\n", addr);
  addr = strdup (addr);
  if (!use_guid)
    {
      char *comma = strrchr (addr, ',');
      if (comma)
        *comma = '\0';
    }
  privconn = dbus_connection_open (addr, &error);
  free (addr);
  if (!privconn)
    die ("couldn't connect to server direct connection: %s\n", error.message);
  dbus_message_unref (reply);

  dbus_connection_set_exit_on_disconnect (privconn, FALSE);
  if (!dbus_connection_add_filter (privconn, filter_private_message,
                                   &private_conn_lost, NULL))
    die ("couldn't add filter to private connection\n");
  test_connection_setup (loop, privconn);

  msg = dbus_message_new_method_call (PRIVSERVER_SERVICE, "/",
                                      PRIVSERVER_INTERFACE, "Quit");
  if (!dbus_connection_send (session, msg, NULL))
    die ("couldn't send Quit message\n");
  dbus_message_unref (msg);

  while (!service_died || !private_conn_lost)
    _dbus_loop_iterate (loop, TRUE);

  dbus_connection_remove_filter (session, filter_session_message,
                                 &service_died);
  dbus_bus_remove_match (session, PRIVSERVER_DIED_RULE, NULL);
  test_connection_shutdown (loop, session);
  dbus_connection_unref (session);

  test_connection_shutdown (loop, privconn);
  dbus_connection_remove_filter (privconn, filter_private_message,
                                 &private_conn_lost);
  dbus_connection_unref (privconn);

  _dbus_loop_unref (loop);
}
Example #27
0
int main (int argc, char* argv[])
{
    if (argc != 3)
        return 1;

    pid_t pid = atoi(argv[2]);
    if (pid <= 0)
        return 1;

    fcitx_utils_init_as_daemon();

    asprintf(&servicename, "%s-%d", FCITX_DBUS_SERVICE, fcitx_utils_get_display_number());

    DBusError err;
    dbus_error_init(&err);

    DBusConnection* conn = dbus_connection_open(argv[1], NULL);
    if (!conn)
        goto some_error;

    FcitxDBusWatch* watches = NULL;

    if (!dbus_connection_set_watch_functions(conn, DBusAddWatch, DBusRemoveWatch, NULL, &watches, NULL)) {
        goto some_error;
    }

    dbus_connection_set_exit_on_disconnect(conn, TRUE);
    if (!dbus_bus_register(conn, NULL))
        goto some_error;

    dbus_bus_add_match(conn,
            "type='signal',"
            "interface='" DBUS_INTERFACE_DBUS "',"
            "path='" DBUS_PATH_DBUS "',"
            "member='NameOwnerChanged'",
            &err);

    if (dbus_error_is_set(&err))
        goto some_error;

    if (!dbus_connection_add_filter(conn, WatcherDBusFilter, NULL, NULL))
        goto some_error;

#ifndef NZERO
#define NZERO 20
#endif
    nice(NZERO - 1);

    fd_set rfds, wfds, efds;
    FD_ZERO(&rfds);
    FD_ZERO(&wfds);
    FD_ZERO(&efds);
    do {
        DBusProcessEventForWatches(watches, &rfds, &wfds, &efds);
        DBusProcessEventForConnection(conn);

        if (status != WATCHER_WAITING)
            break;

        FD_ZERO(&rfds);
        FD_ZERO(&wfds);
        FD_ZERO(&efds);
        int maxfd = DBusUpdateFDSet(watches, &rfds, &wfds, &efds);
        if (maxfd == 0)
            break;
        select(maxfd + 1, &rfds, &wfds, &efds, NULL);
    } while(1);

    if (status == FCITX_DIE) {
        kill(pid, SIGTERM);
    }

some_error:
    if (conn)
        dbus_connection_unref(conn);

    dbus_error_free(&err);

    fcitx_utils_free(servicename);
    return 1;
}