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