17f01c02362fb7a6226934709c71223e0d6a1aee
[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 typedef enum {
44   A11Y_BUS_STATE_IDLE = 0,
45   A11Y_BUS_STATE_READING_ADDRESS,
46   A11Y_BUS_STATE_RUNNING,
47   A11Y_BUS_STATE_ERROR
48 } A11yBusState;
49
50 typedef struct {
51   GMainLoop *loop;
52   gboolean launch_immediately;
53   gboolean a11y_enabled;
54   gboolean screen_reader_enabled;
55   GDBusConnection *session_bus;
56   GSettings *a11y_schema;
57   GSettings *interface_schema;
58   int name_owner_id;
59
60   GDBusProxy *client_proxy;
61
62   A11yBusState state;
63   /* -1 == error, 0 == pending, > 0 == running */
64   int a11y_bus_pid;
65   char *a11y_bus_address;
66   int pipefd[2];
67   int listenfd;
68   char *a11y_launch_error_message;
69 } A11yBusLauncher;
70
71 static A11yBusLauncher *_global_app = NULL;
72
73 static const gchar introspection_xml[] =
74   "<node>"
75   "  <interface name='org.a11y.Bus'>"
76   "    <method name='GetAddress'>"
77   "      <arg type='s' name='address' direction='out'/>"
78   "    </method>"
79   "  </interface>"
80   "<interface name='org.a11y.Status'>"
81   "<property name='IsEnabled' type='b' access='readwrite'/>"
82   "<property name='ScreenReaderEnabled' type='b' access='readwrite'/>"
83   "</interface>"
84   "</node>";
85 static GDBusNodeInfo *introspection_data = NULL;
86
87 static void
88 respond_to_end_session (GDBusProxy *proxy)
89 {
90   GVariant *parameters;
91
92   parameters = g_variant_new ("(bs)", TRUE, "");
93
94   g_dbus_proxy_call (proxy,
95                      "EndSessionResponse", parameters,
96                      G_DBUS_CALL_FLAGS_NONE,
97                      -1, NULL, NULL, NULL);
98 }
99
100 static void
101 g_signal_cb (GDBusProxy *proxy,
102              gchar      *sender_name,
103              gchar      *signal_name,
104              GVariant   *parameters,
105              gpointer    user_data)
106 {
107   A11yBusLauncher *app = user_data;
108
109   if (g_strcmp0 (signal_name, "QueryEndSession") == 0)
110     respond_to_end_session (proxy);
111   else if (g_strcmp0 (signal_name, "EndSession") == 0)
112     respond_to_end_session (proxy);
113   else if (g_strcmp0 (signal_name, "Stop") == 0)
114     g_main_loop_quit (app->loop);
115 }
116
117 static void
118 client_proxy_ready_cb (GObject      *source_object,
119                        GAsyncResult *res,
120                        gpointer      user_data)
121 {
122   A11yBusLauncher *app = user_data;
123   GError *error = NULL;
124
125   app->client_proxy = g_dbus_proxy_new_for_bus_finish (res, &error);
126
127   if (error != NULL)
128     {
129       g_warning ("Failed to get a client proxy: %s", error->message);
130       g_error_free (error);
131
132       return;
133     }
134
135   g_signal_connect (app->client_proxy, "g-signal",
136                     G_CALLBACK (g_signal_cb), app);
137 }
138
139 static void
140 register_client (A11yBusLauncher *app)
141 {
142   GDBusProxyFlags flags;
143   GDBusProxy *sm_proxy;
144   GError *error;
145   const gchar *app_id;
146   const gchar *autostart_id;
147   gchar *client_startup_id;
148   GVariant *parameters;
149   GVariant *variant;
150   gchar *object_path;
151
152   flags = G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
153           G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS;
154
155   error = NULL;
156   sm_proxy = g_dbus_proxy_new_sync (app->session_bus, flags, NULL,
157                                     "org.gnome.SessionManager",
158                                     "/org/gnome/SessionManager",
159                                     "org.gnome.SessionManager",
160                                     NULL, &error);
161
162   if (error != NULL)
163     {
164       g_warning ("Failed to get session manager proxy: %s", error->message);
165       g_error_free (error);
166
167       return;
168     }
169
170   app_id = "at-spi-bus-launcher";
171   autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");
172
173   if (autostart_id != NULL)
174     {
175       client_startup_id = g_strdup (autostart_id);
176       g_unsetenv ("DESKTOP_AUTOSTART_ID");
177     }
178   else
179     {
180       client_startup_id = g_strdup ("");
181     }
182
183   parameters = g_variant_new ("(ss)", app_id, client_startup_id);
184   g_free (client_startup_id);
185
186   error = NULL;
187   variant = g_dbus_proxy_call_sync (sm_proxy,
188                                     "RegisterClient", parameters,
189                                     G_DBUS_CALL_FLAGS_NONE,
190                                     -1, NULL, &error);
191
192   g_object_unref (sm_proxy);
193
194   if (error != NULL)
195     {
196       g_warning ("Failed to register client: %s", error->message);
197       g_error_free (error);
198
199       return;
200     }
201
202   g_variant_get (variant, "(o)", &object_path);
203   g_variant_unref (variant);
204
205   flags = G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES;
206   g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION, flags, NULL,
207                             "org.gnome.SessionManager", object_path,
208                             "org.gnome.SessionManager.ClientPrivate",
209                             NULL, client_proxy_ready_cb, app);
210
211   g_free (object_path);
212 }
213
214 static void
215 name_appeared_handler (GDBusConnection *connection,
216                        const gchar     *name,
217                        const gchar     *name_owner,
218                        gpointer         user_data)
219 {
220   A11yBusLauncher *app = user_data;
221
222   register_client (app);
223 }
224
225 /**
226  * unix_read_all_fd_to_string:
227  *
228  * Read all data from a file descriptor to a C string buffer.
229  */
230 static gboolean
231 unix_read_all_fd_to_string (int      fd,
232                             char    *buf,
233                             ssize_t  max_bytes)
234 {
235   ssize_t bytes_read;
236
237   while (max_bytes > 1 && (bytes_read = read (fd, buf, MIN (4096, max_bytes - 1))))
238     {
239       if (bytes_read < 0)
240         return FALSE;
241       buf += bytes_read;
242       max_bytes -= bytes_read;
243     }
244   *buf = '\0';
245   return TRUE;
246 }
247
248 static void
249 on_bus_exited (GPid     pid,
250                gint     status,
251                gpointer data)
252 {
253   A11yBusLauncher *app = data;
254   
255   app->a11y_bus_pid = -1;
256   app->state = A11Y_BUS_STATE_ERROR;
257   if (app->a11y_launch_error_message == NULL)
258     {
259       if (WIFEXITED (status))
260         app->a11y_launch_error_message = g_strdup_printf ("Bus exited with code %d", WEXITSTATUS (status));
261       else if (WIFSIGNALED (status))
262         app->a11y_launch_error_message = g_strdup_printf ("Bus killed by signal %d", WTERMSIG (status));
263       else if (WIFSTOPPED (status))
264         app->a11y_launch_error_message = g_strdup_printf ("Bus stopped by signal %d", WSTOPSIG (status));
265     }
266   g_main_loop_quit (app->loop);
267
268
269 #ifdef DBUS_DAEMON
270 static void
271 setup_bus_child_daemon (gpointer data)
272 {
273   A11yBusLauncher *app = data;
274   (void) app;
275
276   close (app->pipefd[0]);
277   dup2 (app->pipefd[1], 3);
278   close (app->pipefd[1]);
279
280   /* On Linux, tell the bus process to exit if this process goes away */
281 #ifdef __linux__
282   prctl (PR_SET_PDEATHSIG, 15);
283 #endif
284 }
285
286 static gboolean
287 ensure_a11y_bus_daemon (A11yBusLauncher *app, char *config_path)
288 {
289   char *argv[] = { DBUS_DAEMON, config_path, "--nofork", "--print-address", "3", NULL };
290   GPid pid;
291   char addr_buf[2048];
292   GError *error = NULL;
293
294   if (pipe (app->pipefd) < 0)
295     g_error ("Failed to create pipe: %s", strerror (errno));
296
297   g_clear_pointer (&app->a11y_launch_error_message, g_free);
298
299   if (!g_spawn_async (NULL,
300                       argv,
301                       NULL,
302                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
303                       setup_bus_child_daemon,
304                       app,
305                       &pid,
306                       &error))
307     {
308       app->a11y_bus_pid = -1;
309       app->a11y_launch_error_message = g_strdup (error->message);
310       g_clear_error (&error);
311       goto error;
312     }
313
314   close (app->pipefd[1]);
315   app->pipefd[1] = -1;
316
317   g_child_watch_add (pid, on_bus_exited, app);
318
319   app->state = A11Y_BUS_STATE_READING_ADDRESS;
320   app->a11y_bus_pid = pid;
321   g_debug ("Launched a11y bus, child is %ld", (long) pid);
322   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
323     {
324       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", strerror (errno));
325       kill (app->a11y_bus_pid, SIGTERM);
326       goto error;
327     }
328   close (app->pipefd[0]);
329   app->pipefd[0] = -1;
330   app->state = A11Y_BUS_STATE_RUNNING;
331
332   /* Trim the trailing newline */
333   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
334   g_debug ("a11y bus address: %s", app->a11y_bus_address);
335
336   return TRUE;
337
338 error:
339   close (app->pipefd[0]);
340   close (app->pipefd[1]);
341   app->state = A11Y_BUS_STATE_ERROR;
342
343   return FALSE;
344 }
345 #else
346 static gboolean
347 ensure_a11y_bus_daemon (A11yBusLauncher *app, char *config_path)
348 {
349         return FALSE;
350 }
351 #endif
352
353 #ifdef DBUS_BROKER
354 static void
355 setup_bus_child_broker (gpointer data)
356 {
357   A11yBusLauncher *app = data;
358   gchar *pid_str;
359   (void) app;
360
361   dup2 (app->listenfd, 3);
362   close (app->listenfd);
363   g_setenv("LISTEN_FDS", "1", TRUE);
364
365   pid_str = g_strdup_printf("%u", getpid());
366   g_setenv("LISTEN_PID", pid_str, TRUE);
367   g_free(pid_str);
368
369   /* Tell the bus process to exit if this process goes away */
370   prctl (PR_SET_PDEATHSIG, SIGTERM);
371 }
372
373 static gboolean
374 ensure_a11y_bus_broker (A11yBusLauncher *app, char *config_path)
375 {
376   char *argv[] = { DBUS_BROKER, config_path, "--scope", "user", NULL };
377   struct sockaddr_un addr = { .sun_family = AF_UNIX };
378   socklen_t addr_len = sizeof(addr);
379   GPid pid;
380   GError *error = NULL;
381
382   if ((app->listenfd = socket (PF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) < 0)
383     g_error ("Failed to create listening socket: %s", strerror (errno));
384
385   if (bind (app->listenfd, (struct sockaddr *)&addr, sizeof(sa_family_t)) < 0)
386     g_error ("Failed to bind listening socket: %s", strerror (errno));
387
388   if (getsockname (app->listenfd, (struct sockaddr *)&addr, &addr_len) < 0)
389     g_error ("Failed to get socket name for listening socket: %s", strerror(errno));
390
391   if (listen (app->listenfd, 1024) < 0)
392     g_error ("Failed to listen on socket: %s", strerror(errno));
393
394   g_clear_pointer (&app->a11y_launch_error_message, g_free);
395
396   if (!g_spawn_async (NULL,
397                       argv,
398                       NULL,
399                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
400                       setup_bus_child_broker,
401                       app,
402                       &pid,
403                       &error))
404     {
405       app->a11y_bus_pid = -1;
406       app->a11y_launch_error_message = g_strdup (error->message);
407       g_clear_error (&error);
408       goto error;
409     }
410
411   close (app->listenfd);
412   app->listenfd = -1;
413
414   g_child_watch_add (pid, on_bus_exited, app);
415   app->a11y_bus_pid = pid;
416   g_debug ("Launched a11y bus, child is %ld", (long) pid);
417   app->state = A11Y_BUS_STATE_RUNNING;
418
419   app->a11y_bus_address = g_strconcat("unix:abstract=", addr.sun_path + 1, NULL);
420   g_debug ("a11y bus address: %s", app->a11y_bus_address);
421
422   return TRUE;
423
424 error:
425   close (app->listenfd);
426   app->state = A11Y_BUS_STATE_ERROR;
427
428   return FALSE;
429 }
430 #else
431 static gboolean
432 ensure_a11y_bus_broker (A11yBusLauncher *app, char *config_path)
433 {
434         return FALSE;
435 }
436 #endif
437
438 static gboolean
439 ensure_a11y_bus (A11yBusLauncher *app)
440 {
441   char *config_path = NULL;
442   gboolean success = FALSE;
443
444   if (app->a11y_bus_pid != 0)
445     return FALSE;
446
447   if (g_file_test (SYSCONFDIR"/at-spi2/accessibility.conf", G_FILE_TEST_EXISTS))
448       config_path = "--config-file="SYSCONFDIR"/at-spi2/accessibility.conf";
449   else
450       config_path = "--config-file="DATADIR"/defaults/at-spi2/accessibility.conf";
451
452 #ifdef WANT_DBUS_BROKER
453     success = ensure_a11y_bus_broker (app, config_path);
454     if (!success)
455       {
456         if (!ensure_a11y_bus_daemon (app, config_path))
457             return FALSE;
458       }
459 #else
460     success = ensure_a11y_bus_daemon (app, config_path);
461     if (!success)
462       {
463         if (!ensure_a11y_bus_broker (app, config_path))
464             return FALSE;
465       }
466 #endif
467
468 #ifdef HAVE_X11
469   {
470     Display *display = XOpenDisplay (NULL);
471     if (display)
472       {
473         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
474         XChangeProperty (display,
475                          XDefaultRootWindow (display),
476                          bus_address_atom,
477                          XA_STRING, 8, PropModeReplace,
478                          (guchar *) app->a11y_bus_address, strlen (app->a11y_bus_address));
479         XFlush (display);
480         XCloseDisplay (display);
481       }
482   }
483 #endif
484
485   return TRUE;
486 }
487
488 static void
489 handle_method_call (GDBusConnection       *connection,
490                     const gchar           *sender,
491                     const gchar           *object_path,
492                     const gchar           *interface_name,
493                     const gchar           *method_name,
494                     GVariant              *parameters,
495                     GDBusMethodInvocation *invocation,
496                     gpointer               user_data)
497 {
498   A11yBusLauncher *app = user_data;
499
500   if (g_strcmp0 (method_name, "GetAddress") == 0)
501     {
502       ensure_a11y_bus (app);
503       if (app->a11y_bus_pid > 0)
504         g_dbus_method_invocation_return_value (invocation,
505                                                g_variant_new ("(s)", app->a11y_bus_address));
506       else
507         g_dbus_method_invocation_return_dbus_error (invocation,
508                                                     "org.a11y.Bus.Error",
509                                                     app->a11y_launch_error_message);
510     }
511 }
512
513 static GVariant *
514 handle_get_property  (GDBusConnection       *connection,
515                       const gchar           *sender,
516                       const gchar           *object_path,
517                       const gchar           *interface_name,
518                       const gchar           *property_name,
519                     GError **error,
520                     gpointer               user_data)
521 {
522   A11yBusLauncher *app = user_data;
523
524   if (g_strcmp0 (property_name, "IsEnabled") == 0)
525     return g_variant_new ("b", app->a11y_enabled);
526   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
527     return g_variant_new ("b", app->screen_reader_enabled);
528   else
529     return NULL;
530 }
531
532 static void
533 handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
534                                gboolean notify_gsettings)
535 {
536   GVariantBuilder builder;
537   GVariantBuilder invalidated_builder;
538
539   if (enabled == app->a11y_enabled)
540     return;
541
542   app->a11y_enabled = enabled;
543
544   if (notify_gsettings && app->interface_schema)
545     {
546       g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
547                               enabled);
548       g_settings_sync ();
549     }
550
551   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
552   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
553   g_variant_builder_add (&builder, "{sv}", "IsEnabled",
554                          g_variant_new_boolean (enabled));
555
556   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
557                                  "org.freedesktop.DBus.Properties",
558                                  "PropertiesChanged",
559                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
560                                                 &builder,
561                                                 &invalidated_builder),
562                                  NULL);
563
564   g_variant_builder_clear (&builder);
565   g_variant_builder_clear (&invalidated_builder);
566 }
567
568 static void
569 handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
570                                gboolean notify_gsettings)
571 {
572   GVariantBuilder builder;
573   GVariantBuilder invalidated_builder;
574
575   if (enabled == app->screen_reader_enabled)
576     return;
577
578   /* If the screen reader is being enabled, we should enable accessibility
579    * if it isn't enabled already */
580   if (enabled)
581     handle_a11y_enabled_change (app, enabled, notify_gsettings);
582
583   app->screen_reader_enabled = enabled;
584
585   if (notify_gsettings && app->a11y_schema)
586     {
587       g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
588                               enabled);
589       g_settings_sync ();
590     }
591
592   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
593   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
594   g_variant_builder_add (&builder, "{sv}", "ScreenReaderEnabled",
595                          g_variant_new_boolean (enabled));
596
597   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
598                                  "org.freedesktop.DBus.Properties",
599                                  "PropertiesChanged",
600                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
601                                                 &builder,
602                                                 &invalidated_builder),
603                                  NULL);
604
605   g_variant_builder_clear (&builder);
606   g_variant_builder_clear (&invalidated_builder);
607 }
608
609 static gboolean
610 handle_set_property  (GDBusConnection       *connection,
611                       const gchar           *sender,
612                       const gchar           *object_path,
613                       const gchar           *interface_name,
614                       const gchar           *property_name,
615                       GVariant *value,
616                     GError **error,
617                     gpointer               user_data)
618 {
619   A11yBusLauncher *app = user_data;
620   const gchar *type = g_variant_get_type_string (value);
621   gboolean enabled;
622   
623   if (g_strcmp0 (type, "b") != 0)
624     {
625       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
626                        "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
627       return FALSE;
628     }
629
630   enabled = g_variant_get_boolean (value);
631
632   if (g_strcmp0 (property_name, "IsEnabled") == 0)
633     {
634       handle_a11y_enabled_change (app, enabled, TRUE);
635       return TRUE;
636     }
637   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
638     {
639       handle_screen_reader_enabled_change (app, enabled, TRUE);
640       return TRUE;
641     }
642   else
643     {
644       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
645                        "Unknown property '%s'", property_name);
646       return FALSE;
647     }
648 }
649
650 static const GDBusInterfaceVTable bus_vtable =
651 {
652   handle_method_call,
653   NULL, /* handle_get_property, */
654   NULL  /* handle_set_property */
655 };
656
657 static const GDBusInterfaceVTable status_vtable =
658 {
659   NULL, /* handle_method_call */
660   handle_get_property,
661   handle_set_property
662 };
663
664 static void
665 on_bus_acquired (GDBusConnection *connection,
666                  const gchar     *name,
667                  gpointer         user_data)
668 {
669   A11yBusLauncher *app = user_data;
670   GError *error;
671   guint registration_id;
672   
673   if (connection == NULL)
674     {
675       g_main_loop_quit (app->loop);
676       return;
677     }
678   app->session_bus = connection;
679
680   if (app->launch_immediately)
681     {
682       ensure_a11y_bus (app);
683       if (app->state == A11Y_BUS_STATE_ERROR)
684         {
685           g_main_loop_quit (app->loop);
686           return;
687         }
688     }
689
690   error = NULL;
691   registration_id = g_dbus_connection_register_object (connection,
692                                                        "/org/a11y/bus",
693                                                        introspection_data->interfaces[0],
694                                                        &bus_vtable,
695                                                        _global_app,
696                                                        NULL,
697                                                        &error);
698   if (registration_id == 0)
699     {
700       g_error ("%s", error->message);
701       g_clear_error (&error);
702     }
703
704   g_dbus_connection_register_object (connection,
705                                      "/org/a11y/bus",
706                                      introspection_data->interfaces[1],
707                                      &status_vtable,
708                                      _global_app,
709                                      NULL,
710                                      NULL);
711 }
712
713 static void
714 on_name_lost (GDBusConnection *connection,
715               const gchar     *name,
716               gpointer         user_data)
717 {
718   A11yBusLauncher *app = user_data;
719   if (app->session_bus == NULL
720       && connection == NULL
721       && app->a11y_launch_error_message == NULL)
722     app->a11y_launch_error_message = g_strdup ("Failed to connect to session bus");
723   g_main_loop_quit (app->loop);
724 }
725
726 static void
727 on_name_acquired (GDBusConnection *connection,
728                   const gchar     *name,
729                   gpointer         user_data)
730 {
731   g_bus_watch_name (G_BUS_TYPE_SESSION,
732                     "org.gnome.SessionManager",
733                     G_BUS_NAME_WATCHER_FLAGS_NONE,
734                     name_appeared_handler, NULL,
735                     user_data, NULL);
736 }
737
738 static int sigterm_pipefd[2];
739
740 static void
741 sigterm_handler (int signum)
742 {
743   write (sigterm_pipefd[1], "X", 1);
744 }
745
746 static gboolean
747 on_sigterm_pipe (GIOChannel  *channel,
748                  GIOCondition condition,
749                  gpointer     data)
750 {
751   A11yBusLauncher *app = data;
752   
753   g_main_loop_quit (app->loop);
754
755   return FALSE;
756 }
757
758 static void
759 init_sigterm_handling (A11yBusLauncher *app)
760 {
761   GIOChannel *sigterm_channel;
762
763   if (pipe (sigterm_pipefd) < 0)
764     g_error ("Failed to create pipe: %s", strerror (errno));
765   signal (SIGTERM, sigterm_handler);
766
767   sigterm_channel = g_io_channel_unix_new (sigterm_pipefd[0]);
768   g_io_add_watch (sigterm_channel,
769                   G_IO_IN | G_IO_ERR | G_IO_HUP,
770                   on_sigterm_pipe,
771                   app);
772 }
773
774 static gboolean
775 already_running ()
776 {
777 #ifdef HAVE_X11
778   Atom AT_SPI_BUS;
779   Atom actual_type;
780   Display *bridge_display;
781   int actual_format;
782   unsigned char *data = NULL;
783   unsigned long nitems;
784   unsigned long leftover;
785   gboolean result = FALSE;
786
787   bridge_display = XOpenDisplay (NULL);
788   if (!bridge_display)
789               return FALSE;
790       
791   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
792   XGetWindowProperty (bridge_display,
793                       XDefaultRootWindow (bridge_display),
794                       AT_SPI_BUS, 0L,
795                       (long) BUFSIZ, False,
796                       (Atom) 31, &actual_type, &actual_format,
797                       &nitems, &leftover, &data);
798
799   if (data)
800   {
801     GDBusConnection *bus;
802     bus = g_dbus_connection_new_for_address_sync ((const gchar *)data, 0,
803                                                   NULL, NULL, NULL);
804     if (bus != NULL)
805       {
806         result = TRUE;
807         g_object_unref (bus);
808       }
809   }
810
811   XCloseDisplay (bridge_display);
812   return result;
813 #else
814   return FALSE;
815 #endif
816 }
817
818 static GSettings *
819 get_schema (const gchar *name)
820 {
821 #if GLIB_CHECK_VERSION (2, 32, 0)
822   GSettingsSchemaSource *source = g_settings_schema_source_get_default ();
823   GSettingsSchema *schema = g_settings_schema_source_lookup (source, name, FALSE);
824
825   if (schema == NULL)
826     return NULL;
827
828   return g_settings_new_full (schema, NULL, NULL);
829 #else
830   const char * const *schemas = NULL;
831   gint i;
832
833   schemas = g_settings_list_schemas ();
834   for (i = 0; schemas[i]; i++)
835   {
836     if (!strcmp (schemas[i], name))
837       return g_settings_new (schemas[i]);
838   }
839
840   return NULL;
841 #endif
842 }
843
844 static void
845 gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
846 {
847   gboolean new_val = g_settings_get_boolean (gsettings, key);
848
849   if (!strcmp (key, "toolkit-accessibility"))
850     handle_a11y_enabled_change (_global_app, new_val, FALSE);
851   else if (!strcmp (key, "screen-reader-enabled"))
852     handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
853 }
854
855 int
856 main (int    argc,
857       char **argv)
858 {
859   gboolean a11y_set = FALSE;
860   gboolean screen_reader_set = FALSE;
861   gint i;
862
863   if (already_running ())
864     return 0;
865
866   _global_app = g_slice_new0 (A11yBusLauncher);
867   _global_app->loop = g_main_loop_new (NULL, FALSE);
868
869   for (i = 1; i < argc; i++)
870     {
871       if (!strcmp (argv[i], "--launch-immediately"))
872         _global_app->launch_immediately = TRUE;
873       else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 1)
874         a11y_set = TRUE;
875       else if (sscanf (argv[i], "--screen-reader=%d",
876                        &_global_app->screen_reader_enabled) == 1)
877         screen_reader_set = TRUE;
878     else
879       g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
880     }
881
882   _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
883   _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
884
885   if (!a11y_set)
886     {
887       _global_app->a11y_enabled = _global_app->interface_schema
888                                   ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
889                                   : _global_app->launch_immediately;
890     }
891
892   if (!screen_reader_set)
893     {
894       _global_app->screen_reader_enabled = _global_app->a11y_schema
895                                   ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
896                                   : FALSE;
897     }
898
899   if (_global_app->interface_schema)
900     g_signal_connect (_global_app->interface_schema,
901                       "changed::toolkit-accessibility",
902                       G_CALLBACK (gsettings_key_changed), _global_app);
903
904   if (_global_app->a11y_schema)
905     g_signal_connect (_global_app->a11y_schema,
906                       "changed::screen-reader-enabled",
907                       G_CALLBACK (gsettings_key_changed), _global_app);
908
909   init_sigterm_handling (_global_app);
910
911   introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
912   g_assert (introspection_data != NULL);
913
914   _global_app->name_owner_id =
915     g_bus_own_name (G_BUS_TYPE_SESSION,
916                     "org.a11y.Bus",
917                     G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
918                     on_bus_acquired,
919                     on_name_acquired,
920                     on_name_lost,
921                     _global_app,
922                     NULL);
923
924   g_main_loop_run (_global_app->loop);
925
926   if (_global_app->a11y_bus_pid > 0)
927     kill (_global_app->a11y_bus_pid, SIGTERM);
928
929   /* Clear the X property if our bus is gone; in the case where e.g. 
930    * GDM is launching a login on an X server it was using before,
931    * we don't want early login processes to pick up the stale address.
932    */
933 #ifdef HAVE_X11
934   {
935     Display *display = XOpenDisplay (NULL);
936     if (display)
937       {
938         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
939         XDeleteProperty (display,
940                          XDefaultRootWindow (display),
941                          bus_address_atom);
942
943         XFlush (display);
944         XCloseDisplay (display);
945       }
946   }
947 #endif
948
949   if (_global_app->a11y_launch_error_message)
950     {
951       g_printerr ("Failed to launch bus: %s", _global_app->a11y_launch_error_message);
952       return 1;
953     }
954   return 0;
955 }