connection.c 61.4 KB
Newer Older
1 2 3 4 5
/* -*- mode: C; c-file-style: "gnu" -*- */
/* connection.c  Client connections
 *
 * Copyright (C) 2003  Red Hat, Inc.
 *
6
 * Licensed under the Academic Free License version 2.1
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "connection.h"
24
#include "dispatch.h"
25
#include "policy.h"
26
#include "services.h"
27
#include "utils.h"
28
#include "signals.h"
29
#include "expirelist.h"
30
#include "selinux.h"
31
#include <dbus/dbus-list.h>
32
#include <dbus/dbus-hash.h>
33
#include <dbus/dbus-timeout.h>
34

35 36
static void bus_connection_remove_transactions (DBusConnection *connection);

37 38 39 40 41 42 43 44 45 46 47
typedef struct
{
  BusExpireItem expire_item;

  DBusConnection *will_get_reply;
  DBusConnection *will_send_reply;

  dbus_uint32_t reply_serial;
  
} BusPendingReply;

48 49 50
struct BusConnections
{
  int refcount;
51 52 53 54
  DBusList *completed;  /**< List of all completed connections */
  int n_completed;      /**< Length of completed list */
  DBusList *incomplete; /**< List of all not-yet-active connections */
  int n_incomplete;     /**< Length of incomplete list */
55
  BusContext *context;
56
  DBusHashTable *completed_by_user; /**< Number of completed connections for each UID */
57
  DBusTimeout *expire_timeout; /**< Timeout for expiring incomplete connections. */
58
  int stamp;                   /**< Incrementing number */
59
  BusExpireList *pending_replies; /**< List of pending replies */
60 61
};

62
static dbus_int32_t connection_data_slot = -1;
63 64 65

typedef struct
{
66
  BusConnections *connections;
67
  DBusList *link_in_connection_list;
68
  DBusConnection *connection;
69
  DBusList *services_owned;
70
  int n_services_owned;
71 72
  DBusList *match_rules;
  int n_match_rules;
73
  char *name;
74 75 76
  DBusList *transaction_messages; /**< Stuff we need to send as part of a transaction */
  DBusMessage *oom_message;
  DBusPreallocatedSend *oom_preallocated;
77
  BusClientPolicy *policy;
78

79 80
  BusSELinuxID *selinux_id;

81 82
  long connection_tv_sec;  /**< Time when we connected (seconds component) */
  long connection_tv_usec; /**< Time when we connected (microsec component) */
83
  int stamp;               /**< connections->stamp last time we were traversed */
84 85
} BusConnectionData;

86 87 88
static dbus_bool_t bus_pending_reply_expired (BusExpireList *list,
                                              DBusList      *link,
                                              void          *data);
89 90 91 92

static void bus_connection_drop_pending_replies (BusConnections  *connections,
                                                 DBusConnection  *connection);

93 94
static dbus_bool_t expire_incomplete_timeout (void *data);

95 96
#define BUS_CONNECTION_DATA(connection) (dbus_connection_get_data ((connection), connection_data_slot))

97
static DBusLoop*
98 99 100 101 102 103 104 105 106
connection_get_loop (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  return bus_context_get_loop (d->connections->context);
}

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

static int
get_connections_for_uid (BusConnections *connections,
                         dbus_uid_t      uid)
{
  void *val;
  int current_count;

  /* val is NULL is 0 when it isn't in the hash yet */
  
  val = _dbus_hash_table_lookup_ulong (connections->completed_by_user,
                                       uid);

  current_count = _DBUS_POINTER_TO_INT (val);

  return current_count;
}

static dbus_bool_t
adjust_connections_for_uid (BusConnections *connections,
                            dbus_uid_t      uid,
                            int             adjustment)
{
  int current_count;

  current_count = get_connections_for_uid (connections, uid);

  _dbus_verbose ("Adjusting connection count for UID " DBUS_UID_FORMAT
                 ": was %d adjustment %d making %d\n",
                 uid, current_count, adjustment, current_count + adjustment);
  
  _dbus_assert (current_count >= 0);
  
  current_count += adjustment;

  _dbus_assert (current_count >= 0);

  if (current_count == 0)
    {
      _dbus_hash_table_remove_ulong (connections->completed_by_user, uid);
      return TRUE;
    }
  else
    {
      dbus_bool_t retval;
      
      retval = _dbus_hash_table_insert_ulong (connections->completed_by_user,
                                              uid, _DBUS_INT_TO_POINTER (current_count));

      /* only positive adjustment can fail as otherwise
       * a hash entry should already exist
       */
      _dbus_assert (adjustment > 0 ||
                    (adjustment <= 0 && retval));

      return retval;
    }
}

