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