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