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