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