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