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