166
void
167
bus_connection_disconnected (DBusConnection *connection)
168 169 170
{
  BusConnectionData *d;
  BusService *service;
171 172
  BusMatchmaker *matchmaker;
  
173
  d = BUS_CONNECTION_DATA (connection);
174
  _dbus_assert (d != NULL);
175

176 177
  _dbus_verbose ("%s disconnected, dropping all service ownership and releasing\n",
                 d->name ? d->name : "(inactive)");
178 179 180 181 182 183 184

  /* Delete our match rules */
  if (d->n_match_rules > 0)
    {
      matchmaker = bus_context_get_matchmaker (d->connections->context);
      bus_matchmaker_disconnected (matchmaker, connection);
    }
185
  
186 187 188 189 190
  /* Drop any service ownership. FIXME Unfortunately, this requires
   * memory allocation and there doesn't seem to be a good way to
   * handle it other than sleeping; we can't "fail" the operation of
   * disconnecting a client, and preallocating a broadcast "service is
   * now gone" message for every client-service pair seems kind of
191
   * involved. Probably we need to do that though.
192
   */
193 194 195 196 197 198 199 200 201 202 203 204 205
  while ((service = _dbus_list_get_last (&d->services_owned)))
    {
      BusTransaction *transaction;
      DBusError error;

    retry:
      
      dbus_error_init (&error);
        
      transaction = NULL;
      while (transaction == NULL)
        {
          transaction = bus_transaction_new (d->connections->context);
206
          _dbus_wait_for_memory ();
207 208 209 210 211
        }
        
      if (!bus_service_remove_owner (service, connection,
                                     transaction, &error))
        {
212 213
          _DBUS_ASSERT_ERROR_IS_SET (&error);
          
214 215 216 217
          if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
            {
              dbus_error_free (&error);
              bus_transaction_cancel_and_free (transaction);
218
              _dbus_wait_for_memory ();
219 220 221
              goto retry;
            }
          else
222 223 224 225 226
            {
              _dbus_verbose ("Failed to remove service owner: %s %s\n",
                             error.name, error.message);
              _dbus_assert_not_reached ("Removing service owner failed for non-memory-related reason");
            }
227 228 229 230
        }
        
      bus_transaction_execute_and_free (transaction);
    }
231

232
  bus_dispatch_remove_connection (connection);
233
  
234
  /* no more watching */
235
  if (!dbus_connection_set_watch_functions (connection,
236
                                            NULL, NULL, NULL,
237 238 239 240 241
                                            connection,
                                            NULL))
    _dbus_assert_not_reached ("setting watch functions to NULL failed");

  if (!dbus_connection_set_timeout_functions (connection,
242
                                              NULL, NULL, NULL,
243 244 245 246
                                              connection,
                                              NULL))
    _dbus_assert_not_reached ("setting timeout functions to NULL failed");
  
247 248
  dbus_connection_set_unix_user_function (connection,
                                          NULL, NULL, NULL);
249 250 251

  dbus_connection_set_dispatch_status_function (connection,
                                                NULL, NULL, NULL);
252
  
253
  bus_connection_remove_transactions (connection);
254

255 256 257 258 259 260 261 262 263
  if (d->link_in_connection_list != NULL)
    {
      if (d->name != NULL)
        {
          unsigned long uid;
          
          _dbus_list_remove_link (&d->connections->completed, d->link_in_connection_list);
          d->link_in_connection_list = NULL;
          d->connections->n_completed -= 1;
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
          if (dbus_connection_get_unix_user (connection, &uid))
            {
              if (!adjust_connections_for_uid (d->connections,
                                               uid, -1))
                _dbus_assert_not_reached ("adjusting downward should never fail");
            }
        }
      else
        {
          _dbus_list_remove_link (&d->connections->incomplete, d->link_in_connection_list);
          d->link_in_connection_list = NULL;
          d->connections->n_incomplete -= 1;
        }
      
      _dbus_assert (d->connections->n_incomplete >= 0);
      _dbus_assert (d->connections->n_completed >= 0);
    }
282 283

  bus_connection_drop_pending_replies (d->connections, connection);
284
  
285
  /* frees "d" as side effect */
286 287 288
  dbus_connection_set_data (connection,
                            connection_data_slot,
                            NULL, NULL);
289
  
290 291 292
  dbus_connection_unref (connection);
}

293
static dbus_bool_t
294 295 296 297
connection_watch_callback (DBusWatch     *watch,
                           unsigned int   condition,
                           void          *data)
{
298
 /* FIXME this can be done in dbus-mainloop.c
299 300 301
  * if the code in activation.c for the babysitter
  * watch handler is fixed.
  */
302
  
303 304 305
#if 0
  _dbus_verbose ("Calling handle_watch\n");
#endif
306
  return dbus_watch_handle (watch, condition);
307 308
}

309
static dbus_bool_t
310
add_connection_watch (DBusWatch      *watch,
311
                      void           *data)
312
{
313 314
  DBusConnection *connection = data;

315 316 317
  return _dbus_loop_add_watch (connection_get_loop (connection),
                               watch, connection_watch_callback, connection,
                               NULL);
318 319 320 321
}

static void
remove_connection_watch (DBusWatch      *watch,
322
                         void           *data)
323
{
324 325
  DBusConnection *connection = data;
  
326 327
  _dbus_loop_remove_watch (connection_get_loop (connection),
                           watch, connection_watch_callback, connection);
328 329
}

330 331 332 333
static void
connection_timeout_callback (DBusTimeout   *timeout,
                             void          *data)
{
334
  /* DBusConnection *connection = data; */
335

336
  /* can return FALSE on OOM but we just let it fire again later */
337 338 339 340 341
  dbus_timeout_handle (timeout);
}

static dbus_bool_t
add_connection_timeout (DBusTimeout    *timeout,
342
                        void           *data)
343
{
344 345
  DBusConnection *connection = data;
  
346 347
  return _dbus_loop_add_timeout (connection_get_loop (connection),
                                 timeout, connection_timeout_callback, connection, NULL);
348 349 350 351
}

static void
remove_connection_timeout (DBusTimeout    *timeout,
352
                           void           *data)
