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