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