2.38.0
[platform/upstream/at-spi2-atk.git] / atk-adaptor / bridge.c
1 /*
2  * AT-SPI - Assistive Technology Service Provider Interface
3  * (Gnome Accessibility Project; http://developer.gnome.org/projects/gap)
4  *
5  * Copyright 2008, 2009 Codethink Ltd.
6  * Copyright 2001, 2002, 2003 Sun Microsystems Inc.,
7  * Copyright 2001, 2002, 2003 Ximian, Inc.
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #define _GNU_SOURCE
26 #include "config.h"
27
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include<sys/stat.h>
34 #include <atk/atk.h>
35
36 #include <droute/droute.h>
37 #include <atspi/atspi.h>
38 #include <atk-bridge.h>
39
40 #include "bridge.h"
41 #include "event.h"
42 #include "adaptors.h"
43 #include "object.h"
44 #include "accessible-stateset.h"
45
46 #include "accessible-register.h"
47 #include "accessible-leasing.h"
48 #include "accessible-cache.h"
49
50 #include "spi-dbus.h"
51
52 /*---------------------------------------------------------------------------*/
53
54 static DBusHandlerResult
55 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data);
56
57 SpiBridge *spi_global_app_data = NULL;
58
59 static gboolean inited = FALSE;
60 static gboolean atexit_added = FALSE;
61
62 /*---------------------------------------------------------------------------*/
63
64 static event_data *
65 add_event (const char *bus_name, const char *event)
66 {
67   event_data *evdata;
68   gchar **data;
69
70   spi_atk_add_client (bus_name);
71   evdata = g_new0 (event_data, 1);
72   data = g_strsplit (event, ":", 3);
73   if (!data)
74     {
75       g_free (evdata);
76       return NULL;
77     }
78   evdata->bus_name = g_strdup (bus_name);
79   evdata->data = data;
80   spi_global_app_data->events = g_list_append (spi_global_app_data->events, evdata);
81   return evdata;
82 }
83
84 static GSList *clients = NULL;
85
86 static void
87 tally_event_reply ()
88 {
89   static int replies_received = 0;
90
91   if (!spi_global_app_data)
92     return;
93
94   replies_received++;
95   if (replies_received == 3)
96   {
97     if (!clients)
98       spi_atk_deregister_event_listeners ();
99     spi_global_app_data->events_initialized = TRUE;
100   }
101 }
102
103 GType
104 _atk_bridge_type_from_iface (const char *iface)
105 {
106   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_ACCESSIBLE))
107     return ATK_TYPE_OBJECT;
108   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_ACTION))
109     return ATK_TYPE_ACTION;
110   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_COMPONENT))
111     return ATK_TYPE_COMPONENT;
112   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_DOCUMENT))
113     return ATK_TYPE_DOCUMENT;
114   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_HYPERTEXT))
115     return ATK_TYPE_HYPERTEXT;
116   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_HYPERLINK))
117     return ATK_TYPE_HYPERLINK;
118   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_IMAGE))
119     return ATK_TYPE_IMAGE;
120   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_SELECTION))
121     return ATK_TYPE_SELECTION;
122   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_TABLE))
123     return ATK_TYPE_TABLE;
124   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_TEXT))
125     return ATK_TYPE_TEXT;
126   if (!strcmp (iface, ATSPI_DBUS_INTERFACE_VALUE))
127     return ATK_TYPE_VALUE;
128   return 0;
129 }
130
131 DRoutePropertyFunction
132 _atk_bridge_find_property_func (const char *property, GType *type)
133 {
134   const char *iface;
135   const char *member;
136   DRouteProperty *dp;
137
138   if (!strncasecmp (property, "action.", 7))
139   {
140     iface = ATSPI_DBUS_INTERFACE_ACTION;
141     member = property + 7;
142   }
143   else if (!strncasecmp (property, "component.", 10))
144   {
145     iface = ATSPI_DBUS_INTERFACE_COMPONENT;
146     member = property + 10;
147   }
148   else if (!strncasecmp (property, "selection.", 10))
149   {
150     iface = ATSPI_DBUS_INTERFACE_SELECTION;
151     member = property + 10;
152   }
153   else if (!strncasecmp (property, "table.", 6))
154   {
155     iface = ATSPI_DBUS_INTERFACE_TABLE;
156     member = property + 6;
157   }
158   else if (!strncasecmp (property, "text.", 5))
159   {
160     iface = ATSPI_DBUS_INTERFACE_TEXT;
161     member = property + 5;
162   }
163   else if (!strncasecmp (property, "value.", 6))
164   {
165     iface = ATSPI_DBUS_INTERFACE_VALUE;
166     member = property + 6;
167   }
168   else
169   {
170     iface = ATSPI_DBUS_INTERFACE_ACCESSIBLE;
171     member = property;
172   }
173
174   *type = _atk_bridge_type_from_iface (iface);
175
176   dp = g_hash_table_lookup (spi_global_app_data->property_hash, iface);
177
178   if (!dp)
179     return NULL;
180
181   for (;dp->name; dp++)
182   {
183     if (!strcasecmp (dp->name, member))
184     {
185       return dp->get;
186     }
187   }
188   return NULL;
189 }
190
191 static void
192 add_property_to_event (event_data *evdata, const char *property)
193 {
194   AtspiPropertyDefinition *prop = g_new0 (AtspiPropertyDefinition, 1);
195   prop->func = _atk_bridge_find_property_func (property, &prop->type);
196   if (!prop->func)
197   {
198     g_warning ("atk-bridge: Request for unknown property '%s'", property);
199     g_free (prop);
200     return;
201   }
202
203   prop->name = g_strdup (property);
204   evdata->properties = g_slist_append (evdata->properties, prop);
205 }
206
207 static void
208 add_event_from_iter (DBusMessageIter *iter)
209 {
210   const char *bus_name, *event;
211   event_data *evdata;
212
213   dbus_message_iter_get_basic (iter, &bus_name);
214   dbus_message_iter_next (iter);
215   dbus_message_iter_get_basic (iter, &event);
216   dbus_message_iter_next (iter);
217   evdata = add_event (bus_name, event);
218   if (dbus_message_iter_get_arg_type (iter) == DBUS_TYPE_ARRAY)
219   {
220     DBusMessageIter iter_sub_array;
221     dbus_message_iter_recurse (iter, &iter_sub_array);
222     while (dbus_message_iter_get_arg_type (&iter_sub_array) != DBUS_TYPE_INVALID)
223     {
224       const char *property;
225       dbus_message_iter_get_basic (&iter_sub_array, &property);
226       add_property_to_event (evdata, property);
227        dbus_message_iter_next (&iter_sub_array);
228     }
229   }
230 }
231
232 static void
233 get_events_reply (DBusPendingCall *pending, void *user_data)
234 {
235   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
236   DBusMessageIter iter, iter_array, iter_struct;
237
238   if (!reply || !spi_global_app_data)
239     goto done;
240
241   if (strcmp (dbus_message_get_signature (reply), "a(ss)") != 0 &&
242       strcmp (dbus_message_get_signature (reply), "a(ssas)") != 0)
243     {
244       g_warning ("atk-bridge: GetRegisteredEvents returned message with unknown signature");
245       goto done;
246     }
247
248   dbus_message_iter_init (reply, &iter);
249   dbus_message_iter_recurse (&iter, &iter_array);
250   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
251     {
252       dbus_message_iter_recurse (&iter_array, &iter_struct);
253       add_event_from_iter (&iter_struct);
254       dbus_message_iter_next (&iter_array);
255     }
256
257 done:
258   if (reply)
259     dbus_message_unref (reply);
260   if (pending)
261     dbus_pending_call_unref (pending);
262
263   tally_event_reply ();
264 }
265
266 static void
267 get_device_events_reply (DBusPendingCall *pending, void *user_data)
268 {
269   DBusMessage *reply = dbus_pending_call_steal_reply (pending);
270   DBusMessageIter iter, iter_array, iter_struct;
271
272   if (!reply)
273     goto done;
274
275   if (strncmp (dbus_message_get_signature (reply), "a(s", 3) != 0)
276     {
277       g_warning ("atk-bridge: get_device_events_reply: unknown signature");
278       goto done;
279     }
280
281   dbus_message_iter_init (reply, &iter);
282   dbus_message_iter_recurse (&iter, &iter_array);
283   while (dbus_message_iter_get_arg_type (&iter_array) != DBUS_TYPE_INVALID)
284     {
285       char *bus_name;
286       dbus_message_iter_recurse (&iter_array, &iter_struct);
287       dbus_message_iter_get_basic (&iter_struct, &bus_name);
288       spi_atk_add_client (bus_name);
289       dbus_message_iter_next (&iter_array);
290     }
291
292 done:
293   if (reply)
294     dbus_message_unref (reply);
295   if (pending)
296     dbus_pending_call_unref (pending);
297
298   tally_event_reply ();
299 }
300
301 static void
302 get_registered_event_listeners (SpiBridge *app)
303 {
304   DBusMessage *message;
305   DBusPendingCall *pending = NULL;
306
307   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
308                                          ATSPI_DBUS_PATH_REGISTRY,
309                                          ATSPI_DBUS_INTERFACE_REGISTRY,
310                                          "GetRegisteredEvents");
311   if (!message)
312     return;
313
314   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
315   dbus_message_unref (message);
316   if (!pending)
317     {
318       spi_global_app_data->events_initialized = TRUE;
319       return;
320     }
321   dbus_pending_call_set_notify (pending, get_events_reply, NULL, NULL);
322
323   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
324                                          ATSPI_DBUS_PATH_DEC,
325                                          ATSPI_DBUS_INTERFACE_DEC,
326                                          "GetKeystrokeListeners");
327   if (!message)
328     return;
329   pending = NULL;
330   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
331   dbus_message_unref (message);
332   if (!pending)
333     {
334       spi_global_app_data->events_initialized = TRUE;
335       return;
336     }
337   dbus_pending_call_set_notify (pending, get_device_events_reply, NULL, NULL);
338
339   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
340                                          ATSPI_DBUS_PATH_DEC,
341                                          ATSPI_DBUS_INTERFACE_DEC,
342                                          "GetDeviceEventListeners");
343   if (!message)
344     return;
345   pending = NULL;
346   dbus_connection_send_with_reply (app->bus, message, &pending, -1);
347   dbus_message_unref (message);
348   if (!pending)
349     {
350       spi_global_app_data->events_initialized = TRUE;
351       return;
352     }
353   dbus_pending_call_set_notify (pending, get_device_events_reply, NULL, NULL);
354 }
355
356 static void
357 register_reply (DBusPendingCall *pending, void *user_data)
358 {
359   DBusMessage *reply;
360   SpiBridge *app = user_data;
361
362   reply = dbus_pending_call_steal_reply (pending);
363   dbus_pending_call_unref (pending);
364
365   if (!spi_global_app_data)
366     {
367       if (reply)
368          dbus_message_unref (reply);
369       return;
370     }
371
372   if (reply)
373     {
374       gchar *app_name, *obj_path;
375
376       if (strcmp (dbus_message_get_signature (reply), "(so)") != 0)
377         {
378           g_warning ("AT-SPI: Could not obtain desktop path or name\n");
379         }
380       else
381         {
382           DBusMessageIter iter, iter_struct;
383           dbus_message_iter_init (reply, &iter);
384           dbus_message_iter_recurse (&iter, &iter_struct);
385           dbus_message_iter_get_basic (&iter_struct, &app_name);
386           dbus_message_iter_next (&iter_struct);
387           dbus_message_iter_get_basic (&iter_struct, &obj_path);
388
389           g_free (app->desktop_name);
390           app->desktop_name = g_strdup (app_name);
391           g_free (app->desktop_path);
392           app->desktop_path = g_strdup (obj_path);
393         }
394     }
395   else
396     {
397       g_warning ("AT-SPI: Could not embed inside desktop");
398       return;
399     }
400   dbus_message_unref (reply);
401
402   if (!spi_global_app_data->events_initialized)
403     get_registered_event_listeners (spi_global_app_data);
404 }
405
406 static gboolean
407 register_application (gpointer data)
408 {
409   SpiBridge * app = data;
410   DBusMessage *message;
411   DBusMessageIter iter;
412   DBusPendingCall *pending;
413
414   spi_global_app_data->registration_pending = 0;
415
416   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
417                                           ATSPI_DBUS_PATH_ROOT,
418                                           ATSPI_DBUS_INTERFACE_SOCKET,
419                                           "Embed");
420
421   dbus_message_iter_init_append (message, &iter);
422   spi_object_append_reference (&iter, app->root);
423   
424     if (!dbus_connection_send_with_reply (app->bus, message, &pending, -1)
425         || !pending)
426     {
427         if (pending)
428           dbus_pending_call_unref (pending);
429
430         dbus_message_unref (message);
431         return FALSE;
432     }
433
434     dbus_pending_call_set_notify (pending, register_reply, app, NULL);
435
436   if (message)
437     dbus_message_unref (message);
438
439   return FALSE;
440 }
441
442 void
443 _atk_bridge_schedule_application_registration (SpiBridge *app)
444 {
445   /* We need the callback to be called first thing, before any other of ours
446    * (and possibly of client apps), so use a high priority and a short timeout
447    * to try and be called first by the main loop. */
448   if (!app->registration_pending)
449     app->registration_pending = spi_timeout_add_full (G_PRIORITY_HIGH, 0,
450                                                       register_application,
451                                                       app, NULL);
452 }
453
454 gboolean
455 _atk_bridge_remove_pending_application_registration (SpiBridge *app)
456 {
457   if (app->registration_pending)
458   {
459     g_source_remove (app->registration_pending);
460     app->registration_pending = 0;
461     return TRUE;
462   }
463
464   return FALSE;
465 }
466
467 /*---------------------------------------------------------------------------*/
468
469 static void
470 remove_socket ()
471 {
472   if (!spi_global_app_data)
473     return;
474
475   if (spi_global_app_data->app_bus_addr &&
476       !strncmp (spi_global_app_data->app_bus_addr, "unix:path=", 10))
477   {
478     unlink (spi_global_app_data->app_bus_addr + 10);
479     g_free (spi_global_app_data->app_bus_addr);
480     spi_global_app_data->app_bus_addr = NULL;
481   }
482
483   if (spi_global_app_data->app_tmp_dir)
484   {
485     rmdir (spi_global_app_data->app_tmp_dir);
486     g_free (spi_global_app_data->app_tmp_dir);
487     spi_global_app_data->app_tmp_dir = NULL;
488   }
489 }
490
491 static void
492 deregister_application (SpiBridge * app)
493 {
494   DBusMessage *message;
495   DBusMessageIter iter;
496   const char *uname;
497
498   if (_atk_bridge_remove_pending_application_registration (spi_global_app_data))
499     return;
500
501   message = dbus_message_new_method_call (SPI_DBUS_NAME_REGISTRY,
502                                           ATSPI_DBUS_PATH_REGISTRY,
503                                           ATSPI_DBUS_INTERFACE_REGISTRY,
504                                           "DeregisterApplication");
505   dbus_message_set_no_reply (message, TRUE);
506
507   uname = dbus_bus_get_unique_name (app->bus);
508
509   dbus_message_iter_init_append (message, &iter);
510   dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &uname);
511   dbus_connection_send (app->bus, message, NULL);
512   if (message)
513     dbus_message_unref (message);
514
515   remove_socket ();
516
517   g_free (app->desktop_name);
518   app->desktop_name = NULL;
519   g_free (app->desktop_path);
520   app->desktop_path = NULL;
521 }
522
523 /*---------------------------------------------------------------------------*/
524
525 /*---------------------------------------------------------------------------*/
526
527 static AtkPlugClass *plug_class;
528 static AtkSocketClass *socket_class;
529
530 static gchar *
531 get_plug_id (AtkPlug * plug)
532 {
533   const char *uname = dbus_bus_get_unique_name (spi_global_app_data->bus);
534   gchar *path;
535   GString *str = g_string_new (NULL);
536
537   path = spi_register_object_to_path (spi_global_register, G_OBJECT (plug));
538   g_string_printf (str, "%s:%s", uname, path);
539   g_free (path);
540   return g_string_free (str, FALSE);
541 }
542
543 AtkStateSet *
544 socket_ref_state_set (AtkObject *accessible)
545 {
546   char *child_name, *child_path;
547   AtkSocket *socket = ATK_SOCKET (accessible);
548   int count = 0;
549   int j;
550   int v;
551   DBusMessage *message, *reply;
552   DBusMessageIter iter, iter_array;
553   AtkStateSet *set;
554
555   set = atk_state_set_new ();
556
557   if (!socket->embedded_plug_id)
558     return set;
559
560   child_name = g_strdup (socket->embedded_plug_id);
561   if (!child_name)
562     return set;
563   child_path = g_utf8_strchr (child_name + 1, -1, ':');
564   if (!child_path)
565     {
566       g_free (child_name);
567       return set;
568     }
569   *(child_path++) = '\0';
570   message = dbus_message_new_method_call (child_name, child_path, ATSPI_DBUS_INTERFACE_ACCESSIBLE, "GetState");
571   g_free (child_name);
572   reply = dbus_connection_send_with_reply_and_block (spi_global_app_data->bus, message, 1, NULL);
573   dbus_message_unref (message);
574   if (reply == NULL)
575     return set;
576   if (strcmp (dbus_message_get_signature (reply), "au") != 0)
577     {
578       dbus_message_unref (reply);
579       return set;
580     }
581
582   dbus_message_iter_init (reply, &iter);
583   dbus_message_iter_recurse (&iter, &iter_array);
584   do
585     {
586       dbus_message_iter_get_basic (&iter_array, &v);
587       for (j = 0; j < 32; j++)
588         {
589           if (v & (1 << j))
590             {
591               AtkState state = spi_atk_state_from_spi_state ((count << 5) + j);
592               atk_state_set_add_state (set, state);
593             }
594         }
595       count++;
596     }
597   while (dbus_message_iter_next (&iter_array));
598   dbus_message_unref (reply);
599   return set;
600 }
601
602 static void
603 socket_embed_hook (AtkSocket * socket, const gchar * plug_id)
604 {
605   g_return_if_fail (spi_global_register != NULL);
606
607   AtkObject *accessible = ATK_OBJECT(socket);
608   gchar *plug_name, *plug_path;
609   AtkObjectClass *klass;
610
611   /* Force registration */
612   gchar *path = spi_register_object_to_path (spi_global_register, G_OBJECT (accessible));
613   /* Let the plug know that it has been embedded */
614   plug_name = g_strdup (plug_id);
615   if (!plug_name)
616     {
617       g_free (path);
618       return;
619     }
620   plug_path = g_utf8_strchr (plug_name + 1, -1, ':');
621   if (plug_path)
622     {
623       DBusMessage *message;
624       *(plug_path++) = '\0';
625       message = dbus_message_new_method_call (plug_name, plug_path, ATSPI_DBUS_INTERFACE_SOCKET, "Embedded");
626       dbus_message_append_args (message, DBUS_TYPE_STRING, &path, DBUS_TYPE_INVALID);
627       dbus_connection_send (spi_global_app_data->bus, message, NULL);
628     }
629   g_free (plug_name);
630   g_free (path);
631
632   klass = ATK_OBJECT_GET_CLASS (accessible);
633   klass->ref_state_set = socket_ref_state_set;
634 }
635
636 static void
637 install_plug_hooks ()
638 {
639   gpointer data;
640
641   data = g_type_class_ref (ATK_TYPE_PLUG);
642   plug_class = ATK_PLUG_CLASS (data);
643   data = g_type_class_ref (ATK_TYPE_SOCKET);
644   socket_class = ATK_SOCKET_CLASS (data);
645   plug_class->get_object_id = get_plug_id;
646   socket_class->embed = socket_embed_hook;
647 }
648
649 static guint
650 get_ancestral_uid (guint pid)
651 {
652   FILE *fp;
653   char buf [80];
654   int ppid = 0;
655   int uid = 0;
656   gboolean got_ppid = 0;
657   gboolean got_uid = 0;
658
659   sprintf (buf, "/proc/%d/status", pid);
660   fp = fopen (buf, "r");
661   if (!fp)
662     return 0;
663   while ((!got_ppid || !got_uid) && fgets (buf, sizeof (buf), fp))
664   {
665     if (sscanf (buf, "PPid:\t%d", &ppid) == 1)
666       got_ppid = TRUE;
667     else if (sscanf (buf, "Uid:\t%d", &uid) == 1)
668       got_uid = TRUE;
669   }
670   fclose (fp);
671
672   if (!got_ppid || !got_uid)
673     return 0;
674   if (uid != 0)
675     return uid;
676   if (ppid == 0 || ppid == 1)
677     return 0;
678   return get_ancestral_uid (ppid);
679 }
680
681 static dbus_bool_t
682 user_check (DBusConnection *bus, unsigned long uid, void *data)
683 {
684   if (uid == getuid () || uid == geteuid ())
685     return TRUE;
686   if (getuid () == 0)
687   {
688     guint ancestor = get_ancestral_uid (getpid ());
689     return (ancestor == uid || ancestor == 1 || ancestor == 0);
690   }
691   return FALSE;
692 }
693
694 static void
695 new_connection_cb (DBusServer *server, DBusConnection *con, void *data)
696 {
697   dbus_connection_set_unix_user_function (con, user_check, NULL, NULL);
698   dbus_connection_ref(con);
699   atspi_dbus_connection_setup_with_g_main(con, spi_context);
700   droute_intercept_dbus (con);
701   droute_context_register (spi_global_app_data->droute, con);
702
703   spi_global_app_data->direct_connections = g_list_append (spi_global_app_data->direct_connections, con);
704 }
705
706
707 gchar *atspi_dbus_name = NULL;
708 static gboolean atspi_no_register = FALSE;
709
710 static GOptionEntry atspi_option_entries[] = {
711   {"atspi-dbus-name", 0, 0, G_OPTION_ARG_STRING, &atspi_dbus_name,
712    "D-Bus bus name to register as", NULL},
713   {"atspi-no-register", 0, 0, G_OPTION_ARG_NONE, &atspi_no_register,
714    "Do not register with Registry Daemon", NULL},
715   {NULL}
716 };
717
718 static gchar *
719 introspect_children_cb (const char *path, void *data)
720 {
721   if (!strcmp (path, "/org/a11y/atspi/accessible"))
722     {
723       return g_strdup ("<node name=\"root\"/>\n");
724       /* TODO: Should we place the whole hierarchy here? */
725     }
726   return NULL;
727 }
728
729 static void
730 handle_event_listener_registered (DBusConnection *bus, DBusMessage *message,
731                                   void *user_data)
732 {
733   DBusMessageIter iter;
734   const char *signature = dbus_message_get_signature (message);
735
736   if (strcmp (signature, "ssas") != 0 &&
737       strcmp (signature, "ss") != 0)
738   {
739     g_warning ("got RegisterEvent with invalid signature '%s'", signature);
740     return;
741   }
742
743   dbus_message_iter_init (message, &iter);
744   add_event_from_iter (&iter);
745 }
746
747 static void
748 free_property_definition (void *data)
749 {
750   AtspiPropertyDefinition *pd = data;
751
752   g_free (pd->name);
753   g_free (pd);
754 }
755
756 static void
757 remove_events (const char *bus_name, const char *event)
758 {
759   gchar **remove_data;
760   GList *list;
761
762   remove_data = g_strsplit (event, ":", 3);
763   if (!remove_data)
764     {
765       return;
766     }
767
768   for (list = spi_global_app_data->events; list;)
769     {
770       event_data *evdata = list->data;
771       if (!g_strcmp0 (evdata->bus_name, bus_name) &&
772           spi_event_is_subtype (evdata->data, remove_data))
773         {
774           GList *next;
775           GList *events = spi_global_app_data->events;
776
777           g_strfreev (evdata->data);
778           g_free (evdata->bus_name);
779           g_slist_free_full (evdata->properties, free_property_definition);
780           g_free (evdata);
781
782           next = list->next;
783           spi_global_app_data->events = g_list_delete_link (events, list);
784           list = next;
785         }
786       else
787         {
788           list = list->next;
789         }
790     }
791
792   g_strfreev (remove_data);
793 }
794
795 static void
796 handle_event_listener_deregistered (DBusConnection *bus, DBusMessage *message,
797                                     void *user_data)
798 {
799   gchar *name;
800   char *sender;
801
802   if (!dbus_message_get_args (message, NULL, DBUS_TYPE_STRING, &sender,
803                               DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID))
804     return;
805
806   remove_events (sender, name);
807 }
808
809 static void
810 handle_device_listener_registered (DBusConnection *bus, DBusMessage *message,
811                                     void *user_data)
812 {
813   char *sender;
814   DBusMessageIter iter, iter_struct;
815
816   if (strncmp (dbus_message_get_signature (message), "(s", 2) != 0)
817     {
818       g_warning ("atk-bridge: handle_device_listener_register: unknown signature");
819       return;
820     }
821
822   dbus_message_iter_init (message, &iter);
823   dbus_message_iter_recurse (&iter, &iter_struct);
824   dbus_message_iter_get_basic (&iter_struct, &sender);
825   spi_atk_add_client (sender);
826 }
827
828 static DBusHandlerResult
829 signal_filter (DBusConnection *bus, DBusMessage *message, void *user_data)
830 {
831   const char *interface = dbus_message_get_interface (message);
832   const char *member = dbus_message_get_member (message);
833   DBusHandlerResult result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
834   static gboolean registry_lost = FALSE;
835
836   if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
837     return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
838
839   if (!strcmp (interface, ATSPI_DBUS_INTERFACE_REGISTRY))
840     {
841       result = DBUS_HANDLER_RESULT_HANDLED;
842       if (!strcmp (member, "EventListenerRegistered"))
843         handle_event_listener_registered (bus, message, user_data);
844       else if (!strcmp (member, "EventListenerDeregistered"))
845         handle_event_listener_deregistered (bus, message, user_data);
846       else
847         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
848     }
849   else if (!strcmp (interface, ATSPI_DBUS_INTERFACE_DEVICE_EVENT_LISTENER))
850     {
851       result = DBUS_HANDLER_RESULT_HANDLED;
852       if (!strcmp (member, "KeystrokeListenerRegistered"))
853         handle_device_listener_registered (bus, message, user_data);
854       else if (!strcmp (member, "DeviceListenerRegistered"))
855         handle_device_listener_registered (bus, message, user_data);
856       else
857         result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
858     }
859
860   if (!g_strcmp0(interface, DBUS_INTERFACE_DBUS) &&
861       !g_strcmp0(member, "NameOwnerChanged"))
862     {
863       char *name, *old, *new;
864       if (dbus_message_get_args (message, NULL,
865                                  DBUS_TYPE_STRING, &name,
866                                  DBUS_TYPE_STRING, &old,
867                                  DBUS_TYPE_STRING, &new,
868                                  DBUS_TYPE_INVALID))
869         {
870           if (!strcmp (name, "org.a11y.atspi.Registry"))
871             {
872               if (registry_lost && !old[0])
873                 {
874                   register_application (spi_global_app_data);
875                   registry_lost = FALSE;
876                 }
877               else if (!new[0])
878                 registry_lost = TRUE;
879             }
880           else if (*old != '\0' && *new == '\0')
881               spi_atk_remove_client (old);
882         }
883     }
884
885   return result;
886 }
887
888 int
889 spi_atk_create_socket (SpiBridge *app)
890 {
891 #ifndef DISABLE_P2P
892   DBusServer *server;
893   DBusError error;
894   const gchar *user_runtime_dir = g_get_user_runtime_dir ();
895
896   if (g_mkdir_with_parents (user_runtime_dir, 0700) != 0)
897     return -1;
898
899   if (getuid () != 0)
900   {
901     app->app_tmp_dir = g_build_filename (user_runtime_dir,
902                                          "at-spi2-XXXXXX", NULL);
903     if (!g_mkdtemp (app->app_tmp_dir))
904     {
905       g_free (app->app_tmp_dir);
906       app->app_tmp_dir = NULL;
907       return -1;
908     }
909   }
910
911   if (app->app_tmp_dir)
912     app->app_bus_addr = g_strdup_printf ("unix:path=%s/socket", app->app_tmp_dir);
913   else
914     app->app_bus_addr = g_strdup_printf ("unix:path=%s/at-spi2-socket-%d",
915                                          user_runtime_dir, getpid ());
916
917   if (!spi_global_app_data->app_bus_addr)
918     return -1;
919
920   dbus_error_init(&error);
921   server = dbus_server_listen(spi_global_app_data->app_bus_addr, &error);
922   if (server == NULL)
923   {
924     g_warning ("atk-bridge: Couldn't listen on dbus server: %s", error.message);
925     dbus_error_free (&error);
926     spi_global_app_data->app_bus_addr [0] = '\0';
927     return -1;
928   }
929
930   atspi_dbus_server_setup_with_g_main(server, spi_context);
931   dbus_server_set_new_connection_function(server, new_connection_cb, NULL, NULL);
932
933   spi_global_app_data->server = server;
934 #endif
935
936   return 0;
937 }
938
939 /*
940  * Checks the status of the environment variables
941  *
942  * At this moment it only checks NO_AT_BRIDGE
943  *
944  * Returns TRUE if there isn't anything on the environment preventing
945  * you to load the bridge, FALSE otherwise
946  */
947 static gboolean
948 check_envvar (void)
949 {
950   const gchar *envvar;
951
952   envvar = g_getenv ("NO_AT_BRIDGE");
953
954   if (envvar && atoi (envvar) == 1)
955     return FALSE;
956   else
957     return TRUE;
958 }
959
960 void
961 spi_atk_activate ()
962 {
963   DRoutePath *treepath;
964
965   spi_atk_register_event_listeners ();
966   if (!spi_global_cache)
967     {
968       spi_global_cache    = g_object_new (SPI_CACHE_TYPE, NULL);
969       treepath = droute_add_one (spi_global_app_data->droute,
970                                  "/org/a11y/atspi/cache", spi_global_cache);
971
972       if (!treepath)
973         {
974           g_warning ("atk-bridge: Error in droute_add_one().  Already running?");
975           return;
976         }
977       spi_initialize_cache (treepath);
978       if (spi_global_app_data->bus)
979         droute_path_register (treepath, spi_global_app_data->bus);
980     }
981 }
982
983 /**
984  * atk_bridge_adaptor_init: initializes the atk bridge adaptor
985  *
986  * The following needs to be initialized.
987  *
988  * - DRoute for routing message to their accessible objects.
989  * - Event handlers for emmitting signals on specific ATK events.
990  * - setup the bus for p2p communication
991  * - Application registration with the AT-SPI registry.
992  *
993  * Returns: 0 if the bridge gets or was already initialized
994  * succesfully, -1 otherwise
995  */
996 int
997 atk_bridge_adaptor_init (gint * argc, gchar ** argv[])
998 {
999   GOptionContext *opt;
1000   GError *err = NULL;
1001   DBusError error;
1002   AtkObject *root;
1003   gboolean load_bridge;
1004   DRoutePath *accpath;
1005
1006   load_bridge = check_envvar ();
1007   if (inited && !load_bridge)
1008     g_warning ("ATK Bridge is disabled but a11y has already been enabled.");
1009
1010   if (inited)
1011     return 0;
1012   if (!load_bridge)
1013     return -1;
1014
1015   inited = TRUE;
1016
1017   root = atk_get_root ();
1018   g_warn_if_fail (root);
1019   if (!root)
1020     {
1021       inited = FALSE;
1022       return -1;
1023     }
1024
1025   /* Parse command line options */
1026   opt = g_option_context_new (NULL);
1027   g_option_context_add_main_entries (opt, atspi_option_entries, NULL);
1028   g_option_context_set_ignore_unknown_options (opt, TRUE);
1029   if (!g_option_context_parse (opt, argc, argv, &err))
1030     {
1031       g_warning ("AT-SPI Option parsing failed: %s\n", err->message);
1032       g_error_free (err);
1033     }
1034   g_option_context_free (opt);
1035
1036   /* Allocate global data and do ATK initializations */
1037   spi_global_app_data = g_new0 (SpiBridge, 1);
1038   spi_global_app_data->root = g_object_ref (root);
1039   spi_global_app_data->desktop_name = g_strdup (ATSPI_DBUS_NAME_REGISTRY);
1040   spi_global_app_data->desktop_path = g_strdup (ATSPI_DBUS_PATH_ROOT);
1041
1042   /* Set up D-Bus connection and register bus name */
1043   dbus_error_init (&error);
1044   spi_global_app_data->bus = atspi_get_a11y_bus ();
1045   if (!spi_global_app_data->bus)
1046     {
1047       g_free (spi_global_app_data);
1048       spi_global_app_data = NULL;
1049       inited = FALSE;
1050       return -1;
1051     }
1052
1053   if (atspi_dbus_name != NULL)
1054     {
1055       if (dbus_bus_request_name
1056           (spi_global_app_data->bus, atspi_dbus_name, 0, &error))
1057         {
1058           g_print ("AT-SPI Recieved D-Bus name - %s\n", atspi_dbus_name);
1059         }
1060       else
1061         {
1062           g_print
1063             ("AT-SPI D-Bus name requested but could not be allocated - %s\n",
1064              atspi_dbus_name);
1065         }
1066     }
1067
1068   spi_global_app_data->main_context = g_main_context_new ();
1069
1070   atspi_dbus_connection_setup_with_g_main (spi_global_app_data->bus, NULL);
1071
1072   /* Hook our plug-and socket functions */
1073   install_plug_hooks ();
1074
1075   /* 
1076    * Create the leasing, register and cache objects.
1077    * The order is important here, the cache depends on the
1078    * register object.
1079    */
1080   spi_global_register = g_object_new (SPI_REGISTER_TYPE, NULL);
1081   spi_global_leasing  = g_object_new (SPI_LEASING_TYPE, NULL);
1082
1083   /* Register droute for routing AT-SPI messages */
1084   spi_global_app_data->droute =
1085     droute_new ();
1086
1087   accpath = droute_add_many (spi_global_app_data->droute,
1088                              "/org/a11y/atspi/accessible",
1089                              NULL,
1090                              introspect_children_cb,
1091                              NULL,
1092                              (DRouteGetDatumFunction)
1093                              spi_global_register_path_to_object);
1094
1095
1096   /* Register all interfaces with droute and set up application accessible db */
1097   spi_initialize_accessible (accpath);
1098   spi_initialize_application (accpath);
1099   spi_initialize_action (accpath);
1100   spi_initialize_collection (accpath);
1101   spi_initialize_component (accpath);
1102   spi_initialize_document (accpath);
1103   spi_initialize_editabletext (accpath);
1104   spi_initialize_hyperlink (accpath);
1105   spi_initialize_hypertext (accpath);
1106   spi_initialize_image (accpath);
1107   spi_initialize_selection (accpath);
1108   spi_initialize_socket (accpath);
1109   spi_initialize_table (accpath);
1110   spi_initialize_table_cell (accpath);
1111   spi_initialize_text (accpath);
1112   spi_initialize_value (accpath);
1113
1114   droute_context_register (spi_global_app_data->droute,
1115                            spi_global_app_data->bus);
1116
1117   /* Register methods to send D-Bus signals on certain ATK events */
1118   if (clients)
1119     spi_atk_activate ();
1120
1121   /* Set up filter and match rules to catch signals */
1122   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.Registry', sender='org.a11y.atspi.Registry'", NULL);
1123   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', interface='org.a11y.atspi.DeviceEventListener', sender='org.a11y.atspi.Registry'", NULL);
1124   dbus_bus_add_match (spi_global_app_data->bus, "type='signal', arg0='org.a11y.atspi.Registry', interface='org.freedesktop.DBus', member='NameOwnerChanged'", NULL);
1125   dbus_connection_add_filter (spi_global_app_data->bus, signal_filter, NULL,
1126                               NULL);
1127
1128   /* Register this app by sending a signal out to AT-SPI registry daemon */
1129   if (!atspi_no_register && (!root || !ATK_IS_PLUG (root)))
1130     _atk_bridge_schedule_application_registration (spi_global_app_data);
1131   else
1132     get_registered_event_listeners (spi_global_app_data);
1133
1134   if (!atexit_added)
1135     atexit (remove_socket);
1136   atexit_added = TRUE;
1137
1138   dbus_error_free (&error);
1139   return 0;
1140 }
1141
1142 void
1143 atk_bridge_adaptor_cleanup (void)
1144 {
1145   GList *l;
1146   GSList *ls;
1147
1148   if (!inited)
1149     return;
1150
1151   if (!spi_global_app_data)
1152       return;
1153
1154   spi_atk_tidy_windows ();
1155   spi_atk_deregister_event_listeners ();
1156
1157   deregister_application (spi_global_app_data);
1158
1159   if (spi_global_app_data->bus)
1160     {
1161       dbus_connection_remove_filter (spi_global_app_data->bus, signal_filter, NULL);
1162       droute_context_unregister (spi_global_app_data->droute, spi_global_app_data->bus);
1163       dbus_connection_close (spi_global_app_data->bus);
1164       dbus_connection_unref (spi_global_app_data->bus);
1165       spi_global_app_data->bus = NULL;
1166     }
1167
1168   for (l = spi_global_app_data->direct_connections; l; l = l->next)
1169     {
1170       DBusConnection *connection;
1171
1172       connection = l->data;
1173
1174       droute_context_unregister (spi_global_app_data->droute, connection);
1175       droute_unintercept_dbus (connection);
1176       dbus_connection_close (connection);
1177       dbus_connection_unref (connection);
1178     }
1179   g_list_free (spi_global_app_data->direct_connections);
1180   spi_global_app_data->direct_connections = NULL;
1181
1182   for (ls = clients; ls; ls = ls->next)
1183     g_free (ls->data);
1184   g_slist_free (clients);
1185   clients = NULL;
1186
1187   g_clear_object (&spi_global_cache);
1188   g_clear_object (&spi_global_leasing);
1189   g_clear_object (&spi_global_register);
1190
1191   if (spi_global_app_data->main_context)
1192     g_main_context_unref (spi_global_app_data->main_context);
1193
1194   droute_free (spi_global_app_data->droute);
1195
1196   g_free (spi_global_app_data);
1197   spi_global_app_data = NULL;
1198
1199   inited = FALSE;
1200 }
1201
1202 /*---------------------------------------------------------------------------*/
1203
1204 static gchar *name_match_tmpl =
1205        "type='signal', interface='org.freedesktop.DBus', member='NameOwnerChanged', arg0='%s'";
1206
1207 void
1208 spi_atk_add_client (const char *bus_name)
1209 {
1210   GSList *l;
1211   gchar *match;
1212
1213   for (l = clients; l; l = l->next)
1214   {
1215     if (!g_strcmp0 (l->data, bus_name))
1216       return;
1217   }
1218   if (!clients)
1219     spi_atk_activate ();
1220   clients = g_slist_append (clients, g_strdup (bus_name));
1221   match = g_strdup_printf (name_match_tmpl, bus_name);
1222   dbus_bus_add_match (spi_global_app_data->bus, match, NULL);
1223   g_free (match);
1224 }
1225
1226 void
1227 spi_atk_remove_client (const char *bus_name)
1228 {
1229   GSList *l;
1230   GSList *next_node;
1231
1232   l = clients;
1233   while (l)
1234   {
1235     next_node = l->next;
1236
1237     if (!g_strcmp0 (l->data, bus_name))
1238     {
1239       gchar *match = g_strdup_printf (name_match_tmpl, l->data);
1240       dbus_bus_remove_match (spi_global_app_data->bus, match, NULL);
1241   g_free (match);
1242       g_free (l->data);
1243       clients = g_slist_delete_link (clients, l);
1244       if (!clients)
1245         spi_atk_deregister_event_listeners ();
1246       return;
1247     }
1248
1249     l = next_node;
1250   }
1251 }
1252
1253 void
1254 spi_atk_add_interface (DRoutePath *path,
1255                        const char *name,
1256                        const char *introspect,
1257                        const DRouteMethod   *methods,
1258                        const DRouteProperty *properties)
1259 {
1260   droute_path_add_interface (path, name, introspect, methods, properties);
1261
1262   if (properties)
1263   {
1264     if (!spi_global_app_data->property_hash)
1265       spi_global_app_data->property_hash = g_hash_table_new_full (g_str_hash,
1266                                                                   g_str_equal,
1267                                                                   g_free, NULL);
1268     g_hash_table_insert (spi_global_app_data->property_hash, g_strdup (name),
1269                          (gpointer) properties);
1270   }
1271 }
1272 /*END------------------------------------------------------------------------*/