353
{
354 355
  DBusConnection *connection = data;
  
356 357
  _dbus_loop_remove_timeout (connection_get_loop (connection),
                             timeout, connection_timeout_callback, connection);
358 359
}

360 361 362 363 364 365 366 367 368 369 370 371 372 373
static void
dispatch_status_function (DBusConnection    *connection,
                          DBusDispatchStatus new_status,
                          void              *data)
{
  DBusLoop *loop = data;
  
  if (new_status != DBUS_DISPATCH_COMPLETE)
    {
      while (!_dbus_loop_queue_dispatch (loop, connection))
        _dbus_wait_for_memory ();
    }
}

374 375 376 377 378 379 380 381 382 383 384 385 386 387
static dbus_bool_t
allow_user_function (DBusConnection *connection,
                     unsigned long   uid,
                     void           *data)
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);
  
  return bus_context_allow_user (d->connections->context, uid);
}

388 389 390 391 392 393 394
static void
free_connection_data (void *data)
{
  BusConnectionData *d = data;

  /* services_owned should be NULL since we should be disconnected */
  _dbus_assert (d->services_owned == NULL);
395
  _dbus_assert (d->n_services_owned == 0);
396 397
  /* similarly */
  _dbus_assert (d->transaction_messages == NULL);
398

399 400
  if (d->oom_preallocated)
    dbus_connection_free_preallocated_send (d->connection, d->oom_preallocated);
401

402 403
  if (d->oom_message)
    dbus_message_unref (d->oom_message);
404 405

  if (d->policy)
406
    bus_client_policy_unref (d->policy);
407 408 409

  if (d->selinux_id)
    bus_selinux_id_unref (d->selinux_id);
410
  
411
  dbus_free (d->name);
412 413 414 415
  
  dbus_free (d);
}

416 417 418 419 420 421 422 423
static void
call_timeout_callback (DBusTimeout   *timeout,
                       void          *data)
{
  /* can return FALSE on OOM but we just let it fire again later */
  dbus_timeout_handle (timeout);
}

424 425
BusConnections*
bus_connections_new (BusContext *context)
426
{
427
  BusConnections *connections;
428

429
  if (!dbus_connection_allocate_data_slot (&connection_data_slot))
430
    goto failed_0;
431

432 433
  connections = dbus_new0 (BusConnections, 1);
  if (connections == NULL)
434
    goto failed_1;
435 436 437 438

  connections->completed_by_user = _dbus_hash_table_new (DBUS_HASH_ULONG,
                                                         NULL, NULL);
  if (connections->completed_by_user == NULL)
439 440 441 442 443 444 445 446 447 448
    goto failed_2;

  connections->expire_timeout = _dbus_timeout_new (100, /* irrelevant */
                                                   expire_incomplete_timeout,
                                                   connections, NULL);
  if (connections->expire_timeout == NULL)
    goto failed_3;

  _dbus_timeout_set_enabled (connections->expire_timeout, FALSE);

449 450 451 452 453 454 455
  connections->pending_replies = bus_expire_list_new (bus_context_get_loop (context),
                                                      bus_context_get_reply_timeout (context),
                                                      bus_pending_reply_expired,
                                                      connections);
  if (connections->pending_replies == NULL)
    goto failed_4;
  
456 457 458
  if (!_dbus_loop_add_timeout (bus_context_get_loop (context),
                               connections->expire_timeout,
                               call_timeout_callback, NULL, NULL))
459
    goto failed_5;
460 461 462 463 464
  
  connections->refcount = 1;
  connections->context = context;
  
  return connections;
465

466 467
 failed_5:
  bus_expire_list_free (connections->pending_replies);
468 469 470 471 472 473 474
 failed_4:
  _dbus_timeout_unref (connections->expire_timeout);
 failed_3:
  _dbus_hash_table_unref (connections->completed_by_user);
 failed_2:
  dbus_free (connections);
 failed_1:
475
  dbus_connection_free_data_slot (&connection_data_slot);
476 477
 failed_0:
  return NULL;
478 479
}

480
BusConnections *
481 482 483 484
bus_connections_ref (BusConnections *connections)
{
  _dbus_assert (connections->refcount > 0);
  connections->refcount += 1;
485 486

  return connections;
487 488 489 490 491 492 493 494 495
}

void
bus_connections_unref (BusConnections *connections)
{
  _dbus_assert (connections->refcount > 0);
  connections->refcount -= 1;
  if (connections->refcount == 0)
    {
496 497
      /* drop all incomplete */
      while (connections->incomplete != NULL)
498 499 500
        {
          DBusConnection *connection;

501
          connection = connections->incomplete->data;
502 503 504 505 506 507

          dbus_connection_ref (connection);
          dbus_connection_disconnect (connection);
          bus_connection_disconnected (connection);
          dbus_connection_unref (connection);
        }
508 509

      _dbus_assert (connections->n_incomplete == 0);
510
      
511 512 513 514 515 516 517 518 519 520
      /* drop all real connections */
      while (connections->completed != NULL)
        {
          DBusConnection *connection;

          connection = connections->completed->data;

          dbus_connection_ref (connection);
          dbus_connection_disconnect (connection);
          bus_connection_disconnected (connection);
521
          dbus_connection_unref (connection);
522 523 524 525
        }

      _dbus_assert (connections->n_completed == 0);

526 527
      bus_expire_list_free (connections->pending_replies);
      
528 529 530 531 532 533
      _dbus_loop_remove_timeout (bus_context_get_loop (connections->context),
                                 connections->expire_timeout,
                                 call_timeout_callback, NULL);
      
      _dbus_timeout_unref (connections->expire_timeout);
      
534
      _dbus_hash_table_unref (connections->completed_by_user);
535
      
536 537
      dbus_free (connections);

538
      dbus_connection_free_data_slot (&connection_data_slot);
539
    }
540 541 542
}

