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