Allow building without X11
[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 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 #include <sys/wait.h>
29 #include <errno.h>
30 #include <stdio.h>
31
32 #include <gio/gio.h>
33 #ifdef HAVE_X11
34 #include <X11/Xlib.h>
35 #include <X11/Xatom.h>
36 #endif
37
38 typedef enum {
39   A11Y_BUS_STATE_IDLE = 0,
40   A11Y_BUS_STATE_READING_ADDRESS,
41   A11Y_BUS_STATE_RUNNING,
42   A11Y_BUS_STATE_ERROR
43 } A11yBusState;
44
45 typedef struct {
46   GMainLoop *loop;
47   gboolean launch_immediately;
48   gboolean a11y_enabled;
49   gboolean screen_reader_enabled;
50   GDBusConnection *session_bus;
51   GSettings *a11y_schema;
52   GSettings *interface_schema;
53
54   A11yBusState state;
55   /* -1 == error, 0 == pending, > 0 == running */
56   int a11y_bus_pid;
57   char *a11y_bus_address;
58   int pipefd[2];
59   char *a11y_launch_error_message;
60 } A11yBusLauncher;
61
62 static A11yBusLauncher *_global_app = NULL;
63
64 static const gchar introspection_xml[] =
65   "<node>"
66   "  <interface name='org.a11y.Bus'>"
67   "    <method name='GetAddress'>"
68   "      <arg type='s' name='address' direction='out'/>"
69   "    </method>"
70   "  </interface>"
71   "<interface name='org.a11y.Status'>"
72   "<property name='IsEnabled' type='b' access='readwrite'/>"
73   "<property name='ScreenReaderEnabled' type='b' access='readwrite'/>"
74   "</interface>"
75   "</node>";
76 static GDBusNodeInfo *introspection_data = NULL;
77
78 static void
79 setup_bus_child (gpointer data)
80 {
81   A11yBusLauncher *app = data;
82   (void) app;
83
84   close (app->pipefd[0]);
85   dup2 (app->pipefd[1], 3);
86   close (app->pipefd[1]);
87
88   /* On Linux, tell the bus process to exit if this process goes away */
89 #ifdef __linux
90 #include <sys/prctl.h>
91   prctl (PR_SET_PDEATHSIG, 15);
92 #endif  
93 }
94
95 /**
96  * unix_read_all_fd_to_string:
97  *
98  * Read all data from a file descriptor to a C string buffer.
99  */
100 static gboolean
101 unix_read_all_fd_to_string (int      fd,
102                             char    *buf,
103                             ssize_t  max_bytes)
104 {
105   ssize_t bytes_read;
106
107   while (max_bytes > 1 && (bytes_read = read (fd, buf, MAX (4096, max_bytes - 1))))
108     {
109       if (bytes_read < 0)
110         return FALSE;
111       buf += bytes_read;
112       max_bytes -= bytes_read;
113     }
114   *buf = '\0';
115   return TRUE;
116 }
117
118 static void
119 on_bus_exited (GPid     pid,
120                gint     status,
121                gpointer data)
122 {
123   A11yBusLauncher *app = data;
124   
125   app->a11y_bus_pid = -1;
126   app->state = A11Y_BUS_STATE_ERROR;
127   if (app->a11y_launch_error_message == NULL)
128     {
129       if (WIFEXITED (status))
130         app->a11y_launch_error_message = g_strdup_printf ("Bus exited with code %d", WEXITSTATUS (status));
131       else if (WIFSIGNALED (status))
132         app->a11y_launch_error_message = g_strdup_printf ("Bus killed by signal %d", WTERMSIG (status));
133       else if (WIFSTOPPED (status))
134         app->a11y_launch_error_message = g_strdup_printf ("Bus stopped by signal %d", WSTOPSIG (status));
135     }
136   g_main_loop_quit (app->loop);
137
138
139 static gboolean
140 ensure_a11y_bus (A11yBusLauncher *app)
141 {
142   GPid pid;
143   char *argv[] = { DBUS_DAEMON, NULL, "--nofork", "--print-address", "3", NULL };
144   char addr_buf[2048];
145   GError *error = NULL;
146
147   if (app->a11y_bus_pid != 0)
148     return FALSE;
149   
150   argv[1] = g_strdup_printf ("--config-file=%s/at-spi2/accessibility.conf", SYSCONFDIR);
151
152   if (pipe (app->pipefd) < 0)
153     g_error ("Failed to create pipe: %s", strerror (errno));
154   
155   if (!g_spawn_async (NULL,
156                       argv,
157                       NULL,
158                       G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD,
159                       setup_bus_child,
160                       app,
161                       &pid,
162                       &error))
163     {
164       app->a11y_bus_pid = -1;
165       app->a11y_launch_error_message = g_strdup (error->message);
166       g_clear_error (&error);
167       goto error;
168     }
169
170   close (app->pipefd[1]);
171   app->pipefd[1] = -1;
172
173   g_child_watch_add (pid, on_bus_exited, app);
174
175   app->state = A11Y_BUS_STATE_READING_ADDRESS;
176   app->a11y_bus_pid = pid;
177   g_debug ("Launched a11y bus, child is %ld", (long) pid);
178   if (!unix_read_all_fd_to_string (app->pipefd[0], addr_buf, sizeof (addr_buf)))
179     {
180       app->a11y_launch_error_message = g_strdup_printf ("Failed to read address: %s", strerror (errno));
181       kill (app->a11y_bus_pid, SIGTERM);
182       goto error;
183     }
184   close (app->pipefd[0]);
185   app->pipefd[0] = -1;
186   app->state = A11Y_BUS_STATE_RUNNING;
187
188   /* Trim the trailing newline */
189   app->a11y_bus_address = g_strchomp (g_strdup (addr_buf));
190   g_debug ("a11y bus address: %s", app->a11y_bus_address);
191
192 #ifdef HAVE_X11
193   {
194     Display *display = XOpenDisplay (NULL);
195     if (display)
196       {
197         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
198         XChangeProperty (display,
199                          XDefaultRootWindow (display),
200                          bus_address_atom,
201                          XA_STRING, 8, PropModeReplace,
202                          (guchar *) app->a11y_bus_address, strlen (app->a11y_bus_address));
203         XFlush (display);
204         XCloseDisplay (display);
205       }
206   }
207 #endif
208
209   return TRUE;
210   
211  error:
212   close (app->pipefd[0]);
213   close (app->pipefd[1]);
214   app->state = A11Y_BUS_STATE_ERROR;
215
216   return FALSE;
217 }
218
219 static void
220 handle_method_call (GDBusConnection       *connection,
221                     const gchar           *sender,
222                     const gchar           *object_path,
223                     const gchar           *interface_name,
224                     const gchar           *method_name,
225                     GVariant              *parameters,
226                     GDBusMethodInvocation *invocation,
227                     gpointer               user_data)
228 {
229   A11yBusLauncher *app = user_data;
230
231   if (g_strcmp0 (method_name, "GetAddress") == 0)
232     {
233       ensure_a11y_bus (app);
234       if (app->a11y_bus_pid > 0)
235         g_dbus_method_invocation_return_value (invocation,
236                                                g_variant_new ("(s)", app->a11y_bus_address));
237       else
238         g_dbus_method_invocation_return_dbus_error (invocation,
239                                                     "org.a11y.Bus.Error",
240                                                     app->a11y_launch_error_message);
241     }
242 }
243
244 static GVariant *
245 handle_get_property  (GDBusConnection       *connection,
246                       const gchar           *sender,
247                       const gchar           *object_path,
248                       const gchar           *interface_name,
249                       const gchar           *property_name,
250                     GError **error,
251                     gpointer               user_data)
252 {
253   A11yBusLauncher *app = user_data;
254
255   if (g_strcmp0 (property_name, "IsEnabled") == 0)
256     return g_variant_new ("b", app->a11y_enabled);
257   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
258     return g_variant_new ("b", app->screen_reader_enabled);
259   else
260     return NULL;
261 }
262
263 static void
264 handle_a11y_enabled_change (A11yBusLauncher *app, gboolean enabled,
265                                gboolean notify_gsettings)
266 {
267   GVariantBuilder builder;
268   GVariantBuilder invalidated_builder;
269
270   if (enabled == app->a11y_enabled)
271     return;
272
273   app->a11y_enabled = enabled;
274
275   if (notify_gsettings && app->interface_schema)
276     {
277       g_settings_set_boolean (app->interface_schema, "toolkit-accessibility",
278                               enabled);
279       g_settings_sync ();
280     }
281
282   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
283   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
284   g_variant_builder_add (&builder, "{sv}", "IsEnabled",
285                          g_variant_new_boolean (enabled));
286
287   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
288                                  "org.freedesktop.DBus.Properties",
289                                  "PropertiesChanged",
290                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
291                                                 &builder,
292                                                 &invalidated_builder),
293                                  NULL);
294 }
295
296 static void
297 handle_screen_reader_enabled_change (A11yBusLauncher *app, gboolean enabled,
298                                gboolean notify_gsettings)
299 {
300   GVariantBuilder builder;
301   GVariantBuilder invalidated_builder;
302
303   if (enabled == app->screen_reader_enabled)
304     return;
305
306   /* If the screen reader is being enabled, we should enable accessibility
307    * if it isn't enabled already */
308   if (enabled)
309     handle_a11y_enabled_change (app, enabled, notify_gsettings);
310
311   app->screen_reader_enabled = enabled;
312
313   if (notify_gsettings && app->a11y_schema)
314     {
315       g_settings_set_boolean (app->a11y_schema, "screen-reader-enabled",
316                               enabled);
317       g_settings_sync ();
318     }
319
320   g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
321   g_variant_builder_init (&invalidated_builder, G_VARIANT_TYPE ("as"));
322   g_variant_builder_add (&builder, "{sv}", "ScreenReaderEnabled",
323                          g_variant_new_boolean (enabled));
324
325   g_dbus_connection_emit_signal (app->session_bus, NULL, "/org/a11y/bus",
326                                  "org.freedesktop.DBus.Properties",
327                                  "PropertiesChanged",
328                                  g_variant_new ("(sa{sv}as)", "org.a11y.Status",
329                                                 &builder,
330                                                 &invalidated_builder),
331                                  NULL);
332 }
333
334 static gboolean
335 handle_set_property  (GDBusConnection       *connection,
336                       const gchar           *sender,
337                       const gchar           *object_path,
338                       const gchar           *interface_name,
339                       const gchar           *property_name,
340                       GVariant *value,
341                     GError **error,
342                     gpointer               user_data)
343 {
344   A11yBusLauncher *app = user_data;
345   const gchar *type = g_variant_get_type_string (value);
346   gboolean enabled;
347   
348   if (g_strcmp0 (type, "b") != 0)
349     {
350       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
351                        "org.a11y.Status.%s expects a boolean but got %s", property_name, type);
352       return FALSE;
353     }
354
355   enabled = g_variant_get_boolean (value);
356
357   if (g_strcmp0 (property_name, "IsEnabled") == 0)
358     {
359       handle_a11y_enabled_change (app, enabled, TRUE);
360       return TRUE;
361     }
362   else if (g_strcmp0 (property_name, "ScreenReaderEnabled") == 0)
363     {
364       handle_screen_reader_enabled_change (app, enabled, TRUE);
365       return TRUE;
366     }
367   else
368     {
369       g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS,
370                        "Unknown property '%s'", property_name);
371       return FALSE;
372     }
373 }
374
375 static const GDBusInterfaceVTable bus_vtable =
376 {
377   handle_method_call,
378   NULL, /* handle_get_property, */
379   NULL  /* handle_set_property */
380 };
381
382 static const GDBusInterfaceVTable status_vtable =
383 {
384   NULL, /* handle_method_call */
385   handle_get_property,
386   handle_set_property
387 };
388
389 static void
390 on_bus_acquired (GDBusConnection *connection,
391                  const gchar     *name,
392                  gpointer         user_data)
393 {
394   A11yBusLauncher *app = user_data;
395   GError *error;
396   guint registration_id;
397   
398   if (connection == NULL)
399     {
400       g_main_loop_quit (app->loop);
401       return;
402     }
403   app->session_bus = connection;
404
405   if (app->launch_immediately)
406     {
407       ensure_a11y_bus (app);
408       if (app->state == A11Y_BUS_STATE_ERROR)
409         {
410           g_main_loop_quit (app->loop);
411           return;
412         }
413     }
414
415   error = NULL;
416   registration_id = g_dbus_connection_register_object (connection,
417                                                        "/org/a11y/bus",
418                                                        introspection_data->interfaces[0],
419                                                        &bus_vtable,
420                                                        _global_app,
421                                                        NULL,
422                                                        &error);
423   if (registration_id == 0)
424     {
425       g_error ("%s", error->message);
426       g_clear_error (&error);
427     }
428
429   g_dbus_connection_register_object (connection,
430                                      "/org/a11y/bus",
431                                      introspection_data->interfaces[1],
432                                      &status_vtable,
433                                      _global_app,
434                                      NULL,
435                                      NULL);
436 }
437
438 static void
439 on_name_lost (GDBusConnection *connection,
440               const gchar     *name,
441               gpointer         user_data)
442 {
443   A11yBusLauncher *app = user_data;
444   if (app->session_bus == NULL
445       && connection == NULL
446       && app->a11y_launch_error_message == NULL)
447     app->a11y_launch_error_message = g_strdup ("Failed to connect to session bus");
448   g_main_loop_quit (app->loop);
449 }
450
451 static void
452 on_name_acquired (GDBusConnection *connection,
453                   const gchar     *name,
454                   gpointer         user_data)
455 {
456   A11yBusLauncher *app = user_data;
457   (void) app;
458 }
459
460 static int sigterm_pipefd[2];
461
462 static void
463 sigterm_handler (int signum)
464 {
465   write (sigterm_pipefd[1], "X", 1);
466 }
467
468 static gboolean
469 on_sigterm_pipe (GIOChannel  *channel,
470                  GIOCondition condition,
471                  gpointer     data)
472 {
473   A11yBusLauncher *app = data;
474   
475   g_main_loop_quit (app->loop);
476
477   return FALSE;
478 }
479
480 static void
481 init_sigterm_handling (A11yBusLauncher *app)
482 {
483   GIOChannel *sigterm_channel;
484
485   if (pipe (sigterm_pipefd) < 0)
486     g_error ("Failed to create pipe: %s", strerror (errno));
487   signal (SIGTERM, sigterm_handler);
488
489   sigterm_channel = g_io_channel_unix_new (sigterm_pipefd[0]);
490   g_io_add_watch (sigterm_channel,
491                   G_IO_IN | G_IO_ERR | G_IO_HUP,
492                   on_sigterm_pipe,
493                   app);
494 }
495
496 static gboolean
497 already_running ()
498 {
499 #ifdef HAVE_X11
500   Atom AT_SPI_BUS;
501   Atom actual_type;
502   Display *bridge_display;
503   int actual_format;
504   unsigned char *data = NULL;
505   unsigned long nitems;
506   unsigned long leftover;
507   gboolean result = FALSE;
508
509   bridge_display = XOpenDisplay (NULL);
510   if (!bridge_display)
511               return FALSE;
512       
513   AT_SPI_BUS = XInternAtom (bridge_display, "AT_SPI_BUS", False);
514   XGetWindowProperty (bridge_display,
515                       XDefaultRootWindow (bridge_display),
516                       AT_SPI_BUS, 0L,
517                       (long) BUFSIZ, False,
518                       (Atom) 31, &actual_type, &actual_format,
519                       &nitems, &leftover, &data);
520
521   if (data)
522   {
523     GDBusConnection *bus;
524     const gchar *old_session = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
525     /* TODO: Is there a better way to connect? This is really hacky */
526     g_setenv ("DBUS_SESSION_BUS_ADDRESS", data, TRUE);
527     bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
528     g_setenv ("DBUS_SESSION_BUS_ADDRESS", old_session, TRUE);
529     if (bus != NULL)
530       {
531         result = TRUE;
532         g_object_unref (bus);
533       }
534   }
535
536   XCloseDisplay (bridge_display);
537   return result;
538 #else
539   return FALSE;
540 #endif
541 }
542
543 static GSettings *
544 get_schema (const gchar *name)
545 {
546   const char * const *schemas = NULL;
547   gint i;
548
549   schemas = g_settings_list_schemas ();
550   for (i = 0; schemas[i]; i++)
551   {
552     if (!strcmp (schemas[i], name))
553       return g_settings_new (schemas[i]);
554   }
555
556   return NULL;
557 }
558
559 static void
560 gsettings_key_changed (GSettings *gsettings, const gchar *key, void *user_data)
561 {
562   gboolean new_val = g_settings_get_boolean (gsettings, key);
563   A11yBusLauncher *app = user_data;
564
565   if (!strcmp (key, "toolkit-accessibility"))
566     handle_a11y_enabled_change (_global_app, new_val, FALSE);
567   else if (!strcmp (key, "screen-reader-enabled"))
568     handle_screen_reader_enabled_change (_global_app, new_val, FALSE);
569 }
570
571 int
572 main (int    argc,
573       char **argv)
574 {
575   GError *error = NULL;
576   GMainLoop *loop;
577   GDBusConnection *session_bus;
578   int name_owner_id;
579   gboolean a11y_set = FALSE;
580   gboolean screen_reader_set = FALSE;
581   gint i;
582
583   g_type_init ();
584
585   if (already_running ())
586     return 0;
587
588   _global_app = g_slice_new0 (A11yBusLauncher);
589   _global_app->loop = g_main_loop_new (NULL, FALSE);
590
591   for (i = 1; i < argc; i++)
592     {
593       if (!strcmp (argv[i], "--launch-immediately"))
594         _global_app->launch_immediately = TRUE;
595       else if (sscanf (argv[i], "--a11y=%d", &_global_app->a11y_enabled) == 2)
596         a11y_set = TRUE;
597       else if (sscanf (argv[i], "--screen-reader=%d",
598                        &_global_app->screen_reader_enabled) == 2)
599         screen_reader_set = TRUE;
600     else
601       g_error ("usage: %s [--launch-immediately] [--a11y=0|1] [--screen-reader=0|1]", argv[0]);
602     }
603
604   _global_app->interface_schema = get_schema ("org.gnome.desktop.interface");
605   _global_app->a11y_schema = get_schema ("org.gnome.desktop.a11y.applications");
606
607   if (!a11y_set)
608     {
609       _global_app->a11y_enabled = _global_app->interface_schema
610                                   ? g_settings_get_boolean (_global_app->interface_schema, "toolkit-accessibility")
611                                   : _global_app->launch_immediately;
612     }
613
614   if (!screen_reader_set)
615     {
616       _global_app->screen_reader_enabled = _global_app->a11y_schema
617                                   ? g_settings_get_boolean (_global_app->a11y_schema, "screen-reader-enabled")
618                                   : FALSE;
619     }
620
621   if (_global_app->interface_schema)
622     g_signal_connect (_global_app->interface_schema,
623                       "changed::toolkit-accessibility",
624                       G_CALLBACK (gsettings_key_changed), _global_app);
625
626   if (_global_app->a11y_schema)
627     g_signal_connect (_global_app->a11y_schema,
628                       "changed::screen-reader-enabled",
629                       G_CALLBACK (gsettings_key_changed), _global_app);
630
631   init_sigterm_handling (_global_app);
632
633   introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
634   g_assert (introspection_data != NULL);
635
636   name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
637                                   "org.a11y.Bus",
638                                   G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT,
639                                   on_bus_acquired,
640                                   on_name_acquired,
641                                   on_name_lost,
642                                   _global_app,
643                                   NULL);
644
645   g_main_loop_run (_global_app->loop);
646
647   if (_global_app->a11y_bus_pid > 0)
648     kill (_global_app->a11y_bus_pid, SIGTERM);
649
650   /* Clear the X property if our bus is gone; in the case where e.g. 
651    * GDM is launching a login on an X server it was using before,
652    * we don't want early login processes to pick up the stale address.
653    */
654 #ifdef HAVE_X11
655   {
656     Display *display = XOpenDisplay (NULL);
657     if (display)
658       {
659         Atom bus_address_atom = XInternAtom (display, "AT_SPI_BUS", False);
660         XDeleteProperty (display,
661                          XDefaultRootWindow (display),
662                          bus_address_atom);
663
664         XFlush (display);
665         XCloseDisplay (display);
666       }
667   }
668 #endif
669
670   if (_global_app->a11y_launch_error_message)
671     {
672       g_printerr ("Failed to launch bus: %s", _global_app->a11y_launch_error_message);
673       return 1;
674     }
675   return 0;
676 }