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