Add DBUS_GNUC_PRINTF checks to new formatting functions
[platform/upstream/dbus.git] / bus / bus.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* bus.c  message bus context object
3  *
4  * Copyright (C) 2003, 2004 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 "bus.h"
25 #include "activation.h"
26 #include "connection.h"
27 #include "services.h"
28 #include "utils.h"
29 #include "policy.h"
30 #include "config-parser.h"
31 #include "signals.h"
32 #include "selinux.h"
33 #include "dir-watch.h"
34 #include <dbus/dbus-list.h>
35 #include <dbus/dbus-hash.h>
36 #include <dbus/dbus-credentials.h>
37 #include <dbus/dbus-internals.h>
38
39 struct BusContext
40 {
41   int refcount;
42   DBusGUID uuid;
43   char *config_file;
44   char *type;
45   char *servicehelper;
46   char *address;
47   char *pidfile;
48   char *user;
49   char *log_prefix;
50   DBusLoop *loop;
51   DBusList *servers;
52   BusConnections *connections;
53   BusActivation *activation;
54   BusRegistry *registry;
55   BusPolicy *policy;
56   BusMatchmaker *matchmaker;
57   BusLimits limits;
58   unsigned int fork : 1;
59   unsigned int syslog : 1;
60   unsigned int keep_umask : 1;
61 };
62
63 static dbus_int32_t server_data_slot = -1;
64
65 typedef struct
66 {
67   BusContext *context;
68 } BusServerData;
69
70 #define BUS_SERVER_DATA(server) (dbus_server_get_data ((server), server_data_slot))
71
72 static BusContext*
73 server_get_context (DBusServer *server)
74 {
75   BusContext *context;
76   BusServerData *bd;
77   
78   if (!dbus_server_allocate_data_slot (&server_data_slot))
79     return NULL;
80
81   bd = BUS_SERVER_DATA (server);
82   if (bd == NULL)
83     {
84       dbus_server_free_data_slot (&server_data_slot);
85       return NULL;
86     }
87
88   context = bd->context;
89
90   dbus_server_free_data_slot (&server_data_slot);
91
92   return context;
93 }
94
95 static dbus_bool_t
96 server_watch_callback (DBusWatch     *watch,
97                        unsigned int   condition,
98                        void          *data)
99 {
100   /* FIXME this can be done in dbus-mainloop.c
101    * if the code in activation.c for the babysitter
102    * watch handler is fixed.
103    */
104   
105   return dbus_watch_handle (watch, condition);
106 }
107
108 static dbus_bool_t
109 add_server_watch (DBusWatch  *watch,
110                   void       *data)
111 {
112   DBusServer *server = data;
113   BusContext *context;
114   
115   context = server_get_context (server);
116   
117   return _dbus_loop_add_watch (context->loop,
118                                watch, server_watch_callback, server,
119                                NULL);
120 }
121
122 static void
123 remove_server_watch (DBusWatch  *watch,
124                      void       *data)
125 {
126   DBusServer *server = data;
127   BusContext *context;
128   
129   context = server_get_context (server);
130   
131   _dbus_loop_remove_watch (context->loop,
132                            watch, server_watch_callback, server);
133 }
134
135
136 static void
137 server_timeout_callback (DBusTimeout   *timeout,
138                          void          *data)
139 {
140   /* can return FALSE on OOM but we just let it fire again later */
141   dbus_timeout_handle (timeout);
142 }
143
144 static dbus_bool_t
145 add_server_timeout (DBusTimeout *timeout,
146                     void        *data)
147 {
148   DBusServer *server = data;
149   BusContext *context;
150   
151   context = server_get_context (server);
152
153   return _dbus_loop_add_timeout (context->loop,
154                                  timeout, server_timeout_callback, server, NULL);
155 }
156
157 static void
158 remove_server_timeout (DBusTimeout *timeout,
159                        void        *data)
160 {
161   DBusServer *server = data;
162   BusContext *context;
163   
164   context = server_get_context (server);
165   
166   _dbus_loop_remove_timeout (context->loop,
167                              timeout, server_timeout_callback, server);
168 }
169
170 static void
171 new_connection_callback (DBusServer     *server,
172                          DBusConnection *new_connection,
173                          void           *data)
174 {
175   BusContext *context = data;
176   
177   if (!bus_connections_setup_connection (context->connections, new_connection))
178     {
179       _dbus_verbose ("No memory to setup new connection\n");
180
181       /* if we don't do this, it will get unref'd without
182        * being disconnected... kind of strange really
183        * that we have to do this, people won't get it right
184        * in general.
185        */
186       dbus_connection_close (new_connection);
187     }
188
189   dbus_connection_set_max_received_size (new_connection,
190                                          context->limits.max_incoming_bytes);
191
192   dbus_connection_set_max_message_size (new_connection,
193                                         context->limits.max_message_size);
194   
195   /* on OOM, we won't have ref'd the connection so it will die. */
196 }
197
198 static void
199 free_server_data (void *data)
200 {
201   BusServerData *bd = data;  
202   
203   dbus_free (bd);
204 }
205
206 static dbus_bool_t
207 setup_server (BusContext *context,
208               DBusServer *server,
209               char      **auth_mechanisms,
210               DBusError  *error)
211 {
212   BusServerData *bd;
213
214   bd = dbus_new0 (BusServerData, 1);
215   if (bd == NULL || !dbus_server_set_data (server,
216                                            server_data_slot,
217                                            bd, free_server_data))
218     {
219       dbus_free (bd);
220       BUS_SET_OOM (error);
221       return FALSE;
222     }
223
224   bd->context = context;
225   
226   if (!dbus_server_set_auth_mechanisms (server, (const char**) auth_mechanisms))
227     {
228       BUS_SET_OOM (error);
229       return FALSE;
230     }
231   
232   dbus_server_set_new_connection_function (server,
233                                            new_connection_callback,
234                                            context, NULL);
235   
236   if (!dbus_server_set_watch_functions (server,
237                                         add_server_watch,
238                                         remove_server_watch,
239                                         NULL,
240                                         server,
241                                         NULL))
242     {
243       BUS_SET_OOM (error);
244       return FALSE;
245     }
246
247   if (!dbus_server_set_timeout_functions (server,
248                                           add_server_timeout,
249                                           remove_server_timeout,
250                                           NULL,
251                                           server, NULL))
252     {
253       BUS_SET_OOM (error);
254       return FALSE;
255     }
256   
257   return TRUE;
258 }
259
260 /* This code only gets executed the first time the
261  * config files are parsed.  It is not executed
262  * when config files are reloaded.
263  */
264 static dbus_bool_t
265 process_config_first_time_only (BusContext      *context,
266                                 BusConfigParser *parser,
267                                 DBusError       *error)
268 {
269   DBusString log_prefix;
270   DBusList *link;
271   DBusList **addresses;
272   const char *user, *pidfile;
273   char **auth_mechanisms;
274   DBusList **auth_mechanisms_list;
275   int len;
276   dbus_bool_t retval;
277
278   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
279
280   retval = FALSE;
281   auth_mechanisms = NULL;
282
283   /* Check for an existing pid file. Of course this is a race;
284    * we'd have to use fcntl() locks on the pid file to
285    * avoid that. But we want to check for the pid file
286    * before overwriting any existing sockets, etc.
287    */
288   pidfile = bus_config_parser_get_pidfile (parser);
289   if (pidfile != NULL)
290     {
291       DBusString u;
292       DBusStat stbuf;
293       
294       _dbus_string_init_const (&u, pidfile);
295
296       if (_dbus_stat (&u, &stbuf, NULL))
297         {
298           dbus_set_error (error, DBUS_ERROR_FAILED,
299                                   "The pid file \"%s\" exists, if the message bus is not running, remove this file",
300                           pidfile);
301               goto failed;
302         }
303     }
304
305   /* keep around the pid filename so we can delete it later */
306   context->pidfile = _dbus_strdup (pidfile);
307
308   /* note that type may be NULL */
309   context->type = _dbus_strdup (bus_config_parser_get_type (parser));
310   if (bus_config_parser_get_type (parser) != NULL && context->type == NULL)
311     goto oom;
312
313   user = bus_config_parser_get_user (parser);
314   if (user != NULL)
315     {
316       context->user = _dbus_strdup (user);
317       if (context->user == NULL)
318         goto oom;
319     }
320
321   /* Set up the prefix for syslog messages */
322   if (!_dbus_string_init (&log_prefix))
323     goto oom;
324   if (context->type && !strcmp (context->type, "system"))
325     {
326       if (!_dbus_string_append (&log_prefix, "[system] "))
327         goto oom;
328     }
329   else if (context->type && !strcmp (context->type, "session"))
330     {
331       DBusCredentials *credentials;
332
333       credentials = _dbus_credentials_new_from_current_process ();
334       if (!credentials)
335         goto oom;
336       if (!_dbus_string_append (&log_prefix, "[session "))
337         goto oom;
338       if (!_dbus_credentials_to_string_append (credentials, &log_prefix))
339         goto oom;
340       if (!_dbus_string_append (&log_prefix, "] "))
341         goto oom;
342       _dbus_credentials_unref (credentials);
343     }
344   if (!_dbus_string_steal_data (&log_prefix, &context->log_prefix))
345     goto oom;
346   _dbus_string_free (&log_prefix);
347
348   /* Build an array of auth mechanisms */
349
350   auth_mechanisms_list = bus_config_parser_get_mechanisms (parser);
351   len = _dbus_list_get_length (auth_mechanisms_list);
352
353   if (len > 0)
354     {
355       int i;
356
357       auth_mechanisms = dbus_new0 (char*, len + 1);
358       if (auth_mechanisms == NULL)
359         goto oom;
360
361       i = 0;
362       link = _dbus_list_get_first_link (auth_mechanisms_list);
363       while (link != NULL)
364         {
365           auth_mechanisms[i] = _dbus_strdup (link->data);
366           if (auth_mechanisms[i] == NULL)
367             goto oom;
368           link = _dbus_list_get_next_link (auth_mechanisms_list, link);
369         }
370     }
371   else
372     {
373       auth_mechanisms = NULL;
374     }
375
376   /* Listen on our addresses */
377   
378   addresses = bus_config_parser_get_addresses (parser);  
379   
380   link = _dbus_list_get_first_link (addresses);
381   while (link != NULL)
382     {
383       DBusServer *server;
384       
385       server = dbus_server_listen (link->data, error);
386       if (server == NULL)
387         {
388           _DBUS_ASSERT_ERROR_IS_SET (error);
389           goto failed;
390         }
391       else if (!setup_server (context, server, auth_mechanisms, error))
392         {
393           _DBUS_ASSERT_ERROR_IS_SET (error);
394           goto failed;
395         }
396
397       if (!_dbus_list_append (&context->servers, server))
398         goto oom;
399
400       link = _dbus_list_get_next_link (addresses, link);
401     }
402
403   context->fork = bus_config_parser_get_fork (parser);
404   context->syslog = bus_config_parser_get_syslog (parser);
405   context->keep_umask = bus_config_parser_get_keep_umask (parser);
406
407   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
408   retval = TRUE;
409
410  failed:
411   dbus_free_string_array (auth_mechanisms);
412   return retval;
413
414  oom:
415   BUS_SET_OOM (error);
416   dbus_free_string_array (auth_mechanisms);
417   return FALSE;
418 }
419
420 /* This code gets executed every time the config files
421  * are parsed: both during BusContext construction
422  * and on reloads. This function is slightly screwy
423  * since it can do a "half reload" in out-of-memory
424  * situations. Realistically, unlikely to ever matter.
425  */
426 static dbus_bool_t
427 process_config_every_time (BusContext      *context,
428                            BusConfigParser *parser,
429                            dbus_bool_t      is_reload,
430                            DBusError       *error)
431 {
432   DBusString full_address;
433   DBusList *link;
434   DBusList **dirs;
435   BusActivation *new_activation;
436   char *addr;
437   const char *servicehelper;
438   char *s;
439   
440   dbus_bool_t retval;
441
442   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
443
444   addr = NULL;
445   retval = FALSE;
446
447   if (!_dbus_string_init (&full_address))
448     {
449       BUS_SET_OOM (error);
450       return FALSE;
451     }
452
453   /* get our limits and timeout lengths */
454   bus_config_parser_get_limits (parser, &context->limits);
455
456   if (context->policy)
457     bus_policy_unref (context->policy);
458   context->policy = bus_config_parser_steal_policy (parser);
459   _dbus_assert (context->policy != NULL);
460
461   /* We have to build the address backward, so that
462    * <listen> later in the config file have priority
463    */
464   link = _dbus_list_get_last_link (&context->servers);
465   while (link != NULL)
466     {
467       addr = dbus_server_get_address (link->data);
468       if (addr == NULL)
469         {
470           BUS_SET_OOM (error);
471           goto failed;
472         }
473
474       if (_dbus_string_get_length (&full_address) > 0)
475         {
476           if (!_dbus_string_append (&full_address, ";"))
477             {
478               BUS_SET_OOM (error);
479               goto failed;
480             }
481         }
482
483       if (!_dbus_string_append (&full_address, addr))
484         {
485           BUS_SET_OOM (error);
486           goto failed;
487         }
488
489       dbus_free (addr);
490       addr = NULL;
491
492       link = _dbus_list_get_prev_link (&context->servers, link);
493     }
494
495   if (is_reload)
496     dbus_free (context->address);
497
498   if (!_dbus_string_copy_data (&full_address, &context->address))
499     {
500       BUS_SET_OOM (error);
501       goto failed;
502     }
503
504   /* get the service directories */
505   dirs = bus_config_parser_get_service_dirs (parser);
506
507   /* and the service helper */
508   servicehelper = bus_config_parser_get_servicehelper (parser);
509
510   s = _dbus_strdup(servicehelper);
511   if (s == NULL && servicehelper != NULL)
512     {
513       BUS_SET_OOM (error);
514       goto failed;
515     }
516   else
517     {
518       dbus_free(context->servicehelper);
519       context->servicehelper = s;
520     }
521
522   /* Create activation subsystem */
523   if (context->activation)
524     {
525       if (!bus_activation_reload (context->activation, &full_address, dirs, error))
526         goto failed;
527     }
528   else
529     {
530       context->activation = bus_activation_new (context, &full_address, dirs, error);
531     }
532
533   if (context->activation == NULL)
534     {
535       _DBUS_ASSERT_ERROR_IS_SET (error);
536       goto failed;
537     }
538
539   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
540   retval = TRUE;
541
542  failed:
543   _dbus_string_free (&full_address);
544   
545   if (addr)
546     dbus_free (addr);
547
548   return retval;
549 }
550
551 static dbus_bool_t
552 list_concat_new (DBusList **a,
553                  DBusList **b,
554                  DBusList **result)
555 {
556   DBusList *link;
557
558   *result = NULL;
559
560   link = _dbus_list_get_first_link (a);
561   for (link = _dbus_list_get_first_link (a); link; link = _dbus_list_get_next_link (a, link))
562     {
563       if (!_dbus_list_append (result, link->data))
564         goto oom;
565     }
566   for (link = _dbus_list_get_first_link (b); link; link = _dbus_list_get_next_link (b, link))
567     {
568       if (!_dbus_list_append (result, link->data))
569         goto oom;
570     }
571
572   return TRUE;
573 oom:
574   _dbus_list_clear (result);
575   return FALSE;
576 }
577
578 static dbus_bool_t
579 process_config_postinit (BusContext      *context,
580                          BusConfigParser *parser,
581                          DBusError       *error)
582 {
583   DBusHashTable *service_context_table;
584   DBusList *watched_dirs = NULL;
585
586   service_context_table = bus_config_parser_steal_service_context_table (parser);
587   if (!bus_registry_set_service_context_table (context->registry,
588                                                service_context_table))
589     {
590       BUS_SET_OOM (error);
591       return FALSE;
592     }
593
594   _dbus_hash_table_unref (service_context_table);
595
596   /* We need to monitor both the configuration directories and directories
597    * containing .service files.
598    */
599   if (!list_concat_new (bus_config_parser_get_conf_dirs (parser),
600                         bus_config_parser_get_service_dirs (parser),
601                         &watched_dirs))
602     {
603       BUS_SET_OOM (error);
604       return FALSE;
605     }
606
607   bus_set_watched_dirs (context, &watched_dirs);
608
609   _dbus_list_clear (&watched_dirs);
610
611   return TRUE;
612 }
613
614 BusContext*
615 bus_context_new (const DBusString *config_file,
616                  ForceForkSetting  force_fork,
617                  DBusPipe         *print_addr_pipe,
618                  DBusPipe         *print_pid_pipe,
619                  DBusError        *error)
620 {
621   DBusString log_prefix;
622   BusContext *context;
623   BusConfigParser *parser;
624
625   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
626
627   context = NULL;
628   parser = NULL;
629
630   if (!dbus_server_allocate_data_slot (&server_data_slot))
631     {
632       BUS_SET_OOM (error);
633       return NULL;
634     }
635
636   context = dbus_new0 (BusContext, 1);
637   if (context == NULL)
638     {
639       BUS_SET_OOM (error);
640       goto failed;
641     }
642   context->refcount = 1;
643
644   _dbus_generate_uuid (&context->uuid);
645
646   if (!_dbus_string_copy_data (config_file, &context->config_file))
647     {
648       BUS_SET_OOM (error);
649       goto failed;
650     }
651
652   context->loop = _dbus_loop_new ();
653   if (context->loop == NULL)
654     {
655       BUS_SET_OOM (error);
656       goto failed;
657     }
658
659   context->registry = bus_registry_new (context);
660   if (context->registry == NULL)
661     {
662       BUS_SET_OOM (error);
663       goto failed;
664     }
665
666   parser = bus_config_load (config_file, TRUE, NULL, error);
667   if (parser == NULL)
668     {
669       _DBUS_ASSERT_ERROR_IS_SET (error);
670       goto failed;
671     }
672   
673   if (!process_config_first_time_only (context, parser, error))
674     {
675       _DBUS_ASSERT_ERROR_IS_SET (error);
676       goto failed;
677     }
678   if (!process_config_every_time (context, parser, FALSE, error))
679     {
680       _DBUS_ASSERT_ERROR_IS_SET (error);
681       goto failed;
682     }
683   
684   /* we need another ref of the server data slot for the context
685    * to own
686    */
687   if (!dbus_server_allocate_data_slot (&server_data_slot))
688     _dbus_assert_not_reached ("second ref of server data slot failed");
689
690   /* Note that we don't know whether the print_addr_pipe is
691    * one of the sockets we're using to listen on, or some
692    * other random thing. But I think the answer is "don't do
693    * that then"
694    */
695   if (print_addr_pipe != NULL && _dbus_pipe_is_valid (print_addr_pipe))
696     {
697       DBusString addr;
698       const char *a = bus_context_get_address (context);
699       int bytes;
700       
701       _dbus_assert (a != NULL);
702       if (!_dbus_string_init (&addr))
703         {
704           BUS_SET_OOM (error);
705           goto failed;
706         }
707       
708       if (!_dbus_string_append (&addr, a) ||
709           !_dbus_string_append (&addr, "\n"))
710         {
711           _dbus_string_free (&addr);
712           BUS_SET_OOM (error);
713           goto failed;
714         }
715
716       bytes = _dbus_string_get_length (&addr);
717       if (_dbus_pipe_write (print_addr_pipe, &addr, 0, bytes, error) != bytes)
718         {
719           /* pipe write returns an error on failure but not short write */
720           if (error != NULL && !dbus_error_is_set (error))
721             {
722               dbus_set_error (error, DBUS_ERROR_FAILED,
723                               "Printing message bus address: did not write all bytes\n");
724             }
725           _dbus_string_free (&addr);
726           goto failed;
727         }
728
729       if (!_dbus_pipe_is_stdout_or_stderr (print_addr_pipe))
730         _dbus_pipe_close (print_addr_pipe, NULL);
731       
732       _dbus_string_free (&addr);
733     }
734   
735   context->connections = bus_connections_new (context);
736   if (context->connections == NULL)
737     {
738       BUS_SET_OOM (error);
739       goto failed;
740     }
741
742   context->matchmaker = bus_matchmaker_new ();
743   if (context->matchmaker == NULL)
744     {
745       BUS_SET_OOM (error);
746       goto failed;
747     }
748
749   /* check user before we fork */
750   if (context->user != NULL)
751     {
752       if (!_dbus_verify_daemon_user (context->user))
753         {
754           dbus_set_error (error, DBUS_ERROR_FAILED,
755                           "Could not get UID and GID for username \"%s\"",
756                           context->user);
757           goto failed;
758         }
759     }
760
761   /* Now become a daemon if appropriate and write out pid file in any case */
762   {
763     DBusString u;
764
765     if (context->pidfile)
766       _dbus_string_init_const (&u, context->pidfile);
767
768     if ((force_fork != FORK_NEVER && context->fork) || force_fork == FORK_ALWAYS)
769       {
770         _dbus_verbose ("Forking and becoming daemon\n");
771         
772         if (!_dbus_become_daemon (context->pidfile ? &u : NULL, 
773                                   print_pid_pipe,
774                                   error,
775                                   context->keep_umask))
776           {
777             _DBUS_ASSERT_ERROR_IS_SET (error);
778             goto failed;
779           }
780       }
781     else
782       {
783         _dbus_verbose ("Fork not requested\n");
784         
785         /* Need to write PID file and to PID pipe for ourselves,
786          * not for the child process. This is a no-op if the pidfile
787          * is NULL and print_pid_pipe is NULL.
788          */
789         if (!_dbus_write_pid_to_file_and_pipe (context->pidfile ? &u : NULL,
790                                                print_pid_pipe,
791                                                _dbus_getpid (),
792                                                error))
793           {
794             _DBUS_ASSERT_ERROR_IS_SET (error);
795             goto failed;
796           }
797       }
798   }
799
800   if (print_pid_pipe && _dbus_pipe_is_valid (print_pid_pipe) &&
801       !_dbus_pipe_is_stdout_or_stderr (print_pid_pipe))
802     _dbus_pipe_close (print_pid_pipe, NULL);
803
804   if (!bus_selinux_full_init ())
805     {
806       bus_context_log (context, DBUS_SYSTEM_LOG_FATAL, "SELinux enabled but AVC initialization failed; check system log\n");
807     }
808
809   if (!process_config_postinit (context, parser, error))
810     {
811       _DBUS_ASSERT_ERROR_IS_SET (error);
812       goto failed;
813     }
814
815   if (parser != NULL)
816     {
817       bus_config_parser_unref (parser);
818       parser = NULL;
819     }
820   
821   /* Here we change our credentials if required,
822    * as soon as we've set up our sockets and pidfile
823    */
824   if (context->user != NULL)
825     {
826       if (!_dbus_change_to_daemon_user (context->user, error))
827         {
828           _DBUS_ASSERT_ERROR_IS_SET (error);
829           goto failed;
830         }
831
832 #ifdef HAVE_SELINUX
833       /* FIXME - why not just put this in full_init() below? */
834       bus_selinux_audit_init ();
835 #endif
836     }
837
838   dbus_server_free_data_slot (&server_data_slot);
839   
840   return context;
841   
842  failed:  
843   if (parser != NULL)
844     bus_config_parser_unref (parser);
845   if (context != NULL)
846     bus_context_unref (context);
847
848   if (server_data_slot >= 0)
849     dbus_server_free_data_slot (&server_data_slot);
850   
851   return NULL;
852 }
853
854 dbus_bool_t
855 bus_context_get_id (BusContext       *context,
856                     DBusString       *uuid)
857 {
858   return _dbus_uuid_encode (&context->uuid, uuid);
859 }
860
861 dbus_bool_t
862 bus_context_reload_config (BusContext *context,
863                            DBusError  *error)
864 {
865   BusConfigParser *parser;
866   DBusString config_file;
867   dbus_bool_t ret;
868
869   /* Flush the user database cache */
870   _dbus_flush_caches ();
871
872   ret = FALSE;
873   _dbus_string_init_const (&config_file, context->config_file);
874   parser = bus_config_load (&config_file, TRUE, NULL, error);
875   if (parser == NULL)
876     {
877       _DBUS_ASSERT_ERROR_IS_SET (error);
878       goto failed;
879     }
880   
881   if (!process_config_every_time (context, parser, TRUE, error))
882     {
883       _DBUS_ASSERT_ERROR_IS_SET (error);
884       goto failed;
885     }
886   if (!process_config_postinit (context, parser, error))
887     {
888       _DBUS_ASSERT_ERROR_IS_SET (error);
889       goto failed;
890     }
891   ret = TRUE;
892
893   bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Reloaded configuration");
894  failed:
895   if (!ret)
896     bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Unable to reload configuration: %s", error->message);
897   if (parser != NULL)
898     bus_config_parser_unref (parser);
899   return ret;
900 }
901
902 static void
903 shutdown_server (BusContext *context,
904                  DBusServer *server)
905 {
906   if (server == NULL ||
907       !dbus_server_get_is_connected (server))
908     return;
909   
910   if (!dbus_server_set_watch_functions (server,
911                                         NULL, NULL, NULL,
912                                         context,
913                                         NULL))
914     _dbus_assert_not_reached ("setting watch functions to NULL failed");
915   
916   if (!dbus_server_set_timeout_functions (server,
917                                           NULL, NULL, NULL,
918                                           context,
919                                           NULL))
920     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
921   
922   dbus_server_disconnect (server);
923 }
924
925 void
926 bus_context_shutdown (BusContext  *context)
927 {
928   DBusList *link;
929
930   link = _dbus_list_get_first_link (&context->servers);
931   while (link != NULL)
932     {
933       shutdown_server (context, link->data);
934
935       link = _dbus_list_get_next_link (&context->servers, link);
936     }
937 }
938
939 BusContext *
940 bus_context_ref (BusContext *context)
941 {
942   _dbus_assert (context->refcount > 0);
943   context->refcount += 1;
944
945   return context;
946 }
947
948 void
949 bus_context_unref (BusContext *context)
950 {
951   _dbus_assert (context->refcount > 0);
952   context->refcount -= 1;
953
954   if (context->refcount == 0)
955     {
956       DBusList *link;
957       
958       _dbus_verbose ("Finalizing bus context %p\n", context);
959       
960       bus_context_shutdown (context);
961
962       if (context->connections)
963         {
964           bus_connections_unref (context->connections);
965           context->connections = NULL;
966         }
967       
968       if (context->registry)
969         {
970           bus_registry_unref (context->registry);
971           context->registry = NULL;
972         }
973       
974       if (context->activation)
975         {
976           bus_activation_unref (context->activation);
977           context->activation = NULL;
978         }
979
980       link = _dbus_list_get_first_link (&context->servers);
981       while (link != NULL)
982         {
983           dbus_server_unref (link->data);
984           
985           link = _dbus_list_get_next_link (&context->servers, link);
986         }
987       _dbus_list_clear (&context->servers);
988
989       if (context->policy)
990         {
991           bus_policy_unref (context->policy);
992           context->policy = NULL;
993         }
994       
995       if (context->loop)
996         {
997           _dbus_loop_unref (context->loop);
998           context->loop = NULL;
999         }
1000
1001       if (context->matchmaker)
1002         {
1003           bus_matchmaker_unref (context->matchmaker);
1004           context->matchmaker = NULL;
1005         }
1006
1007       dbus_free (context->config_file);
1008       dbus_free (context->log_prefix);
1009       dbus_free (context->type);
1010       dbus_free (context->address);
1011       dbus_free (context->user);
1012       dbus_free (context->servicehelper);
1013
1014       if (context->pidfile)
1015         {
1016           DBusString u;
1017           _dbus_string_init_const (&u, context->pidfile);
1018
1019           /* Deliberately ignore errors here, since there's not much
1020            * we can do about it, and we're exiting anyways.
1021            */
1022           _dbus_delete_file (&u, NULL);
1023
1024           dbus_free (context->pidfile); 
1025         }
1026       dbus_free (context);
1027
1028       dbus_server_free_data_slot (&server_data_slot);
1029     }
1030 }
1031
1032 /* type may be NULL */
1033 const char*
1034 bus_context_get_type (BusContext *context)
1035 {
1036   return context->type;
1037 }
1038
1039 const char*
1040 bus_context_get_address (BusContext *context)
1041 {
1042   return context->address;
1043 }
1044
1045 const char*
1046 bus_context_get_servicehelper (BusContext *context)
1047 {
1048   return context->servicehelper;
1049 }
1050
1051 BusRegistry*
1052 bus_context_get_registry (BusContext  *context)
1053 {
1054   return context->registry;
1055 }
1056
1057 BusConnections*
1058 bus_context_get_connections (BusContext  *context)
1059 {
1060   return context->connections;
1061 }
1062
1063 BusActivation*
1064 bus_context_get_activation (BusContext  *context)
1065 {
1066   return context->activation;
1067 }
1068
1069 BusMatchmaker*
1070 bus_context_get_matchmaker (BusContext  *context)
1071 {
1072   return context->matchmaker;
1073 }
1074
1075 DBusLoop*
1076 bus_context_get_loop (BusContext *context)
1077 {
1078   return context->loop;
1079 }
1080
1081 dbus_bool_t
1082 bus_context_allow_unix_user (BusContext   *context,
1083                              unsigned long uid)
1084 {
1085   return bus_policy_allow_unix_user (context->policy,
1086                                      uid);
1087 }
1088
1089 /* For now this is never actually called because the default
1090  * DBusConnection behavior of 'same user that owns the bus can connect'
1091  * is all it would do.
1092  */
1093 dbus_bool_t
1094 bus_context_allow_windows_user (BusContext       *context,
1095                                 const char       *windows_sid)
1096 {
1097   return bus_policy_allow_windows_user (context->policy,
1098                                         windows_sid);
1099 }
1100
1101 BusPolicy *
1102 bus_context_get_policy (BusContext *context)
1103 {
1104   return context->policy;
1105 }
1106
1107 BusClientPolicy*
1108 bus_context_create_client_policy (BusContext      *context,
1109                                   DBusConnection  *connection,
1110                                   DBusError       *error)
1111 {
1112   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1113   return bus_policy_create_client_policy (context->policy, connection,
1114                                           error);
1115 }
1116
1117 int
1118 bus_context_get_activation_timeout (BusContext *context)
1119 {
1120   
1121   return context->limits.activation_timeout;
1122 }
1123
1124 int
1125 bus_context_get_auth_timeout (BusContext *context)
1126 {
1127   return context->limits.auth_timeout;
1128 }
1129
1130 int
1131 bus_context_get_max_completed_connections (BusContext *context)
1132 {
1133   return context->limits.max_completed_connections;
1134 }
1135
1136 int
1137 bus_context_get_max_incomplete_connections (BusContext *context)
1138 {
1139   return context->limits.max_incomplete_connections;
1140 }
1141
1142 int
1143 bus_context_get_max_connections_per_user (BusContext *context)
1144 {
1145   return context->limits.max_connections_per_user;
1146 }
1147
1148 int
1149 bus_context_get_max_pending_activations (BusContext *context)
1150 {
1151   return context->limits.max_pending_activations;
1152 }
1153
1154 int
1155 bus_context_get_max_services_per_connection (BusContext *context)
1156 {
1157   return context->limits.max_services_per_connection;
1158 }
1159
1160 int
1161 bus_context_get_max_match_rules_per_connection (BusContext *context)
1162 {
1163   return context->limits.max_match_rules_per_connection;
1164 }
1165
1166 int
1167 bus_context_get_max_replies_per_connection (BusContext *context)
1168 {
1169   return context->limits.max_replies_per_connection;
1170 }
1171
1172 int
1173 bus_context_get_reply_timeout (BusContext *context)
1174 {
1175   return context->limits.reply_timeout;
1176 }
1177
1178 void
1179 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...) _DBUS_GNUC_PRINTF (3, 4);
1180
1181 void
1182 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...)
1183 {
1184   va_list args;
1185
1186   if (!context->syslog)
1187     return;
1188
1189   va_start (args, msg);
1190
1191   if (context->log_prefix)
1192     {
1193       DBusString full_msg;
1194
1195       if (!_dbus_string_init (&full_msg))
1196         goto out;
1197       if (!_dbus_string_append (&full_msg, context->log_prefix))
1198         goto oom_out;
1199       if (!_dbus_string_append_printf_valist (&full_msg, msg, args))
1200         goto oom_out;
1201
1202       _dbus_system_log (severity, "%s", _dbus_string_get_const_data (&full_msg));
1203     oom_out:
1204       _dbus_string_free (&full_msg);
1205     }
1206   else
1207     _dbus_system_logv (severity, msg, args);
1208
1209 out:
1210   va_end (args);
1211 }
1212
1213 /*
1214  * addressed_recipient is the recipient specified in the message.
1215  *
1216  * proposed_recipient is the recipient we're considering sending
1217  * to right this second, and may be an eavesdropper.
1218  *
1219  * sender is the sender of the message.
1220  *
1221  * NULL for proposed_recipient or sender definitely means the bus driver.
1222  *
1223  * NULL for addressed_recipient may mean the bus driver, or may mean
1224  * no destination was specified in the message (e.g. a signal).
1225  */
1226 dbus_bool_t
1227 bus_context_check_security_policy (BusContext     *context,
1228                                    BusTransaction *transaction,
1229                                    DBusConnection *sender,
1230                                    DBusConnection *addressed_recipient,
1231                                    DBusConnection *proposed_recipient,
1232                                    DBusMessage    *message,
1233                                    DBusError      *error)
1234 {
1235   const char *dest;
1236   BusClientPolicy *sender_policy;
1237   BusClientPolicy *recipient_policy;
1238   dbus_int32_t toggles;
1239   dbus_bool_t log;
1240   int type;
1241   dbus_bool_t requested_reply;
1242   const char *sender_name;
1243   const char *sender_loginfo;
1244   const char *proposed_recipient_loginfo;
1245   
1246   type = dbus_message_get_type (message);
1247   dest = dbus_message_get_destination (message);
1248   
1249   /* dispatch.c was supposed to ensure these invariants */
1250   _dbus_assert (dest != NULL ||
1251                 type == DBUS_MESSAGE_TYPE_SIGNAL ||
1252                 (sender == NULL && !bus_connection_is_active (proposed_recipient)));
1253   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
1254                 addressed_recipient != NULL ||
1255                 strcmp (dest, DBUS_SERVICE_DBUS) == 0);
1256
1257   /* Used in logging below */
1258   if (sender != NULL)
1259     {
1260       sender_name = bus_connection_get_name (sender);
1261       sender_loginfo = bus_connection_get_loginfo (sender);
1262     }
1263   else
1264     {
1265       sender_name = NULL;
1266       sender_loginfo = "(bus)";
1267     }
1268   
1269   if (proposed_recipient != NULL)
1270     proposed_recipient_loginfo = bus_connection_get_loginfo (proposed_recipient);
1271   else
1272     proposed_recipient_loginfo = "bus";
1273   
1274   switch (type)
1275     {
1276     case DBUS_MESSAGE_TYPE_METHOD_CALL:
1277     case DBUS_MESSAGE_TYPE_SIGNAL:
1278     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
1279     case DBUS_MESSAGE_TYPE_ERROR:
1280       break;
1281       
1282     default:
1283       _dbus_verbose ("security check disallowing message of unknown type %d\n",
1284                      type);
1285
1286       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1287                       "Message bus will not accept messages of unknown type\n");
1288               
1289       return FALSE;
1290     }
1291
1292   requested_reply = FALSE;
1293   
1294   if (sender != NULL)
1295     {
1296       /* First verify the SELinux access controls.  If allowed then
1297        * go on with the standard checks.
1298        */
1299       if (!bus_selinux_allows_send (sender, proposed_recipient,
1300                                     dbus_message_type_to_string (dbus_message_get_type (message)),
1301                                     dbus_message_get_interface (message),
1302                                     dbus_message_get_member (message),
1303                                     dbus_message_get_error_name (message),
1304                                     dest ? dest : DBUS_SERVICE_DBUS, error))
1305         {
1306           if (error != NULL && !dbus_error_is_set (error))
1307             {
1308               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1309                               "An SELinux policy prevents this sender "
1310                               "from sending this message to this recipient "
1311                               "(rejected message had sender \"%s\" interface \"%s\" "
1312                               "member \"%s\" error name \"%s\" destination \"%s\")",
1313                               sender_name ? sender_name : "(unset)",
1314                               dbus_message_get_interface (message) ?
1315                               dbus_message_get_interface (message) : "(unset)",
1316                               dbus_message_get_member (message) ?
1317                               dbus_message_get_member (message) : "(unset)",
1318                               dbus_message_get_error_name (message) ?
1319                               dbus_message_get_error_name (message) : "(unset)",
1320                               dest ? dest : DBUS_SERVICE_DBUS);
1321               _dbus_verbose ("SELinux security check denying send to service\n");
1322             }
1323
1324           return FALSE;
1325         }
1326        
1327       if (bus_connection_is_active (sender))
1328         {
1329           sender_policy = bus_connection_get_policy (sender);
1330           _dbus_assert (sender_policy != NULL);
1331           
1332           /* Fill in requested_reply variable with TRUE if this is a
1333            * reply and the reply was pending.
1334            */
1335           if (dbus_message_get_reply_serial (message) != 0)
1336             {
1337               if (proposed_recipient != NULL /* not to the bus driver */ &&
1338                   addressed_recipient == proposed_recipient /* not eavesdropping */)
1339                 {
1340                   DBusError error2;                  
1341                   
1342                   dbus_error_init (&error2);
1343                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
1344                                                                  transaction,
1345                                                                  sender, addressed_recipient, message,
1346                                                                  &error2);
1347                   if (dbus_error_is_set (&error2))
1348                     {
1349                       dbus_move_error (&error2, error);
1350                       return FALSE;
1351                     }
1352                 }
1353             }
1354         }
1355       else
1356         {
1357           /* Policy for inactive connections is that they can only send
1358            * the hello message to the bus driver
1359            */
1360           if (proposed_recipient == NULL &&
1361               dbus_message_is_method_call (message,
1362                                            DBUS_INTERFACE_DBUS,
1363                                            "Hello"))
1364             {
1365               _dbus_verbose ("security check allowing %s message\n",
1366                              "Hello");
1367               return TRUE;
1368             }
1369           else
1370             {
1371               _dbus_verbose ("security check disallowing non-%s message\n",
1372                              "Hello");
1373
1374               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1375                               "Client tried to send a message other than %s without being registered",
1376                               "Hello");
1377               
1378               return FALSE;
1379             }
1380         }
1381     }
1382   else
1383     {
1384       sender_policy = NULL;
1385
1386       /* If the sender is the bus driver, we assume any reply was a
1387        * requested reply as bus driver won't send bogus ones
1388        */
1389       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1390           dbus_message_get_reply_serial (message) != 0)
1391         requested_reply = TRUE;
1392     }
1393
1394   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1395                 (sender == NULL && sender_policy == NULL));
1396   
1397   if (proposed_recipient != NULL)
1398     {
1399       /* only the bus driver can send to an inactive recipient (as it
1400        * owns no services, so other apps can't address it). Inactive
1401        * recipients can receive any message.
1402        */
1403       if (bus_connection_is_active (proposed_recipient))
1404         {
1405           recipient_policy = bus_connection_get_policy (proposed_recipient);
1406           _dbus_assert (recipient_policy != NULL);
1407         }
1408       else if (sender == NULL)
1409         {
1410           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1411           recipient_policy = NULL;
1412         }
1413       else
1414         {
1415           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus\n");
1416           recipient_policy = NULL;
1417         }
1418     }
1419   else
1420     recipient_policy = NULL;
1421   
1422   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1423                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1424                 (proposed_recipient == NULL && recipient_policy == NULL));
1425   
1426   log = FALSE;
1427   if (sender_policy &&
1428       !bus_client_policy_check_can_send (sender_policy,
1429                                          context->registry,
1430                                          requested_reply,
1431                                          proposed_recipient,
1432                                          message, &toggles, &log))
1433     {
1434       const char *msg = "Rejected send message, %d matched rules; "
1435                         "type=\"%s\", sender=\"%s\" (%s) interface=\"%s\" member=\"%s\" error name=\"%s\" requested_reply=%d destination=\"%s\" (%s))";
1436
1437       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED, msg,
1438                       toggles,
1439                       dbus_message_type_to_string (dbus_message_get_type (message)),
1440                       sender_name ? sender_name : "(unset)",
1441                       sender_loginfo,
1442                       dbus_message_get_interface (message) ?
1443                       dbus_message_get_interface (message) : "(unset)",
1444                       dbus_message_get_member (message) ?
1445                       dbus_message_get_member (message) : "(unset)",
1446                       dbus_message_get_error_name (message) ?
1447                       dbus_message_get_error_name (message) : "(unset)",
1448                       requested_reply,
1449                       dest ? dest : DBUS_SERVICE_DBUS,
1450                       proposed_recipient_loginfo);
1451       /* Needs to be duplicated to avoid calling malloc and having to handle OOM */
1452       if (addressed_recipient == proposed_recipient)
1453         bus_context_log (context, DBUS_SYSTEM_LOG_SECURITY, msg,
1454                                   toggles,
1455                                   dbus_message_type_to_string (dbus_message_get_type (message)),
1456                                   sender_name ? sender_name : "(unset)",
1457                                   sender_loginfo,
1458                                   dbus_message_get_interface (message) ?
1459                                   dbus_message_get_interface (message) : "(unset)",
1460                                   dbus_message_get_member (message) ?
1461                                   dbus_message_get_member (message) : "(unset)",
1462                                   dbus_message_get_error_name (message) ?
1463                                   dbus_message_get_error_name (message) : "(unset)",
1464                                   requested_reply,
1465                                   dest ? dest : DBUS_SERVICE_DBUS,
1466                                   proposed_recipient_loginfo);
1467       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1468       return FALSE;
1469     }
1470
1471   if (log)
1472     bus_context_log (context, DBUS_SYSTEM_LOG_SECURITY,
1473                               "Would reject message, %d matched rules; "
1474                               "type=\"%s\", sender=\"%s\" (%s) interface=\"%s\" member=\"%s\" error name=\"%s\" requested_reply=%d destination=\"%s\" (%s))",
1475                               toggles,
1476                               dbus_message_type_to_string (dbus_message_get_type (message)),
1477                               sender_name ? sender_name : "(unset)",
1478                               sender_loginfo,
1479                               dbus_message_get_interface (message) ?
1480                               dbus_message_get_interface (message) : "(unset)",
1481                               dbus_message_get_member (message) ?
1482                               dbus_message_get_member (message) : "(unset)",
1483                               dbus_message_get_error_name (message) ?
1484                               dbus_message_get_error_name (message) : "(unset)",
1485                               requested_reply,                               
1486                               dest ? dest : DBUS_SERVICE_DBUS,
1487                               proposed_recipient_loginfo);
1488
1489   if (recipient_policy &&
1490       !bus_client_policy_check_can_receive (recipient_policy,
1491                                             context->registry,
1492                                             requested_reply,
1493                                             sender,
1494                                             addressed_recipient, proposed_recipient,
1495                                             message, &toggles))
1496     {
1497       const char *msg = "Rejected receive message, %d matched rules; "
1498                         "type=\"%s\" sender=\"%s\" (%s) interface=\"%s\" member=\"%s\" error name=\"%s\" reply serial=%u requested_reply=%d destination=\"%s\" (%s))";
1499
1500       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED, msg,
1501                       toggles,
1502                       dbus_message_type_to_string (dbus_message_get_type (message)),
1503                       sender_name ? sender_name : "(unset)",
1504                       sender_loginfo,
1505                       dbus_message_get_interface (message) ?
1506                       dbus_message_get_interface (message) : "(unset)",
1507                       dbus_message_get_member (message) ?
1508                       dbus_message_get_member (message) : "(unset)",
1509                       dbus_message_get_error_name (message) ?
1510                       dbus_message_get_error_name (message) : "(unset)",
1511                       dbus_message_get_reply_serial (message),
1512                       requested_reply,
1513                       dest ? dest : DBUS_SERVICE_DBUS,
1514                       proposed_recipient_loginfo);
1515       /* Needs to be duplicated to avoid calling malloc and having to handle OOM */
1516       if (addressed_recipient == proposed_recipient)
1517         bus_context_log (context, DBUS_SYSTEM_LOG_SECURITY, msg,
1518                                   toggles,
1519                                   dbus_message_type_to_string (dbus_message_get_type (message)),
1520                                   sender_name ? sender_name : "(unset)",
1521                                   sender_loginfo,
1522                                   dbus_message_get_interface (message) ?
1523                                   dbus_message_get_interface (message) : "(unset)",
1524                                   dbus_message_get_member (message) ?
1525                                   dbus_message_get_member (message) : "(unset)",
1526                                   dbus_message_get_error_name (message) ?
1527                                   dbus_message_get_error_name (message) : "(unset)",
1528                                   dbus_message_get_reply_serial (message),
1529                                   requested_reply,
1530                                   dest ? dest : DBUS_SERVICE_DBUS,
1531                                   proposed_recipient_loginfo);
1532       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1533       return FALSE;
1534     }
1535
1536   /* See if limits on size have been exceeded */
1537   if (proposed_recipient &&
1538       dbus_connection_get_outgoing_size (proposed_recipient) >
1539       context->limits.max_outgoing_bytes)
1540     {
1541       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1542                       "The destination service \"%s\" has a full message queue",
1543                       dest ? dest : (proposed_recipient ?
1544                                      bus_connection_get_name (proposed_recipient) : 
1545                                      DBUS_SERVICE_DBUS));
1546       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1547       return FALSE;
1548     }
1549
1550   /* Record that we will allow a reply here in the future (don't
1551    * bother if the recipient is the bus or this is an eavesdropping
1552    * connection). Only the addressed recipient may reply.
1553    */
1554   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL &&
1555       sender && 
1556       addressed_recipient &&
1557       addressed_recipient == proposed_recipient && /* not eavesdropping */
1558       !bus_connections_expect_reply (bus_connection_get_connections (sender),
1559                                      transaction,
1560                                      sender, addressed_recipient,
1561                                      message, error))
1562     {
1563       _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1564       return FALSE;
1565     }
1566   
1567   _dbus_verbose ("security policy allowing message\n");
1568   return TRUE;
1569 }