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