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