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