dbus_bool_t
543 544
bus_connections_setup_connection (BusConnections *connections,
                                  DBusConnection *connection)
545 546
{
  BusConnectionData *d;
547
  dbus_bool_t retval;
548
  DBusError error;
549
  
550 551
  d = dbus_new0 (BusConnectionData, 1);
  
552 553
  if (d == NULL)
    return FALSE;
554

555
  d->connections = connections;
556
  d->connection = connection;
557
  
558 559 560
  _dbus_get_current_time (&d->connection_tv_sec,
                          &d->connection_tv_usec);
  
561
  _dbus_assert (connection_data_slot >= 0);
562 563 564 565 566 567 568 569
  
  if (!dbus_connection_set_data (connection,
                                 connection_data_slot,
                                 d, free_connection_data))
    {
      dbus_free (d);
      return FALSE;
    }
570 571

  retval = FALSE;
572 573 574 575 576 577 578 579 580 581 582 583 584 585

  dbus_error_init (&error);
  d->selinux_id = bus_selinux_init_connection_id (connection,
                                                  &error);
  if (dbus_error_is_set (&error))
    {
      /* This is a bit bogus because we pretend all errors
       * are OOM; this is done because we know that in bus.c
       * an OOM error disconnects the connection, which is
       * the same thing we want on any other error.
       */
      dbus_error_free (&error);
      goto out;
    }
586
  
587
  if (!dbus_connection_set_watch_functions (connection,
588 589
                                            add_connection_watch,
                                            remove_connection_watch,
590
                                            NULL,
591 592
                                            connection,
                                            NULL))
593
    goto out;
594 595
  
  if (!dbus_connection_set_timeout_functions (connection,
596 597
                                              add_connection_timeout,
                                              remove_connection_timeout,
598
                                              NULL,
599
                                              connection, NULL))
600
    goto out;
601
  
602 603 604
  dbus_connection_set_unix_user_function (connection,
                                          allow_user_function,
                                          NULL, NULL);
605 606 607 608 609

  dbus_connection_set_dispatch_status_function (connection,
                                                dispatch_status_function,
                                                bus_context_get_loop (connections->context),
                                                NULL);
610 611 612 613

  d->link_in_connection_list = _dbus_list_alloc_link (connection);
  if (d->link_in_connection_list == NULL)
    goto out;
614
  
615 616
  /* Setup the connection with the dispatcher */
  if (!bus_dispatch_add_connection (connection))
617
    goto out;
618 619 620 621 622 623 624 625 626

  if (dbus_connection_get_dispatch_status (connection) != DBUS_DISPATCH_COMPLETE)
    {
      if (!_dbus_loop_queue_dispatch (bus_context_get_loop (connections->context), connection))
        {
          bus_dispatch_remove_connection (connection);
          goto out;
        }
    }
627 628 629

  _dbus_list_append_link (&connections->incomplete, d->link_in_connection_list);
  connections->n_incomplete += 1;
630
  
631
  dbus_connection_ref (connection);
632 633

  /* Note that we might disconnect ourselves here, but it only takes
634 635 636 637 638 639 640 641
   * effect on return to the main loop. We call this to free up
   * expired connections if possible, and to queue the timeout for our
   * own expiration.
   */
  bus_connections_expire_incomplete (connections);
  
  /* And we might also disconnect ourselves here, but again it
   * only takes effect on return to main loop.
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
   */
  if (connections->n_incomplete >
      bus_context_get_max_incomplete_connections (connections->context))
    {
      _dbus_verbose ("Number of incomplete connections exceeds max, dropping oldest one\n");
      
      _dbus_assert (connections->incomplete != NULL);
      /* Disconnect the oldest unauthenticated connection.  FIXME
       * would it be more secure to drop a *random* connection?  This
       * algorithm seems to mean that if someone can create new
       * connections quickly enough, they can keep anyone else from
       * completing authentication. But random may or may not really
       * help with that, a more elaborate solution might be required.
       */
      dbus_connection_disconnect (connections->incomplete->data);
    }
  
659 660 661 662
  retval = TRUE;

 out:
  if (!retval)
663 664 665 666 667
    {
      if (d->selinux_id)
        bus_selinux_id_unref (d->selinux_id);
      d->selinux_id = NULL;
      
668 669 670 671 672 673 674 675 676 677 678
      if (!dbus_connection_set_watch_functions (connection,
                                                NULL, NULL, NULL,
                                                connection,
                                                NULL))
        _dbus_assert_not_reached ("setting watch functions to NULL failed");
      
      if (!dbus_connection_set_timeout_functions (connection,
                                                  NULL, NULL, NULL,
                                                  connection,
                                                  NULL))
        _dbus_assert_not_reached ("setting timeout functions to NULL failed");
679 680 681

      dbus_connection_set_unix_user_function (connection,
                                              NULL, NULL, NULL);
682

683 684
      dbus_connection_set_dispatch_status_function (connection,
                                                    NULL, NULL, NULL);
685 686 687 688 689 690

      if (d->link_in_connection_list != NULL)
        {
          _dbus_assert (d->link_in_connection_list->next == NULL);
          _dbus_assert (d->link_in_connection_list->prev == NULL);
          _dbus_list_free_link (d->link_in_connection_list);
691
          d->link_in_connection_list = NULL;
692
        }
693 694 695 696 697 698 699
      
      if (!dbus_connection_set_data (connection,
                                     connection_data_slot,
                                     NULL, NULL))
        _dbus_assert_not_reached ("failed to set connection data to null");

      /* "d" has now been freed */
700
    }
701
  
702
  return retval;
703 704
}

