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