2003-05-04 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / tools / dbus-launch.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-launch.c  dbus-launch utility
3  *
4  * Copyright (C) 2003 Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23 #include <config.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <sys/wait.h>
29 #include <errno.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <stdarg.h>
34 #ifdef DBUS_BUILD_X11
35 #include <X11/Xlib.h>
36 #endif
37
38 #ifndef TRUE
39 #define TRUE (1)
40 #endif
41
42 #ifndef FALSE
43 #define FALSE (0)
44 #endif
45
46 #undef  MAX
47 #define MAX(a, b)  (((a) > (b)) ? (a) : (b))
48
49 static void
50 verbose (const char *format,
51          ...)
52 {
53   va_list args;
54   static int verbose = TRUE;
55   static int verbose_initted = FALSE;
56   
57   /* things are written a bit oddly here so that
58    * in the non-verbose case we just have the one
59    * conditional and return immediately.
60    */
61   if (!verbose)
62     return;
63   
64   if (!verbose_initted)
65     {
66       verbose = getenv ("DBUS_VERBOSE") != NULL;
67       verbose_initted = TRUE;
68       if (!verbose)
69         return;
70     }
71
72   fprintf (stderr, "%lu: ", (unsigned long) getpid ());
73   
74   va_start (args, format);
75   vfprintf (stderr, format, args);
76   va_end (args);
77 }
78
79 static void
80 usage (void)
81 {
82   fprintf (stderr, "dbus-launch [--version] [--exit-with-session]\n");
83   exit (1);
84 }
85
86 static void
87 version (void)
88 {
89   printf ("D-BUS Message Bus Launcher %s\n"
90           "Copyright (C) 2003 Red Hat, Inc.\n"
91           "This is free software; see the source for copying conditions.\n"
92           "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
93           VERSION);
94   exit (0);
95 }
96
97 typedef enum
98 {
99   READ_STATUS_OK,    /**< Read succeeded */
100   READ_STATUS_ERROR, /**< Some kind of error */
101   READ_STATUS_EOF    /**< EOF returned */
102 } ReadStatus;
103
104 static ReadStatus
105 read_line (int        fd,
106            char      *buf,
107            size_t     maxlen)
108 {
109   size_t bytes = 0;
110   ReadStatus retval;
111
112   memset (buf, '\0', maxlen);
113   maxlen -= 1; /* ensure nul term */
114   
115   retval = READ_STATUS_OK;
116   
117   while (TRUE)
118     {
119       size_t chunk;    
120       size_t to_read;
121       
122     again:
123       to_read = maxlen - bytes;
124
125       if (to_read == 0)
126         break;
127       
128       chunk = read (fd,
129                     buf + bytes,
130                     to_read);
131       if (chunk < 0 && errno == EINTR)
132         goto again;
133           
134       if (chunk < 0)
135         {
136           retval = READ_STATUS_ERROR;
137           break;
138         }
139       else if (chunk == 0)
140         {
141           retval = READ_STATUS_EOF;
142           break; /* EOF */
143         }
144       else /* chunk > 0 */
145         bytes += chunk;
146     }
147
148   if (retval == READ_STATUS_EOF &&
149       bytes > 0)
150     retval = READ_STATUS_OK;
151   
152   /* whack newline */
153   if (retval != READ_STATUS_ERROR &&
154       bytes > 0 &&
155       buf[bytes-1] == '\n')
156     buf[bytes-1] = '\0';
157   
158   return retval;
159 }
160
161 static ReadStatus
162 read_pid (int        fd,
163           pid_t     *buf)
164 {
165   size_t bytes = 0;
166   ReadStatus retval;
167
168   retval = READ_STATUS_OK;
169   
170   while (TRUE)
171     {
172       size_t chunk;    
173       size_t to_read;
174       
175     again:
176       to_read = sizeof (pid_t) - bytes;
177
178       if (to_read == 0)
179         break;
180       
181       chunk = read (fd,
182                     ((char*)buf) + bytes,
183                     to_read);
184       if (chunk < 0 && errno == EINTR)
185         goto again;
186           
187       if (chunk < 0)
188         {
189           retval = READ_STATUS_ERROR;
190           break;
191         }
192       else if (chunk == 0)
193         {
194           retval = READ_STATUS_EOF;
195           break; /* EOF */
196         }
197       else /* chunk > 0 */
198         bytes += chunk;
199     }
200
201   return retval;
202 }
203
204 static void
205 do_write (int fd, const void *buf, size_t count)
206 {
207   size_t bytes_written;
208   int ret;
209   
210   bytes_written = 0;
211   
212  again:
213   
214   ret = write (fd, ((const char*)buf) + bytes_written, count - bytes_written);
215
216   if (ret < 0)
217     {
218       if (errno == EINTR)
219         goto again;
220       else
221         {
222           fprintf (stderr, "Failed to write data to pipe!\n");
223           exit (1); /* give up, we suck */
224         }
225     }
226   else
227     bytes_written += ret;
228   
229   if (bytes_written < count)
230     goto again;
231 }
232
233 static void
234 write_pid (int   fd,
235            pid_t pid)
236 {
237   do_write (fd, &pid, sizeof (pid));
238 }
239
240 static int
241 do_waitpid (pid_t pid)
242 {
243   int ret;
244   
245  again:
246   ret = waitpid (pid, NULL, 0);
247
248   if (ret < 0 &&
249       errno == EINTR)
250     goto again;
251
252   return ret;
253 }
254
255 static pid_t bus_pid_to_kill = -1;
256
257 static void
258 kill_bus_and_exit (void)
259 {
260   verbose ("Killing message bus and exiting babysitter\n");
261   
262   /* in case these point to any NFS mounts, get rid of them immediately */
263   close (0);
264   close (1);
265   close (2);
266
267   kill (bus_pid_to_kill, SIGTERM);
268   sleep (3);
269   kill (bus_pid_to_kill, SIGKILL);
270
271   exit (0);
272 }
273
274 #ifdef DBUS_BUILD_X11
275 static int
276 x_io_error_handler (Display *xdisplay)
277 {
278   verbose ("X IO error\n");
279   kill_bus_and_exit ();
280 }
281 #endif
282
283 static int got_sighup = FALSE;
284
285 static void
286 signal_handler (int sig)
287 {
288   switch (sig)
289     {
290     case SIGHUP:
291       got_sighup = TRUE;
292       break;
293     }
294 }
295
296 static void
297 kill_bus_when_session_ends (void)
298 {
299   int tty_fd;
300   int x_fd;
301   fd_set read_set;
302   fd_set err_set;
303   int ret;
304   struct sigaction act;
305   sigset_t empty_mask;
306 #ifdef DBUS_BUILD_X11
307   Display *xdisplay;
308 #endif
309   
310   /* install SIGHUP handler */
311   got_sighup = FALSE;
312   sigemptyset (&empty_mask);
313   act.sa_handler = signal_handler;
314   act.sa_mask    = empty_mask;
315   act.sa_flags   = 0;
316   sigaction (SIGHUP,  &act, 0);
317   
318 #ifdef DBUS_BUILD_X11
319   xdisplay = XOpenDisplay (NULL);
320   if (xdisplay != NULL)
321     {
322       verbose ("Successfully opened X display\n");
323       x_fd = ConnectionNumber (xdisplay);
324       XSetIOErrorHandler (x_io_error_handler);
325     }
326   else
327     x_fd = -1;
328 #else
329   verbose ("Compiled without X11 support\n");
330   x_fd = -1;
331 #endif
332
333   if (isatty (0))
334     tty_fd = 0;
335   else
336     tty_fd = -1;
337
338   if (tty_fd >= 0)
339     verbose ("stdin isatty(), monitoring it\n");
340   else
341     verbose ("stdin was not a TTY, not monitoring it\n");  
342   
343   if (tty_fd < 0 && x_fd < 0)
344     {
345       fprintf (stderr, "No terminal on standard input and no X display; cannot attach message bus to session lifetime\n");
346       exit (1);
347     }
348   
349   while (TRUE)
350     {
351       FD_ZERO (&read_set);
352       FD_ZERO (&err_set);
353
354       if (tty_fd >= 0)
355         {
356           FD_SET (tty_fd, &read_set);
357           FD_SET (tty_fd, &err_set);
358         }
359
360       if (x_fd >= 0)
361         {
362           FD_SET (x_fd, &read_set);
363           FD_SET (x_fd, &err_set);
364         }
365       
366       ret = select (MAX (tty_fd, x_fd) + 1,
367                     &read_set, NULL, &err_set, NULL);
368
369       if (got_sighup)
370         {
371           verbose ("Got SIGHUP, exiting\n");
372           kill_bus_and_exit ();
373         }
374       
375 #ifdef DBUS_BUILD_X11
376       /* Dump events on the floor, and let
377        * IO error handler run if we lose
378        * the X connection
379        */
380       if (x_fd >= 0)
381         verbose ("X fd condition reading = %d error = %d\n",
382                  FD_ISSET (x_fd, &read_set),
383                  FD_ISSET (x_fd, &err_set));
384       
385       if (xdisplay != NULL)
386         {      
387           while (XPending (xdisplay))
388             {
389               XEvent ignored;
390               XNextEvent (xdisplay, &ignored);
391             }
392         }
393 #endif
394
395       if (tty_fd >= 0)
396         {
397           if (FD_ISSET (tty_fd, &read_set))
398             {
399               int bytes_read;
400               char discard[512];
401
402               verbose ("TTY ready for reading\n");
403               
404               bytes_read = read (tty_fd, discard, sizeof (discard));
405
406               verbose ("Read %d bytes from TTY errno = %d\n",
407                        bytes_read, errno);
408               
409               if (bytes_read == 0)
410                 kill_bus_and_exit (); /* EOF */
411               else if (bytes_read < 0 && errno != EINTR)
412                 {
413                   /* This shouldn't happen I don't think; to avoid
414                    * spinning on the fd forever we exit.
415                    */
416                   fprintf (stderr, "dbus-launch: error reading from stdin: %s\n",
417                            strerror (errno));
418                   kill_bus_and_exit ();
419                 }
420             }
421           else if (FD_ISSET (tty_fd, &err_set))
422             {
423               verbose ("TTY has error condition\n");
424               
425               kill_bus_and_exit ();
426             }
427         }
428     }
429 }
430
431 static void
432 babysit (int   exit_with_session,
433          pid_t child_pid,
434          int   read_bus_pid_fd,  /* read pid from here */
435          int   write_bus_pid_fd) /* forward pid to here */
436 {
437   int ret;
438 #define MAX_PID_LEN 64
439   char buf[MAX_PID_LEN];
440   long val;
441   char *end;
442   
443   /* We chdir ("/") since we are persistent and daemon-like, and fork
444    * again so dbus-launch can reap the parent.  However, we don't
445    * setsid() or close fd 0,1,2 because the idea is to remain attached
446    * to the tty and the X server in order to kill the message bus
447    * when the session ends.
448    */
449
450   if (chdir ("/") < 0)
451     {
452       fprintf (stderr, "Could not change to root directory: %s\n",
453                strerror (errno));
454       exit (1);
455     }      
456
457   ret = fork ();
458
459   if (ret < 0)
460     {
461       fprintf (stderr, "fork() failed in babysitter: %s\n",
462                strerror (errno));
463       exit (1);
464     }
465
466   if (ret > 0)
467     {
468       /* Parent reaps pre-fork part of bus daemon, then exits and is
469        * reaped so the babysitter isn't a zombie
470        */
471
472       verbose ("=== Babysitter's intermediate parent continues again\n");
473       
474       if (do_waitpid (child_pid) < 0)
475         {
476           /* shouldn't happen */
477           fprintf (stderr, "Failed waitpid() waiting for bus daemon's parent\n");
478           exit (1);
479         }
480
481       verbose ("Babysitter's intermediate parent exiting\n");
482       
483       exit (0);
484     }
485
486   /* Child continues */
487   verbose ("=== Babysitter process created\n");
488
489   verbose ("Reading PID from daemon\n");
490   /* Now read data */
491   switch (read_line (read_bus_pid_fd, buf, MAX_PID_LEN))
492     {
493     case READ_STATUS_OK:
494       break;
495     case READ_STATUS_EOF:
496       fprintf (stderr, "EOF reading PID from bus daemon\n");
497       exit (1);
498       break;
499     case READ_STATUS_ERROR:
500       fprintf (stderr, "Error reading PID from bus daemon: %s\n",
501                strerror (errno));
502       exit (1);
503       break;
504     }
505
506   end = NULL;
507   val = strtol (buf, &end, 0);
508   if (buf == end || end == NULL)
509     {
510       fprintf (stderr, "Failed to parse bus PID \"%s\": %s\n",
511                buf, strerror (errno));
512       exit (1);
513     }
514
515   bus_pid_to_kill = val;
516
517   verbose ("Got PID %ld from daemon\n",
518            (long) bus_pid_to_kill);
519   
520   /* Write data to launcher */
521   write_pid (write_bus_pid_fd, bus_pid_to_kill);
522   close (write_bus_pid_fd);
523
524   if (exit_with_session)
525     {
526       /* Bus is now started and launcher has needed info;
527        * we connect to X display and tty and wait to
528        * kill bus if requested.
529        */
530       
531       kill_bus_when_session_ends ();
532     }
533
534   verbose ("Babysitter exiting\n");
535   
536   exit (0);
537 }
538
539 #define READ_END  0
540 #define WRITE_END 1
541
542 int
543 main (int argc, char **argv)
544 {
545   const char *prev_arg;
546   int exit_with_session;
547   int i;  
548   int ret;
549   int bus_pid_to_launcher_pipe[2];
550   int bus_pid_to_babysitter_pipe[2];
551   int bus_address_to_launcher_pipe[2];
552   
553   exit_with_session = FALSE;
554   
555   prev_arg = NULL;
556   i = 1;
557   while (i < argc)
558     {
559       const char *arg = argv[i];
560       
561       if (strcmp (arg, "--help") == 0 ||
562           strcmp (arg, "-h") == 0 ||
563           strcmp (arg, "-?") == 0)
564         usage ();
565       else if (strcmp (arg, "--version") == 0)
566         version ();
567       else if (strcmp (arg, "--exit-with-session") == 0)
568         exit_with_session = TRUE;
569       else
570         usage ();
571       
572       prev_arg = arg;
573       
574       ++i;
575     }
576
577   verbose ("--exit-with-session provided\n");
578
579   if (pipe (bus_pid_to_launcher_pipe) < 0 ||
580       pipe (bus_address_to_launcher_pipe) < 0)
581     {
582       fprintf (stderr,
583                "Failed to create pipe: %s\n",
584                strerror (errno));
585       exit (1);
586     }
587
588   bus_pid_to_babysitter_pipe[READ_END] = -1;
589   bus_pid_to_babysitter_pipe[WRITE_END] = -1;
590   
591   ret = fork ();
592   if (ret < 0)
593     {
594       fprintf (stderr, "Failed to fork: %s\n",
595                strerror (errno));
596       exit (1);
597     }
598
599   if (ret == 0)
600     {
601       /* Child */
602 #define MAX_FD_LEN 64
603       char write_pid_fd_as_string[MAX_FD_LEN];
604       char write_address_fd_as_string[MAX_FD_LEN];
605
606       verbose ("=== Babysitter's intermediate parent created\n");
607       
608       /* Fork once more to create babysitter */
609       
610       if (pipe (bus_pid_to_babysitter_pipe) < 0)
611         {
612           fprintf (stderr,
613                    "Failed to create pipe: %s\n",
614                    strerror (errno));
615           exit (1);              
616         }
617       
618       ret = fork ();
619       if (ret < 0)
620         {
621           fprintf (stderr, "Failed to fork: %s\n",
622                    strerror (errno));
623           exit (1);
624         }
625       
626       if (ret > 0)
627         {
628           /* In babysitter */
629           verbose ("=== Babysitter's intermediate parent continues\n");
630           
631           close (bus_pid_to_launcher_pipe[READ_END]);
632           close (bus_address_to_launcher_pipe[READ_END]);
633           close (bus_address_to_launcher_pipe[WRITE_END]);
634           close (bus_pid_to_babysitter_pipe[WRITE_END]);
635           
636           /* babysit() will fork *again*
637            * and will also reap the pre-forked bus
638            * daemon
639            */
640           babysit (exit_with_session, ret,
641                    bus_pid_to_babysitter_pipe[READ_END],
642                    bus_pid_to_launcher_pipe[WRITE_END]);
643           exit (0);
644         }
645
646       verbose ("=== Bus exec process created\n");
647       
648       /* Now we are the bus process (well, almost;
649        * dbus-daemon-1 itself forks again)
650        */
651       close (bus_pid_to_launcher_pipe[READ_END]);
652       close (bus_address_to_launcher_pipe[READ_END]);
653       close (bus_pid_to_babysitter_pipe[READ_END]);
654       close (bus_pid_to_launcher_pipe[WRITE_END]);
655
656       sprintf (write_pid_fd_as_string,
657                "%d", bus_pid_to_babysitter_pipe[WRITE_END]);
658
659       sprintf (write_address_fd_as_string,
660                "%d", bus_address_to_launcher_pipe[WRITE_END]);
661
662       verbose ("Calling exec()\n");
663       
664       execlp ("dbus-daemon-1",
665               "dbus-daemon-1",
666               "--fork",
667               "--session",
668               "--print-pid", write_pid_fd_as_string,
669               "--print-address", write_address_fd_as_string,
670               NULL);
671
672       fprintf (stderr,
673                "Failed to execute message bus daemon: %s\n",
674                strerror (errno));
675       exit (1);
676     }
677   else
678     {
679       /* Parent */
680 #define MAX_ADDR_LEN 512
681       pid_t bus_pid;  
682       char bus_address[MAX_ADDR_LEN];
683
684       verbose ("=== Parent dbus-launch continues\n");
685       
686       close (bus_pid_to_launcher_pipe[WRITE_END]);
687       close (bus_address_to_launcher_pipe[WRITE_END]);
688
689       verbose ("Waiting for babysitter's intermediate parent\n");
690       
691       /* Immediately reap parent of babysitter
692        * (which was created just for us to reap)
693        */
694       if (do_waitpid (ret) < 0)
695         {
696           fprintf (stderr, "Failed to waitpid() for babysitter intermediate process: %s\n",
697                    strerror (errno));
698           exit (1);
699         }
700
701       verbose ("Reading address from bus\n");
702       
703       /* Read the pipe data, print, and exit */
704       switch (read_line (bus_address_to_launcher_pipe[READ_END],
705                          bus_address, MAX_ADDR_LEN))
706         {
707         case READ_STATUS_OK:
708           break;
709         case READ_STATUS_EOF:
710           fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
711           exit (1);
712           break;
713         case READ_STATUS_ERROR:
714           fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
715                    strerror (errno));
716           exit (1);
717           break;
718         }
719         
720       close (bus_address_to_launcher_pipe[READ_END]);
721
722       verbose ("Reading PID from babysitter\n");
723       
724       switch (read_pid (bus_pid_to_launcher_pipe[READ_END], &bus_pid))
725         {
726         case READ_STATUS_OK:
727           break;
728         case READ_STATUS_EOF:
729           fprintf (stderr, "EOF in dbus-launch reading address from bus daemon\n");
730           exit (1);
731           break;
732         case READ_STATUS_ERROR:
733           fprintf (stderr, "Error in dbus-launch reading address from bus daemon: %s\n",
734                    strerror (errno));
735           exit (1);
736           break;
737         }
738
739       close (bus_pid_to_launcher_pipe[READ_END]);
740
741       printf ("DBUS_SESSION_BUS_ADDRESS='%s'\n",
742               bus_address);
743
744       printf ("DBUS_SESSION_BUS_PID=%ld\n",
745               (long) bus_pid);
746
747       verbose ("dbus-launch exiting\n");
748       
749       exit (0);
750     } 
751   
752   return 0;
753 }