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