Merge branch 'dbus-1.4'
[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   char *addr;
485   const char *servicehelper;
486   char *s;
487
488   dbus_bool_t retval;
489
490   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
491
492   addr = NULL;
493   retval = FALSE;
494
495   if (!_dbus_string_init (&full_address))
496     {
497       BUS_SET_OOM (error);
498       return FALSE;
499     }
500
501   /* get our limits and timeout lengths */
502   bus_config_parser_get_limits (parser, &context->limits);
503
504   if (context->policy)
505     bus_policy_unref (context->policy);
506   context->policy = bus_config_parser_steal_policy (parser);
507   _dbus_assert (context->policy != NULL);
508
509   /* We have to build the address backward, so that
510    * <listen> later in the config file have priority
511    */
512   link = _dbus_list_get_last_link (&context->servers);
513   while (link != NULL)
514     {
515       addr = dbus_server_get_address (link->data);
516       if (addr == NULL)
517         {
518           BUS_SET_OOM (error);
519           goto failed;
520         }
521
522       if (_dbus_string_get_length (&full_address) > 0)
523         {
524           if (!_dbus_string_append (&full_address, ";"))
525             {
526               BUS_SET_OOM (error);
527               goto failed;
528             }
529         }
530
531       if (!_dbus_string_append (&full_address, addr))
532         {
533           BUS_SET_OOM (error);
534           goto failed;
535         }
536
537       dbus_free (addr);
538       addr = NULL;
539
540       link = _dbus_list_get_prev_link (&context->servers, link);
541     }
542
543   if (is_reload)
544     dbus_free (context->address);
545
546   if (!_dbus_string_copy_data (&full_address, &context->address))
547     {
548       BUS_SET_OOM (error);
549       goto failed;
550     }
551
552   /* get the service directories */
553   dirs = bus_config_parser_get_service_dirs (parser);
554
555   /* and the service helper */
556   servicehelper = bus_config_parser_get_servicehelper (parser);
557
558   s = _dbus_strdup(servicehelper);
559   if (s == NULL && servicehelper != NULL)
560     {
561       BUS_SET_OOM (error);
562       goto failed;
563     }
564   else
565     {
566       dbus_free(context->servicehelper);
567       context->servicehelper = s;
568     }
569
570   /* Create activation subsystem */
571   if (context->activation)
572     {
573       if (!bus_activation_reload (context->activation, &full_address, dirs, error))
574         goto failed;
575     }
576   else
577     {
578       context->activation = bus_activation_new (context, &full_address, dirs, error);
579     }
580
581   if (context->activation == NULL)
582     {
583       _DBUS_ASSERT_ERROR_IS_SET (error);
584       goto failed;
585     }
586
587   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
588   retval = TRUE;
589
590  failed:
591   _dbus_string_free (&full_address);
592
593   if (addr)
594     dbus_free (addr);
595
596   return retval;
597 }
598
599 static dbus_bool_t
600 list_concat_new (DBusList **a,
601                  DBusList **b,
602                  DBusList **result)
603 {
604   DBusList *link;
605
606   *result = NULL;
607
608   for (link = _dbus_list_get_first_link (a); link; link = _dbus_list_get_next_link (a, link))
609     {
610       if (!_dbus_list_append (result, link->data))
611         goto oom;
612     }
613   for (link = _dbus_list_get_first_link (b); link; link = _dbus_list_get_next_link (b, link))
614     {
615       if (!_dbus_list_append (result, link->data))
616         goto oom;
617     }
618
619   return TRUE;
620 oom:
621   _dbus_list_clear (result);
622   return FALSE;
623 }
624
625 static void
626 raise_file_descriptor_limit (BusContext      *context)
627 {
628
629   /* I just picked this out of thin air; we need some extra
630    * descriptors for things like any internal pipes we create,
631    * inotify, connections to SELinux, etc.
632    */
633   unsigned int arbitrary_extra_fds = 32;
634   unsigned int limit;
635
636   limit = context->limits.max_completed_connections +
637     context->limits.max_incomplete_connections
638     + arbitrary_extra_fds;
639
640   _dbus_request_file_descriptor_limit (limit);
641 }
642
643 static dbus_bool_t
644 process_config_postinit (BusContext      *context,
645                          BusConfigParser *parser,
646                          DBusError       *error)
647 {
648   DBusHashTable *service_context_table;
649   DBusList *watched_dirs = NULL;
650
651   raise_file_descriptor_limit (context);
652
653   service_context_table = bus_config_parser_steal_service_context_table (parser);
654   if (!bus_registry_set_service_context_table (context->registry,
655                                                service_context_table))
656     {
657       BUS_SET_OOM (error);
658       return FALSE;
659     }
660
661   _dbus_hash_table_unref (service_context_table);
662
663   /* We need to monitor both the configuration directories and directories
664    * containing .service files.
665    */
666   if (!list_concat_new (bus_config_parser_get_conf_dirs (parser),
667                         bus_config_parser_get_service_dirs (parser),
668                         &watched_dirs))
669     {
670       BUS_SET_OOM (error);
671       return FALSE;
672     }
673
674   bus_set_watched_dirs (context, &watched_dirs);
675
676   _dbus_list_clear (&watched_dirs);
677
678   return TRUE;
679 }
680
681 BusContext*
682 bus_context_new (const DBusString *config_file,
683                  ForceForkSetting  force_fork,
684                  DBusPipe         *print_addr_pipe,
685                  DBusPipe         *print_pid_pipe,
686                  const DBusString *address,
687                  dbus_bool_t      systemd_activation,
688                  DBusError        *error)
689 {
690   BusContext *context;
691   BusConfigParser *parser;
692
693   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
694
695   context = NULL;
696   parser = NULL;
697
698   if (!dbus_server_allocate_data_slot (&server_data_slot))
699     {
700       BUS_SET_OOM (error);
701       return NULL;
702     }
703
704   context = dbus_new0 (BusContext, 1);
705   if (context == NULL)
706     {
707       BUS_SET_OOM (error);
708       goto failed;
709     }
710   context->refcount = 1;
711
712   _dbus_generate_uuid (&context->uuid);
713
714   if (!_dbus_string_copy_data (config_file, &context->config_file))
715     {
716       BUS_SET_OOM (error);
717       goto failed;
718     }
719
720   context->loop = _dbus_loop_new ();
721   if (context->loop == NULL)
722     {
723       BUS_SET_OOM (error);
724       goto failed;
725     }
726
727   context->registry = bus_registry_new (context);
728   if (context->registry == NULL)
729     {
730       BUS_SET_OOM (error);
731       goto failed;
732     }
733
734   parser = bus_config_load (config_file, TRUE, NULL, error);
735   if (parser == NULL)
736     {
737       _DBUS_ASSERT_ERROR_IS_SET (error);
738       goto failed;
739     }
740
741   if (!process_config_first_time_only (context, parser, address, systemd_activation, error))
742     {
743       _DBUS_ASSERT_ERROR_IS_SET (error);
744       goto failed;
745     }
746   if (!process_config_every_time (context, parser, FALSE, error))
747     {
748       _DBUS_ASSERT_ERROR_IS_SET (error);
749       goto failed;
750     }
751
752   /* we need another ref of the server data slot for the context
753    * to own
754    */
755   if (!dbus_server_allocate_data_slot (&server_data_slot))
756     _dbus_assert_not_reached ("second ref of server data slot failed");
757
758   /* Note that we don't know whether the print_addr_pipe is
759    * one of the sockets we're using to listen on, or some
760    * other random thing. But I think the answer is "don't do
761    * that then"
762    */
763   if (print_addr_pipe != NULL && _dbus_pipe_is_valid (print_addr_pipe))
764     {
765       DBusString addr;
766       const char *a = bus_context_get_address (context);
767       int bytes;
768
769       _dbus_assert (a != NULL);
770       if (!_dbus_string_init (&addr))
771         {
772           BUS_SET_OOM (error);
773           goto failed;
774         }
775
776       if (!_dbus_string_append (&addr, a) ||
777           !_dbus_string_append (&addr, "\n"))
778         {
779           _dbus_string_free (&addr);
780           BUS_SET_OOM (error);
781           goto failed;
782         }
783
784       bytes = _dbus_string_get_length (&addr);
785       if (_dbus_pipe_write (print_addr_pipe, &addr, 0, bytes, error) != bytes)
786         {
787           /* pipe write returns an error on failure but not short write */
788           if (error != NULL && !dbus_error_is_set (error))
789             {
790               dbus_set_error (error, DBUS_ERROR_FAILED,
791                               "Printing message bus address: did not write all bytes\n");
792             }
793           _dbus_string_free (&addr);
794           goto failed;
795         }
796
797       if (!_dbus_pipe_is_stdout_or_stderr (print_addr_pipe))
798         _dbus_pipe_close (print_addr_pipe, NULL);
799
800       _dbus_string_free (&addr);
801     }
802
803   context->connections = bus_connections_new (context);
804   if (context->connections == NULL)
805     {
806       BUS_SET_OOM (error);
807       goto failed;
808     }
809
810   context->matchmaker = bus_matchmaker_new ();
811   if (context->matchmaker == NULL)
812     {
813       BUS_SET_OOM (error);
814       goto failed;
815     }
816
817   /* check user before we fork */
818   if (context->user != NULL)
819     {
820       if (!_dbus_verify_daemon_user (context->user))
821         {
822           dbus_set_error (error, DBUS_ERROR_FAILED,
823                           "Could not get UID and GID for username \"%s\"",
824                           context->user);
825           goto failed;
826         }
827     }
828
829   /* Now become a daemon if appropriate and write out pid file in any case */
830   {
831     DBusString u;
832
833     if (context->pidfile)
834       _dbus_string_init_const (&u, context->pidfile);
835
836     if ((force_fork != FORK_NEVER && context->fork) || force_fork == FORK_ALWAYS)
837       {
838         _dbus_verbose ("Forking and becoming daemon\n");
839
840         if (!_dbus_become_daemon (context->pidfile ? &u : NULL,
841                                   print_pid_pipe,
842                                   error,
843                                   context->keep_umask))
844           {
845             _DBUS_ASSERT_ERROR_IS_SET (error);
846             goto failed;
847           }
848       }
849     else
850       {
851         _dbus_verbose ("Fork not requested\n");
852
853         /* Need to write PID file and to PID pipe for ourselves,
854          * not for the child process. This is a no-op if the pidfile
855          * is NULL and print_pid_pipe is NULL.
856          */
857         if (!_dbus_write_pid_to_file_and_pipe (context->pidfile ? &u : NULL,
858                                                print_pid_pipe,
859                                                _dbus_getpid (),
860                                                error))
861           {
862             _DBUS_ASSERT_ERROR_IS_SET (error);
863             goto failed;
864           }
865       }
866   }
867
868   if (print_pid_pipe && _dbus_pipe_is_valid (print_pid_pipe) &&
869       !_dbus_pipe_is_stdout_or_stderr (print_pid_pipe))
870     _dbus_pipe_close (print_pid_pipe, NULL);
871
872   if (!bus_selinux_full_init ())
873     {
874       bus_context_log (context, DBUS_SYSTEM_LOG_FATAL, "SELinux enabled but AVC initialization failed; check system log\n");
875     }
876
877   if (!process_config_postinit (context, parser, error))
878     {
879       _DBUS_ASSERT_ERROR_IS_SET (error);
880       goto failed;
881     }
882
883   if (parser != NULL)
884     {
885       bus_config_parser_unref (parser);
886       parser = NULL;
887     }
888
889   /* Here we change our credentials if required,
890    * as soon as we've set up our sockets and pidfile
891    */
892   if (context->user != NULL)
893     {
894       if (!_dbus_change_to_daemon_user (context->user, error))
895         {
896           _DBUS_ASSERT_ERROR_IS_SET (error);
897           goto failed;
898         }
899
900 #ifdef HAVE_SELINUX
901       /* FIXME - why not just put this in full_init() below? */
902       bus_selinux_audit_init ();
903 #endif
904     }
905
906   dbus_server_free_data_slot (&server_data_slot);
907
908   return context;
909
910  failed:
911   if (parser != NULL)
912     bus_config_parser_unref (parser);
913   if (context != NULL)
914     bus_context_unref (context);
915
916   if (server_data_slot >= 0)
917     dbus_server_free_data_slot (&server_data_slot);
918
919   return NULL;
920 }
921
922 dbus_bool_t
923 bus_context_get_id (BusContext       *context,
924                     DBusString       *uuid)
925 {
926   return _dbus_uuid_encode (&context->uuid, uuid);
927 }
928
929 dbus_bool_t
930 bus_context_reload_config (BusContext *context,
931                            DBusError  *error)
932 {
933   BusConfigParser *parser;
934   DBusString config_file;
935   dbus_bool_t ret;
936
937   /* Flush the user database cache */
938   _dbus_flush_caches ();
939
940   ret = FALSE;
941   _dbus_string_init_const (&config_file, context->config_file);
942   parser = bus_config_load (&config_file, TRUE, NULL, error);
943   if (parser == NULL)
944     {
945       _DBUS_ASSERT_ERROR_IS_SET (error);
946       goto failed;
947     }
948
949   if (!process_config_every_time (context, parser, TRUE, error))
950     {
951       _DBUS_ASSERT_ERROR_IS_SET (error);
952       goto failed;
953     }
954   if (!process_config_postinit (context, parser, error))
955     {
956       _DBUS_ASSERT_ERROR_IS_SET (error);
957       goto failed;
958     }
959   ret = TRUE;
960
961   bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Reloaded configuration");
962  failed:
963   if (!ret)
964     bus_context_log (context, DBUS_SYSTEM_LOG_INFO, "Unable to reload configuration: %s", error->message);
965   if (parser != NULL)
966     bus_config_parser_unref (parser);
967   return ret;
968 }
969
970 static void
971 shutdown_server (BusContext *context,
972                  DBusServer *server)
973 {
974   if (server == NULL ||
975       !dbus_server_get_is_connected (server))
976     return;
977
978   if (!dbus_server_set_watch_functions (server,
979                                         NULL, NULL, NULL,
980                                         context,
981                                         NULL))
982     _dbus_assert_not_reached ("setting watch functions to NULL failed");
983
984   if (!dbus_server_set_timeout_functions (server,
985                                           NULL, NULL, NULL,
986                                           context,
987                                           NULL))
988     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
989
990   dbus_server_disconnect (server);
991 }
992
993 void
994 bus_context_shutdown (BusContext  *context)
995 {
996   DBusList *link;
997
998   link = _dbus_list_get_first_link (&context->servers);
999   while (link != NULL)
1000     {
1001       shutdown_server (context, link->data);
1002
1003       link = _dbus_list_get_next_link (&context->servers, link);
1004     }
1005 }
1006
1007 BusContext *
1008 bus_context_ref (BusContext *context)
1009 {
1010   _dbus_assert (context->refcount > 0);
1011   context->refcount += 1;
1012
1013   return context;
1014 }
1015
1016 void
1017 bus_context_unref (BusContext *context)
1018 {
1019   _dbus_assert (context->refcount > 0);
1020   context->refcount -= 1;
1021
1022   if (context->refcount == 0)
1023     {
1024       DBusList *link;
1025
1026       _dbus_verbose ("Finalizing bus context %p\n", context);
1027
1028       bus_context_shutdown (context);
1029
1030       if (context->connections)
1031         {
1032           bus_connections_unref (context->connections);
1033           context->connections = NULL;
1034         }
1035
1036       if (context->registry)
1037         {
1038           bus_registry_unref (context->registry);
1039           context->registry = NULL;
1040         }
1041
1042       if (context->activation)
1043         {
1044           bus_activation_unref (context->activation);
1045           context->activation = NULL;
1046         }
1047
1048       link = _dbus_list_get_first_link (&context->servers);
1049       while (link != NULL)
1050         {
1051           dbus_server_unref (link->data);
1052
1053           link = _dbus_list_get_next_link (&context->servers, link);
1054         }
1055       _dbus_list_clear (&context->servers);
1056
1057       if (context->policy)
1058         {
1059           bus_policy_unref (context->policy);
1060           context->policy = NULL;
1061         }
1062
1063       if (context->loop)
1064         {
1065           _dbus_loop_unref (context->loop);
1066           context->loop = NULL;
1067         }
1068
1069       if (context->matchmaker)
1070         {
1071           bus_matchmaker_unref (context->matchmaker);
1072           context->matchmaker = NULL;
1073         }
1074
1075       dbus_free (context->config_file);
1076       dbus_free (context->log_prefix);
1077       dbus_free (context->type);
1078       dbus_free (context->address);
1079       dbus_free (context->user);
1080       dbus_free (context->servicehelper);
1081
1082       if (context->pidfile)
1083         {
1084           DBusString u;
1085           _dbus_string_init_const (&u, context->pidfile);
1086
1087           /* Deliberately ignore errors here, since there's not much
1088            * we can do about it, and we're exiting anyways.
1089            */
1090           _dbus_delete_file (&u, NULL);
1091
1092           dbus_free (context->pidfile);
1093         }
1094       dbus_free (context);
1095
1096       dbus_server_free_data_slot (&server_data_slot);
1097     }
1098 }
1099
1100 /* type may be NULL */
1101 const char*
1102 bus_context_get_type (BusContext *context)
1103 {
1104   return context->type;
1105 }
1106
1107 const char*
1108 bus_context_get_address (BusContext *context)
1109 {
1110   return context->address;
1111 }
1112
1113 const char*
1114 bus_context_get_servicehelper (BusContext *context)
1115 {
1116   return context->servicehelper;
1117 }
1118
1119 dbus_bool_t
1120 bus_context_get_systemd_activation (BusContext *context)
1121 {
1122   return context->systemd_activation;
1123 }
1124
1125 BusRegistry*
1126 bus_context_get_registry (BusContext  *context)
1127 {
1128   return context->registry;
1129 }
1130
1131 BusConnections*
1132 bus_context_get_connections (BusContext  *context)
1133 {
1134   return context->connections;
1135 }
1136
1137 BusActivation*
1138 bus_context_get_activation (BusContext  *context)
1139 {
1140   return context->activation;
1141 }
1142
1143 BusMatchmaker*
1144 bus_context_get_matchmaker (BusContext  *context)
1145 {
1146   return context->matchmaker;
1147 }
1148
1149 DBusLoop*
1150 bus_context_get_loop (BusContext *context)
1151 {
1152   return context->loop;
1153 }
1154
1155 dbus_bool_t
1156 bus_context_allow_unix_user (BusContext   *context,
1157                              unsigned long uid)
1158 {
1159   return bus_policy_allow_unix_user (context->policy,
1160                                      uid);
1161 }
1162
1163 /* For now this is never actually called because the default
1164  * DBusConnection behavior of 'same user that owns the bus can connect'
1165  * is all it would do.
1166  */
1167 dbus_bool_t
1168 bus_context_allow_windows_user (BusContext       *context,
1169                                 const char       *windows_sid)
1170 {
1171   return bus_policy_allow_windows_user (context->policy,
1172                                         windows_sid);
1173 }
1174
1175 BusPolicy *
1176 bus_context_get_policy (BusContext *context)
1177 {
1178   return context->policy;
1179 }
1180
1181 BusClientPolicy*
1182 bus_context_create_client_policy (BusContext      *context,
1183                                   DBusConnection  *connection,
1184                                   DBusError       *error)
1185 {
1186   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1187   return bus_policy_create_client_policy (context->policy, connection,
1188                                           error);
1189 }
1190
1191 int
1192 bus_context_get_activation_timeout (BusContext *context)
1193 {
1194
1195   return context->limits.activation_timeout;
1196 }
1197
1198 int
1199 bus_context_get_auth_timeout (BusContext *context)
1200 {
1201   return context->limits.auth_timeout;
1202 }
1203
1204 int
1205 bus_context_get_max_completed_connections (BusContext *context)
1206 {
1207   return context->limits.max_completed_connections;
1208 }
1209
1210 int
1211 bus_context_get_max_incomplete_connections (BusContext *context)
1212 {
1213   return context->limits.max_incomplete_connections;
1214 }
1215
1216 int
1217 bus_context_get_max_connections_per_user (BusContext *context)
1218 {
1219   return context->limits.max_connections_per_user;
1220 }
1221
1222 int
1223 bus_context_get_max_pending_activations (BusContext *context)
1224 {
1225   return context->limits.max_pending_activations;
1226 }
1227
1228 int
1229 bus_context_get_max_services_per_connection (BusContext *context)
1230 {
1231   return context->limits.max_services_per_connection;
1232 }
1233
1234 int
1235 bus_context_get_max_match_rules_per_connection (BusContext *context)
1236 {
1237   return context->limits.max_match_rules_per_connection;
1238 }
1239
1240 int
1241 bus_context_get_max_replies_per_connection (BusContext *context)
1242 {
1243   return context->limits.max_replies_per_connection;
1244 }
1245
1246 int
1247 bus_context_get_reply_timeout (BusContext *context)
1248 {
1249   return context->limits.reply_timeout;
1250 }
1251
1252 void
1253 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...) _DBUS_GNUC_PRINTF (3, 4);
1254
1255 void
1256 bus_context_log (BusContext *context, DBusSystemLogSeverity severity, const char *msg, ...)
1257 {
1258   va_list args;
1259
1260   if (!context->syslog)
1261     {
1262       /* we're not syslogging; just output to stderr */
1263       va_start (args, msg);
1264       vfprintf (stderr, msg, args);
1265       fprintf (stderr, "\n");
1266       va_end (args);
1267       return;
1268     }
1269
1270   va_start (args, msg);
1271
1272   if (context->log_prefix)
1273     {
1274       DBusString full_msg;
1275
1276       if (!_dbus_string_init (&full_msg))
1277         goto out;
1278       if (!_dbus_string_append (&full_msg, context->log_prefix))
1279         goto oom_out;
1280       if (!_dbus_string_append_printf_valist (&full_msg, msg, args))
1281         goto oom_out;
1282
1283       _dbus_system_log (severity, "%s", _dbus_string_get_const_data (&full_msg));
1284     oom_out:
1285       _dbus_string_free (&full_msg);
1286     }
1287   else
1288     _dbus_system_logv (severity, msg, args);
1289
1290 out:
1291   va_end (args);
1292 }
1293
1294 static inline const char *
1295 nonnull (const char *maybe_null,
1296          const char *if_null)
1297 {
1298   return (maybe_null ? maybe_null : if_null);
1299 }
1300
1301 /*
1302  * Log something about a message, usually that it was rejected.
1303  */
1304 static void
1305 complain_about_message (BusContext     *context,
1306                         const char     *error_name,
1307                         const char     *complaint,
1308                         int             matched_rules,
1309                         DBusMessage    *message,
1310                         DBusConnection *sender,
1311                         DBusConnection *proposed_recipient,
1312                         dbus_bool_t     requested_reply,
1313                         dbus_bool_t     log,
1314                         DBusError      *error)
1315 {
1316   DBusError stack_error = DBUS_ERROR_INIT;
1317   const char *sender_name;
1318   const char *sender_loginfo;
1319   const char *proposed_recipient_loginfo;
1320
1321   if (error == NULL && !log)
1322     return;
1323
1324   if (sender != NULL)
1325     {
1326       sender_name = bus_connection_get_name (sender);
1327       sender_loginfo = bus_connection_get_loginfo (sender);
1328     }
1329   else
1330     {
1331       sender_name = "(unset)";
1332       sender_loginfo = "(bus)";
1333     }
1334
1335   if (proposed_recipient != NULL)
1336     proposed_recipient_loginfo = bus_connection_get_loginfo (proposed_recipient);
1337   else
1338     proposed_recipient_loginfo = "bus";
1339
1340   dbus_set_error (&stack_error, error_name,
1341       "%s, %d matched rules; type=\"%s\", sender=\"%s\" (%s) "
1342       "interface=\"%s\" member=\"%s\" error name=\"%s\" "
1343       "requested_reply=\"%d\" destination=\"%s\" (%s)",
1344       complaint,
1345       matched_rules,
1346       dbus_message_type_to_string (dbus_message_get_type (message)),
1347       sender_name,
1348       sender_loginfo,
1349       nonnull (dbus_message_get_interface (message), "(unset)"),
1350       nonnull (dbus_message_get_member (message), "(unset)"),
1351       nonnull (dbus_message_get_error_name (message), "(unset)"),
1352       requested_reply,
1353       nonnull (dbus_message_get_destination (message), DBUS_SERVICE_DBUS),
1354       proposed_recipient_loginfo);
1355
1356   /* If we hit OOM while setting the error, this will syslog "out of memory"
1357    * which is itself an indication that something is seriously wrong */
1358   if (log)
1359     bus_context_log (context, DBUS_SYSTEM_LOG_SECURITY, "%s",
1360         stack_error.message);
1361
1362   dbus_move_error (&stack_error, error);
1363 }
1364
1365 /*
1366  * addressed_recipient is the recipient specified in the message.
1367  *
1368  * proposed_recipient is the recipient we're considering sending
1369  * to right this second, and may be an eavesdropper.
1370  *
1371  * sender is the sender of the message.
1372  *
1373  * NULL for proposed_recipient or sender definitely means the bus driver.
1374  *
1375  * NULL for addressed_recipient may mean the bus driver, or may mean
1376  * no destination was specified in the message (e.g. a signal).
1377  */
1378 dbus_bool_t
1379 bus_context_check_security_policy (BusContext     *context,
1380                                    BusTransaction *transaction,
1381                                    DBusConnection *sender,
1382                                    DBusConnection *addressed_recipient,
1383                                    DBusConnection *proposed_recipient,
1384                                    DBusMessage    *message,
1385                                    DBusError      *error)
1386 {
1387   const char *dest;
1388   BusClientPolicy *sender_policy;
1389   BusClientPolicy *recipient_policy;
1390   dbus_int32_t toggles;
1391   dbus_bool_t log;
1392   int type;
1393   dbus_bool_t requested_reply;
1394
1395   type = dbus_message_get_type (message);
1396   dest = dbus_message_get_destination (message);
1397
1398   /* dispatch.c was supposed to ensure these invariants */
1399   _dbus_assert (dest != NULL ||
1400                 type == DBUS_MESSAGE_TYPE_SIGNAL ||
1401                 (sender == NULL && !bus_connection_is_active (proposed_recipient)));
1402   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
1403                 addressed_recipient != NULL ||
1404                 strcmp (dest, DBUS_SERVICE_DBUS) == 0);
1405
1406   switch (type)
1407     {
1408     case DBUS_MESSAGE_TYPE_METHOD_CALL:
1409     case DBUS_MESSAGE_TYPE_SIGNAL:
1410     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
1411     case DBUS_MESSAGE_TYPE_ERROR:
1412       break;
1413
1414     default:
1415       _dbus_verbose ("security check disallowing message of unknown type %d\n",
1416                      type);
1417
1418       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1419                       "Message bus will not accept messages of unknown type\n");
1420
1421       return FALSE;
1422     }
1423
1424   requested_reply = FALSE;
1425
1426   if (sender != NULL)
1427     {
1428       /* First verify the SELinux access controls.  If allowed then
1429        * go on with the standard checks.
1430        */
1431       if (!bus_selinux_allows_send (sender, proposed_recipient,
1432                                     dbus_message_type_to_string (dbus_message_get_type (message)),
1433                                     dbus_message_get_interface (message),
1434                                     dbus_message_get_member (message),
1435                                     dbus_message_get_error_name (message),
1436                                     dest ? dest : DBUS_SERVICE_DBUS, error))
1437         {
1438           if (error != NULL && !dbus_error_is_set (error))
1439             {
1440               /* don't syslog this, just set the error: avc_has_perm should
1441                * have already written to either the audit log or syslog */
1442               complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1443                   "An SELinux policy prevents this sender from sending this "
1444                   "message to this recipient",
1445                   0, message, sender, proposed_recipient, FALSE, FALSE, error);
1446               _dbus_verbose ("SELinux security check denying send to service\n");
1447             }
1448
1449           return FALSE;
1450         }
1451
1452       if (bus_connection_is_active (sender))
1453         {
1454           sender_policy = bus_connection_get_policy (sender);
1455           _dbus_assert (sender_policy != NULL);
1456
1457           /* Fill in requested_reply variable with TRUE if this is a
1458            * reply and the reply was pending.
1459            */
1460           if (dbus_message_get_reply_serial (message) != 0)
1461             {
1462               if (proposed_recipient != NULL /* not to the bus driver */ &&
1463                   addressed_recipient == proposed_recipient /* not eavesdropping */)
1464                 {
1465                   DBusError error2;
1466
1467                   dbus_error_init (&error2);
1468                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
1469                                                                  transaction,
1470                                                                  sender, addressed_recipient, message,
1471                                                                  &error2);
1472                   if (dbus_error_is_set (&error2))
1473                     {
1474                       dbus_move_error (&error2, error);
1475                       return FALSE;
1476                     }
1477                 }
1478             }
1479         }
1480       else
1481         {
1482           /* Policy for inactive connections is that they can only send
1483            * the hello message to the bus driver
1484            */
1485           if (proposed_recipient == NULL &&
1486               dbus_message_is_method_call (message,
1487                                            DBUS_INTERFACE_DBUS,
1488                                            "Hello"))
1489             {
1490               _dbus_verbose ("security check allowing %s message\n",
1491                              "Hello");
1492               return TRUE;
1493             }
1494           else
1495             {
1496               _dbus_verbose ("security check disallowing non-%s message\n",
1497                              "Hello");
1498
1499               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1500                               "Client tried to send a message other than %s without being registered",
1501                               "Hello");
1502
1503               return FALSE;
1504             }
1505         }
1506     }
1507   else
1508     {
1509       sender_policy = NULL;
1510
1511       /* If the sender is the bus driver, we assume any reply was a
1512        * requested reply as bus driver won't send bogus ones
1513        */
1514       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1515           dbus_message_get_reply_serial (message) != 0)
1516         requested_reply = TRUE;
1517     }
1518
1519   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1520                 (sender == NULL && sender_policy == NULL));
1521
1522   if (proposed_recipient != NULL)
1523     {
1524       /* only the bus driver can send to an inactive recipient (as it
1525        * owns no services, so other apps can't address it). Inactive
1526        * recipients can receive any message.
1527        */
1528       if (bus_connection_is_active (proposed_recipient))
1529         {
1530           recipient_policy = bus_connection_get_policy (proposed_recipient);
1531           _dbus_assert (recipient_policy != NULL);
1532         }
1533       else if (sender == NULL)
1534         {
1535           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1536           recipient_policy = NULL;
1537         }
1538       else
1539         {
1540           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus\n");
1541           recipient_policy = NULL;
1542         }
1543     }
1544   else
1545     recipient_policy = NULL;
1546
1547   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1548                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1549                 (proposed_recipient == NULL && recipient_policy == NULL));
1550
1551   log = FALSE;
1552   if (sender_policy &&
1553       !bus_client_policy_check_can_send (sender_policy,
1554                                          context->registry,
1555                                          requested_reply,
1556                                          proposed_recipient,
1557                                          message, &toggles, &log))
1558     {
1559       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1560           "Rejected send message", toggles,
1561           message, sender, proposed_recipient, requested_reply,
1562           (addressed_recipient == proposed_recipient), error);
1563       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1564       return FALSE;
1565     }
1566
1567   if (log)
1568     {
1569       /* We want to drop this message, and are only not doing so for backwards
1570        * compatibility. */
1571       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1572           "Would reject message", toggles,
1573           message, sender, proposed_recipient, requested_reply,
1574           TRUE, NULL);
1575     }
1576
1577   if (recipient_policy &&
1578       !bus_client_policy_check_can_receive (recipient_policy,
1579                                             context->registry,
1580                                             requested_reply,
1581                                             sender,
1582                                             addressed_recipient, proposed_recipient,
1583                                             message, &toggles))
1584     {
1585       complain_about_message (context, DBUS_ERROR_ACCESS_DENIED,
1586           "Rejected receive message", toggles,
1587           message, sender, proposed_recipient, requested_reply,
1588           (addressed_recipient == proposed_recipient), NULL);
1589       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1590       return FALSE;
1591     }
1592
1593   /* See if limits on size have been exceeded */
1594   if (proposed_recipient &&
1595       ((dbus_connection_get_outgoing_size (proposed_recipient) > context->limits.max_outgoing_bytes) ||
1596        (dbus_connection_get_outgoing_unix_fds (proposed_recipient) > context->limits.max_outgoing_unix_fds)))
1597     {
1598       complain_about_message (context, DBUS_ERROR_LIMITS_EXCEEDED,
1599           "Rejected: destination has a full message queue",
1600           0, message, sender, proposed_recipient, requested_reply, TRUE,
1601           error);
1602       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1603       return FALSE;
1604     }
1605
1606   /* Record that we will allow a reply here in the future (don't
1607    * bother if the recipient is the bus or this is an eavesdropping
1608    * connection). Only the addressed recipient may reply.
1609    */
1610   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL &&
1611       sender &&
1612       addressed_recipient &&
1613       addressed_recipient == proposed_recipient && /* not eavesdropping */
1614       !bus_connections_expect_reply (bus_connection_get_connections (sender),
1615                                      transaction,
1616                                      sender, addressed_recipient,
1617                                      message, error))
1618     {
1619       _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1620       return FALSE;
1621     }
1622
1623   _dbus_verbose ("security policy allowing message\n");
1624   return TRUE;
1625 }