Merge branch 'dbus-1.4'
[platform/upstream/dbus.git] / bus / main.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* main.c  main() for message bus
3  *
4  * Copyright (C) 2003 Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include <config.h>
25 #include "bus.h"
26 #include "driver.h"
27 #include <dbus/dbus-internals.h>
28 #include <dbus/dbus-watch.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #ifdef HAVE_SIGNAL_H
33 #include <signal.h>
34 #endif
35 #ifdef HAVE_ERRNO_H
36 #include <errno.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>     /* for write() and STDERR_FILENO */
40 #endif
41 #include "selinux.h"
42
43 static BusContext *context;
44
45 #ifdef DBUS_UNIX
46
47 static int reload_pipe[2];
48 #define RELOAD_READ_END 0
49 #define RELOAD_WRITE_END 1
50
51 static void close_reload_pipe (DBusWatch **);
52
53 typedef enum
54  {
55    ACTION_RELOAD = 'r',
56    ACTION_QUIT = 'q'
57  } SignalAction;
58
59 static void
60 signal_handler (int sig)
61 {
62   switch (sig)
63     {
64 #ifdef DBUS_BUS_ENABLE_DNOTIFY_ON_LINUX
65     case SIGIO:
66       /* explicit fall-through */
67 #endif /* DBUS_BUS_ENABLE_DNOTIFY_ON_LINUX  */
68 #ifdef SIGHUP
69     case SIGHUP:
70       {
71         DBusString str;
72         char action[2] = { ACTION_RELOAD, '\0' };
73
74         _dbus_string_init_const (&str, action);
75         if ((reload_pipe[RELOAD_WRITE_END] > 0) &&
76             !_dbus_write_socket (reload_pipe[RELOAD_WRITE_END], &str, 0, 1))
77           {
78             /* If we receive SIGHUP often enough to fill the pipe buffer (4096
79              * times on old Linux, 65536 on modern Linux) before it can be
80              * drained, let's just warn and ignore. The configuration will be
81              * reloaded while draining the pipe buffer, which is what we
82              * wanted. It's harmless that it will be reloaded fewer times than
83              * we asked for, since the reload is delayed anyway, so new changes
84              * will be picked up.
85              *
86              * We use write() because _dbus_warn uses vfprintf, which isn't
87              * async-signal-safe.
88              *
89              * This is necessarily Unix-specific, but so are POSIX signals,
90              * so... */
91             static const char message[] =
92               "Unable to write to reload pipe - buffer full?\n";
93
94             write (STDERR_FILENO, message, strlen (message));
95           }
96       }
97       break;
98 #endif
99
100     case SIGTERM:
101       {
102         DBusString str;
103         char action[2] = { ACTION_QUIT, '\0' };
104         _dbus_string_init_const (&str, action);
105         if ((reload_pipe[RELOAD_WRITE_END] < 0) ||
106             !_dbus_write_socket (reload_pipe[RELOAD_WRITE_END], &str, 0, 1))
107           {
108             /* If we can't write to the socket, dying seems a more
109              * important response to SIGTERM than cleaning up sockets,
110              * so we exit. We'd use exit(), but that's not async-signal-safe,
111              * so we'll have to resort to _exit(). */
112             static const char message[] =
113               "Unable to write termination signal to pipe - buffer full?\n"
114               "Will exit instead.\n";
115
116             write (STDERR_FILENO, message, strlen (message));
117             _exit (1);
118           }
119       }
120       break;
121     }
122 }
123 #endif /* DBUS_UNIX */
124
125 static void
126 usage (void)
127 {
128   fprintf (stderr, DBUS_DAEMON_NAME " [--version] [--session] [--system] [--config-file=FILE] [--print-address[=DESCRIPTOR]] [--print-pid[=DESCRIPTOR]] [--fork] [--nofork] [--introspect] [--address=ADDRESS] [--systemd-activation]\n");
129   exit (1);
130 }
131
132 static void
133 version (void)
134 {
135   printf ("D-Bus Message Bus Daemon %s\n"
136           "Copyright (C) 2002, 2003 Red Hat, Inc., CodeFactory AB, and others\n"
137           "This is free software; see the source for copying conditions.\n"
138           "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
139           DBUS_VERSION_STRING);
140   exit (0);
141 }
142
143 static void
144 introspect (void)
145 {
146   DBusString xml;
147   const char *v_STRING;
148
149   if (!_dbus_string_init (&xml))
150     goto oom;
151
152   if (!bus_driver_generate_introspect_string (&xml))
153     {
154       _dbus_string_free (&xml);
155       goto oom;
156     }
157
158   v_STRING = _dbus_string_get_const_data (&xml);
159   printf ("%s\n", v_STRING);
160
161   exit (0);
162
163  oom:
164   _dbus_warn ("Can not introspect - Out of memory\n");
165   exit (1);
166 }
167
168 static void
169 check_two_config_files (const DBusString *config_file,
170                         const char       *extra_arg)
171 {
172   if (_dbus_string_get_length (config_file) > 0)
173     {
174       fprintf (stderr, "--%s specified but configuration file %s already requested\n",
175                extra_arg, _dbus_string_get_const_data (config_file));
176       exit (1);
177     }
178 }
179
180 static void
181 check_two_addresses (const DBusString *address,
182                      const char       *extra_arg)
183 {
184   if (_dbus_string_get_length (address) > 0)
185     {
186       fprintf (stderr, "--%s specified but address %s already requested\n",
187                extra_arg, _dbus_string_get_const_data (address));
188       exit (1);
189     }
190 }
191
192 static void
193 check_two_addr_descriptors (const DBusString *addr_fd,
194                             const char       *extra_arg)
195 {
196   if (_dbus_string_get_length (addr_fd) > 0)
197     {
198       fprintf (stderr, "--%s specified but printing address to %s already requested\n",
199                extra_arg, _dbus_string_get_const_data (addr_fd));
200       exit (1);
201     }
202 }
203
204 static void
205 check_two_pid_descriptors (const DBusString *pid_fd,
206                            const char       *extra_arg)
207 {
208   if (_dbus_string_get_length (pid_fd) > 0)
209     {
210       fprintf (stderr, "--%s specified but printing pid to %s already requested\n",
211                extra_arg, _dbus_string_get_const_data (pid_fd));
212       exit (1);
213     }
214 }
215
216 #ifdef DBUS_UNIX
217 static dbus_bool_t
218 handle_reload_watch (DBusWatch    *watch,
219                      unsigned int  flags,
220                      void         *data)
221 {
222   DBusError error;
223   DBusString str;
224   char *action_str;
225   char action = '\0';
226
227   while (!_dbus_string_init (&str))
228     _dbus_wait_for_memory ();
229
230   if ((reload_pipe[RELOAD_READ_END] > 0) &&
231       _dbus_read_socket (reload_pipe[RELOAD_READ_END], &str, 1) != 1)
232     {
233       _dbus_warn ("Couldn't read from reload pipe.\n");
234       close_reload_pipe (&watch);
235       return TRUE;
236     }
237
238   action_str = _dbus_string_get_data (&str);
239   if (action_str != NULL)
240     {
241       action = action_str[0];
242     }
243   _dbus_string_free (&str);
244
245   /* this can only fail if we don't understand the config file
246    * or OOM.  Either way we should just stick with the currently
247    * loaded config.
248    */
249   dbus_error_init (&error);
250
251   switch (action)
252     {
253     case ACTION_RELOAD:
254       if (! bus_context_reload_config (context, &error))
255         {
256           _DBUS_ASSERT_ERROR_IS_SET (&error);
257           _dbus_assert (dbus_error_has_name (&error, DBUS_ERROR_FAILED) ||
258                         dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY));
259           _dbus_warn ("Unable to reload configuration: %s\n",
260                       error.message);
261           dbus_error_free (&error);
262         }
263       break;
264
265     case ACTION_QUIT:
266       {
267         DBusLoop *loop;
268         /*
269          * On OSs without abstract sockets, we want to quit
270          * gracefully rather than being killed by SIGTERM,
271          * so that DBusServer gets a chance to clean up the
272          * sockets from the filesystem. fd.o #38656
273          */
274         loop = bus_context_get_loop (context);
275         if (loop != NULL)
276           {
277             _dbus_loop_quit (loop);
278           }
279       }
280       break;
281
282     default:
283       break;
284     }
285
286   return TRUE;
287 }
288
289 static void
290 setup_reload_pipe (DBusLoop *loop)
291 {
292   DBusError error;
293   DBusWatch *watch;
294
295   dbus_error_init (&error);
296
297   if (!_dbus_full_duplex_pipe (&reload_pipe[0], &reload_pipe[1],
298                                TRUE, &error))
299     {
300       _dbus_warn ("Unable to create reload pipe: %s\n",
301                   error.message);
302       dbus_error_free (&error);
303       exit (1);
304     }
305
306   watch = _dbus_watch_new (reload_pipe[RELOAD_READ_END],
307                            DBUS_WATCH_READABLE, TRUE,
308                            handle_reload_watch, NULL, NULL);
309
310   if (watch == NULL)
311     {
312       _dbus_warn ("Unable to create reload watch: %s\n",
313                   error.message);
314       dbus_error_free (&error);
315       exit (1);
316     }
317
318   if (!_dbus_loop_add_watch (loop, watch))
319     {
320       _dbus_warn ("Unable to add reload watch to main loop: %s\n",
321                   error.message);
322       dbus_error_free (&error);
323       exit (1);
324     }
325
326 }
327
328 static void
329 close_reload_pipe (DBusWatch **watch)
330 {
331     _dbus_loop_remove_watch (bus_context_get_loop (context), *watch);
332     _dbus_watch_invalidate (*watch);
333     _dbus_watch_unref (*watch);
334     *watch = NULL;
335
336     _dbus_close_socket (reload_pipe[RELOAD_READ_END], NULL);
337     reload_pipe[RELOAD_READ_END] = -1;
338
339     _dbus_close_socket (reload_pipe[RELOAD_WRITE_END], NULL);
340     reload_pipe[RELOAD_WRITE_END] = -1;
341 }
342 #endif /* DBUS_UNIX */
343
344 int
345 main (int argc, char **argv)
346 {
347   DBusError error;
348   DBusString config_file;
349   DBusString address;
350   DBusString addr_fd;
351   DBusString pid_fd;
352   const char *prev_arg;
353   DBusPipe print_addr_pipe;
354   DBusPipe print_pid_pipe;
355   int i;
356   dbus_bool_t print_address;
357   dbus_bool_t print_pid;
358   int force_fork;
359   dbus_bool_t systemd_activation;
360
361   if (!_dbus_string_init (&config_file))
362     return 1;
363
364   if (!_dbus_string_init (&address))
365     return 1;
366
367   if (!_dbus_string_init (&addr_fd))
368     return 1;
369
370   if (!_dbus_string_init (&pid_fd))
371     return 1;
372
373   print_address = FALSE;
374   print_pid = FALSE;
375   force_fork = FORK_FOLLOW_CONFIG_FILE;
376   systemd_activation = FALSE;
377
378   prev_arg = NULL;
379   i = 1;
380   while (i < argc)
381     {
382       const char *arg = argv[i];
383
384       if (strcmp (arg, "--help") == 0 ||
385           strcmp (arg, "-h") == 0 ||
386           strcmp (arg, "-?") == 0)
387         usage ();
388       else if (strcmp (arg, "--version") == 0)
389         version ();
390       else if (strcmp (arg, "--introspect") == 0)
391         introspect ();
392       else if (strcmp (arg, "--nofork") == 0)
393         force_fork = FORK_NEVER;
394       else if (strcmp (arg, "--fork") == 0)
395         force_fork = FORK_ALWAYS;
396       else if (strcmp (arg, "--systemd-activation") == 0)
397         systemd_activation = TRUE;
398       else if (strcmp (arg, "--system") == 0)
399         {
400           check_two_config_files (&config_file, "system");
401
402           if (!_dbus_append_system_config_file (&config_file))
403             exit (1);
404         }
405       else if (strcmp (arg, "--session") == 0)
406         {
407           check_two_config_files (&config_file, "session");
408
409           if (!_dbus_append_session_config_file (&config_file))
410             exit (1);
411         }
412       else if (strstr (arg, "--config-file=") == arg)
413         {
414           const char *file;
415
416           check_two_config_files (&config_file, "config-file");
417
418           file = strchr (arg, '=');
419           ++file;
420
421           if (!_dbus_string_append (&config_file, file))
422             exit (1);
423         }
424       else if (prev_arg &&
425                strcmp (prev_arg, "--config-file") == 0)
426         {
427           check_two_config_files (&config_file, "config-file");
428
429           if (!_dbus_string_append (&config_file, arg))
430             exit (1);
431         }
432       else if (strcmp (arg, "--config-file") == 0)
433         ; /* wait for next arg */
434       else if (strstr (arg, "--address=") == arg)
435         {
436           const char *file;
437
438           check_two_addresses (&address, "address");
439
440           file = strchr (arg, '=');
441           ++file;
442
443           if (!_dbus_string_append (&address, file))
444             exit (1);
445         }
446       else if (prev_arg &&
447                strcmp (prev_arg, "--address") == 0)
448         {
449           check_two_addresses (&address, "address");
450
451           if (!_dbus_string_append (&address, arg))
452             exit (1);
453         }
454       else if (strcmp (arg, "--address") == 0)
455         ; /* wait for next arg */
456       else if (strstr (arg, "--print-address=") == arg)
457         {
458           const char *desc;
459
460           check_two_addr_descriptors (&addr_fd, "print-address");
461
462           desc = strchr (arg, '=');
463           ++desc;
464
465           if (!_dbus_string_append (&addr_fd, desc))
466             exit (1);
467
468           print_address = TRUE;
469         }
470       else if (prev_arg &&
471                strcmp (prev_arg, "--print-address") == 0)
472         {
473           check_two_addr_descriptors (&addr_fd, "print-address");
474
475           if (!_dbus_string_append (&addr_fd, arg))
476             exit (1);
477
478           print_address = TRUE;
479         }
480       else if (strcmp (arg, "--print-address") == 0)
481         print_address = TRUE; /* and we'll get the next arg if appropriate */
482       else if (strstr (arg, "--print-pid=") == arg)
483         {
484           const char *desc;
485
486           check_two_pid_descriptors (&pid_fd, "print-pid");
487
488           desc = strchr (arg, '=');
489           ++desc;
490
491           if (!_dbus_string_append (&pid_fd, desc))
492             exit (1);
493
494           print_pid = TRUE;
495         }
496       else if (prev_arg &&
497                strcmp (prev_arg, "--print-pid") == 0)
498         {
499           check_two_pid_descriptors (&pid_fd, "print-pid");
500
501           if (!_dbus_string_append (&pid_fd, arg))
502             exit (1);
503
504           print_pid = TRUE;
505         }
506       else if (strcmp (arg, "--print-pid") == 0)
507         print_pid = TRUE; /* and we'll get the next arg if appropriate */
508       else
509         usage ();
510
511       prev_arg = arg;
512
513       ++i;
514     }
515
516   if (_dbus_string_get_length (&config_file) == 0)
517     {
518       fprintf (stderr, "No configuration file specified.\n");
519       usage ();
520     }
521
522   _dbus_pipe_invalidate (&print_addr_pipe);
523   if (print_address)
524     {
525       _dbus_pipe_init_stdout (&print_addr_pipe);
526       if (_dbus_string_get_length (&addr_fd) > 0)
527         {
528           long val;
529           int end;
530           if (!_dbus_string_parse_int (&addr_fd, 0, &val, &end) ||
531               end != _dbus_string_get_length (&addr_fd) ||
532               val < 0 || val > _DBUS_INT_MAX)
533             {
534               fprintf (stderr, "Invalid file descriptor: \"%s\"\n",
535                        _dbus_string_get_const_data (&addr_fd));
536               exit (1);
537             }
538
539           _dbus_pipe_init (&print_addr_pipe, val);
540         }
541     }
542   _dbus_string_free (&addr_fd);
543
544   _dbus_pipe_invalidate (&print_pid_pipe);
545   if (print_pid)
546     {
547       _dbus_pipe_init_stdout (&print_pid_pipe);
548       if (_dbus_string_get_length (&pid_fd) > 0)
549         {
550           long val;
551           int end;
552           if (!_dbus_string_parse_int (&pid_fd, 0, &val, &end) ||
553               end != _dbus_string_get_length (&pid_fd) ||
554               val < 0 || val > _DBUS_INT_MAX)
555             {
556               fprintf (stderr, "Invalid file descriptor: \"%s\"\n",
557                        _dbus_string_get_const_data (&pid_fd));
558               exit (1);
559             }
560
561           _dbus_pipe_init (&print_pid_pipe, val);
562         }
563     }
564   _dbus_string_free (&pid_fd);
565
566   if (!bus_selinux_pre_init ())
567     {
568       _dbus_warn ("SELinux pre-initialization failed\n");
569       exit (1);
570     }
571
572   dbus_error_init (&error);
573   context = bus_context_new (&config_file, force_fork,
574                              &print_addr_pipe, &print_pid_pipe,
575                              _dbus_string_get_length(&address) > 0 ? &address : NULL,
576                              systemd_activation,
577                              &error);
578   _dbus_string_free (&config_file);
579   if (context == NULL)
580     {
581       _dbus_warn ("Failed to start message bus: %s\n",
582                   error.message);
583       dbus_error_free (&error);
584       exit (1);
585     }
586
587   /* bus_context_new() closes the print_addr_pipe and
588    * print_pid_pipe
589    */
590
591 #ifdef DBUS_UNIX
592   setup_reload_pipe (bus_context_get_loop (context));
593
594   /* POSIX signals are Unix-specific, and _dbus_set_signal_handler is
595    * unimplemented (and probably unimplementable) on Windows, so there's
596    * no point in trying to make the handler portable to non-Unix. */
597
598   _dbus_set_signal_handler (SIGTERM, signal_handler);
599 #ifdef SIGHUP
600   _dbus_set_signal_handler (SIGHUP, signal_handler);
601 #endif
602 #ifdef DBUS_BUS_ENABLE_DNOTIFY_ON_LINUX
603   _dbus_set_signal_handler (SIGIO, signal_handler);
604 #endif /* DBUS_BUS_ENABLE_DNOTIFY_ON_LINUX */
605 #endif /* DBUS_UNIX */
606
607   _dbus_verbose ("We are on D-Bus...\n");
608   _dbus_loop_run (bus_context_get_loop (context));
609
610   bus_context_shutdown (context);
611   bus_context_unref (context);
612   bus_selinux_shutdown ();
613
614   return 0;
615 }