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