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