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