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