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