droute: Fix another memory few memory leaks
[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 #include <stdio.h>
27
28 #include "droute.h"
29 #include "droute-pairhash.h"
30
31 #define CHUNKS_DEFAULT (512)
32
33 #define oom() g_error ("D-Bus out of memory, this message will fail anyway")
34
35 #if defined DROUTE_DEBUG
36     #define _DROUTE_DEBUG(format, args...) g_print (format , ## args)
37 #else
38     #define _DROUTE_DEBUG(format, args...)
39 #endif
40
41 struct _DRouteContext
42 {
43     GPtrArray            *registered_paths;
44
45     gchar                *introspect_string;
46 };
47
48 struct _DRoutePath
49 {
50     DRouteContext        *cnx;
51     gchar *path;
52     gboolean prefix;
53     GStringChunk         *chunks;
54     GPtrArray            *interfaces;
55     GPtrArray            *introspection;
56     GHashTable           *methods;
57     GHashTable           *properties;
58
59     DRouteIntrospectChildrenFunction introspect_children_cb;
60     void *introspect_children_data;
61     void                   *user_data;
62     DRouteGetDatumFunction  get_datum;
63 };
64
65 /*---------------------------------------------------------------------------*/
66
67 typedef struct PropertyPair
68 {
69     DRoutePropertyFunction get;
70     DRoutePropertyFunction set;
71 } PropertyPair;
72
73 /*---------------------------------------------------------------------------*/
74
75 static DBusHandlerResult
76 handle_message (DBusConnection *bus, DBusMessage *message, void *user_data);
77
78 static DBusMessage *
79 droute_object_does_not_exist_error (DBusMessage *message);
80
81 /*---------------------------------------------------------------------------*/
82
83 static DRoutePath *
84 path_new (DRouteContext *cnx,
85           const char *path,
86           gboolean prefix,
87           void    *user_data,
88           DRouteIntrospectChildrenFunction introspect_children_cb,
89           void *introspect_children_data,
90           DRouteGetDatumFunction get_datum)
91 {
92     DRoutePath *new_path;
93
94     new_path = g_new0 (DRoutePath, 1);
95     new_path->cnx = cnx;
96     new_path->path = g_strdup (path);
97     new_path->prefix = prefix;
98     new_path->chunks = g_string_chunk_new (CHUNKS_DEFAULT);
99     new_path->interfaces = g_ptr_array_new ();
100     new_path->introspection = g_ptr_array_new ();
101
102     new_path->methods = g_hash_table_new_full ((GHashFunc)str_pair_hash,
103                                                str_pair_equal,
104                                                g_free,
105                                                NULL);
106
107     new_path->properties = g_hash_table_new_full ((GHashFunc)str_pair_hash,
108                                                   str_pair_equal,
109                                                   g_free,
110                                                   g_free);
111
112     new_path->introspect_children_cb = introspect_children_cb;
113     new_path->introspect_children_data = introspect_children_data;
114     new_path->user_data = user_data;
115     new_path->get_datum = get_datum;
116
117     return new_path;
118 }
119
120 static void
121 path_free (DRoutePath *path, gpointer user_data)
122 {
123     g_free (path->path);
124     g_string_chunk_free  (path->chunks);
125     g_ptr_array_free     (path->interfaces, TRUE);
126     g_free(g_ptr_array_free     (path->introspection, FALSE));
127     g_hash_table_destroy (path->methods);
128     g_hash_table_destroy (path->properties);
129     g_free (path);
130 }
131
132 static void *
133 path_get_datum (DRoutePath *path, const gchar *pathstr)
134 {
135     if (path->get_datum != NULL)
136         return (path->get_datum) (pathstr, path->user_data);
137     else
138         return path->user_data;
139 }
140
141 /*---------------------------------------------------------------------------*/
142
143 DRouteContext *
144 droute_new ()
145 {
146     DRouteContext *cnx;
147
148     cnx = g_new0 (DRouteContext, 1);
149     cnx->registered_paths = g_ptr_array_new ();
150
151     return cnx;
152 }
153
154 void
155 droute_free (DRouteContext *cnx)
156 {
157     g_ptr_array_foreach (cnx->registered_paths, (GFunc) path_free, NULL);
158     g_ptr_array_free (cnx->registered_paths, TRUE);
159     g_free (cnx);
160 }
161
162 /*---------------------------------------------------------------------------*/
163
164 /*---------------------------------------------------------------------------*/
165
166 static DBusObjectPathVTable droute_vtable =
167 {
168   NULL,
169   &handle_message,
170   NULL, NULL, NULL, NULL
171 };
172
173 DRoutePath *
174 droute_add_one (DRouteContext *cnx,
175                 const char    *path,
176                 const void    *data)
177 {
178     DRoutePath *new_path;
179
180     new_path = path_new (cnx, path, FALSE, (void *)data, NULL, NULL, NULL);
181
182     g_ptr_array_add (cnx->registered_paths, new_path);
183     return new_path;
184 }
185
186 DRoutePath *
187 droute_add_many (DRouteContext *cnx,
188                  const char    *path,
189                  const void    *data,
190                  DRouteIntrospectChildrenFunction introspect_children_cb,
191                  void *introspect_children_data,
192                  const DRouteGetDatumFunction get_datum)
193 {
194     DRoutePath *new_path;
195
196     new_path = path_new (cnx, path, TRUE, (void *) data,
197                          introspect_children_cb, introspect_children_data,
198                          get_datum);
199
200     g_ptr_array_add (cnx->registered_paths, new_path);
201     return new_path;
202 }
203
204 /*---------------------------------------------------------------------------*/
205
206 void
207 droute_path_add_interface(DRoutePath *path,
208                           const char *name,
209                           const char *introspect,
210                           const DRouteMethod   *methods,
211                           const DRouteProperty *properties)
212 {
213     gchar *itf;
214
215     g_return_if_fail (name != NULL);
216
217     itf = g_string_chunk_insert (path->chunks, name);
218     g_ptr_array_add (path->interfaces, itf);
219     g_ptr_array_add (path->introspection, (gpointer) introspect);
220
221     for (; methods != NULL && methods->name != NULL; methods++)
222       {
223         gchar *meth;
224
225         meth = g_string_chunk_insert (path->chunks, methods->name);
226         g_hash_table_insert (path->methods, str_pair_new (itf, meth), methods->func);
227       }
228
229     for (; properties != NULL && properties->name != NULL; properties++)
230       {
231         gchar *prop;
232         PropertyPair *pair;
233
234         prop = g_string_chunk_insert (path->chunks, properties->name);
235         pair = g_new (PropertyPair, 1);
236         pair->get = properties->get;
237         pair->set = properties->set;
238         g_hash_table_insert (path->properties, str_pair_new (itf, prop), pair);
239       }
240 }
241
242 /*---------------------------------------------------------------------------*/
243
244 /* The data structures don't support an efficient implementation of GetAll
245  * and I don't really care.
246  */
247 static DBusMessage *
248 impl_prop_GetAll (DBusMessage *message,
249                   DRoutePath  *path,
250                   const char  *pathstr)
251 {
252     DBusMessageIter iter, iter_dict, iter_dict_entry;
253     DBusMessage *reply;
254     DBusError error;
255     GHashTableIter prop_iter;
256
257     StrPair *key;
258     PropertyPair *value;
259     gchar *iface;
260
261     void  *datum = path_get_datum (path, pathstr);
262     if (!datum)
263         return droute_object_does_not_exist_error (message);
264
265     dbus_error_init (&error);
266     if (!dbus_message_get_args
267                 (message, &error, DBUS_TYPE_STRING, &iface, DBUS_TYPE_INVALID))
268         return dbus_message_new_error (message, DBUS_ERROR_FAILED, error.message);
269
270     reply = dbus_message_new_method_return (message);
271     if (!reply)
272         oom ();
273
274     dbus_message_iter_init_append (reply, &iter);
275     if (!dbus_message_iter_open_container
276                 (&iter, DBUS_TYPE_ARRAY, "{sv}", &iter_dict))
277         oom ();
278
279     g_hash_table_iter_init (&prop_iter, path->properties);
280     while (g_hash_table_iter_next (&prop_iter, (gpointer*)&key, (gpointer*)&value))
281       {
282         if (!g_strcmp0 (key->one, iface))
283          {
284            if (!value->get)
285               continue;
286            if (!dbus_message_iter_open_container
287                         (&iter_dict, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict_entry))
288               oom ();
289            dbus_message_iter_append_basic (&iter_dict_entry, DBUS_TYPE_STRING,
290                                            &key->two);
291            (value->get) (&iter_dict_entry, datum);
292            if (!dbus_message_iter_close_container (&iter_dict, &iter_dict_entry))
293                oom ();
294          }
295       }
296
297     if (!dbus_message_iter_close_container (&iter, &iter_dict))
298         oom ();
299     return reply;
300 }
301
302 static DBusMessage *
303 impl_prop_GetSet (DBusMessage *message,
304                   DRoutePath  *path,
305                   const char  *pathstr,
306                   gboolean     get)
307 {
308     DBusMessage *reply = NULL;
309     DBusError error;
310
311     StrPair pair;
312     PropertyPair *prop_funcs = NULL;
313
314     void *datum;
315
316     dbus_error_init (&error);
317     if (!dbus_message_get_args (message,
318                                 &error,
319                                 DBUS_TYPE_STRING,
320                                 &(pair.one),
321                                 DBUS_TYPE_STRING,
322                                 &(pair.two),
323                                 DBUS_TYPE_INVALID))
324         return dbus_message_new_error (message, DBUS_ERROR_FAILED, error.message);
325
326     _DROUTE_DEBUG ("DRoute (handle prop): %s|%s on %s\n", pair.one, pair.two, pathstr);
327
328     prop_funcs = (PropertyPair *) g_hash_table_lookup (path->properties, &pair);
329     if (!prop_funcs)
330 #ifdef DBUS_ERROR_UNKNOWN_PROPERTY
331         return dbus_message_new_error (message, DBUS_ERROR_UNKNOWN_PROPERTY, "Property unavailable");
332 #else
333         return dbus_message_new_error (message, DBUS_ERROR_FAILED, "Property unavailable");
334 #endif
335
336     datum = path_get_datum (path, pathstr);
337     if (!datum)
338         return droute_object_does_not_exist_error (message);
339
340     if (get && prop_funcs->get)
341       {
342         
343         DBusMessageIter iter;
344
345         _DROUTE_DEBUG ("DRoute (handle prop Get): %s|%s on %s\n", pair.one, pair.two, pathstr);
346
347         reply = dbus_message_new_method_return (message);
348         dbus_message_iter_init_append (reply, &iter);
349         if (!(prop_funcs->get) (&iter, datum))
350           {
351             dbus_message_unref (reply);
352             reply = dbus_message_new_error (message, DBUS_ERROR_FAILED, "Get failed");
353           }
354       }
355     else if (!get && prop_funcs->set)
356       {
357         DBusMessageIter iter;
358
359         _DROUTE_DEBUG ("DRoute (handle prop Get): %s|%s on %s\n", pair.one, pair.two, pathstr);
360
361         dbus_message_iter_init (message, &iter);
362         /* Skip the interface and property name */
363         dbus_message_iter_next(&iter);
364         dbus_message_iter_next(&iter);
365         (prop_funcs->set) (&iter, datum);
366
367         reply = dbus_message_new_method_return (message);
368       }
369 #ifdef DBUS_ERROR_PROPERTY_READ_ONLY
370     else if (!get)
371       {
372         reply = dbus_message_new_error (message, DBUS_ERROR_PROPERTY_READ_ONLY, "Property is read-only");
373       }
374 #endif
375     else
376       {
377         reply = dbus_message_new_error (message, DBUS_ERROR_FAILED, "Getter or setter unavailable");
378       }
379
380     return reply;
381 }
382
383 static DBusHandlerResult
384 handle_dbus (DBusConnection *bus,
385                    DBusMessage    *message,
386                    const gchar    *iface,
387                    const gchar    *member,
388                    const gchar    *pathstr)
389 {
390   static int id = 1;
391   char *id_str = (char *) g_malloc(40);
392   DBusMessage *reply;
393
394   if (strcmp (iface, DBUS_INTERFACE_DBUS) != 0 ||
395       strcmp (member, "Hello") != 0)
396     {
397       g_free (id_str);
398       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
399     }
400
401     /* TODO: Fix this hack (we don't handle wrap-around, for instance) */
402     sprintf (id_str, ":1.%d", id++);
403     reply = dbus_message_new_method_return (message);
404     dbus_message_append_args (reply, DBUS_TYPE_STRING, &id_str, DBUS_TYPE_INVALID);
405     dbus_connection_send (bus, reply, NULL);
406   dbus_connection_flush (bus);
407     dbus_message_unref (reply);
408   g_free (id_str);
409     return DBUS_HANDLER_RESULT_HANDLED;
410 }
411
412 static DBusHandlerResult
413 handle_properties (DBusConnection *bus,
414                    DBusMessage    *message,
415                    DRoutePath     *path,
416                    const gchar    *iface,
417                    const gchar    *member,
418                    const gchar    *pathstr)
419 {
420     DBusMessage *reply = NULL;
421     DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
422
423     if (!g_strcmp0(member, "GetAll"))
424        reply = impl_prop_GetAll (message, path, pathstr);
425     else if (!g_strcmp0 (member, "Get"))
426        reply = impl_prop_GetSet (message, path, pathstr, TRUE);
427     else if (!g_strcmp0 (member, "Set"))
428        reply = impl_prop_GetSet (message, path, pathstr, FALSE);
429     else
430        result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
431
432     if (reply)
433       {
434         dbus_connection_send (bus, reply, NULL);
435         dbus_message_unref (reply);
436       }
437
438     return result;
439 }
440
441 /*---------------------------------------------------------------------------*/
442
443 static const char *introspection_header =
444 "<?xml version=\"1.0\"?>\n";
445
446 static const char *introspection_node_element =
447 "<node name=\"%s\">\n";
448
449 static const char *introspection_footer =
450 "</node>";
451
452 static DBusHandlerResult
453 handle_introspection (DBusConnection *bus,
454                       DBusMessage    *message,
455                       DRoutePath     *path,
456                       const gchar    *iface,
457                       const gchar    *member,
458                       const gchar    *pathstr)
459 {
460     GString *output;
461     gchar *final;
462     gint i;
463
464     DBusMessage *reply;
465
466     _DROUTE_DEBUG ("DRoute (handle introspection): %s\n", pathstr);
467
468     if (g_strcmp0 (member, "Introspect"))
469         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
470
471     output = g_string_new(introspection_header);
472
473     g_string_append_printf(output, introspection_node_element, pathstr);
474
475     if (!path->get_datum || path_get_datum (path, pathstr))
476       {
477         for (i=0; i < path->introspection->len; i++)
478           {
479             gchar *introspect = (gchar *) g_ptr_array_index (path->introspection, i);
480             g_string_append (output, introspect);
481           }
482       }
483
484     if (path->introspect_children_cb)
485       {
486         gchar *children = (*path->introspect_children_cb) (pathstr, path->introspect_children_data);
487         if (children)
488           {
489             g_string_append (output, children);
490             g_free (children);
491           }
492       }
493
494     g_string_append(output, introspection_footer);
495     final = g_string_free(output, FALSE);
496
497     reply = dbus_message_new_method_return (message);
498     if (!reply)
499         oom ();
500     dbus_message_append_args(reply, DBUS_TYPE_STRING, &final,
501                              DBUS_TYPE_INVALID);
502     dbus_connection_send (bus, reply, NULL);
503
504     dbus_message_unref (reply);
505     g_free(final);
506     return DBUS_HANDLER_RESULT_HANDLED;
507 }
508
509 /*---------------------------------------------------------------------------*/
510
511 static DBusHandlerResult
512 handle_other (DBusConnection *bus,
513               DBusMessage    *message,
514               DRoutePath     *path,
515               const gchar    *iface,
516               const gchar    *member,
517               const gchar    *pathstr)
518 {
519     gint result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
520
521     StrPair pair;
522     DRouteFunction func;
523     DBusMessage *reply = NULL;
524
525     void *datum;
526
527     pair.one = iface;
528     pair.two = member;
529
530     _DROUTE_DEBUG ("DRoute (handle other): %s|%s on %s\n", member, iface, pathstr);
531
532     func = (DRouteFunction) g_hash_table_lookup (path->methods, &pair);
533     if (func != NULL)
534       {
535         datum = path_get_datum (path, pathstr);
536         if (!datum)
537             reply = droute_object_does_not_exist_error (message);
538         else
539             reply = (func) (bus, message, datum);
540
541         /* All D-Bus method calls must have a reply.
542          * If one is not provided presume that the caller has already
543          * sent one.
544          */
545         if (reply)
546           {
547             dbus_connection_send (bus, reply, NULL);
548             dbus_message_unref (reply);
549           }
550         result = DBUS_HANDLER_RESULT_HANDLED;
551       }
552
553     _DROUTE_DEBUG ("DRoute (handle other) (reply): type %d\n",
554                    dbus_message_get_type(reply));
555     return result;
556 }
557
558 /*---------------------------------------------------------------------------*/
559
560 static DBusHandlerResult
561 handle_message (DBusConnection *bus, DBusMessage *message, void *user_data)
562 {
563     DRoutePath *path = (DRoutePath *) user_data;
564     const gchar *iface   = dbus_message_get_interface (message);
565     const gchar *member  = dbus_message_get_member (message);
566     const gint   type    = dbus_message_get_type (message);
567     const gchar *pathstr = dbus_message_get_path (message);
568
569     DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
570
571     _DROUTE_DEBUG ("DRoute (handle message): %s|%s of type %d on %s\n", member, iface, type, pathstr);
572
573     /* Check for basic reasons not to handle */
574     if (type   != DBUS_MESSAGE_TYPE_METHOD_CALL ||
575         member == NULL ||
576         iface  == NULL)
577         return result;
578
579     if (!strcmp (pathstr, DBUS_PATH_DBUS))
580         result = handle_dbus (bus, message, iface, member, pathstr);
581     else if (!strcmp (iface, "org.freedesktop.DBus.Properties"))
582         result = handle_properties (bus, message, path, iface, member, pathstr);
583     else if (!strcmp (iface, "org.freedesktop.DBus.Introspectable"))
584         result = handle_introspection (bus, message, path, iface, member, pathstr);
585     else
586         result = handle_other (bus, message, path, iface, member, pathstr);
587 #if 0
588     if (result == DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
589         g_print ("DRoute | Unhandled message: %s|%s of type %d on %s\n", member, iface, type, pathstr);
590 #endif
591       
592     return result;
593 }
594
595 /*---------------------------------------------------------------------------*/
596
597 static DBusMessage *
598 droute_object_does_not_exist_error (DBusMessage *message)
599 {
600     DBusMessage *reply;
601     gchar       *errmsg;
602
603     errmsg= g_strdup_printf (
604             "Method \"%s\" with signature \"%s\" on interface \"%s\" could not be processed as object %s does not exist\n",
605             dbus_message_get_member (message),
606             dbus_message_get_signature (message),
607             dbus_message_get_interface (message),
608             dbus_message_get_path (message));
609 #ifdef DBUS_ERROR_UNKNOWN_OBJECT
610     reply = dbus_message_new_error (message,
611                                     DBUS_ERROR_UNKNOWN_OBJECT,
612                                     errmsg);
613 #else
614     reply = dbus_message_new_error (message,
615                                     DBUS_ERROR_FAILED,
616                                     errmsg);
617 #endif
618     g_free (errmsg);
619     return reply;
620 }
621
622 /*---------------------------------------------------------------------------*/
623
624 DBusMessage *
625 droute_not_yet_handled_error (DBusMessage *message)
626 {
627     DBusMessage *reply;
628     gchar       *errmsg;
629
630     errmsg= g_strdup_printf (
631             "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
632             dbus_message_get_member (message),
633             dbus_message_get_signature (message),
634             dbus_message_get_interface (message));
635     reply = dbus_message_new_error (message,
636                                     DBUS_ERROR_UNKNOWN_METHOD,
637                                     errmsg);
638     g_free (errmsg);
639     return reply;
640 }
641
642 DBusMessage *
643 droute_out_of_memory_error (DBusMessage *message)
644 {
645     DBusMessage *reply;
646     gchar       *errmsg;
647
648     errmsg= g_strdup_printf (
649             "Method \"%s\" with signature \"%s\" on interface \"%s\" could not be processed due to lack of memory\n",
650             dbus_message_get_member (message),
651             dbus_message_get_signature (message),
652             dbus_message_get_interface (message));
653     reply = dbus_message_new_error (message,
654                                     DBUS_ERROR_NO_MEMORY,
655                                     errmsg);
656     g_free (errmsg);
657     return reply;
658 }
659
660 DBusMessage *
661 droute_invalid_arguments_error (DBusMessage *message)
662 {
663     DBusMessage *reply;
664     gchar       *errmsg;
665
666     errmsg= g_strdup_printf (
667             "Method \"%s\" with signature \"%s\" on interface \"%s\" was supplied with invalid arguments\n",
668             dbus_message_get_member (message),
669             dbus_message_get_signature (message),
670             dbus_message_get_interface (message));
671     reply = dbus_message_new_error (message,
672                                     DBUS_ERROR_INVALID_ARGS,
673                                     errmsg);
674     g_free (errmsg);
675     return reply;
676 }
677
678 void
679 droute_path_register (DRoutePath *path, DBusConnection *bus)
680 {
681     if (path->prefix)
682       dbus_connection_register_fallback (bus, path->path, &droute_vtable, path);
683     else
684       dbus_connection_register_object_path (bus, path->path,
685                                             &droute_vtable, path);
686 }
687
688 void
689 droute_path_unregister (DRoutePath *path, DBusConnection *bus)
690 {
691   dbus_connection_unregister_object_path (bus, path->path);
692 }
693
694 void
695 droute_context_register (DRouteContext *cnx, DBusConnection *bus)
696 {
697     g_ptr_array_foreach (cnx->registered_paths, (GFunc) droute_path_register,
698                          bus);
699 }
700
701 void
702 droute_context_unregister (DRouteContext *cnx, DBusConnection *bus)
703 {
704     g_ptr_array_foreach (cnx->registered_paths, (GFunc) droute_path_unregister,
705                          bus);
706 }
707
708 void
709 droute_context_deregister (DRouteContext *cnx, DBusConnection *bus)
710 {
711     g_ptr_array_foreach (cnx->registered_paths, (GFunc) droute_path_unregister,
712                          bus);
713 }
714
715 void
716 droute_intercept_dbus (DBusConnection *bus)
717 {
718     dbus_connection_register_object_path (bus, DBUS_PATH_DBUS,
719                                           &droute_vtable, NULL);
720 }
721
722 void
723 droute_unintercept_dbus (DBusConnection *bus)
724 {
725     dbus_connection_unregister_object_path (bus, DBUS_PATH_DBUS);
726 }
727
728 /*END------------------------------------------------------------------------*/