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