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