Initialize Tizen 2.3
[framework/web/wrt-commons.git] / modules / dbus / src / connection.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16 /**
17  * @file    connection.cpp
18  * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
19  * @version 1.0
20  * @brief
21  */
22 #include <stddef.h>
23 #include <dpl/log/wrt_log.h>
24 #include <dpl/dbus/connection.h>
25 #include <dpl/dbus/exception.h>
26 #include <dpl/dbus/object_proxy.h>
27
28 namespace DPL {
29 namespace DBus {
30 ConnectionPtr Connection::sessionBus()
31 {
32     return connectTo(G_BUS_TYPE_SESSION);
33 }
34
35 ConnectionPtr Connection::systemBus()
36 {
37     return connectTo(G_BUS_TYPE_SYSTEM);
38 }
39
40 ConnectionPtr Connection::connectTo(GBusType busType)
41 {
42     GError* error = NULL;
43
44     GDBusConnection* connection = g_bus_get_sync(busType,
45                                                  NULL,
46                                                  &error);
47     if (NULL == connection) {
48         std::string message;
49         if (NULL != error) {
50             message = error->message;
51             g_error_free(error);
52         }
53         ThrowMsg(DBus::Exception,
54                  "Couldn't connect to bus: " << message);
55     }
56
57     g_dbus_connection_set_exit_on_close(connection, FALSE);
58
59     return ConnectionPtr(new Connection(connection));
60 }
61
62 ConnectionPtr Connection::connectTo(const std::string& address)
63 {
64     GError* error = NULL;
65
66     GDBusConnection* connection = g_dbus_connection_new_for_address_sync(
67             address.c_str(),
68             G_DBUS_CONNECTION_FLAGS_NONE,
69             NULL,
70             NULL,
71             &error);
72     if (NULL == connection) {
73         std::string message;
74         if (NULL != error) {
75             message = error->message;
76             g_error_free(error);
77         }
78         ThrowMsg(DBus::Exception,
79                  "Couldn't connect to " << address << ": " << message);
80     }
81
82     return ConnectionPtr(new Connection(connection));
83 }
84
85 Connection::Connection(GDBusConnection* connection) :
86     m_connection(connection)
87 {
88     g_signal_connect(m_connection,
89                      "closed",
90                      G_CALLBACK(onConnectionClosed),
91                      this);
92 }
93
94 Connection::~Connection()
95 {
96     std::for_each(m_registeredServices.begin(),
97                   m_registeredServices.end(),
98                   [] (const RegisteredServices::value_type & value)
99                   {
100                       g_bus_unown_name(value.second);
101                   });
102
103     std::for_each(m_registeredObjects.begin(),
104                   m_registeredObjects.end(),
105                   [this] (const RegisteredObjects::value_type & value)
106                   {
107                       g_dbus_connection_unregister_object(
108                           m_connection,
109                           value.second.registrationId);
110                   });
111
112     if (!g_dbus_connection_is_closed(m_connection)) {
113         GError* error = NULL;
114
115         if (FALSE ==
116             g_dbus_connection_flush_sync(m_connection, NULL, &error))
117         {
118             WrtLogD("Could not flush the connection <%s>", error->message);
119             g_error_free(error);
120         }
121     }
122
123     g_object_unref(m_connection);
124 }
125
126 void Connection::registerService(const std::string& serviceName)
127 {
128     guint regId = g_bus_own_name_on_connection(m_connection,
129                                                serviceName.c_str(),
130                                                G_BUS_NAME_OWNER_FLAGS_NONE,
131                                                onServiceNameAcquired,
132                                                onServiceNameLost,
133                                                this,
134                                                NULL);
135     if (0 >= regId) {
136         ThrowMsg(DBus::Exception, "Error while registering service.");
137     }
138
139     m_registeredServices.insert(RegisteredServices::value_type(serviceName,
140                                                                regId));
141 }
142
143 void Connection::unregisterService(const std::string& serviceName)
144 {
145     auto it = m_registeredServices.find(serviceName);
146     if (m_registeredServices.end() == it) {
147         ThrowMsg(DBus::Exception, "Service not registered.");
148     }
149
150     g_bus_unown_name(it->second);
151
152     m_registeredServices.erase(it);
153 }
154
155 void Connection::registerObject(const ObjectPtr& object)
156 {
157     GError* error = NULL;
158
159     guint regId = g_dbus_connection_register_object(
160             m_connection,
161             object->getPath().c_str(),
162             object->getInterface()->getInfo(),
163             object->getInterface()->getVTable(),
164             // TODO This is ugly, fix this!
165             object->getInterface().get(),
166             NULL,
167             &error);
168     if (0 == regId) {
169         std::string message;
170         if (NULL != error) {
171             message = error->message;
172             WrtLogD("%s %i", error->message, error->code);
173             g_error_free(error);
174         }
175         ThrowMsg(DBus::Exception, "Error while registering an object: "
176                  << message);
177     }
178
179     m_registeredObjects.insert(RegisteredObjects::value_type(
180                                    object->getPath(),
181                                    ObjectRegistration(regId, object)));
182 }
183
184 void Connection::unregisterObject(const std::string& objectPath)
185 {
186     auto it = m_registeredObjects.find(objectPath);
187     if (m_registeredObjects.end() == it) {
188         ThrowMsg(DBus::Exception, "Object not registered.");
189     }
190
191     gboolean result = g_dbus_connection_unregister_object(
192             m_connection,
193             it->second.registrationId);
194     if (FALSE == result) {
195         ThrowMsg(DBus::Exception, "Unregistering object failed.");
196     }
197     m_registeredObjects.erase(it);
198 }
199
200 ObjectProxyPtr Connection::createObjectProxy(const std::string& serviceName,
201                                              const std::string& objectPath)
202 {
203     if (g_dbus_connection_is_closed(m_connection)) {
204         ThrowMsg(DBus::ConnectionClosedException, "Connection closed.");
205     }
206
207     return ObjectProxyPtr(
208                new ObjectProxy(m_connection, serviceName, objectPath));
209 }
210
211 void Connection::onServiceNameAcquired(GDBusConnection* /*connection*/,
212                                        const gchar* serviceName,
213                                        gpointer data)
214 {
215     AssertMsg(data, "Connection should not be NULL");
216
217     Connection* self = static_cast<Connection*>(data);
218
219     WrtLogD("Emitting service name acquired event: %s", serviceName);
220
221     ConnectionEvents::ServiceNameAcquiredEvent event(serviceName);
222     self->DPL::Event::EventSupport<ConnectionEvents::ServiceNameAcquiredEvent>
223         ::
224         EmitEvent(event, DPL::Event::EmitMode::Queued);
225 }
226
227 void Connection::onServiceNameLost(GDBusConnection* /*connection*/,
228                                    const gchar* serviceName,
229                                    gpointer data)
230 {
231     AssertMsg(data, "Connection should not be NULL");
232
233     Connection* self = static_cast<Connection*>(data);
234
235     WrtLogD("Emitting service name lost event: %s", serviceName);
236
237     ConnectionEvents::ServiceNameLostEvent event(serviceName);
238     self->DPL::Event::EventSupport<ConnectionEvents::ServiceNameLostEvent>::
239         EmitEvent(event, DPL::Event::EmitMode::Queued);
240 }
241
242 void Connection::onConnectionClosed(GDBusConnection* /*connection*/,
243                                     gboolean peerVanished,
244                                     GError* error,
245                                     gpointer data)
246 {
247     AssertMsg(NULL != data, "Connection cannot be NULL");
248
249     Connection* self = static_cast<Connection*>(data);
250
251     if ((NULL == error) && (FALSE == peerVanished)) {
252         // Connection closed by this.
253     } else if (NULL != error) {
254         std::string message = error->message;
255
256         g_error_free(error);
257
258         if (TRUE == peerVanished) {
259             // Connection closed by remote host.
260             ConnectionEvents::ConnectionBrokenEvent event(message);
261             self->DPL::Event::EventSupport<ConnectionEvents::
262                                                ConnectionBrokenEvent>::
263                 EmitEvent(event, DPL::Event::EmitMode::Queued);
264         } else {
265             // Invalid or malformed data on connection.
266             ConnectionEvents::ConnectionInvalidEvent event(message);
267             self->DPL::Event::EventSupport<ConnectionEvents::
268                                                ConnectionInvalidEvent>::
269                 EmitEvent(event, DPL::Event::EmitMode::Queued);
270         }
271     }
272 }
273 }
274 }