705 706 707 708 709 710 711
void
bus_connections_expire_incomplete (BusConnections *connections)
{    
  int next_interval;

  next_interval = -1;
  
712
  if (connections->incomplete != NULL)
713
    {
714 715 716
      long tv_sec, tv_usec;
      DBusList *link;
      int auth_timeout;
717
      
718 719 720 721 722 723 724 725 726 727
      _dbus_get_current_time (&tv_sec, &tv_usec);
      auth_timeout = bus_context_get_auth_timeout (connections->context);
  
      link = _dbus_list_get_first_link (&connections->incomplete);
      while (link != NULL)
        {
          DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);
          DBusConnection *connection;
          BusConnectionData *d;
          double elapsed;
728
      
729
          connection = link->data;
730
      
731
          d = BUS_CONNECTION_DATA (connection);
732
      
733 734
          _dbus_assert (d != NULL);
      
735 736 737
          elapsed = ELAPSED_MILLISECONDS_SINCE (d->connection_tv_sec,
                                                d->connection_tv_usec,
                                                tv_sec, tv_usec);
738

739 740 741 742 743 744 745 746 747 748 749
          if (elapsed >= (double) auth_timeout)
            {
              _dbus_verbose ("Timing out authentication for connection %p\n", connection);
              dbus_connection_disconnect (connection);
            }
          else
            {
              /* We can end the loop, since the connections are in oldest-first order */
              next_interval = ((double)auth_timeout) - elapsed;
              _dbus_verbose ("Connection %p authentication expires in %d milliseconds\n",
                             connection, next_interval);
750
          
751 752
              break;
            }
753
      
754 755
          link = next;
        }
756 757
    }

758 759
  bus_expire_timeout_set_interval (connections->expire_timeout,
                                   next_interval);
760 761 762 763 764 765 766
}

static dbus_bool_t
expire_incomplete_timeout (void *data)
{
  BusConnections *connections = data;

767 768
  _dbus_verbose ("Running %s\n", _DBUS_FUNCTION_NAME);
  
769 770 771 772 773 774
  /* note that this may remove the timeout */
  bus_connections_expire_incomplete (connections);

  return TRUE;
}

775
dbus_bool_t
776 777
bus_connection_get_groups  (DBusConnection   *connection,
                            unsigned long   **groups,
778 779
                            int              *n_groups,
                            DBusError        *error)
780 781
{
  BusConnectionData *d;
782 783 784
  unsigned long uid;
  DBusUserDatabase *user_database;
  
785 786 787 788
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

789 790
  user_database = bus_context_get_user_database (d->connections->context);
  
791 792 793
  *groups = NULL;
  *n_groups = 0;

794
  if (dbus_connection_get_unix_user (connection, &uid))
795
    {
796 797
      if (!_dbus_user_database_get_groups (user_database,
                                           uid, groups, n_groups,
798
                                           error))
799
        {
800
          _DBUS_ASSERT_ERROR_IS_SET (error);
801 802 803 804 805 806 807 808 809
          _dbus_verbose ("Did not get any groups for UID %lu\n",
                         uid);
          return FALSE;
        }
      else
        {
          _dbus_verbose ("Got %d groups for UID %lu\n",
                         *n_groups, uid);
          return TRUE;
810 811
        }
    }
812 813
  else
    return TRUE; /* successfully got 0 groups */
814 815 816 817 818 819 820
}

dbus_bool_t
bus_connection_is_in_group (DBusConnection *connection,
                            unsigned long   gid)
{
  int i;
821
  unsigned long *group_ids;
822 823
  int n_group_ids;

824 825
  if (!bus_connection_get_groups (connection, &group_ids, &n_group_ids,
                                  NULL))
826 827 828 829 830 831
    return FALSE;

  i = 0;
  while (i < n_group_ids)
    {
      if (group_ids[i] == gid)
832 833 834 835
        {
          dbus_free (group_ids);
          return TRUE;
        }
836 837 838
      ++i;
    }

839
  dbus_free (group_ids);
840 841 842
  return FALSE;
}

843
BusClientPolicy*
844
bus_connection_get_policy (DBusConnection *connection)
845 846 847 848 849 850
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);
851
  _dbus_assert (d->policy != NULL);
852
  
853 854
  return d->policy;
}
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
static dbus_bool_t
foreach_active (BusConnections               *connections,
                BusConnectionForeachFunction  function,
                void                         *data)
{
  DBusList *link;
  
  link = _dbus_list_get_first_link (&connections->completed);
  while (link != NULL)
    {
      DBusConnection *connection = link->data;
      DBusList *next = _dbus_list_get_next_link (&connections->completed, link);

      if (!(* function) (connection, data))
        return FALSE;
      
      link = next;
    }

  return TRUE;
}

