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