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