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