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