plug a possible BusClientPolicy leak (FDO Bug #13242)
[platform/upstream/dbus.git] / bus / connection.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* connection.c  Client connections
3  *
4  * Copyright (C) 2003  Red Hat, Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 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           bus_client_policy_unref (d->policy);
1310           d->policy = NULL;
1311           return FALSE;
1312         }
1313     }
1314   
1315   /* Now the connection is active, move it between lists */
1316   _dbus_list_unlink (&d->connections->incomplete,
1317                      d->link_in_connection_list);
1318   d->connections->n_incomplete -= 1;
1319   _dbus_list_append_link (&d->connections->completed,
1320                           d->link_in_connection_list);
1321   d->connections->n_completed += 1;
1322
1323   _dbus_assert (d->connections->n_incomplete >= 0);
1324   _dbus_assert (d->connections->n_completed > 0);
1325
1326   /* See if we can remove the timeout */
1327   bus_connections_expire_incomplete (d->connections);
1328
1329   _dbus_assert (bus_connection_is_active (connection));
1330   
1331   return TRUE;
1332 }
1333
1334 const char *
1335 bus_connection_get_name (DBusConnection *connection)
1336 {
1337   BusConnectionData *d;
1338   
1339   d = BUS_CONNECTION_DATA (connection);
1340   _dbus_assert (d != NULL);
1341   
1342   return d->name;
1343 }
1344
1345 /**
1346  * Check whether completing the passed-in connection would
1347  * exceed limits, and if so set error and return #FALSE
1348  */
1349 dbus_bool_t
1350 bus_connections_check_limits (BusConnections  *connections,
1351                               DBusConnection  *requesting_completion,
1352                               DBusError       *error)
1353 {
1354   BusConnectionData *d;
1355   unsigned long uid;
1356   
1357   d = BUS_CONNECTION_DATA (requesting_completion);
1358   _dbus_assert (d != NULL);
1359
1360   _dbus_assert (d->name == NULL);
1361
1362   if (connections->n_completed >=
1363       bus_context_get_max_completed_connections (connections->context))
1364     {
1365       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1366                       "The maximum number of active connections has been reached");
1367       return FALSE;
1368     }
1369   
1370   if (dbus_connection_get_unix_user (requesting_completion, &uid))
1371     {
1372       if (get_connections_for_uid (connections, uid) >=
1373           bus_context_get_max_connections_per_user (connections->context))
1374         {
1375           dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1376                           "The maximum number of active connections for UID %lu has been reached",
1377                           uid);
1378           return FALSE;
1379         }
1380     }
1381   
1382   return TRUE;
1383 }
1384
1385 static void
1386 bus_pending_reply_free (BusPendingReply *pending)
1387 {
1388   _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
1389                  pending,
1390                  pending->will_send_reply,
1391                  pending->will_get_reply,
1392                  pending->reply_serial);
1393
1394   dbus_free (pending);
1395 }
1396
1397 static dbus_bool_t
1398 bus_pending_reply_send_no_reply (BusConnections  *connections,
1399                                  BusTransaction  *transaction,
1400                                  BusPendingReply *pending)
1401 {
1402   DBusMessage *message;
1403   DBusMessageIter iter;
1404   dbus_bool_t retval;
1405   const char *errmsg;
1406
1407   retval = FALSE;
1408   
1409   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1410   if (message == NULL)
1411     return FALSE;
1412   
1413   dbus_message_set_no_reply (message, TRUE);
1414   
1415   if (!dbus_message_set_reply_serial (message,
1416                                       pending->reply_serial))
1417     goto out;
1418
1419   if (!dbus_message_set_error_name (message,
1420                                     DBUS_ERROR_NO_REPLY))
1421     goto out;
1422
1423   errmsg = "Message did not receive a reply (timeout by message bus)";
1424   dbus_message_iter_init_append (message, &iter);
1425   if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
1426     goto out;
1427     
1428   if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
1429                                          message))
1430     goto out;
1431
1432   retval = TRUE;
1433
1434  out:
1435   dbus_message_unref (message);
1436   return retval;
1437 }
1438
1439 static dbus_bool_t
1440 bus_pending_reply_expired (BusExpireList *list,
1441                            DBusList      *link,
1442                            void          *data)
1443 {
1444   BusPendingReply *pending = link->data;
1445   BusConnections *connections = data;
1446   BusTransaction *transaction;
1447   
1448   /* No reply is forthcoming. So nuke it if we can. If not,
1449    * leave it in the list to try expiring again later when we
1450    * get more memory.
1451    */
1452
1453   _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
1454                  pending,
1455                  pending->will_send_reply,
1456                  pending->will_get_reply,
1457                  pending->reply_serial);
1458   
1459   transaction = bus_transaction_new (connections->context);
1460   if (transaction == NULL)
1461     return FALSE;
1462   
1463   if (!bus_pending_reply_send_no_reply (connections,
1464                                         transaction,
1465                                         pending))
1466     {
1467       bus_transaction_cancel_and_free (transaction);
1468       return FALSE;
1469     }
1470   
1471   _dbus_list_remove_link (&connections->pending_replies->items,
1472                           link);
1473   bus_pending_reply_free (pending);
1474   bus_transaction_execute_and_free (transaction);
1475
1476   return TRUE;
1477 }
1478
1479 static void
1480 bus_connection_drop_pending_replies (BusConnections  *connections,
1481                                      DBusConnection  *connection)
1482 {
1483   /* The DBusConnection is almost 100% finalized here, so you can't
1484    * do anything with it except check for pointer equality
1485    */
1486   DBusList *link;
1487
1488   _dbus_verbose ("Dropping pending replies that involve connection %p\n",
1489                  connection);
1490   
1491   link = _dbus_list_get_first_link (&connections->pending_replies->items);
1492   while (link != NULL)
1493     {
1494       DBusList *next;
1495       BusPendingReply *pending;
1496
1497       next = _dbus_list_get_next_link (&connections->pending_replies->items,
1498                                        link);
1499       pending = link->data;
1500
1501       if (pending->will_get_reply == connection)
1502         {
1503           /* We don't need to track this pending reply anymore */
1504
1505           _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
1506                          pending,
1507                          pending->will_send_reply,
1508                          pending->will_get_reply,
1509                          pending->reply_serial);
1510           
1511           _dbus_list_remove_link (&connections->pending_replies->items,
1512                                   link);
1513           bus_pending_reply_free (pending);
1514         }
1515       else if (pending->will_send_reply == connection)
1516         {
1517           /* The reply isn't going to be sent, so set things
1518            * up so it will be expired right away
1519            */
1520           _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
1521                          pending,
1522                          pending->will_send_reply,
1523                          pending->will_get_reply,
1524                          pending->reply_serial);
1525           
1526           pending->will_send_reply = NULL;
1527           pending->expire_item.added_tv_sec = 0;
1528           pending->expire_item.added_tv_usec = 0;
1529
1530           bus_expire_timeout_set_interval (connections->pending_replies->timeout,
1531                                            0);
1532         }
1533       
1534       link = next;
1535     }
1536 }
1537
1538
1539 typedef struct
1540 {
1541   BusPendingReply *pending;
1542   BusConnections  *connections;
1543 } CancelPendingReplyData;
1544
1545 static void
1546 cancel_pending_reply (void *data)
1547 {
1548   CancelPendingReplyData *d = data;
1549
1550   _dbus_verbose ("%s: d = %p\n", _DBUS_FUNCTION_NAME, d);
1551   
1552   if (!_dbus_list_remove (&d->connections->pending_replies->items,
1553                           d->pending))
1554     _dbus_assert_not_reached ("pending reply did not exist to be cancelled");
1555
1556   bus_pending_reply_free (d->pending); /* since it's been cancelled */
1557 }
1558
1559 static void
1560 cancel_pending_reply_data_free (void *data)
1561 {
1562   CancelPendingReplyData *d = data;
1563
1564   _dbus_verbose ("%s: d = %p\n", _DBUS_FUNCTION_NAME, d);
1565   
1566   /* d->pending should be either freed or still
1567    * in the list of pending replies (owned by someone
1568    * else)
1569    */
1570   
1571   dbus_free (d);
1572 }
1573
1574 /*
1575  * Record that a reply is allowed; return TRUE on success.
1576  */
1577 dbus_bool_t
1578 bus_connections_expect_reply (BusConnections  *connections,
1579                               BusTransaction  *transaction,
1580                               DBusConnection  *will_get_reply,
1581                               DBusConnection  *will_send_reply,
1582                               DBusMessage     *reply_to_this,
1583                               DBusError       *error)
1584 {
1585   BusPendingReply *pending;
1586   dbus_uint32_t reply_serial;
1587   DBusList *link;
1588   CancelPendingReplyData *cprd;
1589   int count;
1590
1591   _dbus_assert (will_get_reply != NULL);
1592   _dbus_assert (will_send_reply != NULL);
1593   _dbus_assert (reply_to_this != NULL);
1594   
1595   if (dbus_message_get_no_reply (reply_to_this))
1596     return TRUE; /* we won't allow a reply, since client doesn't care for one. */
1597   
1598   reply_serial = dbus_message_get_serial (reply_to_this);
1599
1600   link = _dbus_list_get_first_link (&connections->pending_replies->items);
1601   count = 0;
1602   while (link != NULL)
1603     {
1604       pending = link->data;
1605
1606       if (pending->reply_serial == reply_serial &&
1607           pending->will_get_reply == will_get_reply &&
1608           pending->will_send_reply == will_send_reply)
1609         {
1610           dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1611                           "Message has the same reply serial as a currently-outstanding existing method call");
1612           return FALSE;
1613         }
1614       
1615       link = _dbus_list_get_next_link (&connections->pending_replies->items,
1616                                        link);
1617       if (pending->will_get_reply == will_get_reply)
1618         ++count;
1619     }
1620   
1621   if (count >=
1622       bus_context_get_max_replies_per_connection (connections->context))
1623     {
1624       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1625                       "The maximum number of pending replies per connection has been reached");
1626       return FALSE;
1627     }
1628
1629   pending = dbus_new0 (BusPendingReply, 1);
1630   if (pending == NULL)
1631     {
1632       BUS_SET_OOM (error);
1633       return FALSE;
1634     }
1635
1636 #ifdef DBUS_ENABLE_VERBOSE_MODE
1637   /* so we can see a not-yet-added pending reply */
1638   pending->expire_item.added_tv_sec = 1;
1639   pending->expire_item.added_tv_usec = 1;
1640 #endif
1641
1642   pending->will_get_reply = will_get_reply;
1643   pending->will_send_reply = will_send_reply;
1644   pending->reply_serial = reply_serial;
1645   
1646   cprd = dbus_new0 (CancelPendingReplyData, 1);
1647   if (cprd == NULL)
1648     {
1649       BUS_SET_OOM (error);
1650       bus_pending_reply_free (pending);
1651       return FALSE;
1652     }
1653   
1654   if (!_dbus_list_prepend (&connections->pending_replies->items,
1655                            pending))
1656     {
1657       BUS_SET_OOM (error);
1658       dbus_free (cprd);
1659       bus_pending_reply_free (pending);
1660       return FALSE;
1661     }
1662
1663   if (!bus_transaction_add_cancel_hook (transaction,
1664                                         cancel_pending_reply,
1665                                         cprd,
1666                                         cancel_pending_reply_data_free))
1667     {
1668       BUS_SET_OOM (error);
1669       _dbus_list_remove (&connections->pending_replies->items, pending);
1670       dbus_free (cprd);
1671       bus_pending_reply_free (pending);
1672       return FALSE;
1673     }
1674                                         
1675   cprd->pending = pending;
1676   cprd->connections = connections;
1677   
1678   _dbus_get_current_time (&pending->expire_item.added_tv_sec,
1679                           &pending->expire_item.added_tv_usec);
1680
1681   _dbus_verbose ("Added pending reply %p, replier %p receiver %p serial %u\n",
1682                  pending,
1683                  pending->will_send_reply,
1684                  pending->will_get_reply,
1685                  pending->reply_serial);
1686   
1687   return TRUE;
1688 }
1689
1690 typedef struct
1691 {
1692   DBusList        *link;
1693   BusConnections  *connections;
1694 } CheckPendingReplyData;
1695
1696 static void
1697 cancel_check_pending_reply (void *data)
1698 {
1699   CheckPendingReplyData *d = data;
1700
1701   _dbus_verbose ("%s: d = %p\n", _DBUS_FUNCTION_NAME, d);
1702   
1703   _dbus_list_prepend_link (&d->connections->pending_replies->items,
1704                            d->link);
1705   d->link = NULL;
1706 }
1707
1708 static void
1709 check_pending_reply_data_free (void *data)
1710 {
1711   CheckPendingReplyData *d = data;
1712
1713   _dbus_verbose ("%s: d = %p\n", _DBUS_FUNCTION_NAME, d);
1714   
1715   if (d->link != NULL)
1716     {
1717       BusPendingReply *pending = d->link->data;
1718       
1719       _dbus_assert (_dbus_list_find_last (&d->connections->pending_replies->items,
1720                                           pending) == NULL);
1721       
1722       bus_pending_reply_free (pending);
1723       _dbus_list_free_link (d->link);
1724     }
1725   
1726   dbus_free (d);
1727 }
1728
1729 /*
1730  * Check whether a reply is allowed, remove BusPendingReply
1731  * if so, return TRUE if so.
1732  */
1733 dbus_bool_t
1734 bus_connections_check_reply (BusConnections *connections,
1735                              BusTransaction *transaction,
1736                              DBusConnection *sending_reply,
1737                              DBusConnection *receiving_reply,
1738                              DBusMessage    *reply,
1739                              DBusError      *error)
1740 {
1741   CheckPendingReplyData *cprd;
1742   DBusList *link;
1743   dbus_uint32_t reply_serial;
1744   
1745   _dbus_assert (sending_reply != NULL);
1746   _dbus_assert (receiving_reply != NULL);
1747
1748   reply_serial = dbus_message_get_reply_serial (reply);
1749
1750   link = _dbus_list_get_first_link (&connections->pending_replies->items);
1751   while (link != NULL)
1752     {
1753       BusPendingReply *pending = link->data;
1754
1755       if (pending->reply_serial == reply_serial &&
1756           pending->will_get_reply == receiving_reply &&
1757           pending->will_send_reply == sending_reply)
1758         {
1759           _dbus_verbose ("Found pending reply with serial %u\n", reply_serial);
1760           break;
1761         }
1762       
1763       link = _dbus_list_get_next_link (&connections->pending_replies->items,
1764                                        link);
1765     }
1766
1767   if (link == NULL)
1768     {
1769       _dbus_verbose ("No pending reply expected\n");
1770
1771       return FALSE;
1772     }
1773
1774   cprd = dbus_new0 (CheckPendingReplyData, 1);
1775   if (cprd == NULL)
1776     {
1777       BUS_SET_OOM (error);
1778       return FALSE;
1779     }
1780   
1781   if (!bus_transaction_add_cancel_hook (transaction,
1782                                         cancel_check_pending_reply,
1783                                         cprd,
1784                                         check_pending_reply_data_free))
1785     {
1786       BUS_SET_OOM (error);
1787       dbus_free (cprd);
1788       return FALSE;
1789     }
1790
1791   cprd->link = link;
1792   cprd->connections = connections;
1793   
1794   _dbus_list_unlink (&connections->pending_replies->items,
1795                      link);
1796   
1797   _dbus_assert (_dbus_list_find_last (&connections->pending_replies->items,
1798                                       link->data) == NULL);
1799
1800   return TRUE;
1801 }
1802
1803 /*
1804  * Transactions
1805  *
1806  * Note that this is fairly fragile; in particular, don't try to use
1807  * one transaction across any main loop iterations.
1808  */
1809
1810 typedef struct
1811 {
1812   BusTransaction *transaction;
1813   DBusMessage    *message;
1814   DBusPreallocatedSend *preallocated;
1815 } MessageToSend;
1816
1817 typedef struct
1818 {
1819   BusTransactionCancelFunction cancel_function;
1820   DBusFreeFunction free_data_function;
1821   void *data;
1822 } CancelHook;
1823
1824 struct BusTransaction
1825 {
1826   DBusList *connections;
1827   BusContext *context;
1828   DBusList *cancel_hooks;
1829 };
1830
1831 static void
1832 message_to_send_free (DBusConnection *connection,
1833                       MessageToSend  *to_send)
1834 {
1835   if (to_send->message)
1836     dbus_message_unref (to_send->message);
1837
1838   if (to_send->preallocated)
1839     dbus_connection_free_preallocated_send (connection, to_send->preallocated);
1840
1841   dbus_free (to_send);
1842 }
1843
1844 static void
1845 cancel_hook_cancel (void *element,
1846                     void *data)
1847 {
1848   CancelHook *ch = element;
1849
1850   _dbus_verbose ("Running transaction cancel hook\n");
1851   
1852   if (ch->cancel_function)
1853     (* ch->cancel_function) (ch->data);  
1854 }
1855
1856 static void
1857 cancel_hook_free (void *element,
1858                   void *data)
1859 {
1860   CancelHook *ch = element;
1861
1862   if (ch->free_data_function)
1863     (* ch->free_data_function) (ch->data);
1864
1865   dbus_free (ch);
1866 }
1867
1868 static void
1869 free_cancel_hooks (BusTransaction *transaction)
1870 {
1871   _dbus_list_foreach (&transaction->cancel_hooks,
1872                       cancel_hook_free, NULL);
1873   
1874   _dbus_list_clear (&transaction->cancel_hooks);
1875 }
1876
1877 BusTransaction*
1878 bus_transaction_new (BusContext *context)
1879 {
1880   BusTransaction *transaction;
1881
1882   transaction = dbus_new0 (BusTransaction, 1);
1883   if (transaction == NULL)
1884     return NULL;
1885
1886   transaction->context = context;
1887   
1888   return transaction;
1889 }
1890
1891 BusContext*
1892 bus_transaction_get_context (BusTransaction  *transaction)
1893 {
1894   return transaction->context;
1895 }
1896
1897 BusConnections*
1898 bus_transaction_get_connections (BusTransaction  *transaction)
1899 {
1900   return bus_context_get_connections (transaction->context);
1901 }
1902
1903 dbus_bool_t
1904 bus_transaction_send_from_driver (BusTransaction *transaction,
1905                                   DBusConnection *connection,
1906                                   DBusMessage    *message)
1907 {
1908   /* We have to set the sender to the driver, and have
1909    * to check security policy since it was not done in
1910    * dispatch.c
1911    */
1912   _dbus_verbose ("Sending %s %s %s from driver\n",
1913                  dbus_message_get_interface (message) ?
1914                  dbus_message_get_interface (message) : "(no interface)",
1915                  dbus_message_get_member (message) ?
1916                  dbus_message_get_member (message) : "(no member)",
1917                  dbus_message_get_error_name (message) ?
1918                  dbus_message_get_error_name (message) : "(no error name)");
1919                  
1920   if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
1921     return FALSE;
1922
1923   if (bus_connection_is_active (connection))
1924     {
1925       if (!dbus_message_set_destination (message,
1926                                          bus_connection_get_name (connection)))
1927         return FALSE;
1928     }
1929   
1930   /* bus driver never wants a reply */
1931   dbus_message_set_no_reply (message, TRUE);
1932   
1933   /* If security policy doesn't allow the message, we silently
1934    * eat it; the driver doesn't care about getting a reply.
1935    */
1936   if (!bus_context_check_security_policy (bus_transaction_get_context (transaction),
1937                                           transaction,
1938                                           NULL, connection, connection, message, NULL))
1939     return TRUE;
1940
1941   return bus_transaction_send (transaction, connection, message);
1942 }
1943
1944 dbus_bool_t
1945 bus_transaction_send (BusTransaction *transaction,
1946                       DBusConnection *connection,
1947                       DBusMessage    *message)
1948 {
1949   MessageToSend *to_send;
1950   BusConnectionData *d;
1951   DBusList *link;
1952
1953   _dbus_verbose ("  trying to add %s interface=%s member=%s error=%s to transaction%s\n",
1954                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ? "error" :
1955                  dbus_message_get_reply_serial (message) != 0 ? "reply" :
1956                  "message",
1957                  dbus_message_get_interface (message) ?
1958                  dbus_message_get_interface (message) : "(unset)",
1959                  dbus_message_get_member (message) ?
1960                  dbus_message_get_member (message) : "(unset)",
1961                  dbus_message_get_error_name (message) ?
1962                  dbus_message_get_error_name (message) : "(unset)",
1963                  dbus_connection_get_is_connected (connection) ?
1964                  "" : " (disconnected)");
1965
1966   _dbus_assert (dbus_message_get_sender (message) != NULL);
1967   
1968   if (!dbus_connection_get_is_connected (connection))
1969     return TRUE; /* silently ignore disconnected connections */
1970   
1971   d = BUS_CONNECTION_DATA (connection);
1972   _dbus_assert (d != NULL);
1973   
1974   to_send = dbus_new (MessageToSend, 1);
1975   if (to_send == NULL)
1976     {
1977       return FALSE;
1978     }
1979
1980   to_send->preallocated = dbus_connection_preallocate_send (connection);
1981   if (to_send->preallocated == NULL)
1982     {
1983       dbus_free (to_send);
1984       return FALSE;
1985     }  
1986   
1987   dbus_message_ref (message);
1988   to_send->message = message;
1989   to_send->transaction = transaction;
1990
1991   _dbus_verbose ("about to prepend message\n");
1992   
1993   if (!_dbus_list_prepend (&d->transaction_messages, to_send))
1994     {
1995       message_to_send_free (connection, to_send);
1996       return FALSE;
1997     }
1998
1999   _dbus_verbose ("prepended message\n");
2000   
2001   /* See if we already had this connection in the list
2002    * for this transaction. If we have a pending message,
2003    * then we should already be in transaction->connections
2004    */
2005   link = _dbus_list_get_first_link (&d->transaction_messages);
2006   _dbus_assert (link->data == to_send);
2007   link = _dbus_list_get_next_link (&d->transaction_messages, link);
2008   while (link != NULL)
2009     {
2010       MessageToSend *m = link->data;
2011       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2012       
2013       if (m->transaction == transaction)
2014         break;
2015         
2016       link = next;
2017     }
2018
2019   if (link == NULL)
2020     {
2021       if (!_dbus_list_prepend (&transaction->connections, connection))
2022         {
2023           _dbus_list_remove (&d->transaction_messages, to_send);
2024           message_to_send_free (connection, to_send);
2025           return FALSE;
2026         }
2027     }
2028
2029   return TRUE;
2030 }
2031
2032 static void
2033 connection_cancel_transaction (DBusConnection *connection,
2034                                BusTransaction *transaction)
2035 {
2036   DBusList *link;
2037   BusConnectionData *d;
2038   
2039   d = BUS_CONNECTION_DATA (connection);
2040   _dbus_assert (d != NULL);
2041   
2042   link = _dbus_list_get_first_link (&d->transaction_messages);
2043   while (link != NULL)
2044     {
2045       MessageToSend *m = link->data;
2046       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2047       
2048       if (m->transaction == transaction)
2049         {
2050           _dbus_list_remove_link (&d->transaction_messages,
2051                                   link);
2052           
2053           message_to_send_free (connection, m);
2054         }
2055         
2056       link = next;
2057     }
2058 }
2059
2060 void
2061 bus_transaction_cancel_and_free (BusTransaction *transaction)
2062 {
2063   DBusConnection *connection;
2064
2065   _dbus_verbose ("TRANSACTION: cancelled\n");
2066   
2067   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2068     connection_cancel_transaction (connection, transaction);
2069
2070   _dbus_assert (transaction->connections == NULL);
2071
2072   _dbus_list_foreach (&transaction->cancel_hooks,
2073                       cancel_hook_cancel, NULL);
2074
2075   free_cancel_hooks (transaction);
2076   
2077   dbus_free (transaction);
2078 }
2079
2080 static void
2081 connection_execute_transaction (DBusConnection *connection,
2082                                 BusTransaction *transaction)
2083 {
2084   DBusList *link;
2085   BusConnectionData *d;
2086   
2087   d = BUS_CONNECTION_DATA (connection);
2088   _dbus_assert (d != NULL);
2089
2090   /* Send the queue in order (FIFO) */
2091   link = _dbus_list_get_last_link (&d->transaction_messages);
2092   while (link != NULL)
2093     {
2094       MessageToSend *m = link->data;
2095       DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
2096       
2097       if (m->transaction == transaction)
2098         {
2099           _dbus_list_remove_link (&d->transaction_messages,
2100                                   link);
2101
2102           _dbus_assert (dbus_message_get_sender (m->message) != NULL);
2103           
2104           dbus_connection_send_preallocated (connection,
2105                                              m->preallocated,
2106                                              m->message,
2107                                              NULL);
2108
2109           m->preallocated = NULL; /* so we don't double-free it */
2110           
2111           message_to_send_free (connection, m);
2112         }
2113         
2114       link = prev;
2115     }
2116 }
2117
2118 void
2119 bus_transaction_execute_and_free (BusTransaction *transaction)
2120 {
2121   /* For each connection in transaction->connections
2122    * send the messages
2123    */
2124   DBusConnection *connection;
2125
2126   _dbus_verbose ("TRANSACTION: executing\n");
2127   
2128   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2129     connection_execute_transaction (connection, transaction);
2130
2131   _dbus_assert (transaction->connections == NULL);
2132
2133   free_cancel_hooks (transaction);
2134   
2135   dbus_free (transaction);
2136 }
2137
2138 static void
2139 bus_connection_remove_transactions (DBusConnection *connection)
2140 {
2141   MessageToSend *to_send;
2142   BusConnectionData *d;
2143   
2144   d = BUS_CONNECTION_DATA (connection);
2145   _dbus_assert (d != NULL);
2146   
2147   while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
2148     {
2149       /* only has an effect for the first MessageToSend listing this transaction */
2150       _dbus_list_remove (&to_send->transaction->connections,
2151                          connection);
2152
2153       _dbus_list_remove (&d->transaction_messages, to_send);
2154       message_to_send_free (connection, to_send);
2155     }
2156 }
2157
2158 /**
2159  * Converts the DBusError to a message reply
2160  */
2161 dbus_bool_t
2162 bus_transaction_send_error_reply (BusTransaction  *transaction,
2163                                   DBusConnection  *connection,
2164                                   const DBusError *error,
2165                                   DBusMessage     *in_reply_to)
2166 {
2167   DBusMessage *reply;
2168   
2169   _dbus_assert (error != NULL);
2170   _DBUS_ASSERT_ERROR_IS_SET (error);
2171   
2172   _dbus_verbose ("Sending error reply %s \"%s\"\n",
2173                  error->name, error->message);
2174
2175   reply = dbus_message_new_error (in_reply_to,
2176                                   error->name,
2177                                   error->message);
2178   if (reply == NULL)
2179     return FALSE;
2180
2181   if (!bus_transaction_send_from_driver (transaction, connection, reply))
2182     {
2183       dbus_message_unref (reply);
2184       return FALSE;
2185     }
2186
2187   dbus_message_unref (reply);
2188   
2189   return TRUE;
2190 }
2191
2192 dbus_bool_t
2193 bus_transaction_add_cancel_hook (BusTransaction               *transaction,
2194                                  BusTransactionCancelFunction  cancel_function,
2195                                  void                         *data,
2196                                  DBusFreeFunction              free_data_function)
2197 {
2198   CancelHook *ch;
2199
2200   ch = dbus_new (CancelHook, 1);
2201   if (ch == NULL)
2202     return FALSE;
2203
2204   _dbus_verbose ("     adding cancel hook function = %p data = %p\n",
2205                  cancel_function, data);
2206   
2207   ch->cancel_function = cancel_function;
2208   ch->data = data;
2209   ch->free_data_function = free_data_function;
2210
2211   /* It's important that the hooks get run in reverse order that they
2212    * were added
2213    */
2214   if (!_dbus_list_prepend (&transaction->cancel_hooks, ch))
2215     {
2216       dbus_free (ch);
2217       return FALSE;
2218     }
2219
2220   return TRUE;
2221 }