Merge "tizen: Add additional unit for "unified" user session" into tizen
[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     {
353       char buf[4096] = { 0 };
354       strerror_r (errno, buf, sizeof(buf));
355       g_error ("Failed to create pipe: %s", buf);
356     }
357
358   g_clear_pointer (&app->a11y_launch_error_message, g_free);
359
360   if (!g_spawn_async (NULL,
361                       argv,
362                       NULL,
363                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
364                       setup_bus_child_daemon,
365                       app,
366                       &pid,
367                       &error))
368     {
369       app->a11y_bus_pid = -1;
370       app->a11y_launch_error_message = g_strdup (error->message);
371       g_clear_error (&error);
372       goto error;
373     }
374
375   close (app->pipefd[1]);
376   app->pipefd[1] = -1;
377
378   g_child_watch_add (pid, on_bus_exited, app);
379
380   app->state = A11Y_BUS_STATE_READING_ADDRESS;
381   app->a11y_bus_pid = pid;
382   LOGD("Launched a11y bus, child is %ld", (long) pid);
383   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
384     {
385       char buf[4096] = { 0 };
386       strerror_r (errno, buf, sizeof(buf));
387       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", buf);
388       kill (app->a11y_bus_pid, SIGTERM);
389       goto error;
390     }
391   close (app->pipefd[0]);
392   app->pipefd[0] = -1;
393   app->state = A11Y_BUS_STATE_RUNNING;
394
395   /* Trim the trailing newline */
396   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
397   LOGD("a11y bus address: %s", app->a11y_bus_address);
398
399   return TRUE;
400
401 error:
402   close (app->pipefd[0]);
403   close (app->pipefd[1]);
404   app->state = A11Y_BUS_STATE_ERROR;
405
406   return FALSE;
407 }
408 #else
409 static gboolean
410 ensure_a11y_bus_daemon (A11yBusLauncher *app, char *config_path)
411 {
412         return FALSE;
413 }
414 #endif
415
416 #ifdef DBUS_BROKER
417 static void
418 setup_bus_child_broker (gpointer data)
419 {
420   A11yBusLauncher *app = data;
421   gchar *pid_str;
422   (void) app;
423
424   dup2 (app->listenfd, 3);
425   close (app->listenfd);
426   g_setenv("LISTEN_FDS", "1", TRUE);
427
428   pid_str = g_strdup_printf("%u", getpid());
429   g_setenv("LISTEN_PID", pid_str, TRUE);
430   g_free(pid_str);
431
432   /* Tell the bus process to exit if this process goes away */
433   prctl (PR_SET_PDEATHSIG, SIGTERM);
434 }
435
436 static gboolean
437 ensure_a11y_bus_broker (A11yBusLauncher *app, char *config_path)
438 {
439   char *argv[] = { DBUS_BROKER, config_path, "--scope", "user", NULL };
440   struct sockaddr_un addr = { .sun_family = AF_UNIX };
441   socklen_t addr_len = sizeof(addr);
442   GPid pid;
443   GError *error = NULL;
444
445   if ((app->listenfd = socket (PF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0)
446     {
447       char buf[4096] = { 0 };
448       strerror_r (errno, buf, sizeof(buf));
449       g_error ("Failed to create listening socket: %s", buf);
450     }
451
452   if (bind (app->listenfd, (struct sockaddr *)&addr, sizeof(sa_family_t)) < 0)
453     {
454       char buf[4096] = { 0 };
455       strerror_r (errno, buf, sizeof(buf));
456       g_error ("Failed to bind listening socket: %s", buf);
457     }
458
459   if (getsockname (app->listenfd, (struct sockaddr *)&addr, &addr_len) < 0)
460     {
461       char buf[4096] = { 0 };
462       strerror_r (errno, buf, sizeof(buf));
463       g_error ("Failed to get socket name for listening socket: %s", buf);
464     }
465
466   if (listen (app->listenfd, 1024) < 0)
467     {
468       char buf[4096] = { 0 };
469       strerror_r (errno, buf, sizeof(buf));
470       g_error ("Failed to listen on socket: %s", buf);
471     }
472
473   g_clear_pointer (&app->a11y_launch_error_message, g_free);
474
475   if (!g_spawn_async (NULL,
476                       argv,
477                       NULL,
478                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
479                       setup_bus_child_broker,
480                       app,
481                       &pid,
482                       &error))
483     {
484       app->a11y_bus_pid = -1;
485       app->a11y_launch_error_message = g_strdup (error->message);
486       g_clear_error (&error);
487       goto error;
488     }
489
490   close (app->listenfd);
491   app->listenfd = -1;
492
493   g_child_watch_add (pid, on_bus_exited, app);
494   app->a11y_bus_pid = pid;
495   g_debug ("Launched a11y bus, child is %ld", (long) pid);
496   app->state = A11Y_BUS_STATE_RUNNING;
497
498   app->a11y_bus_address = g_strconcat("unix:abstract=", addr.sun_path + 1, NULL);
499   g_debug ("a11y bus address: %s", app->a11y_bus_address);
500
501   return TRUE;
502
503 error:
504   close (app->listenfd);
505   app->state = A11Y_BUS_STATE_ERROR;
506
507   return FALSE;
508 }
509 #else
510 static gboolean
511 ensure_a11y_bus_broker (A11yBusLauncher *app, char *config_path)
512 {
513         return FALSE;
514 }
515 #endif
516
517 static gboolean
518 ensure_a11y_bus (A11yBusLauncher *app)
519 {
520   char *config_path = NULL;
521   gboolean success = FALSE;
522
523   if (app->a11y_bus_pid != 0)
524     return FALSE;
525
526   if (g_file_test (SYSCONFDIR"/at-spi2/accessibility.conf", G_FILE_TEST_EXISTS))
527       config_path = "--config-file="SYSCONFDIR"/at-spi2/accessibility.conf";
528   else
529       config_path = "--config-file="DATADIR"/defaults/at-spi2/accessibility.conf";
530
531 #ifdef WANT_DBUS_BROKER
532     success = ensure_a11y_bus_broker (app, config_path);
533     if (!success)
534       {
535         if (!ensure_a11y_bus_daemon (app, config_path))
536             return FALSE;
537       }
538 #else
539     success = ensure_a11y_bus_daemon (app, config_path);
540     if (!success)
541       {
542         if (!ensure_a11y_bus_broker (app, config_path))
543             return FALSE;
544       }
545 #endif
546
547 #ifdef HAVE_X11
548   {
549     Display *display = XOpenDisplay (NULL);
550     if (display)
551       {
552         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
553         XChangeProperty (display,
554                          XDefaultRootWindow (display),
555                          bus_address_atom,
556                          XA_STRING, 8, PropModeReplace,
557                          (guchar *) app->a11y_bus_address, strlen (app->a11y_bus_address));
558         XFlush (display);
559         XCloseDisplay (display);
560       }
561   }
562 #endif
563
564   return TRUE;
565 }
566
567 static void
568 handle_method_call (GDBusConnection       *connection,
569                     const gchar           *sender,
570                     const gchar           *object_path,
571                     const gchar           *interface_name,
572                     const gchar           *method_name,
573                     GVariant              *parameters,
574                     GDBusMethodInvocation *invocation,
575                     gpointer               user_data)
576 {
577   A11yBusLauncher *app = user_data;
578
579   if (g_strcmp0 (method_name, "GetAddress") == 0)
580     {
581       ensure_a11y_bus (app);
582       if (app->a11y_bus_pid > 0)
583         g_dbus_method_invocation_return_value (invocation,
584                                                g_variant_new ("(s)", app->a11y_bus_address));
585       else
586         g_dbus_method_invocation_return_dbus_error (invocation,
587                                                     "org.a11y.Bus.Error",
588                                                     app->a11y_launch_error_message);
589     }
590 }
591
592 static GVariant *
593 handle_get_property  (GDBusConnection       *connection,
594                       const gchar           *sender,
595                       const gchar           *object_path,
596                       const gchar           *interface_name,
597                       const gchar           *property_name,
598                     GError **error,
599                     gpointer               user_data)
600 {
601   A11yBusLauncher *app = user_data;
602
603   if (g_strcmp0 (property_name, "IsEnabled") == 0)
604     return g_variant_new ("b", app->a11y_enabled);
605   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
606     return g_variant_new ("b", app->screen_reader_enabled);
607   else
608     return NULL;
609 }
610
611 static void
612 handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
613                                gboolean notify_gsettings)
614 {
615   GVariantBuilder builder;
616   GVariantBuilder invalidated_builder;
617
618   if (enabled == app->a11y_enabled)
619     return;
620
621   app->a11y_enabled = enabled;
622
623   if (notify_gsettings && app->interface_schema)
624     {
625       g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
626                               enabled);
627       g_settings_sync ();
628     }
629
630   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
631   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
632   g_variant_builder_add (&builder, "{sv}", "IsEnabled",
633                          g_variant_new_boolean (enabled));
634
635   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
636                                  "org.freedesktop.DBus.Properties",
637                                  "PropertiesChanged",
638                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
639                                                 &builder,
640                                                 &invalidated_builder),
641                                  NULL);
642
643   g_variant_builder_clear (&builder);
644   g_variant_builder_clear (&invalidated_builder);
645 }
646
647 static void
648 handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
649                                gboolean notify_gsettings)
650 {
651   GVariantBuilder builder;
652   GVariantBuilder invalidated_builder;
653
654   if (enabled == app->screen_reader_enabled)
655     return;
656
657   app->screen_reader_enabled = enabled;
658
659   if (notify_gsettings && app->a11y_schema)
660     {
661       g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
662                               enabled);
663       g_settings_sync ();
664     }
665
666   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
667   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
668   g_variant_builder_add (&builder, "{sv}", "ScreenReaderEnabled",
669                          g_variant_new_boolean (enabled));
670
671   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
672                                  "org.freedesktop.DBus.Properties",
673                                  "PropertiesChanged",
674                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
675                                                 &builder,
676                                                 &invalidated_builder),
677                                  NULL);
678   g_variant_builder_clear (&builder);
679   g_variant_builder_clear (&invalidated_builder);
680 }
681
682 static gboolean
683 is_client_connected(A11yBusLauncher *app)
684 {
685   guint watchers = g_hash_table_size(app->client_watcher_id);
686   LOGD("clients connected: %d", watchers);
687   return watchers > 0;
688 }
689
690 static void
691 remove_client_watch(A11yBusLauncher *app,
692                                   const gchar     *sender)
693 {
694   LOGD("Remove client watcher for %s", sender);
695   guint watcher_id = GPOINTER_TO_UINT(g_hash_table_lookup(app->client_watcher_id, sender));
696   if (watcher_id)
697     g_bus_unwatch_name(watcher_id);
698
699   g_hash_table_remove(app->client_watcher_id, sender);
700   if (!is_client_connected(app))
701     handle_a11y_enabled_change (app, FALSE, TRUE);
702 }
703
704 static void
705 on_client_name_vanished (GDBusConnection *connection,
706                                        const gchar     *name,
707                                        gpointer         user_data)
708 {
709   A11yBusLauncher *app = user_data;
710   remove_client_watch(app, name);
711 }
712
713 static void
714 add_client_watch(A11yBusLauncher *app,
715                                const gchar     *sender)
716 {
717   LOGD("Add client watcher for %s", sender);
718
719   if (g_hash_table_contains(app->client_watcher_id, sender))
720     {
721       LOGI("Watcher for %s already registered", sender);
722       return;
723     }
724
725   guint watcher_id = g_bus_watch_name(G_BUS_TYPE_SESSION,
726                      sender,
727                      G_BUS_NAME_WATCHER_FLAGS_NONE,
728                      NULL,
729                      on_client_name_vanished,
730                      app,
731                      NULL);
732
733   g_hash_table_insert(app->client_watcher_id, g_strdup(sender), GUINT_TO_POINTER(watcher_id));
734   handle_a11y_enabled_change (app, TRUE, TRUE);
735 }
736
737 static gboolean
738 handle_set_property  (GDBusConnection       *connection,
739                       const gchar           *sender,
740                       const gchar           *object_path,
741                       const gchar           *interface_name,
742                       const gchar           *property_name,
743                       GVariant *value,
744                     GError **error,
745                     gpointer               user_data)
746 {
747   A11yBusLauncher *app = user_data;
748   const gchar *type = g_variant_get_type_string (value);
749   gboolean enabled;
750
751   if (g_strcmp0 (type, "b") != 0)
752     {
753       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
754                        "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
755       return FALSE;
756     }
757
758   enabled = g_variant_get_boolean (value);
759
760   if (g_strcmp0 (property_name, "IsEnabled") == 0)
761     {
762       if (enabled)
763         add_client_watch(app, sender);
764       else
765         remove_client_watch(app, sender);
766       return TRUE;
767     }
768   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
769     {
770       handle_screen_reader_enabled_change (app, enabled, TRUE);
771       return TRUE;
772     }
773   else
774     {
775       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
776                        "Unknown property '%s'", property_name);
777       return FALSE;
778     }
779 }
780
781 static const GDBusInterfaceVTable bus_vtable =
782 {
783   handle_method_call,
784   NULL, /* handle_get_property, */
785   NULL  /* handle_set_property */
786 };
787
788 static const GDBusInterfaceVTable status_vtable =
789 {
790   NULL, /* handle_method_call */
791   handle_get_property,
792   handle_set_property
793 };
794
795 static void
796 on_bus_acquired (GDBusConnection *connection,
797                  const gchar     *name,
798                  gpointer         user_data)
799 {
800   A11yBusLauncher *app = user_data;
801   GError *error;
802   guint registration_id;
803
804   if (connection == NULL)
805     {
806       g_main_loop_quit (app->loop);
807       return;
808     }
809   app->session_bus = connection;
810
811   if (app->launch_immediately)
812     {
813       ensure_a11y_bus (app);
814       if (app->state == A11Y_BUS_STATE_ERROR)
815         {
816           g_main_loop_quit (app->loop);
817           return;
818         }
819     }
820
821   error = NULL;
822   registration_id = g_dbus_connection_register_object (connection,
823                                                        "/org/a11y/bus",
824                                                        introspection_data->interfaces[0],
825                                                        &bus_vtable,
826                                                        _global_app,
827                                                        NULL,
828                                                        &error);
829   if (registration_id == 0)
830     {
831       g_error ("%s", error->message);
832       g_clear_error (&error);
833     }
834
835   g_dbus_connection_register_object (connection,
836                                      "/org/a11y/bus",
837                                      introspection_data->interfaces[1],
838                                      &status_vtable,
839                                      _global_app,
840                                      NULL,
841                                      NULL);
842 }
843
844 static void
845 on_name_lost (GDBusConnection *connection,
846               const gchar     *name,
847               gpointer         user_data)
848 {
849   A11yBusLauncher *app = user_data;
850   if (app->session_bus == NULL
851       && connection == NULL
852       && app->a11y_launch_error_message == NULL)
853     app->a11y_launch_error_message = g_strdup ("Failed to connect to session bus");
854   g_main_loop_quit (app->loop);
855 }
856
857 static void
858 on_name_acquired (GDBusConnection *connection,
859                   const gchar     *name,
860                   gpointer         user_data)
861 {
862   g_bus_watch_name (G_BUS_TYPE_SESSION,
863                     "org.gnome.SessionManager",
864                     G_BUS_NAME_WATCHER_FLAGS_NONE,
865                     name_appeared_handler, NULL,
866                     user_data, NULL);
867 }
868
869 static int sigterm_pipefd[2];
870
871 static void
872 sigterm_handler (int signum)
873 {
874   write (sigterm_pipefd[1], "X", 1);
875 }
876
877 static gboolean
878 on_sigterm_pipe (GIOChannel  *channel,
879                  GIOCondition condition,
880                  gpointer     data)
881 {
882   A11yBusLauncher *app = data;
883
884   g_main_loop_quit (app->loop);
885
886   return FALSE;
887 }
888
889 static void
890 init_sigterm_handling (A11yBusLauncher *app)
891 {
892   GIOChannel *sigterm_channel;
893
894   if (pipe (sigterm_pipefd) < 0)
895     {
896       char buf[4096] = { 0 };
897       strerror_r (errno, buf, sizeof(buf));
898       g_error ("Failed to create pipe: %s", buf);
899     }
900   signal (SIGTERM, sigterm_handler);
901
902   sigterm_channel = g_io_channel_unix_new (sigterm_pipefd[0]);
903   g_io_add_watch (sigterm_channel,
904                   G_IO_IN | G_IO_ERR | G_IO_HUP,
905                   on_sigterm_pipe,
906                   app);
907 }
908
909 static gboolean
910 already_running ()
911 {
912 #ifdef HAVE_X11
913   Atom AT_SPI_BUS;
914   Atom actual_type;
915   Display *bridge_display;
916   int actual_format;
917   unsigned char *data = NULL;
918   unsigned long nitems;
919   unsigned long leftover;
920   gboolean result = FALSE;
921
922   bridge_display = XOpenDisplay (NULL);
923   if (!bridge_display)
924               return FALSE;
925
926   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
927   XGetWindowProperty (bridge_display,
928                       XDefaultRootWindow (bridge_display),
929                       AT_SPI_BUS, 0L,
930                       (long) BUFSIZ, False,
931                       (Atom) 31, &actual_type, &actual_format,
932                       &nitems, &leftover, &data);
933
934   if (data)
935   {
936     GDBusConnection *bus;
937     bus = g_dbus_connection_new_for_address_sync ((const gchar *)data, 0,
938                                                   NULL, NULL, NULL);
939     if (bus != NULL)
940       {
941         result = TRUE;
942         g_object_unref (bus);
943       }
944   }
945
946   XCloseDisplay (bridge_display);
947   return result;
948 #else
949   return FALSE;
950 #endif
951 }
952
953 static GSettings *
954 get_schema (const gchar *name)
955 {
956 #if GLIB_CHECK_VERSION (2, 32, 0)
957   GSettingsSchemaSource *source = g_settings_schema_source_get_default ();
958   if (!source) return NULL;
959
960   GSettingsSchema *schema = g_settings_schema_source_lookup (source, name, FALSE);
961
962   if (schema == NULL)
963     return NULL;
964
965   return g_settings_new_full (schema, NULL, NULL);
966 #else
967   const char * const *schemas = NULL;
968   gint i;
969
970   schemas = g_settings_list_schemas ();
971   for (i = 0; schemas[i]; i++)
972   {
973     if (!strcmp (schemas[i], name))
974       return g_settings_new (schemas[i]);
975   }
976
977   return NULL;
978 #endif
979 }
980
981 static void
982 gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
983 {
984   gboolean new_val = g_settings_get_boolean (gsettings, key);
985
986   if (!strcmp (key, "toolkit-accessibility"))
987     handle_a11y_enabled_change (_global_app, new_val, FALSE);
988   else if (!strcmp (key, "screen-reader-enabled"))
989     handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
990 }
991
992 static int
993 _process_dead_tracker (int pid, void *data)
994 {
995   A11yBusLauncher *app = data;
996
997   if (app->screen_reader.pid > 0 && pid == app->screen_reader.pid)
998     {
999       LOGE("screen reader is dead, pid: %d, restarting", pid);
1000       app->screen_reader.pid = 0;
1001       g_timeout_add_seconds (2, _launch_process_repeat_until_success, &app->screen_reader);
1002     }
1003
1004   if (app->universal_switch.pid > 0 && pid == app->universal_switch.pid)
1005     {
1006       LOGE("universal switch is dead, pid: %d, restarting", pid);
1007       app->universal_switch.pid = 0;
1008       g_timeout_add_seconds (2, _launch_process_repeat_until_success, &app->universal_switch);
1009     }
1010   return 0;
1011 }
1012
1013 static void
1014 _register_process_dead_tracker ()
1015 {
1016         if(_global_app->screen_reader.pid > 0 || _global_app->universal_switch.pid > 0) {
1017                 LOGD("registering process dead tracker");
1018                 aul_listen_app_dead_signal(_process_dead_tracker, _global_app);
1019         } else {
1020                 LOGD("unregistering process dead tracker");
1021                 aul_listen_app_dead_signal(NULL, NULL);
1022         }
1023 }
1024
1025
1026 static gboolean
1027 _launch_client(A11yBusClient *client, gboolean by_vconf_change)
1028 {
1029    LOGD("Launching %s", client->name);
1030
1031    bundle *kb = NULL;
1032    gboolean ret = FALSE;
1033
1034    kb = bundle_create();
1035
1036    if (kb == NULL)
1037      {
1038         LOGD("Can't create bundle");
1039         return FALSE;
1040      }
1041
1042    if (by_vconf_change)
1043      {
1044         if (bundle_add_str(kb, "by_vconf_change", "yes") != BUNDLE_ERROR_NONE)
1045           {
1046              LOGD("Can't add information to bundle");
1047           }
1048      }
1049
1050    int operation_error = appsvc_set_operation(kb, client->app_control_operation);
1051    LOGD("appsvc_set_operation: %i", operation_error);
1052
1053    client->pid = appsvc_run_service(kb, 0, NULL, NULL);
1054
1055    if (client->pid > 0)
1056      {
1057         LOGD("Process launched with pid: %i", client->pid);
1058         _register_process_dead_tracker();
1059         ret = TRUE;
1060      }
1061    else
1062      {
1063         LOGD("Can't start %s - error code: %i", client->name, client->pid);
1064      }
1065
1066    bundle_free(kb);
1067    return ret;
1068 }
1069
1070 static gboolean
1071 _launch_process_repeat_until_success(gpointer user_data) {
1072     A11yBusClient *client = user_data;
1073
1074     if (client->launch_repeats > 100 || client->pid > 0)
1075       {
1076          //do not try anymore
1077          return FALSE;
1078       }
1079
1080     gboolean ret = _launch_client(client, FALSE);
1081
1082     if (ret)
1083       {
1084          //we managed to
1085          client->launch_repeats = 0;
1086          return FALSE;
1087       }
1088     client->launch_repeats++;
1089     //try again
1090     return TRUE;
1091 }
1092
1093 static gboolean
1094 _terminate_process(int pid)
1095 {
1096    int ret;
1097    int ret_aul;
1098    if (pid <= 0)
1099      return FALSE;
1100
1101    int status = aul_app_get_status_bypid(pid);
1102
1103    if (status < 0)
1104      {
1105        LOGD("App with pid %d already terminated", pid);
1106        return TRUE;
1107      }
1108
1109    LOGD("terminate process with pid %d", pid);
1110    ret_aul = aul_terminate_pid(pid);
1111    if (ret_aul >= 0)
1112      {
1113         LOGD("Terminating with aul_terminate_pid: return is %d", ret_aul);
1114         return TRUE;
1115      }
1116    else
1117      LOGD("aul_terminate_pid failed: return is %d", ret_aul);
1118
1119    LOGD("Unable to terminate process using aul api. Sending SIGTERM signal");
1120    ret = kill(pid, SIGTERM);
1121    if (!ret)
1122      {
1123         return TRUE;
1124      }
1125
1126    LOGD("Unable to terminate process: %d with api or signal.", pid);
1127    return FALSE;
1128 }
1129
1130 static gboolean
1131 _terminate_client(A11yBusClient *client)
1132 {
1133    LOGD("Terminating %s", client->name);
1134    int pid = client->pid;
1135    client->pid = 0;
1136    _register_process_dead_tracker();
1137    gboolean ret = _terminate_process(pid);
1138    return ret;
1139 }
1140
1141 void vconf_client_cb(keynode_t *node, void *user_data)
1142 {
1143    A11yBusClient *client = user_data;
1144
1145    gboolean client_needed = FALSE;
1146    int i;
1147    for (i = 0; i < client->number_of_keys; i++) {
1148       int status = 0;
1149       int ret =vconf_get_bool(client->vconf_key[i], &status);
1150       if (ret != 0)
1151       {
1152         LOGD("Could not read %s key value.\n", client->vconf_key[i]);
1153         return;
1154       }
1155       LOGD("vconf_keynode_get_bool(node): %i", status);
1156       if (status < 0)
1157         return;
1158
1159       if (status == 1) {
1160         client_needed = TRUE;
1161         break;
1162       }
1163    }
1164
1165    //check if process really exists (e.g didn't crash)
1166    if (client->pid > 0)
1167      {
1168         int err = kill(client->pid,0);
1169         //process doesn't exist
1170         if (err == ESRCH)
1171           client->pid = 0;
1172      }
1173
1174    LOGD("client_needed: %i, client->pid: %i", client_needed, client->pid);
1175    if (!client_needed && (client->pid > 0))
1176            _terminate_client(client);
1177    else if (client_needed && (client->pid <= 0))
1178      _launch_client(client, TRUE);
1179 }
1180
1181
1182 static gboolean register_executable(A11yBusClient *client)
1183 {
1184   gboolean client_needed = FALSE;
1185
1186   int i;
1187   for (i = 0; i < client->number_of_keys; i++) {
1188     if (!client->vconf_key[i]) {
1189       LOGE("Vconf_key missing for client: %d \n", i);
1190       return FALSE;
1191     }
1192
1193     int status = 0;
1194     int ret = vconf_get_bool(client->vconf_key[i], &status);
1195     if (ret != 0)
1196     {
1197       LOGD("Could not read %s key value.\n", client->vconf_key[i]);
1198       return FALSE;
1199     }
1200     ret = vconf_notify_key_changed(client->vconf_key[i], vconf_client_cb, client);
1201     if (ret != 0)
1202     {
1203       LOGD("Could not add information level callback\n");
1204       return FALSE;
1205     }
1206     if (status)
1207       client_needed = TRUE;
1208   }
1209
1210   if (client_needed)
1211   g_timeout_add_seconds(2,_launch_process_repeat_until_success, client);
1212   return TRUE;
1213 }
1214
1215 int
1216 main (int    argc,
1217       char **argv)
1218 {
1219 #ifdef ATSPI_BUS_LAUNCHER_LOG_TO_FILE
1220   log_file = fopen("/tmp/at-spi-bus-launcher.log", "a");
1221 #endif
1222
1223   LOGD("Starting atspi bus launcher");
1224
1225   gboolean a11y_set = FALSE;
1226   gboolean screen_reader_set = FALSE;
1227   gint i;
1228
1229   if (already_running ())
1230     {
1231        LOGD("atspi bus launcher is already running");
1232        return 0;
1233     }
1234
1235   _global_app = g_slice_new0 (A11yBusLauncher);
1236   _global_app->loop = g_main_loop_new (NULL, FALSE);
1237   _global_app->client_watcher_id = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
1238
1239   _global_app->screen_reader.name = "screen-reader";
1240   _global_app->screen_reader.app_control_operation = APP_CONTROL_OPERATION_SCREEN_READ;
1241   _global_app->screen_reader.vconf_key[0] = VCONFKEY_SETAPPL_ACCESSIBILITY_TTS;
1242   _global_app->screen_reader.number_of_keys = 1;
1243
1244   _global_app->universal_switch.name = "universal-switch";
1245   _global_app->universal_switch.app_control_operation = APP_CONTROL_OPERATION_UNIVERSAL_SWITCH;
1246   _global_app->universal_switch.vconf_key[0] = VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH_CONFIGURATION_SERVICE;
1247   _global_app->universal_switch.vconf_key[1] = VCONFKEY_SETAPPL_ACCESSIBILITY_UNIVERSAL_SWITCH_INTERACTION_SERVICE;
1248   _global_app->universal_switch.number_of_keys = 2;
1249
1250   for (i = 1; i < argc; i++)
1251     {
1252       if (!strcmp (argv[i], "--launch-immediately"))
1253         _global_app->launch_immediately = TRUE;
1254       else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 1)
1255         a11y_set = TRUE;
1256       else if (sscanf (argv[i], "--screen-reader=%d",
1257                        &_global_app->screen_reader_enabled) == 1)
1258         screen_reader_set = TRUE;
1259     else
1260       g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
1261     }
1262
1263   _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
1264   _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
1265
1266   if (!a11y_set)
1267     {
1268       _global_app->a11y_enabled = _global_app->interface_schema
1269                                   ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
1270                                   : _global_app->launch_immediately;
1271     }
1272
1273   if (!screen_reader_set)
1274     {
1275       _global_app->screen_reader_enabled = _global_app->a11y_schema
1276                                   ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
1277                                   : FALSE;
1278     }
1279
1280   if (_global_app->interface_schema)
1281     g_signal_connect (_global_app->interface_schema,
1282                       "changed::toolkit-accessibility",
1283                       G_CALLBACK (gsettings_key_changed), _global_app);
1284
1285   if (_global_app->a11y_schema)
1286     g_signal_connect (_global_app->a11y_schema,
1287                       "changed::screen-reader-enabled",
1288                       G_CALLBACK (gsettings_key_changed), _global_app);
1289
1290   init_sigterm_handling (_global_app);
1291
1292   introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
1293   g_assert (introspection_data != NULL);
1294
1295   g_bus_own_name (G_BUS_TYPE_SESSION,
1296                                   "org.a11y.Bus",
1297                                   G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
1298                                   on_bus_acquired,
1299                                   on_name_acquired,
1300                                   on_name_lost,
1301                                   _global_app,
1302                                   NULL);
1303
1304   register_executable (&_global_app->screen_reader);
1305   register_executable (&_global_app->universal_switch);
1306
1307   g_main_loop_run (_global_app->loop);
1308
1309   if (_global_app->a11y_bus_pid > 0)
1310     kill (_global_app->a11y_bus_pid, SIGTERM);
1311
1312   /* Clear the X property if our bus is gone; in the case where e.g.
1313    * GDM is launching a login on an X server it was using before,
1314    * we don't want early login processes to pick up the stale address.
1315    */
1316 #ifdef HAVE_X11
1317   {
1318     Display *display = XOpenDisplay (NULL);
1319     if (display)
1320       {
1321         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
1322         XDeleteProperty (display,
1323                          XDefaultRootWindow (display),
1324                          bus_address_atom);
1325
1326         XFlush (display);
1327         XCloseDisplay (display);
1328       }
1329   }
1330 #endif
1331
1332   if (_global_app->a11y_launch_error_message)
1333     {
1334       g_printerr ("Failed to launch bus: %s", _global_app->a11y_launch_error_message);
1335       return 1;
1336     }
1337   return 0;
1338 }