Fix object lifecycle errors.
[platform/core/uifw/at-spi2-atk.git] / droute / droute.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2008 Novell, Inc.
6  * Copyright 2008 Codethink Ltd.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "droute.h"
28 #include "droute-pairhash.h"
29
30 #define CHUNKS_DEFAULT (512)
31
32 #define oom() g_error ("D-Bus out of memory, this message will fail anyway")
33
34 #if defined DROUTE_DEBUG
35     #define _DROUTE_DEBUG(format, args...) g_print (format , ## args)
36 #else
37     #define _DROUTE_DEBUG(format, args...)
38 #endif
39
40 struct _DRouteContext
41 {
42     DBusConnection       *bus;
43     GPtrArray            *registered_paths;
44
45     gchar                *introspect_dir;
46 };
47
48 struct _DRoutePath
49 {
50     DRouteContext        *cnx;
51     GStringChunk         *chunks;
52     GPtrArray            *interfaces;
53     GHashTable           *methods;
54     GHashTable           *properties;
55
56     void                   *user_data;
57     DRouteGetDatumFunction  get_datum;
58 };
59
60 /*---------------------------------------------------------------------------*/
61
62 typedef struct PropertyPair
63 {
64     DRoutePropertyFunction get;
65     DRoutePropertyFunction set;
66 } PropertyPair;
67
68 /*---------------------------------------------------------------------------*/
69
70 static DBusHandlerResult
71 handle_message (DBusConnection *bus, DBusMessage *message, void *user_data);
72
73 /*---------------------------------------------------------------------------*/
74
75 static DRoutePath *
76 path_new (DRouteContext *cnx,
77           void    *user_data,
78           DRouteGetDatumFunction get_datum)
79 {
80     DRoutePath *new_path;
81
82     new_path = g_new0 (DRoutePath, 1);
83     new_path->cnx = cnx;
84     new_path->chunks = g_string_chunk_new (CHUNKS_DEFAULT);
85     new_path->interfaces = g_ptr_array_new ();
86
87     new_path->methods = g_hash_table_new_full ((GHashFunc)str_pair_hash,
88                                                str_pair_equal,
89                                                g_free,
90                                                NULL);
91
92     new_path->properties = g_hash_table_new_full ((GHashFunc)str_pair_hash,
93                                                   str_pair_equal,
94                                                   g_free,
95                                                   NULL);
96
97     new_path->user_data = user_data;
98     new_path->get_datum = get_datum;
99
100     return new_path;
101 }
102
103 static void
104 path_free (DRoutePath *path, gpointer user_data)
105 {
106     g_string_chunk_free  (path->chunks);
107     g_ptr_array_free     (path->interfaces, TRUE);
108     g_hash_table_destroy (path->methods);
109     g_hash_table_destroy (path->properties);
110 }
111
112 static void *
113 path_get_datum (DRoutePath *path, const gchar *pathstr)
114 {
115     if (path->get_datum != NULL)
116         return (path->get_datum) (pathstr, path->user_data);
117     else
118         return path->user_data;
119 }
120
121 /*---------------------------------------------------------------------------*/
122
123 DRouteContext *
124 droute_new (DBusConnection *bus, const char *introspect_dir)
125 {
126     DRouteContext *cnx;
127
128     cnx = g_new0 (DRouteContext, 1);
129     cnx->bus = bus;
130     cnx->registered_paths = g_ptr_array_new ();
131     cnx->introspect_dir = g_strdup(introspect_dir);
132
133     return cnx;
134 }
135
136 void
137 droute_free (DRouteContext *cnx)
138 {
139     g_ptr_array_foreach (cnx->registered_paths, (GFunc) path_free, NULL);
140     g_free (cnx->introspect_dir);
141     g_free (cnx);
142 }
143
144 /*---------------------------------------------------------------------------*/
145
146 DBusConnection *
147 droute_get_bus (DRouteContext *cnx)
148 {
149     return cnx->bus;
150 }
151
152 /*---------------------------------------------------------------------------*/
153
154 static DBusObjectPathVTable droute_vtable =
155 {
156   NULL,
157   &handle_message,
158   NULL, NULL, NULL, NULL
159 };
160
161 DRoutePath *
162 droute_add_one (DRouteContext *cnx,
163                 const char    *path,
164                 const void    *data)
165 {
166     DRoutePath *new_path;
167     gboolean registered;
168
169     new_path = path_new (cnx, (void *) data, NULL);
170
171     registered = dbus_connection_register_object_path (cnx->bus, path, &droute_vtable, new_path);
172     if (!registered)
173         oom();
174
175     g_ptr_array_add (cnx->registered_paths, new_path);
176     return new_path;
177 }
178
179 DRoutePath *
180 droute_add_many (DRouteContext *cnx,
181                  const char    *path,
182                  const void    *data,
183                  const DRouteGetDatumFunction get_datum)
184 {
185     DRoutePath *new_path;
186
187     new_path = path_new (cnx, (void *) data, get_datum);
188
189     if (!dbus_connection_register_fallback (cnx->bus, path, &droute_vtable, new_path))
190         oom();
191
192     g_ptr_array_add (cnx->registered_paths, new_path);
193     return new_path;
194 }
195
196 /*---------------------------------------------------------------------------*/
197
198 void
199 droute_path_add_interface(DRoutePath *path,
200                           const char *name,
201                           const DRouteMethod   *methods,
202                           const DRouteProperty *properties)
203 {
204     gchar *itf;
205
206     g_return_if_fail (name != NULL);
207
208     itf = g_string_chunk_insert (path->chunks, name);
209     g_ptr_array_add (path->interfaces, itf);
210
211     for (; methods != NULL && methods->name != NULL; methods++)
212       {
213         gchar *meth;
214
215         meth = g_string_chunk_insert (path->chunks, methods->name);
216         g_hash_table_insert (path->methods, str_pair_new (itf, meth), methods->func);
217       }
218
219     for (; properties != NULL && properties->name != NULL; properties++)
220       {
221         gchar *prop;
222         PropertyPair *pair;
223
224         prop = g_string_chunk_insert (path->chunks, properties->name);
225         pair = g_new (PropertyPair, 1);
226         pair->get = properties->get;
227         pair->set = properties->set;
228         g_hash_table_insert (path->properties, str_pair_new (itf, prop), pair);
229       }
230 }
231
232 /*---------------------------------------------------------------------------*/
233
234 /* The data structures don't support an efficient implementation of GetAll
235  * and I don't really care.
236  */
237 static DBusMessage *
238 impl_prop_GetAll (DBusMessage *message,
239                   DRoutePath  *path,
240                   const char  *pathstr)
241 {
242     DBusMessageIter iter, iter_dict, iter_dict_entry;
243     DBusMessage *reply;
244     DBusError error;
245     GHashTableIter prop_iter;
246
247     StrPair *key;
248     PropertyPair *value;
249     gchar *iface;
250
251     void  *datum = path_get_datum (path, pathstr);
252     if (!datum)
253         return NULL;
254
255     dbus_error_init (&error);
256     if (!dbus_message_get_args
257                 (message, &error, DBUS_TYPE_STRING, &iface, DBUS_TYPE_INVALID))
258         return dbus_message_new_error (message, DBUS_ERROR_FAILED, error.message);
259
260     reply = dbus_message_new_method_return (message);
261     if (!reply)
262         oom ();
263
264     dbus_message_iter_init_append (reply, &iter);
265     if (!dbus_message_iter_open_container
266                 (&iter, DBUS_TYPE_ARRAY, "{sv}", &iter_dict))
267         oom ();
268
269     g_hash_table_iter_init (&prop_iter, path->properties);
270     while (g_hash_table_iter_next (&prop_iter, (gpointer*)&key, (gpointer*)&value))
271       {
272         if (!g_strcmp0 (key->one, iface))
273          {
274            if (!value->get)
275               continue;
276            if (!dbus_message_iter_open_container
277                         (&iter_dict, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict_entry))
278               oom ();
279            dbus_message_iter_append_basic (&iter_dict_entry, DBUS_TYPE_STRING,
280                                            key->two);
281            (value->get) (&iter_dict_entry, datum);
282            if (!dbus_message_iter_close_container (&iter_dict, &iter_dict_entry))
283                oom ();
284          }
285       }
286
287     if (!dbus_message_iter_close_container (&iter, &iter_dict))
288         oom ();
289     return reply;
290 }
291
292 static DBusMessage *
293 impl_prop_GetSet (DBusMessage *message,
294                   DRoutePath  *path,
295                   const char  *pathstr,
296                   gboolean     get)
297 {
298     DBusMessage *reply = NULL;
299     DBusError error;
300
301     StrPair pair;
302     PropertyPair *prop_funcs = NULL;
303
304     void *datum;
305
306     dbus_error_init (&error);
307     if (!dbus_message_get_args (message,
308                                 &error,
309                                 DBUS_TYPE_STRING,
310                                 &(pair.one),
311                                 DBUS_TYPE_STRING,
312                                 &(pair.two),
313                                 DBUS_TYPE_INVALID))
314         return dbus_message_new_error (message, DBUS_ERROR_FAILED, error.message);
315
316     _DROUTE_DEBUG ("DRoute (handle prop): %s|%s on %s\n", pair.one, pair.two, pathstr);
317
318     prop_funcs = (PropertyPair *) g_hash_table_lookup (path->properties, &pair);
319     if (!prop_funcs)
320         return dbus_message_new_error (message, DBUS_ERROR_FAILED, "Property unavailable");
321
322     datum = path_get_datum (path, pathstr);
323     if (!datum)
324         return NULL;
325
326     if (get && prop_funcs->get)
327       {
328         
329         DBusMessageIter iter;
330
331         _DROUTE_DEBUG ("DRoute (handle prop Get): %s|%s on %s\n", pair.one, pair.two, pathstr);
332
333         reply = dbus_message_new_method_return (message);
334         dbus_message_iter_init_append (reply, &iter);
335         if (!(prop_funcs->get) (&iter, datum))
336           {
337             dbus_message_unref (reply);
338             reply = dbus_message_new_error (message, DBUS_ERROR_FAILED, "Get failed");
339           }
340       }
341     else if (!get && prop_funcs->set)
342       {
343         DBusMessageIter iter;
344
345         _DROUTE_DEBUG ("DRoute (handle prop Get): %s|%s on %s\n", pair.one, pair.two, pathstr);
346
347         dbus_message_iter_init (message, &iter);
348         /* Skip the interface and property name */
349         dbus_message_iter_next(&iter);
350         dbus_message_iter_next(&iter);
351         (prop_funcs->set) (&iter, datum);
352
353         reply = dbus_message_new_method_return (message);
354       }
355     else
356       {
357         reply = dbus_message_new_error (message, DBUS_ERROR_FAILED, "Getter or setter unavailable");
358       }
359
360     return reply;
361 }
362
363 static DBusHandlerResult
364 handle_properties (DBusConnection *bus,
365                    DBusMessage    *message,
366                    DRoutePath     *path,
367                    const gchar    *iface,
368                    const gchar    *member,
369                    const gchar    *pathstr)
370 {
371     DBusMessage *reply;
372     DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
373
374     if (!g_strcmp0(member, "GetAll"))
375        reply = impl_prop_GetAll (message, path, pathstr);
376     else if (!g_strcmp0 (member, "Get"))
377        reply = impl_prop_GetSet (message, path, pathstr, TRUE);
378     else if (!g_strcmp0 (member, "Set"))
379        reply = impl_prop_GetSet (message, path, pathstr, FALSE);
380     else
381        result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
382
383     if (reply)
384       {
385         dbus_connection_send (bus, reply, NULL);
386         dbus_message_unref (reply);
387       }
388
389     return result;
390 }
391
392 /*---------------------------------------------------------------------------*/
393
394 static const char *introspection_header =
395 "<?xml version=\"1.0\"?>\n";
396
397 static const char *introspection_node_element =
398 "<node name=\"%s\">\n";
399
400 static const char *introspection_footer =
401 "</node>";
402
403 static void
404 append_interface (GString     *str,
405                   const gchar *interface,
406                   const gchar *directory)
407 {
408     gchar *filename;
409     gchar *contents;
410     gsize len;
411
412     GError *err = NULL;
413
414     filename = g_build_filename (directory, interface, NULL);
415
416     if (g_file_get_contents (filename, &contents, &len, &err))
417       {
418         g_string_append_len (str, contents, len);
419       }
420     else
421       {
422         g_warning ("AT-SPI: Cannot find introspection XML file %s - %s",
423                    filename, err->message);
424         g_error_free (err);
425       }
426
427     g_string_append (str, "\n");
428     g_free (filename);
429     g_free (contents);
430 }
431
432 static DBusHandlerResult
433 handle_introspection (DBusConnection *bus,
434                       DBusMessage    *message,
435                       DRoutePath     *path,
436                       const gchar    *iface,
437                       const gchar    *member,
438                       const gchar    *pathstr)
439 {
440     GString *output;
441     gchar *final;
442     gint i;
443
444     DBusMessage *reply;
445
446     _DROUTE_DEBUG ("DRoute (handle introspection): %s\n", pathstr);
447
448     if (g_strcmp0 (member, "Introspect"))
449         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
450
451     output = g_string_new(introspection_header);
452
453     g_string_append_printf(output, introspection_node_element, pathstr);
454
455     for (i=0; i < path->interfaces->len; i++)
456       {
457         gchar *interface = (gchar *) g_ptr_array_index (path->interfaces, i);
458         _DROUTE_DEBUG ("DRoute (appending interface): %s\n", interface);
459         append_interface(output, interface, path->cnx->introspect_dir);
460       }
461
462     g_string_append(output, introspection_footer);
463     final = g_string_free(output, FALSE);
464
465     reply = dbus_message_new_method_return (message);
466     if (!reply)
467         oom ();
468     dbus_message_append_args(reply, DBUS_TYPE_STRING, &final,
469                              DBUS_TYPE_INVALID);
470     dbus_connection_send (bus, reply, NULL);
471
472     dbus_message_unref (reply);
473     g_free(final);
474     return DBUS_HANDLER_RESULT_HANDLED;
475 }
476
477 /*---------------------------------------------------------------------------*/
478
479 static DBusHandlerResult
480 handle_other (DBusConnection *bus,
481               DBusMessage    *message,
482               DRoutePath     *path,
483               const gchar    *iface,
484               const gchar    *member,
485               const gchar    *pathstr)
486 {
487     gint result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
488
489     StrPair pair;
490     DRouteFunction func;
491     DBusMessage *reply = NULL;
492
493     void *datum;
494
495     pair.one = iface;
496     pair.two = member;
497
498     _DROUTE_DEBUG ("DRoute (handle other): %s|%s on %s\n", member, iface, pathstr);
499
500     datum = path_get_datum (path, pathstr);
501     if (!datum)
502         return result;
503
504     func = (DRouteFunction) g_hash_table_lookup (path->methods, &pair);
505     if (func != NULL)
506       {
507
508         reply = (func) (bus, message, datum);
509
510         if (!reply)
511           {
512             /* All D-Bus method calls must have a reply.
513              * If one is not provided presume that the call has a void
514              * return and no error has occured.
515              */
516             reply = dbus_message_new_method_return (message);
517           }
518         dbus_connection_send (bus, reply, NULL);
519         dbus_message_unref (reply);
520         result = DBUS_HANDLER_RESULT_HANDLED;
521       }
522
523     _DROUTE_DEBUG ("DRoute (handle other) (reply): type %d\n",
524                    dbus_message_get_type(reply));
525     return result;
526 }
527
528 /*---------------------------------------------------------------------------*/
529
530 static DBusHandlerResult
531 handle_message (DBusConnection *bus, DBusMessage *message, void *user_data)
532 {
533     DRoutePath *path = (DRoutePath *) user_data;
534     const gchar *iface   = dbus_message_get_interface (message);
535     const gchar *member  = dbus_message_get_member (message);
536     const gint   type    = dbus_message_get_type (message);
537     const gchar *pathstr = dbus_message_get_path (message);
538
539     _DROUTE_DEBUG ("DRoute (handle message): %s|%s of type %d on %s\n", member, iface, type, pathstr);
540
541     /* Check for basic reasons not to handle */
542     if (type   != DBUS_MESSAGE_TYPE_METHOD_CALL ||
543         member == NULL ||
544         iface  == NULL)
545         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
546
547     if (!strcmp (iface, "org.freedesktop.DBus.Properties"))
548         return handle_properties (bus, message, path, iface, member, pathstr);
549
550     if (!strcmp (iface, "org.freedesktop.DBus.Introspectable"))
551         return handle_introspection (bus, message, path, iface, member, pathstr);
552
553     return handle_other (bus, message, path, iface, member, pathstr);
554 }
555
556 /*---------------------------------------------------------------------------*/
557
558 DBusMessage *
559 droute_not_yet_handled_error (DBusMessage *message)
560 {
561     DBusMessage *reply;
562     gchar       *errmsg;
563
564     errmsg= g_strdup_printf (
565             "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
566             dbus_message_get_member (message),
567             dbus_message_get_signature (message),
568             dbus_message_get_interface (message));
569     reply = dbus_message_new_error (message,
570                                     DBUS_ERROR_UNKNOWN_METHOD,
571                                     errmsg);
572     g_free (errmsg);
573     return reply;
574 }
575
576 DBusMessage *
577 droute_out_of_memory_error (DBusMessage *message)
578 {
579     DBusMessage *reply;
580     gchar       *errmsg;
581
582     errmsg= g_strdup_printf (
583             "Method \"%s\" with signature \"%s\" on interface \"%s\" could not be processed due to lack of memory\n",
584             dbus_message_get_member (message),
585             dbus_message_get_signature (message),
586             dbus_message_get_interface (message));
587     reply = dbus_message_new_error (message,
588                                     DBUS_ERROR_NO_MEMORY,
589                                     errmsg);
590     g_free (errmsg);
591     return reply;
592 }
593
594 DBusMessage *
595 droute_invalid_arguments_error (DBusMessage *message)
596 {
597     DBusMessage *reply;
598     gchar       *errmsg;
599
600     errmsg= g_strdup_printf (
601             "Method \"%s\" with signature \"%s\" on interface \"%s\" was supplied with invalid arguments\n",
602             dbus_message_get_member (message),
603             dbus_message_get_signature (message),
604             dbus_message_get_interface (message));
605     reply = dbus_message_new_error (message,
606                                     DBUS_ERROR_INVALID_ARGS,
607                                     errmsg);
608     g_free (errmsg);
609     return reply;
610 }
611
612 /*END------------------------------------------------------------------------*/