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