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