020ac546adfdcee946039fa072ce9682444a6288
[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                  int               print_addr_fd,
531                  int               print_pid_fd,
532                  DBusError        *error)
533 {
534   BusContext *context;
535   BusConfigParser *parser;
536   DBusCredentials creds;
537
538   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
539
540   context = NULL;
541   parser = NULL;
542
543   if (!dbus_server_allocate_data_slot (&server_data_slot))
544     {
545       BUS_SET_OOM (error);
546       return NULL;
547     }
548
549   context = dbus_new0 (BusContext, 1);
550   if (context == NULL)
551     {
552       BUS_SET_OOM (error);
553       goto failed;
554     }
555   context->refcount = 1;
556
557   if (!_dbus_string_copy_data (config_file, &context->config_file))
558     {
559       BUS_SET_OOM (error);
560       goto failed;
561     }
562
563   context->loop = _dbus_loop_new ();
564   if (context->loop == NULL)
565     {
566       BUS_SET_OOM (error);
567       goto failed;
568     }
569
570   context->registry = bus_registry_new (context);
571   if (context->registry == NULL)
572     {
573       BUS_SET_OOM (error);
574       goto failed;
575     }
576
577   parser = bus_config_load (config_file, TRUE, NULL, error);
578   if (parser == NULL)
579     {
580       _DBUS_ASSERT_ERROR_IS_SET (error);
581       goto failed;
582     }
583   
584   if (!process_config_first_time_only (context, parser, error))
585     {
586       _DBUS_ASSERT_ERROR_IS_SET (error);
587       goto failed;
588     }
589   if (!process_config_every_time (context, parser, FALSE, error))
590     {
591       _DBUS_ASSERT_ERROR_IS_SET (error);
592       goto failed;
593     }
594   
595   /* we need another ref of the server data slot for the context
596    * to own
597    */
598   if (!dbus_server_allocate_data_slot (&server_data_slot))
599     _dbus_assert_not_reached ("second ref of server data slot failed");
600
601   /* Note that we don't know whether the print_addr_fd is
602    * one of the sockets we're using to listen on, or some
603    * other random thing. But I think the answer is "don't do
604    * that then"
605    */
606   if (print_addr_fd >= 0)
607     {
608       DBusString addr;
609       const char *a = bus_context_get_address (context);
610       int bytes;
611       
612       _dbus_assert (a != NULL);
613       if (!_dbus_string_init (&addr))
614         {
615           BUS_SET_OOM (error);
616           goto failed;
617         }
618       
619       if (!_dbus_string_append (&addr, a) ||
620           !_dbus_string_append (&addr, "\n"))
621         {
622           _dbus_string_free (&addr);
623           BUS_SET_OOM (error);
624           goto failed;
625         }
626
627       bytes = _dbus_string_get_length (&addr);
628       if (_dbus_write_pipe (print_addr_fd, &addr, 0, bytes) != bytes)
629         {
630           dbus_set_error (error, DBUS_ERROR_FAILED,
631                           "Printing message bus address: %s\n",
632                           _dbus_strerror (errno));
633           _dbus_string_free (&addr);
634           goto failed;
635         }
636
637       if (print_addr_fd > 2)
638         _dbus_close_socket (print_addr_fd, NULL);
639
640       _dbus_string_free (&addr);
641     }
642   
643   context->connections = bus_connections_new (context);
644   if (context->connections == NULL)
645     {
646       BUS_SET_OOM (error);
647       goto failed;
648     }
649
650   context->matchmaker = bus_matchmaker_new ();
651   if (context->matchmaker == NULL)
652     {
653       BUS_SET_OOM (error);
654       goto failed;
655     }
656
657   /* check user before we fork */
658   if (context->user != NULL)
659     {
660       DBusString u;
661
662       _dbus_string_init_const (&u, context->user);
663
664       if (!_dbus_credentials_from_username (&u, &creds) ||
665           creds.uid < 0 ||
666           creds.gid < 0)
667         {
668           dbus_set_error (error, DBUS_ERROR_FAILED,
669                           "Could not get UID and GID for username \"%s\"",
670                           context->user);
671           goto failed;
672         }
673     }
674
675   /* Now become a daemon if appropriate */
676   if ((force_fork != FORK_NEVER && context->fork) || force_fork == FORK_ALWAYS)
677     {
678       DBusString u;
679
680       if (context->pidfile)
681         _dbus_string_init_const (&u, context->pidfile);
682       
683       if (!_dbus_become_daemon (context->pidfile ? &u : NULL, 
684                                 print_pid_fd,
685                                 error))
686         {
687           _DBUS_ASSERT_ERROR_IS_SET (error);
688           goto failed;
689         }
690     }
691   else
692     {
693       /* Need to write PID file for ourselves, not for the child process */
694       if (context->pidfile != NULL)
695         {
696           DBusString u;
697
698           _dbus_string_init_const (&u, context->pidfile);
699           
700           if (!_dbus_write_pid_file (&u, _dbus_getpid (), error))
701             {
702               _DBUS_ASSERT_ERROR_IS_SET (error);
703               goto failed;
704             }
705         }
706     }
707
708   /* Write PID if requested */
709   if (print_pid_fd >= 0)
710     {
711       DBusString pid;
712       int bytes;
713
714       if (!_dbus_string_init (&pid))
715         {
716           BUS_SET_OOM (error);
717           goto failed;
718         }
719       
720       if (!_dbus_string_append_int (&pid, _dbus_getpid ()) ||
721           !_dbus_string_append (&pid, "\n"))
722         {
723           _dbus_string_free (&pid);
724           BUS_SET_OOM (error);
725           goto failed;
726         }
727
728       bytes = _dbus_string_get_length (&pid);
729       if (_dbus_write_pipe (print_pid_fd, &pid, 0, bytes) != bytes)
730         {
731           dbus_set_error (error, DBUS_ERROR_FAILED,
732                           "Printing message bus PID: %s\n",
733                           _dbus_strerror (errno));
734           _dbus_string_free (&pid);
735           goto failed;
736         }
737
738       if (print_pid_fd > 2)
739         _dbus_close_socket (print_pid_fd, NULL);
740       
741       _dbus_string_free (&pid);
742     }
743
744   if (!bus_selinux_full_init ())
745     {
746       _dbus_warn ("SELinux initialization failed\n");
747     }
748
749   if (!process_config_postinit (context, parser, error))
750     {
751       _DBUS_ASSERT_ERROR_IS_SET (error);
752       goto failed;
753     }
754
755   if (parser != NULL)
756     {
757       bus_config_parser_unref (parser);
758       parser = NULL;
759     }
760   
761   /* Here we change our credentials if required,
762    * as soon as we've set up our sockets and pidfile
763    */
764   if (context->user != NULL)
765     {
766       if (!_dbus_change_identity (creds.uid, creds.gid, error))
767         {
768           _DBUS_ASSERT_ERROR_IS_SET (error);
769           goto failed;
770         }
771     }
772   
773   dbus_server_free_data_slot (&server_data_slot);
774   
775   return context;
776   
777  failed:  
778   if (parser != NULL)
779     bus_config_parser_unref (parser);
780   if (context != NULL)
781     bus_context_unref (context);
782
783   if (server_data_slot >= 0)
784     dbus_server_free_data_slot (&server_data_slot);
785   
786   return NULL;
787 }
788
789 dbus_bool_t
790 bus_context_reload_config (BusContext *context,
791                            DBusError  *error)
792 {
793   BusConfigParser *parser;
794   DBusString config_file;
795   dbus_bool_t ret;
796
797   /* Flush the user database cache */
798   _dbus_user_database_flush_system ();
799
800   ret = FALSE;
801   _dbus_string_init_const (&config_file, context->config_file);
802   parser = bus_config_load (&config_file, TRUE, NULL, error);
803   if (parser == NULL)
804     {
805       _DBUS_ASSERT_ERROR_IS_SET (error);
806       goto failed;
807     }
808   
809   if (!process_config_every_time (context, parser, TRUE, error))
810     {
811       _DBUS_ASSERT_ERROR_IS_SET (error);
812       goto failed;
813     }
814   if (!process_config_postinit (context, parser, error))
815     {
816       _DBUS_ASSERT_ERROR_IS_SET (error);
817       goto failed;
818     }
819   ret = TRUE;
820
821  failed:  
822   if (parser != NULL)
823     bus_config_parser_unref (parser);
824   return ret;
825 }
826
827 static void
828 shutdown_server (BusContext *context,
829                  DBusServer *server)
830 {
831   if (server == NULL ||
832       !dbus_server_get_is_connected (server))
833     return;
834   
835   if (!dbus_server_set_watch_functions (server,
836                                         NULL, NULL, NULL,
837                                         context,
838                                         NULL))
839     _dbus_assert_not_reached ("setting watch functions to NULL failed");
840   
841   if (!dbus_server_set_timeout_functions (server,
842                                           NULL, NULL, NULL,
843                                           context,
844                                           NULL))
845     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
846   
847   dbus_server_disconnect (server);
848 }
849
850 void
851 bus_context_shutdown (BusContext  *context)
852 {
853   DBusList *link;
854
855   link = _dbus_list_get_first_link (&context->servers);
856   while (link != NULL)
857     {
858       shutdown_server (context, link->data);
859
860       link = _dbus_list_get_next_link (&context->servers, link);
861     }
862 }
863
864 BusContext *
865 bus_context_ref (BusContext *context)
866 {
867   _dbus_assert (context->refcount > 0);
868   context->refcount += 1;
869
870   return context;
871 }
872
873 void
874 bus_context_unref (BusContext *context)
875 {
876   _dbus_assert (context->refcount > 0);
877   context->refcount -= 1;
878
879   if (context->refcount == 0)
880     {
881       DBusList *link;
882       
883       _dbus_verbose ("Finalizing bus context %p\n", context);
884       
885       bus_context_shutdown (context);
886
887       if (context->connections)
888         {
889           bus_connections_unref (context->connections);
890           context->connections = NULL;
891         }
892       
893       if (context->registry)
894         {
895           bus_registry_unref (context->registry);
896           context->registry = NULL;
897         }
898       
899       if (context->activation)
900         {
901           bus_activation_unref (context->activation);
902           context->activation = NULL;
903         }
904
905       link = _dbus_list_get_first_link (&context->servers);
906       while (link != NULL)
907         {
908           dbus_server_unref (link->data);
909           
910           link = _dbus_list_get_next_link (&context->servers, link);
911         }
912       _dbus_list_clear (&context->servers);
913
914       if (context->policy)
915         {
916           bus_policy_unref (context->policy);
917           context->policy = NULL;
918         }
919       
920       if (context->loop)
921         {
922           _dbus_loop_unref (context->loop);
923           context->loop = NULL;
924         }
925
926       if (context->matchmaker)
927         {
928           bus_matchmaker_unref (context->matchmaker);
929           context->matchmaker = NULL;
930         }
931       
932       dbus_free (context->config_file);
933       dbus_free (context->type);
934       dbus_free (context->address);
935       dbus_free (context->user);
936
937       if (context->pidfile)
938         {
939           DBusString u;
940           _dbus_string_init_const (&u, context->pidfile);
941
942           /* Deliberately ignore errors here, since there's not much
943            * we can do about it, and we're exiting anyways.
944            */
945           _dbus_delete_file (&u, NULL);
946
947           dbus_free (context->pidfile); 
948         }
949       dbus_free (context);
950
951       dbus_server_free_data_slot (&server_data_slot);
952     }
953 }
954
955 /* type may be NULL */
956 const char*
957 bus_context_get_type (BusContext *context)
958 {
959   return context->type;
960 }
961
962 const char*
963 bus_context_get_address (BusContext *context)
964 {
965   return context->address;
966 }
967
968 BusRegistry*
969 bus_context_get_registry (BusContext  *context)
970 {
971   return context->registry;
972 }
973
974 BusConnections*
975 bus_context_get_connections (BusContext  *context)
976 {
977   return context->connections;
978 }
979
980 BusActivation*
981 bus_context_get_activation (BusContext  *context)
982 {
983   return context->activation;
984 }
985
986 BusMatchmaker*
987 bus_context_get_matchmaker (BusContext  *context)
988 {
989   return context->matchmaker;
990 }
991
992 DBusLoop*
993 bus_context_get_loop (BusContext *context)
994 {
995   return context->loop;
996 }
997
998 dbus_bool_t
999 bus_context_allow_user (BusContext   *context,
1000                         unsigned long uid)
1001 {
1002   return bus_policy_allow_user (context->policy,
1003                                 uid);
1004 }
1005
1006 BusPolicy *
1007 bus_context_get_policy (BusContext *context)
1008 {
1009   return context->policy;
1010 }
1011
1012 BusClientPolicy*
1013 bus_context_create_client_policy (BusContext      *context,
1014                                   DBusConnection  *connection,
1015                                   DBusError       *error)
1016 {
1017   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1018   return bus_policy_create_client_policy (context->policy, connection,
1019                                           error);
1020 }
1021
1022 int
1023 bus_context_get_activation_timeout (BusContext *context)
1024 {
1025   
1026   return context->limits.activation_timeout;
1027 }
1028
1029 int
1030 bus_context_get_auth_timeout (BusContext *context)
1031 {
1032   return context->limits.auth_timeout;
1033 }
1034
1035 int
1036 bus_context_get_max_completed_connections (BusContext *context)
1037 {
1038   return context->limits.max_completed_connections;
1039 }
1040
1041 int
1042 bus_context_get_max_incomplete_connections (BusContext *context)
1043 {
1044   return context->limits.max_incomplete_connections;
1045 }
1046
1047 int
1048 bus_context_get_max_connections_per_user (BusContext *context)
1049 {
1050   return context->limits.max_connections_per_user;
1051 }
1052
1053 int
1054 bus_context_get_max_pending_activations (BusContext *context)
1055 {
1056   return context->limits.max_pending_activations;
1057 }
1058
1059 int
1060 bus_context_get_max_services_per_connection (BusContext *context)
1061 {
1062   return context->limits.max_services_per_connection;
1063 }
1064
1065 int
1066 bus_context_get_max_match_rules_per_connection (BusContext *context)
1067 {
1068   return context->limits.max_match_rules_per_connection;
1069 }
1070
1071 int
1072 bus_context_get_max_replies_per_connection (BusContext *context)
1073 {
1074   return context->limits.max_replies_per_connection;
1075 }
1076
1077 int
1078 bus_context_get_reply_timeout (BusContext *context)
1079 {
1080   return context->limits.reply_timeout;
1081 }
1082
1083 /*
1084  * addressed_recipient is the recipient specified in the message.
1085  *
1086  * proposed_recipient is the recipient we're considering sending
1087  * to right this second, and may be an eavesdropper.
1088  *
1089  * sender is the sender of the message.
1090  *
1091  * NULL for proposed_recipient or sender definitely means the bus driver.
1092  *
1093  * NULL for addressed_recipient may mean the bus driver, or may mean
1094  * no destination was specified in the message (e.g. a signal).
1095  */
1096 dbus_bool_t
1097 bus_context_check_security_policy (BusContext     *context,
1098                                    BusTransaction *transaction,
1099                                    DBusConnection *sender,
1100                                    DBusConnection *addressed_recipient,
1101                                    DBusConnection *proposed_recipient,
1102                                    DBusMessage    *message,
1103                                    DBusError      *error)
1104 {
1105   BusClientPolicy *sender_policy;
1106   BusClientPolicy *recipient_policy;
1107   int type;
1108   dbus_bool_t requested_reply;
1109   
1110   type = dbus_message_get_type (message);
1111   
1112   /* dispatch.c was supposed to ensure these invariants */
1113   _dbus_assert (dbus_message_get_destination (message) != NULL ||
1114                 type == DBUS_MESSAGE_TYPE_SIGNAL ||
1115                 (sender == NULL && !bus_connection_is_active (proposed_recipient)));
1116   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
1117                 addressed_recipient != NULL ||
1118                 strcmp (dbus_message_get_destination (message), DBUS_SERVICE_DBUS) == 0);
1119   
1120   switch (type)
1121     {
1122     case DBUS_MESSAGE_TYPE_METHOD_CALL:
1123     case DBUS_MESSAGE_TYPE_SIGNAL:
1124     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
1125     case DBUS_MESSAGE_TYPE_ERROR:
1126       break;
1127       
1128     default:
1129       _dbus_verbose ("security check disallowing message of unknown type %d\n",
1130                      type);
1131
1132       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1133                       "Message bus will not accept messages of unknown type\n");
1134               
1135       return FALSE;
1136     }
1137
1138   requested_reply = FALSE;
1139   
1140   if (sender != NULL)
1141     {
1142       const char *dest;
1143
1144       dest = dbus_message_get_destination (message);
1145         
1146       /* First verify the SELinux access controls.  If allowed then
1147        * go on with the standard checks.
1148        */
1149       if (!bus_selinux_allows_send (sender, proposed_recipient,
1150                                     dbus_message_type_to_string (dbus_message_get_type (message)),
1151                                     dbus_message_get_interface (message),
1152                                     dbus_message_get_member (message),
1153                                     dbus_message_get_error_name (message),
1154                                     dest ? dest : DBUS_SERVICE_DBUS, error))
1155         {
1156
1157           if (dbus_error_is_set (error) &&
1158               dbus_error_has_name (error, DBUS_ERROR_NO_MEMORY))
1159             {
1160               return FALSE;
1161             }
1162           
1163
1164           dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1165                           "An SELinux policy prevents this sender "
1166                           "from sending this message to this recipient "
1167                           "(rejected message had interface \"%s\" "
1168                           "member \"%s\" error name \"%s\" destination \"%s\")",
1169                           dbus_message_get_interface (message) ?
1170                           dbus_message_get_interface (message) : "(unset)",
1171                           dbus_message_get_member (message) ?
1172                           dbus_message_get_member (message) : "(unset)",
1173                           dbus_message_get_error_name (message) ?
1174                           dbus_message_get_error_name (message) : "(unset)",
1175                           dest ? dest : DBUS_SERVICE_DBUS);
1176           _dbus_verbose ("SELinux security check denying send to service\n");
1177           return FALSE;
1178         }
1179        
1180       if (bus_connection_is_active (sender))
1181         {
1182           sender_policy = bus_connection_get_policy (sender);
1183           _dbus_assert (sender_policy != NULL);
1184           
1185           /* Fill in requested_reply variable with TRUE if this is a
1186            * reply and the reply was pending.
1187            */
1188           if (dbus_message_get_reply_serial (message) != 0)
1189             {
1190               if (proposed_recipient != NULL /* not to the bus driver */ &&
1191                   addressed_recipient == proposed_recipient /* not eavesdropping */)
1192                 {
1193                   DBusError error2;                  
1194                   
1195                   dbus_error_init (&error2);
1196                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
1197                                                                  transaction,
1198                                                                  sender, addressed_recipient, message,
1199                                                                  &error2);
1200                   if (dbus_error_is_set (&error2))
1201                     {
1202                       dbus_move_error (&error2, error);
1203                       return FALSE;
1204                     }
1205                 }
1206             }
1207         }
1208       else
1209         {
1210           /* Policy for inactive connections is that they can only send
1211            * the hello message to the bus driver
1212            */
1213           if (proposed_recipient == NULL &&
1214               dbus_message_is_method_call (message,
1215                                            DBUS_INTERFACE_DBUS,
1216                                            "Hello"))
1217             {
1218               _dbus_verbose ("security check allowing %s message\n",
1219                              "Hello");
1220               return TRUE;
1221             }
1222           else
1223             {
1224               _dbus_verbose ("security check disallowing non-%s message\n",
1225                              "Hello");
1226
1227               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1228                               "Client tried to send a message other than %s without being registered",
1229                               "Hello");
1230               
1231               return FALSE;
1232             }
1233         }
1234     }
1235   else
1236     {
1237       sender_policy = NULL;
1238
1239       /* If the sender is the bus driver, we assume any reply was a
1240        * requested reply as bus driver won't send bogus ones
1241        */
1242       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1243           dbus_message_get_reply_serial (message) != 0)
1244         requested_reply = TRUE;
1245     }
1246
1247   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1248                 (sender == NULL && sender_policy == NULL));
1249   
1250   if (proposed_recipient != NULL)
1251     {
1252       /* only the bus driver can send to an inactive recipient (as it
1253        * owns no services, so other apps can't address it). Inactive
1254        * recipients can receive any message.
1255        */
1256       if (bus_connection_is_active (proposed_recipient))
1257         {
1258           recipient_policy = bus_connection_get_policy (proposed_recipient);
1259           _dbus_assert (recipient_policy != NULL);
1260         }
1261       else if (sender == NULL)
1262         {
1263           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1264           recipient_policy = NULL;
1265         }
1266       else
1267         {
1268           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus\n");
1269           recipient_policy = NULL;
1270         }
1271     }
1272   else
1273     recipient_policy = NULL;
1274   
1275   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1276                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1277                 (proposed_recipient == NULL && recipient_policy == NULL));
1278   
1279   if (sender_policy &&
1280       !bus_client_policy_check_can_send (sender_policy,
1281                                          context->registry,
1282                                          requested_reply,
1283                                          proposed_recipient,
1284                                          message))
1285     {
1286       const char *dest;
1287
1288       dest = dbus_message_get_destination (message);
1289       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1290                       "A security policy in place prevents this sender "
1291                       "from sending this message to this recipient, "
1292                       "see message bus configuration file (rejected message "
1293                       "had interface \"%s\" member \"%s\" error name \"%s\" destination \"%s\")",
1294                       dbus_message_get_interface (message) ?
1295                       dbus_message_get_interface (message) : "(unset)",
1296                       dbus_message_get_member (message) ?
1297                       dbus_message_get_member (message) : "(unset)",
1298                       dbus_message_get_error_name (message) ?
1299                       dbus_message_get_error_name (message) : "(unset)",
1300                       dest ? dest : DBUS_SERVICE_DBUS);
1301       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1302       return FALSE;
1303     }
1304
1305   if (recipient_policy &&
1306       !bus_client_policy_check_can_receive (recipient_policy,
1307                                             context->registry,
1308                                             requested_reply,
1309                                             sender,
1310                                             addressed_recipient, proposed_recipient,
1311                                             message))
1312     {
1313       const char *dest;
1314
1315       dest = dbus_message_get_destination (message);
1316       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1317                       "A security policy in place prevents this recipient "
1318                       "from receiving this message from this sender, "
1319                       "see message bus configuration file (rejected message "
1320                       "had interface \"%s\" member \"%s\" error name \"%s\" destination \"%s\" reply serial %u requested_reply=%d)",
1321                       dbus_message_get_interface (message) ?
1322                       dbus_message_get_interface (message) : "(unset)",
1323                       dbus_message_get_member (message) ?
1324                       dbus_message_get_member (message) : "(unset)",
1325                       dbus_message_get_error_name (message) ?
1326                       dbus_message_get_error_name (message) : "(unset)",
1327                       dest ? dest : DBUS_SERVICE_DBUS,
1328                       dbus_message_get_reply_serial (message),
1329                       requested_reply);
1330       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1331       return FALSE;
1332     }
1333
1334   /* See if limits on size have been exceeded */
1335   if (proposed_recipient &&
1336       dbus_connection_get_outgoing_size (proposed_recipient) >
1337       context->limits.max_outgoing_bytes)
1338     {
1339       const char *dest;
1340
1341       dest = dbus_message_get_destination (message);
1342       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1343                       "The destination service \"%s\" has a full message queue",
1344                       dest ? dest : (proposed_recipient ?
1345                                      bus_connection_get_name (proposed_recipient) : 
1346                                      DBUS_SERVICE_DBUS));
1347       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1348       return FALSE;
1349     }
1350
1351   /* Record that we will allow a reply here in the future (don't
1352    * bother if the recipient is the bus or this is an eavesdropping
1353    * connection). Only the addressed recipient may reply.
1354    */
1355   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL &&
1356       sender && 
1357       addressed_recipient &&
1358       addressed_recipient == proposed_recipient && /* not eavesdropping */
1359       !bus_connections_expect_reply (bus_connection_get_connections (sender),
1360                                      transaction,
1361                                      sender, addressed_recipient,
1362                                      message, error))
1363     {
1364       _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1365       return FALSE;
1366     }
1367   
1368   _dbus_verbose ("security policy allowing message\n");
1369   return TRUE;
1370 }