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