static dbus_bool_t
foreach_inactive (BusConnections               *connections,
                  BusConnectionForeachFunction  function,
                  void                         *data)
{
  DBusList *link;
  
  link = _dbus_list_get_first_link (&connections->incomplete);
  while (link != NULL)
    {
      DBusConnection *connection = link->data;
      DBusList *next = _dbus_list_get_next_link (&connections->incomplete, link);

      if (!(* function) (connection, data))
        return FALSE;
      
      link = next;
    }

  return TRUE;
}

/**
 * Calls function on each active connection; if the function returns
 * #FALSE, stops iterating. Active connections are authenticated
 * and have sent a Hello message.
 *
 * @param connections the connections object
 * @param function the function
 * @param data data to pass to it as a second arg
 */
void
bus_connections_foreach_active (BusConnections               *connections,
                                BusConnectionForeachFunction  function,
                                void                         *data)
{
  foreach_active (connections, function, data);
}

917 918 919 920 921 922 923 924 925 926 927
/**
 * Calls function on each connection; if the function returns
 * #FALSE, stops iterating.
 *
 * @param connections the connections object
 * @param function the function
 * @param data data to pass to it as a second arg
 */
void
bus_connections_foreach (BusConnections               *connections,
                         BusConnectionForeachFunction  function,
928
                         void                         *data)
929
{
930 931
  if (!foreach_active (connections, function, data))
    return;
932

933
  foreach_inactive (connections, function, data);
934 935 936 937 938 939 940 941
}

BusContext*
bus_connections_get_context (BusConnections *connections)
{
  return connections->context;
}

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
/*
 * This is used to avoid covering the same connection twice when
 * traversing connections. Note that it assumes we will
 * bus_connection_mark_stamp() each connection at least once per
 * INT_MAX increments of the global stamp, or wraparound would break
 * things.
 */
void
bus_connections_increment_stamp (BusConnections *connections)
{
  connections->stamp += 1;
}

/* Mark connection with current stamp, return TRUE if it
 * didn't already have that stamp
 */
dbus_bool_t
bus_connection_mark_stamp (DBusConnection *connection)
{
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  
  _dbus_assert (d != NULL);

  if (d->stamp == d->connections->stamp)
    return FALSE;
  else
    {
      d->stamp = d->connections->stamp;
      return TRUE;
    }
}

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
BusContext*
bus_connection_get_context (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return d->connections->context;
}

BusConnections*
bus_connection_get_connections (DBusConnection *connection)
{
  BusConnectionData *d;
    
  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return d->connections;
}

BusRegistry*
bus_connection_get_registry (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return bus_context_get_registry (d->connections->context);
}

BusActivation*
bus_connection_get_activation (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return bus_context_get_activation (d->connections->context);
}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
BusMatchmaker*
bus_connection_get_matchmaker (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return bus_context_get_matchmaker (d->connections->context);
}

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
BusSELinuxID*
bus_connection_get_selinux_id (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);

  _dbus_assert (d != NULL);

  return d->selinux_id;
}

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
/**
 * Checks whether the connection is registered with the message bus.
 *
 * @param connection the connection
 * @returns #TRUE if we're an active message bus participant
 */
dbus_bool_t
bus_connection_is_active (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  
  return d != NULL && d->name != NULL;
}

dbus_bool_t
bus_connection_preallocate_oom_error (DBusConnection *connection)
{
  DBusMessage *message;
  DBusPreallocatedSend *preallocated;
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);  

  _dbus_assert (d != NULL);

  if (d->oom_preallocated != NULL)
    return TRUE;
  
  preallocated = dbus_connection_preallocate_send (connection);
  if (preallocated == NULL)
    return FALSE;

1082 1083
  message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);

1084 1085 1086 1087 1088 1089
  if (message == NULL)
    {
      dbus_connection_free_preallocated_send (connection, preallocated);
      return FALSE;
    }

1090
  /* d->name may be NULL, but that is OK */
1091
  if (!dbus_message_set_error_name (message, DBUS_ERROR_NO_MEMORY) ||
1092 1093
      !dbus_message_set_destination (message, d->name) ||
      !dbus_message_set_sender (message,
1094
                                DBUS_SERVICE_ORG_FREEDESKTOP_DBUS))
1095 1096 1097 1098 1099
    {
      dbus_connection_free_preallocated_send (connection, preallocated);
      dbus_message_unref (message);
      return FALSE;
    }
1100
  
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  /* set reply serial to placeholder value just so space is already allocated
   * for it.
   */
  if (!dbus_message_set_reply_serial (message, 14))
    {
      dbus_connection_free_preallocated_send (connection, preallocated);
      dbus_message_unref (message);
      return FALSE;
    }

  d->oom_message = message;
  d->oom_preallocated = preallocated;
  
  return TRUE;
}

void
bus_connection_send_oom_error (DBusConnection *connection,
                               DBusMessage    *in_reply_to)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);  

  _dbus_assert (d != NULL);  
  _dbus_assert (d->oom_message != NULL);

  /* should always succeed since we set it to a placeholder earlier */
  if (!dbus_message_set_reply_serial (d->oom_message,
                                      dbus_message_get_serial (in_reply_to)))
    _dbus_assert_not_reached ("Failed to set reply serial for preallocated oom message");

1133 1134
  _dbus_assert (dbus_message_get_sender (d->oom_message) != NULL);
  
