Enhance droute so that unhandled messages are better debugged.
[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 static DBusMessage *
74 droute_object_does_not_exist_error (DBusMessage *message);
75
76 /*---------------------------------------------------------------------------*/
77
78 static DRoutePath *
79 path_new (DRouteContext *cnx,
80           void    *user_data,
81           DRouteGetDatumFunction get_datum)
82 {
83     DRoutePath *new_path;
84
85     new_path = g_new0 (DRoutePath, 1);
86     new_path->cnx = cnx;
87     new_path->chunks = g_string_chunk_new (CHUNKS_DEFAULT);
88     new_path->interfaces = g_ptr_array_new ();
89
90     new_path->methods = g_hash_table_new_full ((GHashFunc)str_pair_hash,
91                                                str_pair_equal,
92                                                g_free,
93                                                NULL);
94
95     new_path->properties = g_hash_table_new_full ((GHashFunc)str_pair_hash,
96                                                   str_pair_equal,
97                                                   g_free,
98                                                   NULL);
99
100     new_path->user_data = user_data;
101     new_path->get_datum = get_datum;
102
103     return new_path;
104 }
105
106 static void
107 path_free (DRoutePath *path, gpointer user_data)
108 {
109     g_string_chunk_free  (path->chunks);
110     g_ptr_array_free     (path->interfaces, TRUE);
111     g_hash_table_destroy (path->methods);
112     g_hash_table_destroy (path->properties);
113 }
114
115 static void *
116 path_get_datum (DRoutePath *path, const gchar *pathstr)
117 {
118     if (path->get_datum != NULL)
119         return (path->get_datum) (pathstr, path->user_data);
120     else
121         return path->user_data;
122 }
123
124 /*---------------------------------------------------------------------------*/
125
126 DRouteContext *
127 droute_new (DBusConnection *bus, const char *introspect_dir)
128 {
129     DRouteContext *cnx;
130
131     cnx = g_new0 (DRouteContext, 1);
132     cnx->bus = bus;
133     cnx->registered_paths = g_ptr_array_new ();
134     cnx->introspect_dir = g_strdup(introspect_dir);
135
136     return cnx;
137 }
138
139 void
140 droute_free (DRouteContext *cnx)
141 {
142     g_ptr_array_foreach (cnx->registered_paths, (GFunc) path_free, NULL);
143     g_free (cnx->introspect_dir);
144     g_free (cnx);
145 }
146
147 /*---------------------------------------------------------------------------*/
148
149 DBusConnection *
150 droute_get_bus (DRouteContext *cnx)
151 {
152     return cnx->bus;
153 }
154
155 /*---------------------------------------------------------------------------*/
156
157 static DBusObjectPathVTable droute_vtable =
158 {
159   NULL,
160   &handle_message,
161   NULL, NULL, NULL, NULL
162 };
163
164 DRoutePath *
165 droute_add_one (DRouteContext *cnx,
166                 const char    *path,
167                 const void    *data)
168 {
169     DRoutePath *new_path;
170     gboolean registered;
171
172     new_path = path_new (cnx, (void *) data, NULL);
173
174     registered = dbus_connection_register_object_path (cnx->bus, path, &droute_vtable, new_path);
175     if (!registered)
176         oom();
177
178     g_ptr_array_add (cnx->registered_paths, new_path);
179     return new_path;
180 }
181
182 DRoutePath *
183 droute_add_many (DRouteContext *cnx,
184                  const char    *path,
185                  const void    *data,
186                  const DRouteGetDatumFunction get_datum)
187 {
188     DRoutePath *new_path;
189
190     new_path = path_new (cnx, (void *) data, get_datum);
191
192     if (!dbus_connection_register_fallback (cnx->bus, path, &droute_vtable, new_path))
193         oom();
194
195     g_ptr_array_add (cnx->registered_paths, new_path);
196     return new_path;
197 }
198
199 /*---------------------------------------------------------------------------*/
200
201 void
202 droute_path_add_interface(DRoutePath *path,
203                           const char *name,
204                           const DRouteMethod   *methods,
205                           const DRouteProperty *properties)
206 {
207     gchar *itf;
208
209     g_return_if_fail (name != NULL);
210
211     itf = g_string_chunk_insert (path->chunks, name);
212     g_ptr_array_add (path->interfaces, itf);
213
214     for (; methods != NULL && methods->name != NULL; methods++)
215       {
216         gchar *meth;
217
218         meth = g_string_chunk_insert (path->chunks, methods->name);
219         g_hash_table_insert (path->methods, str_pair_new (itf, meth), methods->func);
220       }
221
222     for (; properties != NULL && properties->name != NULL; properties++)
223       {
224         gchar *prop;
225         PropertyPair *pair;
226
227         prop = g_string_chunk_insert (path->chunks, properties->name);
228         pair = g_new (PropertyPair, 1);
229         pair->get = properties->get;
230         pair->set = properties->set;
231         g_hash_table_insert (path->properties, str_pair_new (itf, prop), pair);
232       }
233 }
234
235 /*---------------------------------------------------------------------------*/
236
237 /* The data structures don't support an efficient implementation of GetAll
238  * and I don't really care.
239  */
240 static DBusMessage *
241 impl_prop_GetAll (DBusMessage *message,
242                   DRoutePath  *path,
243                   const char  *pathstr)
244 {
245     DBusMessageIter iter, iter_dict, iter_dict_entry;
246     DBusMessage *reply;
247     DBusError error;
248     GHashTableIter prop_iter;
249
250     StrPair *key;
251     PropertyPair *value;
252     gchar *iface;
253
254     void  *datum = path_get_datum (path, pathstr);
255     if (!datum)
256         return droute_object_does_not_exist_error (message);
257
258     dbus_error_init (&error);
259     if (!dbus_message_get_args
260                 (message, &error, DBUS_TYPE_STRING, &iface, DBUS_TYPE_INVALID))
261         return dbus_message_new_error (message, DBUS_ERROR_FAILED, error.message);
262
263     reply = dbus_message_new_method_return (message);
264     if (!reply)
265         oom ();
266
267     dbus_message_iter_init_append (reply, &iter);
268     if (!dbus_message_iter_open_container
269                 (&iter, DBUS_TYPE_ARRAY, "{sv}", &iter_dict))
270         oom ();
271
272     g_hash_table_iter_init (&prop_iter, path->properties);
273     while (g_hash_table_iter_next (&prop_iter, (gpointer*)&key, (gpointer*)&value))
274       {
275         if (!g_strcmp0 (key->one, iface))
276          {
277            if (!value->get)
278               continue;
279            if (!dbus_message_iter_open_container
280                         (&iter_dict, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict_entry))
281               oom ();
282            dbus_message_iter_append_basic (&iter_dict_entry, DBUS_TYPE_STRING,
283                                            key->two);
284            (value->get) (&iter_dict_entry, datum);
285            if (!dbus_message_iter_close_container (&iter_dict, &iter_dict_entry))
286                oom ();
287          }
288       }
289
290     if (!dbus_message_iter_close_container (&iter, &iter_dict))
291         oom ();
292     return reply;
293 }
294
295 static DBusMessage *
296 impl_prop_GetSet (DBusMessage *message,
297                   DRoutePath  *path,
298                   const char  *pathstr,
299                   gboolean     get)
300 {
301     DBusMessage *reply = NULL;
302     DBusError error;
303
304     StrPair pair;
305     PropertyPair *prop_funcs = NULL;
306
307     void *datum;
308
309     dbus_error_init (&error);
310     if (!dbus_message_get_args (message,
311                                 &error,
312                                 DBUS_TYPE_STRING,
313                                 &(pair.one),
314                                 DBUS_TYPE_STRING,
315                                 &(pair.two),
316                                 DBUS_TYPE_INVALID))
317         return dbus_message_new_error (message, DBUS_ERROR_FAILED, error.message);
318
319     _DROUTE_DEBUG ("DRoute (handle prop): %s|%s on %s\n", pair.one, pair.two, pathstr);
320
321     prop_funcs = (PropertyPair *) g_hash_table_lookup (path->properties, &pair);
322     if (!prop_funcs)
323         return dbus_message_new_error (message, DBUS_ERROR_FAILED, "Property unavailable");
324
325     datum = path_get_datum (path, pathstr);
326     if (!datum)
327         return droute_object_does_not_exist_error (message);
328
329     if (get && prop_funcs->get)
330       {
331         
332         DBusMessageIter iter;
333
334         _DROUTE_DEBUG ("DRoute (handle prop Get): %s|%s on %s\n", pair.one, pair.two, pathstr);
335
336         reply = dbus_message_new_method_return (message);
337         dbus_message_iter_init_append (reply, &iter);
338         if (!(prop_funcs->get) (&iter, datum))
339           {
340             dbus_message_unref (reply);
341             reply = dbus_message_new_error (message, DBUS_ERROR_FAILED, "Get failed");
342           }
343       }
344     else if (!get && prop_funcs->set)
345       {
346         DBusMessageIter iter;
347
348         _DROUTE_DEBUG ("DRoute (handle prop Get): %s|%s on %s\n", pair.one, pair.two, pathstr);
349
350         dbus_message_iter_init (message, &iter);
351         /* Skip the interface and property name */
352         dbus_message_iter_next(&iter);
353         dbus_message_iter_next(&iter);
354         (prop_funcs->set) (&iter, datum);
355
356         reply = dbus_message_new_method_return (message);
357       }
358     else
359       {
360         reply = dbus_message_new_error (message, DBUS_ERROR_FAILED, "Getter or setter unavailable");
361       }
362
363     return reply;
364 }
365
366 static DBusHandlerResult
367 handle_properties (DBusConnection *bus,
368                    DBusMessage    *message,
369                    DRoutePath     *path,
370                    const gchar    *iface,
371                    const gchar    *member,
372                    const gchar    *pathstr)
373 {
374     DBusMessage *reply;
375     DBusHandlerResult result = DBUS_HANDLER_RESULT_HANDLED;
376
377     if (!g_strcmp0(member, "GetAll"))
378        reply = impl_prop_GetAll (message, path, pathstr);
379     else if (!g_strcmp0 (member, "Get"))
380        reply = impl_prop_GetSet (message, path, pathstr, TRUE);
381     else if (!g_strcmp0 (member, "Set"))
382        reply = impl_prop_GetSet (message, path, pathstr, FALSE);
383     else
384        result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
385
386     if (reply)
387       {
388         dbus_connection_send (bus, reply, NULL);
389         dbus_message_unref (reply);
390       }
391
392     return result;
393 }
394
395 /*---------------------------------------------------------------------------*/
396
397 static const char *introspection_header =
398 "<?xml version=\"1.0\"?>\n";
399
400 static const char *introspection_node_element =
401 "<node name=\"%s\">\n";
402
403 static const char *introspection_footer =
404 "</node>";
405
406 static void
407 append_interface (GString     *str,
408                   const gchar *interface,
409                   const gchar *directory)
410 {
411     gchar *filename;
412     gchar *contents;
413     gsize len;
414
415     GError *err = NULL;
416
417     filename = g_build_filename (directory, interface, NULL);
418
419     if (g_file_get_contents (filename, &contents, &len, &err))
420       {
421         g_string_append_len (str, contents, len);
422       }
423     else
424       {
425         g_warning ("AT-SPI: Cannot find introspection XML file %s - %s",
426                    filename, err->message);
427         g_error_free (err);
428       }
429
430     g_string_append (str, "\n");
431     g_free (filename);
432     g_free (contents);
433 }
434
435 static DBusHandlerResult
436 handle_introspection (DBusConnection *bus,
437                       DBusMessage    *message,
438                       DRoutePath     *path,
439                       const gchar    *iface,
440                       const gchar    *member,
441                       const gchar    *pathstr)
442 {
443     GString *output;
444     gchar *final;
445     gint i;
446
447     DBusMessage *reply;
448
449     _DROUTE_DEBUG ("DRoute (handle introspection): %s\n", pathstr);
450
451     if (g_strcmp0 (member, "Introspect"))
452         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
453
454     output = g_string_new(introspection_header);
455
456     g_string_append_printf(output, introspection_node_element, pathstr);
457
458     for (i=0; i < path->interfaces->len; i++)
459       {
460         gchar *interface = (gchar *) g_ptr_array_index (path->interfaces, i);
461         _DROUTE_DEBUG ("DRoute (appending interface): %s\n", interface);
462         append_interface(output, interface, path->cnx->introspect_dir);
463       }
464
465     g_string_append(output, introspection_footer);
466     final = g_string_free(output, FALSE);
467
468     reply = dbus_message_new_method_return (message);
469     if (!reply)
470         oom ();
471     dbus_message_append_args(reply, DBUS_TYPE_STRING, &final,
472                              DBUS_TYPE_INVALID);
473     dbus_connection_send (bus, reply, NULL);
474
475     dbus_message_unref (reply);
476     g_free(final);
477     return DBUS_HANDLER_RESULT_HANDLED;
478 }
479
480 /*---------------------------------------------------------------------------*/
481
482 static DBusHandlerResult
483 handle_other (DBusConnection *bus,
484               DBusMessage    *message,
485               DRoutePath     *path,
486               const gchar    *iface,
487               const gchar    *member,
488               const gchar    *pathstr)
489 {
490     gint result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
491
492     StrPair pair;
493     DRouteFunction func;
494     DBusMessage *reply = NULL;
495
496     void *datum;
497
498     pair.one = iface;
499     pair.two = member;
500
501     _DROUTE_DEBUG ("DRoute (handle other): %s|%s on %s\n", member, iface, pathstr);
502
503     func = (DRouteFunction) g_hash_table_lookup (path->methods, &pair);
504     if (func != NULL)
505       {
506         datum = path_get_datum (path, pathstr);
507         if (!datum)
508             reply = droute_object_does_not_exist_error (message);
509         else
510             reply = (func) (bus, message, datum);
511
512         if (!reply)
513           {
514             /* All D-Bus method calls must have a reply.
515              * If one is not provided presume that the call has a void
516              * return and no error has occured.
517              */
518             reply = dbus_message_new_method_return (message);
519           }
520         dbus_connection_send (bus, reply, NULL);
521         dbus_message_unref (reply);
522         result = DBUS_HANDLER_RESULT_HANDLED;
523       }
524
525     _DROUTE_DEBUG ("DRoute (handle other) (reply): type %d\n",
526                    dbus_message_get_type(reply));
527     return result;
528 }
529
530 /*---------------------------------------------------------------------------*/
531
532 static DBusHandlerResult
533 handle_message (DBusConnection *bus, DBusMessage *message, void *user_data)
534 {
535     DRoutePath *path = (DRoutePath *) user_data;
536     const gchar *iface   = dbus_message_get_interface (message);
537     const gchar *member  = dbus_message_get_member (message);
538     const gint   type    = dbus_message_get_type (message);
539     const gchar *pathstr = dbus_message_get_path (message);
540
541     DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
542
543     _DROUTE_DEBUG ("DRoute (handle message): %s|%s of type %d on %s\n", member, iface, type, pathstr);
544
545     /* Check for basic reasons not to handle */
546     if (type   != DBUS_MESSAGE_TYPE_METHOD_CALL ||
547         member == NULL ||
548         iface  == NULL)
549         return result;
550
551     if (!strcmp (iface, "org.freedesktop.DBus.Properties"))
552         result = handle_properties (bus, message, path, iface, member, pathstr);
553     else if (!strcmp (iface, "org.freedesktop.DBus.Introspectable"))
554         result = handle_introspection (bus, message, path, iface, member, pathstr);
555     else
556         result = handle_other (bus, message, path, iface, member, pathstr);
557 #if 0
558     if (result == DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
559         g_print ("DRoute | Unhandled message: %s|%s of type %d on %s\n", member, iface, type, pathstr);
560 #endif
561       
562     return result;
563 }
564
565 /*---------------------------------------------------------------------------*/
566
567 static DBusMessage *
568 droute_object_does_not_exist_error (DBusMessage *message)
569 {
570     DBusMessage *reply;
571     gchar       *errmsg;
572
573     errmsg= g_strdup_printf (
574             "Method \"%s\" with signature \"%s\" on interface \"%s\" could not be processed as object %s does not exist\n",
575             dbus_message_get_member (message),
576             dbus_message_get_signature (message),
577             dbus_message_get_interface (message),
578             dbus_message_get_path (message));
579     reply = dbus_message_new_error (message,
580                                     DBUS_ERROR_FAILED,
581                                     errmsg);
582     g_free (errmsg);
583     return reply;
584 }
585
586 /*---------------------------------------------------------------------------*/
587
588 DBusMessage *
589 droute_not_yet_handled_error (DBusMessage *message)
590 {
591     DBusMessage *reply;
592     gchar       *errmsg;
593
594     errmsg= g_strdup_printf (
595             "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
596             dbus_message_get_member (message),
597             dbus_message_get_signature (message),
598             dbus_message_get_interface (message));
599     reply = dbus_message_new_error (message,
600                                     DBUS_ERROR_UNKNOWN_METHOD,
601                                     errmsg);
602     g_free (errmsg);
603     return reply;
604 }
605
606 DBusMessage *
607 droute_out_of_memory_error (DBusMessage *message)
608 {
609     DBusMessage *reply;
610     gchar       *errmsg;
611
612     errmsg= g_strdup_printf (
613             "Method \"%s\" with signature \"%s\" on interface \"%s\" could not be processed due to lack of memory\n",
614             dbus_message_get_member (message),
615             dbus_message_get_signature (message),
616             dbus_message_get_interface (message));
617     reply = dbus_message_new_error (message,
618                                     DBUS_ERROR_NO_MEMORY,
619                                     errmsg);
620     g_free (errmsg);
621     return reply;
622 }
623
624 DBusMessage *
625 droute_invalid_arguments_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\" was supplied with invalid arguments\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_INVALID_ARGS,
637                                     errmsg);
638     g_free (errmsg);
639     return reply;
640 }
641
642 /*END------------------------------------------------------------------------*/