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