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