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