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