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