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