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