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