1135 1136 1137 1138 1139 1140 1141 1142
  dbus_connection_send_preallocated (connection, d->oom_preallocated,
                                     d->oom_message, NULL);

  dbus_message_unref (d->oom_message);
  d->oom_message = NULL;
  d->oom_preallocated = NULL;
}

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
void
bus_connection_add_match_rule_link (DBusConnection *connection,
                                    DBusList       *link)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_append_link (&d->match_rules, link);

  d->n_match_rules += 1;
}

dbus_bool_t
bus_connection_add_match_rule (DBusConnection *connection,
                               BusMatchRule   *rule)
{
    DBusList *link;

  link = _dbus_list_alloc_link (rule);

  if (link == NULL)
    return FALSE;

  bus_connection_add_match_rule_link (connection, link);

  return TRUE;
}

void
bus_connection_remove_match_rule (DBusConnection *connection,
                                  BusMatchRule   *rule)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_remove_last (&d->match_rules, rule);

  d->n_match_rules -= 1;
  _dbus_assert (d->n_match_rules >= 0);
}

int
bus_connection_get_n_match_rules (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  return d->n_match_rules;
}

1199 1200 1201
void
bus_connection_add_owned_service_link (DBusConnection *connection,
                                       DBusList       *link)
1202 1203 1204 1205 1206 1207
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

1208
  _dbus_list_append_link (&d->services_owned, link);
1209 1210

  d->n_services_owned += 1;
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
}

dbus_bool_t
bus_connection_add_owned_service (DBusConnection *connection,
                                  BusService     *service)
{
  DBusList *link;

  link = _dbus_list_alloc_link (service);

  if (link == NULL)
1222 1223
    return FALSE;

1224 1225
  bus_connection_add_owned_service_link (connection, link);

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  return TRUE;
}

void
bus_connection_remove_owned_service (DBusConnection *connection,
                                     BusService     *service)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);

  _dbus_list_remove_last (&d->services_owned, service);
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252

  d->n_services_owned -= 1;
  _dbus_assert (d->n_services_owned >= 0);
}

int
bus_connection_get_n_services_owned (DBusConnection *connection)
{
  BusConnectionData *d;

  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  return d->n_services_owned;
1253
}
1254 1255

dbus_bool_t
1256 1257 1258
bus_connection_complete (DBusConnection   *connection,
			 const DBusString *name,
                         DBusError        *error)
1259 1260
{
  BusConnectionData *d;
1261
  unsigned long uid;
1262 1263 1264 1265
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  _dbus_assert (d->name == NULL);
1266
  _dbus_assert (d->policy == NULL);
1267 1268

  _dbus_assert (!bus_connection_is_active (connection));
1269
  
1270
  if (!_dbus_string_copy_data (name, &d->name))
1271 1272 1273 1274
    {
      BUS_SET_OOM (error);
      return FALSE;
    }
1275

1276 1277
  _dbus_assert (d->name != NULL);
  
1278
  _dbus_verbose ("Name %s assigned to %p\n", d->name, connection);
1279

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  d->policy = bus_context_create_client_policy (d->connections->context,
                                                connection,
                                                error);

  /* we may have a NULL policy on OOM or error getting list of
   * groups for a user. In the latter case we don't handle it so
   * well currently, as it will just keep failing over and over.
   */

  if (d->policy == NULL)
    {
      _dbus_verbose ("Failed to create security policy for connection %p\n",
                     connection);
      _DBUS_ASSERT_ERROR_IS_SET (error);
      dbus_free (d->name);
      d->name = NULL;
      return FALSE;
    }
  
1299 1300 1301 1302 1303
  if (dbus_connection_get_unix_user (connection, &uid))
    {
      if (!adjust_connections_for_uid (d->connections,
                                       uid, 1))
        {
1304
          BUS_SET_OOM (error);
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
          dbus_free (d->name);
          d->name = NULL;
          return FALSE;
        }
    }
  
  /* Now the connection is active, move it between lists */
  _dbus_list_unlink (&d->connections->incomplete,
                     d->link_in_connection_list);
  d->connections->n_incomplete -= 1;
  _dbus_list_append_link (&d->connections->completed,
                          d->link_in_connection_list);
  d->connections->n_completed += 1;

  _dbus_assert (d->connections->n_incomplete >= 0);
  _dbus_assert (d->connections->n_completed > 0);
1321 1322 1323

  /* See if we can remove the timeout */
  bus_connections_expire_incomplete (d->connections);
1324 1325

  _dbus_assert (bus_connection_is_active (connection));
1326
  
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  return TRUE;
}

const char *
bus_connection_get_name (DBusConnection *connection)
{
  BusConnectionData *d;
  
  d = BUS_CONNECTION_DATA (connection);
  _dbus_assert (d != NULL);
  
  return d->name;
}
1340

1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
/**
 * Check whether completing the passed-in connection would
 * exceed limits, and if so set error and return #FALSE
 */
