Merge branch 'dbus-1.10'
[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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include <config.h>
25 #include "bus.h"
26
27 #include <stdio.h>
28
29 #include "activation.h"
30 #include "connection.h"
31 #include "services.h"
32 #include "utils.h"
33 #include "policy.h"
34 #include "config-parser.h"
35 #include "signals.h"
36 #include "selinux.h"
37 #include "apparmor.h"
38 #include "audit.h"
39 #include "dir-watch.h"
40 #include <dbus/dbus-list.h>
41 #include <dbus/dbus-hash.h>
42 #include <dbus/dbus-credentials.h>
43 #include <dbus/dbus-internals.h>
44 #include <dbus/dbus-server-protected.h>
45
46 #ifdef DBUS_CYGWIN
47 #include <signal.h>
48 #endif
49
50 struct BusContext
51 {
52   int refcount;
53   DBusGUID uuid;
54   char *config_file;
55   char *type;
56   char *servicehelper;
57   char *address;
58   char *pidfile;
59   char *user;
60   char *log_prefix;
61   DBusLoop *loop;
62   DBusList *servers;
63   BusConnections *connections;
64   BusActivation *activation;
65   BusRegistry *registry;
66   BusPolicy *policy;
67   BusMatchmaker *matchmaker;
68   BusLimits limits;
69   DBusRLimit *initial_fd_limit;
70   unsigned int fork : 1;
71   unsigned int syslog : 1;
72   unsigned int keep_umask : 1;
73   unsigned int allow_anonymous : 1;
74   unsigned int systemd_activation : 1;
75   dbus_bool_t watches_enabled;
76 };
77
78 static dbus_int32_t server_data_slot = -1;
79
80 typedef struct
81 {
82   BusContext *context;
83 } BusServerData;
84
85 #define BUS_SERVER_DATA(server) (dbus_server_get_data ((server), server_data_slot))
86
87 static BusContext*
88 server_get_context (DBusServer *server)
89 {
90   BusContext *context;
91   BusServerData *bd;
92
93   /* this data slot was allocated by the BusContext */
94   _dbus_assert (server_data_slot >= 0);
95
96   bd = BUS_SERVER_DATA (server);
97
98   /* every DBusServer in the dbus-daemon has gone through setup_server() */
99   _dbus_assert (bd != NULL);
100
101   context = bd->context;
102
103   return context;
104 }
105
106 static dbus_bool_t
107 add_server_watch (DBusWatch  *watch,
108                   void       *data)
109 {
110   DBusServer *server = data;
111   BusContext *context;
112
113   context = server_get_context (server);
114
115   return _dbus_loop_add_watch (context->loop, watch);
116 }
117
118 static void
119 remove_server_watch (DBusWatch  *watch,
120                      void       *data)
121 {
122   DBusServer *server = data;
123   BusContext *context;
124
125   context = server_get_context (server);
126
127   _dbus_loop_remove_watch (context->loop, watch);
128 }
129
130 static void
131 toggle_server_watch (DBusWatch  *watch,
132                      void       *data)
133 {
134   DBusServer *server = data;
135   BusContext *context;
136
137   context = server_get_context (server);
138
139   _dbus_loop_toggle_watch (context->loop, watch);
140 }
141
142 static dbus_bool_t
143 add_server_timeout (DBusTimeout *timeout,
144                     void        *data)
145 {
146   DBusServer *server = data;
147   BusContext *context;
148
149   context = server_get_context (server);
150
151   return _dbus_loop_add_timeout (context->loop, timeout);
152 }
153
154 static void
155 remove_server_timeout (DBusTimeout *timeout,
156                        void        *data)
157 {
158   DBusServer *server = data;
159   BusContext *context;
160
161   context = server_get_context (server);
162
163   _dbus_loop_remove_timeout (context->loop, timeout);
164 }
165
166 static void
167 new_connection_callback (DBusServer     *server,
168                          DBusConnection *new_connection,
169                          void           *data)
170 {
171   BusContext *context = data;
172
173   if (!bus_connections_setup_connection (context->connections, new_connection))
174     {
175       _dbus_verbose ("No memory to setup new connection\n");
176
177       /* if we don't do this, it will get unref'd without
178        * being disconnected... kind of strange really
179        * that we have to do this, people won't get it right
180        * in general.
181        */
182       dbus_connection_close (new_connection);
183     }
184
185   dbus_connection_set_max_received_size (new_connection,
186                                          context->limits.max_incoming_bytes);
187
188   dbus_connection_set_max_message_size (new_connection,
189                                         context->limits.max_message_size);
190
191   dbus_connection_set_max_received_unix_fds (new_connection,
192                                          context->limits.max_incoming_unix_fds);
193
194   dbus_connection_set_max_message_unix_fds (new_connection,
195                                         context->limits.max_message_unix_fds);
196
197   dbus_connection_set_allow_anonymous (new_connection,
198                                        context->allow_anonymous);
199
200   /* on OOM, we won't have ref'd the connection so it will die. */
201 }
202
203 static void
204 free_server_data (void *data)
205 {
206   BusServerData *bd = data;
207
208   dbus_free (bd);
209 }
210
211 static dbus_bool_t
212 setup_server (BusContext *context,
213               DBusServer *server,
214               char      **auth_mechanisms,
215               DBusError  *error)
216 {
217   BusServerData *bd;
218
219   bd = dbus_new0 (BusServerData, 1);
220   if (bd == NULL || !dbus_server_set_data (server,
221                                            server_data_slot,
222                                            bd, free_server_data))
223     {
224       dbus_free (bd);
225       BUS_SET_OOM (error);
226       return FALSE;
227     }
228
229   bd->context = context;
230
231   if (!dbus_server_set_auth_mechanisms (server, (const char**) auth_mechanisms))
232     {
233       BUS_SET_OOM (error);
234       return FALSE;
235     }
236
237   dbus_server_set_new_connection_function (server,
238                                            new_connection_callback,
239                                            context, NULL);
240
241   if (!dbus_server_set_watch_functions (server,
242                                         add_server_watch,
243                                         remove_server_watch,
244                                         toggle_server_watch,
245                                         server,
246                                         NULL))
247     {
248       BUS_SET_OOM (error);
249       return FALSE;
250     }
251
252   if (!dbus_server_set_timeout_functions (server,
253                                           add_server_timeout,
254                                           remove_server_timeout,
255                                           NULL,
256                                           server, NULL))
257     {
258       BUS_SET_OOM (error);
259       return FALSE;
260     }
261
262   return TRUE;
263 }
264
265 /* This code only gets executed the first time the
266  * config files are parsed.  It is not executed
267  * when config files are reloaded.
268  */
269 static dbus_bool_t
270 process_config_first_time_only (BusContext       *context,
271                                 BusConfigParser  *parser,
272                                 const DBusString *address,
273                                 BusContextFlags   flags,
274                                 DBusError        *error)
275 {
276   DBusString log_prefix;
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   DBusLogFlags log_flags = DBUS_LOG_FLAGS_STDERR;
285
286   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
287
288   retval = FALSE;
289   auth_mechanisms = NULL;
290   pidfile = NULL;
291
292   if (flags & BUS_CONTEXT_FLAG_SYSLOG_ALWAYS)
293     {
294       context->syslog = TRUE;
295       log_flags |= DBUS_LOG_FLAGS_SYSTEM_LOG;
296
297       if (flags & BUS_CONTEXT_FLAG_SYSLOG_ONLY)
298         log_flags &= ~DBUS_LOG_FLAGS_STDERR;
299     }
300   else if (flags & BUS_CONTEXT_FLAG_SYSLOG_NEVER)
301     {
302       context->syslog = FALSE;
303     }
304   else
305     {
306       context->syslog = bus_config_parser_get_syslog (parser);
307
308       if (context->syslog)
309         log_flags |= DBUS_LOG_FLAGS_SYSTEM_LOG;
310     }
311
312   _dbus_init_system_log ("dbus-daemon", log_flags);
313
314   if (flags & BUS_CONTEXT_FLAG_SYSTEMD_ACTIVATION)
315     context->systemd_activation = TRUE;
316   else
317     context->systemd_activation = FALSE;
318
319   /* Check for an existing pid file. Of course this is a race;
320    * we'd have to use fcntl() locks on the pid file to
321    * avoid that. But we want to check for the pid file
322    * before overwriting any existing sockets, etc.
323    */
324
325   if (flags & BUS_CONTEXT_FLAG_WRITE_PID_FILE)
326     pidfile = bus_config_parser_get_pidfile (parser);
327
328   if (pidfile != NULL)
329     {
330       DBusString u;
331       DBusStat stbuf;
332
333       _dbus_string_init_const (&u, pidfile);
334
335       if (_dbus_stat (&u, &stbuf, NULL))
336         {
337 #ifdef DBUS_CYGWIN
338           DBusString p;
339           long /* int */ pid;
340
341           _dbus_string_init (&p);
342           _dbus_file_get_contents(&p, &u, NULL);
343           _dbus_string_parse_int(&p, 0, &pid, NULL);
344           _dbus_string_free(&p);
345
346           if ((kill((int)pid, 0))) {
347             dbus_set_error(NULL, DBUS_ERROR_FILE_EXISTS,
348                            "pid %ld not running, removing stale pid file\n",
349                            pid);
350             _dbus_delete_file(&u, NULL);
351           } else {
352 #endif
353           dbus_set_error (error, DBUS_ERROR_FAILED,
354                                   "The pid file \"%s\" exists, if the message bus is not running, remove this file",
355                           pidfile);
356               goto failed;
357 #ifdef DBUS_CYGWIN
358           }
359 #endif
360         }
361     }
362
363   /* keep around the pid filename so we can delete it later */
364   context->pidfile = _dbus_strdup (pidfile);
365
366   /* note that type may be NULL */
367   context->type = _dbus_strdup (bus_config_parser_get_type (parser));
368   if (bus_config_parser_get_type (parser) != NULL && context->type == NULL)
369     goto oom;
370
371   user = bus_config_parser_get_user (parser);
372   if (user != NULL)
373     {
374       context->user = _dbus_strdup (user);
375       if (context->user == NULL)
376         goto oom;
377     }
378
379   /* Set up the prefix for syslog messages */
380   if (!_dbus_string_init (&log_prefix))
381     goto oom;
382   if (context->type && !strcmp (context->type, "system"))
383     {
384       if (!_dbus_string_append (&log_prefix, "[system] "))
385         goto oom;
386     }
387   else if (context->type && !strcmp (context->type, "session"))
388     {
389       DBusCredentials *credentials;
390
391       credentials = _dbus_credentials_new_from_current_process ();
392       if (!credentials)
393         goto oom;
394       if (!_dbus_string_append (&log_prefix, "[session "))
395         {
396           _dbus_credentials_unref (credentials);
397           goto oom;
398         }
399       if (!_dbus_credentials_to_string_append (credentials, &log_prefix))
400         {
401           _dbus_credentials_unref (credentials);
402           goto oom;
403         }
404       if (!_dbus_string_append (&log_prefix, "] "))
405         {
406           _dbus_credentials_unref (credentials);
407           goto oom;
408         }
409       _dbus_credentials_unref (credentials);
410     }
411   if (!_dbus_string_steal_data (&log_prefix, &context->log_prefix))
412     goto oom;
413   _dbus_string_free (&log_prefix);
414
415   /* Build an array of auth mechanisms */
416
417   auth_mechanisms_list = bus_config_parser_get_mechanisms (parser);
418   len = _dbus_list_get_length (auth_mechanisms_list);
419
420   if (len > 0)
421     {
422       int i;
423
424       auth_mechanisms = dbus_new0 (char*, len + 1);
425       if (auth_mechanisms == NULL)
426         goto oom;
427
428       i = 0;
429       link = _dbus_list_get_first_link (auth_mechanisms_list);
430       while (link != NULL)
431         {
432           auth_mechanisms[i] = _dbus_strdup (link->data);
433           if (auth_mechanisms[i] == NULL)
434             goto oom;
435           link = _dbus_list_get_next_link (auth_mechanisms_list, link);
436           i += 1;
437         }
438     }
439   else
440     {
441       auth_mechanisms = NULL;
442     }
443
444   /* Listen on our addresses */
445
446   if (address)
447     {
448       DBusServer *server;
449
450       server = dbus_server_listen (_dbus_string_get_const_data(address), error);
451       if (server == NULL)
452         {
453           _DBUS_ASSERT_ERROR_IS_SET (error);
454           goto failed;
455         }
456       else if (!setup_server (context, server, auth_mechanisms, error))
457         {
458           _DBUS_ASSERT_ERROR_IS_SET (error);
459           goto failed;
460         }
461
462       if (!_dbus_list_append (&context->servers, server))
463         goto oom;
464     }
465   else
466     {
467       addresses = bus_config_parser_get_addresses (parser);
468
469       link = _dbus_list_get_first_link (addresses);
470       while (link != NULL)
471         {
472           DBusServer *server;
473
474           server = dbus_server_listen (link->data, error);
475           if (server == NULL)
476             {
477               _DBUS_ASSERT_ERROR_IS_SET (error);
478               goto failed;
479             }
480           else if (!setup_server (context, server, auth_mechanisms, error))
481             {
482               _DBUS_ASSERT_ERROR_IS_SET (error);
483               goto failed;
484             }
485
486           if (!_dbus_list_append (&context->servers, server))
487             goto oom;
488
489           link = _dbus_list_get_next_link (addresses, link);
490         }
491     }
492
493   context->fork = bus_config_parser_get_fork (parser);
494   context->keep_umask = bus_config_parser_get_keep_umask (parser);
495   context->allow_anonymous = bus_config_parser_get_allow_anonymous (parser);
496
497   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
498   retval = TRUE;
499
500  failed:
501   dbus_free_string_array (auth_mechanisms);
502   return retval;
503
504  oom:
505   BUS_SET_OOM (error);
506   dbus_free_string_array (auth_mechanisms);
507   return FALSE;
508 }
509
510 /* This code gets executed every time the config files
511  * are parsed: both during BusContext construction
512  * and on reloads. This function is slightly screwy
513  * since it can do a "half reload" in out-of-memory
514  * situations. Realistically, unlikely to ever matter.
515  */
516 static dbus_bool_t
517 process_config_every_time (BusContext      *context,
518                            BusConfigParser *parser,
519                            dbus_bool_t      is_reload,
520                            DBusError       *error)
521 {
522   DBusString full_address;
523   DBusList *link;
524   DBusList **dirs;
525   char *addr;
526   const char *servicehelper;
527   char *s;
528
529   dbus_bool_t retval;
530
531   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
532
533   addr = NULL;
534   retval = FALSE;
535
536   if (!_dbus_string_init (&full_address))
537     {
538       BUS_SET_OOM (error);
539       return FALSE;
540     }
541
542   /* get our limits and timeout lengths */
543   bus_config_parser_get_limits (parser, &context->limits);
544
545   if (context->policy)
546     bus_policy_unref (context->policy);
547   context->policy = bus_config_parser_steal_policy (parser);
548   _dbus_assert (context->policy != NULL);
549
550   /* context->connections is NULL when creating new BusContext */
551   if (context->connections)
552     {
553       _dbus_verbose ("Reload policy rules for completed connections\n");
554       retval = bus_connections_reload_policy (context->connections, error);
555       if (!retval)
556         {
557           _DBUS_ASSERT_ERROR_IS_SET (error);
558           goto failed;
559         }
560     }
561
562   /* We have to build the address backward, so that
563    * <listen> later in the config file have priority
564    */
565   link = _dbus_list_get_last_link (&context->servers);
566   while (link != NULL)
567     {
568       addr = dbus_server_get_address (link->data);
569       if (addr == NULL)
570         {
571           BUS_SET_OOM (error);
572           goto failed;
573         }
574
575       if (_dbus_string_get_length (&full_address) > 0)
576         {
577           if (!_dbus_string_append (&full_address, ";"))
578             {
579               BUS_SET_OOM (error);
580               goto failed;
581             }
582         }
583
584       if (!_dbus_string_append (&full_address, addr))
585         {
586           BUS_SET_OOM (error);
587           goto failed;
588         }
589
590       dbus_free (addr);
591       addr = NULL;
592
593       link = _dbus_list_get_prev_link (&context->servers, link);
594     }
595
596   if (is_reload)
597     dbus_free (context->address);
598
599   if (!_dbus_string_copy_data (&full_address, &context->address))
600     {
601       BUS_SET_OOM (error);
602       goto failed;
603     }
604
605   /* get the service directories */
606   dirs = bus_config_parser_get_service_dirs (parser);
607
608   /* and the service helper */
609   servicehelper = bus_config_parser_get_servicehelper (parser);
610
611   s = _dbus_strdup(servicehelper);
612   if (s == NULL && servicehelper != NULL)
613     {
614       BUS_SET_OOM (error);
615       goto failed;
616     }
617   else
618     {
619       dbus_free(context->servicehelper);
620       context->servicehelper = s;
621     }
622
623   /* Create activation subsystem */
624   if (context->activation)
625     {
626       if (!bus_activation_reload (context->activation, &full_address, dirs, error))
627         goto failed;
628     }
629   else
630     {
631       context->activation = bus_activation_new (context, &full_address, dirs, error);
632     }
633
634   if (context->activation == NULL)
635     {
636       _DBUS_ASSERT_ERROR_IS_SET (error);
637       goto failed;
638     }
639
640   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
641   retval = TRUE;
642
643  failed:
644   _dbus_string_free (&full_address);
645
646   if (addr)
647     dbus_free (addr);
648
649   return retval;
650 }
651
652 static dbus_bool_t
653 list_concat_new (DBusList **a,
654                  DBusList **b,
655                  DBusList **result)
656 {
657   DBusList *link;
658
659   *result = NULL;
660
661   for (link = _dbus_list_get_first_link (a); link; link = _dbus_list_get_next_link (a, link))
662     {
663       if (!_dbus_list_append (result, link->data))
664         goto oom;
665     }
666   for (link = _dbus_list_get_first_link (b); link; link = _dbus_list_get_next_link (b, link))
667     {
668       if (!_dbus_list_append (result, link->data))
669         goto oom;
670     }
671
672   return TRUE;
673 oom:
674   _dbus_list_clear (result);
675   return FALSE;
676 }
677
678 static void
679 raise_file_descriptor_limit (BusContext      *context)
680 {
681 #ifdef DBUS_UNIX
682   DBusError error = DBUS_ERROR_INIT;
683
684   /* we only do this once */
685   if (context->initial_fd_limit != NULL)
686     return;
687
688   context->initial_fd_limit = _dbus_rlimit_save_fd_limit (&error);
689
690   if (context->initial_fd_limit == NULL)
691     {
692       bus_context_log (context, DBUS_SYSTEM_LOG_WARNING,
693                        "%s: %s", error.name, error.message);
694       dbus_error_free (&error);
695       return;
696     }
697
698   /* We used to compute a suitable rlimit based on the configured number
699    * of connections, but that breaks down as soon as we allow fd-passing,
700    * because each connection is allowed to pass 64 fds to us, and if
701    * they all did, we'd hit kernel limits. We now hard-code 64k as a
702    * good limit, like systemd does: that's enough to avoid DoS from
703    * anything short of multiple uids conspiring against us.
704    */
705   if (!_dbus_rlimit_raise_fd_limit_if_privileged (65536, &error))
706     {
707       bus_context_log (context, DBUS_SYSTEM_LOG_WARNING,
708                        "%s: %s", error.name, error.message);
709       dbus_error_free (&error);
710       return;
711     }
712 #endif
713 }
714
715 static dbus_bool_t
716 process_config_postinit (BusContext      *context,
717                          BusConfigParser *parser,
718                          DBusError       *error)
719 {
720   DBusHashTable *service_context_table;
721   DBusList *watched_dirs = NULL;
722
723   raise_file_descriptor_limit (context);
724
725   service_context_table = bus_config_parser_steal_service_context_table (parser);
726   if (!bus_registry_set_service_context_table (context->registry,
727                                                service_context_table))
728     {
729       BUS_SET_OOM (error);
730       return FALSE;
731     }
732
733   _dbus_hash_table_unref (service_context_table);
734
735   /* We need to monitor both the configuration directories and directories
736    * containing .service files.
737    */
738   if (!list_concat_new (bus_config_parser_get_conf_dirs (parser),
739                         bus_config_parser_get_service_dirs (parser),
740                         &watched_dirs))
741     {
742       BUS_SET_OOM (error);
743       return FALSE;
744     }
745
746   bus_set_watched_dirs (context, &watched_dirs);
747
748   _dbus_list_clear (&watched_dirs);
749
750   return TRUE;
751 }
752
753 BusContext*
754 bus_context_new (const DBusString *config_file,
755                  BusContextFlags   flags,
756                  DBusPipe         *print_addr_pipe,
757                  DBusPipe         *print_pid_pipe,
758                  const DBusString *address,
759                  DBusError        *error)
760 {
761   BusContext *context;
762   BusConfigParser *parser;
763
764   _dbus_assert ((flags & BUS_CONTEXT_FLAG_FORK_NEVER) == 0 ||
765                 (flags & BUS_CONTEXT_FLAG_FORK_ALWAYS) == 0);
766
767   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
768
769   context = NULL;
770   parser = NULL;
771
772   if (!dbus_server_allocate_data_slot (&server_data_slot))
773     {
774       BUS_SET_OOM (error);
775       return NULL;
776     }
777
778   context = dbus_new0 (BusContext, 1);
779   if (context == NULL)
780     {
781       BUS_SET_OOM (error);
782       goto failed;
783     }
784   context->refcount = 1;
785
786   if (!_dbus_generate_uuid (&context->uuid, error))
787     goto failed;
788
789   if (!_dbus_string_copy_data (config_file, &context->config_file))
790     {
791       BUS_SET_OOM (error);
792       goto failed;
793     }
794
795   context->loop = _dbus_loop_new ();
796   if (context->loop == NULL)
797     {
798       BUS_SET_OOM (error);
799       goto failed;
800     }
801
802   context->watches_enabled = TRUE;
803
804   context->registry = bus_registry_new (context);
805   if (context->registry == NULL)
806     {
807       BUS_SET_OOM (error);
808       goto failed;
809     }
810
811   parser = bus_config_load (config_file, TRUE, NULL, error);
812   if (parser == NULL)
813     {
814       _DBUS_ASSERT_ERROR_IS_SET (error);
815       goto failed;
816     }
817
818   if (!process_config_first_time_only (context, parser, address, flags, error))
819     {
820       _DBUS_ASSERT_ERROR_IS_SET (error);
821       goto failed;
822     }
823   if (!process_config_every_time (context, parser, FALSE, error))
824     {
825       _DBUS_ASSERT_ERROR_IS_SET (error);
826       goto failed;
827     }
828
829   /* we need another ref of the server data slot for the context
830    * to own
831    */
832   if (!dbus_server_allocate_data_slot (&server_data_slot))
833     _dbus_assert_not_reached ("second ref of server data slot failed");
834
835   /* Note that we don't know whether the print_addr_pipe is
836    * one of the sockets we're using to listen on, or some
837    * other random thing. But I think the answer is "don't do
838    * that then"
839    */
840   if (print_addr_pipe != NULL && _dbus_pipe_is_valid (print_addr_pipe))
841     {
842       DBusString addr;
843       const char *a = bus_context_get_address (context);
844       int bytes;
845
846       _dbus_assert (a != NULL);
847       if (!_dbus_string_init (&addr))
848         {
849           BUS_SET_OOM (error);
850           goto failed;
851         }
852
853       if (!_dbus_string_append (&addr, a) ||
854           !_dbus_string_append (&addr, "\n"))
855         {
856           _dbus_string_free (&addr);
857           BUS_SET_OOM (error);
858           goto failed;
859         }
860
861       bytes = _dbus_string_get_length (&addr);
862       if (_dbus_pipe_write (print_addr_pipe, &addr, 0, bytes, error) != bytes)
863         {
864           /* pipe write returns an error on failure but not short write */
865           if (error != NULL && !dbus_error_is_set (error))
866             {
867               dbus_set_error (error, DBUS_ERROR_FAILED,
868                               "Printing message bus address: did not write all bytes\n");
869             }
870           _dbus_string_free (&addr);
871           goto failed;
872         }
873
874       if (!_dbus_pipe_is_stdout_or_stderr (print_addr_pipe))
875         _dbus_pipe_close (print_addr_pipe, NULL);
876
877       _dbus_string_free (&addr);
878     }
879
880   context->connections = bus_connections_new (context);
881   if (context->connections == NULL)
882     {
883       BUS_SET_OOM (error);
884       goto failed;
885     }
886
887   context->matchmaker = bus_matchmaker_new ();
888   if (context->matchmaker == NULL)
889     {
890       BUS_SET_OOM (error);
891       goto failed;
892     }
893
894   /* check user before we fork */
895   if (context->user != NULL)
896     {
897       if (!_dbus_verify_daemon_user (context->user))
898         {
899           dbus_set_error (error, DBUS_ERROR_FAILED,
900                           "Could not get UID and GID for username \"%s\"",
901                           context->user);
902           goto failed;
903         }
904     }
905
906   /* Now become a daemon if appropriate and write out pid file in any case */
907   {
908     DBusString u;
909
910     if (context->pidfile)
911       _dbus_string_init_const (&u, context->pidfile);
912
913     if (((flags & BUS_CONTEXT_FLAG_FORK_NEVER) == 0 && context->fork) ||
914         (flags & BUS_CONTEXT_FLAG_FORK_ALWAYS))
915       {
916         _dbus_verbose ("Forking and becoming daemon\n");
917
918         if (!_dbus_become_daemon (context->pidfile ? &u : NULL,
919                                   print_pid_pipe,
920                                   error,
921                                   context->keep_umask))
922           {
923             _DBUS_ASSERT_ERROR_IS_SET (error);
924             goto failed;
925           }
926       }
927     else
928       {
929         _dbus_verbose ("Fork not requested\n");
930
931         /* Need to write PID file and to PID pipe for ourselves,
932          * not for the child process. This is a no-op if the pidfile
933          * is NULL and print_pid_pipe is NULL.
934          */
935         if (!_dbus_write_pid_to_file_and_pipe (context->pidfile ? &u : NULL,
936                                                print_pid_pipe,
937                                                _dbus_getpid (),
938                                                error))
939           {
940             _DBUS_ASSERT_ERROR_IS_SET (error);
941             goto failed;
942           }
943       }
944   }
945
946   if (print_pid_pipe && _dbus_pipe_is_valid (print_pid_pipe) &&
947       !_dbus_pipe_is_stdout_or_stderr (print_pid_pipe))
948     _dbus_pipe_close (print_pid_pipe, NULL);
949
950   /* Here we change our credentials if required,
951    * as soon as we've set up our sockets and pidfile.
952    * This must be done before initializing LSMs, so that the netlink
953    * monitoring thread started by avc_init() will not lose CAP_AUDIT_WRITE
954    * when the main thread calls setuid().
955    * https://bugs.freedesktop.org/show_bug.cgi?id=92832
956    */
957   if (context->user != NULL)
958     {
959       if (!_dbus_change_to_daemon_user (context->user, error))
960         {
961           _DBUS_ASSERT_ERROR_IS_SET (error);
962           goto failed;
963         }
964     }
965
966   /* Auditing should be initialized before LSMs, so that the LSMs are able
967    * to log audit-events that happen during their initialization.
968    */
969   bus_audit_init (context);
970
971   if (!bus_selinux_full_init ())
972     {
973       bus_context_log (context, DBUS_SYSTEM_LOG_FATAL, "SELinux enabled but D-Bus initialization failed; check system log\n");
974     }
975
976   if (!bus_apparmor_full_init (error))
977     {
978       _DBUS_ASSERT_ERROR_IS_SET (error);
979       goto failed;
980     }
981
982   if (bus_apparmor_enabled ())
983     {
984       /* Only print AppArmor mediation message when syslog support is enabled */
985       if (context->syslog)
986         bus_context_log (context, DBUS_SYSTEM_LOG_INFO,
987                          "AppArmor D-Bus mediation is enabled\n");
988     }
989
990   /* When SELinux is used, this must happen after bus_selinux_full_init()
991    * so that it has access to the access vector cache, which is required
992    * to process <associate/> elements.
993    * http://lists.freedesktop.org/archives/dbus/2008-October/010491.html
994    */
995   if (!process_config_postinit (context, parser, error))
996     {
997       _DBUS_ASSERT_ERROR_IS_SET (error);
998       goto failed;
999     }
1000
1001   if (parser != NULL)
1002     {
1003       bus_config_parser_unref (parser);
1004       parser = NULL;
1005     }
1006
1007   dbus_server_free_data_slot (&server_data_slot);
1008
1009   return context;
1010
1011  failed:
1012   if (parser != NULL)
1013     bus_config_parser_unref (parser);
1014   if (context != NULL)
1015     bus_context_unref (context);
1016
1017   if (server_data_slot >= 0)
1018     dbus_server_free_data_slot (&server_data_slot);
1019
1020   return NULL;
1021 }
1022
1023 dbus_bool_t
1024 bus_context_get_id (BusContext       *context,
1025                     DBusString       *uuid)
1026 {
1027   return _dbus_uuid_encode (&context->uuid, uuid);
1028 }
1029
1030 dbus_bool_t
1031 bus_context_reload_config (BusContext *context,
1032                            DBusError  *error)
1033 {
1034   BusConfigParser *parser;
1035   DBusString config_file;
1036   dbus_bool_t ret;
1037
1038   /* Flush the user database cache */
1039   _dbus_flush_caches ();
1040
1041   ret = FALSE;
1042   _dbus_string_init_const (&config_file, context->config_file);
1043   parser = bus_config_load (&config_file, TRUE, NULL, error);
1044   if (parser == NULL)
1045     {
1046       _DBUS_ASSERT_ERROR_IS_SET (error);
1047       goto failed;
1048     }
1049
1050   if (!process_config_every_time (context, parser, TRUE, error))
1051     {
1052       _DBUS_ASSERT_ERROR_IS_SET (error);
1053       goto failed;
1054     }
1055   if (!process_config_postinit (context, parser, error))
1056     {
1057       _DBUS_ASSERT_ERROR_IS_SET (error);
1058       goto failed;
1059     }
1060   ret = TRUE;
1061
1062   bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Reloaded configuration");
1063  failed:
1064   if (!ret)
1065     bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Unable to reload configuration: %s", error->message);
1066   if (parser != NULL)
1067     bus_config_parser_unref (parser);
1068   return ret;
1069 }
1070
1071 static void
1072 shutdown_server (BusContext *context,
1073                  DBusServer *server)
1074 {
1075   if (server == NULL ||
1076       !dbus_server_get_is_connected (server))
1077     return;
1078
1079   if (!dbus_server_set_watch_functions (server,
1080                                         NULL, NULL, NULL,
1081                                         context,
1082                                         NULL))
1083     _dbus_assert_not_reached ("setting watch functions to NULL failed");
1084
1085   if (!dbus_server_set_timeout_functions (server,
1086                                           NULL, NULL, NULL,
1087                                           context,
1088                                           NULL))
1089     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
1090
1091   dbus_server_disconnect (server);
1092 }
1093
1094 void
1095 bus_context_shutdown (BusContext  *context)
1096 {
1097   DBusList *link;
1098
1099   link = _dbus_list_get_first_link (&context->servers);
1100   while (link != NULL)
1101     {
1102       shutdown_server (context, link->data);
1103
1104       link = _dbus_list_get_next_link (&context->servers, link);
1105     }
1106 }
1107
1108 BusContext *
1109 bus_context_ref (BusContext *context)
1110 {
1111   _dbus_assert (context->refcount > 0);
1112   context->refcount += 1;
1113
1114   return context;
1115 }
1116
1117 void
1118 bus_context_unref (BusContext *context)
1119 {
1120   _dbus_assert (context->refcount > 0);
1121   context->refcount -= 1;
1122
1123   if (context->refcount == 0)
1124     {
1125       DBusList *link;
1126
1127       _dbus_verbose ("Finalizing bus context %p\n", context);
1128
1129       bus_context_shutdown (context);
1130
1131       if (context->connections)
1132         {
1133           bus_connections_unref (context->connections);
1134           context->connections = NULL;
1135         }
1136
1137       if (context->registry)
1138         {
1139           bus_registry_unref (context->registry);
1140           context->registry = NULL;
1141         }
1142
1143       if (context->activation)
1144         {
1145           bus_activation_unref (context->activation);
1146           context->activation = NULL;
1147         }
1148
1149       link = _dbus_list_get_first_link (&context->servers);
1150       while (link != NULL)
1151         {
1152           dbus_server_unref (link->data);
1153
1154           link = _dbus_list_get_next_link (&context->servers, link);
1155         }
1156       _dbus_list_clear (&context->servers);
1157
1158       if (context->policy)
1159         {
1160           bus_policy_unref (context->policy);
1161           context->policy = NULL;
1162         }
1163
1164       if (context->loop)
1165         {
1166           _dbus_loop_unref (context->loop);
1167           context->loop = NULL;
1168         }
1169
1170       if (context->matchmaker)
1171         {
1172           bus_matchmaker_unref (context->matchmaker);
1173           context->matchmaker = NULL;
1174         }
1175
1176       dbus_free (context->config_file);
1177       dbus_free (context->log_prefix);
1178       dbus_free (context->type);
1179       dbus_free (context->address);
1180       dbus_free (context->user);
1181       dbus_free (context->servicehelper);
1182
1183       if (context->pidfile)
1184         {
1185           DBusString u;
1186           _dbus_string_init_const (&u, context->pidfile);
1187
1188           /* Deliberately ignore errors here, since there's not much
1189            * we can do about it, and we're exiting anyways.
1190            */
1191           _dbus_delete_file (&u, NULL);
1192
1193           dbus_free (context->pidfile);
1194         }
1195
1196       if (context->initial_fd_limit)
1197         _dbus_rlimit_free (context->initial_fd_limit);
1198
1199       dbus_free (context);
1200
1201       dbus_server_free_data_slot (&server_data_slot);
1202     }
1203 }
1204
1205 /* type may be NULL */
1206 const char*
1207 bus_context_get_type (BusContext *context)
1208 {
1209   return context->type;
1210 }
1211
1212 const char*
1213 bus_context_get_address (BusContext *context)
1214 {
1215   return context->address;
1216 }
1217
1218 const char*
1219 bus_context_get_servicehelper (BusContext *context)
1220 {
1221   return context->servicehelper;
1222 }
1223
1224 dbus_bool_t
1225 bus_context_get_systemd_activation (BusContext *context)
1226 {
1227   return context->systemd_activation;
1228 }
1229
1230 BusRegistry*
1231 bus_context_get_registry (BusContext  *context)
1232 {
1233   return context->registry;
1234 }
1235
1236 BusConnections*
1237 bus_context_get_connections (BusContext  *context)
1238 {
1239   return context->connections;
1240 }
1241
1242 BusActivation*
1243 bus_context_get_activation (BusContext  *context)
1244 {
1245   return context->activation;
1246 }
1247
1248 BusMatchmaker*
1249 bus_context_get_matchmaker (BusContext  *context)
1250 {
1251   return context->matchmaker;
1252 }
1253
1254 DBusLoop*
1255 bus_context_get_loop (BusContext *context)
1256 {
1257   return context->loop;
1258 }
1259
1260 dbus_bool_t
1261 bus_context_allow_unix_user (BusContext   *context,
1262                              unsigned long uid)
1263 {
1264   return bus_policy_allow_unix_user (context->policy,
1265                                      uid);
1266 }
1267
1268 /* For now this is never actually called because the default
1269  * DBusConnection behavior of 'same user that owns the bus can connect'
1270  * is all it would do.
1271  */
1272 dbus_bool_t
1273 bus_context_allow_windows_user (BusContext       *context,
1274                                 const char       *windows_sid)
1275 {
1276   return bus_policy_allow_windows_user (context->policy,
1277                                         windows_sid);
1278 }
1279
1280 BusPolicy *
1281 bus_context_get_policy (BusContext *context)
1282 {
1283   return context->policy;
1284 }
1285
1286 BusClientPolicy*
1287 bus_context_create_client_policy (BusContext      *context,
1288                                   DBusConnection  *connection,
1289                                   DBusError       *error)
1290 {
1291   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1292   return bus_policy_create_client_policy (context->policy, connection,
1293                                           error);
1294 }
1295
1296 int
1297 bus_context_get_activation_timeout (BusContext *context)
1298 {
1299
1300   return context->limits.activation_timeout;
1301 }
1302
1303 int
1304 bus_context_get_auth_timeout (BusContext *context)
1305 {
1306   return context->limits.auth_timeout;
1307 }
1308
1309 int
1310 bus_context_get_pending_fd_timeout (BusContext *context)
1311 {
1312   return context->limits.pending_fd_timeout;
1313 }
1314
1315 int
1316 bus_context_get_max_completed_connections (BusContext *context)
1317 {
1318   return context->limits.max_completed_connections;
1319 }
1320
1321 int
1322 bus_context_get_max_incomplete_connections (BusContext *context)
1323 {
1324   return context->limits.max_incomplete_connections;
1325 }
1326
1327 int
1328 bus_context_get_max_connections_per_user (BusContext *context)
1329 {
1330   return context->limits.max_connections_per_user;
1331 }
1332
1333 int
1334 bus_context_get_max_pending_activations (BusContext *context)
1335 {
1336   return context->limits.max_pending_activations;
1337 }
1338
1339 int
1340 bus_context_get_max_services_per_connection (BusContext *context)
1341 {
1342   return context->limits.max_services_per_connection;
1343 }
1344
1345 int
1346 bus_context_get_max_match_rules_per_connection (BusContext *context)
1347 {
1348   return context->limits.max_match_rules_per_connection;
1349 }
1350
1351 int
1352 bus_context_get_max_replies_per_connection (BusContext *context)
1353 {
1354   return context->limits.max_replies_per_connection;
1355 }
1356
1357 int
1358 bus_context_get_reply_timeout (BusContext *context)
1359 {
1360   return context->limits.reply_timeout;
1361 }
1362
1363 DBusRLimit *
1364 bus_context_get_initial_fd_limit (BusContext *context)
1365 {
1366   return context->initial_fd_limit;
1367 }
1368
1369 dbus_bool_t
1370 bus_context_get_using_syslog (BusContext *context)
1371 {
1372   return context->syslog;
1373 }
1374
1375 void
1376 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...)
1377 {
1378   va_list args;
1379
1380   va_start (args, msg);
1381
1382   if (context->log_prefix)
1383     {
1384       DBusString full_msg;
1385
1386       if (!_dbus_string_init (&full_msg))
1387         goto out;
1388       if (!_dbus_string_append (&full_msg, context->log_prefix))
1389         goto oom_out;
1390       if (!_dbus_string_append_printf_valist (&full_msg, msg, args))
1391         goto oom_out;
1392
1393       _dbus_log (severity, "%s", _dbus_string_get_const_data (&full_msg));
1394     oom_out:
1395       _dbus_string_free (&full_msg);
1396     }
1397   else
1398     _dbus_logv (severity, msg, args);
1399
1400 out:
1401   va_end (args);
1402 }
1403
1404 static inline const char *
1405 nonnull (const char *maybe_null,
1406          const char *if_null)
1407 {
1408   return (maybe_null ? maybe_null : if_null);
1409 }
1410
1411 void
1412 bus_context_log_literal (BusContext            *context,
1413                          DBusSystemLogSeverity  severity,
1414                          const char            *msg)
1415 {
1416   _dbus_log (severity, "%s%s", nonnull (context->log_prefix, ""), msg);
1417 }
1418
1419 void
1420 bus_context_log_and_set_error (BusContext            *context,
1421                                DBusSystemLogSeverity  severity,
1422                                DBusError             *error,
1423                                const char            *name,
1424                                const char            *msg,
1425                                ...)
1426 {
1427   DBusError stack_error = DBUS_ERROR_INIT;
1428   va_list args;
1429
1430   va_start (args, msg);
1431   _dbus_set_error_valist (&stack_error, name, msg, args);
1432   va_end (args);
1433
1434   /* If we hit OOM while setting the error, this will syslog "out of memory"
1435    * which is itself an indication that something is seriously wrong */
1436   bus_context_log_literal (context, DBUS_SYSTEM_LOG_SECURITY,
1437                            stack_error.message);
1438
1439   dbus_move_error (&stack_error, error);
1440 }
1441
1442 /*
1443  * Log something about a message, usually that it was rejected.
1444  */
1445 static void
1446 complain_about_message (BusContext     *context,
1447                         const char     *error_name,
1448                         const char     *complaint,
1449                         int             matched_rules,
1450                         DBusMessage    *message,
1451                         DBusConnection *sender,
1452                         DBusConnection *proposed_recipient,
1453                         dbus_bool_t     requested_reply,
1454                         dbus_bool_t     log,
1455                         DBusError      *error)
1456 {
1457   DBusError stack_error = DBUS_ERROR_INIT;
1458   const char *sender_name;
1459   const char *sender_loginfo;
1460   const char *proposed_recipient_loginfo;
1461
1462   if (error == NULL && !log)
1463     return;
1464
1465   if (sender != NULL)
1466     {
1467       sender_name = bus_connection_get_name (sender);
1468       sender_loginfo = bus_connection_get_loginfo (sender);
1469     }
1470   else
1471     {
1472       sender_name = "(unset)";
1473       sender_loginfo = "(bus)";
1474     }
1475
1476   if (proposed_recipient != NULL)
1477     proposed_recipient_loginfo = bus_connection_get_loginfo (proposed_recipient);
1478   else
1479     proposed_recipient_loginfo = "bus";
1480
1481   dbus_set_error (&stack_error, error_name,
1482       "%s, %d matched rules; type=\"%s\", sender=\"%s\" (%s) "
1483       "interface=\"%s\" member=\"%s\" error name=\"%s\" "
1484       "requested_reply=\"%d\" destination=\"%s\" (%s)",
1485       complaint,
1486       matched_rules,
1487       dbus_message_type_to_string (dbus_message_get_type (message)),
1488       sender_name,
1489       sender_loginfo,
1490       nonnull (dbus_message_get_interface (message), "(unset)"),
1491       nonnull (dbus_message_get_member (message), "(unset)"),
1492       nonnull (dbus_message_get_error_name (message), "(unset)"),
1493       requested_reply,
1494       nonnull (dbus_message_get_destination (message), DBUS_SERVICE_DBUS),
1495       proposed_recipient_loginfo);
1496
1497   /* If we hit OOM while setting the error, this will syslog "out of memory"
1498    * which is itself an indication that something is seriously wrong */
1499   if (log)
1500     bus_context_log_literal (context, DBUS_SYSTEM_LOG_SECURITY,
1501         stack_error.message);
1502
1503   dbus_move_error (&stack_error, error);
1504 }
1505
1506 /*
1507  * addressed_recipient is the recipient specified in the message.
1508  *
1509  * proposed_recipient is the recipient we're considering sending
1510  * to right this second, and may be an eavesdropper.
1511  *
1512  * sender is the sender of the message.
1513  *
1514  * NULL for sender definitely means the bus driver.
1515  *
1516  * NULL for proposed_recipient may mean the bus driver, or may mean
1517  * we are checking whether service-activation is allowed as a first
1518  * pass before all details of the activated service are known.
1519  *
1520  * NULL for addressed_recipient may mean the bus driver, or may mean
1521  * no destination was specified in the message (e.g. a signal).
1522  */
1523 dbus_bool_t
1524 bus_context_check_security_policy (BusContext     *context,
1525                                    BusTransaction *transaction,
1526                                    DBusConnection *sender,
1527                                    DBusConnection *addressed_recipient,
1528                                    DBusConnection *proposed_recipient,
1529                                    DBusMessage    *message,
1530                                    BusActivationEntry *activation_entry,
1531                                    DBusError      *error)
1532 {
1533   const char *src, *dest;
1534   BusClientPolicy *sender_policy;
1535   BusClientPolicy *recipient_policy;
1536   dbus_int32_t toggles;
1537   dbus_bool_t log;
1538   int type;
1539   dbus_bool_t requested_reply;
1540
1541   type = dbus_message_get_type (message);
1542   src = dbus_message_get_sender (message);
1543   dest = dbus_message_get_destination (message);
1544
1545   /* dispatch.c was supposed to ensure these invariants */
1546   _dbus_assert (dest != NULL ||
1547                 type == DBUS_MESSAGE_TYPE_SIGNAL ||
1548                 (sender == NULL && !bus_connection_is_active (proposed_recipient)));
1549   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
1550                 addressed_recipient != NULL ||
1551                 activation_entry != NULL ||
1552                 strcmp (dest, DBUS_SERVICE_DBUS) == 0);
1553
1554   switch (type)
1555     {
1556     case DBUS_MESSAGE_TYPE_METHOD_CALL:
1557     case DBUS_MESSAGE_TYPE_SIGNAL:
1558     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
1559     case DBUS_MESSAGE_TYPE_ERROR:
1560       break;
1561
1562     default:
1563       _dbus_verbose ("security check disallowing message of unknown type %d\n",
1564                      type);
1565
1566       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1567                       "Message bus will not accept messages of unknown type\n");
1568
1569       return FALSE;
1570     }
1571
1572   requested_reply = FALSE;
1573
1574   if (sender != NULL)
1575     {
1576       if (bus_connection_is_active (sender))
1577         {
1578           sender_policy = bus_connection_get_policy (sender);
1579           _dbus_assert (sender_policy != NULL);
1580
1581           /* Fill in requested_reply variable with TRUE if this is a
1582            * reply and the reply was pending.
1583            */
1584           if (dbus_message_get_reply_serial (message) != 0)
1585             {
1586               if (proposed_recipient != NULL /* not to the bus driver */ &&
1587                   addressed_recipient == proposed_recipient /* not eavesdropping */)
1588                 {
1589                   DBusError error2;
1590
1591                   dbus_error_init (&error2);
1592                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
1593                                                                  transaction,
1594                                                                  sender, addressed_recipient, message,
1595                                                                  &error2);
1596                   if (dbus_error_is_set (&error2))
1597                     {
1598                       dbus_move_error (&error2, error);
1599                       return FALSE;
1600                     }
1601                 }
1602             }
1603         }
1604       else
1605         {
1606           sender_policy = NULL;
1607         }
1608
1609       /* First verify the SELinux access controls.  If allowed then
1610        * go on with the standard checks.
1611        */
1612       if (!bus_selinux_allows_send (sender, proposed_recipient,
1613                                     dbus_message_type_to_string (dbus_message_get_type (message)),
1614                                     dbus_message_get_interface (message),
1615                                     dbus_message_get_member (message),
1616                                     dbus_message_get_error_name (message),
1617                                     dest ? dest : DBUS_SERVICE_DBUS,
1618                                     activation_entry,
1619                                     error))
1620         {
1621           if (error != NULL && !dbus_error_is_set (error))
1622             {
1623               /* don't syslog this, just set the error: avc_has_perm should
1624                * have already written to either the audit log or syslog */
1625               complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1626                   "An SELinux policy prevents this sender from sending this "
1627                   "message to this recipient",
1628                   0, message, sender, proposed_recipient, FALSE, FALSE, error);
1629               _dbus_verbose ("SELinux security check denying send to service\n");
1630             }
1631
1632           return FALSE;
1633         }
1634
1635       /* next verify AppArmor access controls.  If allowed then
1636        * go on with the standard checks.
1637        */
1638       if (!bus_apparmor_allows_send (sender, proposed_recipient,
1639                                      requested_reply,
1640                                      bus_context_get_type (context),
1641                                      dbus_message_get_type (message),
1642                                      dbus_message_get_path (message),
1643                                      dbus_message_get_interface (message),
1644                                      dbus_message_get_member (message),
1645                                      dbus_message_get_error_name (message),
1646                                      dest ? dest : DBUS_SERVICE_DBUS,
1647                                      src ? src : DBUS_SERVICE_DBUS,
1648                                      activation_entry,
1649                                      error))
1650         return FALSE;
1651
1652       if (!bus_connection_is_active (sender))
1653         {
1654           /* Policy for inactive connections is that they can only send
1655            * the hello message to the bus driver
1656            */
1657           if (proposed_recipient == NULL &&
1658               dbus_message_is_method_call (message,
1659                                            DBUS_INTERFACE_DBUS,
1660                                            "Hello"))
1661             {
1662               _dbus_verbose ("security check allowing %s message\n",
1663                              "Hello");
1664               return TRUE;
1665             }
1666           else
1667             {
1668               _dbus_verbose ("security check disallowing non-%s message\n",
1669                              "Hello");
1670
1671               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1672                               "Client tried to send a message other than %s without being registered",
1673                               "Hello");
1674
1675               return FALSE;
1676             }
1677         }
1678     }
1679   else
1680     {
1681       sender_policy = NULL;
1682
1683       /* If the sender is the bus driver, we assume any reply was a
1684        * requested reply as bus driver won't send bogus ones
1685        */
1686       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1687           dbus_message_get_reply_serial (message) != 0)
1688         requested_reply = TRUE;
1689     }
1690
1691   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1692                 (sender == NULL && sender_policy == NULL));
1693
1694   if (proposed_recipient != NULL)
1695     {
1696       /* only the bus driver can send to an inactive recipient (as it
1697        * owns no services, so other apps can't address it). Inactive
1698        * recipients can receive any message.
1699        */
1700       if (bus_connection_is_active (proposed_recipient))
1701         {
1702           recipient_policy = bus_connection_get_policy (proposed_recipient);
1703           _dbus_assert (recipient_policy != NULL);
1704         }
1705       else if (sender == NULL)
1706         {
1707           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1708           recipient_policy = NULL;
1709         }
1710       else
1711         {
1712           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus");
1713           recipient_policy = NULL;
1714         }
1715     }
1716   else
1717     recipient_policy = NULL;
1718
1719   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1720                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1721                 (proposed_recipient == NULL && recipient_policy == NULL));
1722
1723   log = FALSE;
1724   if (sender_policy &&
1725       !bus_client_policy_check_can_send (sender_policy,
1726                                          context->registry,
1727                                          requested_reply,
1728                                          proposed_recipient,
1729                                          message, &toggles, &log))
1730     {
1731       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1732           "Rejected send message", toggles,
1733           message, sender, proposed_recipient, requested_reply,
1734           (addressed_recipient == proposed_recipient), error);
1735       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1736       return FALSE;
1737     }
1738
1739   if (log)
1740     {
1741       /* We want to drop this message, and are only not doing so for backwards
1742        * compatibility. */
1743       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1744           "Would reject message", toggles,
1745           message, sender, proposed_recipient, requested_reply,
1746           TRUE, NULL);
1747     }
1748
1749   if (recipient_policy &&
1750       !bus_client_policy_check_can_receive (recipient_policy,
1751                                             context->registry,
1752                                             requested_reply,
1753                                             sender,
1754                                             addressed_recipient, proposed_recipient,
1755                                             message, &toggles))
1756     {
1757       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1758           "Rejected receive message", toggles,
1759           message, sender, proposed_recipient, requested_reply,
1760           (addressed_recipient == proposed_recipient), error);
1761       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1762       return FALSE;
1763     }
1764
1765   /* See if limits on size have been exceeded */
1766   if (proposed_recipient &&
1767       ((dbus_connection_get_outgoing_size (proposed_recipient) > context->limits.max_outgoing_bytes) ||
1768        (dbus_connection_get_outgoing_unix_fds (proposed_recipient) > context->limits.max_outgoing_unix_fds)))
1769     {
1770       complain_about_message (context, DBUS_ERROR_LIMITS_EXCEEDED,
1771           "Rejected: destination has a full message queue",
1772           0, message, sender, proposed_recipient, requested_reply, TRUE,
1773           error);
1774       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1775       return FALSE;
1776     }
1777
1778   /* Record that we will allow a reply here in the future (don't
1779    * bother if the recipient is the bus or this is an eavesdropping
1780    * connection). Only the addressed recipient may reply.
1781    *
1782    * This isn't done for activation attempts because they have no addressed
1783    * or proposed recipient; when we check whether to actually deliver the
1784    * message, later, we'll record the reply expectation at that point.
1785    */
1786   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL &&
1787       sender &&
1788       addressed_recipient &&
1789       addressed_recipient == proposed_recipient && /* not eavesdropping */
1790       !bus_connections_expect_reply (bus_connection_get_connections (sender),
1791                                      transaction,
1792                                      sender, addressed_recipient,
1793                                      message, error))
1794     {
1795       _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1796       return FALSE;
1797     }
1798
1799   _dbus_verbose ("security policy allowing message\n");
1800   return TRUE;
1801 }
1802
1803 void
1804 bus_context_check_all_watches (BusContext *context)
1805 {
1806   DBusList *link;
1807   dbus_bool_t enabled = TRUE;
1808
1809   if (bus_connections_get_n_incomplete (context->connections) >=
1810       bus_context_get_max_incomplete_connections (context))
1811     {
1812       enabled = FALSE;
1813     }
1814
1815   if (context->watches_enabled == enabled)
1816     return;
1817
1818   context->watches_enabled = enabled;
1819
1820   for (link = _dbus_list_get_first_link (&context->servers);
1821        link != NULL;
1822        link = _dbus_list_get_next_link (&context->servers, link))
1823     {
1824       /* A BusContext might contains several DBusServer (if there are
1825        * several <listen> configuration items) and a DBusServer might
1826        * contain several DBusWatch in its DBusWatchList (if getaddrinfo
1827        * returns several addresses on a dual IPv4-IPv6 stack or if
1828        * systemd passes several fds).
1829        * We want to enable/disable them all.
1830        */
1831       DBusServer *server = link->data;
1832       _dbus_server_toggle_all_watches (server, enabled);
1833     }
1834 }