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