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