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