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