bus: enforce pending_fd_timeout
[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               _dbus_verbose ("Timing out authentication for connection %p\n", connection);
864               dbus_connection_close (connection);
865             }
866           else
867             {
868               /* We can end the loop, since the connections are in oldest-first order */
869               next_interval = ((double)auth_timeout) - elapsed;
870               _dbus_verbose ("Connection %p authentication expires in %d milliseconds\n",
871                              connection, next_interval);
872           
873               break;
874             }
875       
876           link = next;
877         }
878     }
879
880   bus_expire_timeout_set_interval (connections->expire_timeout,
881                                    next_interval);
882 }
883
884 static dbus_bool_t
885 expire_incomplete_timeout (void *data)
886 {
887   BusConnections *connections = data;
888
889   _dbus_verbose ("Running\n");
890   
891   /* note that this may remove the timeout */
892   bus_connections_expire_incomplete (connections);
893
894   return TRUE;
895 }
896
897 dbus_bool_t
898 bus_connection_get_unix_groups  (DBusConnection   *connection,
899                                  unsigned long   **groups,
900                                  int              *n_groups,
901                                  DBusError        *error)
902 {
903   unsigned long uid;
904
905   *groups = NULL;
906   *n_groups = 0;
907
908   if (dbus_connection_get_unix_user (connection, &uid))
909     {
910       if (!_dbus_unix_groups_from_uid (uid, groups, n_groups))
911         {
912           _dbus_verbose ("Did not get any groups for UID %lu\n",
913                          uid);
914           return FALSE;
915         }
916       else
917         {
918           _dbus_verbose ("Got %d groups for UID %lu\n",
919                          *n_groups, uid);
920           return TRUE;
921         }
922     }
923   else
924     return TRUE; /* successfully got 0 groups */
925 }
926
927 dbus_bool_t
928 bus_connection_is_in_unix_group (DBusConnection *connection,
929                                  unsigned long   gid)
930 {
931   int i;
932   unsigned long *group_ids;
933   int n_group_ids;
934
935   if (!bus_connection_get_unix_groups (connection, &group_ids, &n_group_ids,
936                                        NULL))
937     return FALSE;
938
939   i = 0;
940   while (i < n_group_ids)
941     {
942       if (group_ids[i] == gid)
943         {
944           dbus_free (group_ids);
945           return TRUE;
946         }
947       ++i;
948     }
949
950   dbus_free (group_ids);
951   return FALSE;
952 }
953
954 const char *
955 bus_connection_get_loginfo (DBusConnection        *connection)
956 {
957   BusConnectionData *d;
958     
959   d = BUS_CONNECTION_DATA (connection);
960
961   if (!bus_connection_is_active (connection))
962     return "inactive";
963   return d->cached_loginfo_string;  
964 }
965
966 BusClientPolicy*
967 bus_connection_get_policy (DBusConnection *connection)
968 {
969   BusConnectionData *d;
970     
971   d = BUS_CONNECTION_DATA (connection);
972
973   _dbus_assert (d != NULL);
974   _dbus_assert (d->policy != NULL);
975   
976   return d->policy;
977 }
978
979 static dbus_bool_t
980 foreach_active (BusConnections               *connections,
981                 BusConnectionForeachFunction  function,
982                 void                         *data)
983 {
984   DBusList *link;
985   
986   link = _dbus_list_get_first_link (&connections->completed);
987   while (link != NULL)
988     {
989       DBusConnection *connection = link->data;
990       DBusList *next = _dbus_list_get_next_link (&connections->completed, link);
991
992       if (!(* function) (connection, data))
993         return FALSE;
994       
995       link = next;
996     }
997
998   return TRUE;
999 }
1000
1001 static dbus_bool_t
1002 foreach_inactive (BusConnections               *connections,
1003                   BusConnectionForeachFunction  function,
1004                   void                         *data)
1005 {
1006   DBusList *link;
1007   
1008   link = _dbus_list_get_first_link (&connections->incomplete);
1009   while (link != NULL)
1010     {
1011       DBusConnection *connection = link->data;
1012       DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
1013
1014       if (!(* function) (connection, data))
1015         return FALSE;
1016       
1017       link = next;
1018     }
1019
1020   return TRUE;
1021 }
1022
1023 /**
1024  * Calls function on each active connection; if the function returns
1025  * #FALSE, stops iterating. Active connections are authenticated
1026  * and have sent a Hello message.
1027  *
1028  * @param connections the connections object
1029  * @param function the function
1030  * @param data data to pass to it as a second arg
1031  */
1032 void
1033 bus_connections_foreach_active (BusConnections               *connections,
1034                                 BusConnectionForeachFunction  function,
1035                                 void                         *data)
1036 {
1037   foreach_active (connections, function, data);
1038 }
1039
1040 /**
1041  * Calls function on each connection; if the function returns
1042  * #FALSE, stops iterating.
1043  *
1044  * @param connections the connections object
1045  * @param function the function
1046  * @param data data to pass to it as a second arg
1047  */
1048 void
1049 bus_connections_foreach (BusConnections               *connections,
1050                          BusConnectionForeachFunction  function,
1051                          void                         *data)
1052 {
1053   if (!foreach_active (connections, function, data))
1054     return;
1055
1056   foreach_inactive (connections, function, data);
1057 }
1058
1059 BusContext*
1060 bus_connections_get_context (BusConnections *connections)
1061 {
1062   return connections->context;
1063 }
1064
1065 /*
1066  * This is used to avoid covering the same connection twice when
1067  * traversing connections. Note that it assumes we will
1068  * bus_connection_mark_stamp() each connection at least once per
1069  * INT_MAX increments of the global stamp, or wraparound would break
1070  * things.
1071  */
1072 void
1073 bus_connections_increment_stamp (BusConnections *connections)
1074 {
1075   connections->stamp += 1;
1076 }
1077
1078 /* Mark connection with current stamp, return TRUE if it
1079  * didn't already have that stamp
1080  */
1081 dbus_bool_t
1082 bus_connection_mark_stamp (DBusConnection *connection)
1083 {
1084   BusConnectionData *d;
1085   
1086   d = BUS_CONNECTION_DATA (connection);
1087   
1088   _dbus_assert (d != NULL);
1089
1090   if (d->stamp == d->connections->stamp)
1091     return FALSE;
1092   else
1093     {
1094       d->stamp = d->connections->stamp;
1095       return TRUE;
1096     }
1097 }
1098
1099 BusContext*
1100 bus_connection_get_context (DBusConnection *connection)
1101 {
1102   BusConnectionData *d;
1103
1104   d = BUS_CONNECTION_DATA (connection);
1105
1106   _dbus_assert (d != NULL);
1107
1108   return d->connections->context;
1109 }
1110
1111 BusConnections*
1112 bus_connection_get_connections (DBusConnection *connection)
1113 {
1114   BusConnectionData *d;
1115     
1116   d = BUS_CONNECTION_DATA (connection);
1117
1118   _dbus_assert (d != NULL);
1119
1120   return d->connections;
1121 }
1122
1123 BusRegistry*
1124 bus_connection_get_registry (DBusConnection *connection)
1125 {
1126   BusConnectionData *d;
1127
1128   d = BUS_CONNECTION_DATA (connection);
1129
1130   _dbus_assert (d != NULL);
1131
1132   return bus_context_get_registry (d->connections->context);
1133 }
1134
1135 BusActivation*
1136 bus_connection_get_activation (DBusConnection *connection)
1137 {
1138   BusConnectionData *d;
1139
1140   d = BUS_CONNECTION_DATA (connection);
1141
1142   _dbus_assert (d != NULL);
1143
1144   return bus_context_get_activation (d->connections->context);
1145 }
1146
1147 BusMatchmaker*
1148 bus_connection_get_matchmaker (DBusConnection *connection)
1149 {
1150   BusConnectionData *d;
1151
1152   d = BUS_CONNECTION_DATA (connection);
1153
1154   _dbus_assert (d != NULL);
1155
1156   return bus_context_get_matchmaker (d->connections->context);
1157 }
1158
1159 BusSELinuxID*
1160 bus_connection_get_selinux_id (DBusConnection *connection)
1161 {
1162   BusConnectionData *d;
1163
1164   d = BUS_CONNECTION_DATA (connection);
1165
1166   _dbus_assert (d != NULL);
1167
1168   return d->selinux_id;
1169 }
1170
1171 /**
1172  * Checks whether the connection is registered with the message bus.
1173  *
1174  * @param connection the connection
1175  * @returns #TRUE if we're an active message bus participant
1176  */
1177 dbus_bool_t
1178 bus_connection_is_active (DBusConnection *connection)
1179 {
1180   BusConnectionData *d;
1181
1182   d = BUS_CONNECTION_DATA (connection);
1183   
1184   return d != NULL && d->name != NULL;
1185 }
1186
1187 dbus_bool_t
1188 bus_connection_preallocate_oom_error (DBusConnection *connection)
1189 {
1190   DBusMessage *message;
1191   DBusPreallocatedSend *preallocated;
1192   BusConnectionData *d;
1193
1194   d = BUS_CONNECTION_DATA (connection);  
1195
1196   _dbus_assert (d != NULL);
1197
1198   if (d->oom_preallocated != NULL)
1199     return TRUE;
1200   
1201   preallocated = dbus_connection_preallocate_send (connection);
1202   if (preallocated == NULL)
1203     return FALSE;
1204
1205   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1206
1207   if (message == NULL)
1208     {
1209       dbus_connection_free_preallocated_send (connection, preallocated);
1210       return FALSE;
1211     }
1212
1213   /* d->name may be NULL, but that is OK */
1214   if (!dbus_message_set_error_name (message, DBUS_ERROR_NO_MEMORY) ||
1215       !dbus_message_set_destination (message, d->name) ||
1216       !dbus_message_set_sender (message,
1217                                 DBUS_SERVICE_DBUS))
1218     {
1219       dbus_connection_free_preallocated_send (connection, preallocated);
1220       dbus_message_unref (message);
1221       return FALSE;
1222     }
1223   
1224   /* set reply serial to placeholder value just so space is already allocated
1225    * for it.
1226    */
1227   if (!dbus_message_set_reply_serial (message, 14))
1228     {
1229       dbus_connection_free_preallocated_send (connection, preallocated);
1230       dbus_message_unref (message);
1231       return FALSE;
1232     }
1233
1234   d->oom_message = message;
1235   d->oom_preallocated = preallocated;
1236   
1237   return TRUE;
1238 }
1239
1240 void
1241 bus_connection_send_oom_error (DBusConnection *connection,
1242                                DBusMessage    *in_reply_to)
1243 {
1244   BusConnectionData *d;
1245
1246   d = BUS_CONNECTION_DATA (connection);  
1247
1248   _dbus_assert (d != NULL);  
1249   _dbus_assert (d->oom_message != NULL);
1250
1251   /* should always succeed since we set it to a placeholder earlier */
1252   if (!dbus_message_set_reply_serial (d->oom_message,
1253                                       dbus_message_get_serial (in_reply_to)))
1254     _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");
1255
1256   _dbus_assert (dbus_message_get_sender (d->oom_message) != NULL);
1257   
1258   dbus_connection_send_preallocated (connection, d->oom_preallocated,
1259                                      d->oom_message, NULL);
1260
1261   dbus_message_unref (d->oom_message);
1262   d->oom_message = NULL;
1263   d->oom_preallocated = NULL;
1264 }
1265
1266 #ifdef DBUS_ENABLE_STATS
1267 static void
1268 update_peak (int *peak,
1269              int n)
1270 {
1271   if (*peak < n)
1272     *peak = n;
1273 }
1274 #endif
1275
1276 void
1277 bus_connection_add_match_rule_link (DBusConnection *connection,
1278                                     DBusList       *link)
1279 {
1280   BusConnectionData *d;
1281
1282   d = BUS_CONNECTION_DATA (connection);
1283   _dbus_assert (d != NULL);
1284
1285   _dbus_list_append_link (&d->match_rules, link);
1286
1287   d->n_match_rules += 1;
1288
1289 #ifdef DBUS_ENABLE_STATS
1290   update_peak (&d->peak_match_rules, d->n_match_rules);
1291   update_peak (&d->connections->peak_match_rules_per_conn, d->n_match_rules);
1292
1293   d->connections->total_match_rules += 1;
1294   update_peak (&d->connections->peak_match_rules,
1295                d->connections->total_match_rules);
1296 #endif
1297 }
1298
1299 dbus_bool_t
1300 bus_connection_add_match_rule (DBusConnection *connection,
1301                                BusMatchRule   *rule)
1302 {
1303     DBusList *link;
1304
1305   link = _dbus_list_alloc_link (rule);
1306
1307   if (link == NULL)
1308     return FALSE;
1309
1310   bus_connection_add_match_rule_link (connection, link);
1311
1312   return TRUE;
1313 }
1314
1315 void
1316 bus_connection_remove_match_rule (DBusConnection *connection,
1317                                   BusMatchRule   *rule)
1318 {
1319   BusConnectionData *d;
1320
1321   d = BUS_CONNECTION_DATA (connection);
1322   _dbus_assert (d != NULL);
1323
1324   _dbus_list_remove_last (&d->match_rules, rule);
1325
1326   d->n_match_rules -= 1;
1327   _dbus_assert (d->n_match_rules >= 0);
1328
1329 #ifdef DBUS_ENABLE_STATS
1330   d->connections->total_match_rules -= 1;
1331 #endif
1332 }
1333
1334 int
1335 bus_connection_get_n_match_rules (DBusConnection *connection)
1336 {
1337   BusConnectionData *d;
1338
1339   d = BUS_CONNECTION_DATA (connection);
1340   _dbus_assert (d != NULL);
1341   
1342   return d->n_match_rules;
1343 }
1344
1345 void
1346 bus_connection_add_owned_service_link (DBusConnection *connection,
1347                                        DBusList       *link)
1348 {
1349   BusConnectionData *d;
1350
1351   d = BUS_CONNECTION_DATA (connection);
1352   _dbus_assert (d != NULL);
1353
1354   _dbus_list_append_link (&d->services_owned, link);
1355
1356   d->n_services_owned += 1;
1357
1358 #ifdef DBUS_ENABLE_STATS
1359   update_peak (&d->peak_bus_names, d->n_services_owned);
1360   update_peak (&d->connections->peak_bus_names_per_conn,
1361                d->n_services_owned);
1362
1363   d->connections->total_bus_names += 1;
1364   update_peak (&d->connections->peak_bus_names,
1365                d->connections->total_bus_names);
1366 #endif
1367 }
1368
1369 dbus_bool_t
1370 bus_connection_add_owned_service (DBusConnection *connection,
1371                                   BusService     *service)
1372 {
1373   DBusList *link;
1374
1375   link = _dbus_list_alloc_link (service);
1376
1377   if (link == NULL)
1378     return FALSE;
1379
1380   bus_connection_add_owned_service_link (connection, link);
1381
1382   return TRUE;
1383 }
1384
1385 void
1386 bus_connection_remove_owned_service (DBusConnection *connection,
1387                                      BusService     *service)
1388 {
1389   BusConnectionData *d;
1390
1391   d = BUS_CONNECTION_DATA (connection);
1392   _dbus_assert (d != NULL);
1393
1394   _dbus_list_remove_last (&d->services_owned, service);
1395
1396   d->n_services_owned -= 1;
1397   _dbus_assert (d->n_services_owned >= 0);
1398
1399 #ifdef DBUS_ENABLE_STATS
1400   d->connections->total_bus_names -= 1;
1401 #endif
1402 }
1403
1404 int
1405 bus_connection_get_n_services_owned (DBusConnection *connection)
1406 {
1407   BusConnectionData *d;
1408
1409   d = BUS_CONNECTION_DATA (connection);
1410   _dbus_assert (d != NULL);
1411   
1412   return d->n_services_owned;
1413 }
1414
1415 dbus_bool_t
1416 bus_connection_complete (DBusConnection   *connection,
1417                          const DBusString *name,
1418                          DBusError        *error)
1419 {
1420   BusConnectionData *d;
1421   unsigned long uid;
1422   
1423   d = BUS_CONNECTION_DATA (connection);
1424   _dbus_assert (d != NULL);
1425   _dbus_assert (d->name == NULL);
1426   _dbus_assert (d->policy == NULL);
1427
1428   _dbus_assert (!bus_connection_is_active (connection));
1429   
1430   if (!_dbus_string_copy_data (name, &d->name))
1431     {
1432       BUS_SET_OOM (error);
1433       return FALSE;
1434     }
1435
1436   _dbus_assert (d->name != NULL);
1437   
1438   _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);
1439
1440   d->policy = bus_context_create_client_policy (d->connections->context,
1441                                                 connection,
1442                                                 error);
1443
1444   /* we may have a NULL policy on OOM or error getting list of
1445    * groups for a user. In the latter case we don't handle it so
1446    * well currently, as it will just keep failing over and over.
1447    */
1448
1449   if (d->policy == NULL)
1450     {
1451       _dbus_verbose ("Failed to create security policy for connection %p\n",
1452                      connection);
1453       _DBUS_ASSERT_ERROR_IS_SET (error);
1454       dbus_free (d->name);
1455       d->name = NULL;
1456       return FALSE;
1457     }
1458   
1459   if (dbus_connection_get_unix_user (connection, &uid))
1460     {
1461       if (!adjust_connections_for_uid (d->connections,
1462                                        uid, 1))
1463         goto fail;
1464     }
1465
1466   /* Create and cache a string which holds information about the 
1467    * peer process; used for logging purposes.
1468    */
1469   if (!cache_peer_loginfo_string (d, connection))
1470     goto fail;
1471
1472   /* Now the connection is active, move it between lists */
1473   _dbus_list_unlink (&d->connections->incomplete,
1474                      d->link_in_connection_list);
1475   d->connections->n_incomplete -= 1;
1476   _dbus_list_append_link (&d->connections->completed,
1477                           d->link_in_connection_list);
1478   d->connections->n_completed += 1;
1479
1480   _dbus_assert (d->connections->n_incomplete >= 0);
1481   _dbus_assert (d->connections->n_completed > 0);
1482
1483   /* If we have dropped below the max. number of incomplete
1484    * connections, start accept()ing again */
1485   bus_context_check_all_watches (d->connections->context);
1486
1487   /* See if we can remove the timeout */
1488   bus_connections_expire_incomplete (d->connections);
1489
1490   _dbus_assert (bus_connection_is_active (connection));
1491   
1492   return TRUE;
1493 fail:
1494   BUS_SET_OOM (error);
1495   dbus_free (d->name);
1496   d->name = NULL;
1497   if (d->policy)
1498     bus_client_policy_unref (d->policy);
1499   d->policy = NULL;
1500   return FALSE;
1501 }
1502
1503 dbus_bool_t
1504 bus_connections_reload_policy (BusConnections *connections,
1505                                DBusError      *error)
1506 {
1507   BusConnectionData *d;
1508   DBusConnection *connection;
1509   DBusList *link;
1510
1511   _dbus_assert (connections != NULL);
1512   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1513
1514   for (link = _dbus_list_get_first_link (&(connections->completed));
1515        link;
1516        link = _dbus_list_get_next_link (&(connections->completed), link))
1517     {
1518       connection = link->data;
1519       d = BUS_CONNECTION_DATA (connection);
1520       _dbus_assert (d != NULL);
1521       _dbus_assert (d->policy != NULL);
1522
1523       bus_client_policy_unref (d->policy);
1524       d->policy = bus_context_create_client_policy (connections->context,
1525                                                     connection,
1526                                                     error);
1527       if (d->policy == NULL)
1528         {
1529           _dbus_verbose ("Failed to create security policy for connection %p\n",
1530                       connection);
1531           _DBUS_ASSERT_ERROR_IS_SET (error);
1532           return FALSE;
1533         }
1534     }
1535
1536   return TRUE;
1537 }
1538
1539 const char *
1540 bus_connection_get_name (DBusConnection *connection)
1541 {
1542   BusConnectionData *d;
1543   
1544   d = BUS_CONNECTION_DATA (connection);
1545   _dbus_assert (d != NULL);
1546   
1547   return d->name;
1548 }
1549
1550 /**
1551  * Check whether completing the passed-in connection would
1552  * exceed limits, and if so set error and return #FALSE
1553  */
1554 dbus_bool_t
1555 bus_connections_check_limits (BusConnections  *connections,
1556                               DBusConnection  *requesting_completion,
1557                               DBusError       *error)
1558 {
1559   unsigned long uid;
1560
1561   if (connections->n_completed >=
1562       bus_context_get_max_completed_connections (connections->context))
1563     {
1564       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1565                       "The maximum number of active connections has been reached");
1566       return FALSE;
1567     }
1568   
1569   if (dbus_connection_get_unix_user (requesting_completion, &uid))
1570     {
1571       if (get_connections_for_uid (connections, uid) >=
1572           bus_context_get_max_connections_per_user (connections->context))
1573         {
1574           dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1575                           "The maximum number of active connections for UID %lu has been reached",
1576                           uid);
1577           return FALSE;
1578         }
1579     }
1580   
1581   return TRUE;
1582 }
1583
1584 static void
1585 bus_pending_reply_free (BusPendingReply *pending)
1586 {
1587   _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
1588                  pending,
1589                  pending->will_send_reply,
1590                  pending->will_get_reply,
1591                  pending->reply_serial);
1592
1593   dbus_free (pending);
1594 }
1595
1596 static dbus_bool_t
1597 bus_pending_reply_send_no_reply (BusConnections  *connections,
1598                                  BusTransaction  *transaction,
1599                                  BusPendingReply *pending)
1600 {
1601   DBusMessage *message;
1602   DBusMessageIter iter;
1603   dbus_bool_t retval;
1604   const char *errmsg;
1605
1606   retval = FALSE;
1607   
1608   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1609   if (message == NULL)
1610     return FALSE;
1611   
1612   dbus_message_set_no_reply (message, TRUE);
1613   
1614   if (!dbus_message_set_reply_serial (message,
1615                                       pending->reply_serial))
1616     goto out;
1617
1618   if (!dbus_message_set_error_name (message,
1619                                     DBUS_ERROR_NO_REPLY))
1620     goto out;
1621
1622   errmsg = "Message did not receive a reply (timeout by message bus)";
1623   dbus_message_iter_init_append (message, &iter);
1624   if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
1625     goto out;
1626     
1627   if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
1628                                          message))
1629     goto out;
1630
1631   retval = TRUE;
1632
1633  out:
1634   dbus_message_unref (message);
1635   return retval;
1636 }
1637
1638 static dbus_bool_t
1639 bus_pending_reply_expired (BusExpireList *list,
1640                            DBusList      *link,
1641                            void          *data)
1642 {
1643   BusPendingReply *pending = link->data;
1644   BusConnections *connections = data;
1645   BusTransaction *transaction;
1646   
1647   /* No reply is forthcoming. So nuke it if we can. If not,
1648    * leave it in the list to try expiring again later when we
1649    * get more memory.
1650    */
1651
1652   _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
1653                  pending,
1654                  pending->will_send_reply,
1655                  pending->will_get_reply,
1656                  pending->reply_serial);
1657   
1658   transaction = bus_transaction_new (connections->context);
1659   if (transaction == NULL)
1660     return FALSE;
1661   
1662   if (!bus_pending_reply_send_no_reply (connections,
1663                                         transaction,
1664                                         pending))
1665     {
1666       bus_transaction_cancel_and_free (transaction);
1667       return FALSE;
1668     }
1669
1670   bus_expire_list_remove_link (connections->pending_replies, link);
1671
1672   bus_pending_reply_free (pending);
1673   bus_transaction_execute_and_free (transaction);
1674
1675   return TRUE;
1676 }
1677
1678 static void
1679 bus_connection_drop_pending_replies (BusConnections  *connections,
1680                                      DBusConnection  *connection)
1681 {
1682   /* The DBusConnection is almost 100% finalized here, so you can't
1683    * do anything with it except check for pointer equality
1684    */
1685   DBusList *link;
1686
1687   _dbus_verbose ("Dropping pending replies that involve connection %p\n",
1688                  connection);
1689   
1690   link = bus_expire_list_get_first_link (connections->pending_replies);
1691   while (link != NULL)
1692     {
1693       DBusList *next;
1694       BusPendingReply *pending;
1695
1696       next = bus_expire_list_get_next_link (connections->pending_replies,
1697                                             link);
1698       pending = link->data;
1699
1700       if (pending->will_get_reply == connection)
1701         {
1702           /* We don't need to track this pending reply anymore */
1703
1704           _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
1705                          pending,
1706                          pending->will_send_reply,
1707                          pending->will_get_reply,
1708                          pending->reply_serial);
1709           
1710           bus_expire_list_remove_link (connections->pending_replies,
1711                                        link);
1712           bus_pending_reply_free (pending);
1713         }
1714       else if (pending->will_send_reply == connection)
1715         {
1716           /* The reply isn't going to be sent, so set things
1717            * up so it will be expired right away
1718            */
1719           _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
1720                          pending,
1721                          pending->will_send_reply,
1722                          pending->will_get_reply,
1723                          pending->reply_serial);
1724           
1725           pending->will_send_reply = NULL;
1726           pending->expire_item.added_tv_sec = 0;
1727           pending->expire_item.added_tv_usec = 0;
1728
1729           bus_expire_list_recheck_immediately (connections->pending_replies);
1730         }
1731       
1732       link = next;
1733     }
1734 }
1735
1736
1737 typedef struct
1738 {
1739   BusPendingReply *pending;
1740   BusConnections  *connections;
1741 } CancelPendingReplyData;
1742
1743 static void
1744 cancel_pending_reply (void *data)
1745 {
1746   CancelPendingReplyData *d = data;
1747
1748   _dbus_verbose ("d = %p\n", d);
1749   
1750   if (!bus_expire_list_remove (d->connections->pending_replies,
1751                                &d->pending->expire_item))
1752     _dbus_assert_not_reached ("pending reply did not exist to be cancelled");
1753
1754   bus_pending_reply_free (d->pending); /* since it's been cancelled */
1755 }
1756
1757 static void
1758 cancel_pending_reply_data_free (void *data)
1759 {
1760   CancelPendingReplyData *d = data;
1761
1762   _dbus_verbose ("d = %p\n", d);
1763   
1764   /* d->pending should be either freed or still
1765    * in the list of pending replies (owned by someone
1766    * else)
1767    */
1768   
1769   dbus_free (d);
1770 }
1771
1772 /*
1773  * Record that a reply is allowed; return TRUE on success.
1774  */
1775 dbus_bool_t
1776 bus_connections_expect_reply (BusConnections  *connections,
1777                               BusTransaction  *transaction,
1778                               DBusConnection  *will_get_reply,
1779                               DBusConnection  *will_send_reply,
1780                               DBusMessage     *reply_to_this,
1781                               DBusError       *error)
1782 {
1783   BusPendingReply *pending;
1784   dbus_uint32_t reply_serial;
1785   DBusList *link;
1786   CancelPendingReplyData *cprd;
1787   int count;
1788
1789   _dbus_assert (will_get_reply != NULL);
1790   _dbus_assert (will_send_reply != NULL);
1791   _dbus_assert (reply_to_this != NULL);
1792   
1793   if (dbus_message_get_no_reply (reply_to_this))
1794     return TRUE; /* we won't allow a reply, since client doesn't care for one. */
1795   
1796   reply_serial = dbus_message_get_serial (reply_to_this);
1797
1798   link = bus_expire_list_get_first_link (connections->pending_replies);
1799   count = 0;
1800   while (link != NULL)
1801     {
1802       pending = link->data;
1803
1804       if (pending->reply_serial == reply_serial &&
1805           pending->will_get_reply == will_get_reply &&
1806           pending->will_send_reply == will_send_reply)
1807         {
1808           dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1809                           "Message has the same reply serial as a currently-outstanding existing method call");
1810           return FALSE;
1811         }
1812       
1813       link = bus_expire_list_get_next_link (connections->pending_replies,
1814                                             link);
1815       if (pending->will_get_reply == will_get_reply)
1816         ++count;
1817     }
1818   
1819   if (count >=
1820       bus_context_get_max_replies_per_connection (connections->context))
1821     {
1822       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1823                       "The maximum number of pending replies per connection has been reached");
1824       return FALSE;
1825     }
1826
1827   pending = dbus_new0 (BusPendingReply, 1);
1828   if (pending == NULL)
1829     {
1830       BUS_SET_OOM (error);
1831       return FALSE;
1832     }
1833
1834 #ifdef DBUS_ENABLE_VERBOSE_MODE
1835   /* so we can see a not-yet-added pending reply */
1836   pending->expire_item.added_tv_sec = 1;
1837   pending->expire_item.added_tv_usec = 1;
1838 #endif
1839
1840   pending->will_get_reply = will_get_reply;
1841   pending->will_send_reply = will_send_reply;
1842   pending->reply_serial = reply_serial;
1843   
1844   cprd = dbus_new0 (CancelPendingReplyData, 1);
1845   if (cprd == NULL)
1846     {
1847       BUS_SET_OOM (error);
1848       bus_pending_reply_free (pending);
1849       return FALSE;
1850     }
1851   
1852   if (!bus_expire_list_add (connections->pending_replies,
1853                             &pending->expire_item))
1854     {
1855       BUS_SET_OOM (error);
1856       dbus_free (cprd);
1857       bus_pending_reply_free (pending);
1858       return FALSE;
1859     }
1860
1861   if (!bus_transaction_add_cancel_hook (transaction,
1862                                         cancel_pending_reply,
1863                                         cprd,
1864                                         cancel_pending_reply_data_free))
1865     {
1866       BUS_SET_OOM (error);
1867       bus_expire_list_remove (connections->pending_replies, &pending->expire_item);
1868       dbus_free (cprd);
1869       bus_pending_reply_free (pending);
1870       return FALSE;
1871     }
1872                                         
1873   cprd->pending = pending;
1874   cprd->connections = connections;
1875   
1876   _dbus_get_monotonic_time (&pending->expire_item.added_tv_sec,
1877                             &pending->expire_item.added_tv_usec);
1878
1879   _dbus_verbose ("Added pending reply %p, replier %p receiver %p serial %u\n",
1880                  pending,
1881                  pending->will_send_reply,
1882                  pending->will_get_reply,
1883                  pending->reply_serial);
1884   
1885   return TRUE;
1886 }
1887
1888 typedef struct
1889 {
1890   DBusList        *link;
1891   BusConnections  *connections;
1892 } CheckPendingReplyData;
1893
1894 static void
1895 cancel_check_pending_reply (void *data)
1896 {
1897   CheckPendingReplyData *d = data;
1898
1899   _dbus_verbose ("d = %p\n",d);
1900
1901   bus_expire_list_add_link (d->connections->pending_replies,
1902                             d->link);
1903   d->link = NULL;
1904 }
1905
1906 static void
1907 check_pending_reply_data_free (void *data)
1908 {
1909   CheckPendingReplyData *d = data;
1910
1911   _dbus_verbose ("d = %p\n",d);
1912   
1913   if (d->link != NULL)
1914     {
1915       BusPendingReply *pending = d->link->data;
1916       
1917       _dbus_assert (!bus_expire_list_contains_item (d->connections->pending_replies,
1918                                                     &pending->expire_item));
1919       
1920       bus_pending_reply_free (pending);
1921       _dbus_list_free_link (d->link);
1922     }
1923   
1924   dbus_free (d);
1925 }
1926
1927 /*
1928  * Check whether a reply is allowed, remove BusPendingReply
1929  * if so, return TRUE if so.
1930  */
1931 dbus_bool_t
1932 bus_connections_check_reply (BusConnections *connections,
1933                              BusTransaction *transaction,
1934                              DBusConnection *sending_reply,
1935                              DBusConnection *receiving_reply,
1936                              DBusMessage    *reply,
1937                              DBusError      *error)
1938 {
1939   CheckPendingReplyData *cprd;
1940   DBusList *link;
1941   dbus_uint32_t reply_serial;
1942   
1943   _dbus_assert (sending_reply != NULL);
1944   _dbus_assert (receiving_reply != NULL);
1945
1946   reply_serial = dbus_message_get_reply_serial (reply);
1947
1948   link = bus_expire_list_get_first_link (connections->pending_replies);
1949   while (link != NULL)
1950     {
1951       BusPendingReply *pending = link->data;
1952
1953       if (pending->reply_serial == reply_serial &&
1954           pending->will_get_reply == receiving_reply &&
1955           pending->will_send_reply == sending_reply)
1956         {
1957           _dbus_verbose ("Found pending reply with serial %u\n", reply_serial);
1958           break;
1959         }
1960       
1961       link = bus_expire_list_get_next_link (connections->pending_replies,
1962                                             link);
1963     }
1964
1965   if (link == NULL)
1966     {
1967       _dbus_verbose ("No pending reply expected\n");
1968
1969       return FALSE;
1970     }
1971
1972   cprd = dbus_new0 (CheckPendingReplyData, 1);
1973   if (cprd == NULL)
1974     {
1975       BUS_SET_OOM (error);
1976       return FALSE;
1977     }
1978   
1979   if (!bus_transaction_add_cancel_hook (transaction,
1980                                         cancel_check_pending_reply,
1981                                         cprd,
1982                                         check_pending_reply_data_free))
1983     {
1984       BUS_SET_OOM (error);
1985       dbus_free (cprd);
1986       return FALSE;
1987     }
1988
1989   cprd->link = link;
1990   cprd->connections = connections;
1991   
1992   bus_expire_list_unlink (connections->pending_replies,
1993                           link);
1994   
1995   _dbus_assert (!bus_expire_list_contains_item (connections->pending_replies, link->data));
1996
1997   return TRUE;
1998 }
1999
2000 /*
2001  * Transactions
2002  *
2003  * Note that this is fairly fragile; in particular, don't try to use
2004  * one transaction across any main loop iterations.
2005  */
2006
2007 typedef struct
2008 {
2009   BusTransaction *transaction;
2010   DBusMessage    *message;
2011   DBusPreallocatedSend *preallocated;
2012 } MessageToSend;
2013
2014 typedef struct
2015 {
2016   BusTransactionCancelFunction cancel_function;
2017   DBusFreeFunction free_data_function;
2018   void *data;
2019 } CancelHook;
2020
2021 struct BusTransaction
2022 {
2023   DBusList *connections;
2024   BusContext *context;
2025   DBusList *cancel_hooks;
2026 };
2027
2028 static void
2029 message_to_send_free (DBusConnection *connection,
2030                       MessageToSend  *to_send)
2031 {
2032   if (to_send->message)
2033     dbus_message_unref (to_send->message);
2034
2035   if (to_send->preallocated)
2036     dbus_connection_free_preallocated_send (connection, to_send->preallocated);
2037
2038   dbus_free (to_send);
2039 }
2040
2041 static void
2042 cancel_hook_cancel (void *element,
2043                     void *data)
2044 {
2045   CancelHook *ch = element;
2046
2047   _dbus_verbose ("Running transaction cancel hook\n");
2048   
2049   if (ch->cancel_function)
2050     (* ch->cancel_function) (ch->data);  
2051 }
2052
2053 static void
2054 cancel_hook_free (void *element,
2055                   void *data)
2056 {
2057   CancelHook *ch = element;
2058
2059   if (ch->free_data_function)
2060     (* ch->free_data_function) (ch->data);
2061
2062   dbus_free (ch);
2063 }
2064
2065 static void
2066 free_cancel_hooks (BusTransaction *transaction)
2067 {
2068   _dbus_list_foreach (&transaction->cancel_hooks,
2069                       cancel_hook_free, NULL);
2070   
2071   _dbus_list_clear (&transaction->cancel_hooks);
2072 }
2073
2074 BusTransaction*
2075 bus_transaction_new (BusContext *context)
2076 {
2077   BusTransaction *transaction;
2078
2079   transaction = dbus_new0 (BusTransaction, 1);
2080   if (transaction == NULL)
2081     return NULL;
2082
2083   transaction->context = context;
2084   
2085   return transaction;
2086 }
2087
2088 BusContext*
2089 bus_transaction_get_context (BusTransaction  *transaction)
2090 {
2091   return transaction->context;
2092 }
2093
2094 dbus_bool_t
2095 bus_transaction_send_from_driver (BusTransaction *transaction,
2096                                   DBusConnection *connection,
2097                                   DBusMessage    *message)
2098 {
2099   /* We have to set the sender to the driver, and have
2100    * to check security policy since it was not done in
2101    * dispatch.c
2102    */
2103   _dbus_verbose ("Sending %s %s %s from driver\n",
2104                  dbus_message_get_interface (message) ?
2105                  dbus_message_get_interface (message) : "(no interface)",
2106                  dbus_message_get_member (message) ?
2107                  dbus_message_get_member (message) : "(no member)",
2108                  dbus_message_get_error_name (message) ?
2109                  dbus_message_get_error_name (message) : "(no error name)");
2110                  
2111   if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2112     return FALSE;
2113
2114   if (bus_connection_is_active (connection))
2115     {
2116       if (!dbus_message_set_destination (message,
2117                                          bus_connection_get_name (connection)))
2118         return FALSE;
2119     }
2120   
2121   /* bus driver never wants a reply */
2122   dbus_message_set_no_reply (message, TRUE);
2123   
2124   /* If security policy doesn't allow the message, we silently
2125    * eat it; the driver doesn't care about getting a reply.
2126    */
2127   if (!bus_context_check_security_policy (bus_transaction_get_context (transaction),
2128                                           transaction,
2129                                           NULL, connection, connection, message, NULL))
2130     return TRUE;
2131
2132   return bus_transaction_send (transaction, connection, message);
2133 }
2134
2135 dbus_bool_t
2136 bus_transaction_send (BusTransaction *transaction,
2137                       DBusConnection *connection,
2138                       DBusMessage    *message)
2139 {
2140   MessageToSend *to_send;
2141   BusConnectionData *d;
2142   DBusList *link;
2143
2144   _dbus_verbose ("  trying to add %s interface=%s member=%s error=%s to transaction%s\n",
2145                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ? "error" :
2146                  dbus_message_get_reply_serial (message) != 0 ? "reply" :
2147                  "message",
2148                  dbus_message_get_interface (message) ?
2149                  dbus_message_get_interface (message) : "(unset)",
2150                  dbus_message_get_member (message) ?
2151                  dbus_message_get_member (message) : "(unset)",
2152                  dbus_message_get_error_name (message) ?
2153                  dbus_message_get_error_name (message) : "(unset)",
2154                  dbus_connection_get_is_connected (connection) ?
2155                  "" : " (disconnected)");
2156
2157   _dbus_assert (dbus_message_get_sender (message) != NULL);
2158   
2159   if (!dbus_connection_get_is_connected (connection))
2160     return TRUE; /* silently ignore disconnected connections */
2161   
2162   d = BUS_CONNECTION_DATA (connection);
2163   _dbus_assert (d != NULL);
2164   
2165   to_send = dbus_new (MessageToSend, 1);
2166   if (to_send == NULL)
2167     {
2168       return FALSE;
2169     }
2170
2171   to_send->preallocated = dbus_connection_preallocate_send (connection);
2172   if (to_send->preallocated == NULL)
2173     {
2174       dbus_free (to_send);
2175       return FALSE;
2176     }  
2177   
2178   dbus_message_ref (message);
2179   to_send->message = message;
2180   to_send->transaction = transaction;
2181
2182   _dbus_verbose ("about to prepend message\n");
2183   
2184   if (!_dbus_list_prepend (&d->transaction_messages, to_send))
2185     {
2186       message_to_send_free (connection, to_send);
2187       return FALSE;
2188     }
2189
2190   _dbus_verbose ("prepended message\n");
2191   
2192   /* See if we already had this connection in the list
2193    * for this transaction. If we have a pending message,
2194    * then we should already be in transaction->connections
2195    */
2196   link = _dbus_list_get_first_link (&d->transaction_messages);
2197   _dbus_assert (link->data == to_send);
2198   link = _dbus_list_get_next_link (&d->transaction_messages, link);
2199   while (link != NULL)
2200     {
2201       MessageToSend *m = link->data;
2202       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2203       
2204       if (m->transaction == transaction)
2205         break;
2206         
2207       link = next;
2208     }
2209
2210   if (link == NULL)
2211     {
2212       if (!_dbus_list_prepend (&transaction->connections, connection))
2213         {
2214           _dbus_list_remove (&d->transaction_messages, to_send);
2215           message_to_send_free (connection, to_send);
2216           return FALSE;
2217         }
2218     }
2219
2220   return TRUE;
2221 }
2222
2223 static void
2224 transaction_free (BusTransaction *transaction)
2225 {
2226   _dbus_assert (transaction->connections == NULL);
2227
2228   free_cancel_hooks (transaction);
2229
2230   dbus_free (transaction);
2231 }
2232
2233 static void
2234 connection_cancel_transaction (DBusConnection *connection,
2235                                BusTransaction *transaction)
2236 {
2237   DBusList *link;
2238   BusConnectionData *d;
2239   
2240   d = BUS_CONNECTION_DATA (connection);
2241   _dbus_assert (d != NULL);
2242   
2243   link = _dbus_list_get_first_link (&d->transaction_messages);
2244   while (link != NULL)
2245     {
2246       MessageToSend *m = link->data;
2247       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2248       
2249       if (m->transaction == transaction)
2250         {
2251           _dbus_list_remove_link (&d->transaction_messages,
2252                                   link);
2253           
2254           message_to_send_free (connection, m);
2255         }
2256         
2257       link = next;
2258     }
2259 }
2260
2261 void
2262 bus_transaction_cancel_and_free (BusTransaction *transaction)
2263 {
2264   DBusConnection *connection;
2265
2266   _dbus_verbose ("TRANSACTION: cancelled\n");
2267   
2268   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2269     connection_cancel_transaction (connection, transaction);
2270
2271   _dbus_list_foreach (&transaction->cancel_hooks,
2272                       cancel_hook_cancel, NULL);
2273
2274   transaction_free (transaction);
2275 }
2276
2277 static void
2278 connection_execute_transaction (DBusConnection *connection,
2279                                 BusTransaction *transaction)
2280 {
2281   DBusList *link;
2282   BusConnectionData *d;
2283   
2284   d = BUS_CONNECTION_DATA (connection);
2285   _dbus_assert (d != NULL);
2286
2287   /* Send the queue in order (FIFO) */
2288   link = _dbus_list_get_last_link (&d->transaction_messages);
2289   while (link != NULL)
2290     {
2291       MessageToSend *m = link->data;
2292       DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
2293       
2294       if (m->transaction == transaction)
2295         {
2296           _dbus_list_remove_link (&d->transaction_messages,
2297                                   link);
2298
2299           _dbus_assert (dbus_message_get_sender (m->message) != NULL);
2300           
2301           dbus_connection_send_preallocated (connection,
2302                                              m->preallocated,
2303                                              m->message,
2304                                              NULL);
2305
2306           m->preallocated = NULL; /* so we don't double-free it */
2307           
2308           message_to_send_free (connection, m);
2309         }
2310         
2311       link = prev;
2312     }
2313 }
2314
2315 void
2316 bus_transaction_execute_and_free (BusTransaction *transaction)
2317 {
2318   /* For each connection in transaction->connections
2319    * send the messages
2320    */
2321   DBusConnection *connection;
2322
2323   _dbus_verbose ("TRANSACTION: executing\n");
2324   
2325   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2326     connection_execute_transaction (connection, transaction);
2327
2328   transaction_free (transaction);
2329 }
2330
2331 static void
2332 bus_connection_remove_transactions (DBusConnection *connection)
2333 {
2334   MessageToSend *to_send;
2335   BusConnectionData *d;
2336   
2337   d = BUS_CONNECTION_DATA (connection);
2338   _dbus_assert (d != NULL);
2339   
2340   while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
2341     {
2342       /* only has an effect for the first MessageToSend listing this transaction */
2343       _dbus_list_remove (&to_send->transaction->connections,
2344                          connection);
2345
2346       _dbus_list_remove (&d->transaction_messages, to_send);
2347       message_to_send_free (connection, to_send);
2348     }
2349 }
2350
2351 /**
2352  * Converts the DBusError to a message reply
2353  */
2354 dbus_bool_t
2355 bus_transaction_send_error_reply (BusTransaction  *transaction,
2356                                   DBusConnection  *connection,
2357                                   const DBusError *error,
2358                                   DBusMessage     *in_reply_to)
2359 {
2360   DBusMessage *reply;
2361   
2362   _dbus_assert (error != NULL);
2363   _DBUS_ASSERT_ERROR_IS_SET (error);
2364   
2365   _dbus_verbose ("Sending error reply %s \"%s\"\n",
2366                  error->name, error->message);
2367
2368   reply = dbus_message_new_error (in_reply_to,
2369                                   error->name,
2370                                   error->message);
2371   if (reply == NULL)
2372     return FALSE;
2373
2374   if (!bus_transaction_send_from_driver (transaction, connection, reply))
2375     {
2376       dbus_message_unref (reply);
2377       return FALSE;
2378     }
2379
2380   dbus_message_unref (reply);
2381   
2382   return TRUE;
2383 }
2384
2385 dbus_bool_t
2386 bus_transaction_add_cancel_hook (BusTransaction               *transaction,
2387                                  BusTransactionCancelFunction  cancel_function,
2388                                  void                         *data,
2389                                  DBusFreeFunction              free_data_function)
2390 {
2391   CancelHook *ch;
2392
2393   ch = dbus_new (CancelHook, 1);
2394   if (ch == NULL)
2395     return FALSE;
2396
2397   _dbus_verbose ("     adding cancel hook function = %p data = %p\n",
2398                  cancel_function, data);
2399   
2400   ch->cancel_function = cancel_function;
2401   ch->data = data;
2402   ch->free_data_function = free_data_function;
2403
2404   /* It's important that the hooks get run in reverse order that they
2405    * were added
2406    */
2407   if (!_dbus_list_prepend (&transaction->cancel_hooks, ch))
2408     {
2409       dbus_free (ch);
2410       return FALSE;
2411     }
2412
2413   return TRUE;
2414 }
2415
2416 int
2417 bus_connections_get_n_active (BusConnections *connections)
2418 {
2419   return connections->n_completed;
2420 }
2421
2422 int
2423 bus_connections_get_n_incomplete (BusConnections *connections)
2424 {
2425   return connections->n_incomplete;
2426 }
2427
2428 #ifdef DBUS_ENABLE_STATS
2429 int
2430 bus_connections_get_total_match_rules (BusConnections *connections)
2431 {
2432   return connections->total_match_rules;
2433 }
2434
2435 int
2436 bus_connections_get_peak_match_rules (BusConnections *connections)
2437 {
2438   return connections->peak_match_rules;
2439 }
2440
2441 int
2442 bus_connections_get_peak_match_rules_per_conn (BusConnections *connections)
2443 {
2444   return connections->peak_match_rules_per_conn;
2445 }
2446
2447 int
2448 bus_connections_get_total_bus_names (BusConnections *connections)
2449 {
2450   return connections->total_bus_names;
2451 }
2452
2453 int
2454 bus_connections_get_peak_bus_names (BusConnections *connections)
2455 {
2456   return connections->peak_bus_names;
2457 }
2458
2459 int
2460 bus_connections_get_peak_bus_names_per_conn (BusConnections *connections)
2461 {
2462   return connections->peak_bus_names_per_conn;
2463 }
2464
2465 int
2466 bus_connection_get_peak_match_rules (DBusConnection *connection)
2467 {
2468   BusConnectionData *d;
2469
2470   d = BUS_CONNECTION_DATA (connection);
2471   return d->peak_match_rules;
2472 }
2473
2474 int
2475 bus_connection_get_peak_bus_names (DBusConnection *connection)
2476 {
2477   BusConnectionData *d;
2478
2479   d = BUS_CONNECTION_DATA (connection);
2480   return d->peak_bus_names;
2481 }
2482 #endif /* DBUS_ENABLE_STATS */