Revert "Fix for smack error when dbus-daemon(session) accesses proc/cmdline"
[platform/upstream/dbus.git] / bus / connection.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* connection.c  Client connections
3  *
4  * Copyright (C) 2003  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 "connection.h"
26 #include "dispatch.h"
27 #include "policy.h"
28 #include "services.h"
29 #include "utils.h"
30 #include "signals.h"
31 #include "expirelist.h"
32 #include "selinux.h"
33 #include "apparmor.h"
34 #include "check.h"
35 #include <dbus/dbus-list.h>
36 #include <dbus/dbus-hash.h>
37 #include <dbus/dbus-timeout.h>
38 #include <dbus/dbus-connection-internal.h>
39 #include <dbus/dbus-internals.h>
40 #include <dbus/dbus-message-internal.h>
41 #ifdef DBUS_ENABLE_CYNARA
42 #include <stdlib.h>
43 #include <cynara-session.h>
44 #include <stdio.h>
45 #endif
46
47 /* Trim executed commands to this length; we want to keep logs readable */
48 #define MAX_LOG_COMMAND_LEN 50
49
50 static void bus_connection_remove_transactions (DBusConnection *connection);
51
52 typedef struct
53 {
54   BusExpireItem expire_item;
55
56   DBusConnection *will_get_reply;
57   DBusConnection *will_send_reply;
58
59   dbus_uint32_t reply_serial;
60   
61 } BusPendingReply;
62
63 struct BusConnections
64 {
65   int refcount;
66   DBusList *completed;  /**< List of all completed connections */
67   int n_completed;      /**< Length of completed list */
68   DBusList *incomplete; /**< List of all not-yet-active connections */
69   int n_incomplete;     /**< Length of incomplete list */
70   BusContext *context;
71   DBusHashTable *completed_by_user; /**< Number of completed connections for each UID */
72   DBusTimeout *expire_timeout; /**< Timeout for expiring incomplete connections. */
73   int stamp;                   /**< Incrementing number */
74   BusExpireList *pending_replies; /**< List of pending replies */
75
76   /** List of all monitoring connections, a subset of completed.
77    * Each member is a #DBusConnection. */
78   DBusList *monitors;
79   BusMatchmaker *monitor_matchmaker;
80
81 #ifdef DBUS_ENABLE_STATS
82   int total_match_rules;
83   int peak_match_rules;
84   int peak_match_rules_per_conn;
85
86   int total_bus_names;
87   int peak_bus_names;
88   int peak_bus_names_per_conn;
89 #endif
90 };
91
92 static dbus_int32_t connection_data_slot = -1;
93
94 typedef struct
95 {
96   BusConnections *connections;
97   DBusList *link_in_connection_list;
98   DBusConnection *connection;
99   DBusList *services_owned;
100   int n_services_owned;
101   DBusList *match_rules;
102   int n_match_rules;
103   char *name;
104   DBusList *transaction_messages; /**< Stuff we need to send as part of a transaction */
105   DBusMessage *oom_message;
106   DBusPreallocatedSend *oom_preallocated;
107   BusClientPolicy *policy;
108   DBusList *deferred_messages;  /**< Queue of messages deferred due to pending policy check */
109
110   char *cached_loginfo_string;
111   BusSELinuxID *selinux_id;
112   BusAppArmorConfinement *apparmor_confinement;
113
114   long connection_tv_sec;  /**< Time when we connected (seconds component) */
115   long connection_tv_usec; /**< Time when we connected (microsec component) */
116   int stamp;               /**< connections->stamp last time we were traversed */
117
118 #ifdef DBUS_ENABLE_STATS
119   int peak_match_rules;
120   int peak_bus_names;
121 #endif
122   int n_pending_unix_fds;
123   DBusTimeout *pending_unix_fds_timeout;
124
125   /** non-NULL if and only if this is a monitor */
126   DBusList *link_in_monitors;
127 #ifdef DBUS_ENABLE_CYNARA
128   char *cynara_session_id;
129 #endif
130 } BusConnectionData;
131
132 static dbus_bool_t bus_pending_reply_expired (BusExpireList *list,
133                                               DBusList      *link,
134                                               void          *data);
135
136 static void bus_connection_drop_pending_replies (BusConnections  *connections,
137                                                  DBusConnection  *connection);
138
139 static dbus_bool_t expire_incomplete_timeout (void *data);
140
141 #define BUS_CONNECTION_DATA(connection) (dbus_connection_get_data ((connection), connection_data_slot))
142
143 DBusLoop*
144 bus_connection_get_loop (DBusConnection *connection)
145 {
146   BusConnectionData *d;
147
148   d = BUS_CONNECTION_DATA (connection);
149   _dbus_assert(d != NULL);
150
151   return bus_context_get_loop (d->connections->context);
152 }
153
154
155 static int
156 get_connections_for_uid (BusConnections *connections,
157                          dbus_uid_t      uid)
158 {
159   void *val;
160   int current_count;
161
162   /* val is NULL is 0 when it isn't in the hash yet */
163   
164   val = _dbus_hash_table_lookup_uintptr (connections->completed_by_user,
165                                        uid);
166
167   current_count = _DBUS_POINTER_TO_INT (val);
168
169   return current_count;
170 }
171
172 static dbus_bool_t
173 adjust_connections_for_uid (BusConnections *connections,
174                             dbus_uid_t      uid,
175                             int             adjustment)
176 {
177   int current_count;
178
179   current_count = get_connections_for_uid (connections, uid);
180
181   _dbus_verbose ("Adjusting connection count for UID " DBUS_UID_FORMAT
182                  ": was %d adjustment %d making %d\n",
183                  uid, current_count, adjustment, current_count + adjustment);
184   
185   _dbus_assert (current_count >= 0);
186   
187   current_count += adjustment;
188
189   _dbus_assert (current_count >= 0);
190
191   if (current_count == 0)
192     {
193       _dbus_hash_table_remove_uintptr (connections->completed_by_user, uid);
194       return TRUE;
195     }
196   else
197     {
198       dbus_bool_t retval;
199       
200       retval = _dbus_hash_table_insert_uintptr (connections->completed_by_user,
201                                               uid, _DBUS_INT_TO_POINTER (current_count));
202
203       /* only positive adjustment can fail as otherwise
204        * a hash entry should already exist
205        */
206       _dbus_assert (adjustment > 0 ||
207                     (adjustment <= 0 && retval));
208
209       return retval;
210     }
211 }
212
213 void
214 bus_connection_disconnected (DBusConnection *connection)
215 {
216   BusConnectionData *d;
217   BusService *service;
218   BusMatchmaker *matchmaker;
219   
220   d = BUS_CONNECTION_DATA (connection);
221   _dbus_assert (d != NULL);
222
223   _dbus_verbose ("%s disconnected, dropping all service ownership and releasing\n",
224                  d->name ? d->name : "(inactive)");
225
226   /* Delete our match rules */
227   if (d->n_match_rules > 0)
228     {
229       matchmaker = bus_context_get_matchmaker (d->connections->context);
230       bus_matchmaker_disconnected (matchmaker, connection);
231     }
232   
233   /* Drop any service ownership. Unfortunately, this requires
234    * memory allocation and there doesn't seem to be a good way to
235    * handle it other than sleeping; we can't "fail" the operation of
236    * disconnecting a client, and preallocating a broadcast "service is
237    * now gone" message for every client-service pair seems kind of
238    * involved.
239    */
240   while ((service = _dbus_list_get_last (&d->services_owned)))
241     {
242       BusTransaction *transaction;
243       DBusError error;
244
245     retry:
246       
247       dbus_error_init (&error);
248         
249       while ((transaction = bus_transaction_new (d->connections->context)) == NULL)
250         _dbus_wait_for_memory ();
251         
252       if (!bus_service_remove_owner (service, connection,
253                                      transaction, &error))
254         {
255           _DBUS_ASSERT_ERROR_IS_SET (&error);
256           
257           if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
258             {
259               dbus_error_free (&error);
260               bus_transaction_cancel_and_free (transaction);
261               _dbus_wait_for_memory ();
262               goto retry;
263             }
264           else
265             {
266               _dbus_verbose ("Failed to remove service owner: %s %s\n",
267                              error.name, error.message);
268               _dbus_assert_not_reached ("Removing service owner failed for non-memory-related reason");
269             }
270         }
271         
272       bus_transaction_execute_and_free (transaction);
273     }
274
275   bus_connection_clear_deferred_messages(connection);
276
277   bus_dispatch_remove_connection (connection);
278   
279   /* no more watching */
280   if (!dbus_connection_set_watch_functions (connection,
281                                             NULL, NULL, NULL,
282                                             connection,
283                                             NULL))
284     _dbus_assert_not_reached ("setting watch functions to NULL failed");
285
286   if (!dbus_connection_set_timeout_functions (connection,
287                                               NULL, NULL, NULL,
288                                               connection,
289                                               NULL))
290     _dbus_assert_not_reached ("setting timeout functions to NULL failed");
291   
292   dbus_connection_set_unix_user_function (connection,
293                                           NULL, NULL, NULL);
294   dbus_connection_set_windows_user_function (connection,
295                                              NULL, NULL, NULL);
296   
297   dbus_connection_set_dispatch_status_function (connection,
298                                                 NULL, NULL, NULL);
299
300   if (d->pending_unix_fds_timeout)
301     {
302       _dbus_loop_remove_timeout (bus_context_get_loop (d->connections->context),
303                                  d->pending_unix_fds_timeout);
304       _dbus_timeout_unref (d->pending_unix_fds_timeout);
305     }
306   d->pending_unix_fds_timeout = NULL;
307   _dbus_connection_set_pending_fds_function (connection, NULL, NULL);
308   
309   bus_connection_remove_transactions (connection);
310
311   if (d->link_in_monitors != NULL)
312     {
313       BusMatchmaker *mm = d->connections->monitor_matchmaker;
314
315       if (mm != NULL)
316         bus_matchmaker_disconnected (mm, connection);
317
318       _dbus_list_remove_link (&d->connections->monitors, d->link_in_monitors);
319       d->link_in_monitors = NULL;
320     }
321
322   if (d->link_in_connection_list != NULL)
323     {
324       if (d->name != NULL)
325         {
326           unsigned long uid;
327           
328           _dbus_list_remove_link (&d->connections->completed, d->link_in_connection_list);
329           d->link_in_connection_list = NULL;
330           d->connections->n_completed -= 1;
331
332           if (dbus_connection_get_unix_user (connection, &uid))
333             {
334               if (!adjust_connections_for_uid (d->connections,
335                                                uid, -1))
336                 _dbus_assert_not_reached ("adjusting downward should never fail");
337             }
338         }
339       else
340         {
341           _dbus_list_remove_link (&d->connections->incomplete, d->link_in_connection_list);
342           d->link_in_connection_list = NULL;
343           d->connections->n_incomplete -= 1;
344
345           /* If we have dropped below the max. number of incomplete
346            * connections, start accept()ing again */
347           bus_context_check_all_watches (d->connections->context);
348         }
349       
350       _dbus_assert (d->connections->n_incomplete >= 0);
351       _dbus_assert (d->connections->n_completed >= 0);
352     }
353
354   bus_connection_drop_pending_replies (d->connections, connection);
355   
356   /* frees "d" as side effect */
357   dbus_connection_set_data (connection,
358                             connection_data_slot,
359                             NULL, NULL);
360   
361   dbus_connection_unref (connection);
362 }
363
364 static dbus_bool_t
365 add_connection_watch (DBusWatch      *watch,
366                       void           *data)
367 {
368   DBusConnection *connection = data;
369
370   return _dbus_loop_add_watch (bus_connection_get_loop (connection), watch);
371 }
372
373 static void
374 remove_connection_watch (DBusWatch      *watch,
375                          void           *data)
376 {
377   DBusConnection *connection = data;
378   
379   _dbus_loop_remove_watch (bus_connection_get_loop (connection), watch);
380 }
381
382 static void
383 toggle_connection_watch (DBusWatch      *watch,
384                          void           *data)
385 {
386   DBusConnection *connection = data;
387
388   _dbus_loop_toggle_watch (bus_connection_get_loop (connection), watch);
389 }
390
391 static dbus_bool_t
392 add_connection_timeout (DBusTimeout    *timeout,
393                         void           *data)
394 {
395   DBusConnection *connection = data;
396   
397   return _dbus_loop_add_timeout (bus_connection_get_loop (connection), timeout);
398 }
399
400 static void
401 remove_connection_timeout (DBusTimeout    *timeout,
402                            void           *data)
403 {
404   DBusConnection *connection = data;
405   
406   _dbus_loop_remove_timeout (bus_connection_get_loop (connection), timeout);
407 }
408
409 static void
410 dispatch_status_function (DBusConnection    *connection,
411                           DBusDispatchStatus new_status,
412                           void              *data)
413 {
414   DBusLoop *loop = data;
415   
416   if (new_status != DBUS_DISPATCH_COMPLETE)
417     {
418       while (!_dbus_loop_queue_dispatch (loop, connection))
419         _dbus_wait_for_memory ();
420     }
421 }
422
423 static dbus_bool_t
424 allow_unix_user_function (DBusConnection *connection,
425                           unsigned long   uid,
426                           void           *data)
427 {
428   BusConnectionData *d;
429     
430   d = BUS_CONNECTION_DATA (connection);
431
432   _dbus_assert (d != NULL);
433   
434   return bus_context_allow_unix_user (d->connections->context, uid);
435 }
436
437 static void
438 free_connection_data (void *data)
439 {
440   BusConnectionData *d = data;
441
442   /* services_owned should be NULL since we should be disconnected */
443   _dbus_assert (d->services_owned == NULL);
444   _dbus_assert (d->n_services_owned == 0);
445   /* similarly */
446   _dbus_assert (d->transaction_messages == NULL);
447
448   if (d->oom_preallocated)
449     dbus_connection_free_preallocated_send (d->connection, d->oom_preallocated);
450
451   if (d->oom_message)
452     dbus_message_unref (d->oom_message);
453
454   if (d->policy)
455     bus_client_policy_unref (d->policy);
456
457   if (d->selinux_id)
458     bus_selinux_id_unref (d->selinux_id);
459
460   if (d->apparmor_confinement)
461     bus_apparmor_confinement_unref (d->apparmor_confinement);
462   
463   dbus_free (d->cached_loginfo_string);
464   
465   dbus_free (d->name);
466   
467 #ifdef DBUS_ENABLE_CYNARA
468   free (d->cynara_session_id);
469 #endif
470
471   dbus_free (d);
472 }
473
474 BusConnections*
475 bus_connections_new (BusContext *context)
476 {
477   BusConnections *connections;
478
479   if (!dbus_connection_allocate_data_slot (&connection_data_slot))
480     goto failed_0;
481
482   connections = dbus_new0 (BusConnections, 1);
483   if (connections == NULL)
484     goto failed_1;
485
486   connections->completed_by_user = _dbus_hash_table_new (DBUS_HASH_UINTPTR,
487                                                          NULL, NULL);
488   if (connections->completed_by_user == NULL)
489     goto failed_2;
490
491   connections->expire_timeout = _dbus_timeout_new (100, /* irrelevant */
492                                                    expire_incomplete_timeout,
493                                                    connections, NULL);
494   if (connections->expire_timeout == NULL)
495     goto failed_3;
496
497   _dbus_timeout_disable (connections->expire_timeout);
498
499   connections->pending_replies = bus_expire_list_new (bus_context_get_loop (context),
500                                                       bus_context_get_reply_timeout (context),
501                                                       bus_pending_reply_expired,
502                                                       connections);
503   if (connections->pending_replies == NULL)
504     goto failed_4;
505   
506   if (!_dbus_loop_add_timeout (bus_context_get_loop (context),
507                                connections->expire_timeout))
508     goto failed_5;
509   
510   connections->refcount = 1;
511   connections->context = context;
512   
513   return connections;
514
515  failed_5:
516   bus_expire_list_free (connections->pending_replies);
517  failed_4:
518   _dbus_timeout_unref (connections->expire_timeout);
519  failed_3:
520   _dbus_hash_table_unref (connections->completed_by_user);
521  failed_2:
522   dbus_free (connections);
523  failed_1:
524   dbus_connection_free_data_slot (&connection_data_slot);
525  failed_0:
526   return NULL;
527 }
528
529 BusConnections *
530 bus_connections_ref (BusConnections *connections)
531 {
532   _dbus_assert (connections->refcount > 0);
533   connections->refcount += 1;
534
535   return connections;
536 }
537
538 void
539 bus_connections_unref (BusConnections *connections)
540 {
541   _dbus_assert (connections->refcount > 0);
542   connections->refcount -= 1;
543   if (connections->refcount == 0)
544     {
545       /* drop all incomplete */
546       while (connections->incomplete != NULL)
547         {
548           DBusConnection *connection;
549
550           connection = connections->incomplete->data;
551
552           dbus_connection_ref (connection);
553           dbus_connection_close (connection);
554           bus_connection_disconnected (connection);
555           dbus_connection_unref (connection);
556         }
557
558       _dbus_assert (connections->n_incomplete == 0);
559
560       /* drop all monitors */
561       _dbus_list_clear (&connections->monitors);
562
563       /* drop all real connections */
564       while (connections->completed != NULL)
565         {
566           DBusConnection *connection;
567
568           connection = connections->completed->data;
569
570           dbus_connection_ref (connection);
571           dbus_connection_close (connection);
572           bus_connection_disconnected (connection);
573           dbus_connection_unref (connection);
574         }
575
576       _dbus_assert (connections->n_completed == 0);
577
578       bus_expire_list_free (connections->pending_replies);
579       
580       _dbus_loop_remove_timeout (bus_context_get_loop (connections->context),
581                                  connections->expire_timeout);
582       
583       _dbus_timeout_unref (connections->expire_timeout);
584       
585       _dbus_hash_table_unref (connections->completed_by_user);
586
587       if (connections->monitor_matchmaker != NULL)
588         bus_matchmaker_unref (connections->monitor_matchmaker);
589
590       dbus_free (connections);
591
592       dbus_connection_free_data_slot (&connection_data_slot);
593     }
594 }
595
596 /* Used for logging */
597 static dbus_bool_t
598 cache_peer_loginfo_string (BusConnectionData *d, 
599                            DBusConnection    *connection)
600 {
601   DBusString loginfo_buf;
602   unsigned long uid;
603   unsigned long pid;
604   char *windows_sid;
605   dbus_bool_t prev_added;
606
607   if (!_dbus_string_init (&loginfo_buf))
608     return FALSE;
609   
610   prev_added = FALSE;
611   if (dbus_connection_get_unix_user (connection, &uid))
612     {
613       if (!_dbus_string_append_printf (&loginfo_buf, "uid=%ld", uid))
614         goto oom;
615       else
616         prev_added = TRUE;
617     }
618
619   if (dbus_connection_get_unix_process_id (connection, &pid))
620     {
621       if (prev_added)
622         {
623           if (!_dbus_string_append_byte (&loginfo_buf, ' '))
624             goto oom;
625         }
626       if (!_dbus_string_append_printf (&loginfo_buf, "pid=%ld comm=\"", pid))
627         goto oom;
628       /* Ignore errors here; we may not have permissions to read the
629        * proc file. */
630       _dbus_command_for_pid (pid, &loginfo_buf, MAX_LOG_COMMAND_LEN, NULL);
631       if (!_dbus_string_append_byte (&loginfo_buf, '"'))
632         goto oom;
633     }
634
635   if (dbus_connection_get_windows_user (connection, &windows_sid))
636     {
637       dbus_bool_t did_append;
638       did_append = _dbus_string_append_printf (&loginfo_buf,
639                                                "sid=\"%s\" ", windows_sid);
640       dbus_free (windows_sid);
641       if (!did_append)
642         goto oom;
643     }
644
645   if (!_dbus_string_steal_data (&loginfo_buf, &(d->cached_loginfo_string)))
646     goto oom;
647
648   _dbus_string_free (&loginfo_buf); 
649
650   return TRUE;
651 oom:
652    _dbus_string_free (&loginfo_buf);
653    return FALSE;
654 }
655
656 static void
657 check_pending_fds_cb (DBusConnection *connection)
658 {
659   BusConnectionData *d = BUS_CONNECTION_DATA (connection);
660   int n_pending_unix_fds_old;
661   int n_pending_unix_fds_new;
662
663   _dbus_assert(d != NULL);
664
665   n_pending_unix_fds_old = d->n_pending_unix_fds;
666   n_pending_unix_fds_new = _dbus_connection_get_pending_fds_count (connection);
667
668   _dbus_verbose ("Pending fds count changed on connection %p: %d -> %d\n",
669                  connection, n_pending_unix_fds_old, n_pending_unix_fds_new);
670
671   if (n_pending_unix_fds_old == 0 && n_pending_unix_fds_new > 0)
672     {
673       _dbus_timeout_restart (d->pending_unix_fds_timeout,
674               bus_context_get_pending_fd_timeout (d->connections->context));
675     }
676
677   if (n_pending_unix_fds_old > 0 && n_pending_unix_fds_new == 0)
678     {
679       _dbus_timeout_disable (d->pending_unix_fds_timeout);
680     }
681
682
683   d->n_pending_unix_fds = n_pending_unix_fds_new;
684 }
685
686 static dbus_bool_t
687 pending_unix_fds_timeout_cb (void *data)
688 {
689   DBusConnection *connection = data;
690   dbus_connection_close (connection);
691   return TRUE;
692 }
693
694 dbus_bool_t
695 bus_connections_setup_connection (BusConnections *connections,
696                                   DBusConnection *connection)
697 {
698
699   BusConnectionData *d;
700   dbus_bool_t retval;
701   DBusError error;
702
703   
704   d = dbus_new0 (BusConnectionData, 1);
705   
706   if (d == NULL)
707     return FALSE;
708
709   d->connections = connections;
710   d->connection = connection;
711   
712   _dbus_get_monotonic_time (&d->connection_tv_sec,
713                             &d->connection_tv_usec);
714   
715   _dbus_assert (connection_data_slot >= 0);
716   
717   if (!dbus_connection_set_data (connection,
718                                  connection_data_slot,
719                                  d, free_connection_data))
720     {
721       dbus_free (d);
722       return FALSE;
723     }
724
725   dbus_connection_set_route_peer_messages (connection, TRUE);
726   
727   retval = FALSE;
728
729   dbus_error_init (&error);
730   d->selinux_id = bus_selinux_init_connection_id (connection,
731                                                   &error);
732   if (dbus_error_is_set (&error))
733     {
734       /* This is a bit bogus because we pretend all errors
735        * are OOM; this is done because we know that in bus.c
736        * an OOM error disconnects the connection, which is
737        * the same thing we want on any other error.
738        */
739       dbus_error_free (&error);
740       goto out;
741     }
742
743   d->apparmor_confinement = bus_apparmor_init_connection_confinement (connection,
744                                                                       &error);
745   if (dbus_error_is_set (&error))
746     {
747       /* This is a bit bogus because we pretend all errors
748        * are OOM; this is done because we know that in bus.c
749        * an OOM error disconnects the connection, which is
750        * the same thing we want on any other error.
751        */
752       dbus_error_free (&error);
753       goto out;
754     }
755
756   if (!dbus_connection_set_watch_functions (connection,
757                                             add_connection_watch,
758                                             remove_connection_watch,
759                                             toggle_connection_watch,
760                                             connection,
761                                             NULL))
762     goto out;
763   
764   if (!dbus_connection_set_timeout_functions (connection,
765                                               add_connection_timeout,
766                                               remove_connection_timeout,
767                                               NULL,
768                                               connection, NULL))
769     goto out;
770
771   /* For now we don't need to set a Windows user function because
772    * there are no policies in the config file controlling what
773    * Windows users can connect. The default 'same user that owns the
774    * bus can connect' behavior of DBusConnection is fine on Windows.
775    */
776   dbus_connection_set_unix_user_function (connection,
777                                           allow_unix_user_function,
778                                           NULL, NULL);
779
780   dbus_connection_set_dispatch_status_function (connection,
781                                                 dispatch_status_function,
782                                                 bus_context_get_loop (connections->context),
783                                                 NULL);
784
785   d->link_in_connection_list = _dbus_list_alloc_link (connection);
786   if (d->link_in_connection_list == NULL)
787     goto out;
788   
789   /* Setup the connection with the dispatcher */
790   if (!bus_dispatch_add_connection (connection))
791     goto out;
792
793   if (dbus_connection_get_dispatch_status (connection) != DBUS_DISPATCH_COMPLETE)
794     {
795       if (!_dbus_loop_queue_dispatch (bus_context_get_loop (connections->context), connection))
796         {
797           bus_dispatch_remove_connection (connection);
798           goto out;
799         }
800     }
801
802   /* Setup pending fds timeout (see #80559) */
803   d->pending_unix_fds_timeout = _dbus_timeout_new (100, /* irrelevant */
804                                                    pending_unix_fds_timeout_cb,
805                                                    connection, NULL);
806   if (d->pending_unix_fds_timeout == NULL)
807     goto out;
808
809   _dbus_timeout_disable (d->pending_unix_fds_timeout);
810   if (!_dbus_loop_add_timeout (bus_context_get_loop (connections->context),
811                                d->pending_unix_fds_timeout))
812     goto out;
813
814   _dbus_connection_set_pending_fds_function (connection,
815           (DBusPendingFdsChangeFunction) check_pending_fds_cb,
816           connection);
817
818   _dbus_list_append_link (&connections->incomplete, d->link_in_connection_list);
819   connections->n_incomplete += 1;
820   
821   dbus_connection_ref (connection);
822
823   bus_connections_expire_incomplete (connections);
824   
825   /* The listening socket is removed from the main loop,
826    * i.e. does not accept(), while n_incomplete is at its
827    * maximum value; so we shouldn't get here in that case */
828   _dbus_assert (connections->n_incomplete <=
829       bus_context_get_max_incomplete_connections (connections->context));
830
831   /* If we have the maximum number of incomplete connections,
832    * stop accept()ing any more, to avert a DoS. See fd.o #80919 */
833   bus_context_check_all_watches (d->connections->context);
834   
835   retval = TRUE;
836
837  out:
838   if (!retval)
839     {
840       if (d->selinux_id)
841         bus_selinux_id_unref (d->selinux_id);
842       d->selinux_id = NULL;
843
844       if (d->apparmor_confinement)
845         bus_apparmor_confinement_unref (d->apparmor_confinement);
846       d->apparmor_confinement = NULL;
847       
848       if (!dbus_connection_set_watch_functions (connection,
849                                                 NULL, NULL, NULL,
850                                                 connection,
851                                                 NULL))
852         _dbus_assert_not_reached ("setting watch functions to NULL failed");
853       
854       if (!dbus_connection_set_timeout_functions (connection,
855                                                   NULL, NULL, NULL,
856                                                   connection,
857                                                   NULL))
858         _dbus_assert_not_reached ("setting timeout functions to NULL failed");
859
860       dbus_connection_set_unix_user_function (connection,
861                                               NULL, NULL, NULL);
862
863       dbus_connection_set_windows_user_function (connection,
864                                                  NULL, NULL, NULL);
865       
866       dbus_connection_set_dispatch_status_function (connection,
867                                                     NULL, NULL, NULL);
868
869       if (d->pending_unix_fds_timeout)
870         _dbus_timeout_unref (d->pending_unix_fds_timeout);
871
872       d->pending_unix_fds_timeout = NULL;
873
874       _dbus_connection_set_pending_fds_function (connection, NULL, NULL);
875
876       if (d->link_in_connection_list != NULL)
877         {
878           _dbus_assert (d->link_in_connection_list->next == NULL);
879           _dbus_assert (d->link_in_connection_list->prev == NULL);
880           _dbus_list_free_link (d->link_in_connection_list);
881           d->link_in_connection_list = NULL;
882         }
883       
884       if (!dbus_connection_set_data (connection,
885                                      connection_data_slot,
886                                      NULL, NULL))
887         _dbus_assert_not_reached ("failed to set connection data to null");
888
889       /* "d" has now been freed */
890     }
891   
892   return retval;
893 }
894
895 void
896 bus_connections_expire_incomplete (BusConnections *connections)
897 {    
898   int next_interval;
899
900   next_interval = -1;
901   
902   if (connections->incomplete != NULL)
903     {
904       long tv_sec, tv_usec;
905       DBusList *link;
906       int auth_timeout;
907       
908       _dbus_get_monotonic_time (&tv_sec, &tv_usec);
909       auth_timeout = bus_context_get_auth_timeout (connections->context);
910   
911       link = _dbus_list_get_first_link (&connections->incomplete);
912       while (link != NULL)
913         {
914           DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
915           DBusConnection *connection;
916           BusConnectionData *d;
917           double elapsed;
918       
919           connection = link->data;
920       
921           d = BUS_CONNECTION_DATA (connection);
922       
923           _dbus_assert (d != NULL);
924       
925           elapsed = ELAPSED_MILLISECONDS_SINCE (d->connection_tv_sec,
926                                                 d->connection_tv_usec,
927                                                 tv_sec, tv_usec);
928
929           if (elapsed >= (double) auth_timeout)
930             {
931               /* Unfortunately, we can't identify the connection: it doesn't
932                * have a unique name yet, we don't know its uid/pid yet,
933                * and so on. */
934               bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
935                   "Connection has not authenticated soon enough, closing it "
936                   "(auth_timeout=%dms, elapsed: %.0fms)",
937                   auth_timeout, elapsed);
938
939               _dbus_verbose ("Timing out authentication for connection %p\n", connection);
940               dbus_connection_close (connection);
941             }
942           else
943             {
944               /* We can end the loop, since the connections are in oldest-first order */
945               next_interval = ((double)auth_timeout) - elapsed;
946               _dbus_verbose ("Connection %p authentication expires in %d milliseconds\n",
947                              connection, next_interval);
948           
949               break;
950             }
951       
952           link = next;
953         }
954     }
955
956   bus_expire_timeout_set_interval (connections->expire_timeout,
957                                    next_interval);
958 }
959
960 static dbus_bool_t
961 expire_incomplete_timeout (void *data)
962 {
963   BusConnections *connections = data;
964
965   _dbus_verbose ("Running\n");
966   
967   /* note that this may remove the timeout */
968   bus_connections_expire_incomplete (connections);
969
970   return TRUE;
971 }
972
973 dbus_bool_t
974 bus_connection_get_unix_groups  (DBusConnection   *connection,
975                                  unsigned long   **groups,
976                                  int              *n_groups,
977                                  DBusError        *error)
978 {
979   unsigned long uid;
980
981   *groups = NULL;
982   *n_groups = 0;
983
984   if (dbus_connection_get_unix_user (connection, &uid))
985     {
986       if (!_dbus_unix_groups_from_uid (uid, groups, n_groups))
987         {
988           _dbus_verbose ("Did not get any groups for UID %lu\n",
989                          uid);
990           return FALSE;
991         }
992       else
993         {
994           _dbus_verbose ("Got %d groups for UID %lu\n",
995                          *n_groups, uid);
996           return TRUE;
997         }
998     }
999   else
1000     return TRUE; /* successfully got 0 groups */
1001 }
1002
1003 dbus_bool_t
1004 bus_connection_is_in_unix_group (DBusConnection *connection,
1005                                  unsigned long   gid)
1006 {
1007   int i;
1008   unsigned long *group_ids;
1009   int n_group_ids;
1010
1011   if (!bus_connection_get_unix_groups (connection, &group_ids, &n_group_ids,
1012                                        NULL))
1013     return FALSE;
1014
1015   i = 0;
1016   while (i < n_group_ids)
1017     {
1018       if (group_ids[i] == gid)
1019         {
1020           dbus_free (group_ids);
1021           return TRUE;
1022         }
1023       ++i;
1024     }
1025
1026   dbus_free (group_ids);
1027   return FALSE;
1028 }
1029
1030 const char *
1031 bus_connection_get_loginfo (DBusConnection        *connection)
1032 {
1033   BusConnectionData *d;
1034     
1035   d = BUS_CONNECTION_DATA (connection);
1036   _dbus_assert(d != NULL);
1037
1038   if (!bus_connection_is_active (connection))
1039     return "inactive";
1040   return d->cached_loginfo_string;  
1041 }
1042
1043 BusClientPolicy*
1044 bus_connection_get_policy (DBusConnection *connection)
1045 {
1046   BusConnectionData *d;
1047     
1048   d = BUS_CONNECTION_DATA (connection);
1049
1050   _dbus_assert (d != NULL);
1051   _dbus_assert (d->policy != NULL);
1052   
1053   return d->policy;
1054 }
1055
1056 #ifdef DBUS_ENABLE_CYNARA
1057 const char *bus_connection_get_cynara_session_id (DBusConnection *connection)
1058 {
1059   BusConnectionData *d = BUS_CONNECTION_DATA (connection);
1060   _dbus_assert (d != NULL);
1061
1062   if (d->cynara_session_id == NULL)
1063     {
1064       unsigned long pid;
1065       if (dbus_connection_get_unix_process_id(connection, &pid))
1066         d->cynara_session_id = cynara_session_from_pid(pid);
1067
1068       /* If client exits as soon as async call, cynara_session_from_pid() returns null.
1069          cynara_session_from_pid checks /proc/pid to verify process */
1070       if (d->cynara_session_id == NULL)
1071         asprintf (&d->cynara_session_id, "/proc/%ld", pid);
1072     }
1073   return d->cynara_session_id;
1074 }
1075 #endif
1076
1077 static dbus_bool_t
1078 foreach_active (BusConnections               *connections,
1079                 BusConnectionForeachFunction  function,
1080                 void                         *data)
1081 {
1082   DBusList *link;
1083   
1084   link = _dbus_list_get_first_link (&connections->completed);
1085   while (link != NULL)
1086     {
1087       DBusConnection *connection = link->data;
1088       DBusList *next = _dbus_list_get_next_link (&connections->completed, link);
1089
1090       if (!(* function) (connection, data))
1091         return FALSE;
1092       
1093       link = next;
1094     }
1095
1096   return TRUE;
1097 }
1098
1099 static dbus_bool_t
1100 foreach_inactive (BusConnections               *connections,
1101                   BusConnectionForeachFunction  function,
1102                   void                         *data)
1103 {
1104   DBusList *link;
1105   
1106   link = _dbus_list_get_first_link (&connections->incomplete);
1107   while (link != NULL)
1108     {
1109       DBusConnection *connection = link->data;
1110       DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
1111
1112       if (!(* function) (connection, data))
1113         return FALSE;
1114       
1115       link = next;
1116     }
1117
1118   return TRUE;
1119 }
1120
1121 /**
1122  * Calls function on each active connection; if the function returns
1123  * #FALSE, stops iterating. Active connections are authenticated
1124  * and have sent a Hello message.
1125  *
1126  * @param connections the connections object
1127  * @param function the function
1128  * @param data data to pass to it as a second arg
1129  */
1130 void
1131 bus_connections_foreach_active (BusConnections               *connections,
1132                                 BusConnectionForeachFunction  function,
1133                                 void                         *data)
1134 {
1135   foreach_active (connections, function, data);
1136 }
1137
1138 /**
1139  * Calls function on each connection; if the function returns
1140  * #FALSE, stops iterating.
1141  *
1142  * @param connections the connections object
1143  * @param function the function
1144  * @param data data to pass to it as a second arg
1145  */
1146 void
1147 bus_connections_foreach (BusConnections               *connections,
1148                          BusConnectionForeachFunction  function,
1149                          void                         *data)
1150 {
1151   if (!foreach_active (connections, function, data))
1152     return;
1153
1154   foreach_inactive (connections, function, data);
1155 }
1156
1157 BusContext*
1158 bus_connections_get_context (BusConnections *connections)
1159 {
1160   return connections->context;
1161 }
1162
1163 /*
1164  * This is used to avoid covering the same connection twice when
1165  * traversing connections. Note that it assumes we will
1166  * bus_connection_mark_stamp() each connection at least once per
1167  * INT_MAX increments of the global stamp, or wraparound would break
1168  * things.
1169  */
1170 void
1171 bus_connections_increment_stamp (BusConnections *connections)
1172 {
1173   connections->stamp += 1;
1174 }
1175
1176 /* Mark connection with current stamp, return TRUE if it
1177  * didn't already have that stamp
1178  */
1179 dbus_bool_t
1180 bus_connection_mark_stamp (DBusConnection *connection)
1181 {
1182   BusConnectionData *d;
1183   
1184   d = BUS_CONNECTION_DATA (connection);
1185   
1186   _dbus_assert (d != NULL);
1187
1188   if (d->stamp == d->connections->stamp)
1189     return FALSE;
1190   else
1191     {
1192       d->stamp = d->connections->stamp;
1193       return TRUE;
1194     }
1195 }
1196
1197 BusContext*
1198 bus_connection_get_context (DBusConnection *connection)
1199 {
1200   BusConnectionData *d;
1201
1202   d = BUS_CONNECTION_DATA (connection);
1203
1204   _dbus_assert (d != NULL);
1205
1206   return d->connections->context;
1207 }
1208
1209 BusConnections*
1210 bus_connection_get_connections (DBusConnection *connection)
1211 {
1212   BusConnectionData *d;
1213     
1214   d = BUS_CONNECTION_DATA (connection);
1215
1216   _dbus_assert (d != NULL);
1217
1218   return d->connections;
1219 }
1220
1221 BusRegistry*
1222 bus_connection_get_registry (DBusConnection *connection)
1223 {
1224   BusConnectionData *d;
1225
1226   d = BUS_CONNECTION_DATA (connection);
1227
1228   _dbus_assert (d != NULL);
1229
1230   return bus_context_get_registry (d->connections->context);
1231 }
1232
1233 BusActivation*
1234 bus_connection_get_activation (DBusConnection *connection)
1235 {
1236   BusConnectionData *d;
1237
1238   d = BUS_CONNECTION_DATA (connection);
1239
1240   _dbus_assert (d != NULL);
1241
1242   return bus_context_get_activation (d->connections->context);
1243 }
1244
1245 BusMatchmaker*
1246 bus_connection_get_matchmaker (DBusConnection *connection)
1247 {
1248   BusConnectionData *d;
1249
1250   d = BUS_CONNECTION_DATA (connection);
1251
1252   _dbus_assert (d != NULL);
1253
1254   return bus_context_get_matchmaker (d->connections->context);
1255 }
1256
1257 BusSELinuxID*
1258 bus_connection_get_selinux_id (DBusConnection *connection)
1259 {
1260   BusConnectionData *d;
1261
1262   d = BUS_CONNECTION_DATA (connection);
1263
1264   _dbus_assert (d != NULL);
1265
1266   return d->selinux_id;
1267 }
1268
1269 BusAppArmorConfinement*
1270 bus_connection_dup_apparmor_confinement (DBusConnection *connection)
1271 {
1272   BusConnectionData *d;
1273
1274   d = BUS_CONNECTION_DATA (connection);
1275
1276   _dbus_assert (d != NULL);
1277
1278   bus_apparmor_confinement_ref (d->apparmor_confinement);
1279   return d->apparmor_confinement;
1280 }
1281
1282 /**
1283  * Checks whether the connection is registered with the message bus.
1284  *
1285  * @param connection the connection
1286  * @returns #TRUE if we're an active message bus participant
1287  */
1288 dbus_bool_t
1289 bus_connection_is_active (DBusConnection *connection)
1290 {
1291   BusConnectionData *d;
1292
1293   d = BUS_CONNECTION_DATA (connection);
1294   _dbus_assert(d != NULL);
1295   
1296   return d->name != NULL;
1297 }
1298
1299 dbus_bool_t
1300 bus_connection_preallocate_oom_error (DBusConnection *connection)
1301 {
1302   DBusMessage *message;
1303   DBusPreallocatedSend *preallocated;
1304   BusConnectionData *d;
1305
1306   d = BUS_CONNECTION_DATA (connection);  
1307
1308   _dbus_assert (d != NULL);
1309
1310   if (d->oom_preallocated != NULL)
1311     return TRUE;
1312   
1313   preallocated = dbus_connection_preallocate_send (connection);
1314   if (preallocated == NULL)
1315     return FALSE;
1316
1317   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1318
1319   if (message == NULL)
1320     {
1321       dbus_connection_free_preallocated_send (connection, preallocated);
1322       return FALSE;
1323     }
1324
1325   /* d->name may be NULL, but that is OK */
1326   if (!dbus_message_set_error_name (message, DBUS_ERROR_NO_MEMORY) ||
1327       !dbus_message_set_destination (message, d->name) ||
1328       !dbus_message_set_sender (message,
1329                                 DBUS_SERVICE_DBUS))
1330     {
1331       dbus_connection_free_preallocated_send (connection, preallocated);
1332       dbus_message_unref (message);
1333       return FALSE;
1334     }
1335   
1336   /* set reply serial to placeholder value just so space is already allocated
1337    * for it.
1338    */
1339   if (!dbus_message_set_reply_serial (message, 14))
1340     {
1341       dbus_connection_free_preallocated_send (connection, preallocated);
1342       dbus_message_unref (message);
1343       return FALSE;
1344     }
1345
1346   d->oom_message = message;
1347   d->oom_preallocated = preallocated;
1348   
1349   return TRUE;
1350 }
1351
1352 void
1353 bus_connection_send_oom_error (DBusConnection *connection,
1354                                DBusMessage    *in_reply_to)
1355 {
1356   BusConnectionData *d;
1357
1358   d = BUS_CONNECTION_DATA (connection);  
1359
1360   _dbus_assert (d != NULL);  
1361   _dbus_assert (d->oom_message != NULL);
1362
1363   bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
1364                    "dbus-daemon transaction failed (OOM), sending error to "
1365                    "sender %s", bus_connection_get_loginfo (connection));
1366
1367   /* should always succeed since we set it to a placeholder earlier */
1368   if (!dbus_message_set_reply_serial (d->oom_message,
1369                                       dbus_message_get_serial (in_reply_to)))
1370     _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");
1371
1372   _dbus_assert (dbus_message_get_sender (d->oom_message) != NULL);
1373   
1374   dbus_connection_send_preallocated (connection, d->oom_preallocated,
1375                                      d->oom_message, NULL);
1376
1377   dbus_message_unref (d->oom_message);
1378   d->oom_message = NULL;
1379   d->oom_preallocated = NULL;
1380 }
1381
1382 #ifdef DBUS_ENABLE_STATS
1383 static void
1384 update_peak (int *peak,
1385              int n)
1386 {
1387   if (*peak < n)
1388     *peak = n;
1389 }
1390 #endif
1391
1392 void
1393 bus_connection_add_match_rule_link (DBusConnection *connection,
1394                                     DBusList       *link)
1395 {
1396   BusConnectionData *d;
1397
1398   d = BUS_CONNECTION_DATA (connection);
1399   _dbus_assert (d != NULL);
1400
1401   _dbus_list_append_link (&d->match_rules, link);
1402
1403   d->n_match_rules += 1;
1404
1405 #ifdef DBUS_ENABLE_STATS
1406   update_peak (&d->peak_match_rules, d->n_match_rules);
1407   update_peak (&d->connections->peak_match_rules_per_conn, d->n_match_rules);
1408
1409   d->connections->total_match_rules += 1;
1410   update_peak (&d->connections->peak_match_rules,
1411                d->connections->total_match_rules);
1412 #endif
1413 }
1414
1415 dbus_bool_t
1416 bus_connection_add_match_rule (DBusConnection *connection,
1417                                BusMatchRule   *rule)
1418 {
1419     DBusList *link;
1420
1421   link = _dbus_list_alloc_link (rule);
1422
1423   if (link == NULL)
1424     return FALSE;
1425
1426   bus_connection_add_match_rule_link (connection, link);
1427
1428   return TRUE;
1429 }
1430
1431 void
1432 bus_connection_remove_match_rule (DBusConnection *connection,
1433                                   BusMatchRule   *rule)
1434 {
1435   BusConnectionData *d;
1436
1437   d = BUS_CONNECTION_DATA (connection);
1438   _dbus_assert (d != NULL);
1439
1440   _dbus_list_remove_last (&d->match_rules, rule);
1441
1442   d->n_match_rules -= 1;
1443   _dbus_assert (d->n_match_rules >= 0);
1444
1445 #ifdef DBUS_ENABLE_STATS
1446   d->connections->total_match_rules -= 1;
1447 #endif
1448 }
1449
1450 int
1451 bus_connection_get_n_match_rules (DBusConnection *connection)
1452 {
1453   BusConnectionData *d;
1454
1455   d = BUS_CONNECTION_DATA (connection);
1456   _dbus_assert (d != NULL);
1457   
1458   return d->n_match_rules;
1459 }
1460
1461 dbus_bool_t
1462 bus_connection_is_service_owner_by_prefix (DBusConnection *connection,
1463                                            const char *name_prefix)
1464 {
1465   BusConnectionData *d;
1466   DBusList *link;
1467
1468   d = BUS_CONNECTION_DATA (connection);
1469   _dbus_assert (d != NULL);
1470
1471   link = _dbus_list_get_first_link (&d->services_owned);
1472   while (link != NULL)
1473     {
1474       BusService *service = link->data;
1475       DBusString str;
1476
1477       _dbus_string_init_const (&str, bus_service_get_name (service));
1478
1479       if (_dbus_string_starts_with_words_c_str (&str, name_prefix, '.'))
1480         return TRUE;
1481
1482       link = _dbus_list_get_next_link (&d->services_owned, link);
1483     }
1484
1485   return FALSE;
1486 }
1487
1488 void
1489 bus_connection_add_owned_service_link (DBusConnection *connection,
1490                                        DBusList       *link)
1491 {
1492   BusConnectionData *d;
1493
1494   d = BUS_CONNECTION_DATA (connection);
1495   _dbus_assert (d != NULL);
1496
1497   _dbus_list_append_link (&d->services_owned, link);
1498
1499   d->n_services_owned += 1;
1500
1501 #ifdef DBUS_ENABLE_STATS
1502   update_peak (&d->peak_bus_names, d->n_services_owned);
1503   update_peak (&d->connections->peak_bus_names_per_conn,
1504                d->n_services_owned);
1505
1506   d->connections->total_bus_names += 1;
1507   update_peak (&d->connections->peak_bus_names,
1508                d->connections->total_bus_names);
1509 #endif
1510 }
1511
1512 dbus_bool_t
1513 bus_connection_add_owned_service (DBusConnection *connection,
1514                                   BusService     *service)
1515 {
1516   DBusList *link;
1517
1518   link = _dbus_list_alloc_link (service);
1519
1520   if (link == NULL)
1521     return FALSE;
1522
1523   bus_connection_add_owned_service_link (connection, link);
1524
1525   return TRUE;
1526 }
1527
1528 void
1529 bus_connection_remove_owned_service (DBusConnection *connection,
1530                                      BusService     *service)
1531 {
1532   BusConnectionData *d;
1533
1534   d = BUS_CONNECTION_DATA (connection);
1535   _dbus_assert (d != NULL);
1536
1537   _dbus_list_remove_last (&d->services_owned, service);
1538
1539   d->n_services_owned -= 1;
1540   _dbus_assert (d->n_services_owned >= 0);
1541
1542 #ifdef DBUS_ENABLE_STATS
1543   d->connections->total_bus_names -= 1;
1544 #endif
1545 }
1546
1547 int
1548 bus_connection_get_n_services_owned (DBusConnection *connection)
1549 {
1550   BusConnectionData *d;
1551
1552   d = BUS_CONNECTION_DATA (connection);
1553   _dbus_assert (d != NULL);
1554   
1555   return d->n_services_owned;
1556 }
1557
1558 dbus_bool_t
1559 bus_connection_complete (DBusConnection   *connection,
1560                          const DBusString *name,
1561                          DBusError        *error)
1562 {
1563   BusConnectionData *d;
1564   unsigned long uid;
1565   
1566   d = BUS_CONNECTION_DATA (connection);
1567   _dbus_assert (d != NULL);
1568   _dbus_assert (d->name == NULL);
1569   _dbus_assert (d->policy == NULL);
1570
1571   _dbus_assert (!bus_connection_is_active (connection));
1572   
1573   if (!_dbus_string_copy_data (name, &d->name))
1574     {
1575       BUS_SET_OOM (error);
1576       return FALSE;
1577     }
1578
1579   _dbus_assert (d->name != NULL);
1580   
1581   _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);
1582
1583   d->policy = bus_context_create_client_policy (d->connections->context,
1584                                                 connection,
1585                                                 error);
1586
1587   /* we may have a NULL policy on OOM or error getting list of
1588    * groups for a user. In the latter case we don't handle it so
1589    * well currently, as it will just keep failing over and over.
1590    */
1591
1592   if (d->policy == NULL)
1593     {
1594       _dbus_verbose ("Failed to create security policy for connection %p\n",
1595                      connection);
1596       _DBUS_ASSERT_ERROR_IS_SET (error);
1597       dbus_free (d->name);
1598       d->name = NULL;
1599       return FALSE;
1600     }
1601   
1602   if (dbus_connection_get_unix_user (connection, &uid))
1603     {
1604       if (!adjust_connections_for_uid (d->connections,
1605                                        uid, 1))
1606         goto fail;
1607     }
1608
1609   /* Create and cache a string which holds information about the 
1610    * peer process; used for logging purposes.
1611    */
1612   if (!cache_peer_loginfo_string (d, connection))
1613     goto fail;
1614
1615   /* Now the connection is active, move it between lists */
1616   _dbus_list_unlink (&d->connections->incomplete,
1617                      d->link_in_connection_list);
1618   d->connections->n_incomplete -= 1;
1619   _dbus_list_append_link (&d->connections->completed,
1620                           d->link_in_connection_list);
1621   d->connections->n_completed += 1;
1622
1623   _dbus_assert (d->connections->n_incomplete >= 0);
1624   _dbus_assert (d->connections->n_completed > 0);
1625
1626   /* If we have dropped below the max. number of incomplete
1627    * connections, start accept()ing again */
1628   bus_context_check_all_watches (d->connections->context);
1629
1630   /* See if we can remove the timeout */
1631   bus_connections_expire_incomplete (d->connections);
1632
1633   _dbus_assert (bus_connection_is_active (connection));
1634   
1635   return TRUE;
1636 fail:
1637   BUS_SET_OOM (error);
1638   dbus_free (d->name);
1639   d->name = NULL;
1640   if (d->policy)
1641     bus_client_policy_unref (d->policy);
1642   d->policy = NULL;
1643   return FALSE;
1644 }
1645
1646 dbus_bool_t
1647 bus_connections_reload_policy (BusConnections *connections,
1648                                DBusError      *error)
1649 {
1650   BusConnectionData *d;
1651   DBusConnection *connection;
1652   DBusList *link;
1653
1654   _dbus_assert (connections != NULL);
1655   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1656
1657   for (link = _dbus_list_get_first_link (&(connections->completed));
1658        link;
1659        link = _dbus_list_get_next_link (&(connections->completed), link))
1660     {
1661       connection = link->data;
1662       d = BUS_CONNECTION_DATA (connection);
1663       _dbus_assert (d != NULL);
1664       _dbus_assert (d->policy != NULL);
1665
1666       bus_client_policy_unref (d->policy);
1667       d->policy = bus_context_create_client_policy (connections->context,
1668                                                     connection,
1669                                                     error);
1670       if (d->policy == NULL)
1671         {
1672           _dbus_verbose ("Failed to create security policy for connection %p\n",
1673                       connection);
1674           _DBUS_ASSERT_ERROR_IS_SET (error);
1675           return FALSE;
1676         }
1677     }
1678
1679   return TRUE;
1680 }
1681
1682 const char *
1683 bus_connection_get_name (DBusConnection *connection)
1684 {
1685   BusConnectionData *d;
1686   
1687   d = BUS_CONNECTION_DATA (connection);
1688   _dbus_assert (d != NULL);
1689   
1690   return d->name;
1691 }
1692
1693 /**
1694  * Check whether completing the passed-in connection would
1695  * exceed limits, and if so set error and return #FALSE
1696  */
1697 dbus_bool_t
1698 bus_connections_check_limits (BusConnections  *connections,
1699                               DBusConnection  *requesting_completion,
1700                               DBusError       *error)
1701 {
1702   unsigned long uid;
1703
1704   if (connections->n_completed >=
1705       bus_context_get_max_completed_connections (connections->context))
1706     {
1707       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1708                       "The maximum number of active connections has been reached");
1709       return FALSE;
1710     }
1711   
1712   if (dbus_connection_get_unix_user (requesting_completion, &uid))
1713     {
1714       if (get_connections_for_uid (connections, uid) >=
1715           bus_context_get_max_connections_per_user (connections->context))
1716         {
1717           dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1718                           "The maximum number of active connections for UID %lu has been reached",
1719                           uid);
1720           return FALSE;
1721         }
1722     }
1723   
1724   return TRUE;
1725 }
1726
1727 static void
1728 bus_pending_reply_free (BusPendingReply *pending)
1729 {
1730   _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
1731                  pending,
1732                  pending->will_send_reply,
1733                  pending->will_get_reply,
1734                  pending->reply_serial);
1735
1736   dbus_free (pending);
1737 }
1738
1739 static dbus_bool_t
1740 bus_pending_reply_send_no_reply (BusConnections  *connections,
1741                                  BusTransaction  *transaction,
1742                                  BusPendingReply *pending)
1743 {
1744   DBusMessage *message;
1745   DBusMessageIter iter;
1746   dbus_bool_t retval;
1747   const char *errmsg;
1748
1749   retval = FALSE;
1750   
1751   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1752   if (message == NULL)
1753     return FALSE;
1754   
1755   dbus_message_set_no_reply (message, TRUE);
1756   
1757   if (!dbus_message_set_reply_serial (message,
1758                                       pending->reply_serial))
1759     goto out;
1760
1761   if (!dbus_message_set_error_name (message,
1762                                     DBUS_ERROR_NO_REPLY))
1763     goto out;
1764
1765   /* If you change these messages, adjust test/dbus-daemon.c to match */
1766   if (pending->will_send_reply == NULL)
1767     errmsg = "Message recipient disconnected from message bus without replying";
1768   else
1769     errmsg = "Message did not receive a reply (timeout by message bus)";
1770
1771   dbus_message_iter_init_append (message, &iter);
1772   if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
1773     goto out;
1774     
1775   if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
1776                                          message))
1777     goto out;
1778
1779   retval = TRUE;
1780
1781  out:
1782   dbus_message_unref (message);
1783   return retval;
1784 }
1785
1786 static dbus_bool_t
1787 bus_pending_reply_expired (BusExpireList *list,
1788                            DBusList      *link,
1789                            void          *data)
1790 {
1791   BusPendingReply *pending = link->data;
1792   BusConnections *connections = data;
1793   BusTransaction *transaction;
1794   
1795   /* No reply is forthcoming. So nuke it if we can. If not,
1796    * leave it in the list to try expiring again later when we
1797    * get more memory.
1798    */
1799
1800   _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
1801                  pending,
1802                  pending->will_send_reply,
1803                  pending->will_get_reply,
1804                  pending->reply_serial);
1805   
1806   transaction = bus_transaction_new (connections->context);
1807   if (transaction == NULL)
1808     return FALSE;
1809   
1810   if (!bus_pending_reply_send_no_reply (connections,
1811                                         transaction,
1812                                         pending))
1813     {
1814       bus_transaction_cancel_and_free (transaction);
1815       return FALSE;
1816     }
1817
1818   bus_expire_list_remove_link (connections->pending_replies, link);
1819
1820   bus_pending_reply_free (pending);
1821   bus_transaction_execute_and_free (transaction);
1822
1823   return TRUE;
1824 }
1825
1826 static void
1827 bus_connection_drop_pending_replies (BusConnections  *connections,
1828                                      DBusConnection  *connection)
1829 {
1830   /* The DBusConnection is almost 100% finalized here, so you can't
1831    * do anything with it except check for pointer equality
1832    */
1833   DBusList *link;
1834
1835   _dbus_verbose ("Dropping pending replies that involve connection %p\n",
1836                  connection);
1837   
1838   link = bus_expire_list_get_first_link (connections->pending_replies);
1839   while (link != NULL)
1840     {
1841       DBusList *next;
1842       BusPendingReply *pending;
1843
1844       next = bus_expire_list_get_next_link (connections->pending_replies,
1845                                             link);
1846       pending = link->data;
1847
1848       if (pending->will_get_reply == connection)
1849         {
1850           /* We don't need to track this pending reply anymore */
1851
1852           _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
1853                          pending,
1854                          pending->will_send_reply,
1855                          pending->will_get_reply,
1856                          pending->reply_serial);
1857           
1858           bus_expire_list_remove_link (connections->pending_replies,
1859                                        link);
1860           bus_pending_reply_free (pending);
1861         }
1862       else if (pending->will_send_reply == connection)
1863         {
1864           /* The reply isn't going to be sent, so set things
1865            * up so it will be expired right away
1866            */
1867           _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
1868                          pending,
1869                          pending->will_send_reply,
1870                          pending->will_get_reply,
1871                          pending->reply_serial);
1872           
1873           pending->will_send_reply = NULL;
1874           pending->expire_item.added_tv_sec = 0;
1875           pending->expire_item.added_tv_usec = 0;
1876
1877           bus_expire_list_recheck_immediately (connections->pending_replies);
1878         }
1879       
1880       link = next;
1881     }
1882 }
1883
1884
1885 typedef struct
1886 {
1887   BusPendingReply *pending;
1888   BusConnections  *connections;
1889 } CancelPendingReplyData;
1890
1891 static void
1892 cancel_pending_reply (void *data)
1893 {
1894   CancelPendingReplyData *d = data;
1895
1896   _dbus_verbose ("d = %p\n", d);
1897   
1898   if (!bus_expire_list_remove (d->connections->pending_replies,
1899                                &d->pending->expire_item))
1900     _dbus_assert_not_reached ("pending reply did not exist to be cancelled");
1901
1902   bus_pending_reply_free (d->pending); /* since it's been cancelled */
1903 }
1904
1905 static void
1906 cancel_pending_reply_data_free (void *data)
1907 {
1908   CancelPendingReplyData *d = data;
1909
1910   _dbus_verbose ("d = %p\n", d);
1911   
1912   /* d->pending should be either freed or still
1913    * in the list of pending replies (owned by someone
1914    * else)
1915    */
1916   
1917   dbus_free (d);
1918 }
1919
1920 /*
1921  * Record that a reply is allowed; return TRUE on success.
1922  */
1923 dbus_bool_t
1924 bus_connections_expect_reply (BusConnections  *connections,
1925                               BusTransaction  *transaction,
1926                               DBusConnection  *will_get_reply,
1927                               DBusConnection  *will_send_reply,
1928                               DBusMessage     *reply_to_this,
1929                               DBusError       *error)
1930 {
1931   BusPendingReply *pending;
1932   dbus_uint32_t reply_serial;
1933   DBusList *link;
1934   CancelPendingReplyData *cprd;
1935   int count;
1936
1937   _dbus_assert (will_get_reply != NULL);
1938   _dbus_assert (will_send_reply != NULL);
1939   _dbus_assert (reply_to_this != NULL);
1940   
1941   if (dbus_message_get_no_reply (reply_to_this))
1942     return TRUE; /* we won't allow a reply, since client doesn't care for one. */
1943   
1944   reply_serial = dbus_message_get_serial (reply_to_this);
1945
1946   link = bus_expire_list_get_first_link (connections->pending_replies);
1947   count = 0;
1948   while (link != NULL)
1949     {
1950       pending = link->data;
1951
1952       if (pending->reply_serial == reply_serial &&
1953           pending->will_get_reply == will_get_reply &&
1954           pending->will_send_reply == will_send_reply)
1955         {
1956           dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1957                           "Message has the same reply serial as a currently-outstanding existing method call");
1958           return FALSE;
1959         }
1960       
1961       link = bus_expire_list_get_next_link (connections->pending_replies,
1962                                             link);
1963       if (pending->will_get_reply == will_get_reply)
1964         ++count;
1965     }
1966   
1967   if (count >=
1968       bus_context_get_max_replies_per_connection (connections->context))
1969     {
1970       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1971                       "The maximum number of pending replies per connection has been reached");
1972       return FALSE;
1973     }
1974
1975   pending = dbus_new0 (BusPendingReply, 1);
1976   if (pending == NULL)
1977     {
1978       BUS_SET_OOM (error);
1979       return FALSE;
1980     }
1981
1982 #ifdef DBUS_ENABLE_VERBOSE_MODE
1983   /* so we can see a not-yet-added pending reply */
1984   pending->expire_item.added_tv_sec = 1;
1985   pending->expire_item.added_tv_usec = 1;
1986 #endif
1987
1988   pending->will_get_reply = will_get_reply;
1989   pending->will_send_reply = will_send_reply;
1990   pending->reply_serial = reply_serial;
1991   
1992   cprd = dbus_new0 (CancelPendingReplyData, 1);
1993   if (cprd == NULL)
1994     {
1995       BUS_SET_OOM (error);
1996       bus_pending_reply_free (pending);
1997       return FALSE;
1998     }
1999   
2000   if (!bus_expire_list_add (connections->pending_replies,
2001                             &pending->expire_item))
2002     {
2003       BUS_SET_OOM (error);
2004       dbus_free (cprd);
2005       bus_pending_reply_free (pending);
2006       return FALSE;
2007     }
2008
2009   if (!bus_transaction_add_cancel_hook (transaction,
2010                                         cancel_pending_reply,
2011                                         cprd,
2012                                         cancel_pending_reply_data_free))
2013     {
2014       BUS_SET_OOM (error);
2015       bus_expire_list_remove (connections->pending_replies, &pending->expire_item);
2016       dbus_free (cprd);
2017       bus_pending_reply_free (pending);
2018       return FALSE;
2019     }
2020                                         
2021   cprd->pending = pending;
2022   cprd->connections = connections;
2023   
2024   _dbus_get_monotonic_time (&pending->expire_item.added_tv_sec,
2025                             &pending->expire_item.added_tv_usec);
2026
2027   _dbus_verbose ("Added pending reply %p, replier %p receiver %p serial %u\n",
2028                  pending,
2029                  pending->will_send_reply,
2030                  pending->will_get_reply,
2031                  pending->reply_serial);
2032   
2033   return TRUE;
2034 }
2035
2036 typedef struct
2037 {
2038   DBusList        *link;
2039   BusConnections  *connections;
2040 } CheckPendingReplyData;
2041
2042 static void
2043 cancel_check_pending_reply (void *data)
2044 {
2045   CheckPendingReplyData *d = data;
2046
2047   _dbus_verbose ("d = %p\n",d);
2048
2049   bus_expire_list_add_link (d->connections->pending_replies,
2050                             d->link);
2051   d->link = NULL;
2052 }
2053
2054 static void
2055 check_pending_reply_data_free (void *data)
2056 {
2057   CheckPendingReplyData *d = data;
2058
2059   _dbus_verbose ("d = %p\n",d);
2060   
2061   if (d->link != NULL)
2062     {
2063       BusPendingReply *pending = d->link->data;
2064       
2065       _dbus_assert (!bus_expire_list_contains_item (d->connections->pending_replies,
2066                                                     &pending->expire_item));
2067       
2068       bus_pending_reply_free (pending);
2069       _dbus_list_free_link (d->link);
2070     }
2071   
2072   dbus_free (d);
2073 }
2074
2075 /*
2076  * Check whether a reply is allowed, remove BusPendingReply
2077  * if so, return TRUE if so.
2078  */
2079 dbus_bool_t
2080 bus_connections_check_reply (BusConnections *connections,
2081                              BusTransaction *transaction,
2082                              DBusConnection *sending_reply,
2083                              DBusConnection *receiving_reply,
2084                              DBusMessage    *reply,
2085                              DBusError      *error)
2086 {
2087   CheckPendingReplyData *cprd;
2088   DBusList *link;
2089   dbus_uint32_t reply_serial;
2090   
2091   _dbus_assert (sending_reply != NULL);
2092   _dbus_assert (receiving_reply != NULL);
2093
2094   reply_serial = dbus_message_get_reply_serial (reply);
2095
2096   link = bus_expire_list_get_first_link (connections->pending_replies);
2097   while (link != NULL)
2098     {
2099       BusPendingReply *pending = link->data;
2100
2101       if (pending->reply_serial == reply_serial &&
2102           pending->will_get_reply == receiving_reply &&
2103           pending->will_send_reply == sending_reply)
2104         {
2105           _dbus_verbose ("Found pending reply with serial %u\n", reply_serial);
2106           break;
2107         }
2108       
2109       link = bus_expire_list_get_next_link (connections->pending_replies,
2110                                             link);
2111     }
2112
2113   if (link == NULL)
2114     {
2115       _dbus_verbose ("No pending reply expected\n");
2116
2117       return FALSE;
2118     }
2119
2120   cprd = dbus_new0 (CheckPendingReplyData, 1);
2121   if (cprd == NULL)
2122     {
2123       BUS_SET_OOM (error);
2124       return FALSE;
2125     }
2126   
2127   if (!bus_transaction_add_cancel_hook (transaction,
2128                                         cancel_check_pending_reply,
2129                                         cprd,
2130                                         check_pending_reply_data_free))
2131     {
2132       BUS_SET_OOM (error);
2133       dbus_free (cprd);
2134       return FALSE;
2135     }
2136
2137   cprd->link = link;
2138   cprd->connections = connections;
2139   
2140   bus_expire_list_unlink (connections->pending_replies,
2141                           link);
2142   
2143   _dbus_assert (!bus_expire_list_contains_item (connections->pending_replies, link->data));
2144
2145   return TRUE;
2146 }
2147
2148 /*
2149  * Transactions
2150  *
2151  * Note that this is fairly fragile; in particular, don't try to use
2152  * one transaction across any main loop iterations.
2153  */
2154
2155 typedef struct
2156 {
2157   BusTransaction *transaction;
2158   DBusMessage    *message;
2159   DBusPreallocatedSend *preallocated;
2160 } MessageToSend;
2161
2162 typedef struct
2163 {
2164   BusTransactionCancelFunction cancel_function;
2165   DBusFreeFunction free_data_function;
2166   void *data;
2167 } CancelHook;
2168
2169 struct BusTransaction
2170 {
2171   DBusList *connections;
2172   BusContext *context;
2173   DBusList *cancel_hooks;
2174 };
2175
2176 static void
2177 message_to_send_free (DBusConnection *connection,
2178                       MessageToSend  *to_send)
2179 {
2180   if (to_send->message)
2181     dbus_message_unref (to_send->message);
2182
2183   if (to_send->preallocated)
2184     dbus_connection_free_preallocated_send (connection, to_send->preallocated);
2185
2186   dbus_free (to_send);
2187 }
2188
2189 static void
2190 cancel_hook_cancel (void *element,
2191                     void *data)
2192 {
2193   CancelHook *ch = element;
2194
2195   _dbus_verbose ("Running transaction cancel hook\n");
2196   
2197   if (ch->cancel_function)
2198     (* ch->cancel_function) (ch->data);  
2199 }
2200
2201 static void
2202 cancel_hook_free (void *element,
2203                   void *data)
2204 {
2205   CancelHook *ch = element;
2206
2207   if (ch->free_data_function)
2208     (* ch->free_data_function) (ch->data);
2209
2210   dbus_free (ch);
2211 }
2212
2213 static void
2214 free_cancel_hooks (BusTransaction *transaction)
2215 {
2216   _dbus_list_foreach (&transaction->cancel_hooks,
2217                       cancel_hook_free, NULL);
2218   
2219   _dbus_list_clear (&transaction->cancel_hooks);
2220 }
2221
2222 BusTransaction*
2223 bus_transaction_new (BusContext *context)
2224 {
2225   BusTransaction *transaction;
2226
2227   transaction = dbus_new0 (BusTransaction, 1);
2228   if (transaction == NULL)
2229     return NULL;
2230
2231   transaction->context = context;
2232   
2233   return transaction;
2234 }
2235
2236 BusContext*
2237 bus_transaction_get_context (BusTransaction  *transaction)
2238 {
2239   return transaction->context;
2240 }
2241
2242 /**
2243  * Reserve enough memory to capture the given message if the
2244  * transaction goes through.
2245  */
2246 dbus_bool_t
2247 bus_transaction_capture (BusTransaction *transaction,
2248                          DBusConnection *sender,
2249                          DBusMessage    *message)
2250 {
2251   BusConnections *connections;
2252   BusMatchmaker *mm;
2253   DBusList *link;
2254   DBusList *recipients = NULL;
2255   dbus_bool_t ret = FALSE;
2256
2257   connections = bus_context_get_connections (transaction->context);
2258
2259   /* shortcut: don't compose the message unless someone wants it */
2260   if (connections->monitors == NULL)
2261     return TRUE;
2262
2263   mm = connections->monitor_matchmaker;
2264   /* This is non-null if there has ever been a monitor - we don't GC it.
2265    * There's little point, since there is up to 1 per process. */
2266   _dbus_assert (mm != NULL);
2267
2268   if (!bus_matchmaker_get_recipients (mm, connections, sender, NULL, message,
2269         &recipients))
2270     goto out;
2271
2272   for (link = _dbus_list_get_first_link (&recipients);
2273       link != NULL;
2274       link = _dbus_list_get_next_link (&recipients, link))
2275     {
2276       DBusConnection *recipient = link->data;
2277
2278       if (!bus_transaction_send (transaction, recipient, message, FALSE))
2279         goto out;
2280     }
2281
2282   ret = TRUE;
2283
2284 out:
2285   _dbus_list_clear (&recipients);
2286   return ret;
2287 }
2288
2289 dbus_bool_t
2290 bus_transaction_capture_error_reply (BusTransaction  *transaction,
2291                                      const DBusError *error,
2292                                      DBusMessage     *in_reply_to)
2293 {
2294   BusConnections *connections;
2295   DBusMessage *reply;
2296   dbus_bool_t ret = FALSE;
2297
2298   _dbus_assert (error != NULL);
2299   _DBUS_ASSERT_ERROR_IS_SET (error);
2300
2301   connections = bus_context_get_connections (transaction->context);
2302
2303   /* shortcut: don't compose the message unless someone wants it */
2304   if (connections->monitors == NULL)
2305     return TRUE;
2306
2307   reply = dbus_message_new_error (in_reply_to,
2308                                   error->name,
2309                                   error->message);
2310
2311   if (reply == NULL)
2312     return FALSE;
2313
2314   if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2315     goto out;
2316
2317   ret = bus_transaction_capture (transaction, NULL, reply);
2318
2319 out:
2320   dbus_message_unref (reply);
2321   return ret;
2322 }
2323
2324 dbus_bool_t
2325 bus_transaction_send_from_driver (BusTransaction *transaction,
2326                                   DBusConnection *connection,
2327                                   DBusMessage    *message)
2328 {
2329   DBusError error = DBUS_ERROR_INIT;
2330   BusDeferredMessage *deferred_message;
2331
2332   /* We have to set the sender to the driver, and have
2333    * to check security policy since it was not done in
2334    * dispatch.c
2335    */
2336   _dbus_verbose ("Sending %s %s %s from driver\n",
2337                  dbus_message_get_interface (message) ?
2338                  dbus_message_get_interface (message) : "(no interface)",
2339                  dbus_message_get_member (message) ?
2340                  dbus_message_get_member (message) : "(no member)",
2341                  dbus_message_get_error_name (message) ?
2342                  dbus_message_get_error_name (message) : "(no error name)");
2343                  
2344   if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2345     return FALSE;
2346
2347   if (bus_connection_is_active (connection))
2348     {
2349       if (!dbus_message_set_destination (message,
2350                                          bus_connection_get_name (connection)))
2351         return FALSE;
2352     }
2353   
2354   /* bus driver never wants a reply */
2355   dbus_message_set_no_reply (message, TRUE);
2356
2357   /* Capture it for monitors, even if the real recipient's receive policy
2358    * does not allow it to receive this message from us (which would be odd).
2359    */
2360   if (!bus_transaction_capture (transaction, NULL, message))
2361     return FALSE;
2362
2363   /* If security policy doesn't allow the message, we would silently
2364    * eat it; the driver doesn't care about getting a reply. However,
2365    * if we're actively capturing messages, it's nice to log that we
2366    * tried to send it and did not allow ourselves to do so.
2367    */
2368   switch (bus_context_check_security_policy (bus_transaction_get_context (transaction),
2369                                              transaction,
2370                                              NULL, connection, connection,
2371                                              message, NULL, &error,
2372                                              &deferred_message))
2373     {
2374     case BUS_RESULT_TRUE:
2375       break;
2376     case BUS_RESULT_FALSE:
2377       if (!bus_transaction_capture_error_reply (transaction, &error, message))
2378         {
2379           bus_context_log (transaction->context, DBUS_SYSTEM_LOG_WARNING,
2380                            "message from dbus-daemon rejected but not enough "
2381                            "memory to capture it");
2382         }
2383
2384       /* This is not fatal to the transaction so silently eat the disallowed
2385        * message (see reasoning above) */
2386       dbus_error_free (&error);
2387       return TRUE;
2388       break;
2389     case BUS_RESULT_LATER:
2390       if (!bus_deferred_message_queue_at_recipient(deferred_message, transaction, FALSE, FALSE))
2391           return FALSE;
2392       return TRUE; /* pretend to have sent it */
2393     }
2394
2395   return bus_transaction_send (transaction, connection, message, FALSE);
2396 }
2397
2398 dbus_bool_t
2399 bus_transaction_send (BusTransaction *transaction,
2400                       DBusConnection *connection,
2401                       DBusMessage    *message,
2402                       dbus_bool_t     deferred_dispatch)
2403 {
2404   MessageToSend *to_send;
2405   BusConnectionData *d;
2406   DBusList *link;
2407
2408   _dbus_verbose ("  trying to add %s interface=%s member=%s error=%s to transaction%s\n",
2409                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ? "error" :
2410                  dbus_message_get_reply_serial (message) != 0 ? "reply" :
2411                  "message",
2412                  dbus_message_get_interface (message) ?
2413                  dbus_message_get_interface (message) : "(unset)",
2414                  dbus_message_get_member (message) ?
2415                  dbus_message_get_member (message) : "(unset)",
2416                  dbus_message_get_error_name (message) ?
2417                  dbus_message_get_error_name (message) : "(unset)",
2418                  dbus_connection_get_is_connected (connection) ?
2419                  "" : " (disconnected)");
2420
2421   _dbus_assert (dbus_message_get_sender (message) != NULL);
2422   
2423   if (!dbus_connection_get_is_connected (connection))
2424     return TRUE; /* silently ignore disconnected connections */
2425   
2426   d = BUS_CONNECTION_DATA (connection);
2427   _dbus_assert (d != NULL);
2428
2429   if (!deferred_dispatch && d->deferred_messages != NULL)
2430     {
2431       BusDeferredMessage *deferred_message;
2432       dbus_bool_t success;
2433       /* sender and addressed recipient are not required at this point as we only need to send message
2434        * to a single recipient without performing policy check. */
2435       deferred_message = bus_deferred_message_new (message,
2436                                                    NULL,
2437                                                    NULL,
2438                                                    connection,
2439                                                    BUS_RESULT_TRUE);
2440       if (deferred_message == NULL)
2441         return FALSE;
2442
2443       success = bus_deferred_message_queue_at_recipient(deferred_message, transaction,
2444           FALSE, FALSE);
2445       bus_deferred_message_unref(deferred_message);
2446
2447       return success;
2448     }
2449
2450   to_send = dbus_new (MessageToSend, 1);
2451   if (to_send == NULL)
2452     {
2453       return FALSE;
2454     }
2455
2456   to_send->preallocated = dbus_connection_preallocate_send (connection);
2457   if (to_send->preallocated == NULL)
2458     {
2459       dbus_free (to_send);
2460       return FALSE;
2461     }  
2462   
2463   dbus_message_ref (message);
2464   to_send->message = message;
2465   to_send->transaction = transaction;
2466
2467   _dbus_verbose ("about to prepend message\n");
2468   
2469   if (!_dbus_list_prepend (&d->transaction_messages, to_send))
2470     {
2471       message_to_send_free (connection, to_send);
2472       return FALSE;
2473     }
2474
2475   _dbus_verbose ("prepended message\n");
2476   
2477   /* See if we already had this connection in the list
2478    * for this transaction. If we have a pending message,
2479    * then we should already be in transaction->connections
2480    */
2481   link = _dbus_list_get_first_link (&d->transaction_messages);
2482   _dbus_assert (link->data == to_send);
2483   link = _dbus_list_get_next_link (&d->transaction_messages, link);
2484   while (link != NULL)
2485     {
2486       MessageToSend *m = link->data;
2487       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2488       
2489       if (m->transaction == transaction)
2490         break;
2491         
2492       link = next;
2493     }
2494
2495   if (link == NULL)
2496     {
2497       if (!_dbus_list_prepend (&transaction->connections, connection))
2498         {
2499           _dbus_list_remove (&d->transaction_messages, to_send);
2500           message_to_send_free (connection, to_send);
2501           return FALSE;
2502         }
2503     }
2504
2505   return TRUE;
2506 }
2507
2508 static void
2509 transaction_free (BusTransaction *transaction)
2510 {
2511   _dbus_assert (transaction->connections == NULL);
2512
2513   free_cancel_hooks (transaction);
2514
2515   dbus_free (transaction);
2516 }
2517
2518 static void
2519 connection_cancel_transaction (DBusConnection *connection,
2520                                BusTransaction *transaction)
2521 {
2522   DBusList *link;
2523   BusConnectionData *d;
2524   
2525   d = BUS_CONNECTION_DATA (connection);
2526   _dbus_assert (d != NULL);
2527   
2528   link = _dbus_list_get_first_link (&d->transaction_messages);
2529   while (link != NULL)
2530     {
2531       MessageToSend *m = link->data;
2532       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2533       
2534       if (m->transaction == transaction)
2535         {
2536           _dbus_list_remove_link (&d->transaction_messages,
2537                                   link);
2538           
2539           message_to_send_free (connection, m);
2540         }
2541         
2542       link = next;
2543     }
2544 }
2545
2546 void
2547 bus_transaction_cancel_and_free (BusTransaction *transaction)
2548 {
2549   DBusConnection *connection;
2550
2551   _dbus_verbose ("TRANSACTION: cancelled\n");
2552   
2553   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2554     connection_cancel_transaction (connection, transaction);
2555
2556   _dbus_list_foreach (&transaction->cancel_hooks,
2557                       cancel_hook_cancel, NULL);
2558
2559   transaction_free (transaction);
2560 }
2561
2562 static void
2563 connection_execute_transaction (DBusConnection *connection,
2564                                 BusTransaction *transaction)
2565 {
2566   DBusList *link;
2567   BusConnectionData *d;
2568   
2569   d = BUS_CONNECTION_DATA (connection);
2570   _dbus_assert (d != NULL);
2571
2572   /* Send the queue in order (FIFO) */
2573   link = _dbus_list_get_last_link (&d->transaction_messages);
2574   while (link != NULL)
2575     {
2576       MessageToSend *m = link->data;
2577       DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
2578       
2579       if (m->transaction == transaction)
2580         {
2581           _dbus_list_remove_link (&d->transaction_messages,
2582                                   link);
2583
2584           _dbus_assert (dbus_message_get_sender (m->message) != NULL);
2585           
2586           dbus_connection_send_preallocated (connection,
2587                                              m->preallocated,
2588                                              m->message,
2589                                              NULL);
2590
2591           m->preallocated = NULL; /* so we don't double-free it */
2592           
2593           message_to_send_free (connection, m);
2594         }
2595         
2596       link = prev;
2597     }
2598 }
2599
2600 void
2601 bus_transaction_execute_and_free (BusTransaction *transaction)
2602 {
2603   /* For each connection in transaction->connections
2604    * send the messages
2605    */
2606   DBusConnection *connection;
2607
2608   _dbus_verbose ("TRANSACTION: executing\n");
2609   
2610   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2611     connection_execute_transaction (connection, transaction);
2612
2613   transaction_free (transaction);
2614 }
2615
2616 static void
2617 bus_connection_remove_transactions (DBusConnection *connection)
2618 {
2619   MessageToSend *to_send;
2620   BusConnectionData *d;
2621   
2622   d = BUS_CONNECTION_DATA (connection);
2623   _dbus_assert (d != NULL);
2624   
2625   while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
2626     {
2627       /* only has an effect for the first MessageToSend listing this transaction */
2628       _dbus_list_remove (&to_send->transaction->connections,
2629                          connection);
2630
2631       _dbus_list_remove (&d->transaction_messages, to_send);
2632       message_to_send_free (connection, to_send);
2633     }
2634 }
2635
2636 /**
2637  * Converts the DBusError to a message reply
2638  */
2639 dbus_bool_t
2640 bus_transaction_send_error_reply (BusTransaction  *transaction,
2641                                   DBusConnection  *connection,
2642                                   const DBusError *error,
2643                                   DBusMessage     *in_reply_to)
2644 {
2645   DBusMessage *reply;
2646   
2647   _dbus_assert (error != NULL);
2648   _DBUS_ASSERT_ERROR_IS_SET (error);
2649   
2650   _dbus_verbose ("Sending error reply %s \"%s\"\n",
2651                  error->name, error->message);
2652
2653   reply = dbus_message_new_error (in_reply_to,
2654                                   error->name,
2655                                   error->message);
2656   if (reply == NULL)
2657     return FALSE;
2658
2659   if (!bus_transaction_send_from_driver (transaction, connection, reply))
2660     {
2661       dbus_message_unref (reply);
2662       return FALSE;
2663     }
2664
2665   dbus_message_unref (reply);
2666   
2667   return TRUE;
2668 }
2669
2670 dbus_bool_t
2671 bus_transaction_add_cancel_hook (BusTransaction               *transaction,
2672                                  BusTransactionCancelFunction  cancel_function,
2673                                  void                         *data,
2674                                  DBusFreeFunction              free_data_function)
2675 {
2676   CancelHook *ch;
2677
2678   ch = dbus_new (CancelHook, 1);
2679   if (ch == NULL)
2680     return FALSE;
2681
2682   _dbus_verbose ("     adding cancel hook function = %p data = %p\n",
2683                  cancel_function, data);
2684   
2685   ch->cancel_function = cancel_function;
2686   ch->data = data;
2687   ch->free_data_function = free_data_function;
2688
2689   /* It's important that the hooks get run in reverse order that they
2690    * were added
2691    */
2692   if (!_dbus_list_prepend (&transaction->cancel_hooks, ch))
2693     {
2694       dbus_free (ch);
2695       return FALSE;
2696     }
2697
2698   return TRUE;
2699 }
2700
2701 void
2702 bus_connection_dispatch_deferred (DBusConnection *connection)
2703 {
2704   BusDeferredMessage *message;
2705
2706   _dbus_return_if_fail (connection != NULL);
2707
2708   while ((message = bus_connection_pop_deferred_message(connection)) != NULL)
2709     {
2710       bus_deferred_message_dispatch(message);
2711       bus_deferred_message_unref(message);
2712     }
2713 }
2714
2715 dbus_bool_t
2716 bus_connection_has_deferred_messages (DBusConnection *connection)
2717 {
2718   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2719   return d->deferred_messages != NULL ? TRUE : FALSE;
2720 }
2721
2722 dbus_bool_t
2723 bus_connection_queue_deferred_message (DBusConnection *connection,
2724                                        BusDeferredMessage *message,
2725                                        dbus_bool_t prepend)
2726 {
2727   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2728   dbus_bool_t success;
2729   if (prepend)
2730     success = _dbus_list_prepend(&d->deferred_messages, message);
2731   else
2732     success = _dbus_list_append(&d->deferred_messages, message);
2733
2734   if (success)
2735     {
2736       bus_deferred_message_ref(message);
2737       return TRUE;
2738     }
2739
2740   return FALSE;
2741 }
2742
2743 dbus_bool_t
2744 bus_connection_replace_deferred_message (DBusConnection *connection,
2745                                          BusDeferredMessage *oldMessage,
2746                                          BusDeferredMessage *newMessage)
2747 {
2748   DBusList *link;
2749   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2750
2751   link = _dbus_list_find_first(&d->deferred_messages, oldMessage);
2752   if (link == NULL)
2753     return FALSE;
2754
2755   if (!_dbus_list_insert_after(&d->deferred_messages, link, newMessage))
2756     return FALSE;
2757
2758   bus_deferred_message_ref(newMessage);
2759   _dbus_list_remove_link(&d->deferred_messages, link);
2760   bus_deferred_message_unref(oldMessage);
2761   return TRUE;
2762 }
2763
2764 BusDeferredMessage *
2765 bus_connection_pop_deferred_message (DBusConnection *connection)
2766 {
2767   DBusList *link;
2768   BusDeferredMessage *message;
2769   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2770
2771   link =_dbus_list_get_first_link(&d->deferred_messages);
2772   if (link != NULL)
2773     {
2774       message = link->data;
2775       if (!bus_deferred_message_waits_for_check(message))
2776         {
2777           _dbus_list_remove_link(&d->deferred_messages, link);
2778           return message;
2779         }
2780     }
2781
2782   return NULL;
2783 }
2784
2785 dbus_bool_t
2786 bus_connection_putback_deferred_message (DBusConnection *connection, BusDeferredMessage *message)
2787 {
2788   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2789   if (_dbus_list_prepend(&d->deferred_messages, message))
2790     {
2791       return TRUE;
2792     }
2793   return FALSE;
2794 }
2795
2796 void
2797 bus_connection_clear_deferred_messages (DBusConnection *connection)
2798 {
2799   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2800   DBusList *link;
2801   DBusList *next;
2802   BusDeferredMessage *message;
2803
2804   link =_dbus_list_get_first_link(&d->deferred_messages);
2805   while (link != NULL)
2806     {
2807       next = _dbus_list_get_next_link (&d->deferred_messages, link);
2808       message = link->data;
2809
2810       bus_deferred_message_unref(message);
2811       _dbus_list_remove_link(&d->deferred_messages, link);
2812
2813       link = next;
2814     }
2815 }
2816
2817 void
2818 bus_connection_remove_deferred_message (DBusConnection *connection,
2819                                         BusDeferredMessage *message)
2820 {
2821   BusConnectionData *d = BUS_CONNECTION_DATA(connection);
2822   if (_dbus_list_remove(&d->deferred_messages, message))
2823     bus_deferred_message_unref(message);
2824 }
2825
2826 int
2827 bus_connections_get_n_active (BusConnections *connections)
2828 {
2829   return connections->n_completed;
2830 }
2831
2832 int
2833 bus_connections_get_n_incomplete (BusConnections *connections)
2834 {
2835   return connections->n_incomplete;
2836 }
2837
2838 #ifdef DBUS_ENABLE_STATS
2839 int
2840 bus_connections_get_total_match_rules (BusConnections *connections)
2841 {
2842   return connections->total_match_rules;
2843 }
2844
2845 int
2846 bus_connections_get_peak_match_rules (BusConnections *connections)
2847 {
2848   return connections->peak_match_rules;
2849 }
2850
2851 int
2852 bus_connections_get_peak_match_rules_per_conn (BusConnections *connections)
2853 {
2854   return connections->peak_match_rules_per_conn;
2855 }
2856
2857 int
2858 bus_connections_get_total_bus_names (BusConnections *connections)
2859 {
2860   return connections->total_bus_names;
2861 }
2862
2863 int
2864 bus_connections_get_peak_bus_names (BusConnections *connections)
2865 {
2866   return connections->peak_bus_names;
2867 }
2868
2869 int
2870 bus_connections_get_peak_bus_names_per_conn (BusConnections *connections)
2871 {
2872   return connections->peak_bus_names_per_conn;
2873 }
2874
2875 int
2876 bus_connection_get_peak_match_rules (DBusConnection *connection)
2877 {
2878   BusConnectionData *d;
2879
2880   d = BUS_CONNECTION_DATA (connection);
2881   _dbus_assert(d != NULL);
2882
2883   return d->peak_match_rules;
2884 }
2885
2886 int
2887 bus_connection_get_peak_bus_names (DBusConnection *connection)
2888 {
2889   BusConnectionData *d;
2890
2891   d = BUS_CONNECTION_DATA (connection);
2892   _dbus_assert(d != NULL);
2893
2894   return d->peak_bus_names;
2895 }
2896 #endif /* DBUS_ENABLE_STATS */
2897
2898 dbus_bool_t
2899 bus_connection_is_monitor (DBusConnection *connection)
2900 {
2901   BusConnectionData *d;
2902
2903   d = BUS_CONNECTION_DATA (connection);
2904   _dbus_assert(d != NULL);
2905
2906   return d->link_in_monitors != NULL;
2907 }
2908
2909 static dbus_bool_t
2910 bcd_add_monitor_rules (BusConnectionData  *d,
2911                        DBusConnection     *connection,
2912                        DBusList          **rules)
2913 {
2914   BusMatchmaker *mm = d->connections->monitor_matchmaker;
2915   DBusList *iter;
2916
2917   if (mm == NULL)
2918     {
2919       mm = bus_matchmaker_new ();
2920
2921       if (mm == NULL)
2922         return FALSE;
2923
2924       d->connections->monitor_matchmaker = mm;
2925     }
2926
2927   for (iter = _dbus_list_get_first_link (rules);
2928       iter != NULL;
2929       iter = _dbus_list_get_next_link (rules, iter))
2930     {
2931       if (!bus_matchmaker_add_rule (mm, iter->data))
2932         {
2933           bus_matchmaker_disconnected (mm, connection);
2934           return FALSE;
2935         }
2936     }
2937
2938   return TRUE;
2939 }
2940
2941 static void
2942 bcd_drop_monitor_rules (BusConnectionData *d,
2943                         DBusConnection *connection)
2944 {
2945   BusMatchmaker *mm = d->connections->monitor_matchmaker;
2946
2947   if (mm != NULL)
2948     bus_matchmaker_disconnected (mm, connection);
2949 }
2950
2951 dbus_bool_t
2952 bus_connection_be_monitor (DBusConnection  *connection,
2953                            BusTransaction  *transaction,
2954                            DBusList       **rules,
2955                            DBusError       *error)
2956 {
2957   BusConnectionData *d;
2958   DBusList *link;
2959   DBusList *tmp;
2960   DBusList *iter;
2961
2962   d = BUS_CONNECTION_DATA (connection);
2963   _dbus_assert (d != NULL);
2964
2965   link = _dbus_list_alloc_link (connection);
2966
2967   if (link == NULL)
2968     {
2969       BUS_SET_OOM (error);
2970       return FALSE;
2971     }
2972
2973   if (!bcd_add_monitor_rules (d, connection, rules))
2974     {
2975       _dbus_list_free_link (link);
2976       BUS_SET_OOM (error);
2977       return FALSE;
2978     }
2979
2980   /* release all its names */
2981   if (!_dbus_list_copy (&d->services_owned, &tmp))
2982     {
2983       bcd_drop_monitor_rules (d, connection);
2984       _dbus_list_free_link (link);
2985       BUS_SET_OOM (error);
2986       return FALSE;
2987     }
2988
2989   for (iter = _dbus_list_get_first_link (&tmp);
2990       iter != NULL;
2991       iter = _dbus_list_get_next_link (&tmp, iter))
2992     {
2993       BusService *service = iter->data;
2994
2995       /* This call is transactional: if there isn't enough memory to
2996        * do everything, then the service gets all its names back when
2997        * the transaction is cancelled due to OOM. */
2998       if (!bus_service_remove_owner (service, connection, transaction, error))
2999         {
3000           bcd_drop_monitor_rules (d, connection);
3001           _dbus_list_free_link (link);
3002           _dbus_list_clear (&tmp);
3003           return FALSE;
3004         }
3005     }
3006
3007   /* We have now done everything that can fail, so there is no problem
3008    * with doing the irrevocable stuff. */
3009
3010   _dbus_list_clear (&tmp);
3011
3012   bus_context_log (transaction->context, DBUS_SYSTEM_LOG_INFO,
3013                    "Connection %s (%s) became a monitor.", d->name,
3014                    d->cached_loginfo_string);
3015
3016   if (d->n_match_rules > 0)
3017     {
3018       BusMatchmaker *mm;
3019
3020       mm = bus_context_get_matchmaker (d->connections->context);
3021       bus_matchmaker_disconnected (mm, connection);
3022     }
3023
3024   /* flag it as a monitor */
3025   d->link_in_monitors = link;
3026   _dbus_list_append_link (&d->connections->monitors, link);
3027
3028   /* it isn't allowed to reply, and it is no longer relevant whether it
3029    * receives replies */
3030   bus_connection_drop_pending_replies (d->connections, connection);
3031
3032   return TRUE;
3033 }