monitor: use the addressed_recipient to select matches
[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   BusConnectionData *d = BUS_CONNECTION_DATA (connection);
675   unsigned long uid;
676   int limit;
677
678   _dbus_assert (d != NULL);
679   limit = bus_context_get_pending_fd_timeout (d->connections->context);
680
681   if (dbus_connection_get_unix_user (connection, &uid) && uid == 0)
682     {
683       bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
684                        "Connection \"%s\" (%s) has had Unix fds pending for "
685                        "too long (pending_fd_timeout=%dms); tolerating it, "
686                        "because it has uid 0",
687                        d->name != NULL ? d->name : "(null)",
688                        bus_connection_get_loginfo (connection),
689                        limit);
690       return TRUE;
691     }
692
693   bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
694       "Connection \"%s\" (%s) has had Unix fds pending for too long, "
695       "closing it (pending_fd_timeout=%d ms)",
696       d->name != NULL ? d->name : "(null)",
697       bus_connection_get_loginfo (connection),
698       limit);
699
700   dbus_connection_close (connection);
701   return TRUE;
702 }
703
704 dbus_bool_t
705 bus_connections_setup_connection (BusConnections *connections,
706                                   DBusConnection *connection)
707 {
708
709   BusConnectionData *d;
710   dbus_bool_t retval;
711   DBusError error;
712
713   
714   d = dbus_new0 (BusConnectionData, 1);
715   
716   if (d == NULL)
717     return FALSE;
718
719   d->connections = connections;
720   d->connection = connection;
721   
722   _dbus_get_monotonic_time (&d->connection_tv_sec,
723                             &d->connection_tv_usec);
724   
725   _dbus_assert (connection_data_slot >= 0);
726   
727   if (!dbus_connection_set_data (connection,
728                                  connection_data_slot,
729                                  d, free_connection_data))
730     {
731       dbus_free (d);
732       return FALSE;
733     }
734
735   dbus_connection_set_route_peer_messages (connection, TRUE);
736   
737   retval = FALSE;
738
739   dbus_error_init (&error);
740   d->selinux_id = bus_selinux_init_connection_id (connection,
741                                                   &error);
742   if (dbus_error_is_set (&error))
743     {
744       /* This is a bit bogus because we pretend all errors
745        * are OOM; this is done because we know that in bus.c
746        * an OOM error disconnects the connection, which is
747        * the same thing we want on any other error.
748        */
749       dbus_error_free (&error);
750       goto out;
751     }
752
753   d->apparmor_confinement = bus_apparmor_init_connection_confinement (connection,
754                                                                       &error);
755   if (dbus_error_is_set (&error))
756     {
757       /* This is a bit bogus because we pretend all errors
758        * are OOM; this is done because we know that in bus.c
759        * an OOM error disconnects the connection, which is
760        * the same thing we want on any other error.
761        */
762       dbus_error_free (&error);
763       goto out;
764     }
765
766   if (!dbus_connection_set_watch_functions (connection,
767                                             add_connection_watch,
768                                             remove_connection_watch,
769                                             toggle_connection_watch,
770                                             connection,
771                                             NULL))
772     goto out;
773   
774   if (!dbus_connection_set_timeout_functions (connection,
775                                               add_connection_timeout,
776                                               remove_connection_timeout,
777                                               NULL,
778                                               connection, NULL))
779     goto out;
780
781   /* For now we don't need to set a Windows user function because
782    * there are no policies in the config file controlling what
783    * Windows users can connect. The default 'same user that owns the
784    * bus can connect' behavior of DBusConnection is fine on Windows.
785    */
786   dbus_connection_set_unix_user_function (connection,
787                                           allow_unix_user_function,
788                                           NULL, NULL);
789
790   dbus_connection_set_dispatch_status_function (connection,
791                                                 dispatch_status_function,
792                                                 bus_context_get_loop (connections->context),
793                                                 NULL);
794
795   d->link_in_connection_list = _dbus_list_alloc_link (connection);
796   if (d->link_in_connection_list == NULL)
797     goto out;
798   
799   /* Setup the connection with the dispatcher */
800   if (!bus_dispatch_add_connection (connection))
801     goto out;
802
803   if (dbus_connection_get_dispatch_status (connection) != DBUS_DISPATCH_COMPLETE)
804     {
805       if (!_dbus_loop_queue_dispatch (bus_context_get_loop (connections->context), connection))
806         {
807           bus_dispatch_remove_connection (connection);
808           goto out;
809         }
810     }
811
812   /* Setup pending fds timeout (see #80559) */
813   d->pending_unix_fds_timeout = _dbus_timeout_new (100, /* irrelevant */
814                                                    pending_unix_fds_timeout_cb,
815                                                    connection, NULL);
816   if (d->pending_unix_fds_timeout == NULL)
817     goto out;
818
819   _dbus_timeout_set_enabled (d->pending_unix_fds_timeout, FALSE);
820   if (!_dbus_loop_add_timeout (bus_context_get_loop (connections->context),
821                                d->pending_unix_fds_timeout))
822     goto out;
823
824   _dbus_connection_set_pending_fds_function (connection,
825           (DBusPendingFdsChangeFunction) check_pending_fds_cb,
826           connection);
827
828   _dbus_list_append_link (&connections->incomplete, d->link_in_connection_list);
829   connections->n_incomplete += 1;
830   
831   dbus_connection_ref (connection);
832
833   bus_connections_expire_incomplete (connections);
834   
835   /* The listening socket is removed from the main loop,
836    * i.e. does not accept(), while n_incomplete is at its
837    * maximum value; so we shouldn't get here in that case */
838   _dbus_assert (connections->n_incomplete <=
839       bus_context_get_max_incomplete_connections (connections->context));
840
841   /* If we have the maximum number of incomplete connections,
842    * stop accept()ing any more, to avert a DoS. See fd.o #80919 */
843   bus_context_check_all_watches (d->connections->context);
844   
845   retval = TRUE;
846
847  out:
848   if (!retval)
849     {
850       if (d->selinux_id)
851         bus_selinux_id_unref (d->selinux_id);
852       d->selinux_id = NULL;
853
854       if (d->apparmor_confinement)
855         bus_apparmor_confinement_unref (d->apparmor_confinement);
856       d->apparmor_confinement = NULL;
857       
858       if (!dbus_connection_set_watch_functions (connection,
859                                                 NULL, NULL, NULL,
860                                                 connection,
861                                                 NULL))
862         _dbus_assert_not_reached ("setting watch functions to NULL failed");
863       
864       if (!dbus_connection_set_timeout_functions (connection,
865                                                   NULL, NULL, NULL,
866                                                   connection,
867                                                   NULL))
868         _dbus_assert_not_reached ("setting timeout functions to NULL failed");
869
870       dbus_connection_set_unix_user_function (connection,
871                                               NULL, NULL, NULL);
872
873       dbus_connection_set_windows_user_function (connection,
874                                                  NULL, NULL, NULL);
875       
876       dbus_connection_set_dispatch_status_function (connection,
877                                                     NULL, NULL, NULL);
878
879       if (d->pending_unix_fds_timeout)
880         _dbus_timeout_unref (d->pending_unix_fds_timeout);
881
882       d->pending_unix_fds_timeout = NULL;
883
884       _dbus_connection_set_pending_fds_function (connection, NULL, NULL);
885
886       if (d->link_in_connection_list != NULL)
887         {
888           _dbus_assert (d->link_in_connection_list->next == NULL);
889           _dbus_assert (d->link_in_connection_list->prev == NULL);
890           _dbus_list_free_link (d->link_in_connection_list);
891           d->link_in_connection_list = NULL;
892         }
893       
894       if (!dbus_connection_set_data (connection,
895                                      connection_data_slot,
896                                      NULL, NULL))
897         _dbus_assert_not_reached ("failed to set connection data to null");
898
899       /* "d" has now been freed */
900     }
901   
902   return retval;
903 }
904
905 void
906 bus_connections_expire_incomplete (BusConnections *connections)
907 {    
908   int next_interval;
909
910   next_interval = -1;
911   
912   if (connections->incomplete != NULL)
913     {
914       long tv_sec, tv_usec;
915       DBusList *link;
916       int auth_timeout;
917       
918       _dbus_get_monotonic_time (&tv_sec, &tv_usec);
919       auth_timeout = bus_context_get_auth_timeout (connections->context);
920   
921       link = _dbus_list_get_first_link (&connections->incomplete);
922       while (link != NULL)
923         {
924           DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
925           DBusConnection *connection;
926           BusConnectionData *d;
927           double elapsed;
928       
929           connection = link->data;
930       
931           d = BUS_CONNECTION_DATA (connection);
932       
933           _dbus_assert (d != NULL);
934       
935           elapsed = ELAPSED_MILLISECONDS_SINCE (d->connection_tv_sec,
936                                                 d->connection_tv_usec,
937                                                 tv_sec, tv_usec);
938
939           if (elapsed >= (double) auth_timeout)
940             {
941               /* Unfortunately, we can't identify the connection: it doesn't
942                * have a unique name yet, we don't know its uid/pid yet,
943                * and so on. */
944               bus_context_log (connections->context, DBUS_SYSTEM_LOG_WARNING,
945                   "Connection has not authenticated soon enough, closing it "
946                   "(auth_timeout=%dms, elapsed: %.0fms)",
947                   auth_timeout, elapsed);
948
949               _dbus_verbose ("Timing out authentication for connection %p\n", connection);
950               dbus_connection_close (connection);
951             }
952           else
953             {
954               /* We can end the loop, since the connections are in oldest-first order */
955               next_interval = ((double)auth_timeout) - elapsed;
956               _dbus_verbose ("Connection %p authentication expires in %d milliseconds\n",
957                              connection, next_interval);
958           
959               break;
960             }
961       
962           link = next;
963         }
964     }
965
966   bus_expire_timeout_set_interval (connections->expire_timeout,
967                                    next_interval);
968 }
969
970 static dbus_bool_t
971 expire_incomplete_timeout (void *data)
972 {
973   BusConnections *connections = data;
974
975   _dbus_verbose ("Running\n");
976   
977   /* note that this may remove the timeout */
978   bus_connections_expire_incomplete (connections);
979
980   return TRUE;
981 }
982
983 dbus_bool_t
984 bus_connection_get_unix_groups  (DBusConnection   *connection,
985                                  unsigned long   **groups,
986                                  int              *n_groups,
987                                  DBusError        *error)
988 {
989   unsigned long uid;
990
991   *groups = NULL;
992   *n_groups = 0;
993
994   if (dbus_connection_get_unix_user (connection, &uid))
995     {
996       if (!_dbus_unix_groups_from_uid (uid, groups, n_groups))
997         {
998           _dbus_verbose ("Did not get any groups for UID %lu\n",
999                          uid);
1000           return FALSE;
1001         }
1002       else
1003         {
1004           _dbus_verbose ("Got %d groups for UID %lu\n",
1005                          *n_groups, uid);
1006           return TRUE;
1007         }
1008     }
1009   else
1010     return TRUE; /* successfully got 0 groups */
1011 }
1012
1013 dbus_bool_t
1014 bus_connection_is_in_unix_group (DBusConnection *connection,
1015                                  unsigned long   gid)
1016 {
1017   int i;
1018   unsigned long *group_ids;
1019   int n_group_ids;
1020
1021   if (!bus_connection_get_unix_groups (connection, &group_ids, &n_group_ids,
1022                                        NULL))
1023     return FALSE;
1024
1025   i = 0;
1026   while (i < n_group_ids)
1027     {
1028       if (group_ids[i] == gid)
1029         {
1030           dbus_free (group_ids);
1031           return TRUE;
1032         }
1033       ++i;
1034     }
1035
1036   dbus_free (group_ids);
1037   return FALSE;
1038 }
1039
1040 const char *
1041 bus_connection_get_loginfo (DBusConnection        *connection)
1042 {
1043   BusConnectionData *d;
1044     
1045   d = BUS_CONNECTION_DATA (connection);
1046   _dbus_assert(d != NULL);
1047
1048   if (!bus_connection_is_active (connection))
1049     return "inactive";
1050   return d->cached_loginfo_string;  
1051 }
1052
1053 BusClientPolicy*
1054 bus_connection_get_policy (DBusConnection *connection)
1055 {
1056   BusConnectionData *d;
1057     
1058   d = BUS_CONNECTION_DATA (connection);
1059
1060   _dbus_assert (d != NULL);
1061   _dbus_assert (d->policy != NULL);
1062   
1063   return d->policy;
1064 }
1065
1066 static dbus_bool_t
1067 foreach_active (BusConnections               *connections,
1068                 BusConnectionForeachFunction  function,
1069                 void                         *data)
1070 {
1071   DBusList *link;
1072   
1073   link = _dbus_list_get_first_link (&connections->completed);
1074   while (link != NULL)
1075     {
1076       DBusConnection *connection = link->data;
1077       DBusList *next = _dbus_list_get_next_link (&connections->completed, link);
1078
1079       if (!(* function) (connection, data))
1080         return FALSE;
1081       
1082       link = next;
1083     }
1084
1085   return TRUE;
1086 }
1087
1088 static dbus_bool_t
1089 foreach_inactive (BusConnections               *connections,
1090                   BusConnectionForeachFunction  function,
1091                   void                         *data)
1092 {
1093   DBusList *link;
1094   
1095   link = _dbus_list_get_first_link (&connections->incomplete);
1096   while (link != NULL)
1097     {
1098       DBusConnection *connection = link->data;
1099       DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
1100
1101       if (!(* function) (connection, data))
1102         return FALSE;
1103       
1104       link = next;
1105     }
1106
1107   return TRUE;
1108 }
1109
1110 /**
1111  * Calls function on each active connection; if the function returns
1112  * #FALSE, stops iterating. Active connections are authenticated
1113  * and have sent a Hello message.
1114  *
1115  * @param connections the connections object
1116  * @param function the function
1117  * @param data data to pass to it as a second arg
1118  */
1119 void
1120 bus_connections_foreach_active (BusConnections               *connections,
1121                                 BusConnectionForeachFunction  function,
1122                                 void                         *data)
1123 {
1124   foreach_active (connections, function, data);
1125 }
1126
1127 /**
1128  * Calls function on each connection; if the function returns
1129  * #FALSE, stops iterating.
1130  *
1131  * @param connections the connections object
1132  * @param function the function
1133  * @param data data to pass to it as a second arg
1134  */
1135 void
1136 bus_connections_foreach (BusConnections               *connections,
1137                          BusConnectionForeachFunction  function,
1138                          void                         *data)
1139 {
1140   if (!foreach_active (connections, function, data))
1141     return;
1142
1143   foreach_inactive (connections, function, data);
1144 }
1145
1146 BusContext*
1147 bus_connections_get_context (BusConnections *connections)
1148 {
1149   return connections->context;
1150 }
1151
1152 /*
1153  * This is used to avoid covering the same connection twice when
1154  * traversing connections. Note that it assumes we will
1155  * bus_connection_mark_stamp() each connection at least once per
1156  * INT_MAX increments of the global stamp, or wraparound would break
1157  * things.
1158  */
1159 void
1160 bus_connections_increment_stamp (BusConnections *connections)
1161 {
1162   connections->stamp += 1;
1163 }
1164
1165 /* Mark connection with current stamp, return TRUE if it
1166  * didn't already have that stamp
1167  */
1168 dbus_bool_t
1169 bus_connection_mark_stamp (DBusConnection *connection)
1170 {
1171   BusConnectionData *d;
1172   
1173   d = BUS_CONNECTION_DATA (connection);
1174   
1175   _dbus_assert (d != NULL);
1176
1177   if (d->stamp == d->connections->stamp)
1178     return FALSE;
1179   else
1180     {
1181       d->stamp = d->connections->stamp;
1182       return TRUE;
1183     }
1184 }
1185
1186 BusContext*
1187 bus_connection_get_context (DBusConnection *connection)
1188 {
1189   BusConnectionData *d;
1190
1191   d = BUS_CONNECTION_DATA (connection);
1192
1193   _dbus_assert (d != NULL);
1194
1195   return d->connections->context;
1196 }
1197
1198 BusConnections*
1199 bus_connection_get_connections (DBusConnection *connection)
1200 {
1201   BusConnectionData *d;
1202     
1203   d = BUS_CONNECTION_DATA (connection);
1204
1205   _dbus_assert (d != NULL);
1206
1207   return d->connections;
1208 }
1209
1210 BusRegistry*
1211 bus_connection_get_registry (DBusConnection *connection)
1212 {
1213   BusConnectionData *d;
1214
1215   d = BUS_CONNECTION_DATA (connection);
1216
1217   _dbus_assert (d != NULL);
1218
1219   return bus_context_get_registry (d->connections->context);
1220 }
1221
1222 BusActivation*
1223 bus_connection_get_activation (DBusConnection *connection)
1224 {
1225   BusConnectionData *d;
1226
1227   d = BUS_CONNECTION_DATA (connection);
1228
1229   _dbus_assert (d != NULL);
1230
1231   return bus_context_get_activation (d->connections->context);
1232 }
1233
1234 BusMatchmaker*
1235 bus_connection_get_matchmaker (DBusConnection *connection)
1236 {
1237   BusConnectionData *d;
1238
1239   d = BUS_CONNECTION_DATA (connection);
1240
1241   _dbus_assert (d != NULL);
1242
1243   return bus_context_get_matchmaker (d->connections->context);
1244 }
1245
1246 BusSELinuxID*
1247 bus_connection_get_selinux_id (DBusConnection *connection)
1248 {
1249   BusConnectionData *d;
1250
1251   d = BUS_CONNECTION_DATA (connection);
1252
1253   _dbus_assert (d != NULL);
1254
1255   return d->selinux_id;
1256 }
1257
1258 BusAppArmorConfinement*
1259 bus_connection_dup_apparmor_confinement (DBusConnection *connection)
1260 {
1261   BusConnectionData *d;
1262
1263   d = BUS_CONNECTION_DATA (connection);
1264
1265   _dbus_assert (d != NULL);
1266
1267   bus_apparmor_confinement_ref (d->apparmor_confinement);
1268   return d->apparmor_confinement;
1269 }
1270
1271 /**
1272  * Checks whether the connection is registered with the message bus.
1273  *
1274  * @param connection the connection
1275  * @returns #TRUE if we're an active message bus participant
1276  */
1277 dbus_bool_t
1278 bus_connection_is_active (DBusConnection *connection)
1279 {
1280   BusConnectionData *d;
1281
1282   d = BUS_CONNECTION_DATA (connection);
1283   _dbus_assert(d != NULL);
1284   
1285   return d->name != NULL;
1286 }
1287
1288 dbus_bool_t
1289 bus_connection_preallocate_oom_error (DBusConnection *connection)
1290 {
1291   DBusMessage *message;
1292   DBusPreallocatedSend *preallocated;
1293   BusConnectionData *d;
1294
1295   d = BUS_CONNECTION_DATA (connection);  
1296
1297   _dbus_assert (d != NULL);
1298
1299   if (d->oom_preallocated != NULL)
1300     return TRUE;
1301   
1302   preallocated = dbus_connection_preallocate_send (connection);
1303   if (preallocated == NULL)
1304     return FALSE;
1305
1306   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1307
1308   if (message == NULL)
1309     {
1310       dbus_connection_free_preallocated_send (connection, preallocated);
1311       return FALSE;
1312     }
1313
1314   /* d->name may be NULL, but that is OK */
1315   if (!dbus_message_set_error_name (message, DBUS_ERROR_NO_MEMORY) ||
1316       !dbus_message_set_destination (message, d->name) ||
1317       !dbus_message_set_sender (message,
1318                                 DBUS_SERVICE_DBUS))
1319     {
1320       dbus_connection_free_preallocated_send (connection, preallocated);
1321       dbus_message_unref (message);
1322       return FALSE;
1323     }
1324   
1325   /* set reply serial to placeholder value just so space is already allocated
1326    * for it.
1327    */
1328   if (!dbus_message_set_reply_serial (message, 14))
1329     {
1330       dbus_connection_free_preallocated_send (connection, preallocated);
1331       dbus_message_unref (message);
1332       return FALSE;
1333     }
1334
1335   d->oom_message = message;
1336   d->oom_preallocated = preallocated;
1337   
1338   return TRUE;
1339 }
1340
1341 void
1342 bus_connection_send_oom_error (DBusConnection *connection,
1343                                DBusMessage    *in_reply_to)
1344 {
1345   BusConnectionData *d;
1346
1347   d = BUS_CONNECTION_DATA (connection);  
1348
1349   _dbus_assert (d != NULL);  
1350   _dbus_assert (d->oom_message != NULL);
1351
1352   bus_context_log (d->connections->context, DBUS_SYSTEM_LOG_WARNING,
1353                    "dbus-daemon transaction failed (OOM), sending error to "
1354                    "sender %s", bus_connection_get_loginfo (connection));
1355
1356   /* should always succeed since we set it to a placeholder earlier */
1357   if (!dbus_message_set_reply_serial (d->oom_message,
1358                                       dbus_message_get_serial (in_reply_to)))
1359     _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");
1360
1361   _dbus_assert (dbus_message_get_sender (d->oom_message) != NULL);
1362   
1363   dbus_connection_send_preallocated (connection, d->oom_preallocated,
1364                                      d->oom_message, NULL);
1365
1366   dbus_message_unref (d->oom_message);
1367   d->oom_message = NULL;
1368   d->oom_preallocated = NULL;
1369 }
1370
1371 #ifdef DBUS_ENABLE_STATS
1372 static void
1373 update_peak (int *peak,
1374              int n)
1375 {
1376   if (*peak < n)
1377     *peak = n;
1378 }
1379 #endif
1380
1381 void
1382 bus_connection_add_match_rule_link (DBusConnection *connection,
1383                                     DBusList       *link)
1384 {
1385   BusConnectionData *d;
1386
1387   d = BUS_CONNECTION_DATA (connection);
1388   _dbus_assert (d != NULL);
1389
1390   _dbus_list_append_link (&d->match_rules, link);
1391
1392   d->n_match_rules += 1;
1393
1394 #ifdef DBUS_ENABLE_STATS
1395   update_peak (&d->peak_match_rules, d->n_match_rules);
1396   update_peak (&d->connections->peak_match_rules_per_conn, d->n_match_rules);
1397
1398   d->connections->total_match_rules += 1;
1399   update_peak (&d->connections->peak_match_rules,
1400                d->connections->total_match_rules);
1401 #endif
1402 }
1403
1404 dbus_bool_t
1405 bus_connection_add_match_rule (DBusConnection *connection,
1406                                BusMatchRule   *rule)
1407 {
1408     DBusList *link;
1409
1410   link = _dbus_list_alloc_link (rule);
1411
1412   if (link == NULL)
1413     return FALSE;
1414
1415   bus_connection_add_match_rule_link (connection, link);
1416
1417   return TRUE;
1418 }
1419
1420 void
1421 bus_connection_remove_match_rule (DBusConnection *connection,
1422                                   BusMatchRule   *rule)
1423 {
1424   BusConnectionData *d;
1425
1426   d = BUS_CONNECTION_DATA (connection);
1427   _dbus_assert (d != NULL);
1428
1429   _dbus_list_remove_last (&d->match_rules, rule);
1430
1431   d->n_match_rules -= 1;
1432   _dbus_assert (d->n_match_rules >= 0);
1433
1434 #ifdef DBUS_ENABLE_STATS
1435   d->connections->total_match_rules -= 1;
1436 #endif
1437 }
1438
1439 int
1440 bus_connection_get_n_match_rules (DBusConnection *connection)
1441 {
1442   BusConnectionData *d;
1443
1444   d = BUS_CONNECTION_DATA (connection);
1445   _dbus_assert (d != NULL);
1446   
1447   return d->n_match_rules;
1448 }
1449
1450 void
1451 bus_connection_add_owned_service_link (DBusConnection *connection,
1452                                        DBusList       *link)
1453 {
1454   BusConnectionData *d;
1455
1456   d = BUS_CONNECTION_DATA (connection);
1457   _dbus_assert (d != NULL);
1458
1459   _dbus_list_append_link (&d->services_owned, link);
1460
1461   d->n_services_owned += 1;
1462
1463 #ifdef DBUS_ENABLE_STATS
1464   update_peak (&d->peak_bus_names, d->n_services_owned);
1465   update_peak (&d->connections->peak_bus_names_per_conn,
1466                d->n_services_owned);
1467
1468   d->connections->total_bus_names += 1;
1469   update_peak (&d->connections->peak_bus_names,
1470                d->connections->total_bus_names);
1471 #endif
1472 }
1473
1474 dbus_bool_t
1475 bus_connection_add_owned_service (DBusConnection *connection,
1476                                   BusService     *service)
1477 {
1478   DBusList *link;
1479
1480   link = _dbus_list_alloc_link (service);
1481
1482   if (link == NULL)
1483     return FALSE;
1484
1485   bus_connection_add_owned_service_link (connection, link);
1486
1487   return TRUE;
1488 }
1489
1490 void
1491 bus_connection_remove_owned_service (DBusConnection *connection,
1492                                      BusService     *service)
1493 {
1494   BusConnectionData *d;
1495
1496   d = BUS_CONNECTION_DATA (connection);
1497   _dbus_assert (d != NULL);
1498
1499   _dbus_list_remove_last (&d->services_owned, service);
1500
1501   d->n_services_owned -= 1;
1502   _dbus_assert (d->n_services_owned >= 0);
1503
1504 #ifdef DBUS_ENABLE_STATS
1505   d->connections->total_bus_names -= 1;
1506 #endif
1507 }
1508
1509 int
1510 bus_connection_get_n_services_owned (DBusConnection *connection)
1511 {
1512   BusConnectionData *d;
1513
1514   d = BUS_CONNECTION_DATA (connection);
1515   _dbus_assert (d != NULL);
1516   
1517   return d->n_services_owned;
1518 }
1519
1520 dbus_bool_t
1521 bus_connection_complete (DBusConnection   *connection,
1522                          const DBusString *name,
1523                          DBusError        *error)
1524 {
1525   BusConnectionData *d;
1526   unsigned long uid;
1527   
1528   d = BUS_CONNECTION_DATA (connection);
1529   _dbus_assert (d != NULL);
1530   _dbus_assert (d->name == NULL);
1531   _dbus_assert (d->policy == NULL);
1532
1533   _dbus_assert (!bus_connection_is_active (connection));
1534   
1535   if (!_dbus_string_copy_data (name, &d->name))
1536     {
1537       BUS_SET_OOM (error);
1538       return FALSE;
1539     }
1540
1541   _dbus_assert (d->name != NULL);
1542   
1543   _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);
1544
1545   d->policy = bus_context_create_client_policy (d->connections->context,
1546                                                 connection,
1547                                                 error);
1548
1549   /* we may have a NULL policy on OOM or error getting list of
1550    * groups for a user. In the latter case we don't handle it so
1551    * well currently, as it will just keep failing over and over.
1552    */
1553
1554   if (d->policy == NULL)
1555     {
1556       _dbus_verbose ("Failed to create security policy for connection %p\n",
1557                      connection);
1558       _DBUS_ASSERT_ERROR_IS_SET (error);
1559       dbus_free (d->name);
1560       d->name = NULL;
1561       return FALSE;
1562     }
1563   
1564   if (dbus_connection_get_unix_user (connection, &uid))
1565     {
1566       if (!adjust_connections_for_uid (d->connections,
1567                                        uid, 1))
1568         goto fail;
1569     }
1570
1571   /* Create and cache a string which holds information about the 
1572    * peer process; used for logging purposes.
1573    */
1574   if (!cache_peer_loginfo_string (d, connection))
1575     goto fail;
1576
1577   /* Now the connection is active, move it between lists */
1578   _dbus_list_unlink (&d->connections->incomplete,
1579                      d->link_in_connection_list);
1580   d->connections->n_incomplete -= 1;
1581   _dbus_list_append_link (&d->connections->completed,
1582                           d->link_in_connection_list);
1583   d->connections->n_completed += 1;
1584
1585   _dbus_assert (d->connections->n_incomplete >= 0);
1586   _dbus_assert (d->connections->n_completed > 0);
1587
1588   /* If we have dropped below the max. number of incomplete
1589    * connections, start accept()ing again */
1590   bus_context_check_all_watches (d->connections->context);
1591
1592   /* See if we can remove the timeout */
1593   bus_connections_expire_incomplete (d->connections);
1594
1595   _dbus_assert (bus_connection_is_active (connection));
1596   
1597   return TRUE;
1598 fail:
1599   BUS_SET_OOM (error);
1600   dbus_free (d->name);
1601   d->name = NULL;
1602   if (d->policy)
1603     bus_client_policy_unref (d->policy);
1604   d->policy = NULL;
1605   return FALSE;
1606 }
1607
1608 dbus_bool_t
1609 bus_connections_reload_policy (BusConnections *connections,
1610                                DBusError      *error)
1611 {
1612   BusConnectionData *d;
1613   DBusConnection *connection;
1614   DBusList *link;
1615
1616   _dbus_assert (connections != NULL);
1617   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1618
1619   for (link = _dbus_list_get_first_link (&(connections->completed));
1620        link;
1621        link = _dbus_list_get_next_link (&(connections->completed), link))
1622     {
1623       connection = link->data;
1624       d = BUS_CONNECTION_DATA (connection);
1625       _dbus_assert (d != NULL);
1626       _dbus_assert (d->policy != NULL);
1627
1628       bus_client_policy_unref (d->policy);
1629       d->policy = bus_context_create_client_policy (connections->context,
1630                                                     connection,
1631                                                     error);
1632       if (d->policy == NULL)
1633         {
1634           _dbus_verbose ("Failed to create security policy for connection %p\n",
1635                       connection);
1636           _DBUS_ASSERT_ERROR_IS_SET (error);
1637           return FALSE;
1638         }
1639     }
1640
1641   return TRUE;
1642 }
1643
1644 const char *
1645 bus_connection_get_name (DBusConnection *connection)
1646 {
1647   BusConnectionData *d;
1648   
1649   d = BUS_CONNECTION_DATA (connection);
1650   _dbus_assert (d != NULL);
1651   
1652   return d->name;
1653 }
1654
1655 /**
1656  * Check whether completing the passed-in connection would
1657  * exceed limits, and if so set error and return #FALSE
1658  */
1659 dbus_bool_t
1660 bus_connections_check_limits (BusConnections  *connections,
1661                               DBusConnection  *requesting_completion,
1662                               DBusError       *error)
1663 {
1664   unsigned long uid;
1665
1666   if (connections->n_completed >=
1667       bus_context_get_max_completed_connections (connections->context))
1668     {
1669       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1670                       "The maximum number of active connections has been reached");
1671       return FALSE;
1672     }
1673   
1674   if (dbus_connection_get_unix_user (requesting_completion, &uid))
1675     {
1676       if (get_connections_for_uid (connections, uid) >=
1677           bus_context_get_max_connections_per_user (connections->context))
1678         {
1679           dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1680                           "The maximum number of active connections for UID %lu has been reached",
1681                           uid);
1682           return FALSE;
1683         }
1684     }
1685   
1686   return TRUE;
1687 }
1688
1689 static void
1690 bus_pending_reply_free (BusPendingReply *pending)
1691 {
1692   _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
1693                  pending,
1694                  pending->will_send_reply,
1695                  pending->will_get_reply,
1696                  pending->reply_serial);
1697
1698   dbus_free (pending);
1699 }
1700
1701 static dbus_bool_t
1702 bus_pending_reply_send_no_reply (BusConnections  *connections,
1703                                  BusTransaction  *transaction,
1704                                  BusPendingReply *pending)
1705 {
1706   DBusMessage *message;
1707   DBusMessageIter iter;
1708   dbus_bool_t retval;
1709   const char *errmsg;
1710
1711   retval = FALSE;
1712   
1713   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
1714   if (message == NULL)
1715     return FALSE;
1716   
1717   dbus_message_set_no_reply (message, TRUE);
1718   
1719   if (!dbus_message_set_reply_serial (message,
1720                                       pending->reply_serial))
1721     goto out;
1722
1723   if (!dbus_message_set_error_name (message,
1724                                     DBUS_ERROR_NO_REPLY))
1725     goto out;
1726
1727   /* If you change these messages, adjust test/dbus-daemon.c to match */
1728   if (pending->will_send_reply == NULL)
1729     errmsg = "Message recipient disconnected from message bus without replying";
1730   else
1731     errmsg = "Message did not receive a reply (timeout by message bus)";
1732
1733   dbus_message_iter_init_append (message, &iter);
1734   if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
1735     goto out;
1736     
1737   if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
1738                                          message))
1739     goto out;
1740
1741   retval = TRUE;
1742
1743  out:
1744   dbus_message_unref (message);
1745   return retval;
1746 }
1747
1748 static dbus_bool_t
1749 bus_pending_reply_expired (BusExpireList *list,
1750                            DBusList      *link,
1751                            void          *data)
1752 {
1753   BusPendingReply *pending = link->data;
1754   BusConnections *connections = data;
1755   BusTransaction *transaction;
1756   
1757   /* No reply is forthcoming. So nuke it if we can. If not,
1758    * leave it in the list to try expiring again later when we
1759    * get more memory.
1760    */
1761
1762   _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
1763                  pending,
1764                  pending->will_send_reply,
1765                  pending->will_get_reply,
1766                  pending->reply_serial);
1767   
1768   transaction = bus_transaction_new (connections->context);
1769   if (transaction == NULL)
1770     return FALSE;
1771   
1772   if (!bus_pending_reply_send_no_reply (connections,
1773                                         transaction,
1774                                         pending))
1775     {
1776       bus_transaction_cancel_and_free (transaction);
1777       return FALSE;
1778     }
1779
1780   bus_expire_list_remove_link (connections->pending_replies, link);
1781
1782   bus_pending_reply_free (pending);
1783   bus_transaction_execute_and_free (transaction);
1784
1785   return TRUE;
1786 }
1787
1788 static void
1789 bus_connection_drop_pending_replies (BusConnections  *connections,
1790                                      DBusConnection  *connection)
1791 {
1792   /* The DBusConnection is almost 100% finalized here, so you can't
1793    * do anything with it except check for pointer equality
1794    */
1795   DBusList *link;
1796
1797   _dbus_verbose ("Dropping pending replies that involve connection %p\n",
1798                  connection);
1799   
1800   link = bus_expire_list_get_first_link (connections->pending_replies);
1801   while (link != NULL)
1802     {
1803       DBusList *next;
1804       BusPendingReply *pending;
1805
1806       next = bus_expire_list_get_next_link (connections->pending_replies,
1807                                             link);
1808       pending = link->data;
1809
1810       if (pending->will_get_reply == connection)
1811         {
1812           /* We don't need to track this pending reply anymore */
1813
1814           _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
1815                          pending,
1816                          pending->will_send_reply,
1817                          pending->will_get_reply,
1818                          pending->reply_serial);
1819           
1820           bus_expire_list_remove_link (connections->pending_replies,
1821                                        link);
1822           bus_pending_reply_free (pending);
1823         }
1824       else if (pending->will_send_reply == connection)
1825         {
1826           /* The reply isn't going to be sent, so set things
1827            * up so it will be expired right away
1828            */
1829           _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
1830                          pending,
1831                          pending->will_send_reply,
1832                          pending->will_get_reply,
1833                          pending->reply_serial);
1834           
1835           pending->will_send_reply = NULL;
1836           pending->expire_item.added_tv_sec = 0;
1837           pending->expire_item.added_tv_usec = 0;
1838
1839           bus_expire_list_recheck_immediately (connections->pending_replies);
1840         }
1841       
1842       link = next;
1843     }
1844 }
1845
1846
1847 typedef struct
1848 {
1849   BusPendingReply *pending;
1850   BusConnections  *connections;
1851 } CancelPendingReplyData;
1852
1853 static void
1854 cancel_pending_reply (void *data)
1855 {
1856   CancelPendingReplyData *d = data;
1857
1858   _dbus_verbose ("d = %p\n", d);
1859   
1860   if (!bus_expire_list_remove (d->connections->pending_replies,
1861                                &d->pending->expire_item))
1862     _dbus_assert_not_reached ("pending reply did not exist to be cancelled");
1863
1864   bus_pending_reply_free (d->pending); /* since it's been cancelled */
1865 }
1866
1867 static void
1868 cancel_pending_reply_data_free (void *data)
1869 {
1870   CancelPendingReplyData *d = data;
1871
1872   _dbus_verbose ("d = %p\n", d);
1873   
1874   /* d->pending should be either freed or still
1875    * in the list of pending replies (owned by someone
1876    * else)
1877    */
1878   
1879   dbus_free (d);
1880 }
1881
1882 /*
1883  * Record that a reply is allowed; return TRUE on success.
1884  */
1885 dbus_bool_t
1886 bus_connections_expect_reply (BusConnections  *connections,
1887                               BusTransaction  *transaction,
1888                               DBusConnection  *will_get_reply,
1889                               DBusConnection  *will_send_reply,
1890                               DBusMessage     *reply_to_this,
1891                               DBusError       *error)
1892 {
1893   BusPendingReply *pending;
1894   dbus_uint32_t reply_serial;
1895   DBusList *link;
1896   CancelPendingReplyData *cprd;
1897   int count;
1898
1899   _dbus_assert (will_get_reply != NULL);
1900   _dbus_assert (will_send_reply != NULL);
1901   _dbus_assert (reply_to_this != NULL);
1902   
1903   if (dbus_message_get_no_reply (reply_to_this))
1904     return TRUE; /* we won't allow a reply, since client doesn't care for one. */
1905   
1906   reply_serial = dbus_message_get_serial (reply_to_this);
1907
1908   link = bus_expire_list_get_first_link (connections->pending_replies);
1909   count = 0;
1910   while (link != NULL)
1911     {
1912       pending = link->data;
1913
1914       if (pending->reply_serial == reply_serial &&
1915           pending->will_get_reply == will_get_reply &&
1916           pending->will_send_reply == will_send_reply)
1917         {
1918           dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
1919                           "Message has the same reply serial as a currently-outstanding existing method call");
1920           return FALSE;
1921         }
1922       
1923       link = bus_expire_list_get_next_link (connections->pending_replies,
1924                                             link);
1925       if (pending->will_get_reply == will_get_reply)
1926         ++count;
1927     }
1928   
1929   if (count >=
1930       bus_context_get_max_replies_per_connection (connections->context))
1931     {
1932       dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
1933                       "The maximum number of pending replies per connection has been reached");
1934       return FALSE;
1935     }
1936
1937   pending = dbus_new0 (BusPendingReply, 1);
1938   if (pending == NULL)
1939     {
1940       BUS_SET_OOM (error);
1941       return FALSE;
1942     }
1943
1944 #ifdef DBUS_ENABLE_VERBOSE_MODE
1945   /* so we can see a not-yet-added pending reply */
1946   pending->expire_item.added_tv_sec = 1;
1947   pending->expire_item.added_tv_usec = 1;
1948 #endif
1949
1950   pending->will_get_reply = will_get_reply;
1951   pending->will_send_reply = will_send_reply;
1952   pending->reply_serial = reply_serial;
1953   
1954   cprd = dbus_new0 (CancelPendingReplyData, 1);
1955   if (cprd == NULL)
1956     {
1957       BUS_SET_OOM (error);
1958       bus_pending_reply_free (pending);
1959       return FALSE;
1960     }
1961   
1962   if (!bus_expire_list_add (connections->pending_replies,
1963                             &pending->expire_item))
1964     {
1965       BUS_SET_OOM (error);
1966       dbus_free (cprd);
1967       bus_pending_reply_free (pending);
1968       return FALSE;
1969     }
1970
1971   if (!bus_transaction_add_cancel_hook (transaction,
1972                                         cancel_pending_reply,
1973                                         cprd,
1974                                         cancel_pending_reply_data_free))
1975     {
1976       BUS_SET_OOM (error);
1977       bus_expire_list_remove (connections->pending_replies, &pending->expire_item);
1978       dbus_free (cprd);
1979       bus_pending_reply_free (pending);
1980       return FALSE;
1981     }
1982                                         
1983   cprd->pending = pending;
1984   cprd->connections = connections;
1985   
1986   _dbus_get_monotonic_time (&pending->expire_item.added_tv_sec,
1987                             &pending->expire_item.added_tv_usec);
1988
1989   _dbus_verbose ("Added pending reply %p, replier %p receiver %p serial %u\n",
1990                  pending,
1991                  pending->will_send_reply,
1992                  pending->will_get_reply,
1993                  pending->reply_serial);
1994   
1995   return TRUE;
1996 }
1997
1998 typedef struct
1999 {
2000   DBusList        *link;
2001   BusConnections  *connections;
2002 } CheckPendingReplyData;
2003
2004 static void
2005 cancel_check_pending_reply (void *data)
2006 {
2007   CheckPendingReplyData *d = data;
2008
2009   _dbus_verbose ("d = %p\n",d);
2010
2011   bus_expire_list_add_link (d->connections->pending_replies,
2012                             d->link);
2013   d->link = NULL;
2014 }
2015
2016 static void
2017 check_pending_reply_data_free (void *data)
2018 {
2019   CheckPendingReplyData *d = data;
2020
2021   _dbus_verbose ("d = %p\n",d);
2022   
2023   if (d->link != NULL)
2024     {
2025       BusPendingReply *pending = d->link->data;
2026       
2027       _dbus_assert (!bus_expire_list_contains_item (d->connections->pending_replies,
2028                                                     &pending->expire_item));
2029       
2030       bus_pending_reply_free (pending);
2031       _dbus_list_free_link (d->link);
2032     }
2033   
2034   dbus_free (d);
2035 }
2036
2037 /*
2038  * Check whether a reply is allowed, remove BusPendingReply
2039  * if so, return TRUE if so.
2040  */
2041 dbus_bool_t
2042 bus_connections_check_reply (BusConnections *connections,
2043                              BusTransaction *transaction,
2044                              DBusConnection *sending_reply,
2045                              DBusConnection *receiving_reply,
2046                              DBusMessage    *reply,
2047                              DBusError      *error)
2048 {
2049   CheckPendingReplyData *cprd;
2050   DBusList *link;
2051   dbus_uint32_t reply_serial;
2052   
2053   _dbus_assert (sending_reply != NULL);
2054   _dbus_assert (receiving_reply != NULL);
2055
2056   reply_serial = dbus_message_get_reply_serial (reply);
2057
2058   link = bus_expire_list_get_first_link (connections->pending_replies);
2059   while (link != NULL)
2060     {
2061       BusPendingReply *pending = link->data;
2062
2063       if (pending->reply_serial == reply_serial &&
2064           pending->will_get_reply == receiving_reply &&
2065           pending->will_send_reply == sending_reply)
2066         {
2067           _dbus_verbose ("Found pending reply with serial %u\n", reply_serial);
2068           break;
2069         }
2070       
2071       link = bus_expire_list_get_next_link (connections->pending_replies,
2072                                             link);
2073     }
2074
2075   if (link == NULL)
2076     {
2077       _dbus_verbose ("No pending reply expected\n");
2078
2079       return FALSE;
2080     }
2081
2082   cprd = dbus_new0 (CheckPendingReplyData, 1);
2083   if (cprd == NULL)
2084     {
2085       BUS_SET_OOM (error);
2086       return FALSE;
2087     }
2088   
2089   if (!bus_transaction_add_cancel_hook (transaction,
2090                                         cancel_check_pending_reply,
2091                                         cprd,
2092                                         check_pending_reply_data_free))
2093     {
2094       BUS_SET_OOM (error);
2095       dbus_free (cprd);
2096       return FALSE;
2097     }
2098
2099   cprd->link = link;
2100   cprd->connections = connections;
2101   
2102   bus_expire_list_unlink (connections->pending_replies,
2103                           link);
2104   
2105   _dbus_assert (!bus_expire_list_contains_item (connections->pending_replies, link->data));
2106
2107   return TRUE;
2108 }
2109
2110 /*
2111  * Transactions
2112  *
2113  * Note that this is fairly fragile; in particular, don't try to use
2114  * one transaction across any main loop iterations.
2115  */
2116
2117 typedef struct
2118 {
2119   BusTransaction *transaction;
2120   DBusMessage    *message;
2121   DBusPreallocatedSend *preallocated;
2122 } MessageToSend;
2123
2124 typedef struct
2125 {
2126   BusTransactionCancelFunction cancel_function;
2127   DBusFreeFunction free_data_function;
2128   void *data;
2129 } CancelHook;
2130
2131 struct BusTransaction
2132 {
2133   DBusList *connections;
2134   BusContext *context;
2135   DBusList *cancel_hooks;
2136 };
2137
2138 static void
2139 message_to_send_free (DBusConnection *connection,
2140                       MessageToSend  *to_send)
2141 {
2142   if (to_send->message)
2143     dbus_message_unref (to_send->message);
2144
2145   if (to_send->preallocated)
2146     dbus_connection_free_preallocated_send (connection, to_send->preallocated);
2147
2148   dbus_free (to_send);
2149 }
2150
2151 static void
2152 cancel_hook_cancel (void *element,
2153                     void *data)
2154 {
2155   CancelHook *ch = element;
2156
2157   _dbus_verbose ("Running transaction cancel hook\n");
2158   
2159   if (ch->cancel_function)
2160     (* ch->cancel_function) (ch->data);  
2161 }
2162
2163 static void
2164 cancel_hook_free (void *element,
2165                   void *data)
2166 {
2167   CancelHook *ch = element;
2168
2169   if (ch->free_data_function)
2170     (* ch->free_data_function) (ch->data);
2171
2172   dbus_free (ch);
2173 }
2174
2175 static void
2176 free_cancel_hooks (BusTransaction *transaction)
2177 {
2178   _dbus_list_foreach (&transaction->cancel_hooks,
2179                       cancel_hook_free, NULL);
2180   
2181   _dbus_list_clear (&transaction->cancel_hooks);
2182 }
2183
2184 BusTransaction*
2185 bus_transaction_new (BusContext *context)
2186 {
2187   BusTransaction *transaction;
2188
2189   transaction = dbus_new0 (BusTransaction, 1);
2190   if (transaction == NULL)
2191     return NULL;
2192
2193   transaction->context = context;
2194   
2195   return transaction;
2196 }
2197
2198 BusContext*
2199 bus_transaction_get_context (BusTransaction  *transaction)
2200 {
2201   return transaction->context;
2202 }
2203
2204 /**
2205  * Reserve enough memory to capture the given message if the
2206  * transaction goes through.
2207  */
2208 dbus_bool_t
2209 bus_transaction_capture (BusTransaction *transaction,
2210                          DBusConnection *sender,
2211                          DBusConnection *addressed_recipient,
2212                          DBusMessage    *message)
2213 {
2214   BusConnections *connections;
2215   BusMatchmaker *mm;
2216   DBusList *link;
2217   DBusList *recipients = NULL;
2218   dbus_bool_t ret = FALSE;
2219
2220   connections = bus_context_get_connections (transaction->context);
2221
2222   /* shortcut: don't compose the message unless someone wants it */
2223   if (connections->monitors == NULL)
2224     return TRUE;
2225
2226   mm = connections->monitor_matchmaker;
2227   /* This is non-null if there has ever been a monitor - we don't GC it.
2228    * There's little point, since there is up to 1 per process. */
2229   _dbus_assert (mm != NULL);
2230
2231   if (!bus_matchmaker_get_recipients (mm, connections, sender,
2232         addressed_recipient, message, &recipients))
2233     goto out;
2234
2235   for (link = _dbus_list_get_first_link (&recipients);
2236       link != NULL;
2237       link = _dbus_list_get_next_link (&recipients, link))
2238     {
2239       DBusConnection *recipient = link->data;
2240
2241       if (!bus_transaction_send (transaction, recipient, message))
2242         goto out;
2243     }
2244
2245   ret = TRUE;
2246
2247 out:
2248   _dbus_list_clear (&recipients);
2249   return ret;
2250 }
2251
2252 dbus_bool_t
2253 bus_transaction_capture_error_reply (BusTransaction  *transaction,
2254                                      DBusConnection  *addressed_recipient,
2255                                      const DBusError *error,
2256                                      DBusMessage     *in_reply_to)
2257 {
2258   BusConnections *connections;
2259   DBusMessage *reply;
2260   dbus_bool_t ret = FALSE;
2261
2262   _dbus_assert (error != NULL);
2263   _DBUS_ASSERT_ERROR_IS_SET (error);
2264
2265   connections = bus_context_get_connections (transaction->context);
2266
2267   /* shortcut: don't compose the message unless someone wants it */
2268   if (connections->monitors == NULL)
2269     return TRUE;
2270
2271   reply = dbus_message_new_error (in_reply_to,
2272                                   error->name,
2273                                   error->message);
2274
2275   if (reply == NULL)
2276     return FALSE;
2277
2278   if (!dbus_message_set_sender (reply, DBUS_SERVICE_DBUS))
2279     goto out;
2280
2281   ret = bus_transaction_capture (transaction, NULL, addressed_recipient, reply);
2282
2283 out:
2284   dbus_message_unref (reply);
2285   return ret;
2286 }
2287
2288 dbus_bool_t
2289 bus_transaction_send_from_driver (BusTransaction *transaction,
2290                                   DBusConnection *connection,
2291                                   DBusMessage    *message)
2292 {
2293   DBusError error = DBUS_ERROR_INIT;
2294
2295   /* We have to set the sender to the driver, and have
2296    * to check security policy since it was not done in
2297    * dispatch.c
2298    */
2299   _dbus_verbose ("Sending %s %s %s from driver\n",
2300                  dbus_message_get_interface (message) ?
2301                  dbus_message_get_interface (message) : "(no interface)",
2302                  dbus_message_get_member (message) ?
2303                  dbus_message_get_member (message) : "(no member)",
2304                  dbus_message_get_error_name (message) ?
2305                  dbus_message_get_error_name (message) : "(no error name)");
2306                  
2307   if (!dbus_message_set_sender (message, DBUS_SERVICE_DBUS))
2308     return FALSE;
2309
2310   if (bus_connection_is_active (connection))
2311     {
2312       if (!dbus_message_set_destination (message,
2313                                          bus_connection_get_name (connection)))
2314         return FALSE;
2315     }
2316   
2317   /* bus driver never wants a reply */
2318   dbus_message_set_no_reply (message, TRUE);
2319
2320   /* Capture it for monitors, even if the real recipient's receive policy
2321    * does not allow it to receive this message from us (which would be odd).
2322    */
2323   if (!bus_transaction_capture (transaction, NULL, connection, message))
2324     return FALSE;
2325
2326   /* If security policy doesn't allow the message, we would silently
2327    * eat it; the driver doesn't care about getting a reply. However,
2328    * if we're actively capturing messages, it's nice to log that we
2329    * tried to send it and did not allow ourselves to do so.
2330    */
2331   if (!bus_context_check_security_policy (bus_transaction_get_context (transaction),
2332                                           transaction,
2333                                           NULL, connection, connection, message, &error))
2334     {
2335       if (!bus_transaction_capture_error_reply (transaction, connection,
2336                                                 &error, message))
2337         {
2338           bus_context_log (transaction->context, DBUS_SYSTEM_LOG_WARNING,
2339                            "message from dbus-daemon rejected but not enough "
2340                            "memory to capture it");
2341         }
2342
2343       /* This is not fatal to the transaction so silently eat the disallowed
2344        * message (see reasoning above) */
2345       dbus_error_free (&error);
2346       return TRUE;
2347     }
2348
2349   return bus_transaction_send (transaction, connection, message);
2350 }
2351
2352 dbus_bool_t
2353 bus_transaction_send (BusTransaction *transaction,
2354                       DBusConnection *connection,
2355                       DBusMessage    *message)
2356 {
2357   MessageToSend *to_send;
2358   BusConnectionData *d;
2359   DBusList *link;
2360
2361   _dbus_verbose ("  trying to add %s interface=%s member=%s error=%s to transaction%s\n",
2362                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ? "error" :
2363                  dbus_message_get_reply_serial (message) != 0 ? "reply" :
2364                  "message",
2365                  dbus_message_get_interface (message) ?
2366                  dbus_message_get_interface (message) : "(unset)",
2367                  dbus_message_get_member (message) ?
2368                  dbus_message_get_member (message) : "(unset)",
2369                  dbus_message_get_error_name (message) ?
2370                  dbus_message_get_error_name (message) : "(unset)",
2371                  dbus_connection_get_is_connected (connection) ?
2372                  "" : " (disconnected)");
2373
2374   _dbus_assert (dbus_message_get_sender (message) != NULL);
2375   
2376   if (!dbus_connection_get_is_connected (connection))
2377     return TRUE; /* silently ignore disconnected connections */
2378   
2379   d = BUS_CONNECTION_DATA (connection);
2380   _dbus_assert (d != NULL);
2381   
2382   to_send = dbus_new (MessageToSend, 1);
2383   if (to_send == NULL)
2384     {
2385       return FALSE;
2386     }
2387
2388   to_send->preallocated = dbus_connection_preallocate_send (connection);
2389   if (to_send->preallocated == NULL)
2390     {
2391       dbus_free (to_send);
2392       return FALSE;
2393     }  
2394   
2395   dbus_message_ref (message);
2396   to_send->message = message;
2397   to_send->transaction = transaction;
2398
2399   _dbus_verbose ("about to prepend message\n");
2400   
2401   if (!_dbus_list_prepend (&d->transaction_messages, to_send))
2402     {
2403       message_to_send_free (connection, to_send);
2404       return FALSE;
2405     }
2406
2407   _dbus_verbose ("prepended message\n");
2408   
2409   /* See if we already had this connection in the list
2410    * for this transaction. If we have a pending message,
2411    * then we should already be in transaction->connections
2412    */
2413   link = _dbus_list_get_first_link (&d->transaction_messages);
2414   _dbus_assert (link->data == to_send);
2415   link = _dbus_list_get_next_link (&d->transaction_messages, link);
2416   while (link != NULL)
2417     {
2418       MessageToSend *m = link->data;
2419       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2420       
2421       if (m->transaction == transaction)
2422         break;
2423         
2424       link = next;
2425     }
2426
2427   if (link == NULL)
2428     {
2429       if (!_dbus_list_prepend (&transaction->connections, connection))
2430         {
2431           _dbus_list_remove (&d->transaction_messages, to_send);
2432           message_to_send_free (connection, to_send);
2433           return FALSE;
2434         }
2435     }
2436
2437   return TRUE;
2438 }
2439
2440 static void
2441 transaction_free (BusTransaction *transaction)
2442 {
2443   _dbus_assert (transaction->connections == NULL);
2444
2445   free_cancel_hooks (transaction);
2446
2447   dbus_free (transaction);
2448 }
2449
2450 static void
2451 connection_cancel_transaction (DBusConnection *connection,
2452                                BusTransaction *transaction)
2453 {
2454   DBusList *link;
2455   BusConnectionData *d;
2456   
2457   d = BUS_CONNECTION_DATA (connection);
2458   _dbus_assert (d != NULL);
2459   
2460   link = _dbus_list_get_first_link (&d->transaction_messages);
2461   while (link != NULL)
2462     {
2463       MessageToSend *m = link->data;
2464       DBusList *next = _dbus_list_get_next_link (&d->transaction_messages, link);
2465       
2466       if (m->transaction == transaction)
2467         {
2468           _dbus_list_remove_link (&d->transaction_messages,
2469                                   link);
2470           
2471           message_to_send_free (connection, m);
2472         }
2473         
2474       link = next;
2475     }
2476 }
2477
2478 void
2479 bus_transaction_cancel_and_free (BusTransaction *transaction)
2480 {
2481   DBusConnection *connection;
2482
2483   _dbus_verbose ("TRANSACTION: cancelled\n");
2484   
2485   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2486     connection_cancel_transaction (connection, transaction);
2487
2488   _dbus_list_foreach (&transaction->cancel_hooks,
2489                       cancel_hook_cancel, NULL);
2490
2491   transaction_free (transaction);
2492 }
2493
2494 static void
2495 connection_execute_transaction (DBusConnection *connection,
2496                                 BusTransaction *transaction)
2497 {
2498   DBusList *link;
2499   BusConnectionData *d;
2500   
2501   d = BUS_CONNECTION_DATA (connection);
2502   _dbus_assert (d != NULL);
2503
2504   /* Send the queue in order (FIFO) */
2505   link = _dbus_list_get_last_link (&d->transaction_messages);
2506   while (link != NULL)
2507     {
2508       MessageToSend *m = link->data;
2509       DBusList *prev = _dbus_list_get_prev_link (&d->transaction_messages, link);
2510       
2511       if (m->transaction == transaction)
2512         {
2513           _dbus_list_remove_link (&d->transaction_messages,
2514                                   link);
2515
2516           _dbus_assert (dbus_message_get_sender (m->message) != NULL);
2517           
2518           dbus_connection_send_preallocated (connection,
2519                                              m->preallocated,
2520                                              m->message,
2521                                              NULL);
2522
2523           m->preallocated = NULL; /* so we don't double-free it */
2524           
2525           message_to_send_free (connection, m);
2526         }
2527         
2528       link = prev;
2529     }
2530 }
2531
2532 void
2533 bus_transaction_execute_and_free (BusTransaction *transaction)
2534 {
2535   /* For each connection in transaction->connections
2536    * send the messages
2537    */
2538   DBusConnection *connection;
2539
2540   _dbus_verbose ("TRANSACTION: executing\n");
2541   
2542   while ((connection = _dbus_list_pop_first (&transaction->connections)))
2543     connection_execute_transaction (connection, transaction);
2544
2545   transaction_free (transaction);
2546 }
2547
2548 static void
2549 bus_connection_remove_transactions (DBusConnection *connection)
2550 {
2551   MessageToSend *to_send;
2552   BusConnectionData *d;
2553   
2554   d = BUS_CONNECTION_DATA (connection);
2555   _dbus_assert (d != NULL);
2556   
2557   while ((to_send = _dbus_list_get_first (&d->transaction_messages)))
2558     {
2559       /* only has an effect for the first MessageToSend listing this transaction */
2560       _dbus_list_remove (&to_send->transaction->connections,
2561                          connection);
2562
2563       _dbus_list_remove (&d->transaction_messages, to_send);
2564       message_to_send_free (connection, to_send);
2565     }
2566 }
2567
2568 /**
2569  * Converts the DBusError to a message reply
2570  */
2571 dbus_bool_t
2572 bus_transaction_send_error_reply (BusTransaction  *transaction,
2573                                   DBusConnection  *connection,
2574                                   const DBusError *error,
2575                                   DBusMessage     *in_reply_to)
2576 {
2577   DBusMessage *reply;
2578   
2579   _dbus_assert (error != NULL);
2580   _DBUS_ASSERT_ERROR_IS_SET (error);
2581   
2582   _dbus_verbose ("Sending error reply %s \"%s\"\n",
2583                  error->name, error->message);
2584
2585   reply = dbus_message_new_error (in_reply_to,
2586                                   error->name,
2587                                   error->message);
2588   if (reply == NULL)
2589     return FALSE;
2590
2591   if (!bus_transaction_send_from_driver (transaction, connection, reply))
2592     {
2593       dbus_message_unref (reply);
2594       return FALSE;
2595     }
2596
2597   dbus_message_unref (reply);
2598   
2599   return TRUE;
2600 }
2601
2602 dbus_bool_t
2603 bus_transaction_add_cancel_hook (BusTransaction               *transaction,
2604                                  BusTransactionCancelFunction  cancel_function,
2605                                  void                         *data,
2606                                  DBusFreeFunction              free_data_function)
2607 {
2608   CancelHook *ch;
2609
2610   ch = dbus_new (CancelHook, 1);
2611   if (ch == NULL)
2612     return FALSE;
2613
2614   _dbus_verbose ("     adding cancel hook function = %p data = %p\n",
2615                  cancel_function, data);
2616   
2617   ch->cancel_function = cancel_function;
2618   ch->data = data;
2619   ch->free_data_function = free_data_function;
2620
2621   /* It's important that the hooks get run in reverse order that they
2622    * were added
2623    */
2624   if (!_dbus_list_prepend (&transaction->cancel_hooks, ch))
2625     {
2626       dbus_free (ch);
2627       return FALSE;
2628     }
2629
2630   return TRUE;
2631 }
2632
2633 int
2634 bus_connections_get_n_active (BusConnections *connections)
2635 {
2636   return connections->n_completed;
2637 }
2638
2639 int
2640 bus_connections_get_n_incomplete (BusConnections *connections)
2641 {
2642   return connections->n_incomplete;
2643 }
2644
2645 #ifdef DBUS_ENABLE_STATS
2646 int
2647 bus_connections_get_total_match_rules (BusConnections *connections)
2648 {
2649   return connections->total_match_rules;
2650 }
2651
2652 int
2653 bus_connections_get_peak_match_rules (BusConnections *connections)
2654 {
2655   return connections->peak_match_rules;
2656 }
2657
2658 int
2659 bus_connections_get_peak_match_rules_per_conn (BusConnections *connections)
2660 {
2661   return connections->peak_match_rules_per_conn;
2662 }
2663
2664 int
2665 bus_connections_get_total_bus_names (BusConnections *connections)
2666 {
2667   return connections->total_bus_names;
2668 }
2669
2670 int
2671 bus_connections_get_peak_bus_names (BusConnections *connections)
2672 {
2673   return connections->peak_bus_names;
2674 }
2675
2676 int
2677 bus_connections_get_peak_bus_names_per_conn (BusConnections *connections)
2678 {
2679   return connections->peak_bus_names_per_conn;
2680 }
2681
2682 int
2683 bus_connection_get_peak_match_rules (DBusConnection *connection)
2684 {
2685   BusConnectionData *d;
2686
2687   d = BUS_CONNECTION_DATA (connection);
2688   _dbus_assert(d != NULL);
2689
2690   return d->peak_match_rules;
2691 }
2692
2693 int
2694 bus_connection_get_peak_bus_names (DBusConnection *connection)
2695 {
2696   BusConnectionData *d;
2697
2698   d = BUS_CONNECTION_DATA (connection);
2699   _dbus_assert(d != NULL);
2700
2701   return d->peak_bus_names;
2702 }
2703 #endif /* DBUS_ENABLE_STATS */
2704
2705 dbus_bool_t
2706 bus_connection_is_monitor (DBusConnection *connection)
2707 {
2708   BusConnectionData *d;
2709
2710   d = BUS_CONNECTION_DATA (connection);
2711   _dbus_assert(d != NULL);
2712
2713   return d->link_in_monitors != NULL;
2714 }
2715
2716 static dbus_bool_t
2717 bcd_add_monitor_rules (BusConnectionData  *d,
2718                        DBusConnection     *connection,
2719                        DBusList          **rules)
2720 {
2721   BusMatchmaker *mm = d->connections->monitor_matchmaker;
2722   DBusList *iter;
2723
2724   if (mm == NULL)
2725     {
2726       mm = bus_matchmaker_new ();
2727
2728       if (mm == NULL)
2729         return FALSE;
2730
2731       d->connections->monitor_matchmaker = mm;
2732     }
2733
2734   for (iter = _dbus_list_get_first_link (rules);
2735       iter != NULL;
2736       iter = _dbus_list_get_next_link (rules, iter))
2737     {
2738       if (!bus_matchmaker_add_rule (mm, iter->data))
2739         {
2740           bus_matchmaker_disconnected (mm, connection);
2741           return FALSE;
2742         }
2743     }
2744
2745   return TRUE;
2746 }
2747
2748 static void
2749 bcd_drop_monitor_rules (BusConnectionData *d,
2750                         DBusConnection *connection)
2751 {
2752   BusMatchmaker *mm = d->connections->monitor_matchmaker;
2753
2754   if (mm != NULL)
2755     bus_matchmaker_disconnected (mm, connection);
2756 }
2757
2758 dbus_bool_t
2759 bus_connection_be_monitor (DBusConnection  *connection,
2760                            BusTransaction  *transaction,
2761                            DBusList       **rules,
2762                            DBusError       *error)
2763 {
2764   BusConnectionData *d;
2765   DBusList *link;
2766   DBusList *tmp;
2767   DBusList *iter;
2768
2769   d = BUS_CONNECTION_DATA (connection);
2770   _dbus_assert (d != NULL);
2771
2772   link = _dbus_list_alloc_link (connection);
2773
2774   if (link == NULL)
2775     {
2776       BUS_SET_OOM (error);
2777       return FALSE;
2778     }
2779
2780   if (!bcd_add_monitor_rules (d, connection, rules))
2781     {
2782       _dbus_list_free_link (link);
2783       BUS_SET_OOM (error);
2784       return FALSE;
2785     }
2786
2787   /* release all its names */
2788   if (!_dbus_list_copy (&d->services_owned, &tmp))
2789     {
2790       bcd_drop_monitor_rules (d, connection);
2791       _dbus_list_free_link (link);
2792       BUS_SET_OOM (error);
2793       return FALSE;
2794     }
2795
2796   for (iter = _dbus_list_get_first_link (&tmp);
2797       iter != NULL;
2798       iter = _dbus_list_get_next_link (&tmp, iter))
2799     {
2800       BusService *service = iter->data;
2801
2802       /* This call is transactional: if there isn't enough memory to
2803        * do everything, then the service gets all its names back when
2804        * the transaction is cancelled due to OOM. */
2805       if (!bus_service_remove_owner (service, connection, transaction, error))
2806         {
2807           bcd_drop_monitor_rules (d, connection);
2808           _dbus_list_free_link (link);
2809           _dbus_list_clear (&tmp);
2810           return FALSE;
2811         }
2812     }
2813
2814   /* We have now done everything that can fail, so there is no problem
2815    * with doing the irrevocable stuff. */
2816
2817   _dbus_list_clear (&tmp);
2818
2819   bus_context_log (transaction->context, DBUS_SYSTEM_LOG_INFO,
2820                    "Connection %s (%s) became a monitor.", d->name,
2821                    d->cached_loginfo_string);
2822
2823   if (d->n_match_rules > 0)
2824     {
2825       BusMatchmaker *mm;
2826
2827       mm = bus_context_get_matchmaker (d->connections->context);
2828       bus_matchmaker_disconnected (mm, connection);
2829     }
2830
2831   /* flag it as a monitor */
2832   d->link_in_monitors = link;
2833   _dbus_list_append_link (&d->connections->monitors, link);
2834
2835   /* it isn't allowed to reply, and it is no longer relevant whether it
2836    * receives replies */
2837   bus_connection_drop_pending_replies (d->connections, connection);
2838
2839   return TRUE;
2840 }