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