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