Merge branch 'dbus-1.4' and update NEWS for master
[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         }
396     }
397   else
398     {
399       auth_mechanisms = NULL;
400     }
401
402   /* Listen on our addresses */
403
404   if (address)
405     {
406       DBusServer *server;
407
408       server = dbus_server_listen (_dbus_string_get_const_data(address), error);
409       if (server == NULL)
410         {
411           _DBUS_ASSERT_ERROR_IS_SET (error);
412           goto failed;
413         }
414       else if (!setup_server (context, server, auth_mechanisms, error))
415         {
416           _DBUS_ASSERT_ERROR_IS_SET (error);
417           goto failed;
418         }
419
420       if (!_dbus_list_append (&context->servers, server))
421         goto oom;
422     }
423   else
424     {
425       addresses = bus_config_parser_get_addresses (parser);
426
427       link = _dbus_list_get_first_link (addresses);
428       while (link != NULL)
429         {
430           DBusServer *server;
431
432           server = dbus_server_listen (link->data, error);
433           if (server == NULL)
434             {
435               _DBUS_ASSERT_ERROR_IS_SET (error);
436               goto failed;
437             }
438           else if (!setup_server (context, server, auth_mechanisms, error))
439             {
440               _DBUS_ASSERT_ERROR_IS_SET (error);
441               goto failed;
442             }
443
444           if (!_dbus_list_append (&context->servers, server))
445             goto oom;
446
447           link = _dbus_list_get_next_link (addresses, link);
448         }
449     }
450
451   context->fork = bus_config_parser_get_fork (parser);
452   context->syslog = bus_config_parser_get_syslog (parser);
453   context->keep_umask = bus_config_parser_get_keep_umask (parser);
454   context->allow_anonymous = bus_config_parser_get_allow_anonymous (parser);
455
456   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
457   retval = TRUE;
458
459  failed:
460   dbus_free_string_array (auth_mechanisms);
461   return retval;
462
463  oom:
464   BUS_SET_OOM (error);
465   dbus_free_string_array (auth_mechanisms);
466   return FALSE;
467 }
468
469 /* This code gets executed every time the config files
470  * are parsed: both during BusContext construction
471  * and on reloads. This function is slightly screwy
472  * since it can do a "half reload" in out-of-memory
473  * situations. Realistically, unlikely to ever matter.
474  */
475 static dbus_bool_t
476 process_config_every_time (BusContext      *context,
477                            BusConfigParser *parser,
478                            dbus_bool_t      is_reload,
479                            DBusError       *error)
480 {
481   DBusString full_address;
482   DBusList *link;
483   DBusList **dirs;
484   BusActivation *new_activation;
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   DBusString log_prefix;
692   BusContext *context;
693   BusConfigParser *parser;
694
695   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
696
697   context = NULL;
698   parser = NULL;
699
700   if (!dbus_server_allocate_data_slot (&server_data_slot))
701     {
702       BUS_SET_OOM (error);
703       return NULL;
704     }
705
706   context = dbus_new0 (BusContext, 1);
707   if (context == NULL)
708     {
709       BUS_SET_OOM (error);
710       goto failed;
711     }
712   context->refcount = 1;
713
714   _dbus_generate_uuid (&context->uuid);
715
716   if (!_dbus_string_copy_data (config_file, &context->config_file))
717     {
718       BUS_SET_OOM (error);
719       goto failed;
720     }
721
722   context->loop = _dbus_loop_new ();
723   if (context->loop == NULL)
724     {
725       BUS_SET_OOM (error);
726       goto failed;
727     }
728
729   context->registry = bus_registry_new (context);
730   if (context->registry == NULL)
731     {
732       BUS_SET_OOM (error);
733       goto failed;
734     }
735
736   parser = bus_config_load (config_file, TRUE, NULL, error);
737   if (parser == NULL)
738     {
739       _DBUS_ASSERT_ERROR_IS_SET (error);
740       goto failed;
741     }
742
743   if (!process_config_first_time_only (context, parser, address, systemd_activation, error))
744     {
745       _DBUS_ASSERT_ERROR_IS_SET (error);
746       goto failed;
747     }
748   if (!process_config_every_time (context, parser, FALSE, error))
749     {
750       _DBUS_ASSERT_ERROR_IS_SET (error);
751       goto failed;
752     }
753
754   /* we need another ref of the server data slot for the context
755    * to own
756    */
757   if (!dbus_server_allocate_data_slot (&server_data_slot))
758     _dbus_assert_not_reached ("second ref of server data slot failed");
759
760   /* Note that we don't know whether the print_addr_pipe is
761    * one of the sockets we're using to listen on, or some
762    * other random thing. But I think the answer is "don't do
763    * that then"
764    */
765   if (print_addr_pipe != NULL && _dbus_pipe_is_valid (print_addr_pipe))
766     {
767       DBusString addr;
768       const char *a = bus_context_get_address (context);
769       int bytes;
770
771       _dbus_assert (a != NULL);
772       if (!_dbus_string_init (&addr))
773         {
774           BUS_SET_OOM (error);
775           goto failed;
776         }
777
778       if (!_dbus_string_append (&addr, a) ||
779           !_dbus_string_append (&addr, "\n"))
780         {
781           _dbus_string_free (&addr);
782           BUS_SET_OOM (error);
783           goto failed;
784         }
785
786       bytes = _dbus_string_get_length (&addr);
787       if (_dbus_pipe_write (print_addr_pipe, &addr, 0, bytes, error) != bytes)
788         {
789           /* pipe write returns an error on failure but not short write */
790           if (error != NULL && !dbus_error_is_set (error))
791             {
792               dbus_set_error (error, DBUS_ERROR_FAILED,
793                               "Printing message bus address: did not write all bytes\n");
794             }
795           _dbus_string_free (&addr);
796           goto failed;
797         }
798
799       if (!_dbus_pipe_is_stdout_or_stderr (print_addr_pipe))
800         _dbus_pipe_close (print_addr_pipe, NULL);
801
802       _dbus_string_free (&addr);
803     }
804
805   context->connections = bus_connections_new (context);
806   if (context->connections == NULL)
807     {
808       BUS_SET_OOM (error);
809       goto failed;
810     }
811
812   context->matchmaker = bus_matchmaker_new ();
813   if (context->matchmaker == NULL)
814     {
815       BUS_SET_OOM (error);
816       goto failed;
817     }
818
819   /* check user before we fork */
820   if (context->user != NULL)
821     {
822       if (!_dbus_verify_daemon_user (context->user))
823         {
824           dbus_set_error (error, DBUS_ERROR_FAILED,
825                           "Could not get UID and GID for username \"%s\"",
826                           context->user);
827           goto failed;
828         }
829     }
830
831   /* Now become a daemon if appropriate and write out pid file in any case */
832   {
833     DBusString u;
834
835     if (context->pidfile)
836       _dbus_string_init_const (&u, context->pidfile);
837
838     if ((force_fork != FORK_NEVER && context->fork) || force_fork == FORK_ALWAYS)
839       {
840         _dbus_verbose ("Forking and becoming daemon\n");
841
842         if (!_dbus_become_daemon (context->pidfile ? &u : NULL,
843                                   print_pid_pipe,
844                                   error,
845                                   context->keep_umask))
846           {
847             _DBUS_ASSERT_ERROR_IS_SET (error);
848             goto failed;
849           }
850       }
851     else
852       {
853         _dbus_verbose ("Fork not requested\n");
854
855         /* Need to write PID file and to PID pipe for ourselves,
856          * not for the child process. This is a no-op if the pidfile
857          * is NULL and print_pid_pipe is NULL.
858          */
859         if (!_dbus_write_pid_to_file_and_pipe (context->pidfile ? &u : NULL,
860                                                print_pid_pipe,
861                                                _dbus_getpid (),
862                                                error))
863           {
864             _DBUS_ASSERT_ERROR_IS_SET (error);
865             goto failed;
866           }
867       }
868   }
869
870   if (print_pid_pipe && _dbus_pipe_is_valid (print_pid_pipe) &&
871       !_dbus_pipe_is_stdout_or_stderr (print_pid_pipe))
872     _dbus_pipe_close (print_pid_pipe, NULL);
873
874   if (!bus_selinux_full_init ())
875     {
876       bus_context_log (context, DBUS_SYSTEM_LOG_FATAL, "SELinux enabled but AVC initialization failed; check system log\n");
877     }
878
879   if (!process_config_postinit (context, parser, error))
880     {
881       _DBUS_ASSERT_ERROR_IS_SET (error);
882       goto failed;
883     }
884
885   if (parser != NULL)
886     {
887       bus_config_parser_unref (parser);
888       parser = NULL;
889     }
890
891   /* Here we change our credentials if required,
892    * as soon as we've set up our sockets and pidfile
893    */
894   if (context->user != NULL)
895     {
896       if (!_dbus_change_to_daemon_user (context->user, error))
897         {
898           _DBUS_ASSERT_ERROR_IS_SET (error);
899           goto failed;
900         }
901
902 #ifdef HAVE_SELINUX
903       /* FIXME - why not just put this in full_init() below? */
904       bus_selinux_audit_init ();
905 #endif
906     }
907
908   dbus_server_free_data_slot (&server_data_slot);
909
910   return context;
911
912  failed:
913   if (parser != NULL)
914     bus_config_parser_unref (parser);
915   if (context != NULL)
916     bus_context_unref (context);
917
918   if (server_data_slot >= 0)
919     dbus_server_free_data_slot (&server_data_slot);
920
921   return NULL;
922 }
923
924 dbus_bool_t
925 bus_context_get_id (BusContext       *context,
926                     DBusString       *uuid)
927 {
928   return _dbus_uuid_encode (&context->uuid, uuid);
929 }
930
931 dbus_bool_t
932 bus_context_reload_config (BusContext *context,
933                            DBusError  *error)
934 {
935   BusConfigParser *parser;
936   DBusString config_file;
937   dbus_bool_t ret;
938
939   /* Flush the user database cache */
940   _dbus_flush_caches ();
941
942   ret = FALSE;
943   _dbus_string_init_const (&config_file, context->config_file);
944   parser = bus_config_load (&config_file, TRUE, NULL, error);
945   if (parser == NULL)
946     {
947       _DBUS_ASSERT_ERROR_IS_SET (error);
948       goto failed;
949     }
950
951   if (!process_config_every_time (context, parser, TRUE, error))
952     {
953       _DBUS_ASSERT_ERROR_IS_SET (error);
954       goto failed;
955     }
956   if (!process_config_postinit (context, parser, error))
957     {
958       _DBUS_ASSERT_ERROR_IS_SET (error);
959       goto failed;
960     }
961   ret = TRUE;
962
963   bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Reloaded configuration");
964  failed:
965   if (!ret)
966     bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Unable to reload configuration: %s", error->message);
967   if (parser != NULL)
968     bus_config_parser_unref (parser);
969   return ret;
970 }
971
972 static void
973 shutdown_server (BusContext *context,
974                  DBusServer *server)
975 {
976   if (server == NULL ||
977       !dbus_server_get_is_connected (server))
978     return;
979
980   if (!dbus_server_set_watch_functions (server,
981                                         NULL, NULL, NULL,
982                                         context,
983                                         NULL))
984     _dbus_assert_not_reached ("setting watch functions to NULL failed");
985
986   if (!dbus_server_set_timeout_functions (server,
987                                           NULL, NULL, NULL,
988                                           context,
989                                           NULL))
990     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
991
992   dbus_server_disconnect (server);
993 }
994
995 void
996 bus_context_shutdown (BusContext  *context)
997 {
998   DBusList *link;
999
1000   link = _dbus_list_get_first_link (&context->servers);
1001   while (link != NULL)
1002     {
1003       shutdown_server (context, link->data);
1004
1005       link = _dbus_list_get_next_link (&context->servers, link);
1006     }
1007 }
1008
1009 BusContext *
1010 bus_context_ref (BusContext *context)
1011 {
1012   _dbus_assert (context->refcount > 0);
1013   context->refcount += 1;
1014
1015   return context;
1016 }
1017
1018 void
1019 bus_context_unref (BusContext *context)
1020 {
1021   _dbus_assert (context->refcount > 0);
1022   context->refcount -= 1;
1023
1024   if (context->refcount == 0)
1025     {
1026       DBusList *link;
1027
1028       _dbus_verbose ("Finalizing bus context %p\n", context);
1029
1030       bus_context_shutdown (context);
1031
1032       if (context->connections)
1033         {
1034           bus_connections_unref (context->connections);
1035           context->connections = NULL;
1036         }
1037
1038       if (context->registry)
1039         {
1040           bus_registry_unref (context->registry);
1041           context->registry = NULL;
1042         }
1043
1044       if (context->activation)
1045         {
1046           bus_activation_unref (context->activation);
1047           context->activation = NULL;
1048         }
1049
1050       link = _dbus_list_get_first_link (&context->servers);
1051       while (link != NULL)
1052         {
1053           dbus_server_unref (link->data);
1054
1055           link = _dbus_list_get_next_link (&context->servers, link);
1056         }
1057       _dbus_list_clear (&context->servers);
1058
1059       if (context->policy)
1060         {
1061           bus_policy_unref (context->policy);
1062           context->policy = NULL;
1063         }
1064
1065       if (context->loop)
1066         {
1067           _dbus_loop_unref (context->loop);
1068           context->loop = NULL;
1069         }
1070
1071       if (context->matchmaker)
1072         {
1073           bus_matchmaker_unref (context->matchmaker);
1074           context->matchmaker = NULL;
1075         }
1076
1077       dbus_free (context->config_file);
1078       dbus_free (context->log_prefix);
1079       dbus_free (context->type);
1080       dbus_free (context->address);
1081       dbus_free (context->user);
1082       dbus_free (context->servicehelper);
1083
1084       if (context->pidfile)
1085         {
1086           DBusString u;
1087           _dbus_string_init_const (&u, context->pidfile);
1088
1089           /* Deliberately ignore errors here, since there's not much
1090            * we can do about it, and we're exiting anyways.
1091            */
1092           _dbus_delete_file (&u, NULL);
1093
1094           dbus_free (context->pidfile);
1095         }
1096       dbus_free (context);
1097
1098       dbus_server_free_data_slot (&server_data_slot);
1099     }
1100 }
1101
1102 /* type may be NULL */
1103 const char*
1104 bus_context_get_type (BusContext *context)
1105 {
1106   return context->type;
1107 }
1108
1109 const char*
1110 bus_context_get_address (BusContext *context)
1111 {
1112   return context->address;
1113 }
1114
1115 const char*
1116 bus_context_get_servicehelper (BusContext *context)
1117 {
1118   return context->servicehelper;
1119 }
1120
1121 dbus_bool_t
1122 bus_context_get_systemd_activation (BusContext *context)
1123 {
1124   return context->systemd_activation;
1125 }
1126
1127 BusRegistry*
1128 bus_context_get_registry (BusContext  *context)
1129 {
1130   return context->registry;
1131 }
1132
1133 BusConnections*
1134 bus_context_get_connections (BusContext  *context)
1135 {
1136   return context->connections;
1137 }
1138
1139 BusActivation*
1140 bus_context_get_activation (BusContext  *context)
1141 {
1142   return context->activation;
1143 }
1144
1145 BusMatchmaker*
1146 bus_context_get_matchmaker (BusContext  *context)
1147 {
1148   return context->matchmaker;
1149 }
1150
1151 DBusLoop*
1152 bus_context_get_loop (BusContext *context)
1153 {
1154   return context->loop;
1155 }
1156
1157 dbus_bool_t
1158 bus_context_allow_unix_user (BusContext   *context,
1159                              unsigned long uid)
1160 {
1161   return bus_policy_allow_unix_user (context->policy,
1162                                      uid);
1163 }
1164
1165 /* For now this is never actually called because the default
1166  * DBusConnection behavior of 'same user that owns the bus can connect'
1167  * is all it would do.
1168  */
1169 dbus_bool_t
1170 bus_context_allow_windows_user (BusContext       *context,
1171                                 const char       *windows_sid)
1172 {
1173   return bus_policy_allow_windows_user (context->policy,
1174                                         windows_sid);
1175 }
1176
1177 BusPolicy *
1178 bus_context_get_policy (BusContext *context)
1179 {
1180   return context->policy;
1181 }
1182
1183 BusClientPolicy*
1184 bus_context_create_client_policy (BusContext      *context,
1185                                   DBusConnection  *connection,
1186                                   DBusError       *error)
1187 {
1188   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1189   return bus_policy_create_client_policy (context->policy, connection,
1190                                           error);
1191 }
1192
1193 int
1194 bus_context_get_activation_timeout (BusContext *context)
1195 {
1196
1197   return context->limits.activation_timeout;
1198 }
1199
1200 int
1201 bus_context_get_auth_timeout (BusContext *context)
1202 {
1203   return context->limits.auth_timeout;
1204 }
1205
1206 int
1207 bus_context_get_max_completed_connections (BusContext *context)
1208 {
1209   return context->limits.max_completed_connections;
1210 }
1211
1212 int
1213 bus_context_get_max_incomplete_connections (BusContext *context)
1214 {
1215   return context->limits.max_incomplete_connections;
1216 }
1217
1218 int
1219 bus_context_get_max_connections_per_user (BusContext *context)
1220 {
1221   return context->limits.max_connections_per_user;
1222 }
1223
1224 int
1225 bus_context_get_max_pending_activations (BusContext *context)
1226 {
1227   return context->limits.max_pending_activations;
1228 }
1229
1230 int
1231 bus_context_get_max_services_per_connection (BusContext *context)
1232 {
1233   return context->limits.max_services_per_connection;
1234 }
1235
1236 int
1237 bus_context_get_max_match_rules_per_connection (BusContext *context)
1238 {
1239   return context->limits.max_match_rules_per_connection;
1240 }
1241
1242 int
1243 bus_context_get_max_replies_per_connection (BusContext *context)
1244 {
1245   return context->limits.max_replies_per_connection;
1246 }
1247
1248 int
1249 bus_context_get_reply_timeout (BusContext *context)
1250 {
1251   return context->limits.reply_timeout;
1252 }
1253
1254 void
1255 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...) _DBUS_GNUC_PRINTF (3, 4);
1256
1257 void
1258 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...)
1259 {
1260   va_list args;
1261
1262   if (!context->syslog)
1263     {
1264       /* we're not syslogging; just output to stderr */
1265       va_start (args, msg);
1266       vfprintf (stderr, msg, args);
1267       fprintf (stderr, "\n");
1268       va_end (args);
1269       return;
1270     }
1271
1272   va_start (args, msg);
1273
1274   if (context->log_prefix)
1275     {
1276       DBusString full_msg;
1277
1278       if (!_dbus_string_init (&full_msg))
1279         goto out;
1280       if (!_dbus_string_append (&full_msg, context->log_prefix))
1281         goto oom_out;
1282       if (!_dbus_string_append_printf_valist (&full_msg, msg, args))
1283         goto oom_out;
1284
1285       _dbus_system_log (severity, "%s", _dbus_string_get_const_data (&full_msg));
1286     oom_out:
1287       _dbus_string_free (&full_msg);
1288     }
1289   else
1290     _dbus_system_logv (severity, msg, args);
1291
1292 out:
1293   va_end (args);
1294 }
1295
1296 static inline const char *
1297 nonnull (const char *maybe_null,
1298          const char *if_null)
1299 {
1300   return (maybe_null ? maybe_null : if_null);
1301 }
1302
1303 /*
1304  * Log something about a message, usually that it was rejected.
1305  */
1306 static void
1307 complain_about_message (BusContext     *context,
1308                         const char     *error_name,
1309                         const char     *complaint,
1310                         int             matched_rules,
1311                         DBusMessage    *message,
1312                         DBusConnection *sender,
1313                         DBusConnection *proposed_recipient,
1314                         dbus_bool_t     requested_reply,
1315                         dbus_bool_t     log,
1316                         DBusError      *error)
1317 {
1318   DBusError stack_error = DBUS_ERROR_INIT;
1319   const char *sender_name;
1320   const char *sender_loginfo;
1321   const char *proposed_recipient_loginfo;
1322
1323   if (error == NULL && !log)
1324     return;
1325
1326   if (sender != NULL)
1327     {
1328       sender_name = bus_connection_get_name (sender);
1329       sender_loginfo = bus_connection_get_loginfo (sender);
1330     }
1331   else
1332     {
1333       sender_name = "(unset)";
1334       sender_loginfo = "(bus)";
1335     }
1336
1337   if (proposed_recipient != NULL)
1338     proposed_recipient_loginfo = bus_connection_get_loginfo (proposed_recipient);
1339   else
1340     proposed_recipient_loginfo = "bus";
1341
1342   dbus_set_error (&stack_error, error_name,
1343       "%s, %d matched rules; type=\"%s\", sender=\"%s\" (%s) "
1344       "interface=\"%s\" member=\"%s\" error name=\"%s\" "
1345       "requested_reply=\"%d\" destination=\"%s\" (%s)",
1346       complaint,
1347       matched_rules,
1348       dbus_message_type_to_string (dbus_message_get_type (message)),
1349       sender_name,
1350       sender_loginfo,
1351       nonnull (dbus_message_get_interface (message), "(unset)"),
1352       nonnull (dbus_message_get_member (message), "(unset)"),
1353       nonnull (dbus_message_get_error_name (message), "(unset)"),
1354       requested_reply,
1355       nonnull (dbus_message_get_destination (message), DBUS_SERVICE_DBUS),
1356       proposed_recipient_loginfo);
1357
1358   /* If we hit OOM while setting the error, this will syslog "out of memory"
1359    * which is itself an indication that something is seriously wrong */
1360   if (log)
1361     bus_context_log (context, DBUS_SYSTEM_LOG_SECURITY, "%s",
1362         stack_error.message);
1363
1364   dbus_move_error (&stack_error, error);
1365 }
1366
1367 /*
1368  * addressed_recipient is the recipient specified in the message.
1369  *
1370  * proposed_recipient is the recipient we're considering sending
1371  * to right this second, and may be an eavesdropper.
1372  *
1373  * sender is the sender of the message.
1374  *
1375  * NULL for proposed_recipient or sender definitely means the bus driver.
1376  *
1377  * NULL for addressed_recipient may mean the bus driver, or may mean
1378  * no destination was specified in the message (e.g. a signal).
1379  */
1380 dbus_bool_t
1381 bus_context_check_security_policy (BusContext     *context,
1382                                    BusTransaction *transaction,
1383                                    DBusConnection *sender,
1384                                    DBusConnection *addressed_recipient,
1385                                    DBusConnection *proposed_recipient,
1386                                    DBusMessage    *message,
1387                                    DBusError      *error)
1388 {
1389   const char *dest;
1390   BusClientPolicy *sender_policy;
1391   BusClientPolicy *recipient_policy;
1392   dbus_int32_t toggles;
1393   dbus_bool_t log;
1394   int type;
1395   dbus_bool_t requested_reply;
1396   const char *sender_name;
1397   const char *sender_loginfo;
1398   const char *proposed_recipient_loginfo;
1399
1400   type = dbus_message_get_type (message);
1401   dest = dbus_message_get_destination (message);
1402
1403   /* dispatch.c was supposed to ensure these invariants */
1404   _dbus_assert (dest != NULL ||
1405                 type == DBUS_MESSAGE_TYPE_SIGNAL ||
1406                 (sender == NULL && !bus_connection_is_active (proposed_recipient)));
1407   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
1408                 addressed_recipient != NULL ||
1409                 strcmp (dest, DBUS_SERVICE_DBUS) == 0);
1410
1411   switch (type)
1412     {
1413     case DBUS_MESSAGE_TYPE_METHOD_CALL:
1414     case DBUS_MESSAGE_TYPE_SIGNAL:
1415     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
1416     case DBUS_MESSAGE_TYPE_ERROR:
1417       break;
1418
1419     default:
1420       _dbus_verbose ("security check disallowing message of unknown type %d\n",
1421                      type);
1422
1423       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1424                       "Message bus will not accept messages of unknown type\n");
1425
1426       return FALSE;
1427     }
1428
1429   requested_reply = FALSE;
1430
1431   if (sender != NULL)
1432     {
1433       /* First verify the SELinux access controls.  If allowed then
1434        * go on with the standard checks.
1435        */
1436       if (!bus_selinux_allows_send (sender, proposed_recipient,
1437                                     dbus_message_type_to_string (dbus_message_get_type (message)),
1438                                     dbus_message_get_interface (message),
1439                                     dbus_message_get_member (message),
1440                                     dbus_message_get_error_name (message),
1441                                     dest ? dest : DBUS_SERVICE_DBUS, error))
1442         {
1443           if (error != NULL && !dbus_error_is_set (error))
1444             {
1445               /* don't syslog this, just set the error: avc_has_perm should
1446                * have already written to either the audit log or syslog */
1447               complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1448                   "An SELinux policy prevents this sender from sending this "
1449                   "message to this recipient",
1450                   0, message, sender, proposed_recipient, FALSE, FALSE, error);
1451               _dbus_verbose ("SELinux security check denying send to service\n");
1452             }
1453
1454           return FALSE;
1455         }
1456
1457       if (bus_connection_is_active (sender))
1458         {
1459           sender_policy = bus_connection_get_policy (sender);
1460           _dbus_assert (sender_policy != NULL);
1461
1462           /* Fill in requested_reply variable with TRUE if this is a
1463            * reply and the reply was pending.
1464            */
1465           if (dbus_message_get_reply_serial (message) != 0)
1466             {
1467               if (proposed_recipient != NULL /* not to the bus driver */ &&
1468                   addressed_recipient == proposed_recipient /* not eavesdropping */)
1469                 {
1470                   DBusError error2;
1471
1472                   dbus_error_init (&error2);
1473                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
1474                                                                  transaction,
1475                                                                  sender, addressed_recipient, message,
1476                                                                  &error2);
1477                   if (dbus_error_is_set (&error2))
1478                     {
1479                       dbus_move_error (&error2, error);
1480                       return FALSE;
1481                     }
1482                 }
1483             }
1484         }
1485       else
1486         {
1487           /* Policy for inactive connections is that they can only send
1488            * the hello message to the bus driver
1489            */
1490           if (proposed_recipient == NULL &&
1491               dbus_message_is_method_call (message,
1492                                            DBUS_INTERFACE_DBUS,
1493                                            "Hello"))
1494             {
1495               _dbus_verbose ("security check allowing %s message\n",
1496                              "Hello");
1497               return TRUE;
1498             }
1499           else
1500             {
1501               _dbus_verbose ("security check disallowing non-%s message\n",
1502                              "Hello");
1503
1504               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1505                               "Client tried to send a message other than %s without being registered",
1506                               "Hello");
1507
1508               return FALSE;
1509             }
1510         }
1511     }
1512   else
1513     {
1514       sender_policy = NULL;
1515
1516       /* If the sender is the bus driver, we assume any reply was a
1517        * requested reply as bus driver won't send bogus ones
1518        */
1519       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1520           dbus_message_get_reply_serial (message) != 0)
1521         requested_reply = TRUE;
1522     }
1523
1524   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1525                 (sender == NULL && sender_policy == NULL));
1526
1527   if (proposed_recipient != NULL)
1528     {
1529       /* only the bus driver can send to an inactive recipient (as it
1530        * owns no services, so other apps can't address it). Inactive
1531        * recipients can receive any message.
1532        */
1533       if (bus_connection_is_active (proposed_recipient))
1534         {
1535           recipient_policy = bus_connection_get_policy (proposed_recipient);
1536           _dbus_assert (recipient_policy != NULL);
1537         }
1538       else if (sender == NULL)
1539         {
1540           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1541           recipient_policy = NULL;
1542         }
1543       else
1544         {
1545           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus\n");
1546           recipient_policy = NULL;
1547         }
1548     }
1549   else
1550     recipient_policy = NULL;
1551
1552   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1553                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1554                 (proposed_recipient == NULL && recipient_policy == NULL));
1555
1556   log = FALSE;
1557   if (sender_policy &&
1558       !bus_client_policy_check_can_send (sender_policy,
1559                                          context->registry,
1560                                          requested_reply,
1561                                          proposed_recipient,
1562                                          message, &toggles, &log))
1563     {
1564       const char *msg = "Rejected send message, %d matched rules; "
1565                         "type=\"%s\", sender=\"%s\" (%s) interface=\"%s\" member=\"%s\" error name=\"%s\" requested_reply=%d destination=\"%s\" (%s))";
1566
1567       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1568           "Rejected send message", toggles,
1569           message, sender, proposed_recipient, requested_reply,
1570           (addressed_recipient == proposed_recipient), error);
1571       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1572       return FALSE;
1573     }
1574
1575   if (log)
1576     {
1577       /* We want to drop this message, and are only not doing so for backwards
1578        * compatibility. */
1579       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1580           "Would reject message", toggles,
1581           message, sender, proposed_recipient, requested_reply,
1582           TRUE, NULL);
1583     }
1584
1585   if (recipient_policy &&
1586       !bus_client_policy_check_can_receive (recipient_policy,
1587                                             context->registry,
1588                                             requested_reply,
1589                                             sender,
1590                                             addressed_recipient, proposed_recipient,
1591                                             message, &toggles))
1592     {
1593       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1594           "Rejected receive message", toggles,
1595           message, sender, proposed_recipient, requested_reply,
1596           (addressed_recipient == proposed_recipient), NULL);
1597       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1598       return FALSE;
1599     }
1600
1601   /* See if limits on size have been exceeded */
1602   if (proposed_recipient &&
1603       ((dbus_connection_get_outgoing_size (proposed_recipient) > context->limits.max_outgoing_bytes) ||
1604        (dbus_connection_get_outgoing_unix_fds (proposed_recipient) > context->limits.max_outgoing_unix_fds)))
1605     {
1606       complain_about_message (context, DBUS_ERROR_LIMITS_EXCEEDED,
1607           "Rejected: destination has a full message queue",
1608           0, message, sender, proposed_recipient, requested_reply, TRUE,
1609           error);
1610       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1611       return FALSE;
1612     }
1613
1614   /* Record that we will allow a reply here in the future (don't
1615    * bother if the recipient is the bus or this is an eavesdropping
1616    * connection). Only the addressed recipient may reply.
1617    */
1618   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL &&
1619       sender &&
1620       addressed_recipient &&
1621       addressed_recipient == proposed_recipient && /* not eavesdropping */
1622       !bus_connections_expect_reply (bus_connection_get_connections (sender),
1623                                      transaction,
1624                                      sender, addressed_recipient,
1625                                      message, error))
1626     {
1627       _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1628       return FALSE;
1629     }
1630
1631   _dbus_verbose ("security policy allowing message\n");
1632   return TRUE;
1633 }