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