new fremantle branch
[libicd-wpa] / dbus.c
1 /**
2   @file dbus.c
3
4   Copyright (C) 2004 Nokia Corporation. All rights reserved.
5
6   @author Johan Hedberg <johan.hedberg@nokia.com>  
7   @author Janne Ylälehto <janne.ylalehto@nokia.com>
8
9   This program is free software; you can redistribute it and/or modify it
10   under the terms of the GNU General Public License as published by the
11   Free Software Foundation; either version 2 of the License, or (at your
12   option) any later version.
13
14   This program is distributed in the hope that it will be useful, but
15   WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17   General Public License for more details.
18
19   You should have received a copy of the GNU General Public License along
20   with this program; if not, write to the Free Software Foundation, Inc.,
21   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 */
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <glib.h>
27
28 #define DBUS_API_SUBJECT_TO_CHANGE
29 #include <dbus/dbus.h>
30 #include <dbus/dbus-glib.h>
31 #include <dbus/dbus-glib-lowlevel.h>
32
33 #include "log.h"
34 #include "dbus.h"
35
36 static DBusConnection *_dbus_connection = NULL;
37
38 DBusConnection *get_dbus_connection(void) {
39         return _dbus_connection;
40 }
41
42 int setup_dbus_connection(const char *service,
43                           void (*handler_init)(DBusConnection *connection)) {
44         DBusError derror;
45         
46         g_assert(_dbus_connection == NULL);
47
48         dbus_error_init(&derror);
49         _dbus_connection = dbus_bus_get(DBUS_BUS_SYSTEM, &derror);
50         if (_dbus_connection == NULL) {
51                 DLOG_ERR("System DBus connection failed: %s", derror.message);
52                 dbus_error_free(&derror);
53                 return -1;
54         }
55         dbus_connection_setup_with_g_main(_dbus_connection, NULL);
56
57         if (service) {
58                 int ret = dbus_bus_request_name(_dbus_connection, service, 0, 
59                                                 &derror);
60                 if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
61                         DLOG_ERR("Could not aquire D-BUS name '%s' (ret: %d)",
62                                  service, ret);
63                         if (dbus_error_is_set(&derror)) {
64                                 DLOG_DEBUG("%s", derror.message);
65                                 dbus_error_free(&derror);
66                         }
67                         return -1;
68                 }
69         }
70
71         if (handler_init)
72                 handler_init(_dbus_connection);
73         
74         return 0;
75 }
76
77 void close_dbus_connection(void) {
78         g_assert(_dbus_connection != NULL); 
79         dbus_connection_unref(_dbus_connection);
80         _dbus_connection = NULL;
81 }