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