dbus_bool_t
bus_connections_check_limits (BusConnections  *connections,
                              DBusConnection  *requesting_completion,
                              DBusError       *error)
{
  BusConnectionData *d;
  unsigned long uid;
  
  d = BUS_CONNECTION_DATA (requesting_completion);
  _dbus_assert (d != NULL);

  _dbus_assert (d->name == NULL);

  if (connections->n_completed >=
      bus_context_get_max_completed_connections (connections->context))
    {
      dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
                      "The maximum number of active connections has been reached");
      return FALSE;
    }
  
  if (dbus_connection_get_unix_user (requesting_completion, &uid))
    {
      if (get_connections_for_uid (connections, uid) >=
          bus_context_get_max_connections_per_user (connections->context))
        {
          dbus_set_error (error, DBUS_ERROR_LIMITS_EXCEEDED,
                          "The maximum number of active connections for UID %lu has been reached",
                          uid);
          return FALSE;
        }
    }
  
  return TRUE;
}

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
static void
bus_pending_reply_free (BusPendingReply *pending)
{
  _dbus_verbose ("Freeing pending reply %p, replier %p receiver %p serial %u\n",
                 pending,
                 pending->will_send_reply,
                 pending->will_get_reply,
                 pending->reply_serial);

  dbus_free (pending);
}

1393 1394 1395 1396 1397 1398 1399 1400
static dbus_bool_t
bus_pending_reply_send_no_reply (BusConnections  *connections,
                                 BusTransaction  *transaction,
                                 BusPendingReply *pending)
{
  DBusMessage *message;
  DBusMessageIter iter;
  dbus_bool_t retval;
1401
  const char *errmsg;
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417

  retval = FALSE;
  
  message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
  if (message == NULL)
    return FALSE;
  
  dbus_message_set_no_reply (message, TRUE);
  
  if (!dbus_message_set_reply_serial (message,
                                      pending->reply_serial))
    goto out;

  if (!dbus_message_set_error_name (message,
                                    DBUS_ERROR_NO_REPLY))
    goto out;
1418 1419

  errmsg = "Message did not receive a reply (timeout by message bus)";
1420
  dbus_message_append_iter_init (message, &iter);
1421
  if (!dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &errmsg))
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    goto out;
    
  if (!bus_transaction_send_from_driver (transaction, pending->will_get_reply,
                                         message))
    goto out;

  retval = TRUE;

 out:
  dbus_message_unref (message);
  return retval;
}

1435
static dbus_bool_t
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
bus_pending_reply_expired (BusExpireList *list,
                           DBusList      *link,
                           void          *data)
{
  BusPendingReply *pending = link->data;
  BusConnections *connections = data;
  BusTransaction *transaction;
  
  /* No reply is forthcoming. So nuke it if we can. If not,
   * leave it in the list to try expiring again later when we
   * get more memory.
   */
1448 1449 1450 1451 1452 1453 1454

  _dbus_verbose ("Expiring pending reply %p, replier %p receiver %p serial %u\n",
                 pending,
                 pending->will_send_reply,
                 pending->will_get_reply,
                 pending->reply_serial);
  
1455 1456
  transaction = bus_transaction_new (connections->context);
  if (transaction == NULL)
1457
    return FALSE;
1458
  
1459 1460 1461
  if (!bus_pending_reply_send_no_reply (connections,
                                        transaction,
                                        pending))
1462 1463
    {
      bus_transaction_cancel_and_free (transaction);
1464
      return FALSE;
1465
    }
1466 1467 1468 1469
  
  _dbus_list_remove_link (&connections->pending_replies->items,
                          link);
  bus_pending_reply_free (pending);
1470
  bus_transaction_execute_and_free (transaction);
1471 1472

  return TRUE;
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
}

static void
bus_connection_drop_pending_replies (BusConnections  *connections,
                                     DBusConnection  *connection)
{
  /* The DBusConnection is almost 100% finalized here, so you can't
   * do anything with it except check for pointer equality
   */
  DBusList *link;
1483 1484 1485

  _dbus_verbose ("Dropping pending replies that involve connection %p\n",
                 connection);
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
  
  link = _dbus_list_get_first_link (&connections->pending_replies->items);
  while (link != NULL)
    {
      DBusList *next;
      BusPendingReply *pending;

      next = _dbus_list_get_next_link (&connections->pending_replies->items,
                                       link);
      pending = link->data;

      if (pending->will_get_reply == connection)
        {
          /* We don't need to track this pending reply anymore */

1501 1502 1503 1504 1505 1506
          _dbus_verbose ("Dropping pending reply %p, replier %p receiver %p serial %u\n",
                         pending,
                         pending->will_send_reply,
                         pending->will_get_reply,
                         pending->reply_serial);
          
1507 1508
          _dbus_list_remove_link (&connections->pending_replies->items,
                                  link);
1509
          bus_pending_reply_free (pending);
1510 1511 1512 1513 1514 1515
        }
      else if (pending->will_send_reply == connection)
        {
          /* The reply isn't going to be sent, so set things
           * up so it will be expired right away
           */
1516 1517 1518 1519 1520 1521
          _dbus_verbose ("Will expire pending reply %p, replier %p receiver %p serial %u\n",
                         pending,
                         pending->will_send_reply,
                         pending->will_get_reply,
                         pending->reply_serial);
          
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
          pending->will_send_reply = NULL;
          pending->expire_item.added_tv_sec = 0;
          pending->expire_item.added_tv_usec = 0;

          bus_expire_timeout_set_interval (connections->pending_replies->timeout,
                                           0);
        }
      
      link = next;
    }
}


typedef struct
{
  BusPendingReply *pending;
  BusConnections  *connections;
} CancelPendingReplyData;

static void
cancel_pending_reply (void *data)
{
  CancelPendingReplyData *d = data;

1546 1547
  _dbus_verbose ("%s: d = %p\n", _DBUS_FUNCTION_NAME, d);