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