Store AppArmor label of connecting processes
[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 /**
1227  * Checks whether the connection is registered with the message bus.
1228  *
1229  * @param connection the connection
1230  * @returns #TRUE if we're an active message bus participant
1231  */
1232 dbus_bool_t
1233 bus_connection_is_active (DBusConnection *connection)
1234 {
1235   BusConnectionData *d;
1236
1237   d = BUS_CONNECTION_DATA (connection);
1238   
1239   return d != NULL && d->name != NULL;
1240 }
1241
1242 dbus_bool_t
1243 bus_connection_preallocate_oom_error (DBusConnection *connection)
1244 {
1245   DBusMessage *message;
1246   DBusPreallocatedSend *preallocated;
1247   BusConnectionData *d;
1248
1249   d = BUS_CONNECTION_DATA (connection);  
1250
1251   _dbus_assert (d != NULL);
1252
1253   if (d->oom_preallocated != NULL)
1254     return TRUE;
1255   
1256   preallocated = dbus_connection_preallocate_send (connection);
1257   if (preallocated == NULL)
1258     return FALSE;
1259
1260   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1261
1262   if (message == NULL)
1263     {
1264       dbus_connection_free_preallocated_send (connection, preallocated);
1265       return FALSE;
1266     }
1267
1268   /* d->name may be NULL, but that is OK */
1269   if (!dbus_message_set_error_name (message, DBUS_ERROR_NO_MEMORY) ||
1270       !dbus_message_set_destination (message, d->name) ||
1271       !dbus_message_set_sender (message,
1272                                 DBUS_SERVICE_DBUS))
1273     {
1274       dbus_connection_free_preallocated_send (connection, preallocated);
1275       dbus_message_unref (message);
1276       return FALSE;
1277     }
1278   
1279   /* set reply serial to placeholder value just so space is already allocated
1280    * for it.
1281    */
1282   if (!dbus_message_set_reply_serial (message, 14))
1283     {
1284       dbus_connection_free_preallocated_send (connection, preallocated);
1285       dbus_message_unref (message);
1286       return FALSE;
1287     }
1288
1289   d->oom_message = message;
1290   d->oom_preallocated = preallocated;
1291   
1292   return TRUE;
1293 }
1294
1295 void
1296 bus_connection_send_oom_error (DBusConnection *connection,
1297                                DBusMessage    *in_reply_to)
1298 {
1299   BusConnectionData *d;
1300
1301   d = BUS_CONNECTION_DATA (connection);  
1302
1303   _dbus_assert (d != NULL);  
1304   _dbus_assert (d->oom_message != NULL);
1305
1306   bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
1307                    "dbus-daemon transaction failed (OOM), sending error to "
1308                    "sender %s", bus_connection_get_loginfo (connection));
1309
1310   /* should always succeed since we set it to a placeholder earlier */
1311   if (!dbus_message_set_reply_serial (d->oom_message,
1312                                       dbus_message_get_serial (in_reply_to)))
1313     _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");
1314
1315   _dbus_assert (dbus_message_get_sender (d->oom_message) != NULL);
1316   
1317   dbus_connection_send_preallocated (connection, d->oom_preallocated,
1318                                      d->oom_message, NULL);
1319
1320   dbus_message_unref (d->oom_message);
1321   d->oom_message = NULL;
1322   d->oom_preallocated = NULL;
1323 }
1324
1325 #ifdef DBUS_ENABLE_STATS
1326 static void
1327 update_peak (int *peak,
1328              int n)
1329 {
1330   if (*peak < n)
1331     *peak = n;
1332 }
1333 #endif
1334
1335 void
1336 bus_connection_add_match_rule_link (DBusConnection *connection,
1337                                     DBusList       *link)
1338 {
1339   BusConnectionData *d;
1340
1341   d = BUS_CONNECTION_DATA (connection);
1342   _dbus_assert (d != NULL);
1343
1344   _dbus_list_append_link (&d->match_rules, link);
1345
1346   d->n_match_rules += 1;
1347
1348 #ifdef DBUS_ENABLE_STATS
1349   update_peak (&d->peak_match_rules, d->n_match_rules);
1350   update_peak (&d->connections->peak_match_rules_per_conn, d->n_match_rules);
1351
1352   d->connections->total_match_rules += 1;
1353   update_peak (&d->connections->peak_match_rules,
1354                d->connections->total_match_rules);
1355 #endif
1356 }
1357
1358 dbus_bool_t
1359 bus_connection_add_match_rule (DBusConnection *connection,
1360                                BusMatchRule   *rule)
1361 {
1362     DBusList *link;
1363
1364   link = _dbus_list_alloc_link (rule);
1365
1366   if (link == NULL)
1367     return FALSE;
1368
1369   bus_connection_add_match_rule_link (connection, link);
1370
1371   return TRUE;
1372 }
1373
1374 void
1375 bus_connection_remove_match_rule (DBusConnection *connection,
1376                                   BusMatchRule   *rule)
1377 {
1378   BusConnectionData *d;
1379
1380   d = BUS_CONNECTION_DATA (connection);
1381   _dbus_assert (d != NULL);
1382
1383   _dbus_list_remove_last (&d->match_rules, rule);
1384
1385   d->n_match_rules -= 1;
1386   _dbus_assert (d->n_match_rules >= 0);
1387
1388 #ifdef DBUS_ENABLE_STATS
1389   d->connections->total_match_rules -= 1;
1390 #endif
1391 }
1392
1393 int
1394 bus_connection_get_n_match_rules (DBusConnection *connection)
1395 {
1396   BusConnectionData *d;
1397
1398   d = BUS_CONNECTION_DATA (connection);
1399   _dbus_assert (d != NULL);
1400   
1401   return d->n_match_rules;
1402 }
1403
1404 void
1405 bus_connection_add_owned_service_link (DBusConnection *connection,
1406                                        DBusList       *link)
1407 {
1408   BusConnectionData *d;
1409
1410   d = BUS_CONNECTION_DATA (connection);
1411   _dbus_assert (d != NULL);
1412
1413   _dbus_list_append_link (&d->services_owned, link);
1414
1415   d->n_services_owned += 1;
1416
1417 #ifdef DBUS_ENABLE_STATS
1418   update_peak (&d->peak_bus_names, d->n_services_owned);
1419   update_peak (&d->connections->peak_bus_names_per_conn,
1420                d->n_services_owned);
1421
1422   d->connections->total_bus_names += 1;
1423   update_peak (&d->connections->peak_bus_names,
1424                d->connections->total_bus_names);
1425 #endif
1426 }
1427
1428 dbus_bool_t
1429 bus_connection_add_owned_service (DBusConnection *connection,
1430                                   BusService     *service)
1431 {
1432   DBusList *link;
1433
1434   link = _dbus_list_alloc_link (service);
1435
1436   if (link == NULL)
1437     return FALSE;
1438
1439   bus_connection_add_owned_service_link (connection, link);
1440
1441   return TRUE;
1442 }
1443
1444 void
1445 bus_connection_remove_owned_service (DBusConnection *connection,
1446                                      BusService     *service)
1447 {
1448   BusConnectionData *d;
1449
1450   d = BUS_CONNECTION_DATA (connection);
1451   _dbus_assert (d != NULL);
1452
1453   _dbus_list_remove_last (&d->services_owned, service);
1454
1455   d->n_services_owned -= 1;
1456   _dbus_assert (d->n_services_owned >= 0);
1457
1458 #ifdef DBUS_ENABLE_STATS
1459   d->connections->total_bus_names -= 1;
1460 #endif
1461 }
1462
1463 int
1464 bus_connection_get_n_services_owned (DBusConnection *connection)
1465 {
1466   BusConnectionData *d;
1467
1468   d = BUS_CONNECTION_DATA (connection);
1469   _dbus_assert (d != NULL);
1470   
1471   return d->n_services_owned;
1472 }
1473
1474 dbus_bool_t
1475 bus_connection_complete (DBusConnection   *connection,
1476                          const DBusString *name,
1477                          DBusError        *error)
1478 {
1479   BusConnectionData *d;
1480   unsigned long uid;
1481   
1482   d = BUS_CONNECTION_DATA (connection);
1483   _dbus_assert (d != NULL);
1484   _dbus_assert (d->name == NULL);
1485   _dbus_assert (d->policy == NULL);
1486
1487   _dbus_assert (!bus_connection_is_active (connection));
1488   
1489   if (!_dbus_string_copy_data (name, &d->name))
1490     {
1491       BUS_SET_OOM (error);
1492       return FALSE;
1493     }
1494
1495   _dbus_assert (d->name != NULL);
1496   
1497   _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);
1498
1499   d->policy = bus_context_create_client_policy (d->connections->context,
1500                                                 connection,
1501                                                 error);
1502
1503   /* we may have a NULL policy on OOM or error getting list of
1504    * groups for a user. In the latter case we don't handle it so
1505    * well currently, as it will just keep failing over and over.
1506    */
1507
1508   if (d->policy == NULL)
1509     {
1510       _dbus_verbose ("Failed to create security policy for connection %p\n",
1511                      connection);
1512       _DBUS_ASSERT_ERROR_IS_SET (error);
1513       dbus_free (d->name);
1514       d->name = NULL;
1515       return FALSE;
1516     }
1517   
1518   if (dbus_connection_get_unix_user (connection, &uid))
1519     {
1520       if (!adjust_connections_for_uid (d->connections,
1521                                        uid, 1))
1522         goto fail;
1523     }
1524
1525   /* Create and cache a string which holds information about the 
1526    * peer process; used for logging purposes.
1527    */
1528   if (!cache_peer_loginfo_string (d, connection))
1529     goto fail;
1530
1531   /* Now the connection is active, move it between lists */
1532   _dbus_list_unlink (&d->connections->incomplete,
1533                      d->link_in_connection_list);
1534   d->connections->n_incomplete -= 1;
1535   _dbus_list_append_link (&d->connections->completed,
1536                           d->link_in_connection_list);
1537   d->connections->n_completed += 1;
1538
1539   _dbus_assert (d->connections->n_incomplete >= 0);
1540   _dbus_assert (d->connections->n_completed > 0);
1541
1542   /* If we have dropped below the max. number of incomplete
1543    * connections, start accept()ing again */
1544   bus_context_check_all_watches (d->connections->context);
1545
1546   /* See if we can remove the timeout */
1547   bus_connections_expire_incomplete (d->connections);
1548
1549   _dbus_assert (bus_connection_is_active (connection));
1550   
1551   return TRUE;
1552 fail:
1553   BUS_SET_OOM (error);
1554   dbus_free (d->name);
1555   d->name = NULL;
1556   if (d->policy)
1557     bus_client_policy_unref (d->policy);
1558   d->policy = NULL;
1559   return FALSE;
1560 }
1561
1562 dbus_bool_t
1563 bus_connections_reload_policy (BusConnections *connections,
1564                                DBusError      *error)
1565 {
1566   BusConnectionData *d;
1567   DBusConnection *connection;
1568   DBusList *link;
1569
1570   _dbus_assert (connections != NULL);
1571   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1572
1573   for (link = _dbus_list_get_first_link (&(connections->completed));
1574        link;
1575        link = _dbus_list_get_next_link (&(connections->completed), link))
1576     {
1577       connection = link->data;
1578       d = BUS_CONNECTION_DATA (connection);
1579       _dbus_assert (d != NULL);
1580       _dbus_assert (d->policy != NULL);
1581
1582       bus_client_policy_unref (d->policy);
1583       d->policy = bus_context_create_client_policy (connections->context,
1584                                                     connection,
1585                                                     error);
1586       if (d->policy == NULL)
1587         {
1588           _dbus_verbose ("Failed to create security policy for connection %p\n",
1589                       connection);
1590           _DBUS_ASSERT_ERROR_IS_SET (error);
1591           return FALSE;
1592         }
1593     }
1594
1595   return TRUE;
1596 }
1597
1598 const char *
1599 bus_connection_get_name (DBusConnection *connection)
1600 {
1601   BusConnectionData *d;
1602   
1603   d = BUS_CONNECTION_DATA (connection);
1604   _dbus_assert (d != NULL);
1605   
1606   return d->name;
1607 }
1608
1609 /**
1610  * Check whether completing the passed-in connection would
1611  * exceed limits, and if so set error and return #FALSE
1612  */
1613 dbus_bool_t
1614 bus_connections_check_limits (BusConnections  *connections,
1615                               DBusConnection  *requesting_completion,
1616                               DBusError       *error)
1617 {
1618   unsigned long uid;
1619
1620   if (connections->n_completed >=
1621       bus_context_get_max_completed_connections (connections->context))
1622     {
1623       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1624                       "The maximum number of active connections has been reached");
1625       return FALSE;
1626     }
1627   
1628   if (dbus_connection_get_unix_user (requesting_completion, &uid))
1629     {
1630       if (get_connections_for_uid (connections, uid) >=
1631           bus_context_get_max_connections_per_user (connections->context))
1632         {
1633           dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1634                           "The maximum number of active connections for UID %lu has been reached",
1635                           uid);
1636           return FALSE;
1637         }
1638     }
1639   
1640   return TRUE;
1641 }
1642
1643 static void
1644 bus_pending_reply_free (BusPendingReply *pending)
1645 {
1646   _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
1647                  pending,
1648                  pending->will_send_reply,
1649                  pending->will_get_reply,
1650                  pending->reply_serial);
1651
1652   dbus_free (pending);
1653 }
1654
1655 static dbus_bool_t
1656 bus_pending_reply_send_no_reply (BusConnections  *connections,
1657                                  BusTransaction  *transaction,
1658                                  BusPendingReply *pending)
1659 {
1660   DBusMessage *message;
1661   DBusMessageIter iter;
1662   dbus_bool_t retval;
1663   const char *errmsg;
1664
1665   retval = FALSE;
1666   
1667   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1668   if (message == NULL)
1669     return FALSE;
1670   
1671   dbus_message_set_no_reply (message, TRUE);
1672   
1673   if (!dbus_message_set_reply_serial (message,
1674                                       pending->reply_serial))
1675     goto out;
1676
1677   if (!dbus_message_set_error_name (message,
1678                                     DBUS_ERROR_NO_REPLY))
1679     goto out;
1680
1681   /* If you change these messages, adjust test/dbus-daemon.c to match */
1682   if (pending->will_send_reply == NULL)
1683     errmsg = "Message recipient disconnected from message bus without replying";
1684   else
1685     errmsg = "Message did not receive a reply (timeout by message bus)";
1686
1687   dbus_message_iter_init_append (message, &iter);
1688   if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
1689     goto out;
1690     
1691   if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
1692                                          message))
1693     goto out;
1694
1695   retval = TRUE;
1696
1697  out:
1698   dbus_message_unref (message);
1699   return retval;
1700 }
1701
1702 static dbus_bool_t
1703 bus_pending_reply_expired (BusExpireList *list,
1704                            DBusList      *link,
1705                            void          *data)
1706 {
1707   BusPendingReply *pending = link->data;
1708   BusConnections *connections = data;
1709   BusTransaction *transaction;
1710   
1711   /* No reply is forthcoming. So nuke it if we can. If not,
1712    * leave it in the list to try expiring again later when we
1713    * get more memory.
1714    */
1715
1716   _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
1717                  pending,
1718                  pending->will_send_reply,
1719                  pending->will_get_reply,
1720                  pending->reply_serial);
1721   
1722   transaction = bus_transaction_new (connections->context);
1723   if (transaction == NULL)
1724     return FALSE;
1725   
1726   if (!bus_pending_reply_send_no_reply (connections,
1727                                         transaction,
1728                                         pending))
1729     {
1730       bus_transaction_cancel_and_free (transaction);
1731       return FALSE;
1732     }
1733
1734   bus_expire_list_remove_link (connections->pending_replies, link);
1735
1736   bus_pending_reply_free (pending);
1737   bus_transaction_execute_and_free (transaction);
1738
1739   return TRUE;
1740 }
1741
1742 static void
1743 bus_connection_drop_pending_replies (BusConnections  *connections,
1744                                      DBusConnection  *connection)
1745 {
1746   /* The DBusConnection is almost 100% finalized here, so you can't
1747    * do anything with it except check for pointer equality
1748    */
1749   DBusList *link;
1750
1751   _dbus_verbose ("Dropping pending replies that involve connection %p\n",
1752                  connection);
1753   
1754   link = bus_expire_list_get_first_link (connections->pending_replies);
1755   while (link != NULL)
1756     {
1757       DBusList *next;
1758       BusPendingReply *pending;
1759
1760       next = bus_expire_list_get_next_link (connections->pending_replies,
1761                                             link);
1762       pending = link->data;
1763
1764       if (pending->will_get_reply == connection)
1765         {
1766           /* We don't need to track this pending reply anymore */
1767
1768           _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
1769                          pending,
1770                          pending->will_send_reply,
1771                          pending->will_get_reply,
1772                          pending->reply_serial);
1773           
1774           bus_expire_list_remove_link (connections->pending_replies,
1775                                        link);
1776           bus_pending_reply_free (pending);
1777         }
1778       else if (pending->will_send_reply == connection)
1779         {
1780           /* The reply isn't going to be sent, so set things
1781            * up so it will be expired right away
1782            */
1783           _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
1784                          pending,
1785                          pending->will_send_reply,
1786                          pending->will_get_reply,
1787                          pending->reply_serial);
1788           
1789           pending->will_send_reply = NULL;
1790           pending->expire_item.added_tv_sec = 0;
1791           pending->expire_item.added_tv_usec = 0;
1792
1793           bus_expire_list_recheck_immediately (connections->pending_replies);
1794         }
1795       
1796       link = next;
1797     }
1798 }
1799
1800
1801 typedef struct
1802 {
1803   BusPendingReply *pending;
1804   BusConnections  *connections;
1805 } CancelPendingReplyData;
1806
1807 static void
1808 cancel_pending_reply (void *data)
1809 {
1810   CancelPendingReplyData *d = data;
1811
1812   _dbus_verbose ("d = %p\n", d);
1813   
1814   if (!bus_expire_list_remove (d->connections->pending_replies,
1815                                &d->pending->expire_item))
1816     _dbus_assert_not_reached ("pending reply did not exist to be cancelled");
1817
1818   bus_pending_reply_free (d->pending); /* since it's been cancelled */
1819 }
1820
1821 static void
1822 cancel_pending_reply_data_free (void *data)
1823 {
1824   CancelPendingReplyData *d = data;
1825
1826   _dbus_verbose ("d = %p\n", d);
1827   
1828   /* d->pending should be either freed or still
1829    * in the list of pending replies (owned by someone
1830    * else)
1831    */
1832   
1833   dbus_free (d);
1834 }
1835
1836 /*
1837  * Record that a reply is allowed; return TRUE on success.
1838  */
1839 dbus_bool_t
1840 bus_connections_expect_reply (BusConnections  *connections,
1841                               BusTransaction  *transaction,
1842                               DBusConnection  *will_get_reply,
1843                               DBusConnection  *will_send_reply,
1844                               DBusMessage     *reply_to_this,
1845                               DBusError       *error)
1846 {
1847   BusPendingReply *pending;
1848   dbus_uint32_t reply_serial;
1849   DBusList *link;
1850   CancelPendingReplyData *cprd;
1851   int count;
1852
1853   _dbus_assert (will_get_reply != NULL);
1854   _dbus_assert (will_send_reply != NULL);
1855   _dbus_assert (reply_to_this != NULL);
1856   
1857   if (dbus_message_get_no_reply (reply_to_this))
1858     return TRUE; /* we won't allow a reply, since client doesn't care for one. */
1859   
1860   reply_serial = dbus_message_get_serial (reply_to_this);
1861
1862   link = bus_expire_list_get_first_link (connections->pending_replies);
1863   count = 0;
1864   while (link != NULL)
1865     {
1866       pending = link->data;
1867
1868       if (pending->reply_serial == reply_serial &&
1869           pending->will_get_reply == will_get_reply &&
1870           pending->will_send_reply == will_send_reply)
1871         {
1872           dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1873                           "Message has the same reply serial as a currently-outstanding existing method call");
1874           return FALSE;
1875         }
1876       
1877       link = bus_expire_list_get_next_link (connections->pending_replies,
1878                                             link);
1879       if (pending->will_get_reply == will_get_reply)
1880         ++count;
1881     }
1882   
1883   if (count >=
1884       bus_context_get_max_replies_per_connection (connections->context))
1885     {
1886       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1887                       "The maximum number of pending replies per connection has been reached");
1888       return FALSE;
1889     }
1890
1891   pending = dbus_new0 (BusPendingReply, 1);
1892   if (pending == NULL)
1893     {
1894       BUS_SET_OOM (error);
1895       return FALSE;
1896     }
1897
1898 #ifdef DBUS_ENABLE_VERBOSE_MODE
1899   /* so we can see a not-yet-added pending reply */
1900   pending->expire_item.added_tv_sec = 1;
1901   pending->expire_item.added_tv_usec = 1;
1902 #endif
1903
1904   pending->will_get_reply = will_get_reply;
1905   pending->will_send_reply = will_send_reply;
1906   pending->reply_serial = reply_serial;
1907   
1908   cprd = dbus_new0 (CancelPendingReplyData, 1);
1909   if (cprd == NULL)
1910     {
1911       BUS_SET_OOM (error);
1912       bus_pending_reply_free (pending);
1913       return FALSE;
1914     }
1915   
1916   if (!bus_expire_list_add (connections->pending_replies,
1917                             &pending->expire_item))
1918     {
1919       BUS_SET_OOM (error);
1920       dbus_free (cprd);
1921       bus_pending_reply_free (pending);
1922       return FALSE;
1923     }
1924
1925   if (!bus_transaction_add_cancel_hook (transaction,
1926                                         cancel_pending_reply,
1927                                         cprd,
1928                                         cancel_pending_reply_data_free))
1929     {
1930       BUS_SET_OOM (error);
1931       bus_expire_list_remove (connections->pending_replies, &pending->expire_item);
1932       dbus_free (cprd);
1933       bus_pending_reply_free (pending);
1934       return FALSE;
1935     }
1936                                         
1937   cprd->pending = pending;
1938   cprd->connections = connections;
1939   
1940   _dbus_get_monotonic_time (&pending->expire_item.added_tv_sec,
1941                             &pending->expire_item.added_tv_usec);
1942
1943   _dbus_verbose ("Added pending reply %p, replier %p receiver %p serial %u\n",
1944                  pending,
1945                  pending->will_send_reply,
1946                  pending->will_get_reply,
1947                  pending->reply_serial);
1948   
1949   return TRUE;
1950 }
1951
1952 typedef struct
1953 {
1954   DBusList        *link;
1955   BusConnections  *connections;
1956 } CheckPendingReplyData;
1957
1958 static void
1959 cancel_check_pending_reply (void *data)
1960 {
1961   CheckPendingReplyData *d = data;
1962
1963   _dbus_verbose ("d = %p\n",d);
1964
1965   bus_expire_list_add_link (d->connections->pending_replies,
1966                             d->link);
1967   d->link = NULL;
1968 }
1969
1970 static void
1971 check_pending_reply_data_free (void *data)
1972 {
1973   CheckPendingReplyData *d = data;
1974
1975   _dbus_verbose ("d = %p\n",d);
1976   
1977   if (d->link != NULL)
1978     {
1979       BusPendingReply *pending = d->link->data;
1980       
1981       _dbus_assert (!bus_expire_list_contains_item (d->connections->pending_replies,
1982                                                     &pending->expire_item));
1983       
1984       bus_pending_reply_free (pending);
1985       _dbus_list_free_link (d->link);
1986     }
1987   
1988   dbus_free (d);
1989 }
1990
1991 /*
1992  * Check whether a reply is allowed, remove BusPendingReply
1993  * if so, return TRUE if so.
1994  */
1995 dbus_bool_t
1996 bus_connections_check_reply (BusConnections *connections,
1997                              BusTransaction *transaction,
1998                              DBusConnection *sending_reply,
1999                              DBusConnection *receiving_reply,
2000                              DBusMessage    *reply,
2001                              DBusError      *error)
2002 {
2003   CheckPendingReplyData *cprd;
2004   DBusList *link;
2005   dbus_uint32_t reply_serial;
2006   
2007   _dbus_assert (sending_reply != NULL);
2008   _dbus_assert (receiving_reply != NULL);
2009
2010   reply_serial = dbus_message_get_reply_serial (reply);
2011
2012   link = bus_expire_list_get_first_link (connections->pending_replies);
2013   while (link != NULL)
2014     {
2015       BusPendingReply *pending = link->data;
2016
2017       if (pending->reply_serial == reply_serial &&
2018           pending->will_get_reply == receiving_reply &&
2019           pending->will_send_reply == sending_reply)
2020         {
2021           _dbus_verbose ("Found pending reply with serial %u\n", reply_serial);
2022           break;
2023         }
2024       
2025       link = bus_expire_list_get_next_link (connections->pending_replies,
2026                                             link);
2027     }
2028
2029   if (link == NULL)
2030     {
2031       _dbus_verbose ("No pending reply expected\n");
2032
2033       return FALSE;
2034     }
2035
2036   cprd = dbus_new0 (CheckPendingReplyData, 1);
2037   if (cprd == NULL)
2038     {
2039       BUS_SET_OOM (error);
2040       return FALSE;
2041     }
2042   
2043   if (!bus_transaction_add_cancel_hook (transaction,
2044                                         cancel_check_pending_reply,
2045                                         cprd,
2046                                         check_pending_reply_data_free))
2047     {
2048       BUS_SET_OOM (error);
2049       dbus_free (cprd);
2050       return FALSE;
2051     }
2052
2053   cprd->link = link;
2054   cprd->connections = connections;
2055   
2056   bus_expire_list_unlink (connections->pending_replies,
2057                           link);
2058   
2059   _dbus_assert (!bus_expire_list_contains_item (connections->pending_replies, link->data));
2060
2061   return TRUE;
2062 }
2063
2064 /*
2065  * Transactions
2066  *
2067  * Note that this is fairly fragile; in particular, don't try to use
2068  * one transaction across any main loop iterations.
2069  */
2070
2071 typedef struct
2072 {
2073   BusTransaction *transaction;
2074   DBusMessage    *message;
2075   DBusPreallocatedSend *preallocated;
2076 } MessageToSend;
2077
2078 typedef struct
2079 {
2080   BusTransactionCancelFunction cancel_function;
2081   DBusFreeFunction free_data_function;
2082   void *data;
2083 } CancelHook;
2084
2085 struct BusTransaction
2086 {
2087   DBusList *connections;
2088   BusContext *context;
2089   DBusList *cancel_hooks;
2090 };
2091
2092 static void
2093 message_to_send_free (DBusConnection *connection,
2094                       MessageToSend  *to_send)
2095 {
2096   if (to_send->message)
2097     dbus_message_unref (to_send->message);
2098
2099   if (to_send->preallocated)
2100     dbus_connection_free_preallocated_send (connection, to_send->preallocated);
2101
2102   dbus_free (to_send);
2103 }
2104
2105 static void
2106 cancel_hook_cancel (void *element,
2107                     void *data)
2108 {
2109   CancelHook *ch = element;
2110
2111   _dbus_verbose ("Running transaction cancel hook\n");
2112   
2113   if (ch->cancel_function)
2114     (* ch->cancel_function) (ch->data);  
2115 }
2116
2117 static void
2118 cancel_hook_free (void *element,
2119                   void *data)
2120 {
2121   CancelHook *ch = element;
2122
2123   if (ch->free_data_function)
2124     (* ch->free_data_function) (ch->data);
2125
2126   dbus_free (ch);
2127 }
2128
2129 static void
2130 free_cancel_hooks (BusTransaction *transaction)
2131 {
2132   _dbus_list_foreach (&transaction->cancel_hooks,
2133                       cancel_hook_free, NULL);
2134   
2135   _dbus_list_clear (&transaction->cancel_hooks);
2136 }
2137
2138 BusTransaction*
2139 bus_transaction_new (BusContext *context)
2140 {
2141   BusTransaction *transaction;
2142
2143   transaction = dbus_new0 (BusTransaction, 1);
2144   if (transaction == NULL)
2145     return NULL;
2146
2147   transaction->context = context;
2148   
2149   return transaction;
2150 }
2151
2152 BusContext*
2153 bus_transaction_get_context (BusTransaction  *transaction)
2154 {
2155   return transaction->context;
2156 }
2157
2158 /**
2159  * Reserve enough memory to capture the given message if the
2160  * transaction goes through.
2161  */
2162 dbus_bool_t
2163 bus_transaction_capture (BusTransaction *transaction,
2164                          DBusConnection *sender,
2165                          DBusMessage    *message)
2166 {
2167   BusConnections *connections;
2168   BusMatchmaker *mm;
2169   DBusList *link;
2170   DBusList *recipients = NULL;
2171   dbus_bool_t ret = FALSE;
2172
2173   connections = bus_context_get_connections (transaction->context);
2174
2175   /* shortcut: don't compose the message unless someone wants it */
2176   if (connections->monitors == NULL)
2177     return TRUE;
2178
2179   mm = connections->monitor_matchmaker;
2180   /* This is non-null if there has ever been a monitor - we don't GC it.
2181    * There's little point, since there is up to 1 per process. */
2182   _dbus_assert (mm != NULL);
2183
2184   if (!bus_matchmaker_get_recipients (mm, connections, sender, NULL, message,
2185         &recipients))
2186     goto out;
2187
2188   for (link = _dbus_list_get_first_link (&recipients);
2189       link != NULL;
2190       link = _dbus_list_get_next_link (&recipients, link))
2191     {
2192       DBusConnection *recipient = link->data;
2193
2194       if (!bus_transaction_send (transaction, recipient, message))
2195         goto out;
2196     }
2197
2198   ret = TRUE;
2199
2200 out:
2201   _dbus_list_clear (&recipients);
2202   return ret;
2203 }
2204
2205 dbus_bool_t
2206 bus_transaction_capture_error_reply (BusTransaction  *transaction,
2207                                      const DBusError *error,
2208                                      DBusMessage     *in_reply_to)
2209 {
2210   BusConnections *connections;
2211   DBusMessage *reply;
2212   dbus_bool_t ret = FALSE;
2213
2214   _dbus_assert (error != NULL);
2215   _DBUS_ASSERT_ERROR_IS_SET (error);
2216
2217   connections = bus_context_get_connections (transaction->context);
2218
2219   /* shortcut: don't compose the message unless someone wants it */
2220   if (connections->monitors == NULL)
2221     return TRUE;
2222
2223   reply = dbus_message_new_error (in_reply_to,
2224                                   error->name,
2225                                   error->message);
2226
2227   if (reply == NULL)
2228     return FALSE;
2229
2230   if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2231     goto out;
2232
2233   ret = bus_transaction_capture (transaction, NULL, reply);
2234
2235 out:
2236   dbus_message_unref (reply);
2237   return ret;
2238 }
2239
2240 dbus_bool_t
2241 bus_transaction_send_from_driver (BusTransaction *transaction,
2242                                   DBusConnection *connection,
2243                                   DBusMessage    *message)
2244 {
2245   DBusError error = DBUS_ERROR_INIT;
2246
2247   /* We have to set the sender to the driver, and have
2248    * to check security policy since it was not done in
2249    * dispatch.c
2250    */
2251   _dbus_verbose ("Sending %s %s %s from driver\n",
2252                  dbus_message_get_interface (message) ?
2253                  dbus_message_get_interface (message) : "(no interface)",
2254                  dbus_message_get_member (message) ?
2255                  dbus_message_get_member (message) : "(no member)",
2256                  dbus_message_get_error_name (message) ?
2257                  dbus_message_get_error_name (message) : "(no error name)");
2258                  
2259   if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2260     return FALSE;
2261
2262   if (bus_connection_is_active (connection))
2263     {
2264       if (!dbus_message_set_destination (message,
2265                                          bus_connection_get_name (connection)))
2266         return FALSE;
2267     }
2268   
2269   /* bus driver never wants a reply */
2270   dbus_message_set_no_reply (message, TRUE);
2271
2272   /* Capture it for monitors, even if the real recipient's receive policy
2273    * does not allow it to receive this message from us (which would be odd).
2274    */
2275   if (!bus_transaction_capture (transaction, NULL, message))
2276     return FALSE;
2277
2278   /* If security policy doesn't allow the message, we would silently
2279    * eat it; the driver doesn't care about getting a reply. However,
2280    * if we're actively capturing messages, it's nice to log that we
2281    * tried to send it and did not allow ourselves to do so.
2282    */
2283   if (!bus_context_check_security_policy (bus_transaction_get_context (transaction),
2284                                           transaction,
2285                                           NULL, connection, connection, message, &error))
2286     {
2287       if (!bus_transaction_capture_error_reply (transaction, &error, message))
2288         {
2289           bus_context_log (transaction->context, DBUS_SYSTEM_LOG_WARNING,
2290                            "message from dbus-daemon rejected but not enough "
2291                            "memory to capture it");
2292         }
2293
2294       /* This is not fatal to the transaction so silently eat the disallowed
2295        * message (see reasoning above) */
2296       dbus_error_free (&error);
2297       return TRUE;
2298     }
2299
2300   return bus_transaction_send (transaction, connection, message);
2301 }
2302
2303 dbus_bool_t
2304 bus_transaction_send (BusTransaction *transaction,
2305                       DBusConnection *connection,
2306                       DBusMessage    *message)
2307 {
2308   MessageToSend *to_send;
2309   BusConnectionData *d;
2310   DBusList *link;
2311
2312   _dbus_verbose ("  trying to add %s interface=%s member=%s error=%s to transaction%s\n",
2313                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ? "error" :
2314                  dbus_message_get_reply_serial (message) != 0 ? "reply" :
2315                  "message",
2316                  dbus_message_get_interface (message) ?
2317                  dbus_message_get_interface (message) : "(unset)",
2318                  dbus_message_get_member (message) ?
2319                  dbus_message_get_member (message) : "(unset)",
2320                  dbus_message_get_error_name (message) ?
2321                  dbus_message_get_error_name (message) : "(unset)",
2322                  dbus_connection_get_is_connected (connection) ?
2323                  "" : " (disconnected)");
2324
2325   _dbus_assert (dbus_message_get_sender (message) != NULL);
2326   
2327   if (!dbus_connection_get_is_connected (connection))
2328     return TRUE; /* silently ignore disconnected connections */
2329   
2330   d = BUS_CONNECTION_DATA (connection);
2331   _dbus_assert (d != NULL);
2332   
2333   to_send = dbus_new (MessageToSend, 1);
2334   if (to_send == NULL)
2335     {
2336       return FALSE;
2337     }
2338
2339   to_send->preallocated = dbus_connection_preallocate_send (connection);
2340   if (to_send->preallocated == NULL)
2341     {
2342       dbus_free (to_send);
2343       return FALSE;
2344     }  
2345   
2346   dbus_message_ref (message);
2347   to_send->message = message;
2348   to_send->transaction = transaction;
2349
2350   _dbus_verbose ("about to prepend message\n");
2351   
2352   if (!_dbus_list_prepend (&d->transaction_messages, to_send))
2353     {
2354       message_to_send_free (connection, to_send);
2355       return FALSE;
2356     }
2357
2358   _dbus_verbose ("prepended message\n");
2359   
2360   /* See if we already had this connection in the list
2361    * for this transaction. If we have a pending message,
2362    * then we should already be in transaction->connections
2363    */
2364   link = _dbus_list_get_first_link (&d->transaction_messages);
2365   _dbus_assert (link->data == to_send);
2366   link = _dbus_list_get_next_link (&d->transaction_messages, link);
2367   while (link != NULL)
2368     {
2369       MessageToSend *m = link->data;
2370       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2371       
2372       if (m->transaction == transaction)
2373         break;
2374         
2375       link = next;
2376     }
2377
2378   if (link == NULL)
2379     {
2380       if (!_dbus_list_prepend (&transaction->connections, connection))
2381         {
2382           _dbus_list_remove (&d->transaction_messages, to_send);
2383           message_to_send_free (connection, to_send);
2384           return FALSE;
2385         }
2386     }
2387
2388   return TRUE;
2389 }
2390
2391 static void
2392 transaction_free (BusTransaction *transaction)
2393 {
2394   _dbus_assert (transaction->connections == NULL);
2395
2396   free_cancel_hooks (transaction);
2397
2398   dbus_free (transaction);
2399 }
2400
2401 static void
2402 connection_cancel_transaction (DBusConnection *connection,
2403                                BusTransaction *transaction)
2404 {
2405   DBusList *link;
2406   BusConnectionData *d;
2407   
2408   d = BUS_CONNECTION_DATA (connection);
2409   _dbus_assert (d != NULL);
2410   
2411   link = _dbus_list_get_first_link (&d->transaction_messages);
2412   while (link != NULL)
2413     {
2414       MessageToSend *m = link->data;
2415       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2416       
2417       if (m->transaction == transaction)
2418         {
2419           _dbus_list_remove_link (&d->transaction_messages,
2420                                   link);
2421           
2422           message_to_send_free (connection, m);
2423         }
2424         
2425       link = next;
2426     }
2427 }
2428
2429 void
2430 bus_transaction_cancel_and_free (BusTransaction *transaction)
2431 {
2432   DBusConnection *connection;
2433
2434   _dbus_verbose ("TRANSACTION: cancelled\n");
2435   
2436   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2437     connection_cancel_transaction (connection, transaction);
2438
2439   _dbus_list_foreach (&transaction->cancel_hooks,
2440                       cancel_hook_cancel, NULL);
2441
2442   transaction_free (transaction);
2443 }
2444
2445 static void
2446 connection_execute_transaction (DBusConnection *connection,
2447                                 BusTransaction *transaction)
2448 {
2449   DBusList *link;
2450   BusConnectionData *d;
2451   
2452   d = BUS_CONNECTION_DATA (connection);
2453   _dbus_assert (d != NULL);
2454
2455   /* Send the queue in order (FIFO) */
2456   link = _dbus_list_get_last_link (&d->transaction_messages);
2457   while (link != NULL)
2458     {
2459       MessageToSend *m = link->data;
2460       DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
2461       
2462       if (m->transaction == transaction)
2463         {
2464           _dbus_list_remove_link (&d->transaction_messages,
2465                                   link);
2466
2467           _dbus_assert (dbus_message_get_sender (m->message) != NULL);
2468           
2469           dbus_connection_send_preallocated (connection,
2470                                              m->preallocated,
2471                                              m->message,
2472                                              NULL);
2473
2474           m->preallocated = NULL; /* so we don't double-free it */
2475           
2476           message_to_send_free (connection, m);
2477         }
2478         
2479       link = prev;
2480     }
2481 }
2482
2483 void
2484 bus_transaction_execute_and_free (BusTransaction *transaction)
2485 {
2486   /* For each connection in transaction->connections
2487    * send the messages
2488    */
2489   DBusConnection *connection;
2490
2491   _dbus_verbose ("TRANSACTION: executing\n");
2492   
2493   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2494     connection_execute_transaction (connection, transaction);
2495
2496   transaction_free (transaction);
2497 }
2498
2499 static void
2500 bus_connection_remove_transactions (DBusConnection *connection)
2501 {
2502   MessageToSend *to_send;
2503   BusConnectionData *d;
2504   
2505   d = BUS_CONNECTION_DATA (connection);
2506   _dbus_assert (d != NULL);
2507   
2508   while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
2509     {
2510       /* only has an effect for the first MessageToSend listing this transaction */
2511       _dbus_list_remove (&to_send->transaction->connections,
2512                          connection);
2513
2514       _dbus_list_remove (&d->transaction_messages, to_send);
2515       message_to_send_free (connection, to_send);
2516     }
2517 }
2518
2519 /**
2520  * Converts the DBusError to a message reply
2521  */
2522 dbus_bool_t
2523 bus_transaction_send_error_reply (BusTransaction  *transaction,
2524                                   DBusConnection  *connection,
2525                                   const DBusError *error,
2526                                   DBusMessage     *in_reply_to)
2527 {
2528   DBusMessage *reply;
2529   
2530   _dbus_assert (error != NULL);
2531   _DBUS_ASSERT_ERROR_IS_SET (error);
2532   
2533   _dbus_verbose ("Sending error reply %s \"%s\"\n",
2534                  error->name, error->message);
2535
2536   reply = dbus_message_new_error (in_reply_to,
2537                                   error->name,
2538                                   error->message);
2539   if (reply == NULL)
2540     return FALSE;
2541
2542   if (!bus_transaction_send_from_driver (transaction, connection, reply))
2543     {
2544       dbus_message_unref (reply);
2545       return FALSE;
2546     }
2547
2548   dbus_message_unref (reply);
2549   
2550   return TRUE;
2551 }
2552
2553 dbus_bool_t
2554 bus_transaction_add_cancel_hook (BusTransaction               *transaction,
2555                                  BusTransactionCancelFunction  cancel_function,
2556                                  void                         *data,
2557                                  DBusFreeFunction              free_data_function)
2558 {
2559   CancelHook *ch;
2560
2561   ch = dbus_new (CancelHook, 1);
2562   if (ch == NULL)
2563     return FALSE;
2564
2565   _dbus_verbose ("     adding cancel hook function = %p data = %p\n",
2566                  cancel_function, data);
2567   
2568   ch->cancel_function = cancel_function;
2569   ch->data = data;
2570   ch->free_data_function = free_data_function;
2571
2572   /* It's important that the hooks get run in reverse order that they
2573    * were added
2574    */
2575   if (!_dbus_list_prepend (&transaction->cancel_hooks, ch))
2576     {
2577       dbus_free (ch);
2578       return FALSE;
2579     }
2580
2581   return TRUE;
2582 }
2583
2584 int
2585 bus_connections_get_n_active (BusConnections *connections)
2586 {
2587   return connections->n_completed;
2588 }
2589
2590 int
2591 bus_connections_get_n_incomplete (BusConnections *connections)
2592 {
2593   return connections->n_incomplete;
2594 }
2595
2596 #ifdef DBUS_ENABLE_STATS
2597 int
2598 bus_connections_get_total_match_rules (BusConnections *connections)
2599 {
2600   return connections->total_match_rules;
2601 }
2602
2603 int
2604 bus_connections_get_peak_match_rules (BusConnections *connections)
2605 {
2606   return connections->peak_match_rules;
2607 }
2608
2609 int
2610 bus_connections_get_peak_match_rules_per_conn (BusConnections *connections)
2611 {
2612   return connections->peak_match_rules_per_conn;
2613 }
2614
2615 int
2616 bus_connections_get_total_bus_names (BusConnections *connections)
2617 {
2618   return connections->total_bus_names;
2619 }
2620
2621 int
2622 bus_connections_get_peak_bus_names (BusConnections *connections)
2623 {
2624   return connections->peak_bus_names;
2625 }
2626
2627 int
2628 bus_connections_get_peak_bus_names_per_conn (BusConnections *connections)
2629 {
2630   return connections->peak_bus_names_per_conn;
2631 }
2632
2633 int
2634 bus_connection_get_peak_match_rules (DBusConnection *connection)
2635 {
2636   BusConnectionData *d;
2637
2638   d = BUS_CONNECTION_DATA (connection);
2639   return d->peak_match_rules;
2640 }
2641
2642 int
2643 bus_connection_get_peak_bus_names (DBusConnection *connection)
2644 {
2645   BusConnectionData *d;
2646
2647   d = BUS_CONNECTION_DATA (connection);
2648   return d->peak_bus_names;
2649 }
2650 #endif /* DBUS_ENABLE_STATS */
2651
2652 dbus_bool_t
2653 bus_connection_is_monitor (DBusConnection *connection)
2654 {
2655   BusConnectionData *d;
2656
2657   d = BUS_CONNECTION_DATA (connection);
2658
2659   return d != NULL && d->link_in_monitors != NULL;
2660 }
2661
2662 static dbus_bool_t
2663 bcd_add_monitor_rules (BusConnectionData  *d,
2664                        DBusConnection     *connection,
2665                        DBusList          **rules)
2666 {
2667   BusMatchmaker *mm = d->connections->monitor_matchmaker;
2668   DBusList *iter;
2669
2670   if (mm == NULL)
2671     {
2672       mm = bus_matchmaker_new ();
2673
2674       if (mm == NULL)
2675         return FALSE;
2676
2677       d->connections->monitor_matchmaker = mm;
2678     }
2679
2680   for (iter = _dbus_list_get_first_link (rules);
2681       iter != NULL;
2682       iter = _dbus_list_get_next_link (rules, iter))
2683     {
2684       if (!bus_matchmaker_add_rule (mm, iter->data))
2685         {
2686           bus_matchmaker_disconnected (mm, connection);
2687           return FALSE;
2688         }
2689     }
2690
2691   return TRUE;
2692 }
2693
2694 static void
2695 bcd_drop_monitor_rules (BusConnectionData *d,
2696                         DBusConnection *connection)
2697 {
2698   BusMatchmaker *mm = d->connections->monitor_matchmaker;
2699
2700   if (mm != NULL)
2701     bus_matchmaker_disconnected (mm, connection);
2702 }
2703
2704 dbus_bool_t
2705 bus_connection_be_monitor (DBusConnection  *connection,
2706                            BusTransaction  *transaction,
2707                            DBusList       **rules,
2708                            DBusError       *error)
2709 {
2710   BusConnectionData *d;
2711   DBusList *link;
2712   DBusList *tmp;
2713   DBusList *iter;
2714
2715   d = BUS_CONNECTION_DATA (connection);
2716   _dbus_assert (d != NULL);
2717
2718   link = _dbus_list_alloc_link (connection);
2719
2720   if (link == NULL)
2721     {
2722       BUS_SET_OOM (error);
2723       return FALSE;
2724     }
2725
2726   if (!bcd_add_monitor_rules (d, connection, rules))
2727     {
2728       _dbus_list_free_link (link);
2729       BUS_SET_OOM (error);
2730       return FALSE;
2731     }
2732
2733   /* release all its names */
2734   if (!_dbus_list_copy (&d->services_owned, &tmp))
2735     {
2736       bcd_drop_monitor_rules (d, connection);
2737       _dbus_list_free_link (link);
2738       BUS_SET_OOM (error);
2739       return FALSE;
2740     }
2741
2742   for (iter = _dbus_list_get_first_link (&tmp);
2743       iter != NULL;
2744       iter = _dbus_list_get_next_link (&tmp, iter))
2745     {
2746       BusService *service = iter->data;
2747
2748       /* This call is transactional: if there isn't enough memory to
2749        * do everything, then the service gets all its names back when
2750        * the transaction is cancelled due to OOM. */
2751       if (!bus_service_remove_owner (service, connection, transaction, error))
2752         {
2753           bcd_drop_monitor_rules (d, connection);
2754           _dbus_list_free_link (link);
2755           _dbus_list_clear (&tmp);
2756           return FALSE;
2757         }
2758     }
2759
2760   /* We have now done everything that can fail, so there is no problem
2761    * with doing the irrevocable stuff. */
2762
2763   _dbus_list_clear (&tmp);
2764
2765   bus_context_log (transaction->context, DBUS_SYSTEM_LOG_INFO,
2766                    "Connection %s (%s) became a monitor.", d->name,
2767                    d->cached_loginfo_string);
2768
2769   if (d->n_match_rules > 0)
2770     {
2771       BusMatchmaker *mm;
2772
2773       mm = bus_context_get_matchmaker (d->connections->context);
2774       bus_matchmaker_disconnected (mm, connection);
2775     }
2776
2777   /* flag it as a monitor */
2778   d->link_in_monitors = link;
2779   _dbus_list_append_link (&d->connections->monitors, link);
2780
2781   /* it isn't allowed to reply, and it is no longer relevant whether it
2782    * receives replies */
2783   bus_connection_drop_pending_replies (d->connections, connection);
2784
2785   return TRUE;
2786 }