2003-10-20 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / bus / bus.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* bus.c  message bus context object
3  *
4  * Copyright (C) 2003 Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "bus.h"
25 #include "activation.h"
26 #include "connection.h"
27 #include "services.h"
28 #include "utils.h"
29 #include "policy.h"
30 #include "config-parser.h"
31 #include "signals.h"
32 #include <dbus/dbus-list.h>
33 #include <dbus/dbus-hash.h>
34 #include <dbus/dbus-internals.h>
35
36 struct BusContext
37 {
38   int refcount;
39   char *type;
40   char *address;
41   char *pidfile;
42   DBusLoop *loop;
43   DBusList *servers;
44   BusConnections *connections;
45   BusActivation *activation;
46   BusRegistry *registry;
47   BusPolicy *policy;
48   BusMatchmaker *matchmaker;
49   DBusUserDatabase *user_database;
50   BusLimits limits;
51 };
52
53 static dbus_int32_t server_data_slot = -1;
54
55 typedef struct
56 {
57   BusContext *context;
58 } BusServerData;
59
60 #define BUS_SERVER_DATA(server) (dbus_server_get_data ((server), server_data_slot))
61
62 static BusContext*
63 server_get_context (DBusServer *server)
64 {
65   BusContext *context;
66   BusServerData *bd;
67   
68   if (!dbus_server_allocate_data_slot (&server_data_slot))
69     return NULL;
70
71   bd = BUS_SERVER_DATA (server);
72   if (bd == NULL)
73     {
74       dbus_server_free_data_slot (&server_data_slot);
75       return NULL;
76     }
77
78   context = bd->context;
79
80   dbus_server_free_data_slot (&server_data_slot);
81
82   return context;
83 }
84
85 static dbus_bool_t
86 server_watch_callback (DBusWatch     *watch,
87                        unsigned int   condition,
88                        void          *data)
89 {
90   /* FIXME this can be done in dbus-mainloop.c
91    * if the code in activation.c for the babysitter
92    * watch handler is fixed.
93    */
94   
95   return dbus_watch_handle (watch, condition);
96 }
97
98 static dbus_bool_t
99 add_server_watch (DBusWatch  *watch,
100                   void       *data)
101 {
102   DBusServer *server = data;
103   BusContext *context;
104   
105   context = server_get_context (server);
106   
107   return _dbus_loop_add_watch (context->loop,
108                                watch, server_watch_callback, server,
109                                NULL);
110 }
111
112 static void
113 remove_server_watch (DBusWatch  *watch,
114                      void       *data)
115 {
116   DBusServer *server = data;
117   BusContext *context;
118   
119   context = server_get_context (server);
120   
121   _dbus_loop_remove_watch (context->loop,
122                            watch, server_watch_callback, server);
123 }
124
125
126 static void
127 server_timeout_callback (DBusTimeout   *timeout,
128                          void          *data)
129 {
130   /* can return FALSE on OOM but we just let it fire again later */
131   dbus_timeout_handle (timeout);
132 }
133
134 static dbus_bool_t
135 add_server_timeout (DBusTimeout *timeout,
136                     void        *data)
137 {
138   DBusServer *server = data;
139   BusContext *context;
140   
141   context = server_get_context (server);
142
143   return _dbus_loop_add_timeout (context->loop,
144                                  timeout, server_timeout_callback, server, NULL);
145 }
146
147 static void
148 remove_server_timeout (DBusTimeout *timeout,
149                        void        *data)
150 {
151   DBusServer *server = data;
152   BusContext *context;
153   
154   context = server_get_context (server);
155   
156   _dbus_loop_remove_timeout (context->loop,
157                              timeout, server_timeout_callback, server);
158 }
159
160 static void
161 new_connection_callback (DBusServer     *server,
162                          DBusConnection *new_connection,
163                          void           *data)
164 {
165   BusContext *context = data;
166   
167   if (!bus_connections_setup_connection (context->connections, new_connection))
168     {
169       _dbus_verbose ("No memory to setup new connection\n");
170
171       /* if we don't do this, it will get unref'd without
172        * being disconnected... kind of strange really
173        * that we have to do this, people won't get it right
174        * in general.
175        */
176       dbus_connection_disconnect (new_connection);
177     }
178
179   dbus_connection_set_max_received_size (new_connection,
180                                          context->limits.max_incoming_bytes);
181
182   dbus_connection_set_max_message_size (new_connection,
183                                         context->limits.max_message_size);
184   
185   /* on OOM, we won't have ref'd the connection so it will die. */
186 }
187
188 static void
189 free_server_data (void *data)
190 {
191   BusServerData *bd = data;  
192   
193   dbus_free (bd);
194 }
195
196 static dbus_bool_t
197 setup_server (BusContext *context,
198               DBusServer *server,
199               char      **auth_mechanisms,
200               DBusError  *error)
201 {
202   BusServerData *bd;
203
204   bd = dbus_new0 (BusServerData, 1);
205   if (!dbus_server_set_data (server,
206                              server_data_slot,
207                              bd, free_server_data))
208     {
209       dbus_free (bd);
210       BUS_SET_OOM (error);
211       return FALSE;
212     }
213
214   bd->context = context;
215   
216   if (!dbus_server_set_auth_mechanisms (server, (const char**) auth_mechanisms))
217     {
218       BUS_SET_OOM (error);
219       return FALSE;
220     }
221   
222   dbus_server_set_new_connection_function (server,
223                                            new_connection_callback,
224                                            context, NULL);
225   
226   if (!dbus_server_set_watch_functions (server,
227                                         add_server_watch,
228                                         remove_server_watch,
229                                         NULL,
230                                         server,
231                                         NULL))
232     {
233       BUS_SET_OOM (error);
234       return FALSE;
235     }
236
237   if (!dbus_server_set_timeout_functions (server,
238                                           add_server_timeout,
239                                           remove_server_timeout,
240                                           NULL,
241                                           server, NULL))
242     {
243       BUS_SET_OOM (error);
244       return FALSE;
245     }
246   
247   return TRUE;
248 }
249
250 BusContext*
251 bus_context_new (const DBusString *config_file,
252                  dbus_bool_t       force_fork,
253                  int               print_addr_fd,
254                  int               print_pid_fd,
255                  DBusError        *error)
256 {
257   BusContext *context;
258   DBusList *link;
259   DBusList **addresses;
260   BusConfigParser *parser;
261   DBusString full_address;
262   const char *user, *pidfile;
263   char **auth_mechanisms;
264   DBusList **auth_mechanisms_list;
265   int len;
266   
267   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
268
269   if (!_dbus_string_init (&full_address))
270     {
271       BUS_SET_OOM (error);
272       return NULL;
273     }
274
275   if (!dbus_server_allocate_data_slot (&server_data_slot))
276     {
277       BUS_SET_OOM (error);
278       _dbus_string_free (&full_address);
279       return NULL;
280     }
281   
282   parser = NULL;
283   context = NULL;
284   auth_mechanisms = NULL;
285   
286   parser = bus_config_load (config_file, TRUE, error);
287   if (parser == NULL)
288     goto failed;
289
290   /* Check for an existing pid file. Of course this is a race;
291    * we'd have to use fcntl() locks on the pid file to
292    * avoid that. But we want to check for the pid file
293    * before overwriting any existing sockets, etc.
294    */
295   pidfile = bus_config_parser_get_pidfile (parser);
296   if (pidfile != NULL)
297     {
298       DBusString u;
299       DBusStat stbuf;
300       DBusError tmp_error;
301       
302       dbus_error_init (&tmp_error);
303       _dbus_string_init_const (&u, pidfile);
304       
305       if (_dbus_stat (&u, &stbuf, &tmp_error))
306         {
307           dbus_set_error (error, DBUS_ERROR_FAILED,
308                           "The pid file \"%s\" exists, if the message bus is not running, remove this file",
309                           pidfile);
310           dbus_error_free (&tmp_error);
311           goto failed;
312         }
313     }
314   
315   context = dbus_new0 (BusContext, 1);
316   if (context == NULL)
317     {
318       BUS_SET_OOM (error);
319       goto failed;
320     }
321   
322   context->refcount = 1;
323
324   /* get our limits and timeout lengths */
325   bus_config_parser_get_limits (parser, &context->limits);
326   
327   /* we need another ref of the server data slot for the context
328    * to own
329    */
330   if (!dbus_server_allocate_data_slot (&server_data_slot))
331     _dbus_assert_not_reached ("second ref of server data slot failed");
332   
333   context->user_database = _dbus_user_database_new ();
334   if (context->user_database == NULL)
335     {
336       BUS_SET_OOM (error);
337       goto failed;
338     }
339   
340   context->loop = _dbus_loop_new ();
341   if (context->loop == NULL)
342     {
343       BUS_SET_OOM (error);
344       goto failed;
345     }
346   
347   /* Build an array of auth mechanisms */
348   
349   auth_mechanisms_list = bus_config_parser_get_mechanisms (parser);
350   len = _dbus_list_get_length (auth_mechanisms_list);
351
352   if (len > 0)
353     {
354       int i;
355
356       auth_mechanisms = dbus_new0 (char*, len + 1);
357       if (auth_mechanisms == NULL)
358         goto failed;
359       
360       i = 0;
361       link = _dbus_list_get_first_link (auth_mechanisms_list);
362       while (link != NULL)
363         {
364           auth_mechanisms[i] = _dbus_strdup (link->data);
365           if (auth_mechanisms[i] == NULL)
366             goto failed;
367           link = _dbus_list_get_next_link (auth_mechanisms_list, link);
368         }
369     }
370   else
371     {
372       auth_mechanisms = NULL;
373     }
374
375   /* Listen on our addresses */
376   
377   addresses = bus_config_parser_get_addresses (parser);  
378   
379   link = _dbus_list_get_first_link (addresses);
380   while (link != NULL)
381     {
382       DBusServer *server;
383       
384       server = dbus_server_listen (link->data, error);
385       if (server == NULL)
386         goto failed;
387       else if (!setup_server (context, server, auth_mechanisms, error))
388         goto failed;
389
390       if (!_dbus_list_append (&context->servers, server))
391         {
392           BUS_SET_OOM (error);
393           goto failed;
394         }          
395       
396       link = _dbus_list_get_next_link (addresses, link);
397     }
398
399   /* note that type may be NULL */
400   context->type = _dbus_strdup (bus_config_parser_get_type (parser));
401   if (bus_config_parser_get_type (parser) != NULL && context->type == NULL)
402     {
403       BUS_SET_OOM (error);
404       goto failed;
405     }
406   
407   /* We have to build the address backward, so that
408    * <listen> later in the config file have priority
409    */
410   link = _dbus_list_get_last_link (&context->servers);
411   while (link != NULL)
412     {
413       char *addr;
414       
415       addr = dbus_server_get_address (link->data);
416       if (addr == NULL)
417         {
418           BUS_SET_OOM (error);
419           goto failed;
420         }
421
422       if (_dbus_string_get_length (&full_address) > 0)
423         {
424           if (!_dbus_string_append (&full_address, ";"))
425             {
426               BUS_SET_OOM (error);
427               goto failed;
428             }
429         }
430
431       if (!_dbus_string_append (&full_address, addr))
432         {
433           BUS_SET_OOM (error);
434           goto failed;
435         }
436
437       dbus_free (addr);
438
439       link = _dbus_list_get_prev_link (&context->servers, link);
440     }
441
442   if (!_dbus_string_copy_data (&full_address, &context->address))
443     {
444       BUS_SET_OOM (error);
445       goto failed;
446     }
447
448   /* Note that we don't know whether the print_addr_fd is
449    * one of the sockets we're using to listen on, or some
450    * other random thing. But I think the answer is "don't do
451    * that then"
452    */
453   if (print_addr_fd >= 0)
454     {
455       DBusString addr;
456       const char *a = bus_context_get_address (context);
457       int bytes;
458       
459       _dbus_assert (a != NULL);
460       if (!_dbus_string_init (&addr))
461         {
462           BUS_SET_OOM (error);
463           goto failed;
464         }
465       
466       if (!_dbus_string_append (&addr, a) ||
467           !_dbus_string_append (&addr, "\n"))
468         {
469           _dbus_string_free (&addr);
470           BUS_SET_OOM (error);
471           goto failed;
472         }
473
474       bytes = _dbus_string_get_length (&addr);
475       if (_dbus_write (print_addr_fd, &addr, 0, bytes) != bytes)
476         {
477           dbus_set_error (error, DBUS_ERROR_FAILED,
478                           "Printing message bus address: %s\n",
479                           _dbus_strerror (errno));
480           _dbus_string_free (&addr);
481           goto failed;
482         }
483
484       if (print_addr_fd > 2)
485         _dbus_close (print_addr_fd, NULL);
486
487       _dbus_string_free (&addr);
488     }
489   
490   /* Create activation subsystem */
491   
492   context->activation = bus_activation_new (context, &full_address,
493                                             bus_config_parser_get_service_dirs (parser),
494                                             error);
495   if (context->activation == NULL)
496     {
497       _DBUS_ASSERT_ERROR_IS_SET (error);
498       goto failed;
499     }
500
501   context->connections = bus_connections_new (context);
502   if (context->connections == NULL)
503     {
504       BUS_SET_OOM (error);
505       goto failed;
506     }
507
508   context->registry = bus_registry_new (context);
509   if (context->registry == NULL)
510     {
511       BUS_SET_OOM (error);
512       goto failed;
513     }
514
515   context->matchmaker = bus_matchmaker_new ();
516   if (context->matchmaker == NULL)
517     {
518       BUS_SET_OOM (error);
519       goto failed;
520     }
521   
522   context->policy = bus_config_parser_steal_policy (parser);
523   _dbus_assert (context->policy != NULL);
524   
525   /* Now become a daemon if appropriate */
526   if (force_fork || bus_config_parser_get_fork (parser))
527     {
528       DBusString u;
529
530       if (pidfile)
531         _dbus_string_init_const (&u, pidfile);
532       
533       if (!_dbus_become_daemon (pidfile ? &u : NULL, error))
534         goto failed;
535     }
536   else
537     {
538       /* Need to write PID file for ourselves, not for the child process */
539       if (pidfile != NULL)
540         {
541           DBusString u;
542
543           _dbus_string_init_const (&u, pidfile);
544           
545           if (!_dbus_write_pid_file (&u, _dbus_getpid (), error))
546             goto failed;
547         }
548     }
549
550   /* keep around the pid filename so we can delete it later */
551   context->pidfile = _dbus_strdup (pidfile);
552
553   /* Write PID if requested */
554   if (print_pid_fd >= 0)
555     {
556       DBusString pid;
557       int bytes;
558
559       if (!_dbus_string_init (&pid))
560         {
561           BUS_SET_OOM (error);
562           goto failed;
563         }
564       
565       if (!_dbus_string_append_int (&pid, _dbus_getpid ()) ||
566           !_dbus_string_append (&pid, "\n"))
567         {
568           _dbus_string_free (&pid);
569           BUS_SET_OOM (error);
570           goto failed;
571         }
572
573       bytes = _dbus_string_get_length (&pid);
574       if (_dbus_write (print_pid_fd, &pid, 0, bytes) != bytes)
575         {
576           dbus_set_error (error, DBUS_ERROR_FAILED,
577                           "Printing message bus PID: %s\n",
578                           _dbus_strerror (errno));
579           _dbus_string_free (&pid);
580           goto failed;
581         }
582
583       if (print_pid_fd > 2)
584         _dbus_close (print_pid_fd, NULL);
585       
586       _dbus_string_free (&pid);
587     }
588   
589   /* Here we change our credentials if required,
590    * as soon as we've set up our sockets and pidfile
591    */
592   user = bus_config_parser_get_user (parser);
593   if (user != NULL)
594     {
595       DBusCredentials creds;
596       DBusString u;
597
598       _dbus_string_init_const (&u, user);
599
600       if (!_dbus_credentials_from_username (&u, &creds) ||
601           creds.uid < 0 ||
602           creds.gid < 0)
603         {
604           dbus_set_error (error, DBUS_ERROR_FAILED,
605                           "Could not get UID and GID for username \"%s\"",
606                           user);
607           goto failed;
608         }
609       
610       if (!_dbus_change_identity (creds.uid, creds.gid, error))
611         goto failed;
612     }
613   
614   bus_config_parser_unref (parser);
615   _dbus_string_free (&full_address);
616   dbus_free_string_array (auth_mechanisms);
617   dbus_server_free_data_slot (&server_data_slot);
618   
619   return context;
620   
621  failed:  
622   if (parser != NULL)
623     bus_config_parser_unref (parser);
624
625   if (context != NULL)
626     bus_context_unref (context);
627
628   _dbus_string_free (&full_address);
629   dbus_free_string_array (auth_mechanisms);
630
631   dbus_server_free_data_slot (&server_data_slot);
632   
633   return NULL;
634 }
635
636 static void
637 shutdown_server (BusContext *context,
638                  DBusServer *server)
639 {
640   if (server == NULL ||
641       !dbus_server_get_is_connected (server))
642     return;
643   
644   if (!dbus_server_set_watch_functions (server,
645                                         NULL, NULL, NULL,
646                                         context,
647                                         NULL))
648     _dbus_assert_not_reached ("setting watch functions to NULL failed");
649   
650   if (!dbus_server_set_timeout_functions (server,
651                                           NULL, NULL, NULL,
652                                           context,
653                                           NULL))
654     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
655   
656   dbus_server_disconnect (server);
657 }
658
659 void
660 bus_context_shutdown (BusContext  *context)
661 {
662   DBusList *link;
663
664   link = _dbus_list_get_first_link (&context->servers);
665   while (link != NULL)
666     {
667       shutdown_server (context, link->data);
668
669       link = _dbus_list_get_next_link (&context->servers, link);
670     }
671 }
672
673 void
674 bus_context_ref (BusContext *context)
675 {
676   _dbus_assert (context->refcount > 0);
677   context->refcount += 1;
678 }
679
680 void
681 bus_context_unref (BusContext *context)
682 {
683   _dbus_assert (context->refcount > 0);
684   context->refcount -= 1;
685
686   if (context->refcount == 0)
687     {
688       DBusList *link;
689       
690       _dbus_verbose ("Finalizing bus context %p\n", context);
691       
692       bus_context_shutdown (context);
693
694       if (context->connections)
695         {
696           bus_connections_unref (context->connections);
697           context->connections = NULL;
698         }
699       
700       if (context->registry)
701         {
702           bus_registry_unref (context->registry);
703           context->registry = NULL;
704         }
705       
706       if (context->activation)
707         {
708           bus_activation_unref (context->activation);
709           context->activation = NULL;
710         }
711
712       link = _dbus_list_get_first_link (&context->servers);
713       while (link != NULL)
714         {
715           dbus_server_unref (link->data);
716           
717           link = _dbus_list_get_next_link (&context->servers, link);
718         }
719       _dbus_list_clear (&context->servers);
720
721       if (context->policy)
722         {
723           bus_policy_unref (context->policy);
724           context->policy = NULL;
725         }
726       
727       if (context->loop)
728         {
729           _dbus_loop_unref (context->loop);
730           context->loop = NULL;
731         }
732
733       if (context->matchmaker)
734         {
735           bus_matchmaker_unref (context->matchmaker);
736           context->matchmaker = NULL;
737         }
738       
739       dbus_free (context->type);
740       dbus_free (context->address);
741
742       if (context->pidfile)
743         {
744           DBusString u;
745           _dbus_string_init_const (&u, context->pidfile);
746
747           /* Deliberately ignore errors here, since there's not much
748            * we can do about it, and we're exiting anyways.
749            */
750           _dbus_delete_file (&u, NULL);
751
752           dbus_free (context->pidfile); 
753         }
754
755       _dbus_user_database_unref (context->user_database);
756       
757       dbus_free (context);
758
759       dbus_server_free_data_slot (&server_data_slot);
760     }
761 }
762
763 /* type may be NULL */
764 const char*
765 bus_context_get_type (BusContext *context)
766 {
767   return context->type;
768 }
769
770 const char*
771 bus_context_get_address (BusContext *context)
772 {
773   return context->address;
774 }
775
776 BusRegistry*
777 bus_context_get_registry (BusContext  *context)
778 {
779   return context->registry;
780 }
781
782 BusConnections*
783 bus_context_get_connections (BusContext  *context)
784 {
785   return context->connections;
786 }
787
788 BusActivation*
789 bus_context_get_activation (BusContext  *context)
790 {
791   return context->activation;
792 }
793
794 BusMatchmaker*
795 bus_context_get_matchmaker (BusContext  *context)
796 {
797   return context->matchmaker;
798 }
799
800 DBusLoop*
801 bus_context_get_loop (BusContext *context)
802 {
803   return context->loop;
804 }
805
806 DBusUserDatabase*
807 bus_context_get_user_database (BusContext *context)
808 {
809   return context->user_database;
810 }
811
812 dbus_bool_t
813 bus_context_allow_user (BusContext   *context,
814                         unsigned long uid)
815 {
816   return bus_policy_allow_user (context->policy,
817                                 context->user_database,
818                                 uid);
819 }
820
821 BusClientPolicy*
822 bus_context_create_client_policy (BusContext      *context,
823                                   DBusConnection  *connection,
824                                   DBusError       *error)
825 {
826   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
827   return bus_policy_create_client_policy (context->policy, connection,
828                                           error);
829 }
830
831 int
832 bus_context_get_activation_timeout (BusContext *context)
833 {
834   
835   return context->limits.activation_timeout;
836 }
837
838 int
839 bus_context_get_auth_timeout (BusContext *context)
840 {
841   return context->limits.auth_timeout;
842 }
843
844 int
845 bus_context_get_max_completed_connections (BusContext *context)
846 {
847   return context->limits.max_completed_connections;
848 }
849
850 int
851 bus_context_get_max_incomplete_connections (BusContext *context)
852 {
853   return context->limits.max_incomplete_connections;
854 }
855
856 int
857 bus_context_get_max_connections_per_user (BusContext *context)
858 {
859   return context->limits.max_connections_per_user;
860 }
861
862 int
863 bus_context_get_max_pending_activations (BusContext *context)
864 {
865   return context->limits.max_pending_activations;
866 }
867
868 int
869 bus_context_get_max_services_per_connection (BusContext *context)
870 {
871   return context->limits.max_services_per_connection;
872 }
873
874 int
875 bus_context_get_max_match_rules_per_connection (BusContext *context)
876 {
877   return context->limits.max_match_rules_per_connection;
878 }
879
880 int
881 bus_context_get_max_replies_per_connection (BusContext *context)
882 {
883   return context->limits.max_replies_per_connection;
884 }
885
886 int
887 bus_context_get_reply_timeout (BusContext *context)
888 {
889   return context->limits.reply_timeout;
890 }
891
892 /*
893  * addressed_recipient is the recipient specified in the message.
894  *
895  * proposed_recipient is the recipient we're considering sending
896  * to right this second, and may be an eavesdropper.
897  *
898  * sender is the sender of the message.
899  *
900  * NULL for proposed_recipient or sender definitely means the bus driver.
901  *
902  * NULL for addressed_recipient may mean the bus driver, or may mean
903  * no destination was specified in the message (e.g. a signal).
904  */
905 dbus_bool_t
906 bus_context_check_security_policy (BusContext     *context,
907                                    BusTransaction *transaction,
908                                    DBusConnection *sender,
909                                    DBusConnection *addressed_recipient,
910                                    DBusConnection *proposed_recipient,
911                                    DBusMessage    *message,
912                                    DBusError      *error)
913 {
914   BusClientPolicy *sender_policy;
915   BusClientPolicy *recipient_policy;
916   int type;
917   dbus_bool_t requested_reply;
918   
919   type = dbus_message_get_type (message);
920   
921   /* dispatch.c was supposed to ensure these invariants */
922   /* FIXME this assertion is failing in make check */
923   _dbus_assert (dbus_message_get_destination (message) != NULL ||
924                 type == DBUS_MESSAGE_TYPE_SIGNAL);
925   _dbus_assert (type == DBUS_MESSAGE_TYPE_SIGNAL ||
926                 addressed_recipient != NULL ||
927                 strcmp (dbus_message_get_destination (message), DBUS_SERVICE_ORG_FREEDESKTOP_DBUS) == 0);
928   
929   switch (type)
930     {
931     case DBUS_MESSAGE_TYPE_METHOD_CALL:
932     case DBUS_MESSAGE_TYPE_SIGNAL:
933     case DBUS_MESSAGE_TYPE_METHOD_RETURN:
934     case DBUS_MESSAGE_TYPE_ERROR:
935       break;
936       
937     default:
938       _dbus_verbose ("security check disallowing message of unknown type %d\n",
939                      type);
940
941       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
942                       "Message bus will not accept messages of unknown type\n");
943               
944       return FALSE;
945     }
946
947   requested_reply = FALSE;
948   
949   if (sender != NULL)
950     {
951       if (bus_connection_is_active (sender))
952         {
953           sender_policy = bus_connection_get_policy (sender);
954           _dbus_assert (sender_policy != NULL);
955           
956           /* Fill in requested_reply variable with TRUE if this is a
957            * reply and the reply was pending.
958            */
959           if (dbus_message_get_reply_serial (message) != 0)
960             {
961               if (proposed_recipient != NULL /* not to the bus driver */ &&
962                   addressed_recipient == proposed_recipient /* not eavesdropping */)
963                 {
964                   DBusError error2;                  
965                   
966                   dbus_error_init (&error2);
967                   requested_reply = bus_connections_check_reply (bus_connection_get_connections (sender),
968                                                                  transaction,
969                                                                  sender, addressed_recipient, message,
970                                                                  &error2);
971                   if (dbus_error_is_set (&error2))
972                     {
973                       dbus_move_error (&error2, error);
974                       return FALSE;
975                     }
976                 }
977             }
978         }
979       else
980         {
981           /* Policy for inactive connections is that they can only send
982            * the hello message to the bus driver
983            */
984           if (proposed_recipient == NULL &&
985               dbus_message_is_method_call (message,
986                                            DBUS_INTERFACE_ORG_FREEDESKTOP_DBUS,
987                                            "Hello"))
988             {
989               _dbus_verbose ("security check allowing %s message\n",
990                              "Hello");
991               return TRUE;
992             }
993           else
994             {
995               _dbus_verbose ("security check disallowing non-%s message\n",
996                              "Hello");
997
998               dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
999                               "Client tried to send a message other than %s without being registered",
1000                               "Hello");
1001               
1002               return FALSE;
1003             }
1004         }
1005     }
1006   else
1007     {
1008       sender_policy = NULL;
1009
1010       /* If the sender is the bus driver, we assume any reply was a
1011        * requested reply as bus driver won't send bogus ones
1012        */
1013       if (addressed_recipient == proposed_recipient /* not eavesdropping */ &&
1014           dbus_message_get_reply_serial (message) != 0)
1015         requested_reply = TRUE;
1016     }
1017
1018   _dbus_assert ((sender != NULL && sender_policy != NULL) ||
1019                 (sender == NULL && sender_policy == NULL));
1020   
1021   if (proposed_recipient != NULL)
1022     {
1023       /* only the bus driver can send to an inactive recipient (as it
1024        * owns no services, so other apps can't address it). Inactive
1025        * recipients can receive any message.
1026        */
1027       if (bus_connection_is_active (proposed_recipient))
1028         {
1029           recipient_policy = bus_connection_get_policy (proposed_recipient);
1030           _dbus_assert (recipient_policy != NULL);
1031         }
1032       else if (sender == NULL)
1033         {
1034           _dbus_verbose ("security check using NULL recipient policy for message from bus\n");
1035           recipient_policy = NULL;
1036         }
1037       else
1038         {
1039           _dbus_assert_not_reached ("a message was somehow sent to an inactive recipient from a source other than the message bus\n");
1040           recipient_policy = NULL;
1041         }
1042     }
1043   else
1044     recipient_policy = NULL;
1045   
1046   _dbus_assert ((proposed_recipient != NULL && recipient_policy != NULL) ||
1047                 (proposed_recipient != NULL && sender == NULL && recipient_policy == NULL) ||
1048                 (proposed_recipient == NULL && recipient_policy == NULL));
1049   
1050   if (sender_policy &&
1051       !bus_client_policy_check_can_send (sender_policy,
1052                                          context->registry, proposed_recipient,
1053                                          message))
1054     {
1055       const char *dest = dbus_message_get_destination (message);
1056       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1057                       "A security policy in place prevents this sender "
1058                       "from sending this message to this recipient, "
1059                       "see message bus configuration file (rejected message "
1060                       "had interface \"%s\" member \"%s\" error name \"%s\" destination \"%s\")",
1061                       dbus_message_get_interface (message) ?
1062                       dbus_message_get_interface (message) : "(unset)",
1063                       dbus_message_get_member (message) ?
1064                       dbus_message_get_member (message) : "(unset)",
1065                       dbus_message_get_error_name (message) ?
1066                       dbus_message_get_error_name (message) : "(unset)",
1067                       dest ? dest : DBUS_SERVICE_ORG_FREEDESKTOP_DBUS);
1068       _dbus_verbose ("security policy disallowing message due to sender policy\n");
1069       return FALSE;
1070     }
1071
1072   if (recipient_policy &&
1073       !bus_client_policy_check_can_receive (recipient_policy,
1074                                             context->registry,
1075                                             requested_reply,
1076                                             sender,
1077                                             addressed_recipient, proposed_recipient,
1078                                             message))
1079     {
1080       const char *dest = dbus_message_get_destination (message);
1081       dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1082                       "A security policy in place prevents this recipient "
1083                       "from receiving this message from this sender, "
1084                       "see message bus configuration file (rejected message "
1085                       "had interface \"%s\" member \"%s\" error name \"%s\" destination \"%s\" reply serial %u requested_reply=%d)",
1086                       dbus_message_get_interface (message) ?
1087                       dbus_message_get_interface (message) : "(unset)",
1088                       dbus_message_get_member (message) ?
1089                       dbus_message_get_member (message) : "(unset)",
1090                       dbus_message_get_error_name (message) ?
1091                       dbus_message_get_error_name (message) : "(unset)",
1092                       dest ? dest : DBUS_SERVICE_ORG_FREEDESKTOP_DBUS,
1093                       dbus_message_get_reply_serial (message),
1094                       requested_reply);
1095       _dbus_verbose ("security policy disallowing message due to recipient policy\n");
1096       return FALSE;
1097     }
1098
1099   /* See if limits on size have been exceeded */
1100   if (proposed_recipient &&
1101       dbus_connection_get_outgoing_size (proposed_recipient) >
1102       context->limits.max_outgoing_bytes)
1103     {
1104       const char *dest = dbus_message_get_destination (message);
1105       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1106                       "The destination service \"%s\" has a full message queue",
1107                       dest ? dest : (proposed_recipient ?
1108                                      bus_connection_get_name (proposed_recipient) : 
1109                                      DBUS_SERVICE_ORG_FREEDESKTOP_DBUS));
1110       _dbus_verbose ("security policy disallowing message due to full message queue\n");
1111       return FALSE;
1112     }
1113
1114   if (type == DBUS_MESSAGE_TYPE_METHOD_CALL)
1115     {
1116       /* Record that we will allow a reply here in the future (don't
1117        * bother if the recipient is the bus). Only the addressed recipient
1118        * may reply.
1119        */
1120       if (sender && addressed_recipient &&
1121           !bus_connections_expect_reply (bus_connection_get_connections (sender),
1122                                          transaction,
1123                                          sender, addressed_recipient,
1124                                          message, error))
1125         {
1126           _dbus_verbose ("Failed to record reply expectation or problem with the message expecting a reply\n");
1127           return FALSE;
1128         }
1129     }
1130   
1131   _dbus_verbose ("security policy allowing message\n");
1132   return TRUE;
1133 }