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