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