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