Fix for invalid at-spi configuration
[platform/upstream/at-spi2-core.git] / bus / at-spi-bus-launcher.c
1 /* -*- mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2  *
3  * at-spi-bus-launcher: Manage the a11y bus as a child process
4  *
5  * Copyright 2011-2018 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 #include "config.h"
24
25 #include <unistd.h>
26 #include <string.h>
27 #include <signal.h>
28 #ifdef __linux__
29 #include <sys/prctl.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #endif
33 #include <sys/wait.h>
34 #include <errno.h>
35 #include <stdio.h>
36
37 #include <gio/gio.h>
38 #ifdef HAVE_X11
39 #include <X11/Xlib.h>
40 #include <X11/Xatom.h>
41 #endif
42
43 //TODO: move to vconf/vconf-internal-setting-keys.h?
44 #define VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH_CONFIGURATION_SERVICE "db/setting/accessibility/universal-switch/configuration-service"
45 #define VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH_INTERACTION_SERVICE "db/setting/accessibility/universal-switch/interaction-service"
46
47 #define MAX_NUMBER_OF_KEYS_PER_CLIENT 2
48
49 #define APP_CONTROL_OPERATION_SCREEN_READ "http://tizen.org/appcontrol/operation/read_screen"
50 #define APP_CONTROL_OPERATION_UNIVERSAL_SWITCH "http://tizen.org/appcontrol/operation/universal_switch"
51 #include <appsvc.h>
52 #include <vconf.h>
53
54 //uncomment if you want debug
55 //#ifndef TIZEN_ENGINEER_MODE
56 //#define TIZEN_ENGINEER_MODE
57 //#endif
58 #ifdef LOG_TAG
59 #undef LOG_TAG
60 #endif
61
62 #define LOG_TAG "ATSPI_BUS_LAUNCHER"
63
64 #include <dlog.h>
65 #include <aul.h>
66
67 //uncomment this if you want log suring startup
68 //seems like dlog is not working at startup time
69 #define ATSPI_BUS_LAUNCHER_LOG_TO_FILE
70
71 #ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
72 FILE *log_file;
73 #ifdef LOGD
74 #undef LOGD
75 #endif
76 #define LOGD(arg...) do {if (log_file) {fprintf(log_file, ##arg);fprintf(log_file, "\n"); fflush(log_file);}} while(0)
77 #endif
78
79 static gboolean _launch_process_repeat_until_success(gpointer user_data);
80
81 typedef enum {
82   A11Y_BUS_STATE_IDLE = 0,
83   A11Y_BUS_STATE_READING_ADDRESS,
84   A11Y_BUS_STATE_RUNNING,
85   A11Y_BUS_STATE_ERROR
86 } A11yBusState;
87
88 typedef struct {
89   const char * name;
90   const char * app_control_operation;
91   const char * vconf_key[MAX_NUMBER_OF_KEYS_PER_CLIENT];
92   int number_of_keys;
93   int launch_repeats;
94   int pid;
95 } A11yBusClient;
96
97 typedef struct {
98   GMainLoop *loop;
99   gboolean launch_immediately;
100   gboolean a11y_enabled;
101   gboolean screen_reader_enabled;
102   GHashTable *client_watcher_id;
103   GDBusConnection *session_bus;
104   GSettings *a11y_schema;
105   GSettings *interface_schema;
106   int name_owner_id;
107
108   A11yBusClient screen_reader;
109   A11yBusClient universal_switch;
110
111   GDBusProxy *client_proxy;
112
113   A11yBusState state;
114
115   /* -1 == error, 0 == pending, > 0 == running */
116   int a11y_bus_pid;
117   char *a11y_bus_address;
118   int pipefd[2];
119   int listenfd;
120   char *a11y_launch_error_message;
121 } A11yBusLauncher;
122
123 static A11yBusLauncher *_global_app = NULL;
124
125 static const gchar introspection_xml[] =
126   "<node>"
127   "  <interface name='org.a11y.Bus'>"
128   "    <method name='GetAddress'>"
129   "      <arg type='s' name='address' direction='out'/>"
130   "    </method>"
131   "  </interface>"
132   "<interface name='org.a11y.Status'>"
133   "<property name='IsEnabled' type='b' access='readwrite'/>"
134   "<property name='ScreenReaderEnabled' type='b' access='readwrite'/>"
135   "</interface>"
136   "</node>";
137 static GDBusNodeInfo *introspection_data = NULL;
138
139 static void
140 respond_to_end_session (GDBusProxy *proxy)
141 {
142   GVariant *parameters;
143
144   parameters = g_variant_new ("(bs)", TRUE, "");
145
146   g_dbus_proxy_call (proxy,
147                      "EndSessionResponse", parameters,
148                      G_DBUS_CALL_FLAGS_NONE,
149                      -1, NULL, NULL, NULL);
150 }
151
152 static void
153 g_signal_cb (GDBusProxy *proxy,
154              gchar      *sender_name,
155              gchar      *signal_name,
156              GVariant   *parameters,
157              gpointer    user_data)
158 {
159   A11yBusLauncher *app = user_data;
160
161   if (g_strcmp0 (signal_name, "QueryEndSession") == 0)
162     respond_to_end_session (proxy);
163   else if (g_strcmp0 (signal_name, "EndSession") == 0)
164     respond_to_end_session (proxy);
165   else if (g_strcmp0 (signal_name, "Stop") == 0)
166     g_main_loop_quit (app->loop);
167 }
168
169 static void
170 client_proxy_ready_cb (GObject      *source_object,
171                        GAsyncResult *res,
172                        gpointer      user_data)
173 {
174   A11yBusLauncher *app = user_data;
175   GError *error = NULL;
176
177   app->client_proxy = g_dbus_proxy_new_for_bus_finish (res, &error);
178
179   if (error != NULL)
180     {
181       g_warning ("Failed to get a client proxy: %s", error->message);
182       g_error_free (error);
183
184       return;
185     }
186
187   g_signal_connect (app->client_proxy, "g-signal",
188                     G_CALLBACK (g_signal_cb), app);
189 }
190
191 static void
192 register_client (A11yBusLauncher *app)
193 {
194   GDBusProxyFlags flags;
195   GDBusProxy *sm_proxy;
196   GError *error;
197   const gchar *app_id;
198   const gchar *autostart_id;
199   gchar *client_startup_id;
200   GVariant *parameters;
201   GVariant *variant;
202   gchar *object_path;
203
204   flags = G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
205           G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS;
206
207   error = NULL;
208   sm_proxy = g_dbus_proxy_new_sync (app->session_bus, flags, NULL,
209                                     "org.gnome.SessionManager",
210                                     "/org/gnome/SessionManager",
211                                     "org.gnome.SessionManager",
212                                     NULL, &error);
213
214   if (error != NULL)
215     {
216       g_warning ("Failed to get session manager proxy: %s", error->message);
217       g_error_free (error);
218
219       return;
220     }
221
222   app_id = "at-spi-bus-launcher";
223   autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");
224
225   if (autostart_id != NULL)
226     {
227       client_startup_id = g_strdup (autostart_id);
228       g_unsetenv ("DESKTOP_AUTOSTART_ID");
229     }
230   else
231     {
232       client_startup_id = g_strdup ("");
233     }
234
235   parameters = g_variant_new ("(ss)", app_id, client_startup_id);
236   g_free (client_startup_id);
237
238   error = NULL;
239   variant = g_dbus_proxy_call_sync (sm_proxy,
240                                     "RegisterClient", parameters,
241                                     G_DBUS_CALL_FLAGS_NONE,
242                                     -1, NULL, &error);
243
244   g_object_unref (sm_proxy);
245
246   if (error != NULL)
247     {
248       g_warning ("Failed to register client: %s", error->message);
249       g_error_free (error);
250
251       return;
252     }
253
254   g_variant_get (variant, "(o)", &object_path);
255   g_variant_unref (variant);
256
257   flags = G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES;
258   g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION, flags, NULL,
259                             "org.gnome.SessionManager", object_path,
260                             "org.gnome.SessionManager.ClientPrivate",
261                             NULL, client_proxy_ready_cb, app);
262
263   g_free (object_path);
264 }
265
266 static void
267 name_appeared_handler (GDBusConnection *connection,
268                        const gchar     *name,
269                        const gchar     *name_owner,
270                        gpointer         user_data)
271 {
272   A11yBusLauncher *app = user_data;
273
274   register_client (app);
275 }
276
277 /**
278  * unix_read_all_fd_to_string:
279  *
280  * Read all data from a file descriptor to a C string buffer.
281  */
282 static gboolean
283 unix_read_all_fd_to_string (int      fd,
284                             char    *buf,
285                             ssize_t  max_bytes)
286 {
287   ssize_t bytes_read;
288
289   while (max_bytes > 1 && (bytes_read = read (fd, buf, MIN (4096, max_bytes - 1))))
290     {
291       if (bytes_read < 0)
292         return FALSE;
293       buf += bytes_read;
294       max_bytes -= bytes_read;
295     }
296   *buf = '\0';
297   return TRUE;
298 }
299
300 static void
301 on_bus_exited (GPid     pid,
302                gint     status,
303                gpointer data)
304 {
305   A11yBusLauncher *app = data;
306
307   app->a11y_bus_pid = -1;
308   app->state = A11Y_BUS_STATE_ERROR;
309   if (app->a11y_launch_error_message == NULL)
310     {
311       if (WIFEXITED (status))
312         app->a11y_launch_error_message = g_strdup_printf ("Bus exited with code %d", WEXITSTATUS (status));
313       else if (WIFSIGNALED (status))
314         app->a11y_launch_error_message = g_strdup_printf ("Bus killed by signal %d", WTERMSIG (status));
315       else if (WIFSTOPPED (status))
316         app->a11y_launch_error_message = g_strdup_printf ("Bus stopped by signal %d", WSTOPSIG (status));
317     }
318   g_main_loop_quit (app->loop);
319 }
320
321 #ifdef DBUS_DAEMON
322 static void
323 setup_bus_child_daemon (gpointer data)
324 {
325   A11yBusLauncher *app = data;
326   (void) app;
327
328   close (app->pipefd[0]);
329   dup2 (app->pipefd[1], 3);
330   close (app->pipefd[1]);
331
332   /* On Linux, tell the bus process to exit if this process goes away */
333 #ifdef __linux__
334   prctl (PR_SET_PDEATHSIG, 15);
335 #endif
336 }
337
338 static gboolean
339 ensure_a11y_bus_daemon (A11yBusLauncher *app, char *config_path)
340 {
341   char *argv[] = { DBUS_DAEMON, config_path, "--nofork", "--print-address", "3", NULL };
342   GPid pid;
343   char addr_buf[2048];
344   GError *error = NULL;
345
346   if (app->a11y_bus_pid != 0)
347     return FALSE;
348
349   argv[1] = (char*)config_path;
350
351   if (pipe (app->pipefd) < 0)
352     g_error ("Failed to create pipe: %s", strerror (errno));
353
354   g_clear_pointer (&app->a11y_launch_error_message, g_free);
355
356   if (!g_spawn_async (NULL,
357                       argv,
358                       NULL,
359                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
360                       setup_bus_child_daemon,
361                       app,
362                       &pid,
363                       &error))
364     {
365       app->a11y_bus_pid = -1;
366       app->a11y_launch_error_message = g_strdup (error->message);
367       g_clear_error (&error);
368       goto error;
369     }
370
371   close (app->pipefd[1]);
372   app->pipefd[1] = -1;
373
374   g_child_watch_add (pid, on_bus_exited, app);
375
376   app->state = A11Y_BUS_STATE_READING_ADDRESS;
377   app->a11y_bus_pid = pid;
378   LOGD("Launched a11y bus, child is %ld", (long) pid);
379   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
380     {
381       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", strerror (errno));
382       kill (app->a11y_bus_pid, SIGTERM);
383       goto error;
384     }
385   close (app->pipefd[0]);
386   app->pipefd[0] = -1;
387   app->state = A11Y_BUS_STATE_RUNNING;
388
389   /* Trim the trailing newline */
390   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
391   LOGD("a11y bus address: %s", app->a11y_bus_address);
392
393   return TRUE;
394
395 error:
396   close (app->pipefd[0]);
397   close (app->pipefd[1]);
398   app->state = A11Y_BUS_STATE_ERROR;
399
400   return FALSE;
401 }
402 #else
403 static gboolean
404 ensure_a11y_bus_daemon (A11yBusLauncher *app, char *config_path)
405 {
406         return FALSE;
407 }
408 #endif
409
410 #ifdef DBUS_BROKER
411 static void
412 setup_bus_child_broker (gpointer data)
413 {
414   A11yBusLauncher *app = data;
415   gchar *pid_str;
416   (void) app;
417
418   dup2 (app->listenfd, 3);
419   close (app->listenfd);
420   g_setenv("LISTEN_FDS", "1", TRUE);
421
422   pid_str = g_strdup_printf("%u", getpid());
423   g_setenv("LISTEN_PID", pid_str, TRUE);
424   g_free(pid_str);
425
426   /* Tell the bus process to exit if this process goes away */
427   prctl (PR_SET_PDEATHSIG, SIGTERM);
428 }
429
430 static gboolean
431 ensure_a11y_bus_broker (A11yBusLauncher *app, char *config_path)
432 {
433   char *argv[] = { DBUS_BROKER, config_path, "--scope", "user", NULL };
434   struct sockaddr_un addr = { .sun_family = AF_UNIX };
435   socklen_t addr_len = sizeof(addr);
436   GPid pid;
437   GError *error = NULL;
438
439   if ((app->listenfd = socket (PF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0)
440     g_error ("Failed to create listening socket: %s", strerror (errno));
441
442   if (bind (app->listenfd, (struct sockaddr *)&addr, sizeof(sa_family_t)) < 0)
443     g_error ("Failed to bind listening socket: %s", strerror (errno));
444
445   if (getsockname (app->listenfd, (struct sockaddr *)&addr, &addr_len) < 0)
446     g_error ("Failed to get socket name for listening socket: %s", strerror(errno));
447
448   if (listen (app->listenfd, 1024) < 0)
449     g_error ("Failed to listen on socket: %s", strerror(errno));
450
451   g_clear_pointer (&app->a11y_launch_error_message, g_free);
452
453   if (!g_spawn_async (NULL,
454                       argv,
455                       NULL,
456                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
457                       setup_bus_child_broker,
458                       app,
459                       &pid,
460                       &error))
461     {
462       app->a11y_bus_pid = -1;
463       app->a11y_launch_error_message = g_strdup (error->message);
464       g_clear_error (&error);
465       goto error;
466     }
467
468   close (app->listenfd);
469   app->listenfd = -1;
470
471   g_child_watch_add (pid, on_bus_exited, app);
472   app->a11y_bus_pid = pid;
473   g_debug ("Launched a11y bus, child is %ld", (long) pid);
474   app->state = A11Y_BUS_STATE_RUNNING;
475
476   app->a11y_bus_address = g_strconcat("unix:abstract=", addr.sun_path + 1, NULL);
477   g_debug ("a11y bus address: %s", app->a11y_bus_address);
478
479   return TRUE;
480
481 error:
482   close (app->listenfd);
483   app->state = A11Y_BUS_STATE_ERROR;
484
485   return FALSE;
486 }
487 #else
488 static gboolean
489 ensure_a11y_bus_broker (A11yBusLauncher *app, char *config_path)
490 {
491         return FALSE;
492 }
493 #endif
494
495 static gboolean
496 ensure_a11y_bus (A11yBusLauncher *app)
497 {
498   char *config_path = NULL;
499   gboolean success = FALSE;
500
501   if (app->a11y_bus_pid != 0)
502     return FALSE;
503
504   if (g_file_test (SYSCONFDIR"/at-spi2/accessibility.conf", G_FILE_TEST_EXISTS))
505       config_path = "--config-file="SYSCONFDIR"/at-spi2/accessibility.conf";
506   else
507       config_path = "--config-file="DATADIR"/defaults/at-spi2/accessibility.conf";
508
509 #ifdef WANT_DBUS_BROKER
510     success = ensure_a11y_bus_broker (app, config_path);
511     if (!success)
512       {
513         if (!ensure_a11y_bus_daemon (app, config_path))
514             return FALSE;
515       }
516 #else
517     success = ensure_a11y_bus_daemon (app, config_path);
518     if (!success)
519       {
520         if (!ensure_a11y_bus_broker (app, config_path))
521             return FALSE;
522       }
523 #endif
524
525 #ifdef HAVE_X11
526   {
527     Display *display = XOpenDisplay (NULL);
528     if (display)
529       {
530         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
531         XChangeProperty (display,
532                          XDefaultRootWindow (display),
533                          bus_address_atom,
534                          XA_STRING, 8, PropModeReplace,
535                          (guchar *) app->a11y_bus_address, strlen (app->a11y_bus_address));
536         XFlush (display);
537         XCloseDisplay (display);
538       }
539   }
540 #endif
541
542   return TRUE;
543 }
544
545 static void
546 handle_method_call (GDBusConnection       *connection,
547                     const gchar           *sender,
548                     const gchar           *object_path,
549                     const gchar           *interface_name,
550                     const gchar           *method_name,
551                     GVariant              *parameters,
552                     GDBusMethodInvocation *invocation,
553                     gpointer               user_data)
554 {
555   A11yBusLauncher *app = user_data;
556
557   if (g_strcmp0 (method_name, "GetAddress") == 0)
558     {
559       ensure_a11y_bus (app);
560       if (app->a11y_bus_pid > 0)
561         g_dbus_method_invocation_return_value (invocation,
562                                                g_variant_new ("(s)", app->a11y_bus_address));
563       else
564         g_dbus_method_invocation_return_dbus_error (invocation,
565                                                     "org.a11y.Bus.Error",
566                                                     app->a11y_launch_error_message);
567     }
568 }
569
570 static GVariant *
571 handle_get_property  (GDBusConnection       *connection,
572                       const gchar           *sender,
573                       const gchar           *object_path,
574                       const gchar           *interface_name,
575                       const gchar           *property_name,
576                     GError **error,
577                     gpointer               user_data)
578 {
579   A11yBusLauncher *app = user_data;
580
581   if (g_strcmp0 (property_name, "IsEnabled") == 0)
582     return g_variant_new ("b", app->a11y_enabled);
583   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
584     return g_variant_new ("b", app->screen_reader_enabled);
585   else
586     return NULL;
587 }
588
589 static void
590 handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
591                                gboolean notify_gsettings)
592 {
593   GVariantBuilder builder;
594   GVariantBuilder invalidated_builder;
595
596   if (enabled == app->a11y_enabled)
597     return;
598
599   app->a11y_enabled = enabled;
600
601   if (notify_gsettings && app->interface_schema)
602     {
603       g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
604                               enabled);
605       g_settings_sync ();
606     }
607
608   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
609   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
610   g_variant_builder_add (&builder, "{sv}", "IsEnabled",
611                          g_variant_new_boolean (enabled));
612
613   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
614                                  "org.freedesktop.DBus.Properties",
615                                  "PropertiesChanged",
616                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
617                                                 &builder,
618                                                 &invalidated_builder),
619                                  NULL);
620
621   g_variant_builder_clear (&builder);
622   g_variant_builder_clear (&invalidated_builder);
623 }
624
625 static void
626 handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
627                                gboolean notify_gsettings)
628 {
629   GVariantBuilder builder;
630   GVariantBuilder invalidated_builder;
631
632   if (enabled == app->screen_reader_enabled)
633     return;
634
635   app->screen_reader_enabled = enabled;
636
637   if (notify_gsettings && app->a11y_schema)
638     {
639       g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
640                               enabled);
641       g_settings_sync ();
642     }
643
644   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
645   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
646   g_variant_builder_add (&builder, "{sv}", "ScreenReaderEnabled",
647                          g_variant_new_boolean (enabled));
648
649   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
650                                  "org.freedesktop.DBus.Properties",
651                                  "PropertiesChanged",
652                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
653                                                 &builder,
654                                                 &invalidated_builder),
655                                  NULL);
656   g_variant_builder_clear (&builder);
657   g_variant_builder_clear (&invalidated_builder);
658 }
659
660 static gboolean
661 is_client_connected(A11yBusLauncher *app)
662 {
663   guint watchers = g_hash_table_size(app->client_watcher_id);
664   LOGD("clients connected: %d", watchers);
665   return watchers > 0;
666 }
667
668 static void
669 remove_client_watch(A11yBusLauncher *app,
670                                   const gchar     *sender)
671 {
672   LOGD("Remove client watcher for %s", sender);
673   guint watcher_id = GPOINTER_TO_UINT(g_hash_table_lookup(app->client_watcher_id, sender));
674   if (watcher_id)
675     g_bus_unwatch_name(watcher_id);
676
677   g_hash_table_remove(app->client_watcher_id, sender);
678   if (!is_client_connected(app))
679     handle_a11y_enabled_change (app, FALSE, TRUE);
680 }
681
682 static void
683 on_client_name_vanished (GDBusConnection *connection,
684                                        const gchar     *name,
685                                        gpointer         user_data)
686 {
687   A11yBusLauncher *app = user_data;
688   remove_client_watch(app, name);
689 }
690
691 static void
692 add_client_watch(A11yBusLauncher *app,
693                                const gchar     *sender)
694 {
695   LOGD("Add client watcher for %s", sender);
696
697   if (g_hash_table_contains(app->client_watcher_id, sender))
698     {
699       LOGI("Watcher for %s already registered", sender);
700       return;
701     }
702
703   guint watcher_id = g_bus_watch_name(G_BUS_TYPE_SESSION,
704                      sender,
705                      G_BUS_NAME_WATCHER_FLAGS_NONE,
706                      NULL,
707                      on_client_name_vanished,
708                      app,
709                      NULL);
710
711   g_hash_table_insert(app->client_watcher_id, g_strdup(sender), GUINT_TO_POINTER(watcher_id));
712   handle_a11y_enabled_change (app, TRUE, TRUE);
713 }
714
715 static gboolean
716 handle_set_property  (GDBusConnection       *connection,
717                       const gchar           *sender,
718                       const gchar           *object_path,
719                       const gchar           *interface_name,
720                       const gchar           *property_name,
721                       GVariant *value,
722                     GError **error,
723                     gpointer               user_data)
724 {
725   A11yBusLauncher *app = user_data;
726   const gchar *type = g_variant_get_type_string (value);
727   gboolean enabled;
728
729   if (g_strcmp0 (type, "b") != 0)
730     {
731       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
732                        "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
733       return FALSE;
734     }
735
736   enabled = g_variant_get_boolean (value);
737
738   if (g_strcmp0 (property_name, "IsEnabled") == 0)
739     {
740       if (enabled)
741         add_client_watch(app, sender);
742       else
743         remove_client_watch(app, sender);
744       return TRUE;
745     }
746   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
747     {
748       handle_screen_reader_enabled_change (app, enabled, TRUE);
749       return TRUE;
750     }
751   else
752     {
753       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
754                        "Unknown property '%s'", property_name);
755       return FALSE;
756     }
757 }
758
759 static const GDBusInterfaceVTable bus_vtable =
760 {
761   handle_method_call,
762   NULL, /* handle_get_property, */
763   NULL  /* handle_set_property */
764 };
765
766 static const GDBusInterfaceVTable status_vtable =
767 {
768   NULL, /* handle_method_call */
769   handle_get_property,
770   handle_set_property
771 };
772
773 static void
774 on_bus_acquired (GDBusConnection *connection,
775                  const gchar     *name,
776                  gpointer         user_data)
777 {
778   A11yBusLauncher *app = user_data;
779   GError *error;
780   guint registration_id;
781
782   if (connection == NULL)
783     {
784       g_main_loop_quit (app->loop);
785       return;
786     }
787   app->session_bus = connection;
788
789   if (app->launch_immediately)
790     {
791       ensure_a11y_bus (app);
792       if (app->state == A11Y_BUS_STATE_ERROR)
793         {
794           g_main_loop_quit (app->loop);
795           return;
796         }
797     }
798
799   error = NULL;
800   registration_id = g_dbus_connection_register_object (connection,
801                                                        "/org/a11y/bus",
802                                                        introspection_data->interfaces[0],
803                                                        &bus_vtable,
804                                                        _global_app,
805                                                        NULL,
806                                                        &error);
807   if (registration_id == 0)
808     {
809       g_error ("%s", error->message);
810       g_clear_error (&error);
811     }
812
813   g_dbus_connection_register_object (connection,
814                                      "/org/a11y/bus",
815                                      introspection_data->interfaces[1],
816                                      &status_vtable,
817                                      _global_app,
818                                      NULL,
819                                      NULL);
820 }
821
822 static void
823 on_name_lost (GDBusConnection *connection,
824               const gchar     *name,
825               gpointer         user_data)
826 {
827   A11yBusLauncher *app = user_data;
828   if (app->session_bus == NULL
829       && connection == NULL
830       && app->a11y_launch_error_message == NULL)
831     app->a11y_launch_error_message = g_strdup ("Failed to connect to session bus");
832   g_main_loop_quit (app->loop);
833 }
834
835 static void
836 on_name_acquired (GDBusConnection *connection,
837                   const gchar     *name,
838                   gpointer         user_data)
839 {
840   g_bus_watch_name (G_BUS_TYPE_SESSION,
841                     "org.gnome.SessionManager",
842                     G_BUS_NAME_WATCHER_FLAGS_NONE,
843                     name_appeared_handler, NULL,
844                     user_data, NULL);
845 }
846
847 static int sigterm_pipefd[2];
848
849 static void
850 sigterm_handler (int signum)
851 {
852   write (sigterm_pipefd[1], "X", 1);
853 }
854
855 static gboolean
856 on_sigterm_pipe (GIOChannel  *channel,
857                  GIOCondition condition,
858                  gpointer     data)
859 {
860   A11yBusLauncher *app = data;
861
862   g_main_loop_quit (app->loop);
863
864   return FALSE;
865 }
866
867 static void
868 init_sigterm_handling (A11yBusLauncher *app)
869 {
870   GIOChannel *sigterm_channel;
871
872   if (pipe (sigterm_pipefd) < 0)
873     g_error ("Failed to create pipe: %s", strerror (errno));
874   signal (SIGTERM, sigterm_handler);
875
876   sigterm_channel = g_io_channel_unix_new (sigterm_pipefd[0]);
877   g_io_add_watch (sigterm_channel,
878                   G_IO_IN | G_IO_ERR | G_IO_HUP,
879                   on_sigterm_pipe,
880                   app);
881 }
882
883 static gboolean
884 already_running ()
885 {
886 #ifdef HAVE_X11
887   Atom AT_SPI_BUS;
888   Atom actual_type;
889   Display *bridge_display;
890   int actual_format;
891   unsigned char *data = NULL;
892   unsigned long nitems;
893   unsigned long leftover;
894   gboolean result = FALSE;
895
896   bridge_display = XOpenDisplay (NULL);
897   if (!bridge_display)
898               return FALSE;
899
900   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
901   XGetWindowProperty (bridge_display,
902                       XDefaultRootWindow (bridge_display),
903                       AT_SPI_BUS, 0L,
904                       (long) BUFSIZ, False,
905                       (Atom) 31, &actual_type, &actual_format,
906                       &nitems, &leftover, &data);
907
908   if (data)
909   {
910     GDBusConnection *bus;
911     bus = g_dbus_connection_new_for_address_sync ((const gchar *)data, 0,
912                                                   NULL, NULL, NULL);
913     if (bus != NULL)
914       {
915         result = TRUE;
916         g_object_unref (bus);
917       }
918   }
919
920   XCloseDisplay (bridge_display);
921   return result;
922 #else
923   return FALSE;
924 #endif
925 }
926
927 static GSettings *
928 get_schema (const gchar *name)
929 {
930 #if GLIB_CHECK_VERSION (2, 32, 0)
931   GSettingsSchemaSource *source = g_settings_schema_source_get_default ();
932   if (!source) return NULL;
933
934   GSettingsSchema *schema = g_settings_schema_source_lookup (source, name, FALSE);
935
936   if (schema == NULL)
937     return NULL;
938
939   return g_settings_new_full (schema, NULL, NULL);
940 #else
941   const char * const *schemas = NULL;
942   gint i;
943
944   schemas = g_settings_list_schemas ();
945   for (i = 0; schemas[i]; i++)
946   {
947     if (!strcmp (schemas[i], name))
948       return g_settings_new (schemas[i]);
949   }
950
951   return NULL;
952 #endif
953 }
954
955 static void
956 gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
957 {
958   gboolean new_val = g_settings_get_boolean (gsettings, key);
959
960   if (!strcmp (key, "toolkit-accessibility"))
961     handle_a11y_enabled_change (_global_app, new_val, FALSE);
962   else if (!strcmp (key, "screen-reader-enabled"))
963     handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
964 }
965
966 static int
967 _process_dead_tracker (int pid, void *data)
968 {
969   A11yBusLauncher *app = data;
970
971   if (app->screen_reader.pid > 0 && pid == app->screen_reader.pid)
972     {
973       LOGE("screen reader is dead, pid: %d, restarting", pid);
974       app->screen_reader.pid = 0;
975       g_timeout_add_seconds (2, _launch_process_repeat_until_success, &app->screen_reader);
976     }
977
978   if (app->universal_switch.pid > 0 && pid == app->universal_switch.pid)
979     {
980       LOGE("universal switch is dead, pid: %d, restarting", pid);
981       app->universal_switch.pid = 0;
982       g_timeout_add_seconds (2, _launch_process_repeat_until_success, &app->universal_switch);
983     }
984   return 0;
985 }
986
987 static void
988 _register_process_dead_tracker ()
989 {
990         if(_global_app->screen_reader.pid > 0 || _global_app->universal_switch.pid > 0) {
991                 LOGD("registering process dead tracker");
992                 aul_listen_app_dead_signal(_process_dead_tracker, _global_app);
993         } else {
994                 LOGD("unregistering process dead tracker");
995                 aul_listen_app_dead_signal(NULL, NULL);
996         }
997 }
998
999
1000 static gboolean
1001 _launch_client(A11yBusClient *client, gboolean by_vconf_change)
1002 {
1003    LOGD("Launching %s", client->name);
1004
1005    bundle *kb = NULL;
1006    gboolean ret = FALSE;
1007
1008    kb = bundle_create();
1009
1010    if (kb == NULL)
1011      {
1012         LOGD("Can't create bundle");
1013         return FALSE;
1014      }
1015
1016    if (by_vconf_change)
1017      {
1018         if (bundle_add_str(kb, "by_vconf_change", "yes") != BUNDLE_ERROR_NONE)
1019           {
1020              LOGD("Can't add information to bundle");
1021           }
1022      }
1023
1024    int operation_error = appsvc_set_operation(kb, client->app_control_operation);
1025    LOGD("appsvc_set_operation: %i", operation_error);
1026
1027    client->pid = appsvc_run_service(kb, 0, NULL, NULL);
1028
1029    if (client->pid > 0)
1030      {
1031         LOGD("Process launched with pid: %i", client->pid);
1032         _register_process_dead_tracker();
1033         ret = TRUE;
1034      }
1035    else
1036      {
1037         LOGD("Can't start %s - error code: %i", client->name, client->pid);
1038      }
1039
1040    bundle_free(kb);
1041    return ret;
1042 }
1043
1044 static gboolean
1045 _launch_process_repeat_until_success(gpointer user_data) {
1046     A11yBusClient *client = user_data;
1047
1048     if (client->launch_repeats > 100 || client->pid > 0)
1049       {
1050          //do not try anymore
1051          return FALSE;
1052       }
1053
1054     gboolean ret = _launch_client(client, FALSE);
1055
1056     if (ret)
1057       {
1058          //we managed to
1059          client->launch_repeats = 0;
1060          return FALSE;
1061       }
1062     client->launch_repeats++;
1063     //try again
1064     return TRUE;
1065 }
1066
1067 static gboolean
1068 _terminate_process(int pid)
1069 {
1070    int ret;
1071    int ret_aul;
1072    if (pid <= 0)
1073      return FALSE;
1074
1075    int status = aul_app_get_status_bypid(pid);
1076
1077    if (status < 0)
1078      {
1079        LOGD("App with pid %d already terminated", pid);
1080        return TRUE;
1081      }
1082
1083    LOGD("terminate process with pid %d", pid);
1084    ret_aul = aul_terminate_pid(pid);
1085    if (ret_aul >= 0)
1086      {
1087         LOGD("Terminating with aul_terminate_pid: return is %d", ret_aul);
1088         return TRUE;
1089      }
1090    else
1091      LOGD("aul_terminate_pid failed: return is %d", ret_aul);
1092
1093    LOGD("Unable to terminate process using aul api. Sending SIGTERM signal");
1094    ret = kill(pid, SIGTERM);
1095    if (!ret)
1096      {
1097         return TRUE;
1098      }
1099
1100    LOGD("Unable to terminate process: %d with api or signal.", pid);
1101    return FALSE;
1102 }
1103
1104 static gboolean
1105 _terminate_client(A11yBusClient *client)
1106 {
1107    LOGD("Terminating %s", client->name);
1108    int pid = client->pid;
1109    client->pid = 0;
1110    _register_process_dead_tracker();
1111    gboolean ret = _terminate_process(pid);
1112    return ret;
1113 }
1114
1115 void vconf_client_cb(keynode_t *node, void *user_data)
1116 {
1117    A11yBusClient *client = user_data;
1118
1119    gboolean client_needed = FALSE;
1120    int i;
1121    for (i = 0; i < client->number_of_keys; i++) {
1122       int status = 0;
1123       int ret =vconf_get_bool(client->vconf_key[i], &status);
1124       if (ret != 0)
1125       {
1126         LOGD("Could not read %s key value.\n", client->vconf_key[i]);
1127         return;
1128       }
1129       LOGD("vconf_keynode_get_bool(node): %i", status);
1130       if (status < 0)
1131         return;
1132
1133       if (status == 1) {
1134         client_needed = TRUE;
1135         break;
1136       }
1137    }
1138
1139    //check if process really exists (e.g didn't crash)
1140    if (client->pid > 0)
1141      {
1142         int err = kill(client->pid,0);
1143         //process doesn't exist
1144         if (err == ESRCH)
1145           client->pid = 0;
1146      }
1147
1148    LOGD("client_needed: %i, client->pid: %i", client_needed, client->pid);
1149    if (!client_needed && (client->pid > 0))
1150            _terminate_client(client);
1151    else if (client_needed && (client->pid <= 0))
1152      _launch_client(client, TRUE);
1153 }
1154
1155
1156 static gboolean register_executable(A11yBusClient *client)
1157 {
1158   gboolean client_needed = FALSE;
1159
1160   int i;
1161   for (i = 0; i < client->number_of_keys; i++) {
1162     if (!client->vconf_key[i]) {
1163       LOGE("Vconf_key missing for client: %d \n", i);
1164       return FALSE;
1165     }
1166
1167     int status = 0;
1168     int ret = vconf_get_bool(client->vconf_key[i], &status);
1169     if (ret != 0)
1170     {
1171       LOGD("Could not read %s key value.\n", client->vconf_key[i]);
1172       return FALSE;
1173     }
1174     ret = vconf_notify_key_changed(client->vconf_key[i], vconf_client_cb, client);
1175     if (ret != 0)
1176     {
1177       LOGD("Could not add information level callback\n");
1178       return FALSE;
1179     }
1180     if (status)
1181       client_needed = TRUE;
1182   }
1183
1184   if (client_needed)
1185   g_timeout_add_seconds(2,_launch_process_repeat_until_success, client);
1186   return TRUE;
1187 }
1188
1189 int
1190 main (int    argc,
1191       char **argv)
1192 {
1193 #ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
1194   log_file = fopen("/tmp/at-spi-bus-launcher.log", "a");
1195 #endif
1196
1197   LOGD("Starting atspi bus launcher");
1198
1199   gboolean a11y_set = FALSE;
1200   gboolean screen_reader_set = FALSE;
1201   gint i;
1202
1203   if (already_running ())
1204     {
1205        LOGD("atspi bus launcher is already running");
1206        return 0;
1207     }
1208
1209   _global_app = g_slice_new0 (A11yBusLauncher);
1210   _global_app->loop = g_main_loop_new (NULL, FALSE);
1211   _global_app->client_watcher_id = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1212
1213   _global_app->screen_reader.name = "screen-reader";
1214   _global_app->screen_reader.app_control_operation = APP_CONTROL_OPERATION_SCREEN_READ;
1215   _global_app->screen_reader.vconf_key[0] = VCONFKEY_SETAPPL_ACCESSIBILITY_TTS;
1216   _global_app->screen_reader.number_of_keys = 1;
1217
1218   _global_app->universal_switch.name = "universal-switch";
1219   _global_app->universal_switch.app_control_operation = APP_CONTROL_OPERATION_UNIVERSAL_SWITCH;
1220   _global_app->universal_switch.vconf_key[0] = VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH_CONFIGURATION_SERVICE;
1221   _global_app->universal_switch.vconf_key[1] = VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH_INTERACTION_SERVICE;
1222   _global_app->universal_switch.number_of_keys = 2;
1223
1224   for (i = 1; i < argc; i++)
1225     {
1226       if (!strcmp (argv[i], "--launch-immediately"))
1227         _global_app->launch_immediately = TRUE;
1228       else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 1)
1229         a11y_set = TRUE;
1230       else if (sscanf (argv[i], "--screen-reader=%d",
1231                        &_global_app->screen_reader_enabled) == 1)
1232         screen_reader_set = TRUE;
1233     else
1234       g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
1235     }
1236
1237   _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
1238   _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
1239
1240   if (!a11y_set)
1241     {
1242       _global_app->a11y_enabled = _global_app->interface_schema
1243                                   ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
1244                                   : _global_app->launch_immediately;
1245     }
1246
1247   if (!screen_reader_set)
1248     {
1249       _global_app->screen_reader_enabled = _global_app->a11y_schema
1250                                   ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
1251                                   : FALSE;
1252     }
1253
1254   if (_global_app->interface_schema)
1255     g_signal_connect (_global_app->interface_schema,
1256                       "changed::toolkit-accessibility",
1257                       G_CALLBACK (gsettings_key_changed), _global_app);
1258
1259   if (_global_app->a11y_schema)
1260     g_signal_connect (_global_app->a11y_schema,
1261                       "changed::screen-reader-enabled",
1262                       G_CALLBACK (gsettings_key_changed), _global_app);
1263
1264   init_sigterm_handling (_global_app);
1265
1266   introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
1267   g_assert (introspection_data != NULL);
1268
1269   g_bus_own_name (G_BUS_TYPE_SESSION,
1270                                   "org.a11y.Bus",
1271                                   G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
1272                                   on_bus_acquired,
1273                                   on_name_acquired,
1274                                   on_name_lost,
1275                                   _global_app,
1276                                   NULL);
1277
1278   register_executable (&_global_app->screen_reader);
1279   register_executable (&_global_app->universal_switch);
1280
1281   g_main_loop_run (_global_app->loop);
1282
1283   if (_global_app->a11y_bus_pid > 0)
1284     kill (_global_app->a11y_bus_pid, SIGTERM);
1285
1286   /* Clear the X property if our bus is gone; in the case where e.g.
1287    * GDM is launching a login on an X server it was using before,
1288    * we don't want early login processes to pick up the stale address.
1289    */
1290 #ifdef HAVE_X11
1291   {
1292     Display *display = XOpenDisplay (NULL);
1293     if (display)
1294       {
1295         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
1296         XDeleteProperty (display,
1297                          XDefaultRootWindow (display),
1298                          bus_address_atom);
1299
1300         XFlush (display);
1301         XCloseDisplay (display);
1302       }
1303   }
1304 #endif
1305
1306   if (_global_app->a11y_launch_error_message)
1307     {
1308       g_printerr ("Failed to launch bus: %s", _global_app->a11y_launch_error_message);
1309       return 1;
1310     }
1311   return 0;
1312 }