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