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