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