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