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