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